Merge "[OWE] Rename isOweSupported to isEnhancedOpenSupported"
diff --git a/Android.bp b/Android.bp
index 6288940..4b22f9e 100644
--- a/Android.bp
+++ b/Android.bp
@@ -845,6 +845,7 @@
 // specified on the build command line.
 java_library {
     name: "framework-atb-backward-compatibility",
+    installable: true,
     srcs: [
         "core/java/android/content/pm/AndroidTestBaseUpdater.java",
     ],
@@ -1265,10 +1266,7 @@
         "test-base/src/**/*.java",
         ":opt-telephony-srcs",
         ":opt-net-voip-srcs",
-        ":openjdk_javadoc_files",
-        ":non_openjdk_javadoc_files",
-        ":android_icu4j_src_files_for_docs",
-        ":conscrypt_public_api_files",
+        ":core_public_api_files",
         ":updatable-media-srcs-without-aidls",
         "test-mock/src/**/*.java",
         "test-runner/src/**/*.java",
@@ -1327,10 +1325,7 @@
     srcs: [
         ":opt-telephony-srcs",
         ":opt-net-voip-srcs",
-        ":openjdk_javadoc_files",
-        ":non_openjdk_javadoc_files",
-        ":android_icu4j_src_files_for_docs",
-        ":conscrypt_public_api_files",
+        ":core_public_api_files",
         ":updatable-media-srcs-without-aidls",
     ],
     srcs_lib: "framework",
@@ -1514,7 +1509,7 @@
     ],
     proofread_file: "ds-docs-proofrerad.txt",
     args: framework_docs_only_args +
-        " -toroot / -samplegroup Admin " +
+        " -toroot / -yamlV2 -metalavaApiSince -samplegroup Admin " +
         " -samplegroup Background " +
         " -samplegroup Connectivity " +
         " -samplegroup Content " +
diff --git a/apct-tests/perftests/core/src/android/graphics/perftests/RenderNodePerfTest.java b/apct-tests/perftests/core/src/android/graphics/perftests/RenderNodePerfTest.java
index e7fe235..e805ab9 100644
--- a/apct-tests/perftests/core/src/android/graphics/perftests/RenderNodePerfTest.java
+++ b/apct-tests/perftests/core/src/android/graphics/perftests/RenderNodePerfTest.java
@@ -71,7 +71,7 @@
         final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
         RenderNode node = RenderNode.create("LinearLayout", null);
         while (state.keepRunning()) {
-            node.startRecording(100, 100);
+            node.beginRecording(100, 100);
             node.endRecording();
         }
     }
@@ -86,7 +86,7 @@
 
         while (state.keepRunning()) {
             for (int i = 0; i < nodes.length; i++) {
-                nodes[i].startRecording(100, 100);
+                nodes[i].beginRecording(100, 100);
             }
             for (int i = nodes.length - 1; i >= 0; i--) {
                 nodes[i].endRecording();
diff --git a/apct-tests/perftests/core/src/android/text/StaticLayoutPerfTest.java b/apct-tests/perftests/core/src/android/text/StaticLayoutPerfTest.java
index bd7522d..8a6c60f 100644
--- a/apct-tests/perftests/core/src/android/text/StaticLayoutPerfTest.java
+++ b/apct-tests/perftests/core/src/android/text/StaticLayoutPerfTest.java
@@ -265,7 +265,7 @@
             state.pauseTiming();
             final StaticLayout layout =
                     StaticLayout.Builder.obtain(text, 0, text.length(), PAINT, TEXT_WIDTH).build();
-            final RecordingCanvas c = node.startRecording(1200, 200);
+            final RecordingCanvas c = node.beginRecording(1200, 200);
             state.resumeTiming();
 
             layout.draw(c);
@@ -282,7 +282,7 @@
             final CharSequence text = mTextUtil.nextRandomParagraph(WORD_LENGTH, STYLE_TEXT);
             final StaticLayout layout =
                     StaticLayout.Builder.obtain(text, 0, text.length(), PAINT, TEXT_WIDTH).build();
-            final RecordingCanvas c = node.startRecording(1200, 200);
+            final RecordingCanvas c = node.beginRecording(1200, 200);
             state.resumeTiming();
 
             layout.draw(c);
@@ -299,7 +299,7 @@
             final CharSequence text = mTextUtil.nextRandomParagraph(WORD_LENGTH, NO_STYLE_TEXT);
             final StaticLayout layout =
                     StaticLayout.Builder.obtain(text, 0, text.length(), PAINT, TEXT_WIDTH).build();
-            final RecordingCanvas c = node.startRecording(1200, 200);
+            final RecordingCanvas c = node.beginRecording(1200, 200);
             state.resumeTiming();
 
             layout.draw(c);
@@ -316,7 +316,7 @@
             final CharSequence text = mTextUtil.nextRandomParagraph(WORD_LENGTH, STYLE_TEXT);
             final StaticLayout layout =
                     StaticLayout.Builder.obtain(text, 0, text.length(), PAINT, TEXT_WIDTH).build();
-            final RecordingCanvas c = node.startRecording(1200, 200);
+            final RecordingCanvas c = node.beginRecording(1200, 200);
             Canvas.freeTextLayoutCaches();
             state.resumeTiming();
 
@@ -334,7 +334,7 @@
             final CharSequence text = mTextUtil.nextRandomParagraph(WORD_LENGTH, NO_STYLE_TEXT);
             final StaticLayout layout =
                     StaticLayout.Builder.obtain(text, 0, text.length(), PAINT, TEXT_WIDTH).build();
-            final RecordingCanvas c = node.startRecording(1200, 200);
+            final RecordingCanvas c = node.beginRecording(1200, 200);
             Canvas.freeTextLayoutCaches();
             state.resumeTiming();
 
@@ -353,7 +353,7 @@
                     mTextUtil.nextRandomParagraph(WORD_LENGTH, STYLE_TEXT), PAINT);
             final StaticLayout layout =
                     StaticLayout.Builder.obtain(text, 0, text.length(), PAINT, TEXT_WIDTH).build();
-            final RecordingCanvas c = node.startRecording(1200, 200);
+            final RecordingCanvas c = node.beginRecording(1200, 200);
             state.resumeTiming();
 
             layout.draw(c);
@@ -371,7 +371,7 @@
                     mTextUtil.nextRandomParagraph(WORD_LENGTH, NO_STYLE_TEXT), PAINT);
             final StaticLayout layout =
                     StaticLayout.Builder.obtain(text, 0, text.length(), PAINT, TEXT_WIDTH).build();
-            final RecordingCanvas c = node.startRecording(1200, 200);
+            final RecordingCanvas c = node.beginRecording(1200, 200);
             state.resumeTiming();
 
             layout.draw(c);
@@ -389,7 +389,7 @@
                     mTextUtil.nextRandomParagraph(WORD_LENGTH, STYLE_TEXT), PAINT);
             final StaticLayout layout =
                     StaticLayout.Builder.obtain(text, 0, text.length(), PAINT, TEXT_WIDTH).build();
-            final RecordingCanvas c = node.startRecording(1200, 200);
+            final RecordingCanvas c = node.beginRecording(1200, 200);
             Canvas.freeTextLayoutCaches();
             state.resumeTiming();
 
@@ -408,7 +408,7 @@
                     mTextUtil.nextRandomParagraph(WORD_LENGTH, NO_STYLE_TEXT), PAINT);
             final StaticLayout layout =
                     StaticLayout.Builder.obtain(text, 0, text.length(), PAINT, TEXT_WIDTH).build();
-            final RecordingCanvas c = node.startRecording(1200, 200);
+            final RecordingCanvas c = node.beginRecording(1200, 200);
             Canvas.freeTextLayoutCaches();
             state.resumeTiming();
 
diff --git a/apct-tests/perftests/core/src/android/widget/TextViewPrecomputedTextPerfTest.java b/apct-tests/perftests/core/src/android/widget/TextViewPrecomputedTextPerfTest.java
index 0bc9ee4..55d54e4 100644
--- a/apct-tests/perftests/core/src/android/widget/TextViewPrecomputedTextPerfTest.java
+++ b/apct-tests/perftests/core/src/android/widget/TextViewPrecomputedTextPerfTest.java
@@ -344,7 +344,7 @@
             textView.setText(text);
             textView.measure(width, height);
             textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
-            final RecordingCanvas c = node.startRecording(
+            final RecordingCanvas c = node.beginRecording(
                 textView.getMeasuredWidth(), textView.getMeasuredHeight());
             textView.nullLayouts();
             Canvas.freeTextLayoutCaches();
@@ -371,7 +371,7 @@
             textView.setText(text);
             textView.measure(width, height);
             textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
-            final RecordingCanvas c = node.startRecording(
+            final RecordingCanvas c = node.beginRecording(
                 textView.getMeasuredWidth(), textView.getMeasuredHeight());
             textView.nullLayouts();
             Canvas.freeTextLayoutCaches();
@@ -400,7 +400,7 @@
             textView.setText(text);
             textView.measure(width, height);
             textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
-            final RecordingCanvas c = node.startRecording(
+            final RecordingCanvas c = node.beginRecording(
                 textView.getMeasuredWidth(), textView.getMeasuredHeight());
             textView.nullLayouts();
             Canvas.freeTextLayoutCaches();
@@ -430,7 +430,7 @@
             textView.setText(text);
             textView.measure(width, height);
             textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
-            final RecordingCanvas c = node.startRecording(
+            final RecordingCanvas c = node.beginRecording(
                 textView.getMeasuredWidth(), textView.getMeasuredHeight());
             textView.nullLayouts();
             Canvas.freeTextLayoutCaches();
diff --git a/api/current.txt b/api/current.txt
index e95671f..4732405 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -287,6 +287,7 @@
     field public static final int alertDialogTheme = 16843529; // 0x1010309
     field public static final int alignmentMode = 16843642; // 0x101037a
     field public static final int allContactsName = 16843468; // 0x10102cc
+    field public static final int allowAudioPlaybackCapture = 16844199; // 0x10105a7
     field public static final int allowBackup = 16843392; // 0x1010280
     field public static final int allowClearUserData = 16842757; // 0x1010005
     field public static final int allowEmbedded = 16843765; // 0x10103f5
@@ -2925,7 +2926,7 @@
     field public static final int CAPABILITY_CAN_REQUEST_FINGERPRINT_GESTURES = 64; // 0x40
     field public static final int CAPABILITY_CAN_REQUEST_TOUCH_EXPLORATION = 2; // 0x2
     field public static final int CAPABILITY_CAN_RETRIEVE_WINDOW_CONTENT = 1; // 0x1
-    field public static final android.os.Parcelable.Creator<android.accessibilityservice.AccessibilityServiceInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.accessibilityservice.AccessibilityServiceInfo> CREATOR;
     field public static final int DEFAULT = 1; // 0x1
     field public static final int FEEDBACK_ALL_MASK = -1; // 0xffffffff
     field public static final int FEEDBACK_AUDIBLE = 4; // 0x4
@@ -3019,7 +3020,7 @@
     ctor public Account(android.os.Parcel);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.accounts.Account> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.accounts.Account> CREATOR;
     field public final String name;
     field public final String type;
   }
@@ -3036,7 +3037,7 @@
     method public void onRequestContinued();
     method public void onResult(android.os.Bundle);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.accounts.AccountAuthenticatorResponse> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.accounts.AccountAuthenticatorResponse> CREATOR;
   }
 
   public class AccountManager {
@@ -3153,7 +3154,7 @@
     method public int describeContents();
     method public static android.accounts.AuthenticatorDescription newKey(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.accounts.AuthenticatorDescription> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.accounts.AuthenticatorDescription> CREATOR;
     field public final int accountPreferencesId;
     field public final boolean customTokens;
     field public final int iconId;
@@ -3980,7 +3981,7 @@
     method public int describeContents();
     method public void readFromParcel(android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.ActivityManager.MemoryInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.ActivityManager.MemoryInfo> CREATOR;
     field public long availMem;
     field public boolean lowMemory;
     field public long threshold;
@@ -3993,7 +3994,7 @@
     method public void readFromParcel(android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int CRASHED = 1; // 0x1
-    field public static final android.os.Parcelable.Creator<android.app.ActivityManager.ProcessErrorStateInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.ActivityManager.ProcessErrorStateInfo> CREATOR;
     field public static final int NOT_RESPONDING = 2; // 0x2
     field public static final int NO_ERROR = 0; // 0x0
     field public int condition;
@@ -4012,7 +4013,7 @@
     method public int describeContents();
     method public void readFromParcel(android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.ActivityManager.RecentTaskInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.ActivityManager.RecentTaskInfo> CREATOR;
     field @Deprecated public int affiliatedTaskId;
     field @Deprecated public CharSequence description;
     field @Deprecated public int id;
@@ -4025,7 +4026,7 @@
     method public int describeContents();
     method public void readFromParcel(android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.ActivityManager.RunningAppProcessInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.ActivityManager.RunningAppProcessInfo> CREATOR;
     field @Deprecated public static final int IMPORTANCE_BACKGROUND = 400; // 0x190
     field public static final int IMPORTANCE_CACHED = 400; // 0x190
     field public static final int IMPORTANCE_CANT_SAVE_STATE = 350; // 0x15e
@@ -4059,7 +4060,7 @@
     method public int describeContents();
     method public void readFromParcel(android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.ActivityManager.RunningServiceInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.ActivityManager.RunningServiceInfo> CREATOR;
     field public static final int FLAG_FOREGROUND = 2; // 0x2
     field public static final int FLAG_PERSISTENT_PROCESS = 8; // 0x8
     field public static final int FLAG_STARTED = 1; // 0x1
@@ -4085,7 +4086,7 @@
     method public int describeContents();
     method public void readFromParcel(android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.ActivityManager.RunningTaskInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.ActivityManager.RunningTaskInfo> CREATOR;
     field @Deprecated public CharSequence description;
     field @Deprecated public int id;
     field @Deprecated public int numRunning;
@@ -4106,7 +4107,7 @@
     method public int getPrimaryColor();
     method public void readFromParcel(android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.ActivityManager.TaskDescription> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.ActivityManager.TaskDescription> CREATOR;
   }
 
   public class ActivityOptions {
@@ -4167,7 +4168,7 @@
     method public android.app.PendingIntent getShowIntent();
     method public long getTriggerTime();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AlarmManager.AlarmClockInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AlarmManager.AlarmClockInfo> CREATOR;
   }
 
   public static interface AlarmManager.OnAlarmListener {
@@ -4250,10 +4251,9 @@
 
   public class AppComponentFactory {
     ctor public AppComponentFactory();
-    method public android.content.pm.ApplicationInfo getApplicationInfo();
     method @NonNull public android.app.Activity instantiateActivity(@NonNull ClassLoader, @NonNull String, @Nullable android.content.Intent) throws java.lang.ClassNotFoundException, java.lang.IllegalAccessException, java.lang.InstantiationException;
     method @NonNull public android.app.Application instantiateApplication(@NonNull ClassLoader, @NonNull String) throws java.lang.ClassNotFoundException, java.lang.IllegalAccessException, java.lang.InstantiationException;
-    method @NonNull public ClassLoader instantiateClassLoader(@NonNull ClassLoader);
+    method @NonNull public ClassLoader instantiateClassLoader(@NonNull ClassLoader, @NonNull android.content.pm.ApplicationInfo);
     method @NonNull public android.content.ContentProvider instantiateProvider(@NonNull ClassLoader, @NonNull String) throws java.lang.ClassNotFoundException, java.lang.IllegalAccessException, java.lang.InstantiationException;
     method @NonNull public android.content.BroadcastReceiver instantiateReceiver(@NonNull ClassLoader, @NonNull String, @Nullable android.content.Intent) throws java.lang.ClassNotFoundException, java.lang.IllegalAccessException, java.lang.InstantiationException;
     method @NonNull public android.app.Service instantiateService(@NonNull ClassLoader, @NonNull String, @Nullable android.content.Intent) throws java.lang.ClassNotFoundException, java.lang.IllegalAccessException, java.lang.InstantiationException;
@@ -4372,7 +4372,7 @@
     method public static android.content.ComponentName getErrorReportReceiver(android.content.Context, String, int);
     method public void readFromParcel(android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.ApplicationErrorReport> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.ApplicationErrorReport> CREATOR;
     field public static final int TYPE_ANR = 2; // 0x2
     field public static final int TYPE_BATTERY = 3; // 0x3
     field public static final int TYPE_CRASH = 1; // 0x1
@@ -4440,7 +4440,7 @@
     method public int describeContents();
     method public android.app.PendingIntent getUserAction();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AuthenticationRequiredException> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AuthenticationRequiredException> CREATOR;
   }
 
   public final class AutomaticZenRule implements android.os.Parcelable {
@@ -4463,7 +4463,7 @@
     method public void setName(String);
     method public void setZenPolicy(android.service.notification.ZenPolicy);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AutomaticZenRule> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AutomaticZenRule> CREATOR;
   }
 
   public class DatePickerDialog extends android.app.AlertDialog implements android.widget.DatePicker.OnDateChangedListener android.content.DialogInterface.OnClickListener {
@@ -5289,7 +5289,7 @@
     field public static final String CATEGORY_SYSTEM = "sys";
     field public static final String CATEGORY_TRANSPORT = "transport";
     field @ColorInt public static final int COLOR_DEFAULT = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.app.Notification> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.Notification> CREATOR;
     field public static final int DEFAULT_ALL = -1; // 0xffffffff
     field public static final int DEFAULT_LIGHTS = 4; // 0x4
     field public static final int DEFAULT_SOUND = 1; // 0x1
@@ -5398,7 +5398,7 @@
     method public int getSemanticAction();
     method public boolean isContextual();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.Notification.Action> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.Notification.Action> CREATOR;
     field public static final int SEMANTIC_ACTION_ARCHIVE = 5; // 0x5
     field public static final int SEMANTIC_ACTION_CALL = 10; // 0xa
     field public static final int SEMANTIC_ACTION_DELETE = 4; // 0x4
@@ -5480,7 +5480,7 @@
     method public boolean getSuppressInitialNotification();
     method @Deprecated public CharSequence getTitle();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.Notification.BubbleMetadata> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.Notification.BubbleMetadata> CREATOR;
   }
 
   public static class Notification.BubbleMetadata.Builder {
@@ -5499,74 +5499,74 @@
     ctor public Notification.Builder(android.content.Context, String);
     ctor @Deprecated public Notification.Builder(android.content.Context);
     method @Deprecated public android.app.Notification.Builder addAction(int, CharSequence, android.app.PendingIntent);
-    method public android.app.Notification.Builder addAction(android.app.Notification.Action);
-    method public android.app.Notification.Builder addExtras(android.os.Bundle);
+    method @NonNull public android.app.Notification.Builder addAction(android.app.Notification.Action);
+    method @NonNull public android.app.Notification.Builder addExtras(android.os.Bundle);
     method @Deprecated public android.app.Notification.Builder addPerson(String);
-    method public android.app.Notification.Builder addPerson(android.app.Person);
-    method public android.app.Notification build();
+    method @NonNull public android.app.Notification.Builder addPerson(android.app.Person);
+    method @NonNull public android.app.Notification build();
     method public android.widget.RemoteViews createBigContentView();
     method public android.widget.RemoteViews createContentView();
     method public android.widget.RemoteViews createHeadsUpContentView();
-    method public android.app.Notification.Builder extend(android.app.Notification.Extender);
+    method @NonNull public android.app.Notification.Builder extend(android.app.Notification.Extender);
     method public android.os.Bundle getExtras();
     method @Deprecated public android.app.Notification getNotification();
     method public android.app.Notification.Style getStyle();
-    method public static android.app.Notification.Builder recoverBuilder(android.content.Context, android.app.Notification);
-    method public android.app.Notification.Builder setActions(android.app.Notification.Action...);
-    method public android.app.Notification.Builder setAllowSystemGeneratedContextualActions(boolean);
-    method public android.app.Notification.Builder setAutoCancel(boolean);
-    method public android.app.Notification.Builder setBadgeIconType(int);
-    method public android.app.Notification.Builder setBubbleMetadata(android.app.Notification.BubbleMetadata);
-    method public android.app.Notification.Builder setCategory(String);
-    method public android.app.Notification.Builder setChannelId(String);
-    method public android.app.Notification.Builder setChronometerCountDown(boolean);
-    method public android.app.Notification.Builder setColor(@ColorInt int);
-    method public android.app.Notification.Builder setColorized(boolean);
+    method @NonNull public static android.app.Notification.Builder recoverBuilder(android.content.Context, android.app.Notification);
+    method @NonNull public android.app.Notification.Builder setActions(android.app.Notification.Action...);
+    method @NonNull public android.app.Notification.Builder setAllowSystemGeneratedContextualActions(boolean);
+    method @NonNull public android.app.Notification.Builder setAutoCancel(boolean);
+    method @NonNull public android.app.Notification.Builder setBadgeIconType(int);
+    method @NonNull public android.app.Notification.Builder setBubbleMetadata(android.app.Notification.BubbleMetadata);
+    method @NonNull public android.app.Notification.Builder setCategory(String);
+    method @NonNull public android.app.Notification.Builder setChannelId(String);
+    method @NonNull public android.app.Notification.Builder setChronometerCountDown(boolean);
+    method @NonNull public android.app.Notification.Builder setColor(@ColorInt int);
+    method @NonNull public android.app.Notification.Builder setColorized(boolean);
     method @Deprecated public android.app.Notification.Builder setContent(android.widget.RemoteViews);
     method @Deprecated public android.app.Notification.Builder setContentInfo(CharSequence);
-    method public android.app.Notification.Builder setContentIntent(android.app.PendingIntent);
-    method public android.app.Notification.Builder setContentText(CharSequence);
-    method public android.app.Notification.Builder setContentTitle(CharSequence);
-    method public android.app.Notification.Builder setCustomBigContentView(android.widget.RemoteViews);
-    method public android.app.Notification.Builder setCustomContentView(android.widget.RemoteViews);
-    method public android.app.Notification.Builder setCustomHeadsUpContentView(android.widget.RemoteViews);
+    method @NonNull public android.app.Notification.Builder setContentIntent(android.app.PendingIntent);
+    method @NonNull public android.app.Notification.Builder setContentText(CharSequence);
+    method @NonNull public android.app.Notification.Builder setContentTitle(CharSequence);
+    method @NonNull public android.app.Notification.Builder setCustomBigContentView(android.widget.RemoteViews);
+    method @NonNull public android.app.Notification.Builder setCustomContentView(android.widget.RemoteViews);
+    method @NonNull public android.app.Notification.Builder setCustomHeadsUpContentView(android.widget.RemoteViews);
     method @Deprecated public android.app.Notification.Builder setDefaults(int);
-    method public android.app.Notification.Builder setDeleteIntent(android.app.PendingIntent);
-    method public android.app.Notification.Builder setExtras(android.os.Bundle);
-    method public android.app.Notification.Builder setFullScreenIntent(android.app.PendingIntent, boolean);
-    method public android.app.Notification.Builder setGroup(String);
-    method public android.app.Notification.Builder setGroupAlertBehavior(int);
-    method public android.app.Notification.Builder setGroupSummary(boolean);
-    method public android.app.Notification.Builder setLargeIcon(android.graphics.Bitmap);
-    method public android.app.Notification.Builder setLargeIcon(android.graphics.drawable.Icon);
+    method @NonNull public android.app.Notification.Builder setDeleteIntent(android.app.PendingIntent);
+    method @NonNull public android.app.Notification.Builder setExtras(android.os.Bundle);
+    method @NonNull public android.app.Notification.Builder setFullScreenIntent(android.app.PendingIntent, boolean);
+    method @NonNull public android.app.Notification.Builder setGroup(String);
+    method @NonNull public android.app.Notification.Builder setGroupAlertBehavior(int);
+    method @NonNull public android.app.Notification.Builder setGroupSummary(boolean);
+    method @NonNull public android.app.Notification.Builder setLargeIcon(android.graphics.Bitmap);
+    method @NonNull public android.app.Notification.Builder setLargeIcon(android.graphics.drawable.Icon);
     method @Deprecated public android.app.Notification.Builder setLights(@ColorInt int, int, int);
-    method public android.app.Notification.Builder setLocalOnly(boolean);
-    method public android.app.Notification.Builder setNumber(int);
-    method public android.app.Notification.Builder setOngoing(boolean);
-    method public android.app.Notification.Builder setOnlyAlertOnce(boolean);
+    method @NonNull public android.app.Notification.Builder setLocalOnly(boolean);
+    method @NonNull public android.app.Notification.Builder setNumber(int);
+    method @NonNull public android.app.Notification.Builder setOngoing(boolean);
+    method @NonNull public android.app.Notification.Builder setOnlyAlertOnce(boolean);
     method @Deprecated public android.app.Notification.Builder setPriority(int);
-    method public android.app.Notification.Builder setProgress(int, int, boolean);
-    method public android.app.Notification.Builder setPublicVersion(android.app.Notification);
-    method public android.app.Notification.Builder setRemoteInputHistory(CharSequence[]);
-    method public android.app.Notification.Builder setSettingsText(CharSequence);
-    method public android.app.Notification.Builder setShortcutId(String);
-    method public android.app.Notification.Builder setShowWhen(boolean);
-    method public android.app.Notification.Builder setSmallIcon(@DrawableRes int);
-    method public android.app.Notification.Builder setSmallIcon(@DrawableRes int, int);
-    method public android.app.Notification.Builder setSmallIcon(android.graphics.drawable.Icon);
-    method public android.app.Notification.Builder setSortKey(String);
+    method @NonNull public android.app.Notification.Builder setProgress(int, int, boolean);
+    method @NonNull public android.app.Notification.Builder setPublicVersion(android.app.Notification);
+    method @NonNull public android.app.Notification.Builder setRemoteInputHistory(CharSequence[]);
+    method @NonNull public android.app.Notification.Builder setSettingsText(CharSequence);
+    method @NonNull public android.app.Notification.Builder setShortcutId(String);
+    method @NonNull public android.app.Notification.Builder setShowWhen(boolean);
+    method @NonNull public android.app.Notification.Builder setSmallIcon(@DrawableRes int);
+    method @NonNull public android.app.Notification.Builder setSmallIcon(@DrawableRes int, int);
+    method @NonNull public android.app.Notification.Builder setSmallIcon(android.graphics.drawable.Icon);
+    method @NonNull public android.app.Notification.Builder setSortKey(String);
     method @Deprecated public android.app.Notification.Builder setSound(android.net.Uri);
     method @Deprecated public android.app.Notification.Builder setSound(android.net.Uri, int);
     method @Deprecated public android.app.Notification.Builder setSound(android.net.Uri, android.media.AudioAttributes);
-    method public android.app.Notification.Builder setStyle(android.app.Notification.Style);
-    method public android.app.Notification.Builder setSubText(CharSequence);
-    method public android.app.Notification.Builder setTicker(CharSequence);
+    method @NonNull public android.app.Notification.Builder setStyle(android.app.Notification.Style);
+    method @NonNull public android.app.Notification.Builder setSubText(CharSequence);
+    method @NonNull public android.app.Notification.Builder setTicker(CharSequence);
     method @Deprecated public android.app.Notification.Builder setTicker(CharSequence, android.widget.RemoteViews);
-    method public android.app.Notification.Builder setTimeoutAfter(long);
-    method public android.app.Notification.Builder setUsesChronometer(boolean);
+    method @NonNull public android.app.Notification.Builder setTimeoutAfter(long);
+    method @NonNull public android.app.Notification.Builder setUsesChronometer(boolean);
     method @Deprecated public android.app.Notification.Builder setVibrate(long[]);
-    method public android.app.Notification.Builder setVisibility(int);
-    method public android.app.Notification.Builder setWhen(long);
+    method @NonNull public android.app.Notification.Builder setVisibility(int);
+    method @NonNull public android.app.Notification.Builder setWhen(long);
   }
 
   public static final class Notification.CarExtender implements android.app.Notification.Extender {
@@ -5762,7 +5762,7 @@
     method public boolean shouldShowLights();
     method public boolean shouldVibrate();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.NotificationChannel> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.NotificationChannel> CREATOR;
     field public static final String DEFAULT_CHANNEL_ID = "miscellaneous";
   }
 
@@ -5777,7 +5777,7 @@
     method public boolean isBlocked();
     method public void setDescription(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.NotificationChannelGroup> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.NotificationChannelGroup> CREATOR;
   }
 
   public class NotificationManager {
@@ -5855,7 +5855,7 @@
     method public static String prioritySendersToString(int);
     method public static String suppressedEffectsToString(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.NotificationManager.Policy> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.NotificationManager.Policy> CREATOR;
     field public static final int PRIORITY_CATEGORY_ALARMS = 32; // 0x20
     field public static final int PRIORITY_CATEGORY_CALLS = 8; // 0x8
     field public static final int PRIORITY_CATEGORY_EVENTS = 2; // 0x2
@@ -5907,7 +5907,7 @@
     method public void send(android.content.Context, int, @Nullable android.content.Intent, @Nullable android.app.PendingIntent.OnFinished, @Nullable android.os.Handler, @Nullable String, @Nullable android.os.Bundle) throws android.app.PendingIntent.CanceledException;
     method public static void writePendingIntentOrNullToParcel(@Nullable android.app.PendingIntent, @NonNull android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.PendingIntent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.PendingIntent> CREATOR;
     field public static final int FLAG_CANCEL_CURRENT = 268435456; // 0x10000000
     field public static final int FLAG_IMMUTABLE = 67108864; // 0x4000000
     field public static final int FLAG_NO_CREATE = 536870912; // 0x20000000
@@ -5935,7 +5935,7 @@
     method public boolean isImportant();
     method public android.app.Person.Builder toBuilder();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.Person> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.Person> CREATOR;
   }
 
   public static class Person.Builder {
@@ -5952,7 +5952,7 @@
   public final class PictureInPictureParams implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.PictureInPictureParams> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.PictureInPictureParams> CREATOR;
   }
 
   public static class PictureInPictureParams.Builder {
@@ -6005,7 +6005,7 @@
     method @NonNull public android.app.RemoteAction getUserAction();
     method @NonNull public CharSequence getUserMessage();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.RecoverableSecurityException> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.RecoverableSecurityException> CREATOR;
   }
 
   public final class RemoteAction implements android.os.Parcelable {
@@ -6022,7 +6022,7 @@
     method public void setShouldShowIcon(boolean);
     method public boolean shouldShowIcon();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.RemoteAction> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.RemoteAction> CREATOR;
   }
 
   public final class RemoteInput implements android.os.Parcelable {
@@ -6042,7 +6042,7 @@
     method public boolean isDataOnly();
     method public static void setResultsSource(android.content.Intent, int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.RemoteInput> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.RemoteInput> CREATOR;
     field public static final int EDIT_CHOICES_BEFORE_SENDING_AUTO = 0; // 0x0
     field public static final int EDIT_CHOICES_BEFORE_SENDING_DISABLED = 1; // 0x1
     field public static final int EDIT_CHOICES_BEFORE_SENDING_ENABLED = 2; // 0x2
@@ -6164,13 +6164,14 @@
     method public boolean shouldRewriteQueryFromData();
     method public boolean shouldRewriteQueryFromText();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.SearchableInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.SearchableInfo> CREATOR;
   }
 
   public abstract class Service extends android.content.ContextWrapper implements android.content.ComponentCallbacks2 {
     ctor public Service();
     method protected void dump(java.io.FileDescriptor, java.io.PrintWriter, String[]);
     method public final android.app.Application getApplication();
+    method public final int getForegroundServiceType();
     method @Nullable public abstract android.os.IBinder onBind(android.content.Intent);
     method public void onConfigurationChanged(android.content.res.Configuration);
     method public void onCreate();
@@ -6370,7 +6371,7 @@
     method public CharSequence getSynonymAt(int);
     method public void setExtras(android.os.Bundle);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.VoiceInteractor.PickOptionRequest.Option> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.VoiceInteractor.PickOptionRequest.Option> CREATOR;
   }
 
   public static class VoiceInteractor.Prompt implements android.os.Parcelable {
@@ -6381,7 +6382,7 @@
     method @NonNull public CharSequence getVisualPrompt();
     method @NonNull public CharSequence getVoicePromptAt(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.VoiceInteractor.Prompt> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.VoiceInteractor.Prompt> CREATOR;
   }
 
   public abstract static class VoiceInteractor.Request {
@@ -6404,7 +6405,7 @@
     method @Nullable public android.graphics.Color getSecondaryColor();
     method @Nullable public android.graphics.Color getTertiaryColor();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.WallpaperColors> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.WallpaperColors> CREATOR;
   }
 
   public final class WallpaperInfo implements android.os.Parcelable {
@@ -6427,7 +6428,7 @@
     method public android.graphics.drawable.Drawable loadThumbnail(android.content.pm.PackageManager);
     method public boolean supportsMultipleDisplays();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.WallpaperInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.WallpaperInfo> CREATOR;
   }
 
   public class WallpaperManager {
@@ -6498,7 +6499,7 @@
     method public java.net.InetAddress getInetAddress();
     method public int getPort();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.admin.ConnectEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.admin.ConnectEvent> CREATOR;
   }
 
   public class DelegatedAdminReceiver extends android.content.BroadcastReceiver {
@@ -6524,7 +6525,7 @@
     method public boolean supportsTransferOwnership();
     method public boolean usesPolicy(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.admin.DeviceAdminInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.admin.DeviceAdminInfo> CREATOR;
     field public static final int USES_ENCRYPTED_STORAGE = 7; // 0x7
     field public static final int USES_POLICY_DISABLE_CAMERA = 8; // 0x8
     field public static final int USES_POLICY_DISABLE_KEYGUARD_FEATURES = 9; // 0x9
@@ -6974,7 +6975,7 @@
     method public java.util.List<java.net.InetAddress> getInetAddresses();
     method public int getTotalResolvedAddressCount();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.admin.DnsEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.admin.DnsEvent> CREATOR;
   }
 
   public class FreezePeriod {
@@ -6988,7 +6989,7 @@
     method public long getId();
     method public String getPackageName();
     method public long getTimestamp();
-    field public static final android.os.Parcelable.Creator<android.app.admin.NetworkEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.admin.NetworkEvent> CREATOR;
   }
 
   public class SecurityLog {
@@ -7039,7 +7040,7 @@
     method public int getTag();
     method public long getTimeNanos();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.admin.SecurityLog.SecurityEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.admin.SecurityLog.SecurityEvent> CREATOR;
   }
 
   public final class SystemUpdateInfo implements android.os.Parcelable {
@@ -7047,7 +7048,7 @@
     method public long getReceivedTime();
     method public int getSecurityPatchState();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.admin.SystemUpdateInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.admin.SystemUpdateInfo> CREATOR;
     field public static final int SECURITY_PATCH_STATE_FALSE = 1; // 0x1
     field public static final int SECURITY_PATCH_STATE_TRUE = 2; // 0x2
     field public static final int SECURITY_PATCH_STATE_UNKNOWN = 0; // 0x0
@@ -7064,7 +7065,7 @@
     method public int getPolicyType();
     method public android.app.admin.SystemUpdatePolicy setFreezePeriods(java.util.List<android.app.admin.FreezePeriod>);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.admin.SystemUpdatePolicy> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.admin.SystemUpdatePolicy> CREATOR;
     field public static final int TYPE_INSTALL_AUTOMATIC = 1; // 0x1
     field public static final int TYPE_INSTALL_WINDOWED = 2; // 0x2
     field public static final int TYPE_POSTPONE = 3; // 0x3
@@ -7074,7 +7075,7 @@
     method public int describeContents();
     method public int getErrorCode();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.admin.SystemUpdatePolicy.ValidationFailedException> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.admin.SystemUpdatePolicy.ValidationFailedException> CREATOR;
     field public static final int ERROR_COMBINED_FREEZE_PERIOD_TOO_CLOSE = 6; // 0x6
     field public static final int ERROR_COMBINED_FREEZE_PERIOD_TOO_LONG = 5; // 0x5
     field public static final int ERROR_DUPLICATE_OR_OVERLAP = 2; // 0x2
@@ -7102,7 +7103,7 @@
     method public void setStructuredData(String);
     method public void setWebUri(android.net.Uri);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.assist.AssistContent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.assist.AssistContent> CREATOR;
   }
 
   public class AssistStructure implements android.os.Parcelable {
@@ -7115,7 +7116,7 @@
     method public int getWindowNodeCount();
     method public boolean isHomeActivity();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.assist.AssistStructure> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.assist.AssistStructure> CREATOR;
   }
 
   public static class AssistStructure.ViewNode {
@@ -7321,7 +7322,7 @@
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int BACKOFF_POLICY_EXPONENTIAL = 1; // 0x1
     field public static final int BACKOFF_POLICY_LINEAR = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.app.job.JobInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.job.JobInfo> CREATOR;
     field public static final long DEFAULT_INITIAL_BACKOFF_MILLIS = 30000L; // 0x7530L
     field public static final long MAX_BACKOFF_DELAY_MILLIS = 18000000L; // 0x112a880L
     field public static final int NETWORK_BYTES_UNKNOWN = -1; // 0xffffffff
@@ -7365,7 +7366,7 @@
     method public int getFlags();
     method public android.net.Uri getUri();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.job.JobInfo.TriggerContentUri> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.job.JobInfo.TriggerContentUri> CREATOR;
     field public static final int FLAG_NOTIFY_FOR_DESCENDANTS = 1; // 0x1
   }
 
@@ -7383,7 +7384,7 @@
     method @Nullable public android.net.Uri[] getTriggeredContentUris();
     method public boolean isOverrideDeadlineExpired();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.job.JobParameters> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.job.JobParameters> CREATOR;
   }
 
   public abstract class JobScheduler {
@@ -7424,7 +7425,7 @@
     method public long getEstimatedNetworkUploadBytes();
     method public android.content.Intent getIntent();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.job.JobWorkItem> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.job.JobWorkItem> CREATOR;
   }
 
 }
@@ -7435,7 +7436,10 @@
     method @NonNull public android.content.Intent createRequestRoleIntent(@NonNull String);
     method public boolean isRoleAvailable(@NonNull String);
     method public boolean isRoleHeld(@NonNull String);
+    field public static final String ROLE_ASSISTANT = "android.app.role.ASSISTANT";
     field public static final String ROLE_BROWSER = "android.app.role.BROWSER";
+    field public static final String ROLE_CALL_REDIRECTION = "android.app.role.CALL_REDIRECTION";
+    field public static final String ROLE_CALL_SCREENING = "android.app.role.CALL_SCREENING";
     field public static final String ROLE_DIALER = "android.app.role.DIALER";
     field public static final String ROLE_EMERGENCY = "android.app.role.EMERGENCY";
     field public static final String ROLE_GALLERY = "android.app.role.GALLERY";
@@ -7457,7 +7461,7 @@
     method public android.net.Uri getUri();
     method public boolean isCallerNeeded();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.slice.Slice> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.slice.Slice> CREATOR;
     field public static final String EXTRA_RANGE_VALUE = "android.app.slice.extra.RANGE_VALUE";
     field public static final String EXTRA_TOGGLE_STATE = "android.app.slice.extra.TOGGLE_STATE";
     field public static final String HINT_ACTIONS = "actions";
@@ -7521,7 +7525,7 @@
     method public CharSequence getText();
     method public boolean hasHint(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.slice.SliceItem> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.slice.SliceItem> CREATOR;
     field public static final String FORMAT_ACTION = "action";
     field public static final String FORMAT_BUNDLE = "bundle";
     field public static final String FORMAT_IMAGE = "image";
@@ -7581,7 +7585,7 @@
     method public int getRevision();
     method public String getType();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.slice.SliceSpec> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.slice.SliceSpec> CREATOR;
   }
 
 }
@@ -7598,7 +7602,7 @@
     method public long getLastTimeStamp();
     method public long getTotalTimeActive();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.usage.ConfigurationStats> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.usage.ConfigurationStats> CREATOR;
   }
 
   public final class EventStats implements android.os.Parcelable {
@@ -7612,7 +7616,7 @@
     method public long getLastTimeStamp();
     method public long getTotalTime();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.usage.EventStats> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.usage.EventStats> CREATOR;
   }
 
   public final class ExternalStorageStats implements android.os.Parcelable {
@@ -7623,7 +7627,7 @@
     method public long getTotalBytes();
     method public long getVideoBytes();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.usage.ExternalStorageStats> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.usage.ExternalStorageStats> CREATOR;
   }
 
   public final class NetworkStats implements java.lang.AutoCloseable {
@@ -7688,7 +7692,7 @@
     method public long getCacheBytes();
     method public long getDataBytes();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.usage.StorageStats> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.usage.StorageStats> CREATOR;
   }
 
   public class StorageStatsManager {
@@ -7705,7 +7709,7 @@
     method public boolean getNextEvent(android.app.usage.UsageEvents.Event);
     method public boolean hasNextEvent();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.usage.UsageEvents> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.usage.UsageEvents> CREATOR;
   }
 
   public static final class UsageEvents.Event {
@@ -7750,7 +7754,7 @@
     method public long getTotalTimeInForeground();
     method public long getTotalTimeVisible();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.usage.UsageStats> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.usage.UsageStats> CREATOR;
   }
 
   public final class UsageStatsManager {
@@ -7883,7 +7887,7 @@
     method public final String loadLabel(android.content.pm.PackageManager);
     method public final android.graphics.drawable.Drawable loadPreviewImage(@NonNull android.content.Context, int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.appwidget.AppWidgetProviderInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.appwidget.AppWidgetProviderInfo> CREATOR;
     field public static final int RESIZE_BOTH = 3; // 0x3
     field public static final int RESIZE_HORIZONTAL = 1; // 0x1
     field public static final int RESIZE_NONE = 0; // 0x0
@@ -8234,7 +8238,7 @@
     method public int getMajorDeviceClass();
     method public boolean hasService(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothClass> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothClass> CREATOR;
   }
 
   public static class BluetoothClass.Device {
@@ -8352,7 +8356,7 @@
     field public static final int BOND_BONDED = 12; // 0xc
     field public static final int BOND_BONDING = 11; // 0xb
     field public static final int BOND_NONE = 10; // 0xa
-    field public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothDevice> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothDevice> CREATOR;
     field public static final int DEVICE_TYPE_CLASSIC = 1; // 0x1
     field public static final int DEVICE_TYPE_DUAL = 3; // 0x3
     field public static final int DEVICE_TYPE_LE = 2; // 0x2
@@ -8461,7 +8465,7 @@
     method public boolean setValue(String);
     method public void setWriteType(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothGattCharacteristic> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothGattCharacteristic> CREATOR;
     field public static final int FORMAT_FLOAT = 52; // 0x34
     field public static final int FORMAT_SFLOAT = 50; // 0x32
     field public static final int FORMAT_SINT16 = 34; // 0x22
@@ -8501,7 +8505,7 @@
     method public byte[] getValue();
     method public boolean setValue(byte[]);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothGattDescriptor> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothGattDescriptor> CREATOR;
     field public static final byte[] DISABLE_NOTIFICATION_VALUE;
     field public static final byte[] ENABLE_INDICATION_VALUE;
     field public static final byte[] ENABLE_NOTIFICATION_VALUE;
@@ -8560,7 +8564,7 @@
     method public int getType();
     method public java.util.UUID getUuid();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothGattService> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothGattService> CREATOR;
     field public static final int SERVICE_TYPE_PRIMARY = 0; // 0x0
     field public static final int SERVICE_TYPE_SECONDARY = 1; // 0x1
     field protected java.util.List<android.bluetooth.BluetoothGattCharacteristic> mCharacteristics;
@@ -8624,7 +8628,7 @@
     method @Deprecated public String getName();
     method @Deprecated public int getRole();
     method @Deprecated public void writeToParcel(android.os.Parcel, int);
-    field @Deprecated public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothHealthAppConfiguration> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothHealthAppConfiguration> CREATOR;
   }
 
   @Deprecated public abstract class BluetoothHealthCallback {
@@ -8697,7 +8701,7 @@
     method public int getTokenBucketSize();
     method public int getTokenRate();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothHidDeviceAppQosSettings> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothHidDeviceAppQosSettings> CREATOR;
     field public static final int MAX = -1; // 0xffffffff
     field public static final int SERVICE_BEST_EFFORT = 1; // 0x1
     field public static final int SERVICE_GUARANTEED = 2; // 0x2
@@ -8713,7 +8717,7 @@
     method public String getProvider();
     method public byte getSubclass();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothHidDeviceAppSdpSettings> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.BluetoothHidDeviceAppSdpSettings> CREATOR;
   }
 
   public final class BluetoothManager {
@@ -8794,7 +8798,7 @@
     method public java.util.Map<android.os.ParcelUuid,byte[]> getServiceData();
     method public java.util.List<android.os.ParcelUuid> getServiceUuids();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.bluetooth.le.AdvertiseData> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.le.AdvertiseData> CREATOR;
   }
 
   public static final class AdvertiseData.Builder {
@@ -8821,7 +8825,7 @@
     field public static final int ADVERTISE_TX_POWER_LOW = 1; // 0x1
     field public static final int ADVERTISE_TX_POWER_MEDIUM = 2; // 0x2
     field public static final int ADVERTISE_TX_POWER_ULTRA_LOW = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.bluetooth.le.AdvertiseSettings> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.le.AdvertiseSettings> CREATOR;
   }
 
   public static final class AdvertiseSettings.Builder {
@@ -8874,7 +8878,7 @@
     method public boolean isLegacy();
     method public boolean isScannable();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.bluetooth.le.AdvertisingSetParameters> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.le.AdvertisingSetParameters> CREATOR;
     field public static final int INTERVAL_HIGH = 1600; // 0x640
     field public static final int INTERVAL_LOW = 160; // 0xa0
     field public static final int INTERVAL_MAX = 16777215; // 0xffffff
@@ -8967,7 +8971,7 @@
     method @Nullable public android.os.ParcelUuid getServiceUuidMask();
     method public boolean matches(android.bluetooth.le.ScanResult);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.bluetooth.le.ScanFilter> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.le.ScanFilter> CREATOR;
   }
 
   public static final class ScanFilter.Builder {
@@ -9015,7 +9019,7 @@
     method public boolean isConnectable();
     method public boolean isLegacy();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.bluetooth.le.ScanResult> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.le.ScanResult> CREATOR;
     field public static final int DATA_COMPLETE = 0; // 0x0
     field public static final int DATA_TRUNCATED = 2; // 0x2
     field public static final int PERIODIC_INTERVAL_NOT_PRESENT = 0; // 0x0
@@ -9036,7 +9040,7 @@
     field public static final int CALLBACK_TYPE_ALL_MATCHES = 1; // 0x1
     field public static final int CALLBACK_TYPE_FIRST_MATCH = 2; // 0x2
     field public static final int CALLBACK_TYPE_MATCH_LOST = 4; // 0x4
-    field public static final android.os.Parcelable.Creator<android.bluetooth.le.ScanSettings> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.le.ScanSettings> CREATOR;
     field public static final int MATCH_MODE_AGGRESSIVE = 1; // 0x1
     field public static final int MATCH_MODE_STICKY = 2; // 0x2
     field public static final int MATCH_NUM_FEW_ADVERTISEMENT = 2; // 0x2
@@ -9068,7 +9072,7 @@
   public final class AssociationRequest implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.companion.AssociationRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.companion.AssociationRequest> CREATOR;
   }
 
   public static final class AssociationRequest.Builder {
@@ -9081,7 +9085,7 @@
   public final class BluetoothDeviceFilter implements android.companion.DeviceFilter<android.bluetooth.BluetoothDevice> {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.companion.BluetoothDeviceFilter> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.companion.BluetoothDeviceFilter> CREATOR;
   }
 
   public static final class BluetoothDeviceFilter.Builder {
@@ -9096,7 +9100,7 @@
     method public int describeContents();
     method public static int getRenamePrefixLengthLimit();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.companion.BluetoothLeDeviceFilter> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.companion.BluetoothLeDeviceFilter> CREATOR;
   }
 
   public static final class BluetoothLeDeviceFilter.Builder {
@@ -9130,7 +9134,7 @@
   public final class WifiDeviceFilter implements android.companion.DeviceFilter<android.net.wifi.ScanResult> {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.companion.WifiDeviceFilter> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.companion.WifiDeviceFilter> CREATOR;
   }
 
   public static final class WifiDeviceFilter.Builder {
@@ -9254,7 +9258,7 @@
     method public static android.content.ClipData newRawUri(CharSequence, android.net.Uri);
     method public static android.content.ClipData newUri(android.content.ContentResolver, CharSequence, android.net.Uri);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.ClipData> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.ClipData> CREATOR;
   }
 
   public static class ClipData.Item {
@@ -9287,7 +9291,7 @@
     method public boolean hasMimeType(String);
     method public void setExtras(android.os.PersistableBundle);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.ClipDescription> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.ClipDescription> CREATOR;
     field public static final String MIMETYPE_TEXT_HTML = "text/html";
     field public static final String MIMETYPE_TEXT_INTENT = "text/vnd.android.intent";
     field public static final String MIMETYPE_TEXT_PLAIN = "text/plain";
@@ -9347,7 +9351,7 @@
     method @Nullable public static android.content.ComponentName unflattenFromString(@NonNull String);
     method public void writeToParcel(android.os.Parcel, int);
     method public static void writeToParcel(android.content.ComponentName, android.os.Parcel);
-    field public static final android.os.Parcelable.Creator<android.content.ComponentName> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.ComponentName> CREATOR;
   }
 
   public abstract class ContentProvider implements android.content.ComponentCallbacks2 {
@@ -9450,7 +9454,7 @@
     method public String[] resolveSelectionArgsBackReferences(android.content.ContentProviderResult[], int);
     method public android.content.ContentValues resolveValueBackReferences(android.content.ContentProviderResult[], int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.ContentProviderOperation> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.ContentProviderOperation> CREATOR;
   }
 
   public static class ContentProviderOperation.Builder {
@@ -9471,7 +9475,7 @@
     ctor public ContentProviderResult(android.os.Parcel);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.ContentProviderResult> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.ContentProviderResult> CREATOR;
     field public final Integer count;
     field public final android.net.Uri uri;
   }
@@ -9640,7 +9644,7 @@
     method public int size();
     method public java.util.Set<java.util.Map.Entry<java.lang.String,java.lang.Object>> valueSet();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.ContentValues> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.ContentValues> CREATOR;
     field public static final String TAG = "ContentValues";
   }
 
@@ -10334,7 +10338,7 @@
     field public static final String CATEGORY_UNIT_TEST = "android.intent.category.UNIT_TEST";
     field public static final String CATEGORY_VOICE = "android.intent.category.VOICE";
     field public static final String CATEGORY_VR_HOME = "android.intent.category.VR_HOME";
-    field public static final android.os.Parcelable.Creator<android.content.Intent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.Intent> CREATOR;
     field public static final String EXTRA_ALARM_COUNT = "android.intent.extra.ALARM_COUNT";
     field public static final String EXTRA_ALLOW_MULTIPLE = "android.intent.extra.ALLOW_MULTIPLE";
     field @Deprecated public static final String EXTRA_ALLOW_REPLACE = "android.intent.extra.ALLOW_REPLACE";
@@ -10472,7 +10476,7 @@
     method public int describeContents();
     method public static android.content.Intent.ShortcutIconResource fromContext(android.content.Context, @AnyRes int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.Intent.ShortcutIconResource> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.Intent.ShortcutIconResource> CREATOR;
     field public String packageName;
     field public String resourceName;
   }
@@ -10531,7 +10535,7 @@
     method public final java.util.Iterator<java.lang.String> typesIterator();
     method public final void writeToParcel(android.os.Parcel, int);
     method public void writeToXml(org.xmlpull.v1.XmlSerializer) throws java.io.IOException;
-    field public static final android.os.Parcelable.Creator<android.content.IntentFilter> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.IntentFilter> CREATOR;
     field public static final int MATCH_ADJUSTMENT_MASK = 65535; // 0xffff
     field public static final int MATCH_ADJUSTMENT_NORMAL = 32768; // 0x8000
     field public static final int MATCH_CATEGORY_EMPTY = 1048576; // 0x100000
@@ -10573,7 +10577,7 @@
     method public void sendIntent(android.content.Context, int, android.content.Intent, android.content.IntentSender.OnFinished, android.os.Handler, String) throws android.content.IntentSender.SendIntentException;
     method public static void writeIntentSenderOrNullToParcel(android.content.IntentSender, android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.IntentSender> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.IntentSender> CREATOR;
   }
 
   public static interface IntentSender.OnFinished {
@@ -10636,7 +10640,7 @@
     method public int describeContents();
     method @NonNull public android.net.Uri getUri();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.LocusId> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.LocusId> CREATOR;
   }
 
   public class MutableContextWrapper extends android.content.ContextWrapper {
@@ -10658,7 +10662,7 @@
     ctor public PeriodicSync(android.accounts.Account, String, android.os.Bundle, long);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.PeriodicSync> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.PeriodicSync> CREATOR;
     field public final android.accounts.Account account;
     field public final String authority;
     field public final android.os.Bundle extras;
@@ -10712,7 +10716,7 @@
     method public void setTitle(String);
     method public void setType(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.RestrictionEntry> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.RestrictionEntry> CREATOR;
     field public static final int TYPE_BOOLEAN = 1; // 0x1
     field public static final int TYPE_BUNDLE = 7; // 0x7
     field public static final int TYPE_BUNDLE_ARRAY = 8; // 0x8
@@ -10825,7 +10829,7 @@
     method public static android.content.SyncAdapterType newKey(String, String);
     method public boolean supportsUploading();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.SyncAdapterType> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.SyncAdapterType> CREATOR;
     field public final String accountType;
     field public final String authority;
     field public final boolean isKey;
@@ -10847,7 +10851,7 @@
   public class SyncRequest implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.SyncRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.SyncRequest> CREATOR;
   }
 
   public static class SyncRequest.Builder {
@@ -10877,7 +10881,7 @@
     method public String toDebugString();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.content.SyncResult ALREADY_IN_PROGRESS;
-    field public static final android.os.Parcelable.Creator<android.content.SyncResult> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.SyncResult> CREATOR;
     field public boolean databaseError;
     field public long delayUntil;
     field public boolean fullSyncRequested;
@@ -10895,7 +10899,7 @@
     method public void clear();
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.SyncStats> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.SyncStats> CREATOR;
     field public long numAuthExceptions;
     field public long numConflictDetectedExceptions;
     field public long numDeletes;
@@ -10925,7 +10929,7 @@
     method public boolean isReadPermission();
     method public boolean isWritePermission();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.UriPermission> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.UriPermission> CREATOR;
     field public static final long INVALID_TIME = -9223372036854775808L; // 0x8000000000000000L
   }
 
@@ -10958,7 +10962,7 @@
     field public static final int CONFIG_SMALLEST_SCREEN_SIZE = 2048; // 0x800
     field public static final int CONFIG_TOUCHSCREEN = 8; // 0x8
     field public static final int CONFIG_UI_MODE = 512; // 0x200
-    field public static final android.os.Parcelable.Creator<android.content.pm.ActivityInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.ActivityInfo> CREATOR;
     field public static final int DOCUMENT_LAUNCH_ALWAYS = 2; // 0x2
     field public static final int DOCUMENT_LAUNCH_INTO_EXISTING = 1; // 0x1
     field public static final int DOCUMENT_LAUNCH_NEVER = 3; // 0x3
@@ -11050,7 +11054,7 @@
     field public static final int CATEGORY_SOCIAL = 4; // 0x4
     field public static final int CATEGORY_UNDEFINED = -1; // 0xffffffff
     field public static final int CATEGORY_VIDEO = 2; // 0x2
-    field public static final android.os.Parcelable.Creator<android.content.pm.ApplicationInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.ApplicationInfo> CREATOR;
     field public static final int FLAG_ALLOW_BACKUP = 32768; // 0x8000
     field public static final int FLAG_ALLOW_CLEAR_USER_DATA = 64; // 0x40
     field public static final int FLAG_ALLOW_TASK_REPARENTING = 32; // 0x20
@@ -11125,7 +11129,7 @@
     method @NonNull public java.util.List<java.lang.String> getPackageNames();
     method public int getSequenceNumber();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.ChangedPackages> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.ChangedPackages> CREATOR;
   }
 
   public class ComponentInfo extends android.content.pm.PackageItemInfo {
@@ -11151,7 +11155,7 @@
     method public int describeContents();
     method public String getGlEsVersion();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.ConfigurationInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.ConfigurationInfo> CREATOR;
     field public static final int GL_ES_VERSION_UNDEFINED = 0; // 0x0
     field public static final int INPUT_FEATURE_FIVE_WAY_NAV = 2; // 0x2
     field public static final int INPUT_FEATURE_HARD_KEYBOARD = 1; // 0x1
@@ -11174,7 +11178,7 @@
     ctor public FeatureGroupInfo(android.content.pm.FeatureGroupInfo);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.FeatureGroupInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.FeatureGroupInfo> CREATOR;
     field public android.content.pm.FeatureInfo[] features;
   }
 
@@ -11184,7 +11188,7 @@
     method public int describeContents();
     method public String getGlEsVersion();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.FeatureInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.FeatureInfo> CREATOR;
     field public static final int FLAG_REQUIRED = 1; // 0x1
     field public static final int GL_ES_VERSION_UNDEFINED = 0; // 0x0
     field public int flags;
@@ -11197,7 +11201,7 @@
     ctor public InstrumentationInfo();
     ctor public InstrumentationInfo(android.content.pm.InstrumentationInfo);
     method public int describeContents();
-    field public static final android.os.Parcelable.Creator<android.content.pm.InstrumentationInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.InstrumentationInfo> CREATOR;
     field public String dataDir;
     field public boolean functionalTest;
     field public boolean handleProfiling;
@@ -11221,7 +11225,7 @@
     method public String getSourcePackage();
     method public android.graphics.drawable.Drawable loadIcon(android.content.pm.PackageManager);
     method public CharSequence loadLabel(android.content.pm.PackageManager);
-    field public static final android.os.Parcelable.Creator<android.content.pm.LabeledIntent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.LabeledIntent> CREATOR;
   }
 
   public class LauncherActivityInfo {
@@ -11238,7 +11242,7 @@
   public class LauncherApps {
     method public java.util.List<android.content.pm.LauncherActivityInfo> getActivityList(String, android.os.UserHandle);
     method @NonNull public java.util.List<android.content.pm.PackageInstaller.SessionInfo> getAllPackageInstallerSessions();
-    method @Nullable public android.content.pm.LauncherApps.AppUsageLimit getAppUsageLimit(String, android.os.UserHandle);
+    method @Nullable public android.content.pm.LauncherApps.AppUsageLimit getAppUsageLimit(@NonNull String, @NonNull android.os.UserHandle);
     method public android.content.pm.ApplicationInfo getApplicationInfo(@NonNull String, int, @NonNull android.os.UserHandle) throws android.content.pm.PackageManager.NameNotFoundException;
     method public android.content.pm.LauncherApps.PinItemRequest getPinItemRequest(android.content.Intent);
     method public java.util.List<android.os.UserHandle> getProfiles();
@@ -11274,7 +11278,7 @@
     method public long getTotalUsageLimit();
     method public long getUsageRemaining();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.LauncherApps.AppUsageLimit> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.LauncherApps.AppUsageLimit> CREATOR;
   }
 
   public abstract static class LauncherApps.Callback {
@@ -11300,7 +11304,7 @@
     method @Nullable public android.content.pm.ShortcutInfo getShortcutInfo();
     method public boolean isValid();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.LauncherApps.PinItemRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.LauncherApps.PinItemRequest> CREATOR;
     field public static final int REQUEST_TYPE_APPWIDGET = 2; // 0x2
     field public static final int REQUEST_TYPE_SHORTCUT = 1; // 0x1
   }
@@ -11325,7 +11329,7 @@
     method @Nullable public String getPackageName();
     method public boolean isHidden();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.ModuleInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.ModuleInfo> CREATOR;
   }
 
   public class PackageInfo implements android.os.Parcelable {
@@ -11334,7 +11338,7 @@
     method public long getLongVersionCode();
     method public void setLongVersionCode(long);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.PackageInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.PackageInfo> CREATOR;
     field public static final int INSTALL_LOCATION_AUTO = 0; // 0x0
     field public static final int INSTALL_LOCATION_INTERNAL_ONLY = 1; // 0x1
     field public static final int INSTALL_LOCATION_PREFER_EXTERNAL = 2; // 0x2
@@ -11664,6 +11668,7 @@
     field public static final String FEATURE_FAKETOUCH_MULTITOUCH_DISTINCT = "android.hardware.faketouch.multitouch.distinct";
     field public static final String FEATURE_FAKETOUCH_MULTITOUCH_JAZZHAND = "android.hardware.faketouch.multitouch.jazzhand";
     field public static final String FEATURE_FINGERPRINT = "android.hardware.fingerprint";
+    field public static final String FEATURE_FOLDABLE = "android.hardware.type.foldable";
     field public static final String FEATURE_FREEFORM_WINDOW_MANAGEMENT = "android.software.freeform_window_management";
     field public static final String FEATURE_GAMEPAD = "android.hardware.gamepad";
     field public static final String FEATURE_HIFI_SENSORS = "android.hardware.sensor.hifi_sensors";
@@ -11797,7 +11802,7 @@
     ctor @Deprecated public PackageStats(android.content.pm.PackageStats);
     method @Deprecated public int describeContents();
     method @Deprecated public void writeToParcel(android.os.Parcel, int);
-    field @Deprecated public static final android.os.Parcelable.Creator<android.content.pm.PackageStats> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.content.pm.PackageStats> CREATOR;
     field @Deprecated public long cacheSize;
     field @Deprecated public long codeSize;
     field @Deprecated public long dataSize;
@@ -11814,7 +11819,7 @@
     ctor public PathPermission(android.os.Parcel);
     method public String getReadPermission();
     method public String getWritePermission();
-    field public static final android.os.Parcelable.Creator<android.content.pm.PathPermission> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.PathPermission> CREATOR;
   }
 
   public class PermissionGroupInfo extends android.content.pm.PackageItemInfo implements android.os.Parcelable {
@@ -11822,7 +11827,7 @@
     ctor public PermissionGroupInfo(android.content.pm.PermissionGroupInfo);
     method public int describeContents();
     method public CharSequence loadDescription(android.content.pm.PackageManager);
-    field public static final android.os.Parcelable.Creator<android.content.pm.PermissionGroupInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.PermissionGroupInfo> CREATOR;
     field public static final int FLAG_PERSONAL_INFO = 1; // 0x1
     field public int descriptionRes;
     field public int flags;
@@ -11837,7 +11842,7 @@
     method public int getProtection();
     method public int getProtectionFlags();
     method public CharSequence loadDescription(android.content.pm.PackageManager);
-    field public static final android.os.Parcelable.Creator<android.content.pm.PermissionInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.PermissionInfo> CREATOR;
     field public static final int FLAG_COSTS_MONEY = 1; // 0x1
     field public static final int FLAG_INSTALLED = 1073741824; // 0x40000000
     field public static final int PROTECTION_DANGEROUS = 1; // 0x1
@@ -11869,7 +11874,7 @@
     ctor public ProviderInfo(android.content.pm.ProviderInfo);
     method public int describeContents();
     method public void dump(android.util.Printer, String);
-    field public static final android.os.Parcelable.Creator<android.content.pm.ProviderInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.ProviderInfo> CREATOR;
     field public static final int FLAG_SINGLE_USER = 1073741824; // 0x40000000
     field public String authority;
     field public int flags;
@@ -11893,7 +11898,7 @@
     method public android.graphics.drawable.Drawable loadIcon(android.content.pm.PackageManager);
     method public CharSequence loadLabel(android.content.pm.PackageManager);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.ResolveInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.ResolveInfo> CREATOR;
     field public android.content.pm.ActivityInfo activityInfo;
     field public android.content.IntentFilter filter;
     field public int icon;
@@ -11921,7 +11926,7 @@
     method public int describeContents();
     method public void dump(android.util.Printer, String);
     method public int getForegroundServiceType();
-    field public static final android.os.Parcelable.Creator<android.content.pm.ServiceInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.ServiceInfo> CREATOR;
     field public static final int FLAG_EXTERNAL_SERVICE = 4; // 0x4
     field public static final int FLAG_ISOLATED_PROCESS = 2; // 0x2
     field public static final int FLAG_SINGLE_USER = 1073741824; // 0x40000000
@@ -11947,7 +11952,7 @@
     method public int getType();
     method @Deprecated @IntRange(from=0xffffffff) public int getVersion();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.SharedLibraryInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.SharedLibraryInfo> CREATOR;
     field public static final int TYPE_BUILTIN = 0; // 0x0
     field public static final int TYPE_DYNAMIC = 1; // 0x1
     field public static final int TYPE_STATIC = 2; // 0x2
@@ -11977,7 +11982,7 @@
     method public boolean isImmutable();
     method public boolean isPinned();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.ShortcutInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.ShortcutInfo> CREATOR;
     field public static final int DISABLED_REASON_APP_CHANGED = 2; // 0x2
     field public static final int DISABLED_REASON_BACKUP_NOT_SUPPORTED = 101; // 0x65
     field public static final int DISABLED_REASON_BY_APP = 1; // 0x1
@@ -12038,7 +12043,7 @@
     method public char[] toChars(char[], int[]);
     method public String toCharsString();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.Signature> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.Signature> CREATOR;
   }
 
   public final class SigningInfo implements android.os.Parcelable {
@@ -12050,7 +12055,7 @@
     method public boolean hasMultipleSigners();
     method public boolean hasPastSigningCertificates();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.SigningInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.SigningInfo> CREATOR;
   }
 
   public final class VersionedPackage implements android.os.Parcelable {
@@ -12061,7 +12066,7 @@
     method @NonNull public String getPackageName();
     method @Deprecated public int getVersionCode();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.VersionedPackage> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.VersionedPackage> CREATOR;
   }
 
 }
@@ -12082,7 +12087,7 @@
     method public android.os.ParcelFileDescriptor getParcelFileDescriptor();
     method public long getStartOffset();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.res.AssetFileDescriptor> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.res.AssetFileDescriptor> CREATOR;
     field public static final long UNKNOWN_LENGTH = -1L; // 0xffffffffffffffffL
   }
 
@@ -12128,7 +12133,7 @@
     method @NonNull public static android.content.res.ColorStateList valueOf(@ColorInt int);
     method @NonNull public android.content.res.ColorStateList withAlpha(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.res.ColorStateList> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.res.ColorStateList> CREATOR;
   }
 
   public final class Configuration implements java.lang.Comparable<android.content.res.Configuration> android.os.Parcelable {
@@ -12163,7 +12168,7 @@
     field public static final int COLOR_MODE_WIDE_COLOR_GAMUT_NO = 1; // 0x1
     field public static final int COLOR_MODE_WIDE_COLOR_GAMUT_UNDEFINED = 0; // 0x0
     field public static final int COLOR_MODE_WIDE_COLOR_GAMUT_YES = 2; // 0x2
-    field public static final android.os.Parcelable.Creator<android.content.res.Configuration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.res.Configuration> CREATOR;
     field public static final int DENSITY_DPI_UNDEFINED = 0; // 0x0
     field public static final int HARDKEYBOARDHIDDEN_NO = 1; // 0x1
     field public static final int HARDKEYBOARDHIDDEN_UNDEFINED = 0; // 0x0
@@ -12251,7 +12256,7 @@
   public class ObbInfo implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.res.ObbInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.res.ObbInfo> CREATOR;
     field public static final int OBB_OVERLAY = 1; // 0x1
     field public String filename;
     field public int flags;
@@ -12508,7 +12513,7 @@
     method public int getInt(int);
     method public long getLong(int);
     method public android.net.Uri getNotificationUri();
-    method public default java.util.List<android.net.Uri> getNotificationUris();
+    method @Nullable public default java.util.List<android.net.Uri> getNotificationUris();
     method public int getPosition();
     method public short getShort(int);
     method public String getString(int);
@@ -12594,7 +12599,7 @@
     method public boolean setNumColumns(int);
     method public void setStartPosition(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.database.CursorWindow> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.database.CursorWindow> CREATOR;
   }
 
   public class CursorWrapper implements android.database.Cursor {
@@ -13067,19 +13072,19 @@
     method public String buildUnionSubQuery(String, String[], java.util.Set<java.lang.String>, int, String, String, String, String);
     method @Deprecated public String buildUnionSubQuery(String, String[], java.util.Set<java.lang.String>, int, String, String, String[], String, String);
     method public int delete(@NonNull android.database.sqlite.SQLiteDatabase, @Nullable String, @Nullable String[]);
-    method public android.database.sqlite.SQLiteDatabase.CursorFactory getCursorFactory();
+    method @Nullable public android.database.sqlite.SQLiteDatabase.CursorFactory getCursorFactory();
     method public boolean getDistinct();
-    method public java.util.Map<java.lang.String,java.lang.String> getProjectionMap();
+    method @Nullable public java.util.Map<java.lang.String,java.lang.String> getProjectionMap();
     method public boolean getStrict();
-    method public String getTables();
+    method @Nullable public String getTables();
     method public android.database.Cursor query(android.database.sqlite.SQLiteDatabase, String[], String, String[], String, String, String);
     method public android.database.Cursor query(android.database.sqlite.SQLiteDatabase, String[], String, String[], String, String, String, String);
     method public android.database.Cursor query(android.database.sqlite.SQLiteDatabase, String[], String, String[], String, String, String, String, android.os.CancellationSignal);
-    method public void setCursorFactory(android.database.sqlite.SQLiteDatabase.CursorFactory);
+    method public void setCursorFactory(@Nullable android.database.sqlite.SQLiteDatabase.CursorFactory);
     method public void setDistinct(boolean);
-    method public void setProjectionMap(java.util.Map<java.lang.String,java.lang.String>);
+    method public void setProjectionMap(@Nullable java.util.Map<java.lang.String,java.lang.String>);
     method public void setStrict(boolean);
-    method public void setTables(String);
+    method public void setTables(@Nullable String);
     method public int update(@NonNull android.database.sqlite.SQLiteDatabase, @NonNull android.content.ContentValues, @Nullable String, @Nullable String[]);
   }
 
@@ -13355,7 +13360,7 @@
     method public android.graphics.Path toPath(int, int, int, int);
     method public android.graphics.Path toPath(android.graphics.Path, int, int, int, int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.gesture.Gesture> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.gesture.Gesture> CREATOR;
   }
 
   public final class GestureLibraries {
@@ -13549,7 +13554,7 @@
     method @CheckResult public android.graphics.Bitmap extractAlpha(android.graphics.Paint, int[]);
     method public int getAllocationByteCount();
     method public int getByteCount();
-    method public android.graphics.Color getColor(int, int);
+    method @NonNull public android.graphics.Color getColor(int, int);
     method @Nullable public android.graphics.ColorSpace getColorSpace();
     method public android.graphics.Bitmap.Config getConfig();
     method public int getDensity();
@@ -13587,7 +13592,7 @@
     method public void setWidth(int);
     method @Nullable public static android.graphics.Bitmap wrapHardwareBuffer(@NonNull android.hardware.HardwareBuffer, @Nullable android.graphics.ColorSpace);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.graphics.Bitmap> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.graphics.Bitmap> CREATOR;
     field public static final int DENSITY_NONE = 0; // 0x0
   }
 
@@ -14232,7 +14237,7 @@
     method @NonNull public static android.graphics.Insets of(@Nullable android.graphics.Rect);
     method @NonNull public static android.graphics.Insets subtract(@NonNull android.graphics.Insets, @NonNull android.graphics.Insets);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.graphics.Insets> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.graphics.Insets> CREATOR;
     field public static final android.graphics.Insets NONE;
     field public final int bottom;
     field public final int left;
@@ -14736,7 +14741,7 @@
     method public void readFromParcel(@NonNull android.os.Parcel);
     method public void set(int, int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.graphics.Point> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.graphics.Point> CREATOR;
     field public int x;
     field public int y;
   }
@@ -14755,7 +14760,7 @@
     method public final void set(float, float);
     method public final void set(@NonNull android.graphics.PointF);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.graphics.PointF> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.graphics.PointF> CREATOR;
     field public float x;
     field public float y;
   }
@@ -14844,7 +14849,7 @@
     method public void union(int, int);
     method public int width();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.graphics.Rect> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.graphics.Rect> CREATOR;
     field public int bottom;
     field public int left;
     field public int right;
@@ -14886,7 +14891,7 @@
     method public void union(float, float);
     method public final float width();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.graphics.RectF> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.graphics.RectF> CREATOR;
     field public float bottom;
     field public float left;
     field public float right;
@@ -14926,7 +14931,7 @@
     method public void translate(int, int, android.graphics.Region);
     method public final boolean union(@NonNull android.graphics.Rect);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.graphics.Region> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.graphics.Region> CREATOR;
   }
 
   public enum Region.Op {
@@ -14945,13 +14950,15 @@
 
   public final class RenderNode {
     ctor public RenderNode(@Nullable String);
-    method public int computeApproximateMemoryUsage();
+    method public android.graphics.RecordingCanvas beginRecording(int, int);
+    method public android.graphics.RecordingCanvas beginRecording();
+    method public long computeApproximateMemoryUsage();
     method public void discardDisplayList();
     method public void endRecording();
     method public float getAlpha();
-    method public int getAmbientShadowColor();
+    method @ColorInt public int getAmbientShadowColor();
     method public int getBottom();
-    method public float getCameraDistance();
+    method @FloatRange(from=0.0f, to=java.lang.Float.MAX_VALUE) public float getCameraDistance();
     method public boolean getClipToBounds();
     method public boolean getClipToOutline();
     method public float getElevation();
@@ -14962,12 +14969,12 @@
     method public float getPivotX();
     method public float getPivotY();
     method public int getRight();
-    method public float getRotation();
     method public float getRotationX();
     method public float getRotationY();
+    method public float getRotationZ();
     method public float getScaleX();
     method public float getScaleY();
-    method public int getSpotShadowColor();
+    method @ColorInt public int getSpotShadowColor();
     method public int getTop();
     method public float getTranslationX();
     method public float getTranslationY();
@@ -14985,36 +14992,31 @@
     method public boolean offsetTopAndBottom(int);
     method public boolean resetPivot();
     method public boolean setAlpha(float);
-    method public boolean setAmbientShadowColor(int);
-    method public boolean setBottom(int);
-    method public boolean setCameraDistance(float);
-    method public boolean setClipBounds(@Nullable android.graphics.Rect);
+    method public boolean setAmbientShadowColor(@ColorInt int);
+    method public boolean setCameraDistance(@FloatRange(from=0.0f, to=java.lang.Float.MAX_VALUE) float);
+    method public boolean setClipRect(@Nullable android.graphics.Rect);
     method public boolean setClipToBounds(boolean);
     method public boolean setClipToOutline(boolean);
     method public boolean setElevation(float);
     method public boolean setForceDarkAllowed(boolean);
     method public boolean setHasOverlappingRendering(boolean);
-    method public boolean setLeft(int);
-    method public boolean setLeftTopRightBottom(int, int, int, int);
     method public boolean setOutline(@Nullable android.graphics.Outline);
     method public boolean setPivotX(float);
     method public boolean setPivotY(float);
+    method public boolean setPosition(int, int, int, int);
+    method public boolean setPosition(android.graphics.Rect);
     method public boolean setProjectBackwards(boolean);
     method public boolean setProjectionReceiver(boolean);
-    method public boolean setRight(int);
-    method public boolean setRotation(float);
     method public boolean setRotationX(float);
     method public boolean setRotationY(float);
+    method public boolean setRotationZ(float);
     method public boolean setScaleX(float);
     method public boolean setScaleY(float);
-    method public boolean setSpotShadowColor(int);
-    method public boolean setTop(int);
+    method public boolean setSpotShadowColor(@ColorInt int);
     method public boolean setTranslationX(float);
     method public boolean setTranslationY(float);
     method public boolean setTranslationZ(float);
     method public boolean setUseCompositingLayer(boolean, @Nullable android.graphics.Paint);
-    method public android.graphics.RecordingCanvas startRecording(int, int);
-    method public android.graphics.RecordingCanvas startRecording();
   }
 
   public class Shader {
@@ -15515,7 +15517,7 @@
     method public android.graphics.drawable.Icon setTintList(android.content.res.ColorStateList);
     method public android.graphics.drawable.Icon setTintMode(android.graphics.PorterDuff.Mode);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.graphics.drawable.Icon> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.graphics.drawable.Icon> CREATOR;
     field public static final int TYPE_ADAPTIVE_BITMAP = 5; // 0x5
     field public static final int TYPE_BITMAP = 1; // 0x1
     field public static final int TYPE_DATA = 3; // 0x3
@@ -16232,7 +16234,7 @@
     method public static boolean isSupported(@IntRange(from=1) int, @IntRange(from=1) int, int, @IntRange(from=1) int, long);
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int BLOB = 33; // 0x21
-    field public static final android.os.Parcelable.Creator<android.hardware.HardwareBuffer> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.HardwareBuffer> CREATOR;
     field public static final int DS_24UI8 = 50; // 0x32
     field public static final int DS_FP32UI8 = 52; // 0x34
     field public static final int D_16 = 48; // 0x30
@@ -16556,13 +16558,13 @@
 
   public static class BiometricPrompt.Builder {
     ctor public BiometricPrompt.Builder(android.content.Context);
-    method public android.hardware.biometrics.BiometricPrompt build();
-    method public android.hardware.biometrics.BiometricPrompt.Builder setAllowDeviceCredential(boolean);
-    method public android.hardware.biometrics.BiometricPrompt.Builder setDescription(@NonNull CharSequence);
-    method public android.hardware.biometrics.BiometricPrompt.Builder setNegativeButton(@NonNull CharSequence, @NonNull java.util.concurrent.Executor, @NonNull android.content.DialogInterface.OnClickListener);
-    method public android.hardware.biometrics.BiometricPrompt.Builder setRequireConfirmation(boolean);
-    method public android.hardware.biometrics.BiometricPrompt.Builder setSubtitle(@NonNull CharSequence);
-    method public android.hardware.biometrics.BiometricPrompt.Builder setTitle(@NonNull CharSequence);
+    method @NonNull public android.hardware.biometrics.BiometricPrompt build();
+    method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setAllowDeviceCredential(boolean);
+    method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setDescription(@NonNull CharSequence);
+    method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setNegativeButton(@NonNull CharSequence, @NonNull java.util.concurrent.Executor, @NonNull android.content.DialogInterface.OnClickListener);
+    method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setRequireConfirmation(boolean);
+    method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setSubtitle(@NonNull CharSequence);
+    method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setTitle(@NonNull CharSequence);
   }
 
   public static final class BiometricPrompt.CryptoObject {
@@ -16644,93 +16646,93 @@
     method public java.util.List<android.hardware.camera2.CameraCharacteristics.Key<?>> getKeysNeedingPermission();
     method @NonNull public java.util.Set<java.lang.String> getPhysicalCameraIds();
     method @Nullable public android.hardware.camera2.params.RecommendedStreamConfigurationMap getRecommendedStreamConfigurationMap(int);
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> COLOR_CORRECTION_AVAILABLE_ABERRATION_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AE_AVAILABLE_ANTIBANDING_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AE_AVAILABLE_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Range<java.lang.Integer>[]> CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Range<java.lang.Integer>> CONTROL_AE_COMPENSATION_RANGE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Rational> CONTROL_AE_COMPENSATION_STEP;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Boolean> CONTROL_AE_LOCK_AVAILABLE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AF_AVAILABLE_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AVAILABLE_EFFECTS;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AVAILABLE_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AVAILABLE_SCENE_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AWB_AVAILABLE_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Boolean> CONTROL_AWB_LOCK_AVAILABLE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> CONTROL_MAX_REGIONS_AE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> CONTROL_MAX_REGIONS_AF;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> CONTROL_MAX_REGIONS_AWB;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Range<java.lang.Integer>> CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Boolean> DEPTH_DEPTH_IS_EXCLUSIVE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> DISTORTION_CORRECTION_AVAILABLE_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> EDGE_AVAILABLE_EDGE_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Boolean> FLASH_INFO_AVAILABLE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> HOT_PIXEL_AVAILABLE_HOT_PIXEL_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> INFO_SUPPORTED_HARDWARE_LEVEL;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.String> INFO_VERSION;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Size[]> JPEG_AVAILABLE_THUMBNAIL_SIZES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_DISTORTION;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> LENS_FACING;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_INFO_AVAILABLE_APERTURES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_INFO_AVAILABLE_FILTER_DENSITIES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_INFO_AVAILABLE_FOCAL_LENGTHS;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> LENS_INFO_FOCUS_DISTANCE_CALIBRATION;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Float> LENS_INFO_HYPERFOCAL_DISTANCE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Float> LENS_INFO_MINIMUM_FOCUS_DISTANCE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_INTRINSIC_CALIBRATION;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> LENS_POSE_REFERENCE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_POSE_ROTATION;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_POSE_TRANSLATION;
-    field @Deprecated public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_RADIAL_DISTORTION;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> LOGICAL_MULTI_CAMERA_SENSOR_SYNC_TYPE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> REPROCESS_MAX_CAPTURE_STALL;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> REQUEST_AVAILABLE_CAPABILITIES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> REQUEST_MAX_NUM_INPUT_STREAMS;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> REQUEST_MAX_NUM_OUTPUT_PROC;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> REQUEST_MAX_NUM_OUTPUT_PROC_STALLING;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> REQUEST_MAX_NUM_OUTPUT_RAW;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> REQUEST_PARTIAL_RESULT_COUNT;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Byte> REQUEST_PIPELINE_MAX_DEPTH;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Float> SCALER_AVAILABLE_MAX_DIGITAL_ZOOM;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SCALER_CROPPING_TYPE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.MandatoryStreamCombination[]> SCALER_MANDATORY_STREAM_COMBINATIONS;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.StreamConfigurationMap> SCALER_STREAM_CONFIGURATION_MAP;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> SENSOR_AVAILABLE_TEST_PATTERN_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.BlackLevelPattern> SENSOR_BLACK_LEVEL_PATTERN;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_CALIBRATION_TRANSFORM1;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_CALIBRATION_TRANSFORM2;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_COLOR_TRANSFORM1;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_COLOR_TRANSFORM2;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_FORWARD_MATRIX1;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_FORWARD_MATRIX2;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.graphics.Rect> SENSOR_INFO_ACTIVE_ARRAY_SIZE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_INFO_COLOR_FILTER_ARRANGEMENT;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Range<java.lang.Long>> SENSOR_INFO_EXPOSURE_TIME_RANGE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Boolean> SENSOR_INFO_LENS_SHADING_APPLIED;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Long> SENSOR_INFO_MAX_FRAME_DURATION;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.SizeF> SENSOR_INFO_PHYSICAL_SIZE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Size> SENSOR_INFO_PIXEL_ARRAY_SIZE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.graphics.Rect> SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Range<java.lang.Integer>> SENSOR_INFO_SENSITIVITY_RANGE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_INFO_TIMESTAMP_SOURCE;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_INFO_WHITE_LEVEL;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_MAX_ANALOG_SENSITIVITY;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<android.graphics.Rect[]> SENSOR_OPTICAL_BLACK_REGIONS;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_ORIENTATION;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_REFERENCE_ILLUMINANT1;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Byte> SENSOR_REFERENCE_ILLUMINANT2;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> SHADING_AVAILABLE_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<boolean[]> STATISTICS_INFO_AVAILABLE_HOT_PIXEL_MAP_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> STATISTICS_INFO_AVAILABLE_LENS_SHADING_MAP_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> STATISTICS_INFO_AVAILABLE_OIS_DATA_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> STATISTICS_INFO_MAX_FACE_COUNT;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SYNC_MAX_LATENCY;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> TONEMAP_AVAILABLE_TONE_MAP_MODES;
-    field public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> TONEMAP_MAX_CURVE_POINTS;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> COLOR_CORRECTION_AVAILABLE_ABERRATION_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AE_AVAILABLE_ANTIBANDING_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AE_AVAILABLE_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Range<java.lang.Integer>[]> CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Range<java.lang.Integer>> CONTROL_AE_COMPENSATION_RANGE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Rational> CONTROL_AE_COMPENSATION_STEP;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Boolean> CONTROL_AE_LOCK_AVAILABLE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AF_AVAILABLE_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AVAILABLE_EFFECTS;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AVAILABLE_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AVAILABLE_SCENE_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AWB_AVAILABLE_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Boolean> CONTROL_AWB_LOCK_AVAILABLE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> CONTROL_MAX_REGIONS_AE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> CONTROL_MAX_REGIONS_AF;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> CONTROL_MAX_REGIONS_AWB;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Range<java.lang.Integer>> CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Boolean> DEPTH_DEPTH_IS_EXCLUSIVE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> DISTORTION_CORRECTION_AVAILABLE_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> EDGE_AVAILABLE_EDGE_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Boolean> FLASH_INFO_AVAILABLE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> HOT_PIXEL_AVAILABLE_HOT_PIXEL_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> INFO_SUPPORTED_HARDWARE_LEVEL;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.String> INFO_VERSION;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Size[]> JPEG_AVAILABLE_THUMBNAIL_SIZES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_DISTORTION;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> LENS_FACING;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_INFO_AVAILABLE_APERTURES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_INFO_AVAILABLE_FILTER_DENSITIES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_INFO_AVAILABLE_FOCAL_LENGTHS;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> LENS_INFO_FOCUS_DISTANCE_CALIBRATION;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Float> LENS_INFO_HYPERFOCAL_DISTANCE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Float> LENS_INFO_MINIMUM_FOCUS_DISTANCE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_INTRINSIC_CALIBRATION;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> LENS_POSE_REFERENCE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_POSE_ROTATION;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_POSE_TRANSLATION;
+    field @Deprecated @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<float[]> LENS_RADIAL_DISTORTION;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> LOGICAL_MULTI_CAMERA_SENSOR_SYNC_TYPE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> REPROCESS_MAX_CAPTURE_STALL;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> REQUEST_AVAILABLE_CAPABILITIES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> REQUEST_MAX_NUM_INPUT_STREAMS;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> REQUEST_MAX_NUM_OUTPUT_PROC;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> REQUEST_MAX_NUM_OUTPUT_PROC_STALLING;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> REQUEST_MAX_NUM_OUTPUT_RAW;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> REQUEST_PARTIAL_RESULT_COUNT;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Byte> REQUEST_PIPELINE_MAX_DEPTH;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Float> SCALER_AVAILABLE_MAX_DIGITAL_ZOOM;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SCALER_CROPPING_TYPE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.MandatoryStreamCombination[]> SCALER_MANDATORY_STREAM_COMBINATIONS;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.StreamConfigurationMap> SCALER_STREAM_CONFIGURATION_MAP;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> SENSOR_AVAILABLE_TEST_PATTERN_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.BlackLevelPattern> SENSOR_BLACK_LEVEL_PATTERN;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_CALIBRATION_TRANSFORM1;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_CALIBRATION_TRANSFORM2;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_COLOR_TRANSFORM1;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_COLOR_TRANSFORM2;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_FORWARD_MATRIX1;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_FORWARD_MATRIX2;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.graphics.Rect> SENSOR_INFO_ACTIVE_ARRAY_SIZE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_INFO_COLOR_FILTER_ARRANGEMENT;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Range<java.lang.Long>> SENSOR_INFO_EXPOSURE_TIME_RANGE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Boolean> SENSOR_INFO_LENS_SHADING_APPLIED;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Long> SENSOR_INFO_MAX_FRAME_DURATION;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.SizeF> SENSOR_INFO_PHYSICAL_SIZE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Size> SENSOR_INFO_PIXEL_ARRAY_SIZE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.graphics.Rect> SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Range<java.lang.Integer>> SENSOR_INFO_SENSITIVITY_RANGE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_INFO_TIMESTAMP_SOURCE;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_INFO_WHITE_LEVEL;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_MAX_ANALOG_SENSITIVITY;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.graphics.Rect[]> SENSOR_OPTICAL_BLACK_REGIONS;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_ORIENTATION;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_REFERENCE_ILLUMINANT1;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Byte> SENSOR_REFERENCE_ILLUMINANT2;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> SHADING_AVAILABLE_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<boolean[]> STATISTICS_INFO_AVAILABLE_HOT_PIXEL_MAP_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> STATISTICS_INFO_AVAILABLE_LENS_SHADING_MAP_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> STATISTICS_INFO_AVAILABLE_OIS_DATA_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> STATISTICS_INFO_MAX_FACE_COUNT;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SYNC_MAX_LATENCY;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> TONEMAP_AVAILABLE_TONE_MAP_MODES;
+    field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> TONEMAP_MAX_CURVE_POINTS;
   }
 
   public static final class CameraCharacteristics.Key<T> {
@@ -17036,63 +17038,63 @@
     method @Nullable public Object getTag();
     method public boolean isReprocess();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Boolean> BLACK_LEVEL_LOCK;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> COLOR_CORRECTION_ABERRATION_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<android.hardware.camera2.params.RggbChannelVector> COLOR_CORRECTION_GAINS;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> COLOR_CORRECTION_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<android.hardware.camera2.params.ColorSpaceTransform> COLOR_CORRECTION_TRANSFORM;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AE_ANTIBANDING_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AE_EXPOSURE_COMPENSATION;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Boolean> CONTROL_AE_LOCK;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AE_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AE_PRECAPTURE_TRIGGER;
-    field public static final android.hardware.camera2.CaptureRequest.Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AE_REGIONS;
-    field public static final android.hardware.camera2.CaptureRequest.Key<android.util.Range<java.lang.Integer>> CONTROL_AE_TARGET_FPS_RANGE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AF_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AF_REGIONS;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AF_TRIGGER;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Boolean> CONTROL_AWB_LOCK;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AWB_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AWB_REGIONS;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_CAPTURE_INTENT;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_EFFECT_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Boolean> CONTROL_ENABLE_ZSL;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_POST_RAW_SENSITIVITY_BOOST;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_SCENE_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_VIDEO_STABILIZATION_MODE;
-    field public static final android.os.Parcelable.Creator<android.hardware.camera2.CaptureRequest> CREATOR;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> DISTORTION_CORRECTION_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> EDGE_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> FLASH_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> HOT_PIXEL_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<android.location.Location> JPEG_GPS_LOCATION;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> JPEG_ORIENTATION;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Byte> JPEG_QUALITY;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Byte> JPEG_THUMBNAIL_QUALITY;
-    field public static final android.hardware.camera2.CaptureRequest.Key<android.util.Size> JPEG_THUMBNAIL_SIZE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> LENS_APERTURE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> LENS_FILTER_DENSITY;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> LENS_FOCAL_LENGTH;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> LENS_FOCUS_DISTANCE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> LENS_OPTICAL_STABILIZATION_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> NOISE_REDUCTION_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> REPROCESS_EFFECTIVE_EXPOSURE_FACTOR;
-    field public static final android.hardware.camera2.CaptureRequest.Key<android.graphics.Rect> SCALER_CROP_REGION;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Long> SENSOR_EXPOSURE_TIME;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Long> SENSOR_FRAME_DURATION;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> SENSOR_SENSITIVITY;
-    field public static final android.hardware.camera2.CaptureRequest.Key<int[]> SENSOR_TEST_PATTERN_DATA;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> SENSOR_TEST_PATTERN_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> SHADING_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> STATISTICS_FACE_DETECT_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Boolean> STATISTICS_HOT_PIXEL_MAP_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> STATISTICS_LENS_SHADING_MAP_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> STATISTICS_OIS_DATA_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<android.hardware.camera2.params.TonemapCurve> TONEMAP_CURVE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> TONEMAP_GAMMA;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> TONEMAP_MODE;
-    field public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> TONEMAP_PRESET_CURVE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Boolean> BLACK_LEVEL_LOCK;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> COLOR_CORRECTION_ABERRATION_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<android.hardware.camera2.params.RggbChannelVector> COLOR_CORRECTION_GAINS;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> COLOR_CORRECTION_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<android.hardware.camera2.params.ColorSpaceTransform> COLOR_CORRECTION_TRANSFORM;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AE_ANTIBANDING_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AE_EXPOSURE_COMPENSATION;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Boolean> CONTROL_AE_LOCK;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AE_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AE_PRECAPTURE_TRIGGER;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AE_REGIONS;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<android.util.Range<java.lang.Integer>> CONTROL_AE_TARGET_FPS_RANGE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AF_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AF_REGIONS;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AF_TRIGGER;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Boolean> CONTROL_AWB_LOCK;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_AWB_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AWB_REGIONS;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_CAPTURE_INTENT;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_EFFECT_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Boolean> CONTROL_ENABLE_ZSL;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_POST_RAW_SENSITIVITY_BOOST;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_SCENE_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_VIDEO_STABILIZATION_MODE;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.camera2.CaptureRequest> CREATOR;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> DISTORTION_CORRECTION_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> EDGE_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> FLASH_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> HOT_PIXEL_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<android.location.Location> JPEG_GPS_LOCATION;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> JPEG_ORIENTATION;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Byte> JPEG_QUALITY;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Byte> JPEG_THUMBNAIL_QUALITY;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<android.util.Size> JPEG_THUMBNAIL_SIZE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> LENS_APERTURE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> LENS_FILTER_DENSITY;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> LENS_FOCAL_LENGTH;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> LENS_FOCUS_DISTANCE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> LENS_OPTICAL_STABILIZATION_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> NOISE_REDUCTION_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> REPROCESS_EFFECTIVE_EXPOSURE_FACTOR;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<android.graphics.Rect> SCALER_CROP_REGION;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Long> SENSOR_EXPOSURE_TIME;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Long> SENSOR_FRAME_DURATION;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> SENSOR_SENSITIVITY;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<int[]> SENSOR_TEST_PATTERN_DATA;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> SENSOR_TEST_PATTERN_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> SHADING_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> STATISTICS_FACE_DETECT_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Boolean> STATISTICS_HOT_PIXEL_MAP_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> STATISTICS_LENS_SHADING_MAP_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> STATISTICS_OIS_DATA_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<android.hardware.camera2.params.TonemapCurve> TONEMAP_CURVE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> TONEMAP_GAMMA;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> TONEMAP_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> TONEMAP_PRESET_CURVE;
   }
 
   public static final class CaptureRequest.Builder {
@@ -17117,88 +17119,88 @@
     method @NonNull public java.util.List<android.hardware.camera2.CaptureResult.Key<?>> getKeys();
     method @NonNull public android.hardware.camera2.CaptureRequest getRequest();
     method public int getSequenceId();
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Boolean> BLACK_LEVEL_LOCK;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> COLOR_CORRECTION_ABERRATION_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.RggbChannelVector> COLOR_CORRECTION_GAINS;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> COLOR_CORRECTION_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.ColorSpaceTransform> COLOR_CORRECTION_TRANSFORM;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AE_ANTIBANDING_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AE_EXPOSURE_COMPENSATION;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Boolean> CONTROL_AE_LOCK;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AE_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AE_PRECAPTURE_TRIGGER;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AE_REGIONS;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AE_STATE;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.util.Range<java.lang.Integer>> CONTROL_AE_TARGET_FPS_RANGE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AF_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AF_REGIONS;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AF_SCENE_CHANGE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AF_STATE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AF_TRIGGER;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Boolean> CONTROL_AWB_LOCK;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AWB_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AWB_REGIONS;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AWB_STATE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_CAPTURE_INTENT;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_EFFECT_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Boolean> CONTROL_ENABLE_ZSL;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_POST_RAW_SENSITIVITY_BOOST;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_SCENE_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_VIDEO_STABILIZATION_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> DISTORTION_CORRECTION_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> EDGE_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> FLASH_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> FLASH_STATE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> HOT_PIXEL_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.location.Location> JPEG_GPS_LOCATION;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> JPEG_ORIENTATION;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Byte> JPEG_QUALITY;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Byte> JPEG_THUMBNAIL_QUALITY;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.util.Size> JPEG_THUMBNAIL_SIZE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> LENS_APERTURE;
-    field public static final android.hardware.camera2.CaptureResult.Key<float[]> LENS_DISTORTION;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> LENS_FILTER_DENSITY;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> LENS_FOCAL_LENGTH;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> LENS_FOCUS_DISTANCE;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.util.Pair<java.lang.Float,java.lang.Float>> LENS_FOCUS_RANGE;
-    field public static final android.hardware.camera2.CaptureResult.Key<float[]> LENS_INTRINSIC_CALIBRATION;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> LENS_OPTICAL_STABILIZATION_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<float[]> LENS_POSE_ROTATION;
-    field public static final android.hardware.camera2.CaptureResult.Key<float[]> LENS_POSE_TRANSLATION;
-    field @Deprecated public static final android.hardware.camera2.CaptureResult.Key<float[]> LENS_RADIAL_DISTORTION;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> LENS_STATE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.String> LOGICAL_MULTI_CAMERA_ACTIVE_PHYSICAL_ID;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> NOISE_REDUCTION_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> REPROCESS_EFFECTIVE_EXPOSURE_FACTOR;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Byte> REQUEST_PIPELINE_DEPTH;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.graphics.Rect> SCALER_CROP_REGION;
-    field public static final android.hardware.camera2.CaptureResult.Key<float[]> SENSOR_DYNAMIC_BLACK_LEVEL;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> SENSOR_DYNAMIC_WHITE_LEVEL;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Long> SENSOR_EXPOSURE_TIME;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Long> SENSOR_FRAME_DURATION;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> SENSOR_GREEN_SPLIT;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.util.Rational[]> SENSOR_NEUTRAL_COLOR_POINT;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.util.Pair<java.lang.Double,java.lang.Double>[]> SENSOR_NOISE_PROFILE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Long> SENSOR_ROLLING_SHUTTER_SKEW;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> SENSOR_SENSITIVITY;
-    field public static final android.hardware.camera2.CaptureResult.Key<int[]> SENSOR_TEST_PATTERN_DATA;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> SENSOR_TEST_PATTERN_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Long> SENSOR_TIMESTAMP;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> SHADING_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.Face[]> STATISTICS_FACES;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> STATISTICS_FACE_DETECT_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.graphics.Point[]> STATISTICS_HOT_PIXEL_MAP;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Boolean> STATISTICS_HOT_PIXEL_MAP_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.LensShadingMap> STATISTICS_LENS_SHADING_CORRECTION_MAP;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> STATISTICS_LENS_SHADING_MAP_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> STATISTICS_OIS_DATA_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.OisSample[]> STATISTICS_OIS_SAMPLES;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> STATISTICS_SCENE_FLICKER;
-    field public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.TonemapCurve> TONEMAP_CURVE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> TONEMAP_GAMMA;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> TONEMAP_MODE;
-    field public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> TONEMAP_PRESET_CURVE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Boolean> BLACK_LEVEL_LOCK;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> COLOR_CORRECTION_ABERRATION_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.RggbChannelVector> COLOR_CORRECTION_GAINS;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> COLOR_CORRECTION_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.ColorSpaceTransform> COLOR_CORRECTION_TRANSFORM;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AE_ANTIBANDING_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AE_EXPOSURE_COMPENSATION;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Boolean> CONTROL_AE_LOCK;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AE_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AE_PRECAPTURE_TRIGGER;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AE_REGIONS;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AE_STATE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.util.Range<java.lang.Integer>> CONTROL_AE_TARGET_FPS_RANGE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AF_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AF_REGIONS;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AF_SCENE_CHANGE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AF_STATE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AF_TRIGGER;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Boolean> CONTROL_AWB_LOCK;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AWB_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AWB_REGIONS;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_AWB_STATE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_CAPTURE_INTENT;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_EFFECT_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Boolean> CONTROL_ENABLE_ZSL;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_POST_RAW_SENSITIVITY_BOOST;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_SCENE_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_VIDEO_STABILIZATION_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> DISTORTION_CORRECTION_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> EDGE_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> FLASH_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> FLASH_STATE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> HOT_PIXEL_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.location.Location> JPEG_GPS_LOCATION;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> JPEG_ORIENTATION;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Byte> JPEG_QUALITY;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Byte> JPEG_THUMBNAIL_QUALITY;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.util.Size> JPEG_THUMBNAIL_SIZE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> LENS_APERTURE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<float[]> LENS_DISTORTION;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> LENS_FILTER_DENSITY;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> LENS_FOCAL_LENGTH;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> LENS_FOCUS_DISTANCE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.util.Pair<java.lang.Float,java.lang.Float>> LENS_FOCUS_RANGE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<float[]> LENS_INTRINSIC_CALIBRATION;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> LENS_OPTICAL_STABILIZATION_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<float[]> LENS_POSE_ROTATION;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<float[]> LENS_POSE_TRANSLATION;
+    field @Deprecated @NonNull public static final android.hardware.camera2.CaptureResult.Key<float[]> LENS_RADIAL_DISTORTION;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> LENS_STATE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.String> LOGICAL_MULTI_CAMERA_ACTIVE_PHYSICAL_ID;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> NOISE_REDUCTION_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> REPROCESS_EFFECTIVE_EXPOSURE_FACTOR;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Byte> REQUEST_PIPELINE_DEPTH;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.graphics.Rect> SCALER_CROP_REGION;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<float[]> SENSOR_DYNAMIC_BLACK_LEVEL;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> SENSOR_DYNAMIC_WHITE_LEVEL;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Long> SENSOR_EXPOSURE_TIME;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Long> SENSOR_FRAME_DURATION;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> SENSOR_GREEN_SPLIT;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.util.Rational[]> SENSOR_NEUTRAL_COLOR_POINT;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.util.Pair<java.lang.Double,java.lang.Double>[]> SENSOR_NOISE_PROFILE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Long> SENSOR_ROLLING_SHUTTER_SKEW;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> SENSOR_SENSITIVITY;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<int[]> SENSOR_TEST_PATTERN_DATA;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> SENSOR_TEST_PATTERN_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Long> SENSOR_TIMESTAMP;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> SHADING_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.Face[]> STATISTICS_FACES;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> STATISTICS_FACE_DETECT_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.graphics.Point[]> STATISTICS_HOT_PIXEL_MAP;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Boolean> STATISTICS_HOT_PIXEL_MAP_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.LensShadingMap> STATISTICS_LENS_SHADING_CORRECTION_MAP;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> STATISTICS_LENS_SHADING_MAP_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> STATISTICS_OIS_DATA_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.OisSample[]> STATISTICS_OIS_SAMPLES;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> STATISTICS_SCENE_FLICKER;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<android.hardware.camera2.params.TonemapCurve> TONEMAP_CURVE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> TONEMAP_GAMMA;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> TONEMAP_MODE;
+    field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> TONEMAP_PRESET_CURVE;
   }
 
   public static final class CaptureResult.Key<T> {
@@ -17323,7 +17325,7 @@
     method public void removeSurface(@NonNull android.view.Surface);
     method public void setPhysicalCameraId(@Nullable String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.camera2.params.OutputConfiguration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.camera2.params.OutputConfiguration> CREATOR;
     field public static final int SURFACE_GROUP_ID_NONE = -1; // 0xffffffff
   }
 
@@ -17381,7 +17383,7 @@
     method public void setInputConfiguration(@NonNull android.hardware.camera2.params.InputConfiguration);
     method public void setSessionParameters(android.hardware.camera2.CaptureRequest);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.camera2.params.SessionConfiguration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.camera2.params.SessionConfiguration> CREATOR;
     field public static final int SESSION_HIGH_SPEED = 1; // 0x1
     field public static final int SESSION_REGULAR = 0; // 0x0
   }
@@ -17541,7 +17543,7 @@
     method @Nullable public String getUri();
     method @Nullable public String getVersion();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.usb.UsbAccessory> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.usb.UsbAccessory> CREATOR;
   }
 
   public class UsbConfiguration implements android.os.Parcelable {
@@ -17554,7 +17556,7 @@
     method public boolean isRemoteWakeup();
     method public boolean isSelfPowered();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.usb.UsbConfiguration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.usb.UsbConfiguration> CREATOR;
   }
 
   public final class UsbConstants {
@@ -17614,7 +17616,7 @@
     method public int getVendorId();
     method @NonNull public String getVersion();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.usb.UsbDevice> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.usb.UsbDevice> CREATOR;
   }
 
   public class UsbDeviceConnection {
@@ -17644,7 +17646,7 @@
     method public int getMaxPacketSize();
     method public int getType();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.usb.UsbEndpoint> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.usb.UsbEndpoint> CREATOR;
   }
 
   public class UsbInterface implements android.os.Parcelable {
@@ -17658,7 +17660,7 @@
     method public int getInterfaceSubclass();
     method @Nullable public String getName();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.usb.UsbInterface> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.usb.UsbInterface> CREATOR;
   }
 
   public class UsbManager {
@@ -22581,7 +22583,7 @@
     method public void setThoroughfare(String);
     method public void setUrl(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.location.Address> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.Address> CREATOR;
   }
 
   public class Criteria implements android.os.Parcelable {
@@ -22614,7 +22616,7 @@
     field public static final int ACCURACY_HIGH = 3; // 0x3
     field public static final int ACCURACY_LOW = 1; // 0x1
     field public static final int ACCURACY_MEDIUM = 2; // 0x2
-    field public static final android.os.Parcelable.Creator<android.location.Criteria> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.Criteria> CREATOR;
     field public static final int NO_REQUIREMENT = 0; // 0x0
     field public static final int POWER_HIGH = 3; // 0x3
     field public static final int POWER_LOW = 1; // 0x1
@@ -22649,7 +22651,7 @@
     method public boolean hasLeapSecond();
     method public boolean hasTimeUncertaintyNanos();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.location.GnssClock> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.GnssClock> CREATOR;
   }
 
   public final class GnssMeasurement implements android.os.Parcelable {
@@ -22705,7 +22707,7 @@
     field public static final int CODE_TYPE_X = 10; // 0xa
     field public static final int CODE_TYPE_Y = 11; // 0xb
     field public static final int CODE_TYPE_Z = 12; // 0xc
-    field public static final android.os.Parcelable.Creator<android.location.GnssMeasurement> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.GnssMeasurement> CREATOR;
     field public static final int MULTIPATH_INDICATOR_DETECTED = 1; // 0x1
     field public static final int MULTIPATH_INDICATOR_NOT_DETECTED = 2; // 0x2
     field public static final int MULTIPATH_INDICATOR_UNKNOWN = 0; // 0x0
@@ -22734,7 +22736,7 @@
     method @NonNull public android.location.GnssClock getClock();
     method @NonNull public java.util.Collection<android.location.GnssMeasurement> getMeasurements();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.location.GnssMeasurementsEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.GnssMeasurementsEvent> CREATOR;
   }
 
   public abstract static class GnssMeasurementsEvent.Callback {
@@ -22756,7 +22758,7 @@
     method public int getSvid();
     method public int getType();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.location.GnssNavigationMessage> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.GnssNavigationMessage> CREATOR;
     field public static final int STATUS_PARITY_PASSED = 1; // 0x1
     field public static final int STATUS_PARITY_REBUILT = 2; // 0x2
     field public static final int STATUS_UNKNOWN = 0; // 0x0
@@ -22889,7 +22891,7 @@
     method public void setTime(long);
     method public void setVerticalAccuracyMeters(float);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.location.Location> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.Location> CREATOR;
     field public static final int FORMAT_DEGREES = 0; // 0x0
     field public static final int FORMAT_MINUTES = 1; // 0x1
     field public static final int FORMAT_SECONDS = 2; // 0x2
@@ -23021,7 +23023,7 @@
     field public static final int CONTENT_TYPE_SONIFICATION = 4; // 0x4
     field public static final int CONTENT_TYPE_SPEECH = 1; // 0x1
     field public static final int CONTENT_TYPE_UNKNOWN = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.media.AudioAttributes> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.AudioAttributes> CREATOR;
     field public static final int FLAG_AUDIBILITY_ENFORCED = 1; // 0x1
     field public static final int FLAG_HW_AV_SYNC = 16; // 0x10
     field @Deprecated public static final int FLAG_LOW_LATENCY = 256; // 0x100
@@ -23168,7 +23170,7 @@
     field public static final int CHANNEL_OUT_SIDE_RIGHT = 4096; // 0x1000
     field public static final int CHANNEL_OUT_STEREO = 12; // 0xc
     field public static final int CHANNEL_OUT_SURROUND = 1052; // 0x41c
-    field public static final android.os.Parcelable.Creator<android.media.AudioFormat> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.AudioFormat> CREATOR;
     field public static final int ENCODING_AAC_ELD = 15; // 0xf
     field public static final int ENCODING_AAC_HE_V1 = 11; // 0xb
     field public static final int ENCODING_AAC_HE_V2 = 12; // 0xc
@@ -23397,7 +23399,7 @@
     method public int describeContents();
     method public android.media.AudioAttributes getAudioAttributes();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.AudioPlaybackConfiguration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.AudioPlaybackConfiguration> CREATOR;
   }
 
   public final class AudioPresentation {
@@ -23416,14 +23418,14 @@
     field public static final int MASTERING_NOT_INDICATED = 0; // 0x0
   }
 
-  public static class AudioPresentation.Builder {
+  public static final class AudioPresentation.Builder {
     ctor public AudioPresentation.Builder(int);
     method @NonNull public android.media.AudioPresentation build();
     method @NonNull public android.media.AudioPresentation.Builder setHasAudioDescription(boolean);
     method @NonNull public android.media.AudioPresentation.Builder setHasDialogueEnhancement(boolean);
     method @NonNull public android.media.AudioPresentation.Builder setHasSpokenSubtitles(boolean);
-    method @NonNull public android.media.AudioPresentation.Builder setLabels(@NonNull java.util.Map<android.icu.util.ULocale,java.lang.String>);
-    method @NonNull public android.media.AudioPresentation.Builder setLocale(android.icu.util.ULocale);
+    method @NonNull public android.media.AudioPresentation.Builder setLabels(@NonNull java.util.Map<android.icu.util.ULocale,java.lang.CharSequence>);
+    method @NonNull public android.media.AudioPresentation.Builder setLocale(@NonNull android.icu.util.ULocale);
     method @NonNull public android.media.AudioPresentation.Builder setMasteringIndication(int);
     method @NonNull public android.media.AudioPresentation.Builder setProgramId(int);
   }
@@ -23526,7 +23528,7 @@
     method public android.media.AudioFormat getFormat();
     method public boolean isClientSilenced();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.AudioRecordingConfiguration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.AudioRecordingConfiguration> CREATOR;
   }
 
   public interface AudioRecordingMonitor {
@@ -24720,7 +24722,7 @@
     field public static final long BT_FOLDER_TYPE_PLAYLISTS = 5L; // 0x5L
     field public static final long BT_FOLDER_TYPE_TITLES = 1L; // 0x1L
     field public static final long BT_FOLDER_TYPE_YEARS = 6L; // 0x6L
-    field public static final android.os.Parcelable.Creator<android.media.MediaDescription> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.MediaDescription> CREATOR;
     field public static final String EXTRA_BT_FOLDER_TYPE = "android.media.extra.BT_FOLDER_TYPE";
   }
 
@@ -25125,7 +25127,7 @@
     method public long getStartPosition();
     method public void setMetadata(@Nullable android.media.MediaMetadata);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.MediaItem2> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.MediaItem2> CREATOR;
     field public static final long POSITION_UNKNOWN = 576460752303423487L; // 0x7ffffffffffffffL
   }
 
@@ -25149,7 +25151,7 @@
     method public java.util.Set<java.lang.String> keySet();
     method public int size();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.MediaMetadata> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.MediaMetadata> CREATOR;
     field public static final String METADATA_KEY_ALBUM = "android.media.metadata.ALBUM";
     field public static final String METADATA_KEY_ALBUM_ART = "android.media.metadata.ALBUM_ART";
     field public static final String METADATA_KEY_ALBUM_ARTIST = "android.media.metadata.ALBUM_ARTIST";
@@ -26034,6 +26036,7 @@
   public static final class MediaSession2.Builder {
     ctor public MediaSession2.Builder(@NonNull android.content.Context);
     method @NonNull public android.media.MediaSession2 build();
+    method @NonNull public android.media.MediaSession2.Builder setExtras(@Nullable android.os.Bundle);
     method @NonNull public android.media.MediaSession2.Builder setId(@NonNull String);
     method @NonNull public android.media.MediaSession2.Builder setSessionActivity(@Nullable android.app.PendingIntent);
     method @NonNull public android.media.MediaSession2.Builder setSessionCallback(@NonNull java.util.concurrent.Executor, @NonNull android.media.MediaSession2.SessionCallback);
@@ -26186,7 +26189,7 @@
     field public static final int AUDIO_FALLBACK_MODE_DEFAULT = 0; // 0x0
     field public static final int AUDIO_FALLBACK_MODE_FAIL = 2; // 0x2
     field public static final int AUDIO_FALLBACK_MODE_MUTE = 1; // 0x1
-    field public static final android.os.Parcelable.Creator<android.media.PlaybackParams> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.PlaybackParams> CREATOR;
   }
 
   public final class Rating implements android.os.Parcelable {
@@ -26203,7 +26206,7 @@
     method public static android.media.Rating newThumbRating(boolean);
     method public static android.media.Rating newUnratedRating(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.Rating> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.Rating> CREATOR;
     field public static final int RATING_3_STARS = 3; // 0x3
     field public static final int RATING_4_STARS = 4; // 0x4
     field public static final int RATING_5_STARS = 5; // 0x5
@@ -26362,7 +26365,7 @@
     method @Nullable public android.os.Bundle getExtras();
     method public void writeToParcel(@NonNull android.os.Parcel, int);
     field public static final int COMMAND_CODE_CUSTOM = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.media.Session2Command> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.Session2Command> CREATOR;
     field public static final int RESULT_ERROR_UNKNOWN_ERROR = -1; // 0xffffffff
     field public static final int RESULT_INFO_SKIPPED = 1; // 0x1
     field public static final int RESULT_SUCCESS = 0; // 0x0
@@ -26380,7 +26383,7 @@
     method public boolean hasCommand(@NonNull android.media.Session2Command);
     method public boolean hasCommand(int);
     method public void writeToParcel(@NonNull android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.Session2CommandGroup> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.Session2CommandGroup> CREATOR;
   }
 
   public static final class Session2CommandGroup.Builder {
@@ -26396,12 +26399,13 @@
   public final class Session2Token implements android.os.Parcelable {
     ctor public Session2Token(@NonNull android.content.Context, @NonNull android.content.ComponentName);
     method public int describeContents();
+    method @Nullable public android.os.Bundle getExtras();
     method @NonNull public String getPackageName();
     method @Nullable public String getServiceName();
     method public int getType();
     method public int getUid();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.Session2Token> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.Session2Token> CREATOR;
     field public static final int TYPE_SESSION = 0; // 0x0
     field public static final int TYPE_SESSION_SERVICE = 1; // 0x1
   }
@@ -26653,7 +26657,7 @@
     method public float[] getTimes();
     method public float[] getVolumes();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.VolumeShaper.Configuration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.VolumeShaper.Configuration> CREATOR;
     field public static final android.media.VolumeShaper.Configuration CUBIC_RAMP;
     field public static final int INTERPOLATOR_TYPE_CUBIC = 2; // 0x2
     field public static final int INTERPOLATOR_TYPE_CUBIC_MONOTONIC = 3; // 0x3
@@ -26680,7 +26684,7 @@
   public static final class VolumeShaper.Operation implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.VolumeShaper.Operation> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.VolumeShaper.Operation> CREATOR;
     field public static final android.media.VolumeShaper.Operation PLAY;
     field public static final android.media.VolumeShaper.Operation REVERSE;
   }
@@ -27233,7 +27237,7 @@
     method public boolean isBrowsable();
     method public boolean isPlayable();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.browse.MediaBrowser.MediaItem> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.browse.MediaBrowser.MediaItem> CREATOR;
     field public static final int FLAG_BROWSABLE = 1; // 0x1
     field public static final int FLAG_PLAYABLE = 2; // 0x2
   }
@@ -27327,7 +27331,7 @@
     method public int getType();
     method public boolean isPrivate();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.midi.MidiDeviceInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.midi.MidiDeviceInfo> CREATOR;
     field public static final String PROPERTY_BLUETOOTH_DEVICE = "bluetooth_device";
     field public static final String PROPERTY_MANUFACTURER = "manufacturer";
     field public static final String PROPERTY_NAME = "name";
@@ -27365,7 +27369,7 @@
     method public int getOutputPortOpenCount(int);
     method public boolean isInputPortOpen(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.midi.MidiDeviceStatus> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.midi.MidiDeviceStatus> CREATOR;
   }
 
   public final class MidiInputPort extends android.media.midi.MidiReceiver implements java.io.Closeable {
@@ -27488,7 +27492,7 @@
     method public int getPlaybackType();
     method public int getVolumeControl();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.session.MediaController.PlaybackInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.session.MediaController.PlaybackInfo> CREATOR;
     field public static final int PLAYBACK_TYPE_LOCAL = 1; // 0x1
     field public static final int PLAYBACK_TYPE_REMOTE = 2; // 0x2
   }
@@ -27574,14 +27578,14 @@
     method public android.media.MediaDescription getDescription();
     method public long getQueueId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.session.MediaSession.QueueItem> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.session.MediaSession.QueueItem> CREATOR;
     field public static final int UNKNOWN_ID = -1; // 0xffffffff
   }
 
   public static final class MediaSession.Token implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.session.MediaSession.Token> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.session.MediaSession.Token> CREATOR;
   }
 
   public final class MediaSessionManager {
@@ -27643,7 +27647,7 @@
     field public static final long ACTION_SKIP_TO_PREVIOUS = 16L; // 0x10L
     field public static final long ACTION_SKIP_TO_QUEUE_ITEM = 4096L; // 0x1000L
     field public static final long ACTION_STOP = 1L; // 0x1L
-    field public static final android.os.Parcelable.Creator<android.media.session.PlaybackState> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.session.PlaybackState> CREATOR;
     field public static final long PLAYBACK_POSITION_UNKNOWN = -1L; // 0xffffffffffffffffL
     field public static final int STATE_BUFFERING = 6; // 0x6
     field public static final int STATE_CONNECTING = 8; // 0x8
@@ -27681,7 +27685,7 @@
     method public int getIcon();
     method public CharSequence getName();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.session.PlaybackState.CustomAction> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.session.PlaybackState.CustomAction> CREATOR;
   }
 
   public static final class PlaybackState.CustomAction.Builder {
@@ -28119,7 +28123,7 @@
     method public android.graphics.drawable.Drawable loadIcon(@NonNull android.content.Context);
     method public CharSequence loadLabel(@NonNull android.content.Context);
     method public void writeToParcel(@NonNull android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.tv.TvInputInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.tv.TvInputInfo> CREATOR;
     field public static final String EXTRA_INPUT_ID = "android.media.tv.extra.INPUT_ID";
     field public static final int TYPE_COMPONENT = 1004; // 0x3ec
     field public static final int TYPE_COMPOSITE = 1001; // 0x3e9
@@ -28288,7 +28292,7 @@
     method public float getVideoPixelAspectRatio();
     method public int getVideoWidth();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.tv.TvTrackInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.tv.TvTrackInfo> CREATOR;
     field public static final int TYPE_AUDIO = 0; // 0x0
     field public static final int TYPE_SUBTITLE = 2; // 0x2
     field public static final int TYPE_VIDEO = 1; // 0x1
@@ -28610,7 +28614,7 @@
     method public void ignoreNetwork();
     method public void reportCaptivePortalDismissed();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.CaptivePortal> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.CaptivePortal> CREATOR;
   }
 
   public class ConnectivityManager {
@@ -28760,7 +28764,7 @@
     method public int getPrefixLength();
     method public byte[] getRawAddress();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.IpPrefix> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.IpPrefix> CREATOR;
   }
 
   public final class IpSecAlgorithm implements android.os.Parcelable {
@@ -28777,7 +28781,7 @@
     field public static final String AUTH_HMAC_SHA256 = "hmac(sha256)";
     field public static final String AUTH_HMAC_SHA384 = "hmac(sha384)";
     field public static final String AUTH_HMAC_SHA512 = "hmac(sha512)";
-    field public static final android.os.Parcelable.Creator<android.net.IpSecAlgorithm> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.IpSecAlgorithm> CREATOR;
     field public static final String CRYPT_AES_CBC = "cbc(aes)";
   }
 
@@ -28834,7 +28838,7 @@
     method public int getPrefixLength();
     method public int getScope();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.LinkAddress> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.LinkAddress> CREATOR;
   }
 
   public final class LinkProperties implements android.os.Parcelable {
@@ -28849,7 +28853,7 @@
     method public java.util.List<android.net.RouteInfo> getRoutes();
     method public boolean isPrivateDnsActive();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.LinkProperties> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.LinkProperties> CREATOR;
   }
 
   public class LocalServerSocket implements java.io.Closeable {
@@ -28917,7 +28921,7 @@
     method @NonNull public String toOuiString();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.net.MacAddress BROADCAST_ADDRESS;
-    field public static final android.os.Parcelable.Creator<android.net.MacAddress> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.MacAddress> CREATOR;
     field public static final int TYPE_BROADCAST = 3; // 0x3
     field public static final int TYPE_MULTICAST = 2; // 0x2
     field public static final int TYPE_UNICAST = 1; // 0x1
@@ -28947,7 +28951,7 @@
     method public java.net.URLConnection openConnection(java.net.URL) throws java.io.IOException;
     method public java.net.URLConnection openConnection(java.net.URL, java.net.Proxy) throws java.io.IOException;
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.Network> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.Network> CREATOR;
   }
 
   public final class NetworkCapabilities implements android.os.Parcelable {
@@ -28959,7 +28963,7 @@
     method public boolean hasCapability(int);
     method public boolean hasTransport(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.NetworkCapabilities> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.NetworkCapabilities> CREATOR;
     field public static final int NET_CAPABILITY_CAPTIVE_PORTAL = 17; // 0x11
     field public static final int NET_CAPABILITY_CBS = 5; // 0x5
     field public static final int NET_CAPABILITY_DUN = 2; // 0x2
@@ -29007,7 +29011,7 @@
     method @Deprecated public boolean isFailover();
     method @Deprecated public boolean isRoaming();
     method @Deprecated public void writeToParcel(android.os.Parcel, int);
-    field @Deprecated public static final android.os.Parcelable.Creator<android.net.NetworkInfo> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.net.NetworkInfo> CREATOR;
   }
 
   @Deprecated public enum NetworkInfo.DetailedState {
@@ -29040,7 +29044,7 @@
     method public boolean hasCapability(int);
     method public boolean hasTransport(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.NetworkRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.NetworkRequest> CREATOR;
   }
 
   public static class NetworkRequest.Builder {
@@ -29082,7 +29086,7 @@
     method public android.net.Uri getPacFileUrl();
     method public int getPort();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.ProxyInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.ProxyInfo> CREATOR;
   }
 
   public final class RouteInfo implements android.os.Parcelable {
@@ -29094,7 +29098,7 @@
     method public boolean isDefaultRoute();
     method public boolean matches(java.net.InetAddress);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.RouteInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.RouteInfo> CREATOR;
   }
 
   @Deprecated public class SSLCertificateSocketFactory extends javax.net.ssl.SSLSocketFactory {
@@ -29227,7 +29231,7 @@
     method public abstract String toString();
     method public static android.net.Uri withAppendedPath(android.net.Uri, String);
     method public static void writeToParcel(android.os.Parcel, android.net.Uri);
-    field public static final android.os.Parcelable.Creator<android.net.Uri> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.Uri> CREATOR;
     field public static final android.net.Uri EMPTY;
   }
 
@@ -29355,7 +29359,7 @@
     method public android.os.ParcelFileDescriptor establish();
     method public android.net.VpnService.Builder setBlocking(boolean);
     method public android.net.VpnService.Builder setConfigureIntent(android.app.PendingIntent);
-    method public android.net.VpnService.Builder setHttpProxy(android.net.ProxyInfo);
+    method public android.net.VpnService.Builder setHttpProxy(@NonNull android.net.ProxyInfo);
     method public android.net.VpnService.Builder setMetered(boolean);
     method public android.net.VpnService.Builder setMtu(int);
     method public android.net.VpnService.Builder setSession(String);
@@ -29486,7 +29490,7 @@
     method public void setServiceName(String);
     method public void setServiceType(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.nsd.NsdServiceInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.nsd.NsdServiceInfo> CREATOR;
   }
 
 }
@@ -29906,7 +29910,7 @@
     method public void setRealm(String);
     method @Deprecated public void setSubjectMatch(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.WifiEnterpriseConfig> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.WifiEnterpriseConfig> CREATOR;
   }
 
   public static final class WifiEnterpriseConfig.Eap {
@@ -29943,13 +29947,14 @@
     method public String getMacAddress();
     method public int getNetworkId();
     method public int getRssi();
-    method public int getRxLinkSpeedMbps();
+    method @IntRange(from=0xffffffff) public int getRxLinkSpeedMbps();
     method public String getSSID();
     method public android.net.wifi.SupplicantState getSupplicantState();
-    method public int getTxLinkSpeedMbps();
+    method @IntRange(from=0xffffffff) public int getTxLinkSpeedMbps();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final String FREQUENCY_UNITS = "MHz";
     field public static final String LINK_SPEED_UNITS = "Mbps";
+    field public static final int LINK_SPEED_UNKNOWN = -1; // 0xffffffff
   }
 
   public class WifiManager {
@@ -30083,45 +30088,45 @@
   public final class WifiNetworkSpecifier extends android.net.NetworkSpecifier implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.WifiNetworkSpecifier> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.WifiNetworkSpecifier> CREATOR;
   }
 
-  public static class WifiNetworkSpecifier.Builder {
+  public static final class WifiNetworkSpecifier.Builder {
     ctor public WifiNetworkSpecifier.Builder();
-    method public android.net.NetworkSpecifier build();
-    method public android.net.wifi.WifiNetworkSpecifier.Builder setBssid(@NonNull android.net.MacAddress);
-    method public android.net.wifi.WifiNetworkSpecifier.Builder setBssidPattern(@NonNull android.net.MacAddress, @NonNull android.net.MacAddress);
-    method public android.net.wifi.WifiNetworkSpecifier.Builder setIsEnhancedOpen();
-    method public android.net.wifi.WifiNetworkSpecifier.Builder setIsHiddenSsid();
-    method public android.net.wifi.WifiNetworkSpecifier.Builder setSsid(@NonNull String);
-    method public android.net.wifi.WifiNetworkSpecifier.Builder setSsidPattern(@NonNull android.os.PatternMatcher);
-    method public android.net.wifi.WifiNetworkSpecifier.Builder setWpa2EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
-    method public android.net.wifi.WifiNetworkSpecifier.Builder setWpa2Passphrase(@NonNull String);
-    method public android.net.wifi.WifiNetworkSpecifier.Builder setWpa3EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
-    method public android.net.wifi.WifiNetworkSpecifier.Builder setWpa3Passphrase(@NonNull String);
+    method @NonNull public android.net.NetworkSpecifier build();
+    method @NonNull public android.net.wifi.WifiNetworkSpecifier.Builder setBssid(@NonNull android.net.MacAddress);
+    method @NonNull public android.net.wifi.WifiNetworkSpecifier.Builder setBssidPattern(@NonNull android.net.MacAddress, @NonNull android.net.MacAddress);
+    method @NonNull public android.net.wifi.WifiNetworkSpecifier.Builder setIsEnhancedOpen();
+    method @NonNull public android.net.wifi.WifiNetworkSpecifier.Builder setIsHiddenSsid();
+    method @NonNull public android.net.wifi.WifiNetworkSpecifier.Builder setSsid(@NonNull String);
+    method @NonNull public android.net.wifi.WifiNetworkSpecifier.Builder setSsidPattern(@NonNull android.os.PatternMatcher);
+    method @NonNull public android.net.wifi.WifiNetworkSpecifier.Builder setWpa2EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
+    method @NonNull public android.net.wifi.WifiNetworkSpecifier.Builder setWpa2Passphrase(@NonNull String);
+    method @NonNull public android.net.wifi.WifiNetworkSpecifier.Builder setWpa3EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
+    method @NonNull public android.net.wifi.WifiNetworkSpecifier.Builder setWpa3Passphrase(@NonNull String);
   }
 
   public final class WifiNetworkSuggestion implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.WifiNetworkSuggestion> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.WifiNetworkSuggestion> CREATOR;
   }
 
-  public static class WifiNetworkSuggestion.Builder {
+  public static final class WifiNetworkSuggestion.Builder {
     ctor public WifiNetworkSuggestion.Builder();
-    method public android.net.wifi.WifiNetworkSuggestion build();
-    method public android.net.wifi.WifiNetworkSuggestion.Builder setBssid(@NonNull android.net.MacAddress);
-    method public android.net.wifi.WifiNetworkSuggestion.Builder setIsAppInteractionRequired();
-    method public android.net.wifi.WifiNetworkSuggestion.Builder setIsEnhancedOpen();
-    method public android.net.wifi.WifiNetworkSuggestion.Builder setIsHiddenSsid();
-    method public android.net.wifi.WifiNetworkSuggestion.Builder setIsMetered();
-    method public android.net.wifi.WifiNetworkSuggestion.Builder setIsUserInteractionRequired();
-    method public android.net.wifi.WifiNetworkSuggestion.Builder setPriority(int);
-    method public android.net.wifi.WifiNetworkSuggestion.Builder setSsid(@NonNull String);
-    method public android.net.wifi.WifiNetworkSuggestion.Builder setWpa2EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
-    method public android.net.wifi.WifiNetworkSuggestion.Builder setWpa2Passphrase(@NonNull String);
-    method public android.net.wifi.WifiNetworkSuggestion.Builder setWpa3EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
-    method public android.net.wifi.WifiNetworkSuggestion.Builder setWpa3Passphrase(@NonNull String);
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion build();
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setBssid(@NonNull android.net.MacAddress);
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setIsAppInteractionRequired();
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setIsEnhancedOpen();
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setIsHiddenSsid();
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setIsMetered();
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setIsUserInteractionRequired();
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setPriority(int);
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setSsid(@NonNull String);
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setWpa2EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setWpa2Passphrase(@NonNull String);
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setWpa3EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
+    method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setWpa3Passphrase(@NonNull String);
   }
 
   public class WpsInfo implements android.os.Parcelable {
@@ -30130,7 +30135,7 @@
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
     field public String BSSID;
-    field public static final android.os.Parcelable.Creator<android.net.wifi.WpsInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.WpsInfo> CREATOR;
     field public static final int DISPLAY = 1; // 0x1
     field public static final int INVALID = 4; // 0x4
     field public static final int KEYPAD = 2; // 0x2
@@ -30156,7 +30161,7 @@
     method public int getMaxServiceNameLength();
     method public int getMaxServiceSpecificInfoLength();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.aware.Characteristics> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.aware.Characteristics> CREATOR;
   }
 
   public class DiscoverySession implements java.lang.AutoCloseable {
@@ -30189,7 +30194,7 @@
     ctor public ParcelablePeerHandle(android.net.wifi.aware.PeerHandle);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.aware.ParcelablePeerHandle> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.aware.ParcelablePeerHandle> CREATOR;
   }
 
   public class PeerHandle {
@@ -30198,7 +30203,7 @@
   public final class PublishConfig implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.aware.PublishConfig> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.aware.PublishConfig> CREATOR;
     field public static final int PUBLISH_TYPE_SOLICITED = 1; // 0x1
     field public static final int PUBLISH_TYPE_UNSOLICITED = 0; // 0x0
   }
@@ -30222,7 +30227,7 @@
   public final class SubscribeConfig implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.aware.SubscribeConfig> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.aware.SubscribeConfig> CREATOR;
     field public static final int SUBSCRIBE_TYPE_ACTIVE = 1; // 0x1
     field public static final int SUBSCRIBE_TYPE_PASSIVE = 0; // 0x0
   }
@@ -30270,7 +30275,7 @@
     method public int getPort();
     method public int getTransportProtocol();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.aware.WifiAwareNetworkInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.aware.WifiAwareNetworkInfo> CREATOR;
   }
 
   public class WifiAwareSession implements java.lang.AutoCloseable {
@@ -30298,7 +30303,7 @@
     method public void setCredential(android.net.wifi.hotspot2.pps.Credential);
     method public void setHomeSp(android.net.wifi.hotspot2.pps.HomeSp);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.PasspointConfiguration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.PasspointConfiguration> CREATOR;
   }
 
 }
@@ -30332,7 +30337,7 @@
     method public void setSimCredential(android.net.wifi.hotspot2.pps.Credential.SimCredential);
     method public void setUserCredential(android.net.wifi.hotspot2.pps.Credential.UserCredential);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.pps.Credential> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.pps.Credential> CREATOR;
   }
 
   public static final class Credential.CertificateCredential implements android.os.Parcelable {
@@ -30344,7 +30349,7 @@
     method public void setCertSha256Fingerprint(byte[]);
     method public void setCertType(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.pps.Credential.CertificateCredential> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.pps.Credential.CertificateCredential> CREATOR;
   }
 
   public static final class Credential.SimCredential implements android.os.Parcelable {
@@ -30356,7 +30361,7 @@
     method public void setEapType(int);
     method public void setImsi(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.pps.Credential.SimCredential> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.pps.Credential.SimCredential> CREATOR;
   }
 
   public static final class Credential.UserCredential implements android.os.Parcelable {
@@ -30372,7 +30377,7 @@
     method public void setPassword(String);
     method public void setUsername(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.pps.Credential.UserCredential> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.pps.Credential.UserCredential> CREATOR;
   }
 
   public final class HomeSp implements android.os.Parcelable {
@@ -30386,7 +30391,7 @@
     method public void setFriendlyName(String);
     method public void setRoamingConsortiumOis(long[]);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.pps.HomeSp> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.pps.HomeSp> CREATOR;
   }
 
 }
@@ -30398,7 +30403,7 @@
     ctor public WifiP2pConfig(android.net.wifi.p2p.WifiP2pConfig);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.p2p.WifiP2pConfig> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.p2p.WifiP2pConfig> CREATOR;
     field public static final int GROUP_OWNER_BAND_2GHZ = 1; // 0x1
     field public static final int GROUP_OWNER_BAND_5GHZ = 2; // 0x2
     field public static final int GROUP_OWNER_BAND_AUTO = 0; // 0x0
@@ -30430,7 +30435,7 @@
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int AVAILABLE = 3; // 0x3
     field public static final int CONNECTED = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.net.wifi.p2p.WifiP2pDevice> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.p2p.WifiP2pDevice> CREATOR;
     field public static final int FAILED = 2; // 0x2
     field public static final int INVITED = 1; // 0x1
     field public static final int UNAVAILABLE = 4; // 0x4
@@ -30448,7 +30453,7 @@
     method public android.net.wifi.p2p.WifiP2pDevice get(String);
     method public java.util.Collection<android.net.wifi.p2p.WifiP2pDevice> getDeviceList();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.p2p.WifiP2pDeviceList> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.p2p.WifiP2pDeviceList> CREATOR;
   }
 
   public class WifiP2pGroup implements android.os.Parcelable {
@@ -30463,7 +30468,7 @@
     method public String getPassphrase();
     method public boolean isGroupOwner();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.p2p.WifiP2pGroup> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.p2p.WifiP2pGroup> CREATOR;
   }
 
   public class WifiP2pInfo implements android.os.Parcelable {
@@ -30471,7 +30476,7 @@
     ctor public WifiP2pInfo(android.net.wifi.p2p.WifiP2pInfo);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.p2p.WifiP2pInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.p2p.WifiP2pInfo> CREATOR;
     field public boolean groupFormed;
     field public java.net.InetAddress groupOwnerAddress;
     field public boolean isGroupOwner;
@@ -30629,7 +30634,7 @@
     method public int describeContents();
     method public static int getMaxPeers();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.rtt.RangingRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.rtt.RangingRequest> CREATOR;
   }
 
   public static final class RangingRequest.Builder {
@@ -30654,7 +30659,7 @@
     method public int getRssi();
     method public int getStatus();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.rtt.RangingResult> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.rtt.RangingResult> CREATOR;
     field public static final int STATUS_FAIL = 1; // 0x1
     field public static final int STATUS_RESPONDER_DOES_NOT_SUPPORT_IEEE80211MC = 2; // 0x2
     field public static final int STATUS_SUCCESS = 0; // 0x0
@@ -30692,7 +30697,7 @@
     field public static final int ALTITUDE_FLOORS = 2; // 0x2
     field public static final int ALTITUDE_METERS = 1; // 0x1
     field public static final int ALTITUDE_UNDEFINED = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.net.wifi.rtt.ResponderLocation> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.rtt.ResponderLocation> CREATOR;
     field public static final int DATUM_NAD83_MLLW = 3; // 0x3
     field public static final int DATUM_NAD83_NAV88 = 2; // 0x2
     field public static final int DATUM_UNDEFINED = 0; // 0x0
@@ -30751,7 +30756,7 @@
     method public android.nfc.NdefRecord[] getRecords();
     method public byte[] toByteArray();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.nfc.NdefMessage> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.nfc.NdefMessage> CREATOR;
   }
 
   public final class NdefRecord implements android.os.Parcelable {
@@ -30772,7 +30777,7 @@
     method public String toMimeType();
     method public android.net.Uri toUri();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.nfc.NdefRecord> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.nfc.NdefRecord> CREATOR;
     field public static final byte[] RTD_ALTERNATIVE_CARRIER;
     field public static final byte[] RTD_HANDOVER_CARRIER;
     field public static final byte[] RTD_HANDOVER_REQUEST;
@@ -30870,7 +30875,7 @@
     method public byte[] getId();
     method public String[] getTechList();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.nfc.Tag> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.nfc.Tag> CREATOR;
   }
 
   public class TagLostException extends java.io.IOException {
@@ -34382,7 +34387,7 @@
     method public void readFromParcel(android.os.Parcel);
     method public void setClassLoader(ClassLoader);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.Bundle> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.Bundle> CREATOR;
     field public static final android.os.Bundle EMPTY;
   }
 
@@ -34420,7 +34425,7 @@
     method public long getActive();
     method public long getTotal();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.CpuUsageInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.CpuUsageInfo> CREATOR;
   }
 
   public class DeadObjectException extends android.os.RemoteException {
@@ -34528,7 +34533,7 @@
     method public int getTotalSwappablePss();
     method public void readFromParcel(android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.Debug.MemoryInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.Debug.MemoryInfo> CREATOR;
     field public int dalvikPrivateDirty;
     field public int dalvikPss;
     field public int dalvikSharedDirty;
@@ -34569,7 +34574,7 @@
     method public String getText(int);
     method public long getTimeMillis();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.DropBoxManager.Entry> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.DropBoxManager.Entry> CREATOR;
   }
 
   public class Environment {
@@ -34580,7 +34585,7 @@
     method public static java.io.File getExternalStoragePublicDirectory(String);
     method public static String getExternalStorageState();
     method public static String getExternalStorageState(java.io.File);
-    method public static java.io.File getRootDirectory();
+    method @NonNull public static java.io.File getRootDirectory();
     method @Deprecated public static String getStorageState(java.io.File);
     method public static boolean isExternalStorageEmulated();
     method public static boolean isExternalStorageEmulated(java.io.File);
@@ -34766,7 +34771,7 @@
     method @IntRange(from=0) public int size();
     method @NonNull public String toLanguageTags();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.LocaleList> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.LocaleList> CREATOR;
   }
 
   public final class Looper {
@@ -34821,7 +34826,7 @@
     method public void setData(android.os.Bundle);
     method public void setTarget(android.os.Handler);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.Message> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.Message> CREATOR;
     field public int arg1;
     field public int arg2;
     field public Object obj;
@@ -34858,7 +34863,7 @@
     method public void send(android.os.Message) throws android.os.RemoteException;
     method public static void writeMessengerOrNullToParcel(android.os.Messenger, android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.Messenger> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.Messenger> CREATOR;
   }
 
   public class NetworkOnMainThreadException extends java.lang.RuntimeException {
@@ -35015,7 +35020,7 @@
     method public static android.os.ParcelFileDescriptor open(java.io.File, int, android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener) throws java.io.IOException;
     method public static int parseMode(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.ParcelFileDescriptor> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.ParcelFileDescriptor> CREATOR;
     field public static final int MODE_APPEND = 33554432; // 0x2000000
     field public static final int MODE_CREATE = 134217728; // 0x8000000
     field public static final int MODE_READ_ONLY = 268435456; // 0x10000000
@@ -35053,7 +35058,7 @@
     method public static android.os.ParcelUuid fromString(String);
     method public java.util.UUID getUuid();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.ParcelUuid> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.ParcelUuid> CREATOR;
   }
 
   public interface Parcelable {
@@ -35080,7 +35085,7 @@
     method public final int getType();
     method public boolean match(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.PatternMatcher> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.PatternMatcher> CREATOR;
     field public static final int PATTERN_ADVANCED_GLOB = 3; // 0x3
     field public static final int PATTERN_LITERAL = 0; // 0x0
     field public static final int PATTERN_PREFIX = 1; // 0x1
@@ -35097,7 +35102,7 @@
     method @Nullable public android.os.PersistableBundle getPersistableBundle(@Nullable String);
     method public void putPersistableBundle(@Nullable String, @Nullable android.os.PersistableBundle);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.PersistableBundle> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.PersistableBundle> CREATOR;
     field public static final android.os.PersistableBundle EMPTY;
   }
 
@@ -35246,7 +35251,7 @@
     method protected void onReceiveResult(int, android.os.Bundle);
     method public void send(int, android.os.Bundle);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.ResultReceiver> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.ResultReceiver> CREATOR;
   }
 
   public final class SharedMemory implements java.io.Closeable android.os.Parcelable {
@@ -35260,7 +35265,7 @@
     method public boolean setProtect(int);
     method public static void unmap(@NonNull java.nio.ByteBuffer);
     method public void writeToParcel(@NonNull android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.SharedMemory> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.SharedMemory> CREATOR;
   }
 
   public class StatFs {
@@ -35306,27 +35311,27 @@
     ctor public StrictMode.ThreadPolicy.Builder();
     ctor public StrictMode.ThreadPolicy.Builder(android.os.StrictMode.ThreadPolicy);
     method public android.os.StrictMode.ThreadPolicy build();
-    method public android.os.StrictMode.ThreadPolicy.Builder detectAll();
-    method public android.os.StrictMode.ThreadPolicy.Builder detectCustomSlowCalls();
-    method public android.os.StrictMode.ThreadPolicy.Builder detectDiskReads();
-    method public android.os.StrictMode.ThreadPolicy.Builder detectDiskWrites();
-    method public android.os.StrictMode.ThreadPolicy.Builder detectNetwork();
-    method public android.os.StrictMode.ThreadPolicy.Builder detectResourceMismatches();
-    method public android.os.StrictMode.ThreadPolicy.Builder detectUnbufferedIo();
-    method public android.os.StrictMode.ThreadPolicy.Builder penaltyDeath();
-    method public android.os.StrictMode.ThreadPolicy.Builder penaltyDeathOnNetwork();
-    method public android.os.StrictMode.ThreadPolicy.Builder penaltyDialog();
-    method public android.os.StrictMode.ThreadPolicy.Builder penaltyDropBox();
-    method public android.os.StrictMode.ThreadPolicy.Builder penaltyFlashScreen();
-    method public android.os.StrictMode.ThreadPolicy.Builder penaltyListener(@NonNull java.util.concurrent.Executor, @NonNull android.os.StrictMode.OnThreadViolationListener);
-    method public android.os.StrictMode.ThreadPolicy.Builder penaltyLog();
-    method public android.os.StrictMode.ThreadPolicy.Builder permitAll();
-    method public android.os.StrictMode.ThreadPolicy.Builder permitCustomSlowCalls();
-    method public android.os.StrictMode.ThreadPolicy.Builder permitDiskReads();
-    method public android.os.StrictMode.ThreadPolicy.Builder permitDiskWrites();
-    method public android.os.StrictMode.ThreadPolicy.Builder permitNetwork();
-    method public android.os.StrictMode.ThreadPolicy.Builder permitResourceMismatches();
-    method public android.os.StrictMode.ThreadPolicy.Builder permitUnbufferedIo();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder detectAll();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder detectCustomSlowCalls();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder detectDiskReads();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder detectDiskWrites();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder detectNetwork();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder detectResourceMismatches();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder detectUnbufferedIo();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder penaltyDeath();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder penaltyDeathOnNetwork();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder penaltyDialog();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder penaltyDropBox();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder penaltyFlashScreen();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder penaltyListener(@NonNull java.util.concurrent.Executor, @NonNull android.os.StrictMode.OnThreadViolationListener);
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder penaltyLog();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder permitAll();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder permitCustomSlowCalls();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder permitDiskReads();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder permitDiskWrites();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder permitNetwork();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder permitResourceMismatches();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder permitUnbufferedIo();
   }
 
   public static final class StrictMode.VmPolicy {
@@ -35337,26 +35342,26 @@
     ctor public StrictMode.VmPolicy.Builder();
     ctor public StrictMode.VmPolicy.Builder(android.os.StrictMode.VmPolicy);
     method public android.os.StrictMode.VmPolicy build();
-    method public android.os.StrictMode.VmPolicy.Builder detectActivityLeaks();
-    method public android.os.StrictMode.VmPolicy.Builder detectAll();
-    method public android.os.StrictMode.VmPolicy.Builder detectCleartextNetwork();
-    method public android.os.StrictMode.VmPolicy.Builder detectContentUriWithoutPermission();
-    method public android.os.StrictMode.VmPolicy.Builder detectCredentialProtectedWhileLocked();
-    method public android.os.StrictMode.VmPolicy.Builder detectFileUriExposure();
-    method public android.os.StrictMode.VmPolicy.Builder detectImplicitDirectBoot();
-    method public android.os.StrictMode.VmPolicy.Builder detectLeakedClosableObjects();
-    method public android.os.StrictMode.VmPolicy.Builder detectLeakedRegistrationObjects();
-    method public android.os.StrictMode.VmPolicy.Builder detectLeakedSqlLiteObjects();
-    method public android.os.StrictMode.VmPolicy.Builder detectNonSdkApiUsage();
-    method public android.os.StrictMode.VmPolicy.Builder detectUntaggedSockets();
-    method public android.os.StrictMode.VmPolicy.Builder penaltyDeath();
-    method public android.os.StrictMode.VmPolicy.Builder penaltyDeathOnCleartextNetwork();
-    method public android.os.StrictMode.VmPolicy.Builder penaltyDeathOnFileUriExposure();
-    method public android.os.StrictMode.VmPolicy.Builder penaltyDropBox();
-    method public android.os.StrictMode.VmPolicy.Builder penaltyListener(@NonNull java.util.concurrent.Executor, @NonNull android.os.StrictMode.OnVmViolationListener);
-    method public android.os.StrictMode.VmPolicy.Builder penaltyLog();
-    method public android.os.StrictMode.VmPolicy.Builder permitNonSdkApiUsage();
-    method public android.os.StrictMode.VmPolicy.Builder setClassInstanceLimit(Class, int);
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder detectActivityLeaks();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder detectAll();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder detectCleartextNetwork();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder detectContentUriWithoutPermission();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder detectCredentialProtectedWhileLocked();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder detectFileUriExposure();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder detectImplicitDirectBoot();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder detectLeakedClosableObjects();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder detectLeakedRegistrationObjects();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder detectLeakedSqlLiteObjects();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder detectNonSdkApiUsage();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder detectUntaggedSockets();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder penaltyDeath();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder penaltyDeathOnCleartextNetwork();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder penaltyDeathOnFileUriExposure();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder penaltyDropBox();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder penaltyListener(@NonNull java.util.concurrent.Executor, @NonNull android.os.StrictMode.OnVmViolationListener);
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder penaltyLog();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder permitNonSdkApiUsage();
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder setClassInstanceLimit(Class, int);
   }
 
   public final class SystemClock {
@@ -35411,7 +35416,7 @@
     method public static android.os.UserHandle readFromParcel(android.os.Parcel);
     method public void writeToParcel(android.os.Parcel, int);
     method public static void writeToParcel(android.os.UserHandle, android.os.Parcel);
-    field public static final android.os.Parcelable.Creator<android.os.UserHandle> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.UserHandle> CREATOR;
   }
 
   public class UserManager {
@@ -35512,11 +35517,11 @@
 
   public abstract class VibrationEffect implements android.os.Parcelable {
     method public static android.os.VibrationEffect createOneShot(long, int);
-    method public static android.os.VibrationEffect createPrebaked(int);
+    method public static android.os.VibrationEffect createPredefined(int);
     method public static android.os.VibrationEffect createWaveform(long[], int);
     method public static android.os.VibrationEffect createWaveform(long[], int[], int);
     method public int describeContents();
-    field public static final android.os.Parcelable.Creator<android.os.VibrationEffect> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.VibrationEffect> CREATOR;
     field public static final int DEFAULT_AMPLITUDE = -1; // 0xffffffff
     field public static final int EFFECT_CLICK = 0; // 0x0
     field public static final int EFFECT_DOUBLE_CLICK = 1; // 0x1
@@ -35546,7 +35551,7 @@
     method public boolean remove(android.os.WorkSource);
     method public void set(android.os.WorkSource);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.WorkSource> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.WorkSource> CREATOR;
   }
 
 }
@@ -35620,7 +35625,7 @@
     method public void setCount(int);
     method public void setTime(long);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.health.TimerStat> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.health.TimerStat> CREATOR;
   }
 
   public final class UidHealthStats {
@@ -35745,7 +35750,7 @@
     method public boolean isPrimary();
     method public boolean isRemovable();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.storage.StorageVolume> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.storage.StorageVolume> CREATOR;
     field public static final String EXTRA_STORAGE_VOLUME = "android.os.storage.extra.STORAGE_VOLUME";
   }
 
@@ -36003,7 +36008,7 @@
   @Deprecated public static class Preference.BaseSavedState extends android.view.AbsSavedState {
     ctor @Deprecated public Preference.BaseSavedState(android.os.Parcel);
     ctor @Deprecated public Preference.BaseSavedState(android.os.Parcelable);
-    field @Deprecated public static final android.os.Parcelable.Creator<android.preference.Preference.BaseSavedState> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.preference.Preference.BaseSavedState> CREATOR;
   }
 
   @Deprecated public static interface Preference.OnPreferenceChangeListener {
@@ -36063,7 +36068,7 @@
     method @Deprecated public CharSequence getTitle(android.content.res.Resources);
     method @Deprecated public void readFromParcel(android.os.Parcel);
     method @Deprecated public void writeToParcel(android.os.Parcel, int);
-    field @Deprecated public static final android.os.Parcelable.Creator<android.preference.PreferenceActivity.Header> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.preference.PreferenceActivity.Header> CREATOR;
     field @Deprecated public CharSequence breadCrumbShortTitle;
     field @Deprecated @StringRes public int breadCrumbShortTitleRes;
     field @Deprecated public CharSequence breadCrumbTitle;
@@ -36237,7 +36242,7 @@
     method @IntRange(from=0) public int getStart();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.print.PageRange ALL_PAGES;
-    field public static final android.os.Parcelable.Creator<android.print.PageRange> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.print.PageRange> CREATOR;
   }
 
   public final class PrintAttributes implements android.os.Parcelable {
@@ -36250,7 +36255,7 @@
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int COLOR_MODE_COLOR = 2; // 0x2
     field public static final int COLOR_MODE_MONOCHROME = 1; // 0x1
-    field public static final android.os.Parcelable.Creator<android.print.PrintAttributes> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.print.PrintAttributes> CREATOR;
     field public static final int DUPLEX_MODE_LONG_EDGE = 2; // 0x2
     field public static final int DUPLEX_MODE_NONE = 1; // 0x1
     field public static final int DUPLEX_MODE_SHORT_EDGE = 4; // 0x4
@@ -36408,7 +36413,7 @@
     field public static final int CONTENT_TYPE_DOCUMENT = 0; // 0x0
     field public static final int CONTENT_TYPE_PHOTO = 1; // 0x1
     field public static final int CONTENT_TYPE_UNKNOWN = -1; // 0xffffffff
-    field public static final android.os.Parcelable.Creator<android.print.PrintDocumentInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.print.PrintDocumentInfo> CREATOR;
     field public static final int PAGE_COUNT_UNKNOWN = -1; // 0xffffffff
   }
 
@@ -36435,7 +36440,7 @@
   public final class PrintJobId implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.print.PrintJobId> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.print.PrintJobId> CREATOR;
   }
 
   public final class PrintJobInfo implements android.os.Parcelable {
@@ -36452,7 +36457,7 @@
     method public int getState();
     method public boolean hasAdvancedOption(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.print.PrintJobInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.print.PrintJobInfo> CREATOR;
     field public static final int STATE_BLOCKED = 4; // 0x4
     field public static final int STATE_CANCELED = 7; // 0x7
     field public static final int STATE_COMPLETED = 5; // 0x5
@@ -36486,7 +36491,7 @@
     method @NonNull public android.print.PrintAttributes.Margins getMinMargins();
     method @NonNull public java.util.List<android.print.PrintAttributes.Resolution> getResolutions();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.print.PrinterCapabilitiesInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.print.PrinterCapabilitiesInfo> CREATOR;
   }
 
   public static final class PrinterCapabilitiesInfo.Builder {
@@ -36503,7 +36508,7 @@
     method public int describeContents();
     method @NonNull public String getLocalId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.print.PrinterId> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.print.PrinterId> CREATOR;
   }
 
   public final class PrinterInfo implements android.os.Parcelable {
@@ -36514,7 +36519,7 @@
     method @NonNull public String getName();
     method public int getStatus();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.print.PrinterInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.print.PrinterInfo> CREATOR;
     field public static final int STATUS_BUSY = 2; // 0x2
     field public static final int STATUS_IDLE = 1; // 0x1
     field public static final int STATUS_UNAVAILABLE = 3; // 0x3
@@ -38261,7 +38266,7 @@
     method public java.util.List<java.lang.String> getPath();
     method @Nullable public String getRootId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.provider.DocumentsContract.Path> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.provider.DocumentsContract.Path> CREATOR;
   }
 
   public static final class DocumentsContract.Root {
@@ -38402,14 +38407,12 @@
 
   public final class MediaStore {
     ctor public MediaStore();
-    method @NonNull public static android.net.Uri createPending(@NonNull android.content.Context, @NonNull android.provider.MediaStore.PendingParams);
-    method @NonNull public static java.util.Set<java.lang.String> getAllVolumeNames(android.content.Context);
-    method public static android.net.Uri getDocumentUri(android.content.Context, android.net.Uri);
+    method @NonNull public static java.util.Set<java.lang.String> getAllVolumeNames(@NonNull android.content.Context);
+    method @Nullable public static android.net.Uri getDocumentUri(@NonNull android.content.Context, @NonNull android.net.Uri);
     method public static android.net.Uri getMediaScannerUri();
-    method public static android.net.Uri getMediaUri(android.content.Context, android.net.Uri);
+    method @Nullable public static android.net.Uri getMediaUri(@NonNull android.content.Context, @NonNull android.net.Uri);
     method public static String getVersion(android.content.Context);
     method @NonNull public static String getVolumeName(@NonNull android.net.Uri);
-    method @NonNull public static android.provider.MediaStore.PendingSession openPending(@NonNull android.content.Context, @NonNull android.net.Uri);
     method @NonNull public static android.net.Uri setIncludePending(@NonNull android.net.Uri);
     method @NonNull public static android.net.Uri setRequireOriginal(@NonNull android.net.Uri);
     field public static final String ACTION_IMAGE_CAPTURE = "android.media.action.IMAGE_CAPTURE";
@@ -38598,10 +38601,10 @@
   }
 
   public static final class MediaStore.Downloads implements android.provider.MediaStore.DownloadColumns {
-    method public static android.net.Uri getContentUri(String);
+    method @NonNull public static android.net.Uri getContentUri(@NonNull String);
     field public static final String CONTENT_TYPE = "vnd.android.cursor.dir/download";
-    field public static final android.net.Uri EXTERNAL_CONTENT_URI;
-    field public static final android.net.Uri INTERNAL_CONTENT_URI;
+    field @NonNull public static final android.net.Uri EXTERNAL_CONTENT_URI;
+    field @NonNull public static final android.net.Uri INTERNAL_CONTENT_URI;
   }
 
   public static final class MediaStore.Files {
@@ -38682,6 +38685,7 @@
   public static interface MediaStore.MediaColumns extends android.provider.BaseColumns {
     field @Deprecated public static final String DATA = "_data";
     field public static final String DATE_ADDED = "date_added";
+    field public static final String DATE_EXPIRES = "date_expires";
     field public static final String DATE_MODIFIED = "date_modified";
     field public static final String DISPLAY_NAME = "_display_name";
     field public static final String DOCUMENT_ID = "document_id";
@@ -38698,23 +38702,6 @@
     field public static final String WIDTH = "width";
   }
 
-  public static class MediaStore.PendingParams {
-    ctor public MediaStore.PendingParams(@NonNull android.net.Uri, @NonNull String, @NonNull String);
-    method public void setDownloadUri(@Nullable android.net.Uri);
-    method public void setPrimaryDirectory(@Nullable String);
-    method public void setRefererUri(@Nullable android.net.Uri);
-    method public void setSecondaryDirectory(@Nullable String);
-  }
-
-  public static class MediaStore.PendingSession implements java.lang.AutoCloseable {
-    method public void abandon();
-    method public void close();
-    method public void notifyProgress(@IntRange(from=0, to=100) int);
-    method @NonNull public android.os.ParcelFileDescriptor open() throws java.io.FileNotFoundException;
-    method @NonNull public java.io.OutputStream openOutputStream() throws java.io.FileNotFoundException;
-    method @NonNull public android.net.Uri publish();
-  }
-
   public static final class MediaStore.Video {
     ctor public MediaStore.Video();
     method @Deprecated public static android.database.Cursor query(android.content.ContentResolver, android.net.Uri, String[]);
@@ -38898,6 +38885,7 @@
     field public static final String AIRPLANE_MODE_RADIOS = "airplane_mode_radios";
     field public static final String ALWAYS_FINISH_ACTIVITIES = "always_finish_activities";
     field public static final String ANIMATOR_DURATION_SCALE = "animator_duration_scale";
+    field public static final String APPLY_RAMPING_RINGER = "apply_ramping_ringer";
     field public static final String AUTO_TIME = "auto_time";
     field public static final String AUTO_TIME_ZONE = "auto_time_zone";
     field public static final String BLUETOOTH_ON = "bluetooth_on";
@@ -39252,7 +39240,7 @@
   }
 
   public static final class Telephony.CarrierId implements android.provider.BaseColumns {
-    method public static android.net.Uri getPreciseCarrierIdUriForSubscriptionId(int);
+    method @NonNull public static android.net.Uri getPreciseCarrierIdUriForSubscriptionId(int);
     method public static android.net.Uri getUriForSubscriptionId(int);
     field public static final String CARRIER_ID = "carrier_id";
     field public static final String CARRIER_NAME = "carrier_name";
@@ -41103,7 +41091,7 @@
   public final class BatchUpdates implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.BatchUpdates> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.BatchUpdates> CREATOR;
   }
 
   public static class BatchUpdates.Builder {
@@ -41116,7 +41104,7 @@
   public final class CharSequenceTransformation implements android.os.Parcelable android.service.autofill.Transformation {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.CharSequenceTransformation> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.CharSequenceTransformation> CREATOR;
   }
 
   public static class CharSequenceTransformation.Builder {
@@ -41128,7 +41116,7 @@
   public final class CustomDescription implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.CustomDescription> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.CustomDescription> CREATOR;
   }
 
   public static class CustomDescription.Builder {
@@ -41142,7 +41130,7 @@
   public final class Dataset implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.Dataset> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.Dataset> CREATOR;
   }
 
   public static final class Dataset.Builder {
@@ -41161,14 +41149,14 @@
     ctor public DateTransformation(@NonNull android.view.autofill.AutofillId, @NonNull android.icu.text.DateFormat);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.DateTransformation> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.DateTransformation> CREATOR;
   }
 
   public final class DateValueSanitizer implements android.os.Parcelable android.service.autofill.Sanitizer {
     ctor public DateValueSanitizer(@NonNull android.icu.text.DateFormat);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.DateValueSanitizer> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.DateValueSanitizer> CREATOR;
   }
 
   public final class FieldClassification {
@@ -41187,10 +41175,11 @@
 
   public final class FillContext implements android.os.Parcelable {
     method public int describeContents();
+    method @NonNull public android.view.autofill.AutofillId getFocusedId();
     method public int getRequestId();
-    method public android.app.assist.AssistStructure getStructure();
+    method @NonNull public android.app.assist.AssistStructure getStructure();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.FillContext> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.FillContext> CREATOR;
   }
 
   public final class FillEventHistory implements android.os.Parcelable {
@@ -41198,7 +41187,7 @@
     method @Deprecated @Nullable public android.os.Bundle getClientState();
     method @Nullable public java.util.List<android.service.autofill.FillEventHistory.Event> getEvents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.FillEventHistory> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.FillEventHistory> CREATOR;
   }
 
   public static final class FillEventHistory.Event {
@@ -41224,7 +41213,7 @@
     method public int getFlags();
     method public int getId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.FillRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.FillRequest> CREATOR;
     field public static final int FLAG_COMPATIBILITY_MODE_REQUEST = 2; // 0x2
     field public static final int FLAG_MANUAL_REQUEST = 1; // 0x1
   }
@@ -41232,7 +41221,7 @@
   public final class FillResponse implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.FillResponse> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.FillResponse> CREATOR;
     field public static final int FLAG_DISABLE_ACTIVITY_ONLY = 2; // 0x2
     field public static final int FLAG_TRACK_CONTEXT_COMMITED = 1; // 0x1
   }
@@ -41256,7 +41245,7 @@
   public final class ImageTransformation implements android.os.Parcelable android.service.autofill.Transformation {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.ImageTransformation> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.ImageTransformation> CREATOR;
   }
 
   public static class ImageTransformation.Builder {
@@ -41271,7 +41260,7 @@
     ctor public LuhnChecksumValidator(@NonNull android.view.autofill.AutofillId...);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.LuhnChecksumValidator> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.LuhnChecksumValidator> CREATOR;
   }
 
   public interface OnClickAction {
@@ -41281,7 +41270,7 @@
     ctor public RegexValidator(@NonNull android.view.autofill.AutofillId, @NonNull java.util.regex.Pattern);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.RegexValidator> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.RegexValidator> CREATOR;
   }
 
   public interface Sanitizer {
@@ -41296,7 +41285,7 @@
   public final class SaveInfo implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.SaveInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.SaveInfo> CREATOR;
     field public static final int FLAG_DELAY_SAVE = 4; // 0x4
     field public static final int FLAG_DONT_SAVE_ON_FINISH = 2; // 0x2
     field public static final int FLAG_SAVE_ON_ALL_VIEWS_INVISIBLE = 1; // 0x1
@@ -41330,14 +41319,14 @@
     method @Nullable public java.util.List<java.lang.String> getDatasetIds();
     method @NonNull public java.util.List<android.service.autofill.FillContext> getFillContexts();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.SaveRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.SaveRequest> CREATOR;
   }
 
   public final class TextValueSanitizer implements android.os.Parcelable android.service.autofill.Sanitizer {
     ctor public TextValueSanitizer(@NonNull java.util.regex.Pattern, @NonNull String);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.TextValueSanitizer> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.TextValueSanitizer> CREATOR;
   }
 
   public interface Transformation {
@@ -41354,7 +41343,7 @@
     method public static int getMaxValueLength();
     method public static int getMinValueLength();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.UserData> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.UserData> CREATOR;
   }
 
   public static final class UserData.Builder {
@@ -41377,13 +41366,13 @@
   public final class VisibilitySetterAction implements android.service.autofill.OnClickAction android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.VisibilitySetterAction> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.VisibilitySetterAction> CREATOR;
   }
 
-  public static class VisibilitySetterAction.Builder {
+  public static final class VisibilitySetterAction.Builder {
     ctor public VisibilitySetterAction.Builder(@IdRes int, int);
-    method public android.service.autofill.VisibilitySetterAction build();
-    method public android.service.autofill.VisibilitySetterAction.Builder setVisibility(@IdRes int, int);
+    method @NonNull public android.service.autofill.VisibilitySetterAction build();
+    method @NonNull public android.service.autofill.VisibilitySetterAction.Builder setVisibility(@IdRes int, int);
   }
 
 }
@@ -41404,12 +41393,12 @@
     method public int getPreciseCarrierId();
     method @Nullable public String getSpn();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.carrier.CarrierIdentifier> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.carrier.CarrierIdentifier> CREATOR;
   }
 
   public class CarrierMessagingClientService extends android.app.Service {
     ctor public CarrierMessagingClientService();
-    method public final android.os.IBinder onBind(android.content.Intent);
+    method @NonNull public final android.os.IBinder onBind(@Nullable android.content.Intent);
   }
 
   public abstract class CarrierMessagingService extends android.app.Service {
@@ -41473,7 +41462,7 @@
     method public int describeContents();
     method @NonNull public java.util.List<byte[]> getPdus();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.carrier.MessagePdu> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.carrier.MessagePdu> CREATOR;
   }
 
 }
@@ -41489,7 +41478,7 @@
     method public float getScore();
     method public CharSequence getTitle();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.chooser.ChooserTarget> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.chooser.ChooserTarget> CREATOR;
   }
 
   public abstract class ChooserTargetService extends android.app.Service {
@@ -41609,7 +41598,7 @@
     method public android.os.Bundle getSignals();
     method public android.os.UserHandle getUserHandle();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.notification.Adjustment> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.notification.Adjustment> CREATOR;
     field public static final String KEY_CONTEXTUAL_ACTIONS = "key_contextual_actions";
     field public static final String KEY_IMPORTANCE = "key_importance";
     field public static final String KEY_SNOOZE_CRITERIA = "key_snooze_criteria";
@@ -41628,7 +41617,7 @@
     method public static String relevanceToString(int);
     method public static String stateToString(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.notification.Condition> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.notification.Condition> CREATOR;
     field public static final int FLAG_RELEVANT_ALWAYS = 2; // 0x2
     field public static final int FLAG_RELEVANT_NOW = 1; // 0x1
     field public static final String SCHEME = "condition";
@@ -41782,7 +41771,7 @@
     method public String[] getOrderedKeys();
     method public boolean getRanking(String, android.service.notification.NotificationListenerService.Ranking);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.notification.NotificationListenerService.RankingMap> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.notification.NotificationListenerService.RankingMap> CREATOR;
   }
 
   public final class NotificationStats implements android.os.Parcelable {
@@ -41804,7 +41793,7 @@
     method public void setSnoozed();
     method public void setViewedSettings();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.notification.NotificationStats> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.notification.NotificationStats> CREATOR;
     field public static final int DISMISSAL_AOD = 2; // 0x2
     field public static final int DISMISSAL_NOT_DISMISSED = -1; // 0xffffffff
     field public static final int DISMISSAL_OTHER = 0; // 0x0
@@ -41838,7 +41827,7 @@
     method public boolean isOngoing();
     method public void setOverrideGroupKey(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.notification.StatusBarNotification> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.notification.StatusBarNotification> CREATOR;
   }
 
   public final class ZenPolicy implements android.os.Parcelable {
@@ -41861,7 +41850,7 @@
     method public int getVisualEffectPeek();
     method public int getVisualEffectStatusBar();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.notification.ZenPolicy> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.notification.ZenPolicy> CREATOR;
     field public static final int PEOPLE_TYPE_ANYONE = 1; // 0x1
     field public static final int PEOPLE_TYPE_CONTACTS = 2; // 0x2
     field public static final int PEOPLE_TYPE_NONE = 4; // 0x4
@@ -41914,7 +41903,7 @@
     method public void setSubtitle(@Nullable CharSequence);
     method public void updateTile();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.quicksettings.Tile> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.quicksettings.Tile> CREATOR;
     field public static final int STATE_ACTIVE = 2; // 0x2
     field public static final int STATE_INACTIVE = 1; // 0x1
     field public static final int STATE_UNAVAILABLE = 0; // 0x0
@@ -42476,7 +42465,7 @@
     method public int getQuality();
     method public boolean isNetworkConnectionRequired();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.speech.tts.Voice> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.speech.tts.Voice> CREATOR;
     field public static final int LATENCY_HIGH = 400; // 0x190
     field public static final int LATENCY_LOW = 200; // 0xc8
     field public static final int LATENCY_NORMAL = 300; // 0x12c
@@ -42513,6 +42502,7 @@
     method public static void chown(String, int, int) throws android.system.ErrnoException;
     method public static void close(java.io.FileDescriptor) throws android.system.ErrnoException;
     method public static void connect(java.io.FileDescriptor, java.net.InetAddress, int) throws android.system.ErrnoException, java.net.SocketException;
+    method public static void connect(java.io.FileDescriptor, java.net.SocketAddress) throws android.system.ErrnoException, java.net.SocketException;
     method public static java.io.FileDescriptor dup(java.io.FileDescriptor) throws android.system.ErrnoException;
     method public static java.io.FileDescriptor dup2(java.io.FileDescriptor, int) throws android.system.ErrnoException;
     method public static String[] environ();
@@ -43332,7 +43322,7 @@
     method public int getSupportedRouteMask();
     method public boolean isMuted();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telecom.CallAudioState> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.CallAudioState> CREATOR;
     field public static final int ROUTE_BLUETOOTH = 2; // 0x2
     field public static final int ROUTE_EARPIECE = 1; // 0x1
     field public static final int ROUTE_SPEAKER = 8; // 0x8
@@ -43355,7 +43345,7 @@
     field public static final int CONFIDENCE_NOT_NUISANCE = -2; // 0xfffffffe
     field public static final int CONFIDENCE_NUISANCE = 2; // 0x2
     field public static final int CONFIDENCE_UNKNOWN = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.telecom.CallIdentification> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.CallIdentification> CREATOR;
   }
 
   public static class CallIdentification.Builder {
@@ -43648,7 +43638,7 @@
     method public int getVideoState();
     method public boolean isRequestingRtt();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telecom.ConnectionRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.ConnectionRequest> CREATOR;
   }
 
   public abstract class ConnectionService extends android.app.Service {
@@ -43694,7 +43684,7 @@
     field public static final int CALL_PULLED = 12; // 0xc
     field public static final int CANCELED = 4; // 0x4
     field public static final int CONNECTION_MANAGER_NOT_SUPPORTED = 10; // 0xa
-    field public static final android.os.Parcelable.Creator<android.telecom.DisconnectCause> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.DisconnectCause> CREATOR;
     field public static final int ERROR = 1; // 0x1
     field public static final int LOCAL = 2; // 0x2
     field public static final int MISSED = 5; // 0x5
@@ -43713,7 +43703,7 @@
     method public android.net.Uri getOriginalAddress();
     method public boolean isEmpty();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telecom.GatewayInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.GatewayInfo> CREATOR;
   }
 
   public abstract class InCallService extends android.app.Service {
@@ -43791,7 +43781,7 @@
     field public static final int CAPABILITY_SUPPORTS_VIDEO_CALLING = 1024; // 0x400
     field public static final int CAPABILITY_VIDEO_CALLING = 8; // 0x8
     field public static final int CAPABILITY_VIDEO_CALLING_RELIES_ON_PRESENCE = 256; // 0x100
-    field public static final android.os.Parcelable.Creator<android.telecom.PhoneAccount> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.PhoneAccount> CREATOR;
     field public static final String EXTRA_CALL_SUBJECT_CHARACTER_ENCODING = "android.telecom.extra.CALL_SUBJECT_CHARACTER_ENCODING";
     field public static final String EXTRA_CALL_SUBJECT_MAX_LENGTH = "android.telecom.extra.CALL_SUBJECT_MAX_LENGTH";
     field public static final String EXTRA_LOG_SELF_MANAGED_CALLS = "android.telecom.extra.LOG_SELF_MANAGED_CALLS";
@@ -43827,7 +43817,7 @@
     method public String getId();
     method public android.os.UserHandle getUserHandle();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telecom.PhoneAccountHandle> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.PhoneAccountHandle> CREATOR;
   }
 
   public final class PhoneAccountSuggestion implements android.os.Parcelable {
@@ -43836,7 +43826,7 @@
     method public int getReason();
     method public boolean shouldAutoSelect();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telecom.PhoneAccountSuggestion> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.PhoneAccountSuggestion> CREATOR;
     field public static final int REASON_FREQUENT = 2; // 0x2
     field public static final int REASON_INTRA_CARRIER = 1; // 0x1
     field public static final int REASON_NONE = 0; // 0x0
@@ -43967,7 +43957,7 @@
     method public android.graphics.drawable.Icon getIcon();
     method public CharSequence getLabel();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telecom.StatusHints> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.StatusHints> CREATOR;
   }
 
   public class TelecomManager {
@@ -44063,7 +44053,7 @@
     method public static boolean isVideo(int);
     method public static String videoStateToString(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telecom.VideoProfile> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.VideoProfile> CREATOR;
     field public static final int QUALITY_DEFAULT = 4; // 0x4
     field public static final int QUALITY_HIGH = 1; // 0x1
     field public static final int QUALITY_LOW = 3; // 0x3
@@ -44084,7 +44074,7 @@
     method public int getWidth();
     method public boolean isZoomSupported();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telecom.VideoProfile.CameraCapabilities> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.VideoProfile.CameraCapabilities> CREATOR;
   }
 
 }
@@ -44201,7 +44191,7 @@
     method public int getPriority();
     method public int getSubId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.AvailableNetworkInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.AvailableNetworkInfo> CREATOR;
     field public static final int PRIORITY_HIGH = 1; // 0x1
     field public static final int PRIORITY_LOW = 3; // 0x3
     field public static final int PRIORITY_MED = 2; // 0x2
@@ -44390,7 +44380,7 @@
     method @Nullable public CharSequence getOperatorAlphaLong();
     method @Nullable public CharSequence getOperatorAlphaShort();
     method @CallSuper public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellIdentity> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellIdentity> CREATOR;
   }
 
   public final class CellIdentityCdma extends android.telephony.CellIdentity {
@@ -44400,7 +44390,7 @@
     method public int getNetworkId();
     method public int getSystemId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellIdentityCdma> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellIdentityCdma> CREATOR;
   }
 
   public final class CellIdentityGsm extends android.telephony.CellIdentity {
@@ -44415,7 +44405,7 @@
     method @Nullable public String getMobileNetworkOperator();
     method @Deprecated public int getPsc();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellIdentityGsm> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellIdentityGsm> CREATOR;
   }
 
   public final class CellIdentityLte extends android.telephony.CellIdentity {
@@ -44430,7 +44420,7 @@
     method public int getPci();
     method public int getTac();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellIdentityLte> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellIdentityLte> CREATOR;
   }
 
   public final class CellIdentityNr extends android.telephony.CellIdentity {
@@ -44441,7 +44431,7 @@
     method public int getPci();
     method public int getTac();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellIdentityNr> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellIdentityNr> CREATOR;
   }
 
   public final class CellIdentityTdscdma extends android.telephony.CellIdentity {
@@ -44453,7 +44443,7 @@
     method @Nullable public String getMobileNetworkOperator();
     method public int getUarfcn();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellIdentityTdscdma> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellIdentityTdscdma> CREATOR;
   }
 
   public final class CellIdentityWcdma extends android.telephony.CellIdentity {
@@ -44467,7 +44457,7 @@
     method public int getPsc();
     method public int getUarfcn();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellIdentityWcdma> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellIdentityWcdma> CREATOR;
   }
 
   public abstract class CellInfo implements android.os.Parcelable {
@@ -44479,43 +44469,44 @@
     field public static final int CONNECTION_PRIMARY_SERVING = 1; // 0x1
     field public static final int CONNECTION_SECONDARY_SERVING = 2; // 0x2
     field public static final int CONNECTION_UNKNOWN = 2147483647; // 0x7fffffff
-    field public static final android.os.Parcelable.Creator<android.telephony.CellInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellInfo> CREATOR;
     field public static final int UNAVAILABLE = 2147483647; // 0x7fffffff
+    field public static final long UNAVAILABLE_LONG = 9223372036854775807L; // 0x7fffffffffffffffL
   }
 
   public final class CellInfoCdma extends android.telephony.CellInfo implements android.os.Parcelable {
     method public android.telephony.CellIdentityCdma getCellIdentity();
     method public android.telephony.CellSignalStrengthCdma getCellSignalStrength();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellInfoCdma> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellInfoCdma> CREATOR;
   }
 
   public final class CellInfoGsm extends android.telephony.CellInfo implements android.os.Parcelable {
     method public android.telephony.CellIdentityGsm getCellIdentity();
     method public android.telephony.CellSignalStrengthGsm getCellSignalStrength();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellInfoGsm> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellInfoGsm> CREATOR;
   }
 
   public final class CellInfoLte extends android.telephony.CellInfo implements android.os.Parcelable {
     method public android.telephony.CellIdentityLte getCellIdentity();
     method public android.telephony.CellSignalStrengthLte getCellSignalStrength();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellInfoLte> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellInfoLte> CREATOR;
   }
 
   public final class CellInfoNr extends android.telephony.CellInfo {
     method public android.telephony.CellIdentity getCellIdentity();
     method public android.telephony.CellSignalStrength getCellSignalStrength();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellInfoNr> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellInfoNr> CREATOR;
   }
 
   public final class CellInfoWcdma extends android.telephony.CellInfo implements android.os.Parcelable {
     method public android.telephony.CellIdentityWcdma getCellIdentity();
     method public android.telephony.CellSignalStrengthWcdma getCellSignalStrength();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellInfoWcdma> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellInfoWcdma> CREATOR;
   }
 
   public abstract class CellLocation {
@@ -44550,7 +44541,7 @@
     method public int getEvdoSnr();
     method public int getLevel();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellSignalStrengthCdma> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellSignalStrengthCdma> CREATOR;
   }
 
   public final class CellSignalStrengthGsm extends android.telephony.CellSignalStrength implements android.os.Parcelable {
@@ -44561,7 +44552,7 @@
     method public int getLevel();
     method public int getTimingAdvance();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellSignalStrengthGsm> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellSignalStrengthGsm> CREATOR;
   }
 
   public final class CellSignalStrengthLte extends android.telephony.CellSignalStrength implements android.os.Parcelable {
@@ -44576,7 +44567,7 @@
     method public int getRssnr();
     method public int getTimingAdvance();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellSignalStrengthLte> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellSignalStrengthLte> CREATOR;
   }
 
   public final class CellSignalStrengthNr extends android.telephony.CellSignalStrength implements android.os.Parcelable {
@@ -44591,7 +44582,7 @@
     method public int getSsRsrq();
     method public int getSsSinr();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellSignalStrengthNr> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellSignalStrengthNr> CREATOR;
   }
 
   public final class CellSignalStrengthWcdma extends android.telephony.CellSignalStrength implements android.os.Parcelable {
@@ -44600,7 +44591,7 @@
     method public int getDbm();
     method public int getLevel();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CellSignalStrengthWcdma> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellSignalStrengthWcdma> CREATOR;
   }
 
   public class IccOpenLogicalChannelResponse implements android.os.Parcelable {
@@ -44609,7 +44600,7 @@
     method public byte[] getSelectResponse();
     method public int getStatus();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.IccOpenLogicalChannelResponse> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.IccOpenLogicalChannelResponse> CREATOR;
     field public static final int INVALID_CHANNEL = -1; // 0xffffffff
     field public static final int STATUS_MISSING_RESOURCE = 2; // 0x2
     field public static final int STATUS_NO_ERROR = 1; // 0x1
@@ -44682,7 +44673,7 @@
     method @Deprecated public void setCid(int);
     method @Deprecated public void setRssi(int);
     method @Deprecated public void writeToParcel(android.os.Parcel, int);
-    field @Deprecated public static final android.os.Parcelable.Creator<android.telephony.NeighboringCellInfo> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.telephony.NeighboringCellInfo> CREATOR;
     field @Deprecated public static final int UNKNOWN_CID = -1; // 0xffffffff
     field @Deprecated public static final int UNKNOWN_RSSI = 99; // 0x63
   }
@@ -44710,7 +44701,7 @@
     method public int getSearchPeriodicity();
     method public android.telephony.RadioAccessSpecifier[] getSpecifiers();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.NetworkScanRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.NetworkScanRequest> CREATOR;
     field public static final int SCAN_TYPE_ONE_SHOT = 0; // 0x0
     field public static final int SCAN_TYPE_PERIODIC = 1; // 0x1
   }
@@ -44818,7 +44809,7 @@
     method public int[] getChannels();
     method public int getRadioAccessNetwork();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.RadioAccessSpecifier> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.RadioAccessSpecifier> CREATOR;
   }
 
   public class ServiceState implements android.os.Parcelable {
@@ -44845,7 +44836,7 @@
     method public void setStateOff();
     method public void setStateOutOfService();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ServiceState> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ServiceState> CREATOR;
     field public static final int DUPLEX_MODE_FDD = 1; // 0x1
     field public static final int DUPLEX_MODE_TDD = 2; // 0x2
     field public static final int DUPLEX_MODE_UNKNOWN = 0; // 0x0
@@ -44861,6 +44852,7 @@
     method @Deprecated public int getCdmaDbm();
     method @Deprecated public int getCdmaEcio();
     method @NonNull public java.util.List<android.telephony.CellSignalStrength> getCellSignalStrengths();
+    method public <T extends android.telephony.CellSignalStrength> java.util.List<T> getCellSignalStrengths(@NonNull Class<T>);
     method @Deprecated public int getEvdoDbm();
     method @Deprecated public int getEvdoEcio();
     method @Deprecated public int getEvdoSnr();
@@ -45017,7 +45009,7 @@
     method public String getCountryIso();
     method public int getDataRoaming();
     method public CharSequence getDisplayName();
-    method public String getGroupUuid();
+    method @Nullable public String getGroupUuid();
     method public String getIccId();
     method public int getIconTint();
     method @Deprecated public int getMcc();
@@ -45031,7 +45023,7 @@
     method public boolean isEmbedded();
     method public boolean isOpportunistic();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.SubscriptionInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.SubscriptionInfo> CREATOR;
   }
 
   public class SubscriptionManager {
@@ -45058,7 +45050,7 @@
     method public boolean isNetworkRoaming(int);
     method public static boolean isUsableSubscriptionId(int);
     method public static boolean isValidSubscriptionId(int);
-    method public void removeOnOpportunisticSubscriptionsChangedListener(android.telephony.SubscriptionManager.OnOpportunisticSubscriptionsChangedListener);
+    method public void removeOnOpportunisticSubscriptionsChangedListener(@NonNull android.telephony.SubscriptionManager.OnOpportunisticSubscriptionsChangedListener);
     method public void removeOnSubscriptionsChangedListener(android.telephony.SubscriptionManager.OnSubscriptionsChangedListener);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean removeSubscriptionsFromGroup(@NonNull int[]);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setMetered(boolean, int);
@@ -45067,7 +45059,7 @@
     method public void setSubscriptionOverrideCongested(int, boolean, long);
     method public void setSubscriptionOverrideUnmetered(int, boolean, long);
     method public void setSubscriptionPlans(int, @NonNull java.util.List<android.telephony.SubscriptionPlan>);
-    method @RequiresPermission("android.permission.WRITE_EMBEDDED_SUBSCRIPTIONS") public void switchToSubscription(int, android.app.PendingIntent);
+    method @RequiresPermission("android.permission.WRITE_EMBEDDED_SUBSCRIPTIONS") public void switchToSubscription(int, @NonNull android.app.PendingIntent);
     field public static final String ACTION_DEFAULT_SMS_SUBSCRIPTION_CHANGED = "android.telephony.action.DEFAULT_SMS_SUBSCRIPTION_CHANGED";
     field public static final String ACTION_DEFAULT_SUBSCRIPTION_CHANGED = "android.telephony.action.DEFAULT_SUBSCRIPTION_CHANGED";
     field public static final String ACTION_MANAGE_SUBSCRIPTION_PLANS = "android.telephony.action.MANAGE_SUBSCRIPTION_PLANS";
@@ -45104,7 +45096,7 @@
     method public void writeToParcel(android.os.Parcel, int);
     field public static final long BYTES_UNKNOWN = -1L; // 0xffffffffffffffffL
     field public static final long BYTES_UNLIMITED = 9223372036854775807L; // 0x7fffffffffffffffL
-    field public static final android.os.Parcelable.Creator<android.telephony.SubscriptionPlan> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.SubscriptionPlan> CREATOR;
     field public static final int LIMIT_BEHAVIOR_BILLED = 1; // 0x1
     field public static final int LIMIT_BEHAVIOR_DISABLED = 0; // 0x0
     field public static final int LIMIT_BEHAVIOR_THROTTLED = 2; // 0x2
@@ -45176,7 +45168,7 @@
     method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public String getSubscriberId();
     method public String getTypeAllocationCode();
     method public String getTypeAllocationCode(int);
-    method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public java.util.List<android.telephony.UiccCardInfo> getUiccCardsInfo();
+    method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") @NonNull public java.util.List<android.telephony.UiccCardInfo> getUiccCardsInfo();
     method @Nullable @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getVisualVoicemailPackageName();
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getVoiceMailAlphaTag();
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getVoiceMailNumber();
@@ -45347,15 +45339,15 @@
   }
 
   public final class UiccCardInfo implements android.os.Parcelable {
-    ctor public UiccCardInfo(boolean, int, String, String, int);
     method public int describeContents();
     method public int getCardId();
-    method public String getEid();
-    method public String getIccId();
+    method @Nullable public String getEid();
+    method @Nullable public String getIccId();
     method public int getSlotIndex();
     method public boolean isEuicc();
+    method public boolean isRemovable();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.UiccCardInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.UiccCardInfo> CREATOR;
   }
 
   public abstract class VisualVoicemailService extends android.app.Service {
@@ -45379,13 +45371,13 @@
     method public android.telecom.PhoneAccountHandle getPhoneAccountHandle();
     method public String getPrefix();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.VisualVoicemailSms> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.VisualVoicemailSms> CREATOR;
   }
 
   public final class VisualVoicemailSmsFilterSettings implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.VisualVoicemailSmsFilterSettings> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.VisualVoicemailSmsFilterSettings> CREATOR;
     field public static final int DESTINATION_PORT_ANY = -1; // 0xffffffff
     field public static final int DESTINATION_PORT_DATA_SMS = -2; // 0xfffffffe
     field public final String clientPrefix;
@@ -45452,7 +45444,7 @@
     field public static final int AUTH_TYPE_NONE = 0; // 0x0
     field public static final int AUTH_TYPE_PAP = 1; // 0x1
     field public static final int AUTH_TYPE_PAP_OR_CHAP = 3; // 0x3
-    field public static final android.os.Parcelable.Creator<android.telephony.data.ApnSetting> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.data.ApnSetting> CREATOR;
     field public static final int MVNO_TYPE_GID = 2; // 0x2
     field public static final int MVNO_TYPE_ICCID = 3; // 0x3
     field public static final int MVNO_TYPE_IMSI = 1; // 0x1
@@ -45519,7 +45511,7 @@
     method public boolean isFromSources(int);
     method public boolean isInEmergencyServiceCategories(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.emergency.EmergencyNumber> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.emergency.EmergencyNumber> CREATOR;
     field public static final int EMERGENCY_CALL_ROUTING_EMERGENCY = 1; // 0x1
     field public static final int EMERGENCY_CALL_ROUTING_NORMAL = 2; // 0x2
     field public static final int EMERGENCY_CALL_ROUTING_UNKNOWN = 0; // 0x0
@@ -45548,7 +45540,7 @@
     method @Nullable public String getConfirmationCode();
     method @Nullable public String getEncodedActivationCode();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.euicc.DownloadableSubscription> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.euicc.DownloadableSubscription> CREATOR;
   }
 
   public final class EuiccInfo implements android.os.Parcelable {
@@ -45556,7 +45548,7 @@
     method public int describeContents();
     method @Nullable public String getOsVersion();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.euicc.EuiccInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.euicc.EuiccInfo> CREATOR;
   }
 
   public class EuiccManager {
@@ -45668,465 +45660,6 @@
 
 }
 
-package android.telephony.ims {
-
-  public class Rcs1To1Thread extends android.telephony.ims.RcsThread {
-    method @WorkerThread public long getFallbackThreadId() throws android.telephony.ims.RcsMessageStoreException;
-    method @NonNull @WorkerThread public android.telephony.ims.RcsParticipant getRecipient() throws android.telephony.ims.RcsMessageStoreException;
-    method public boolean isGroup();
-    method @WorkerThread public void setFallbackThreadId(long) throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public abstract class RcsEvent {
-    ctor protected RcsEvent(long);
-    method public long getTimestamp();
-  }
-
-  public final class RcsEventQueryParams implements android.os.Parcelable {
-    method public int describeContents();
-    method @android.telephony.ims.RcsEventQueryParams.EventType public int getEventType();
-    method public int getLimit();
-    method public boolean getSortDirection();
-    method public int getSortingProperty();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final int ALL_EVENTS = -1; // 0xffffffff
-    field public static final int ALL_GROUP_THREAD_EVENTS = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsEventQueryParams> CREATOR;
-    field public static final int GROUP_THREAD_ICON_CHANGED_EVENT = 8; // 0x8
-    field public static final int GROUP_THREAD_NAME_CHANGED_EVENT = 16; // 0x10
-    field public static final int GROUP_THREAD_PARTICIPANT_JOINED_EVENT = 2; // 0x2
-    field public static final int GROUP_THREAD_PARTICIPANT_LEFT_EVENT = 4; // 0x4
-    field public static final int PARTICIPANT_ALIAS_CHANGED_EVENT = 1; // 0x1
-    field public static final int SORT_BY_CREATION_ORDER = 0; // 0x0
-    field public static final int SORT_BY_TIMESTAMP = 1; // 0x1
-  }
-
-  public static class RcsEventQueryParams.Builder {
-    ctor public RcsEventQueryParams.Builder();
-    method public android.telephony.ims.RcsEventQueryParams build();
-    method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setEventType(@android.telephony.ims.RcsEventQueryParams.EventType int);
-    method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setGroupThread(@NonNull android.telephony.ims.RcsGroupThread);
-    method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setResultLimit(@IntRange(from=0) int) throws java.security.InvalidParameterException;
-    method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setSortDirection(boolean);
-    method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setSortProperty(@android.telephony.ims.RcsEventQueryParams.SortingProperty int);
-  }
-
-  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsEventQueryParams.ALL_EVENTS, android.telephony.ims.RcsEventQueryParams.ALL_GROUP_THREAD_EVENTS, android.telephony.ims.RcsEventQueryParams.PARTICIPANT_ALIAS_CHANGED_EVENT, android.telephony.ims.RcsEventQueryParams.GROUP_THREAD_PARTICIPANT_JOINED_EVENT, android.telephony.ims.RcsEventQueryParams.GROUP_THREAD_PARTICIPANT_LEFT_EVENT, android.telephony.ims.RcsEventQueryParams.GROUP_THREAD_NAME_CHANGED_EVENT, android.telephony.ims.RcsEventQueryParams.GROUP_THREAD_ICON_CHANGED_EVENT}) public static @interface RcsEventQueryParams.EventType {
-  }
-
-  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsEventQueryParams.SORT_BY_CREATION_ORDER, android.telephony.ims.RcsEventQueryParams.SORT_BY_TIMESTAMP}) public static @interface RcsEventQueryParams.SortingProperty {
-  }
-
-  public class RcsEventQueryResult {
-    method public android.telephony.ims.RcsQueryContinuationToken getContinuationToken();
-    method public java.util.List<android.telephony.ims.RcsEvent> getEvents();
-  }
-
-  public final class RcsFileTransferCreationParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public String getContentMimeType();
-    method public android.net.Uri getContentUri();
-    method public long getFileSize();
-    method @android.telephony.ims.RcsFileTransferPart.RcsFileTransferStatus public int getFileTransferStatus();
-    method public int getHeight();
-    method public long getMediaDuration();
-    method public String getPreviewMimeType();
-    method public android.net.Uri getPreviewUri();
-    method public String getRcsFileTransferSessionId();
-    method public long getTransferOffset();
-    method public int getWidth();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsFileTransferCreationParams> CREATOR;
-  }
-
-  public class RcsFileTransferCreationParams.Builder {
-    ctor public RcsFileTransferCreationParams.Builder();
-    method public android.telephony.ims.RcsFileTransferCreationParams build();
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setContentMimeType(String);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setContentUri(android.net.Uri);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setFileSize(long);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setFileTransferSessionId(String);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setFileTransferStatus(@android.telephony.ims.RcsFileTransferPart.RcsFileTransferStatus int);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setHeight(int);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setMediaDuration(long);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setPreviewMimeType(String);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setPreviewUri(android.net.Uri);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setTransferOffset(long);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setWidth(int);
-  }
-
-  public class RcsFileTransferPart {
-    method @WorkerThread @Nullable public String getContentMimeType() throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public android.net.Uri getContentUri() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public long getFileSize() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public String getFileTransferSessionId() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @android.telephony.ims.RcsFileTransferPart.RcsFileTransferStatus public int getFileTransferStatus() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public int getHeight() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public long getLength() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public String getPreviewMimeType() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public android.net.Uri getPreviewUri() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public long getTransferOffset() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public int getWidth() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setContentMimeType(String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setContentUri(android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setFileSize(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setFileTransferSessionId(String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setFileTransferStatus(@android.telephony.ims.RcsFileTransferPart.RcsFileTransferStatus int) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setHeight(int) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setLength(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setPreviewMimeType(String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setPreviewUri(android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setTransferOffset(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setWidth(int) throws android.telephony.ims.RcsMessageStoreException;
-    field public static final int DOWNLOADING = 6; // 0x6
-    field public static final int DOWNLOADING_CANCELLED = 9; // 0x9
-    field public static final int DOWNLOADING_FAILED = 8; // 0x8
-    field public static final int DOWNLOADING_PAUSED = 7; // 0x7
-    field public static final int DRAFT = 1; // 0x1
-    field public static final int NOT_SET = 0; // 0x0
-    field public static final int SENDING = 2; // 0x2
-    field public static final int SENDING_CANCELLED = 5; // 0x5
-    field public static final int SENDING_FAILED = 4; // 0x4
-    field public static final int SENDING_PAUSED = 3; // 0x3
-    field public static final int SUCCEEDED = 10; // 0xa
-  }
-
-  @IntDef({android.telephony.ims.RcsFileTransferPart.DRAFT, android.telephony.ims.RcsFileTransferPart.SENDING, android.telephony.ims.RcsFileTransferPart.SENDING_PAUSED, android.telephony.ims.RcsFileTransferPart.SENDING_FAILED, android.telephony.ims.RcsFileTransferPart.SENDING_CANCELLED, android.telephony.ims.RcsFileTransferPart.DOWNLOADING, android.telephony.ims.RcsFileTransferPart.DOWNLOADING_PAUSED, android.telephony.ims.RcsFileTransferPart.DOWNLOADING_FAILED, android.telephony.ims.RcsFileTransferPart.DOWNLOADING_CANCELLED, android.telephony.ims.RcsFileTransferPart.SUCCEEDED}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface RcsFileTransferPart.RcsFileTransferStatus {
-  }
-
-  public class RcsGroupThread extends android.telephony.ims.RcsThread {
-    method @WorkerThread public void addParticipant(@NonNull android.telephony.ims.RcsParticipant) throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public android.net.Uri getConferenceUri() throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable public android.net.Uri getGroupIcon() throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public String getGroupName() throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public android.telephony.ims.RcsParticipant getOwner() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public java.util.Set<android.telephony.ims.RcsParticipant> getParticipants() throws android.telephony.ims.RcsMessageStoreException;
-    method public boolean isGroup();
-    method @WorkerThread public void removeParticipant(@NonNull android.telephony.ims.RcsParticipant) throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public void setConferenceUri(android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setGroupIcon(@Nullable android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setGroupName(String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setOwner(@Nullable android.telephony.ims.RcsParticipant) throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public abstract class RcsGroupThreadEvent extends android.telephony.ims.RcsEvent {
-    method @NonNull public android.telephony.ims.RcsParticipant getOriginatingParticipant();
-    method @NonNull public android.telephony.ims.RcsGroupThread getRcsGroupThread();
-  }
-
-  public final class RcsGroupThreadIconChangedEvent extends android.telephony.ims.RcsGroupThreadEvent {
-    ctor public RcsGroupThreadIconChangedEvent(long, @NonNull android.telephony.ims.RcsGroupThread, @NonNull android.telephony.ims.RcsParticipant, @Nullable android.net.Uri);
-    method @Nullable public android.net.Uri getNewIcon();
-  }
-
-  public final class RcsGroupThreadNameChangedEvent extends android.telephony.ims.RcsGroupThreadEvent {
-    ctor public RcsGroupThreadNameChangedEvent(long, @NonNull android.telephony.ims.RcsGroupThread, @NonNull android.telephony.ims.RcsParticipant, @Nullable String);
-    method @Nullable public String getNewName();
-  }
-
-  public final class RcsGroupThreadParticipantJoinedEvent extends android.telephony.ims.RcsGroupThreadEvent {
-    ctor public RcsGroupThreadParticipantJoinedEvent(long, @NonNull android.telephony.ims.RcsGroupThread, @NonNull android.telephony.ims.RcsParticipant, @NonNull android.telephony.ims.RcsParticipant);
-    method public android.telephony.ims.RcsParticipant getJoinedParticipant();
-  }
-
-  public final class RcsGroupThreadParticipantLeftEvent extends android.telephony.ims.RcsGroupThreadEvent {
-    ctor public RcsGroupThreadParticipantLeftEvent(long, @NonNull android.telephony.ims.RcsGroupThread, @NonNull android.telephony.ims.RcsParticipant, @NonNull android.telephony.ims.RcsParticipant);
-    method @NonNull public android.telephony.ims.RcsParticipant getLeavingParticipant();
-    method public void persist() throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public class RcsIncomingMessage extends android.telephony.ims.RcsMessage {
-    method @WorkerThread public long getArrivalTimestamp() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public long getSeenTimestamp() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public android.telephony.ims.RcsParticipant getSenderParticipant() throws android.telephony.ims.RcsMessageStoreException;
-    method public boolean isIncoming();
-    method @WorkerThread public void setArrivalTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setSeenTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public final class RcsIncomingMessageCreationParams extends android.telephony.ims.RcsMessageCreationParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public long getArrivalTimestamp();
-    method public long getSeenTimestamp();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsIncomingMessageCreationParams> CREATOR;
-  }
-
-  public static class RcsIncomingMessageCreationParams.Builder extends android.telephony.ims.RcsMessageCreationParams.Builder {
-    ctor public RcsIncomingMessageCreationParams.Builder(long, long, int);
-    method public android.telephony.ims.RcsIncomingMessageCreationParams build();
-    method @CheckResult public android.telephony.ims.RcsIncomingMessageCreationParams.Builder setArrivalTimestamp(long);
-    method @CheckResult public android.telephony.ims.RcsIncomingMessageCreationParams.Builder setSeenTimestamp(long);
-    method @CheckResult public android.telephony.ims.RcsIncomingMessageCreationParams.Builder setSenderParticipant(android.telephony.ims.RcsParticipant);
-  }
-
-  public class RcsManager {
-    method public android.telephony.ims.RcsMessageStore getRcsMessageStore();
-  }
-
-  public abstract class RcsMessage {
-    method @NonNull @WorkerThread public java.util.Set<android.telephony.ims.RcsFileTransferPart> getFileTransferParts() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public double getLatitude() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public double getLongitude() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public long getOriginationTimestamp() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public String getRcsMessageId() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @android.telephony.ims.RcsMessage.RcsMessageStatus public int getStatus() throws android.telephony.ims.RcsMessageStoreException;
-    method public int getSubscriptionId() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public String getText() throws android.telephony.ims.RcsMessageStoreException;
-    method @NonNull @WorkerThread public android.telephony.ims.RcsFileTransferPart insertFileTransfer(android.telephony.ims.RcsFileTransferCreationParams) throws android.telephony.ims.RcsMessageStoreException;
-    method public abstract boolean isIncoming();
-    method @WorkerThread public void removeFileTransferPart(@NonNull android.telephony.ims.RcsFileTransferPart) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setLatitude(double) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setLongitude(double) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setOriginationTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setRcsMessageId(String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setStatus(@android.telephony.ims.RcsMessage.RcsMessageStatus int) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setSubscriptionId(int) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setText(String) throws android.telephony.ims.RcsMessageStoreException;
-    field public static final int DRAFT = 1; // 0x1
-    field public static final int FAILED = 6; // 0x6
-    field public static final double LOCATION_NOT_SET = 4.9E-324;
-    field public static final int NOT_SET = 0; // 0x0
-    field public static final int QUEUED = 2; // 0x2
-    field public static final int RECEIVED = 7; // 0x7
-    field public static final int RETRYING = 5; // 0x5
-    field public static final int SEEN = 9; // 0x9
-    field public static final int SENDING = 3; // 0x3
-    field public static final int SENT = 4; // 0x4
-  }
-
-  @IntDef({android.telephony.ims.RcsMessage.DRAFT, android.telephony.ims.RcsMessage.QUEUED, android.telephony.ims.RcsMessage.SENDING, android.telephony.ims.RcsMessage.SENT, android.telephony.ims.RcsMessage.RETRYING, android.telephony.ims.RcsMessage.FAILED, android.telephony.ims.RcsMessage.RECEIVED, android.telephony.ims.RcsMessage.SEEN}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface RcsMessage.RcsMessageStatus {
-  }
-
-  public class RcsMessageCreationParams {
-    ctor protected RcsMessageCreationParams(android.telephony.ims.RcsMessageCreationParams.Builder);
-    method public double getLatitude();
-    method public double getLongitude();
-    method public int getMessageStatus();
-    method public long getOriginationTimestamp();
-    method @Nullable public String getRcsMessageGlobalId();
-    method public int getSubId();
-    method @Nullable public String getText();
-  }
-
-  public static class RcsMessageCreationParams.Builder {
-    method public android.telephony.ims.RcsMessageCreationParams build();
-    method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setLatitude(double);
-    method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setLongitude(double);
-    method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setRcsMessageId(String);
-    method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setStatus(@android.telephony.ims.RcsMessage.RcsMessageStatus int);
-    method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setText(String);
-  }
-
-  public final class RcsMessageQueryParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public int getFileTransferPresence();
-    method public int getLimit();
-    method public String getMessageLike();
-    method public int getMessageType();
-    method public boolean getSortDirection();
-    method @android.telephony.ims.RcsMessageQueryParams.SortingProperty public int getSortingProperty();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsMessageQueryParams> CREATOR;
-    field public static final int MESSAGES_WITHOUT_FILE_TRANSFERS = 8; // 0x8
-    field public static final int MESSAGES_WITH_FILE_TRANSFERS = 4; // 0x4
-    field public static final int MESSAGE_TYPE_INCOMING = 1; // 0x1
-    field public static final int MESSAGE_TYPE_OUTGOING = 2; // 0x2
-    field public static final int SORT_BY_CREATION_ORDER = 0; // 0x0
-    field public static final int SORT_BY_TIMESTAMP = 1; // 0x1
-  }
-
-  public static class RcsMessageQueryParams.Builder {
-    ctor public RcsMessageQueryParams.Builder();
-    method public android.telephony.ims.RcsMessageQueryParams build();
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setFileTransferPresence(int);
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setMessageLike(String);
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setMessageType(int);
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setResultLimit(@IntRange(from=0) int) throws java.security.InvalidParameterException;
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setSortDirection(boolean);
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setSortProperty(@android.telephony.ims.RcsMessageQueryParams.SortingProperty int);
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setThread(@Nullable android.telephony.ims.RcsThread);
-  }
-
-  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsMessageQueryParams.SORT_BY_CREATION_ORDER, android.telephony.ims.RcsMessageQueryParams.SORT_BY_TIMESTAMP}) public static @interface RcsMessageQueryParams.SortingProperty {
-  }
-
-  public final class RcsMessageQueryResult implements android.os.Parcelable {
-    method public int describeContents();
-    method @Nullable public android.telephony.ims.RcsQueryContinuationToken getContinuationToken();
-    method @NonNull public java.util.List<android.telephony.ims.RcsMessage> getMessages();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsMessageQueryResult> CREATOR;
-  }
-
-  public final class RcsMessageSnippet implements android.os.Parcelable {
-    method public int describeContents();
-    method @android.telephony.ims.RcsMessage.RcsMessageStatus public int getSnippetStatus();
-    method @Nullable public String getSnippetText();
-    method public long getSnippetTimestamp();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsMessageSnippet> CREATOR;
-  }
-
-  public class RcsMessageStore {
-    ctor public RcsMessageStore();
-    method @WorkerThread @NonNull public android.telephony.ims.RcsGroupThread createGroupThread(@Nullable java.util.List<android.telephony.ims.RcsParticipant>, @Nullable String, @Nullable android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.Rcs1To1Thread createRcs1To1Thread(@NonNull android.telephony.ims.RcsParticipant) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsParticipant createRcsParticipant(String, @Nullable String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void deleteThread(@NonNull android.telephony.ims.RcsThread) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsEventQueryResult getRcsEvents(@Nullable android.telephony.ims.RcsEventQueryParams) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsEventQueryResult getRcsEvents(@NonNull android.telephony.ims.RcsQueryContinuationToken) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsMessageQueryResult getRcsMessages(@Nullable android.telephony.ims.RcsMessageQueryParams) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsMessageQueryResult getRcsMessages(@NonNull android.telephony.ims.RcsQueryContinuationToken) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsParticipantQueryResult getRcsParticipants(@Nullable android.telephony.ims.RcsParticipantQueryParams) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsParticipantQueryResult getRcsParticipants(@NonNull android.telephony.ims.RcsQueryContinuationToken) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsThreadQueryResult getRcsThreads(@Nullable android.telephony.ims.RcsThreadQueryParams) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsThreadQueryResult getRcsThreads(@NonNull android.telephony.ims.RcsQueryContinuationToken) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public void persistRcsEvent(android.telephony.ims.RcsEvent) throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public class RcsMessageStoreException extends java.lang.Exception {
-    ctor public RcsMessageStoreException(String);
-  }
-
-  public class RcsOutgoingMessage extends android.telephony.ims.RcsMessage {
-    method @NonNull @WorkerThread public java.util.List<android.telephony.ims.RcsOutgoingMessageDelivery> getOutgoingDeliveries() throws android.telephony.ims.RcsMessageStoreException;
-    method public boolean isIncoming();
-  }
-
-  public final class RcsOutgoingMessageCreationParams extends android.telephony.ims.RcsMessageCreationParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsOutgoingMessageCreationParams> CREATOR;
-  }
-
-  public static class RcsOutgoingMessageCreationParams.Builder extends android.telephony.ims.RcsMessageCreationParams.Builder {
-    ctor public RcsOutgoingMessageCreationParams.Builder(long, int);
-    method public android.telephony.ims.RcsOutgoingMessageCreationParams build();
-  }
-
-  public class RcsOutgoingMessageDelivery {
-    method @WorkerThread public long getDeliveredTimestamp() throws android.telephony.ims.RcsMessageStoreException;
-    method @NonNull public android.telephony.ims.RcsOutgoingMessage getMessage();
-    method @NonNull public android.telephony.ims.RcsParticipant getRecipient();
-    method @WorkerThread public long getSeenTimestamp() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @android.telephony.ims.RcsMessage.RcsMessageStatus public int getStatus() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setDeliveredTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setSeenTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setStatus(@android.telephony.ims.RcsMessage.RcsMessageStatus int) throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public class RcsParticipant {
-    method @Nullable @WorkerThread public String getAlias() throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public String getCanonicalAddress() throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public String getContactId() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setAlias(String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setContactId(String) throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public final class RcsParticipantAliasChangedEvent extends android.telephony.ims.RcsEvent {
-    ctor public RcsParticipantAliasChangedEvent(long, @NonNull android.telephony.ims.RcsParticipant, @Nullable String);
-    method @Nullable public String getNewAlias();
-    method @NonNull public android.telephony.ims.RcsParticipant getParticipant();
-  }
-
-  public final class RcsParticipantQueryParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public String getAliasLike();
-    method public String getCanonicalAddressLike();
-    method public int getLimit();
-    method public boolean getSortDirection();
-    method public int getSortingProperty();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsParticipantQueryParams> CREATOR;
-    field public static final int SORT_BY_ALIAS = 1; // 0x1
-    field public static final int SORT_BY_CANONICAL_ADDRESS = 2; // 0x2
-    field public static final int SORT_BY_CREATION_ORDER = 0; // 0x0
-  }
-
-  public static class RcsParticipantQueryParams.Builder {
-    ctor public RcsParticipantQueryParams.Builder();
-    method public android.telephony.ims.RcsParticipantQueryParams build();
-    method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setAliasLike(String);
-    method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setCanonicalAddressLike(String);
-    method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setResultLimit(@IntRange(from=0) int) throws java.security.InvalidParameterException;
-    method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setSortDirection(boolean);
-    method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setSortProperty(@android.telephony.ims.RcsParticipantQueryParams.SortingProperty int);
-    method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setThread(android.telephony.ims.RcsThread);
-  }
-
-  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsParticipantQueryParams.SORT_BY_CREATION_ORDER, android.telephony.ims.RcsParticipantQueryParams.SORT_BY_ALIAS, android.telephony.ims.RcsParticipantQueryParams.SORT_BY_CANONICAL_ADDRESS}) public static @interface RcsParticipantQueryParams.SortingProperty {
-  }
-
-  public final class RcsParticipantQueryResult implements android.os.Parcelable {
-    method public int describeContents();
-    method @Nullable public android.telephony.ims.RcsQueryContinuationToken getContinuationToken();
-    method @NonNull public java.util.List<android.telephony.ims.RcsParticipant> getParticipants();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsParticipantQueryResult> CREATOR;
-  }
-
-  public final class RcsQueryContinuationToken implements android.os.Parcelable {
-    method public int describeContents();
-    method @android.telephony.ims.RcsQueryContinuationToken.ContinuationTokenType public int getQueryType();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsQueryContinuationToken> CREATOR;
-    field public static final int EVENT_QUERY_CONTINUATION_TOKEN_TYPE = 0; // 0x0
-    field public static final int MESSAGE_QUERY_CONTINUATION_TOKEN_TYPE = 1; // 0x1
-    field public static final int PARTICIPANT_QUERY_CONTINUATION_TOKEN_TYPE = 2; // 0x2
-    field public static final int THREAD_QUERY_CONTINUATION_TOKEN_TYPE = 3; // 0x3
-  }
-
-  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsQueryContinuationToken.EVENT_QUERY_CONTINUATION_TOKEN_TYPE, android.telephony.ims.RcsQueryContinuationToken.MESSAGE_QUERY_CONTINUATION_TOKEN_TYPE, android.telephony.ims.RcsQueryContinuationToken.PARTICIPANT_QUERY_CONTINUATION_TOKEN_TYPE, android.telephony.ims.RcsQueryContinuationToken.THREAD_QUERY_CONTINUATION_TOKEN_TYPE}) public static @interface RcsQueryContinuationToken.ContinuationTokenType {
-  }
-
-  public abstract class RcsThread {
-    method @WorkerThread @NonNull public android.telephony.ims.RcsIncomingMessage addIncomingMessage(@NonNull android.telephony.ims.RcsIncomingMessageCreationParams) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsOutgoingMessage addOutgoingMessage(@NonNull android.telephony.ims.RcsOutgoingMessageCreationParams) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void deleteMessage(@NonNull android.telephony.ims.RcsMessage) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsMessageQueryResult getMessages() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsMessageSnippet getSnippet() throws android.telephony.ims.RcsMessageStoreException;
-    method public abstract boolean isGroup();
-  }
-
-  public final class RcsThreadQueryParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public int getLimit();
-    method public boolean getSortDirection();
-    method @android.telephony.ims.RcsThreadQueryParams.SortingProperty public int getSortingProperty();
-    method public int getThreadType();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsThreadQueryParams> CREATOR;
-    field public static final int SORT_BY_CREATION_ORDER = 0; // 0x0
-    field public static final int SORT_BY_TIMESTAMP = 1; // 0x1
-    field public static final int THREAD_TYPE_1_TO_1 = 2; // 0x2
-    field public static final int THREAD_TYPE_GROUP = 1; // 0x1
-  }
-
-  public static class RcsThreadQueryParams.Builder {
-    ctor public RcsThreadQueryParams.Builder();
-    method public android.telephony.ims.RcsThreadQueryParams build();
-    method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setParticipant(@NonNull android.telephony.ims.RcsParticipant);
-    method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setParticipants(@NonNull java.util.List<android.telephony.ims.RcsParticipant>);
-    method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setResultLimit(@IntRange(from=0) int) throws java.security.InvalidParameterException;
-    method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setSortDirection(boolean);
-    method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setSortProperty(@android.telephony.ims.RcsThreadQueryParams.SortingProperty int);
-    method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setThreadType(int);
-  }
-
-  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsThreadQueryParams.SORT_BY_CREATION_ORDER, android.telephony.ims.RcsThreadQueryParams.SORT_BY_TIMESTAMP}) public static @interface RcsThreadQueryParams.SortingProperty {
-  }
-
-  public final class RcsThreadQueryResult implements android.os.Parcelable {
-    method public int describeContents();
-    method @Nullable public android.telephony.ims.RcsQueryContinuationToken getContinuationToken();
-    method @NonNull public java.util.List<android.telephony.ims.RcsThread> getThreads();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsThreadQueryResult> CREATOR;
-  }
-
-}
-
 package android.telephony.mbms {
 
   public class DownloadProgressListener {
@@ -46144,7 +45677,7 @@
     method public int getSubscriptionId();
     method public byte[] toByteArray();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.mbms.DownloadRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.mbms.DownloadRequest> CREATOR;
   }
 
   public static class DownloadRequest.Builder {
@@ -46167,14 +45700,14 @@
     method public String getMimeType();
     method public android.net.Uri getUri();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.mbms.FileInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.mbms.FileInfo> CREATOR;
   }
 
   public final class FileServiceInfo extends android.telephony.mbms.ServiceInfo implements android.os.Parcelable {
     method public int describeContents();
     method public java.util.List<android.telephony.mbms.FileInfo> getFiles();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.mbms.FileServiceInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.mbms.FileServiceInfo> CREATOR;
   }
 
   public class GroupCall implements java.lang.AutoCloseable {
@@ -46307,7 +45840,7 @@
   public final class StreamingServiceInfo extends android.telephony.mbms.ServiceInfo implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.mbms.StreamingServiceInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.mbms.StreamingServiceInfo> CREATOR;
   }
 
 }
@@ -47706,7 +47239,7 @@
     method public void updateDrawState(android.text.TextPaint);
     method public void writeToParcel(android.os.Parcel, int);
     field @Deprecated public static final String ACTION_SUGGESTION_PICKED = "android.text.style.SUGGESTION_PICKED";
-    field public static final android.os.Parcelable.Creator<android.text.style.SuggestionSpan> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.text.style.SuggestionSpan> CREATOR;
     field public static final int FLAG_AUTO_CORRECTION = 4; // 0x4
     field public static final int FLAG_EASY_CORRECT = 1; // 0x1
     field public static final int FLAG_MISSPELLED = 2; // 0x2
@@ -49163,7 +48696,7 @@
     method public int describeContents();
     method public final android.os.Parcelable getSuperState();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.AbsSavedState> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.AbsSavedState> CREATOR;
     field public static final android.view.AbsSavedState EMPTY_STATE;
   }
 
@@ -49313,7 +48846,7 @@
     method public float getDesiredMinLuminance();
     method public int[] getSupportedHdrTypes();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.Display.HdrCapabilities> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.Display.HdrCapabilities> CREATOR;
     field public static final int HDR_TYPE_DOLBY_VISION = 1; // 0x1
     field public static final int HDR_TYPE_HDR10 = 2; // 0x2
     field public static final int HDR_TYPE_HDR10_PLUS = 4; // 0x4
@@ -49328,7 +48861,7 @@
     method public int getPhysicalWidth();
     method public float getRefreshRate();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.Display.Mode> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.Display.Mode> CREATOR;
   }
 
   public final class DisplayCutout {
@@ -49349,7 +48882,7 @@
     method public int describeContents();
     method public void release();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.DragAndDropPermissions> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.DragAndDropPermissions> CREATOR;
   }
 
   public class DragEvent implements android.os.Parcelable {
@@ -49368,7 +48901,7 @@
     field public static final int ACTION_DRAG_LOCATION = 2; // 0x2
     field public static final int ACTION_DRAG_STARTED = 1; // 0x1
     field public static final int ACTION_DROP = 3; // 0x3
-    field public static final android.os.Parcelable.Creator<android.view.DragEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.DragEvent> CREATOR;
   }
 
   public class FocusFinder {
@@ -49538,7 +49071,7 @@
     method public boolean isVirtual();
     method public boolean supportsSource(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.InputDevice> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.InputDevice> CREATOR;
     field public static final int KEYBOARD_TYPE_ALPHABETIC = 2; // 0x2
     field public static final int KEYBOARD_TYPE_NONE = 0; // 0x0
     field public static final int KEYBOARD_TYPE_NON_ALPHABETIC = 1; // 0x1
@@ -49595,7 +49128,7 @@
     method public abstract long getEventTime();
     method public abstract int getSource();
     method public boolean isFromSource(int);
-    field public static final android.os.Parcelable.Creator<android.view.InputEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.InputEvent> CREATOR;
   }
 
   public final class InputQueue {
@@ -49627,7 +49160,7 @@
     field @Deprecated public static final int BUILT_IN_KEYBOARD = 0; // 0x0
     field public static final int COMBINING_ACCENT = -2147483648; // 0x80000000
     field public static final int COMBINING_ACCENT_MASK = 2147483647; // 0x7fffffff
-    field public static final android.os.Parcelable.Creator<android.view.KeyCharacterMap> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.KeyCharacterMap> CREATOR;
     field public static final int FULL = 4; // 0x4
     field public static final char HEX_INPUT = 61184; // 0xef00 '\uef00'
     field public static final int MODIFIER_BEHAVIOR_CHORDED = 0; // 0x0
@@ -49720,7 +49253,7 @@
     field public static final int ACTION_DOWN = 0; // 0x0
     field @Deprecated public static final int ACTION_MULTIPLE = 2; // 0x2
     field public static final int ACTION_UP = 1; // 0x1
-    field public static final android.os.Parcelable.Creator<android.view.KeyEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.KeyEvent> CREATOR;
     field public static final int FLAG_CANCELED = 32; // 0x20
     field public static final int FLAG_CANCELED_LONG_PRESS = 256; // 0x100
     field public static final int FLAG_EDITOR_ACTION = 16; // 0x10
@@ -50070,7 +49603,7 @@
     method public java.util.List<android.view.KeyboardShortcutInfo> getItems();
     method public CharSequence getLabel();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.KeyboardShortcutGroup> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.KeyboardShortcutGroup> CREATOR;
   }
 
   public final class KeyboardShortcutInfo implements android.os.Parcelable {
@@ -50082,7 +49615,7 @@
     method @Nullable public CharSequence getLabel();
     method public int getModifiers();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.KeyboardShortcutInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.KeyboardShortcutInfo> CREATOR;
   }
 
   public abstract class LayoutInflater {
@@ -50403,7 +49936,7 @@
     field public static final int CLASSIFICATION_AMBIGUOUS_GESTURE = 1; // 0x1
     field public static final int CLASSIFICATION_DEEP_PRESS = 2; // 0x2
     field public static final int CLASSIFICATION_NONE = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.view.MotionEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.MotionEvent> CREATOR;
     field public static final int EDGE_BOTTOM = 2; // 0x2
     field public static final int EDGE_LEFT = 4; // 0x4
     field public static final int EDGE_RIGHT = 8; // 0x8
@@ -50491,7 +50024,7 @@
     method public static android.view.PointerIcon getSystemIcon(@NonNull android.content.Context, int);
     method public static android.view.PointerIcon load(@NonNull android.content.res.Resources, @XmlRes int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.PointerIcon> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.PointerIcon> CREATOR;
     field public static final int TYPE_ALIAS = 1010; // 0x3f2
     field public static final int TYPE_ALL_SCROLL = 1013; // 0x3f5
     field public static final int TYPE_ARROW = 1000; // 0x3e8
@@ -50590,7 +50123,7 @@
     method @Deprecated public void unlockCanvas(android.graphics.Canvas);
     method public void unlockCanvasAndPost(android.graphics.Canvas);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.Surface> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.Surface> CREATOR;
     field public static final int ROTATION_0 = 0; // 0x0
     field public static final int ROTATION_180 = 2; // 0x2
     field public static final int ROTATION_270 = 3; // 0x3
@@ -50608,7 +50141,7 @@
     method public void readFromParcel(android.os.Parcel);
     method public void release();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.SurfaceControl> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.SurfaceControl> CREATOR;
   }
 
   public static class SurfaceControl.Builder {
@@ -50971,6 +50504,7 @@
     method public android.animation.StateListAnimator getStateListAnimator();
     method protected int getSuggestedMinimumHeight();
     method protected int getSuggestedMinimumWidth();
+    method @NonNull public java.util.List<android.graphics.Rect> getSystemGestureExclusionRects();
     method public int getSystemUiVisibility();
     method @android.view.ViewDebug.ExportedProperty public Object getTag();
     method public Object getTag(int);
@@ -51309,6 +50843,7 @@
     method public void setSelected(boolean);
     method public void setSoundEffectsEnabled(boolean);
     method public void setStateListAnimator(android.animation.StateListAnimator);
+    method public void setSystemGestureExclusionRects(@NonNull java.util.List<android.graphics.Rect>);
     method public void setSystemUiVisibility(int);
     method public void setTag(Object);
     method public void setTag(int, Object);
@@ -51542,7 +51077,7 @@
     ctor public View.BaseSavedState(android.os.Parcel);
     ctor public View.BaseSavedState(android.os.Parcel, ClassLoader);
     ctor public View.BaseSavedState(android.os.Parcelable);
-    field public static final android.os.Parcelable.Creator<android.view.View.BaseSavedState> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.View.BaseSavedState> CREATOR;
   }
 
   public static class View.DragShadowBuilder {
@@ -51661,8 +51196,8 @@
     method public int getScaledHoverSlop();
     method public int getScaledMaximumDrawingCacheSize();
     method public int getScaledMaximumFlingVelocity();
-    method public int getScaledMinScalingSpan();
     method public int getScaledMinimumFlingVelocity();
+    method public int getScaledMinimumScalingSpan();
     method public int getScaledOverflingDistance();
     method public int getScaledOverscrollDistance();
     method public int getScaledPagingTouchSlop();
@@ -52137,6 +51672,7 @@
     method public void addOnGlobalLayoutListener(android.view.ViewTreeObserver.OnGlobalLayoutListener);
     method public void addOnPreDrawListener(android.view.ViewTreeObserver.OnPreDrawListener);
     method public void addOnScrollChangedListener(android.view.ViewTreeObserver.OnScrollChangedListener);
+    method public void addOnSystemGestureExclusionRectsChangedListener(java.util.function.Consumer<java.util.List<android.graphics.Rect>>);
     method public void addOnTouchModeChangeListener(android.view.ViewTreeObserver.OnTouchModeChangeListener);
     method public void addOnWindowAttachListener(android.view.ViewTreeObserver.OnWindowAttachListener);
     method public void addOnWindowFocusChangeListener(android.view.ViewTreeObserver.OnWindowFocusChangeListener);
@@ -52151,6 +51687,7 @@
     method public void removeOnGlobalLayoutListener(android.view.ViewTreeObserver.OnGlobalLayoutListener);
     method public void removeOnPreDrawListener(android.view.ViewTreeObserver.OnPreDrawListener);
     method public void removeOnScrollChangedListener(android.view.ViewTreeObserver.OnScrollChangedListener);
+    method public void removeOnSystemGestureExclusionRectsChangedListener(java.util.function.Consumer<java.util.List<android.graphics.Rect>>);
     method public void removeOnTouchModeChangeListener(android.view.ViewTreeObserver.OnTouchModeChangeListener);
     method public void removeOnWindowAttachListener(android.view.ViewTreeObserver.OnWindowAttachListener);
     method public void removeOnWindowFocusChangeListener(android.view.ViewTreeObserver.OnWindowFocusChangeListener);
@@ -52391,7 +51928,7 @@
   public final class WindowAnimationFrameStats extends android.view.FrameStats implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.WindowAnimationFrameStats> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.WindowAnimationFrameStats> CREATOR;
   }
 
   public final class WindowContentFrameStats extends android.view.FrameStats implements android.os.Parcelable {
@@ -52399,7 +51936,7 @@
     method public long getFramePostedTimeNano(int);
     method public long getFrameReadyTimeNano(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.WindowContentFrameStats> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.WindowContentFrameStats> CREATOR;
   }
 
   public class WindowId implements android.os.Parcelable {
@@ -52408,7 +51945,7 @@
     method public void registerFocusObserver(android.view.WindowId.FocusObserver);
     method public void unregisterFocusObserver(android.view.WindowId.FocusObserver);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.WindowId> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.WindowId> CREATOR;
   }
 
   public abstract static class WindowId.FocusObserver {
@@ -52436,16 +51973,16 @@
     method public boolean hasInsets();
     method public boolean hasStableInsets();
     method public boolean hasSystemWindowInsets();
-    method @NonNull public android.view.WindowInsets inset(int, int, int, int);
+    method @NonNull public android.view.WindowInsets inset(@IntRange(from=0) int, @IntRange(from=0) int, @IntRange(from=0) int, @IntRange(from=0) int);
     method public boolean isConsumed();
     method public boolean isRound();
     method @Deprecated @NonNull public android.view.WindowInsets replaceSystemWindowInsets(int, int, int, int);
     method @Deprecated @NonNull public android.view.WindowInsets replaceSystemWindowInsets(android.graphics.Rect);
   }
 
-  public static class WindowInsets.Builder {
+  public static final class WindowInsets.Builder {
     ctor public WindowInsets.Builder();
-    ctor public WindowInsets.Builder(android.view.WindowInsets);
+    ctor public WindowInsets.Builder(@NonNull android.view.WindowInsets);
     method @NonNull public android.view.WindowInsets build();
     method @NonNull public android.view.WindowInsets.Builder setDisplayCutout(@Nullable android.view.DisplayCutout);
     method @NonNull public android.view.WindowInsets.Builder setStableInsets(@NonNull android.graphics.Insets);
@@ -52489,7 +52026,7 @@
     field public static final float BRIGHTNESS_OVERRIDE_FULL = 1.0f;
     field public static final float BRIGHTNESS_OVERRIDE_NONE = -1.0f;
     field public static final float BRIGHTNESS_OVERRIDE_OFF = 0.0f;
-    field public static final android.os.Parcelable.Creator<android.view.WindowManager.LayoutParams> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.WindowManager.LayoutParams> CREATOR;
     field public static final int DIM_AMOUNT_CHANGED = 32; // 0x20
     field public static final int FIRST_APPLICATION_WINDOW = 1; // 0x1
     field public static final int FIRST_SUB_WINDOW = 1000; // 0x3e8
@@ -52649,7 +52186,7 @@
     field public static final int CONTENT_CHANGE_TYPE_SUBTREE = 1; // 0x1
     field public static final int CONTENT_CHANGE_TYPE_TEXT = 2; // 0x2
     field public static final int CONTENT_CHANGE_TYPE_UNDEFINED = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.view.accessibility.AccessibilityEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.accessibility.AccessibilityEvent> CREATOR;
     field public static final int INVALID_POSITION = -1; // 0xffffffff
     field @Deprecated public static final int MAX_TEXT_LENGTH = 500; // 0x1f4
     field public static final int TYPES_ALL_MASK = -1; // 0xffffffff
@@ -52899,7 +52436,7 @@
     field public static final int ACTION_SELECT = 4; // 0x4
     field public static final int ACTION_SET_SELECTION = 131072; // 0x20000
     field public static final int ACTION_SET_TEXT = 2097152; // 0x200000
-    field public static final android.os.Parcelable.Creator<android.view.accessibility.AccessibilityNodeInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.accessibility.AccessibilityNodeInfo> CREATOR;
     field public static final String EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_LENGTH = "android.view.accessibility.extra.DATA_TEXT_CHARACTER_LOCATION_ARG_LENGTH";
     field public static final String EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_START_INDEX = "android.view.accessibility.extra.DATA_TEXT_CHARACTER_LOCATION_ARG_START_INDEX";
     field public static final String EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY = "android.view.accessibility.extra.DATA_TEXT_CHARACTER_LOCATION_KEY";
@@ -52996,7 +52533,7 @@
     method public int getRegionCount();
     method @Nullable public android.view.accessibility.AccessibilityNodeInfo getTargetForRegion(@NonNull android.graphics.Region);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.accessibility.AccessibilityNodeInfo.TouchDelegateInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.accessibility.AccessibilityNodeInfo.TouchDelegateInfo> CREATOR;
   }
 
   public abstract class AccessibilityNodeProvider {
@@ -53089,7 +52626,7 @@
     method public static android.view.accessibility.AccessibilityWindowInfo obtain(android.view.accessibility.AccessibilityWindowInfo);
     method public void recycle();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.accessibility.AccessibilityWindowInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.accessibility.AccessibilityWindowInfo> CREATOR;
     field public static final int TYPE_ACCESSIBILITY_OVERLAY = 4; // 0x4
     field public static final int TYPE_APPLICATION = 1; // 0x1
     field public static final int TYPE_INPUT_METHOD = 2; // 0x2
@@ -53422,7 +52959,7 @@
   public final class AutofillId implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.autofill.AutofillId> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.autofill.AutofillId> CREATOR;
   }
 
   public final class AutofillManager {
@@ -53483,7 +53020,7 @@
     method public boolean isText();
     method public boolean isToggle();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.autofill.AutofillValue> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.autofill.AutofillValue> CREATOR;
   }
 
 }
@@ -53492,16 +53029,16 @@
 
   public final class ContentCaptureContext implements android.os.Parcelable {
     method public int describeContents();
-    method public static android.view.contentcapture.ContentCaptureContext forLocusId(@NonNull android.net.Uri);
+    method @NonNull public static android.view.contentcapture.ContentCaptureContext forLocusId(@NonNull android.net.Uri);
     method @Nullable public android.os.Bundle getExtras();
     method @NonNull public android.content.LocusId getLocusId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.contentcapture.ContentCaptureContext> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.contentcapture.ContentCaptureContext> CREATOR;
   }
 
   public static final class ContentCaptureContext.Builder {
     ctor public ContentCaptureContext.Builder(@NonNull android.content.LocusId);
-    method public android.view.contentcapture.ContentCaptureContext build();
+    method @NonNull public android.view.contentcapture.ContentCaptureContext build();
     method @NonNull public android.view.contentcapture.ContentCaptureContext.Builder setExtras(@NonNull android.os.Bundle);
   }
 
@@ -53517,7 +53054,7 @@
     method @NonNull public final android.view.contentcapture.ContentCaptureSession createContentCaptureSession(@NonNull android.view.contentcapture.ContentCaptureContext);
     method public final void destroy();
     method @Nullable public final android.view.contentcapture.ContentCaptureContext getContentCaptureContext();
-    method public final android.view.contentcapture.ContentCaptureSessionId getContentCaptureSessionId();
+    method @NonNull public final android.view.contentcapture.ContentCaptureSessionId getContentCaptureSessionId();
     method @NonNull public android.view.autofill.AutofillId newAutofillId(@NonNull android.view.autofill.AutofillId, long);
     method @NonNull public final android.view.ViewStructure newVirtualViewStructure(@NonNull android.view.autofill.AutofillId, long);
     method public final void notifyViewAppeared(@NonNull android.view.ViewStructure);
@@ -53530,7 +53067,7 @@
   public final class ContentCaptureSessionId implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.contentcapture.ContentCaptureSessionId> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.contentcapture.ContentCaptureSessionId> CREATOR;
   }
 
   public final class UserDataRemovalRequest implements android.os.Parcelable {
@@ -53539,12 +53076,12 @@
     method @NonNull public String getPackageName();
     method public boolean isForEverything();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.contentcapture.UserDataRemovalRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.contentcapture.UserDataRemovalRequest> CREATOR;
   }
 
   public static final class UserDataRemovalRequest.Builder {
     ctor public UserDataRemovalRequest.Builder();
-    method public android.view.contentcapture.UserDataRemovalRequest.Builder addLocusId(@NonNull android.content.LocusId, boolean);
+    method @NonNull public android.view.contentcapture.UserDataRemovalRequest.Builder addLocusId(@NonNull android.content.LocusId, boolean);
     method @NonNull public android.view.contentcapture.UserDataRemovalRequest build();
     method @NonNull public android.view.contentcapture.UserDataRemovalRequest.Builder forEverything();
   }
@@ -53602,7 +53139,7 @@
     method public int getPosition();
     method public CharSequence getText();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.inputmethod.CompletionInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.CompletionInfo> CREATOR;
   }
 
   public final class CorrectionInfo implements android.os.Parcelable {
@@ -53612,7 +53149,7 @@
     method public int getOffset();
     method public CharSequence getOldText();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.inputmethod.CorrectionInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.CorrectionInfo> CREATOR;
   }
 
   public final class CursorAnchorInfo implements android.os.Parcelable {
@@ -53631,7 +53168,7 @@
     method public int getSelectionEnd();
     method public int getSelectionStart();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.inputmethod.CursorAnchorInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.CursorAnchorInfo> CREATOR;
     field public static final int FLAG_HAS_INVISIBLE_REGION = 2; // 0x2
     field public static final int FLAG_HAS_VISIBLE_REGION = 1; // 0x1
     field public static final int FLAG_IS_RTL = 4; // 0x4
@@ -53654,7 +53191,7 @@
     method public void dump(android.util.Printer, String);
     method public final void makeCompatible(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.inputmethod.EditorInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.EditorInfo> CREATOR;
     field public static final int IME_ACTION_DONE = 6; // 0x6
     field public static final int IME_ACTION_GO = 2; // 0x2
     field public static final int IME_ACTION_NEXT = 5; // 0x5
@@ -53695,7 +53232,7 @@
     ctor public ExtractedText();
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.inputmethod.ExtractedText> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.ExtractedText> CREATOR;
     field public static final int FLAG_SELECTING = 2; // 0x2
     field public static final int FLAG_SINGLE_LINE = 1; // 0x1
     field public int flags;
@@ -53712,7 +53249,7 @@
     ctor public ExtractedTextRequest();
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.inputmethod.ExtractedTextRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.ExtractedTextRequest> CREATOR;
     field public int flags;
     field public int hintMaxChars;
     field public int hintMaxLines;
@@ -53728,7 +53265,7 @@
     method public int getPid();
     method public int getUid();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.inputmethod.InputBinding> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.InputBinding> CREATOR;
   }
 
   public interface InputConnection {
@@ -53806,7 +53343,7 @@
     method public void releasePermission();
     method public void requestPermission();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.inputmethod.InputContentInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.InputContentInfo> CREATOR;
   }
 
   public interface InputMethod {
@@ -53848,7 +53385,7 @@
     method public android.graphics.drawable.Drawable loadIcon(android.content.pm.PackageManager);
     method public CharSequence loadLabel(android.content.pm.PackageManager);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.inputmethod.InputMethodInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.InputMethodInfo> CREATOR;
   }
 
   public final class InputMethodManager {
@@ -53937,7 +53474,7 @@
     method public boolean isAuxiliary();
     method public boolean overridesImplicitlyEnabledSubtype();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.inputmethod.InputMethodSubtype> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.InputMethodSubtype> CREATOR;
   }
 
   public static class InputMethodSubtype.InputMethodSubtypeBuilder {
@@ -54058,7 +53595,7 @@
     method @Nullable public CharSequence getTextReply();
     method @NonNull public String getType();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.ConversationAction> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.ConversationAction> CREATOR;
     field public static final String TYPE_CALL_PHONE = "call_phone";
     field public static final String TYPE_CREATE_REMINDER = "create_reminder";
     field public static final String TYPE_OPEN_URL = "open_url";
@@ -54086,7 +53623,7 @@
     method @NonNull public java.util.List<android.view.textclassifier.ConversationAction> getConversationActions();
     method @Nullable public String getId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.ConversationActions> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.ConversationActions> CREATOR;
   }
 
   public static final class ConversationActions.Message implements android.os.Parcelable {
@@ -54096,7 +53633,7 @@
     method @Nullable public java.time.ZonedDateTime getReferenceTime();
     method @Nullable public CharSequence getText();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.ConversationActions.Message> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.ConversationActions.Message> CREATOR;
     field public static final android.app.Person PERSON_USER_OTHERS;
     field public static final android.app.Person PERSON_USER_SELF;
   }
@@ -54118,7 +53655,7 @@
     method @IntRange(from=0xffffffff) public int getMaxSuggestions();
     method @NonNull public android.view.textclassifier.TextClassifier.EntityConfig getTypeConfig();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.ConversationActions.Request> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.ConversationActions.Request> CREATOR;
     field public static final String HINT_FOR_IN_APP = "in_app";
     field public static final String HINT_FOR_NOTIFICATION = "notification";
   }
@@ -54169,7 +53706,7 @@
     field public static final int ACTION_SELECT_ALL = 200; // 0xc8
     field public static final int ACTION_SHARE = 104; // 0x68
     field public static final int ACTION_SMART_SHARE = 105; // 0x69
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.SelectionEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.SelectionEvent> CREATOR;
     field public static final int EVENT_AUTO_SELECTION = 5; // 0x5
     field public static final int EVENT_SELECTION_MODIFIED = 2; // 0x2
     field public static final int EVENT_SELECTION_STARTED = 1; // 0x1
@@ -54194,7 +53731,7 @@
     method @Deprecated @Nullable public android.view.View.OnClickListener getOnClickListener();
     method @Nullable public String getText();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextClassification> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextClassification> CREATOR;
   }
 
   public static final class TextClassification.Builder {
@@ -54221,7 +53758,7 @@
     method @IntRange(from=0) public int getStartIndex();
     method @NonNull public CharSequence getText();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextClassification.Request> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextClassification.Request> CREATOR;
   }
 
   public static final class TextClassification.Request.Builder {
@@ -54238,7 +53775,7 @@
     method @NonNull public String getWidgetType();
     method @Nullable public String getWidgetVersion();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextClassificationContext> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextClassificationContext> CREATOR;
   }
 
   public static final class TextClassificationContext.Builder {
@@ -54261,7 +53798,7 @@
   public final class TextClassificationSessionId implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextClassificationSessionId> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextClassificationSessionId> CREATOR;
   }
 
   public interface TextClassifier {
@@ -54311,7 +53848,7 @@
     method public java.util.Collection<java.lang.String> resolveEntityListModifications(@NonNull java.util.Collection<java.lang.String>);
     method public boolean shouldIncludeTypesFromTextClassifier();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextClassifier.EntityConfig> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextClassifier.EntityConfig> CREATOR;
   }
 
   public static final class TextClassifier.EntityConfig.Builder {
@@ -54346,7 +53883,7 @@
     field public static final int CATEGORY_LINKIFY = 2; // 0x2
     field public static final int CATEGORY_SELECTION = 1; // 0x1
     field public static final int CATEGORY_UNDEFINED = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextClassifierEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextClassifierEvent> CREATOR;
     field public static final int TYPE_ACTIONS_GENERATED = 20; // 0x14
     field public static final int TYPE_ACTIONS_SHOWN = 6; // 0x6
     field public static final int TYPE_AUTO_SELECTION = 5; // 0x5
@@ -54396,7 +53933,7 @@
     method @NonNull public android.icu.util.ULocale getLocale(int);
     method @IntRange(from=0) public int getLocaleHypothesisCount();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextLanguage> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextLanguage> CREATOR;
   }
 
   public static final class TextLanguage.Builder {
@@ -54413,7 +53950,7 @@
     method @NonNull public android.os.Bundle getExtras();
     method @NonNull public CharSequence getText();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextLanguage.Request> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextLanguage.Request> CREATOR;
   }
 
   public static final class TextLanguage.Request.Builder {
@@ -54430,7 +53967,7 @@
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int APPLY_STRATEGY_IGNORE = 0; // 0x0
     field public static final int APPLY_STRATEGY_REPLACE = 1; // 0x1
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextLinks> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextLinks> CREATOR;
     field public static final int STATUS_DIFFERENT_TEXT = 3; // 0x3
     field public static final int STATUS_LINKS_APPLIED = 0; // 0x0
     field public static final int STATUS_NO_LINKS_APPLIED = 2; // 0x2
@@ -54455,7 +53992,7 @@
     method @NonNull public android.os.Bundle getExtras();
     method @NonNull public CharSequence getText();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextLinks.Request> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextLinks.Request> CREATOR;
   }
 
   public static final class TextLinks.Request.Builder {
@@ -54475,7 +54012,7 @@
     method public android.os.Bundle getExtras();
     method public int getStart();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextLinks.TextLink> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextLinks.TextLink> CREATOR;
   }
 
   public static class TextLinks.TextLinkSpan extends android.text.style.ClickableSpan {
@@ -54494,7 +54031,7 @@
     method public int getSelectionEndIndex();
     method public int getSelectionStartIndex();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextSelection> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextSelection> CREATOR;
   }
 
   public static final class TextSelection.Builder {
@@ -54514,7 +54051,7 @@
     method @IntRange(from=0) public int getStartIndex();
     method @NonNull public CharSequence getText();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textclassifier.TextSelection.Request> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textclassifier.TextSelection.Request> CREATOR;
   }
 
   public static final class TextSelection.Request.Builder {
@@ -54537,7 +54074,7 @@
     method public int getSuggestionsCount();
     method public android.view.textservice.SuggestionsInfo getSuggestionsInfoAt(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textservice.SentenceSuggestionsInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textservice.SentenceSuggestionsInfo> CREATOR;
   }
 
   public final class SpellCheckerInfo implements android.os.Parcelable {
@@ -54552,7 +54089,7 @@
     method public android.graphics.drawable.Drawable loadIcon(android.content.pm.PackageManager);
     method public CharSequence loadLabel(android.content.pm.PackageManager);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textservice.SpellCheckerInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textservice.SpellCheckerInfo> CREATOR;
   }
 
   public class SpellCheckerSession {
@@ -54582,7 +54119,7 @@
     method @Deprecated @NonNull public String getLocale();
     method public int getNameResId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textservice.SpellCheckerSubtype> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textservice.SpellCheckerSubtype> CREATOR;
   }
 
   public final class SuggestionsInfo implements android.os.Parcelable {
@@ -54597,7 +54134,7 @@
     method public int getSuggestionsCount();
     method public void setCookieAndSequence(int, int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textservice.SuggestionsInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textservice.SuggestionsInfo> CREATOR;
     field public static final int RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS = 4; // 0x4
     field public static final int RESULT_ATTR_IN_THE_DICTIONARY = 1; // 0x1
     field public static final int RESULT_ATTR_LOOKS_LIKE_TYPO = 2; // 0x2
@@ -54614,7 +54151,7 @@
     method public int getSequence();
     method public String getText();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.textservice.TextInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.textservice.TextInfo> CREATOR;
   }
 
   public final class TextServicesManager {
@@ -57171,7 +56708,7 @@
     method public void showNext(int);
     method public void showPrevious(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.widget.RemoteViews> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.widget.RemoteViews> CREATOR;
     field public static final String EXTRA_SHARED_ELEMENT_BOUNDS = "android.widget.extra.SHARED_ELEMENT_BOUNDS";
   }
 
@@ -57954,7 +57491,7 @@
   }
 
   public static class TextView.SavedState extends android.view.View.BaseSavedState {
-    field public static final android.os.Parcelable.Creator<android.widget.TextView.SavedState> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.widget.TextView.SavedState> CREATOR;
   }
 
   public interface ThemedSpinnerAdapter extends android.widget.SpinnerAdapter {
@@ -58229,16 +57766,16 @@
     method @Deprecated public void onZoom(boolean);
   }
 
-  public class ZoomControls extends android.widget.LinearLayout {
-    ctor public ZoomControls(android.content.Context);
-    ctor public ZoomControls(android.content.Context, android.util.AttributeSet);
-    method public void hide();
-    method public void setIsZoomInEnabled(boolean);
-    method public void setIsZoomOutEnabled(boolean);
-    method public void setOnZoomInClickListener(android.view.View.OnClickListener);
-    method public void setOnZoomOutClickListener(android.view.View.OnClickListener);
-    method public void setZoomSpeed(long);
-    method public void show();
+  @Deprecated public class ZoomControls extends android.widget.LinearLayout {
+    ctor @Deprecated public ZoomControls(android.content.Context);
+    ctor @Deprecated public ZoomControls(android.content.Context, android.util.AttributeSet);
+    method @Deprecated public void hide();
+    method @Deprecated public void setIsZoomInEnabled(boolean);
+    method @Deprecated public void setIsZoomOutEnabled(boolean);
+    method @Deprecated public void setOnZoomInClickListener(android.view.View.OnClickListener);
+    method @Deprecated public void setOnZoomOutClickListener(android.view.View.OnClickListener);
+    method @Deprecated public void setZoomSpeed(long);
+    method @Deprecated public void show();
   }
 
 }
diff --git a/api/removed.txt b/api/removed.txt
index c4ed871..fdfaf91 100644
--- a/api/removed.txt
+++ b/api/removed.txt
@@ -32,7 +32,7 @@
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int CONTENTS_FILE_DESCRIPTOR = 1; // 0x1
-    field public static final android.os.Parcelable.Creator<android.app.PictureInPictureArgs> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.PictureInPictureArgs> CREATOR;
     field public static final int PARCELABLE_WRITE_RETURN_VALUE = 1; // 0x1
   }
 
@@ -352,11 +352,11 @@
   }
 
   public static final class StrictMode.ThreadPolicy.Builder {
-    method public android.os.StrictMode.ThreadPolicy.Builder penaltyListener(@NonNull android.os.StrictMode.OnThreadViolationListener, @NonNull java.util.concurrent.Executor);
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder penaltyListener(@NonNull android.os.StrictMode.OnThreadViolationListener, @NonNull java.util.concurrent.Executor);
   }
 
   public static final class StrictMode.VmPolicy.Builder {
-    method public android.os.StrictMode.VmPolicy.Builder penaltyListener(@NonNull android.os.StrictMode.OnVmViolationListener, @NonNull java.util.concurrent.Executor);
+    method @NonNull public android.os.StrictMode.VmPolicy.Builder penaltyListener(@NonNull android.os.StrictMode.OnVmViolationListener, @NonNull java.util.concurrent.Executor);
   }
 
   public final class SystemClock {
@@ -508,6 +508,8 @@
   }
 
   public final class MediaStore {
+    method @Deprecated @NonNull public static android.net.Uri createPending(@NonNull android.content.Context, @NonNull android.provider.MediaStore.PendingParams);
+    method @Deprecated @NonNull public static android.provider.MediaStore.PendingSession openPending(@NonNull android.content.Context, @NonNull android.net.Uri);
     method @Deprecated @NonNull public static android.net.Uri setIncludeTrashed(@NonNull android.net.Uri);
     method @Deprecated public static void trash(@NonNull android.content.Context, @NonNull android.net.Uri);
     method @Deprecated public static void trash(@NonNull android.content.Context, @NonNull android.net.Uri, long);
@@ -515,11 +517,27 @@
   }
 
   public static interface MediaStore.MediaColumns extends android.provider.BaseColumns {
-    field @Deprecated public static final String DATE_EXPIRES = "date_expires";
     field @Deprecated public static final String HASH = "_hash";
     field @Deprecated public static final String IS_TRASHED = "is_trashed";
   }
 
+  @Deprecated public static class MediaStore.PendingParams {
+    ctor public MediaStore.PendingParams(@NonNull android.net.Uri, @NonNull String, @NonNull String);
+    method public void setDownloadUri(@Nullable android.net.Uri);
+    method public void setPrimaryDirectory(@Nullable String);
+    method public void setRefererUri(@Nullable android.net.Uri);
+    method public void setSecondaryDirectory(@Nullable String);
+  }
+
+  @Deprecated public static class MediaStore.PendingSession implements java.lang.AutoCloseable {
+    method public void abandon();
+    method public void close();
+    method public void notifyProgress(@IntRange(from=0, to=100) int);
+    method @NonNull public android.os.ParcelFileDescriptor open() throws java.io.FileNotFoundException;
+    method @NonNull public java.io.OutputStream openOutputStream() throws java.io.FileNotFoundException;
+    method @NonNull public android.net.Uri publish();
+  }
+
   public static final class Settings.Global extends android.provider.Settings.NameValueTable {
     field @Deprecated public static final String CONTACT_METADATA_SYNC = "contact_metadata_sync";
   }
diff --git a/api/system-current.txt b/api/system-current.txt
index b580deb..94bc1dd 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -384,7 +384,7 @@
     method @NonNull public String getOpName();
     method public long getRejectCount(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalOp> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalOp> CREATOR;
   }
 
   public static final class AppOpsManager.HistoricalOps implements android.os.Parcelable {
@@ -395,7 +395,7 @@
     method @Nullable public android.app.AppOpsManager.HistoricalUidOps getUidOps(int);
     method @NonNull public android.app.AppOpsManager.HistoricalUidOps getUidOpsAt(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalOps> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalOps> CREATOR;
   }
 
   public static final class AppOpsManager.HistoricalOpsRequest {
@@ -416,7 +416,7 @@
     method public int getOpCount();
     method @NonNull public String getPackageName();
     method public void writeToParcel(@NonNull android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalPackageOps> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalPackageOps> CREATOR;
   }
 
   public static final class AppOpsManager.HistoricalUidOps implements android.os.Parcelable {
@@ -426,7 +426,7 @@
     method @NonNull public android.app.AppOpsManager.HistoricalPackageOps getPackageOpsAt(int);
     method public int getUid();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalUidOps> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalUidOps> CREATOR;
   }
 
   public static final class AppOpsManager.OpEntry implements android.os.Parcelable {
@@ -444,7 +444,7 @@
     method public int getProxyUid();
     method public boolean isRunning();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.OpEntry> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.OpEntry> CREATOR;
   }
 
   public static final class AppOpsManager.PackageOps implements android.os.Parcelable {
@@ -453,7 +453,7 @@
     method public String getPackageName();
     method public int getUid();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.PackageOps> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.PackageOps> CREATOR;
   }
 
   public class BroadcastOptions {
@@ -565,12 +565,12 @@
   }
 
   public class StatusBarManager {
-    method public android.app.StatusBarManager.DisableInfo getDisableInfo();
-    method public void setDisabledForSetup(boolean);
+    method @NonNull @RequiresPermission(android.Manifest.permission.STATUS_BAR) public android.app.StatusBarManager.DisableInfo getDisableInfo();
+    method @RequiresPermission(android.Manifest.permission.STATUS_BAR) public void setDisabledForSetup(boolean);
   }
 
   public static final class StatusBarManager.DisableInfo {
-    method public boolean areNoComponentsDisabled();
+    method public boolean areAllComponentsEnabled();
     method public boolean isNavigateToHomeDisabled();
     method public boolean isNotificationPeekingDisabled();
     method public boolean isRecentsDisabled();
@@ -588,7 +588,7 @@
     method public int getRemovedFlags();
     method public int getWidth();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.Vr2dDisplayProperties> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.Vr2dDisplayProperties> CREATOR;
     field public static final int FLAG_VIRTUAL_DISPLAY_ENABLED = 1; // 0x1
   }
 
@@ -833,7 +833,7 @@
     ctor public BackupProgress(long, long);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.backup.BackupProgress> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.backup.BackupProgress> CREATOR;
     field public final long bytesExpected;
     field public final long bytesTransferred;
   }
@@ -891,7 +891,7 @@
     method public int getDataType();
     method public String getPackageName();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.backup.RestoreDescription> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.backup.RestoreDescription> CREATOR;
     field public static final android.app.backup.RestoreDescription NO_MORE_PACKAGES;
     field public static final int TYPE_FULL_STREAM = 2; // 0x2
     field public static final int TYPE_KEY_VALUE = 1; // 0x1
@@ -918,7 +918,7 @@
     ctor public RestoreSet(String, String, long);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.backup.RestoreSet> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.backup.RestoreSet> CREATOR;
     field public String device;
     field public String name;
     field public long token;
@@ -939,7 +939,7 @@
     method @Nullable public android.os.Bundle getExtras();
     method @NonNull public java.util.List<android.app.contentsuggestions.ContentSelection> getSelections();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.contentsuggestions.ClassificationsRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.contentsuggestions.ClassificationsRequest> CREATOR;
   }
 
   public static final class ClassificationsRequest.Builder {
@@ -954,7 +954,7 @@
     method @NonNull public android.os.Bundle getExtras();
     method @NonNull public String getId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.contentsuggestions.ContentClassification> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.contentsuggestions.ContentClassification> CREATOR;
   }
 
   public final class ContentSelection implements android.os.Parcelable {
@@ -963,7 +963,7 @@
     method @NonNull public android.os.Bundle getExtras();
     method @NonNull public String getId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.contentsuggestions.ContentSelection> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.contentsuggestions.ContentSelection> CREATOR;
   }
 
   public final class ContentSuggestionsManager {
@@ -987,7 +987,7 @@
     method @Nullable public android.graphics.Point getInterestPoint();
     method public int getTaskId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.contentsuggestions.SelectionsRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.contentsuggestions.SelectionsRequest> CREATOR;
   }
 
   public static final class SelectionsRequest.Builder {
@@ -1016,7 +1016,7 @@
     method public int getPredictedTargetCount();
     method public String getUiSurface();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.prediction.AppPredictionContext> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.prediction.AppPredictionContext> CREATOR;
   }
 
   public static final class AppPredictionContext.Builder {
@@ -1034,7 +1034,7 @@
   public final class AppPredictionSessionId implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.prediction.AppPredictionSessionId> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.prediction.AppPredictionSessionId> CREATOR;
   }
 
   public final class AppPredictor {
@@ -1062,7 +1062,7 @@
     method @Nullable public android.content.pm.ShortcutInfo getShortcutInfo();
     method @NonNull public android.os.UserHandle getUser();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.prediction.AppTarget> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.prediction.AppTarget> CREATOR;
   }
 
   public final class AppTargetEvent implements android.os.Parcelable {
@@ -1074,7 +1074,7 @@
     field public static final int ACTION_DISMISS = 2; // 0x2
     field public static final int ACTION_LAUNCH = 1; // 0x1
     field public static final int ACTION_PIN = 3; // 0x3
-    field public static final android.os.Parcelable.Creator<android.app.prediction.AppTargetEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.prediction.AppTargetEvent> CREATOR;
   }
 
   public static final class AppTargetEvent.Builder {
@@ -1087,7 +1087,7 @@
     ctor public AppTargetId(@NonNull String);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.prediction.AppTargetId> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.prediction.AppTargetId> CREATOR;
   }
 
 }
@@ -1111,7 +1111,6 @@
     method @RequiresPermission("com.android.permissioncontroller.permission.MANAGE_ROLES_FROM_CONTROLLER") public boolean removeRoleHolderFromController(@NonNull String, @NonNull String);
     method @RequiresPermission("com.android.permissioncontroller.permission.MANAGE_ROLES_FROM_CONTROLLER") public void setRoleNamesFromController(@NonNull java.util.List<java.lang.String>);
     field public static final int MANAGE_HOLDERS_FLAG_DONT_KILL_APP = 1; // 0x1
-    field public static final String ROLE_ASSISTANT = "android.app.role.ASSISTANT";
   }
 
   public interface RoleManagerCallback {
@@ -1131,7 +1130,7 @@
     method public android.app.usage.UsageStats getUsageStats();
     method public String getVolumeUuid();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.usage.CacheQuotaHint> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.usage.CacheQuotaHint> CREATOR;
     field public static final long QUOTA_NOT_SET = -1L; // 0xffffffffffffffffL
   }
 
@@ -1173,7 +1172,7 @@
     method @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) public int getAppStandbyBucket(String);
     method @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) public java.util.Map<java.lang.String,java.lang.Integer> getAppStandbyBuckets();
     method public int getUsageSource();
-    method @RequiresPermission(allOf={android.Manifest.permission.SUSPEND_APPS, android.Manifest.permission.OBSERVE_APP_USAGE}) public void registerAppUsageLimitObserver(int, @NonNull String[], long, @NonNull java.util.concurrent.TimeUnit, android.app.PendingIntent);
+    method @RequiresPermission(allOf={android.Manifest.permission.SUSPEND_APPS, android.Manifest.permission.OBSERVE_APP_USAGE}) public void registerAppUsageLimitObserver(int, @NonNull String[], long, @NonNull java.util.concurrent.TimeUnit, @Nullable android.app.PendingIntent);
     method @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE) public void registerAppUsageObserver(int, @NonNull String[], long, @NonNull java.util.concurrent.TimeUnit, @NonNull android.app.PendingIntent);
     method @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE) public void registerUsageSessionObserver(int, @NonNull String[], long, @NonNull java.util.concurrent.TimeUnit, long, @NonNull java.util.concurrent.TimeUnit, @NonNull android.app.PendingIntent, @Nullable android.app.PendingIntent);
     method public void reportUsageStart(@NonNull android.app.Activity, @NonNull String);
@@ -1278,7 +1277,7 @@
     method public int getOffset();
     method public int getType();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.bluetooth.le.ResultStorageDescriptor> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.le.ResultStorageDescriptor> CREATOR;
   }
 
   public final class ScanSettings implements android.os.Parcelable {
@@ -1446,7 +1445,7 @@
     method public int describeContents();
     method public boolean isEnabled();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.om.OverlayInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.om.OverlayInfo> CREATOR;
     field public final String category;
     field public final String packageName;
     field public final String targetPackageName;
@@ -1485,7 +1484,7 @@
     method @NonNull public android.graphics.drawable.Drawable loadIcon(@NonNull android.content.pm.PackageManager);
     method @NonNull public CharSequence loadLabel(@NonNull android.content.pm.PackageManager);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.InstantAppInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.InstantAppInfo> CREATOR;
   }
 
   public final class InstantAppIntentFilter implements android.os.Parcelable {
@@ -1494,7 +1493,7 @@
     method public java.util.List<android.content.IntentFilter> getFilters();
     method public String getSplitName();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.InstantAppIntentFilter> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.InstantAppIntentFilter> CREATOR;
   }
 
   public final class InstantAppResolveInfo implements android.os.Parcelable {
@@ -1512,7 +1511,7 @@
     method @Deprecated public int getVersionCode();
     method public boolean shouldLetInstallerDecide();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.InstantAppResolveInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.InstantAppResolveInfo> CREATOR;
   }
 
   public static final class InstantAppResolveInfo.InstantAppDigest implements android.os.Parcelable {
@@ -1521,7 +1520,7 @@
     method public byte[][] getDigestBytes();
     method public int[] getDigestPrefix();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.InstantAppResolveInfo.InstantAppDigest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.InstantAppResolveInfo.InstantAppDigest> CREATOR;
     field public static final android.content.pm.InstantAppResolveInfo.InstantAppDigest UNDEFINED;
   }
 
@@ -1531,7 +1530,7 @@
     method public String getPackageName();
     method public int getStatus();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.IntentFilterVerificationInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.IntentFilterVerificationInfo> CREATOR;
   }
 
   public class PackageInstaller {
@@ -1715,8 +1714,13 @@
     field public boolean handleAllWebDataURI;
   }
 
+  public final class ShortcutInfo implements android.os.Parcelable {
+    method @Nullable public android.app.Person[] getPersons();
+  }
+
   public class ShortcutManager {
     method @NonNull public java.util.List<android.content.pm.ShortcutManager.ShareShortcutInfo> getShareTargets(@NonNull android.content.IntentFilter);
+    method public boolean hasShareTargets(@NonNull String);
   }
 
   public static final class ShortcutManager.ShareShortcutInfo implements android.os.Parcelable {
@@ -1724,13 +1728,13 @@
     method public android.content.pm.ShortcutInfo getShortcutInfo();
     method public android.content.ComponentName getTargetComponent();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.ShortcutManager.ShareShortcutInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.ShortcutManager.ShareShortcutInfo> CREATOR;
   }
 
   public final class SuspendDialogInfo implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.pm.SuspendDialogInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.SuspendDialogInfo> CREATOR;
   }
 
   public static final class SuspendDialogInfo.Builder {
@@ -1774,7 +1778,7 @@
     method @Deprecated public boolean isGranted();
     method @Deprecated public boolean isStandard();
     method @Deprecated public void writeToParcel(android.os.Parcel, int);
-    field @Deprecated public static final android.os.Parcelable.Creator<android.content.pm.permission.RuntimePermissionPresentationInfo> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.content.pm.permission.RuntimePermissionPresentationInfo> CREATOR;
   }
 
 }
@@ -1787,7 +1791,7 @@
     method public android.content.pm.VersionedPackage getVersionRolledBackFrom();
     method public android.content.pm.VersionedPackage getVersionRolledBackTo();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.rollback.PackageRollbackInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.rollback.PackageRollbackInfo> CREATOR;
   }
 
   public final class RollbackInfo implements android.os.Parcelable {
@@ -1798,7 +1802,7 @@
     method public int getRollbackId();
     method public boolean isStaged();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.rollback.RollbackInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.rollback.RollbackInfo> CREATOR;
   }
 
   public final class RollbackManager {
@@ -1868,13 +1872,13 @@
     method public java.time.LocalDate getLocalDate();
     method public float[] getStats();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.display.AmbientBrightnessDayStats> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.display.AmbientBrightnessDayStats> CREATOR;
   }
 
   public final class BrightnessChangeEvent implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessChangeEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessChangeEvent> CREATOR;
     field public final float batteryLevel;
     field public final float brightness;
     field public final long colorSampleDuration;
@@ -1894,28 +1898,28 @@
   public final class BrightnessConfiguration implements android.os.Parcelable {
     method public int describeContents();
     method @Nullable public android.hardware.display.BrightnessCorrection getCorrectionByCategory(int);
-    method @Nullable public android.hardware.display.BrightnessCorrection getCorrectionByPackageName(String);
+    method @Nullable public android.hardware.display.BrightnessCorrection getCorrectionByPackageName(@NonNull String);
     method public android.util.Pair<float[],float[]> getCurve();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessConfiguration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessConfiguration> CREATOR;
   }
 
   public static class BrightnessConfiguration.Builder {
     ctor public BrightnessConfiguration.Builder(float[], float[]);
-    method public android.hardware.display.BrightnessConfiguration.Builder addCorrectionByCategory(int, android.hardware.display.BrightnessCorrection);
-    method public android.hardware.display.BrightnessConfiguration.Builder addCorrectionByPackageName(String, android.hardware.display.BrightnessCorrection);
-    method public android.hardware.display.BrightnessConfiguration build();
+    method @NonNull public android.hardware.display.BrightnessConfiguration.Builder addCorrectionByCategory(int, @NonNull android.hardware.display.BrightnessCorrection);
+    method @NonNull public android.hardware.display.BrightnessConfiguration.Builder addCorrectionByPackageName(@NonNull String, @NonNull android.hardware.display.BrightnessCorrection);
+    method @NonNull public android.hardware.display.BrightnessConfiguration build();
     method public int getMaxCorrectionsByCategory();
     method public int getMaxCorrectionsByPackageName();
-    method public android.hardware.display.BrightnessConfiguration.Builder setDescription(@Nullable String);
+    method @NonNull public android.hardware.display.BrightnessConfiguration.Builder setDescription(@Nullable String);
   }
 
   public final class BrightnessCorrection implements android.os.Parcelable {
-    method public float apply(float);
+    method @FloatRange(from=0.0) public float apply(@FloatRange(from=0.0) float);
     method @NonNull public static android.hardware.display.BrightnessCorrection createScaleAndTranslateLog(float, float);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessCorrection> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessCorrection> CREATOR;
   }
 
   public final class ColorDisplayManager {
@@ -2092,7 +2096,7 @@
     method public boolean isSourceType();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int ADDR_INTERNAL = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.hardware.hdmi.HdmiDeviceInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.hdmi.HdmiDeviceInfo> CREATOR;
     field public static final int DEVICE_AUDIO_SYSTEM = 5; // 0x5
     field public static final int DEVICE_INACTIVE = -1; // 0xffffffff
     field public static final int DEVICE_PLAYBACK = 4; // 0x4
@@ -2112,7 +2116,7 @@
     method public int getPort();
     method public boolean isConnected();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.hdmi.HdmiHotplugEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.hdmi.HdmiHotplugEvent> CREATOR;
   }
 
   public final class HdmiPlaybackClient extends android.hardware.hdmi.HdmiClient {
@@ -2140,7 +2144,7 @@
     method public boolean isCecSupported();
     method public boolean isMhlSupported();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.hdmi.HdmiPortInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.hdmi.HdmiPortInfo> CREATOR;
     field public static final int PORT_INPUT = 0; // 0x0
     field public static final int PORT_OUTPUT = 1; // 0x1
   }
@@ -2303,7 +2307,7 @@
     method public int getToolchainVersion();
     method public String getVendor();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.location.ContextHubInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.location.ContextHubInfo> CREATOR;
   }
 
   public class ContextHubIntentEvent {
@@ -2364,7 +2368,7 @@
     method @Deprecated public void setMsgType(int);
     method @Deprecated public void setVersion(int);
     method @Deprecated public void writeToParcel(android.os.Parcel, int);
-    field @Deprecated public static final android.os.Parcelable.Creator<android.hardware.location.ContextHubMessage> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.hardware.location.ContextHubMessage> CREATOR;
   }
 
   public class ContextHubTransaction<T> {
@@ -2452,7 +2456,7 @@
     method public int getMonitoringType();
     method public int getSourceTechnologies();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.location.GeofenceHardwareMonitorEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.location.GeofenceHardwareMonitorEvent> CREATOR;
   }
 
   public final class GeofenceHardwareRequest {
@@ -2482,7 +2486,7 @@
     method public boolean isReadable();
     method public boolean isWritable();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.location.MemoryRegion> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.location.MemoryRegion> CREATOR;
   }
 
   @Deprecated public class NanoApp implements android.os.Parcelable {
@@ -2511,7 +2515,7 @@
     method @Deprecated public void setOutputEvents(int[]);
     method @Deprecated public void setPublisher(String);
     method @Deprecated public void writeToParcel(android.os.Parcel, int);
-    field @Deprecated public static final android.os.Parcelable.Creator<android.hardware.location.NanoApp> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.hardware.location.NanoApp> CREATOR;
   }
 
   public final class NanoAppBinary implements android.os.Parcelable {
@@ -2530,7 +2534,7 @@
     method public boolean isEncrypted();
     method public boolean isSigned();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.location.NanoAppBinary> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.location.NanoAppBinary> CREATOR;
   }
 
   @Deprecated public class NanoAppFilter implements android.os.Parcelable {
@@ -2539,7 +2543,7 @@
     method @Deprecated public boolean testMatch(android.hardware.location.NanoAppInstanceInfo);
     method @Deprecated public void writeToParcel(android.os.Parcel, int);
     field @Deprecated public static final int APP_ANY = -1; // 0xffffffff
-    field @Deprecated public static final android.os.Parcelable.Creator<android.hardware.location.NanoAppFilter> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.hardware.location.NanoAppFilter> CREATOR;
     field @Deprecated public static final int FLAGS_VERSION_ANY = -1; // 0xffffffff
     field @Deprecated public static final int FLAGS_VERSION_GREAT_THAN = 2; // 0x2
     field @Deprecated public static final int FLAGS_VERSION_LESS_THAN = 4; // 0x4
@@ -2563,7 +2567,7 @@
     method @Deprecated @NonNull public int[] getOutputEvents();
     method @Deprecated public String getPublisher();
     method @Deprecated public void writeToParcel(android.os.Parcel, int);
-    field @Deprecated public static final android.os.Parcelable.Creator<android.hardware.location.NanoAppInstanceInfo> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.hardware.location.NanoAppInstanceInfo> CREATOR;
   }
 
   public final class NanoAppMessage implements android.os.Parcelable {
@@ -2575,7 +2579,7 @@
     method public long getNanoAppId();
     method public boolean isBroadcastMessage();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.location.NanoAppMessage> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.location.NanoAppMessage> CREATOR;
   }
 
   public final class NanoAppState implements android.os.Parcelable {
@@ -2585,7 +2589,7 @@
     method public long getNanoAppVersion();
     method public boolean isEnabled();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.location.NanoAppState> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.location.NanoAppState> CREATOR;
   }
 
 }
@@ -2598,7 +2602,7 @@
     method public int getType();
     method @NonNull public java.util.Map<java.lang.String,java.lang.String> getVendorInfo();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.Announcement> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.Announcement> CREATOR;
     field public static final int TYPE_EMERGENCY = 1; // 0x1
     field public static final int TYPE_EVENT = 6; // 0x6
     field public static final int TYPE_MISC = 8; // 0x8
@@ -2633,7 +2637,7 @@
     method @NonNull public java.util.Set<java.lang.Integer> getIdentifierTypes();
     method @NonNull public java.util.Set<android.hardware.radio.ProgramSelector.Identifier> getIdentifiers();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.ProgramList.Filter> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.ProgramList.Filter> CREATOR;
   }
 
   public abstract static class ProgramList.ListCallback {
@@ -2659,7 +2663,7 @@
     method @Deprecated @NonNull public long[] getVendorIds();
     method @NonNull public android.hardware.radio.ProgramSelector withSecondaryPreferred(@NonNull android.hardware.radio.ProgramSelector.Identifier);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.ProgramSelector> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.ProgramSelector> CREATOR;
     field public static final int IDENTIFIER_TYPE_AMFM_FREQUENCY = 1; // 0x1
     field public static final int IDENTIFIER_TYPE_DAB_ENSEMBLE = 6; // 0x6
     field public static final int IDENTIFIER_TYPE_DAB_FREQUENCY = 8; // 0x8
@@ -2698,7 +2702,7 @@
     method @android.hardware.radio.ProgramSelector.IdentifierType public int getType();
     method public long getValue();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.ProgramSelector.Identifier> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.ProgramSelector.Identifier> CREATOR;
   }
 
   @IntDef(prefix={"IDENTIFIER_TYPE_"}, value={android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_INVALID, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_AMFM_FREQUENCY, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_RDS_PI, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_HD_STATION_ID_EXT, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_HD_SUBCHANNEL, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_HD_STATION_NAME, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_DAB_SID_EXT, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_DAB_SIDECC, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_DAB_ENSEMBLE, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_DAB_SCID, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_DAB_FREQUENCY, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_DRMO_SERVICE_ID, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_DRMO_FREQUENCY, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_DRMO_MODULATION, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_SXM_SERVICE_ID, android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_SXM_CHANNEL}) @IntRange(from=android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_VENDOR_START, to=android.hardware.radio.ProgramSelector.IDENTIFIER_TYPE_VENDOR_END) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface ProgramSelector.IdentifierType {
@@ -2747,7 +2751,7 @@
 
   public static class RadioManager.AmBandConfig extends android.hardware.radio.RadioManager.BandConfig {
     method public boolean getStereo();
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.AmBandConfig> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.AmBandConfig> CREATOR;
   }
 
   public static class RadioManager.AmBandConfig.Builder {
@@ -2759,7 +2763,7 @@
 
   public static class RadioManager.AmBandDescriptor extends android.hardware.radio.RadioManager.BandDescriptor {
     method public boolean isStereoSupported();
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.AmBandDescriptor> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.AmBandDescriptor> CREATOR;
   }
 
   @IntDef(prefix={"BAND_"}, value={android.hardware.radio.RadioManager.BAND_INVALID, android.hardware.radio.RadioManager.BAND_AM, android.hardware.radio.RadioManager.BAND_FM, android.hardware.radio.RadioManager.BAND_AM_HD, android.hardware.radio.RadioManager.BAND_FM_HD}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface RadioManager.Band {
@@ -2773,7 +2777,7 @@
     method public int getType();
     method public int getUpperLimit();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.BandConfig> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.BandConfig> CREATOR;
   }
 
   public static class RadioManager.BandDescriptor implements android.os.Parcelable {
@@ -2786,7 +2790,7 @@
     method public boolean isAmBand();
     method public boolean isFmBand();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.BandDescriptor> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.BandDescriptor> CREATOR;
   }
 
   public static class RadioManager.FmBandConfig extends android.hardware.radio.RadioManager.BandConfig {
@@ -2795,7 +2799,7 @@
     method public boolean getRds();
     method public boolean getStereo();
     method public boolean getTa();
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.FmBandConfig> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.FmBandConfig> CREATOR;
   }
 
   public static class RadioManager.FmBandConfig.Builder {
@@ -2815,7 +2819,7 @@
     method public boolean isRdsSupported();
     method public boolean isStereoSupported();
     method public boolean isTaSupported();
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.FmBandDescriptor> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.FmBandDescriptor> CREATOR;
   }
 
   public static class RadioManager.ModuleProperties implements android.os.Parcelable {
@@ -2838,7 +2842,7 @@
     method public boolean isProgramIdentifierSupported(@android.hardware.radio.ProgramSelector.IdentifierType int);
     method public boolean isProgramTypeSupported(@android.hardware.radio.ProgramSelector.ProgramType int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.ModuleProperties> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.ModuleProperties> CREATOR;
   }
 
   public static class RadioManager.ProgramInfo implements android.os.Parcelable {
@@ -2860,7 +2864,7 @@
     method public boolean isTrafficProgram();
     method public boolean isTuned();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.ProgramInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.RadioManager.ProgramInfo> CREATOR;
   }
 
   public final class RadioMetadata implements android.os.Parcelable {
@@ -2873,7 +2877,7 @@
     method public java.util.Set<java.lang.String> keySet();
     method public int size();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.RadioMetadata> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.RadioMetadata> CREATOR;
     field public static final String METADATA_KEY_ALBUM = "android.hardware.radio.metadata.ALBUM";
     field public static final String METADATA_KEY_ART = "android.hardware.radio.metadata.ART";
     field public static final String METADATA_KEY_ARTIST = "android.hardware.radio.metadata.ARTIST";
@@ -2911,7 +2915,7 @@
     method public int getTimezoneOffsetMinutes();
     method public long getUtcEpochSeconds();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.radio.RadioMetadata.Clock> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.radio.RadioMetadata.Clock> CREATOR;
   }
 
   public abstract class RadioTuner {
@@ -3011,7 +3015,7 @@
     method public boolean isConnected();
     method public boolean isRoleCombinationSupported(int, int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.usb.UsbPortStatus> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.usb.UsbPortStatus> CREATOR;
     field public static final int DATA_ROLE_DEVICE = 2; // 0x2
     field public static final int DATA_ROLE_HOST = 1; // 0x1
     field public static final int DATA_ROLE_NONE = 0; // 0x0
@@ -3044,7 +3048,7 @@
     method public long getToaGpsNanosecondsOfWeek();
     method public double getVerticalPositionUncertaintyMeters();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.location.GnssMeasurementCorrections> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.GnssMeasurementCorrections> CREATOR;
   }
 
   public static final class GnssMeasurementCorrections.Builder {
@@ -3066,7 +3070,7 @@
     method public double getLatitudeDegrees();
     method public double getLongitudeDegrees();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.location.GnssReflectingPlane> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.GnssReflectingPlane> CREATOR;
   }
 
   public static final class GnssReflectingPlane.Builder {
@@ -3093,7 +3097,7 @@
     method public boolean hasReflectingPlane();
     method public boolean hasValidSatelliteLineOfSight();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.location.GnssSingleSatCorrection> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.GnssSingleSatCorrection> CREATOR;
     field public static final int HAS_EXCESS_PATH_LENGTH_MASK = 2; // 0x2
     field public static final int HAS_EXCESS_PATH_LENGTH_UNC_MASK = 4; // 0x4
     field public static final int HAS_PROB_SAT_IS_LOS_MASK = 1; // 0x1
@@ -3150,7 +3154,7 @@
     method public void setTimeUncertaintyInNs(double);
     method public void setType(byte);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.location.GpsClock> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.GpsClock> CREATOR;
     field public static final byte TYPE_GPS_TIME = 2; // 0x2
     field public static final byte TYPE_LOCAL_HW_TIME = 1; // 0x1
     field public static final byte TYPE_UNKNOWN = 0; // 0x0
@@ -3262,7 +3266,7 @@
     field public static final short ADR_STATE_RESET = 2; // 0x2
     field public static final short ADR_STATE_UNKNOWN = 0; // 0x0
     field public static final short ADR_STATE_VALID = 1; // 0x1
-    field public static final android.os.Parcelable.Creator<android.location.GpsMeasurement> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.GpsMeasurement> CREATOR;
     field public static final byte LOSS_OF_LOCK_CYCLE_SLIP = 2; // 0x2
     field public static final byte LOSS_OF_LOCK_OK = 1; // 0x1
     field public static final byte LOSS_OF_LOCK_UNKNOWN = 0; // 0x0
@@ -3283,7 +3287,7 @@
     method @NonNull public android.location.GpsClock getClock();
     method @NonNull public java.util.Collection<android.location.GpsMeasurement> getMeasurements();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.location.GpsMeasurementsEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.GpsMeasurementsEvent> CREATOR;
     field public static final int STATUS_GPS_LOCATION_DISABLED = 2; // 0x2
     field public static final int STATUS_NOT_SUPPORTED = 0; // 0x0
     field public static final int STATUS_READY = 1; // 0x1
@@ -3311,7 +3315,7 @@
     method public void setSubmessageId(short);
     method public void setType(byte);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.location.GpsNavigationMessage> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.GpsNavigationMessage> CREATOR;
     field public static final short STATUS_PARITY_PASSED = 1; // 0x1
     field public static final short STATUS_PARITY_REBUILT = 2; // 0x2
     field public static final short STATUS_UNKNOWN = 0; // 0x0
@@ -3327,7 +3331,7 @@
     method public int describeContents();
     method @NonNull public android.location.GpsNavigationMessage getNavigationMessage();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.location.GpsNavigationMessageEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.GpsNavigationMessageEvent> CREATOR;
     field public static int STATUS_GPS_LOCATION_DISABLED;
     field public static int STATUS_NOT_SUPPORTED;
     field public static int STATUS_READY;
@@ -3400,7 +3404,7 @@
     field public static final int ACCURACY_BLOCK = 102; // 0x66
     field public static final int ACCURACY_CITY = 104; // 0x68
     field public static final int ACCURACY_FINE = 100; // 0x64
-    field public static final android.os.Parcelable.Creator<android.location.LocationRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.LocationRequest> CREATOR;
     field public static final int POWER_HIGH = 203; // 0xcb
     field public static final int POWER_LOW = 201; // 0xc9
     field public static final int POWER_NONE = 200; // 0xc8
@@ -3436,7 +3440,7 @@
     method public int getLossReceived();
     method @NonNull public String getPackageName();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.AudioFocusInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.AudioFocusInfo> CREATOR;
   }
 
   public final class AudioFocusRequest {
@@ -3451,15 +3455,23 @@
     method @Deprecated public int abandonAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener, android.media.AudioAttributes);
     method public void clearAudioServerStateCallback();
     method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public int dispatchAudioFocusChange(@NonNull android.media.AudioFocusInfo, int, @NonNull android.media.audiopolicy.AudioPolicy);
+    method @NonNull @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public android.media.audiopolicy.AudioProductStrategies getAudioProductStrategies();
+    method @NonNull @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public android.media.audiopolicy.AudioVolumeGroups getAudioVolumeGroups();
+    method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public int getMaxVolumeIndexForAttributes(@NonNull android.media.AudioAttributes);
+    method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public int getMinVolumeIndexForAttributes(@NonNull android.media.AudioAttributes);
+    method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public int getVolumeIndexForAttributes(@NonNull android.media.AudioAttributes);
     method public boolean isAudioServerRunning();
     method public boolean isHdmiSystemAudioSupported();
     method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public int registerAudioPolicy(@NonNull android.media.audiopolicy.AudioPolicy);
+    method public void registerVolumeGroupCallback(@NonNull java.util.concurrent.Executor, @NonNull android.media.AudioManager.VolumeGroupCallback);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int requestAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener, @NonNull android.media.AudioAttributes, int, int) throws java.lang.IllegalArgumentException;
     method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.MODIFY_PHONE_STATE, android.Manifest.permission.MODIFY_AUDIO_ROUTING}) public int requestAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener, @NonNull android.media.AudioAttributes, int, int, android.media.audiopolicy.AudioPolicy) throws java.lang.IllegalArgumentException;
     method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public int requestAudioFocus(@NonNull android.media.AudioFocusRequest, @Nullable android.media.audiopolicy.AudioPolicy);
     method public void setAudioServerStateCallback(@NonNull java.util.concurrent.Executor, @NonNull android.media.AudioManager.AudioServerStateCallback);
     method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public void setFocusRequestResult(@NonNull android.media.AudioFocusInfo, int, @NonNull android.media.audiopolicy.AudioPolicy);
+    method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public void setVolumeIndexForAttributes(@NonNull android.media.AudioAttributes, int, int);
     method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public void unregisterAudioPolicyAsync(@NonNull android.media.audiopolicy.AudioPolicy);
+    method public void unregisterVolumeGroupCallback(@NonNull android.media.AudioManager.VolumeGroupCallback);
     field public static final int AUDIOFOCUS_FLAG_DELAY_OK = 1; // 0x1
     field public static final int AUDIOFOCUS_FLAG_LOCK = 4; // 0x4
     field public static final int AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS = 2; // 0x2
@@ -3473,6 +3485,11 @@
     method public void onAudioServerUp();
   }
 
+  public abstract static class AudioManager.VolumeGroupCallback {
+    ctor public AudioManager.VolumeGroupCallback();
+    method public void onAudioVolumeGroupChanged(int, int);
+  }
+
   public final class AudioPlaybackConfiguration implements android.os.Parcelable {
     method public int getClientPid();
     method public int getClientUid();
@@ -3594,10 +3611,10 @@
     method public int detachMixes(@NonNull java.util.List<android.media.audiopolicy.AudioMix>);
     method public int getFocusDuckingBehavior();
     method public int getStatus();
-    method public int removeUidDeviceAffinity(int);
+    method public boolean removeUidDeviceAffinity(int);
     method public int setFocusDuckingBehavior(int) throws java.lang.IllegalArgumentException, java.lang.IllegalStateException;
     method public void setRegistration(String);
-    method public int setUidDeviceAffinity(int, @NonNull java.util.List<android.media.AudioDeviceInfo>);
+    method public boolean setUidDeviceAffinity(int, @NonNull java.util.List<android.media.AudioDeviceInfo>);
     method public String toLogFriendlyString();
     field public static final int FOCUS_POLICY_DUCKING_DEFAULT = 0; // 0x0
     field public static final int FOCUS_POLICY_DUCKING_IN_APP = 0; // 0x0
@@ -3621,6 +3638,7 @@
   }
 
   public abstract static class AudioPolicy.AudioPolicyVolumeCallback {
+    ctor public AudioPolicy.AudioPolicyVolumeCallback();
     method public void onVolumeAdjustment(int);
   }
 
@@ -3642,10 +3660,13 @@
     method @NonNull public android.media.AudioAttributes getAudioAttributesForProductStrategy(@NonNull android.media.audiopolicy.AudioProductStrategy);
     method @Nullable public android.media.audiopolicy.AudioProductStrategy getById(int);
     method public int getLegacyStreamTypeForAudioAttributes(@NonNull android.media.AudioAttributes);
+    method @Nullable public android.media.audiopolicy.AudioProductStrategy getProductStrategyForAudioAttributes(@NonNull android.media.AudioAttributes);
+    method public int getVolumeGroupIdForAttributes(@NonNull android.media.AudioAttributes);
+    method public int getVolumeGroupIdForLegacyStreamType(int);
     method public java.util.Iterator<android.media.audiopolicy.AudioProductStrategy> iterator();
     method public int size();
     method public void writeToParcel(@NonNull android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.audiopolicy.AudioProductStrategies> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.audiopolicy.AudioProductStrategies> CREATOR;
   }
 
   public final class AudioProductStrategy implements android.os.Parcelable {
@@ -3654,7 +3675,28 @@
     method public int getId();
     method @NonNull public String name();
     method public void writeToParcel(@NonNull android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.audiopolicy.AudioProductStrategy> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.audiopolicy.AudioProductStrategy> CREATOR;
+  }
+
+  public final class AudioVolumeGroup implements android.os.Parcelable {
+    method public int describeContents();
+    method public java.util.List<android.media.AudioAttributes> getAudioAttributes();
+    method public int getId();
+    method @NonNull public int[] getLegacyStreamTypes();
+    method @NonNull public String name();
+    method public void writeToParcel(@NonNull android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.media.audiopolicy.AudioVolumeGroup> CREATOR;
+  }
+
+  public final class AudioVolumeGroups implements java.lang.Iterable<android.media.audiopolicy.AudioVolumeGroup> android.os.Parcelable {
+    ctor public AudioVolumeGroups();
+    method public int describeContents();
+    method @Nullable public android.media.audiopolicy.AudioVolumeGroup getById(int);
+    method public java.util.Iterator<android.media.audiopolicy.AudioVolumeGroup> iterator();
+    method public int size();
+    method public void writeToParcel(@NonNull android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.media.audiopolicy.AudioVolumeGroups> CREATOR;
+    field public static final int DEFAULT_VOLUME_GROUP = -1; // 0xffffffff
   }
 
 }
@@ -3789,7 +3831,7 @@
     field public static final int CABLE_CONNECTION_STATUS_CONNECTED = 1; // 0x1
     field public static final int CABLE_CONNECTION_STATUS_DISCONNECTED = 2; // 0x2
     field public static final int CABLE_CONNECTION_STATUS_UNKNOWN = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.media.tv.TvInputHardwareInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.tv.TvInputHardwareInfo> CREATOR;
     field public static final int TV_INPUT_TYPE_COMPONENT = 6; // 0x6
     field public static final int TV_INPUT_TYPE_COMPOSITE = 3; // 0x3
     field public static final int TV_INPUT_TYPE_DISPLAY_PORT = 10; // 0xa
@@ -3897,7 +3939,7 @@
     method public int getStreamId();
     method public int getType();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.tv.TvStreamConfig> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.tv.TvStreamConfig> CREATOR;
     field public static final int STREAM_TYPE_BUFFER_PRODUCER = 2; // 0x2
     field public static final int STREAM_TYPE_INDEPENDENT_VIDEO_SOURCE = 1; // 0x1
   }
@@ -4094,7 +4136,7 @@
     ctor public NetworkKey(android.net.WifiKey);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.NetworkKey> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.NetworkKey> CREATOR;
     field public static final int TYPE_WIFI = 1; // 0x1
     field public final int type;
     field public final android.net.WifiKey wifiKey;
@@ -4145,7 +4187,7 @@
     method public byte lookupScore(int);
     method public byte lookupScore(int, boolean);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.RssiCurve> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.RssiCurve> CREATOR;
     field public final int activeNetworkRssiBoost;
     field public final int bucketWidth;
     field public final byte[] rssiBuckets;
@@ -4162,7 +4204,7 @@
     field public static final String ATTRIBUTES_KEY_BADGING_CURVE = "android.net.attributes.key.BADGING_CURVE";
     field public static final String ATTRIBUTES_KEY_HAS_CAPTIVE_PORTAL = "android.net.attributes.key.HAS_CAPTIVE_PORTAL";
     field public static final String ATTRIBUTES_KEY_RANKING_SCORE_OFFSET = "android.net.attributes.key.RANKING_SCORE_OFFSET";
-    field public static final android.os.Parcelable.Creator<android.net.ScoredNetwork> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.ScoredNetwork> CREATOR;
     field @Nullable public final android.os.Bundle attributes;
     field public final boolean meteredHint;
     field public final android.net.NetworkKey networkKey;
@@ -4184,7 +4226,7 @@
     method public void setGateway(java.net.InetAddress);
     method public void setIpAddress(android.net.LinkAddress);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.StaticIpConfiguration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.StaticIpConfiguration> CREATOR;
   }
 
   public class TrafficStats {
@@ -4208,7 +4250,7 @@
     ctor public WifiKey(String, String);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.WifiKey> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.WifiKey> CREATOR;
     field public final String bssid;
     field public final String ssid;
   }
@@ -4551,7 +4593,7 @@
     ctor @Deprecated public RttManager.ResponderConfig();
     method @Deprecated public int describeContents();
     method @Deprecated public void writeToParcel(android.os.Parcel, int);
-    field @Deprecated public static final android.os.Parcelable.Creator<android.net.wifi.RttManager.ResponderConfig> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.RttManager.ResponderConfig> CREATOR;
     field @Deprecated public int centerFreq0;
     field @Deprecated public int centerFreq1;
     field @Deprecated public int channelWidth;
@@ -4745,7 +4787,7 @@
     ctor public WifiNetworkConnectionStatistics(android.net.wifi.WifiNetworkConnectionStatistics);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.WifiNetworkConnectionStatistics> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.WifiNetworkConnectionStatistics> CREATOR;
     field public int numConnection;
     field public int numUsage;
   }
@@ -4844,7 +4886,8 @@
     ctor public WifiScanner.ScanSettings();
     field public int band;
     field public android.net.wifi.WifiScanner.ChannelSpec[] channels;
-    field @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE) public boolean ignoreLocationSettings;
+    field public boolean hideFromAppOps;
+    field public boolean ignoreLocationSettings;
     field public int maxPeriodInMs;
     field public int maxScansToCache;
     field public int numBssidsPerScan;
@@ -4871,7 +4914,7 @@
   public final class WifiUsabilityStatsEntry implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.WifiUsabilityStatsEntry> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.WifiUsabilityStatsEntry> CREATOR;
     field public static final int PROBE_STATUS_FAILURE = 3; // 0x3
     field public static final int PROBE_STATUS_NO_PROBE = 1; // 0x1
     field public static final int PROBE_STATUS_SUCCESS = 2; // 0x2
@@ -4926,7 +4969,7 @@
     method public String getFriendlyName();
     method public android.net.Uri getServerUri();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.OsuProvider> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.hotspot2.OsuProvider> CREATOR;
   }
 
   public abstract class ProvisioningCallback {
@@ -4996,7 +5039,7 @@
     field public static final int CHANNEL_WIDTH_40MHZ = 1; // 0x1
     field public static final int CHANNEL_WIDTH_80MHZ = 2; // 0x2
     field public static final int CHANNEL_WIDTH_80MHZ_PLUS_MHZ = 4; // 0x4
-    field public static final android.os.Parcelable.Creator<android.net.wifi.rtt.ResponderConfig> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.rtt.ResponderConfig> CREATOR;
     field public static final int PREAMBLE_HT = 1; // 0x1
     field public static final int PREAMBLE_LEGACY = 0; // 0x0
     field public static final int PREAMBLE_VHT = 2; // 0x2
@@ -5078,7 +5121,7 @@
     method public boolean getForceBackgroundCheck();
     method public int getLocationMode();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.BatterySaverPolicyConfig> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.BatterySaverPolicyConfig> CREATOR;
   }
 
   public static final class BatterySaverPolicyConfig.Builder {
@@ -5128,6 +5171,7 @@
     method public void onError(int);
     method public void onFinished();
     method public void onProgress(float);
+    field public static final int BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS = 5; // 0x5
     field public static final int BUGREPORT_ERROR_INVALID_INPUT = 1; // 0x1
     field public static final int BUGREPORT_ERROR_RUNTIME = 2; // 0x2
     field public static final int BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT = 4; // 0x4
@@ -5166,11 +5210,11 @@
   }
 
   public class Environment {
-    method public static java.io.File getOdmDirectory();
-    method public static java.io.File getOemDirectory();
-    method public static java.io.File getProductDirectory();
-    method public static java.io.File getProductServicesDirectory();
-    method public static java.io.File getVendorDirectory();
+    method @NonNull public static java.io.File getOdmDirectory();
+    method @NonNull public static java.io.File getOemDirectory();
+    method @NonNull public static java.io.File getProductDirectory();
+    method @NonNull public static java.io.File getProductServicesDirectory();
+    method @NonNull public static java.io.File getVendorDirectory();
   }
 
   public class HidlSupport {
@@ -5338,7 +5382,7 @@
     method public long getPrivacyPolicy();
     method public long getTimestamp();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.IncidentManager.IncidentReport> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.IncidentManager.IncidentReport> CREATOR;
   }
 
   public static class IncidentManager.PendingReport {
@@ -5362,7 +5406,7 @@
     method public void setAll(boolean);
     method public void setPrivacyPolicy(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.IncidentReportArgs> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.IncidentReportArgs> CREATOR;
   }
 
   public final class LocaleList implements android.os.Parcelable {
@@ -5416,7 +5460,7 @@
     method public int describeContents();
     method public void sendResult(@Nullable android.os.Bundle);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.RemoteCallback> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.RemoteCallback> CREATOR;
   }
 
   public static interface RemoteCallback.OnResultListener {
@@ -5442,7 +5486,7 @@
     method public boolean isValueType(int);
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int BOOLEAN_VALUE_TYPE = 5; // 0x5
-    field public static final android.os.Parcelable.Creator<android.os.StatsDimensionsValue> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.StatsDimensionsValue> CREATOR;
     field public static final int FLOAT_VALUE_TYPE = 6; // 0x6
     field public static final int INT_VALUE_TYPE = 3; // 0x3
     field public static final int LONG_VALUE_TYPE = 4; // 0x4
@@ -5571,7 +5615,7 @@
     method public android.os.UserHandle getUserHandle();
     method @android.os.UserManager.UserRestrictionSource public int getUserRestrictionSource();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.UserManager.EnforcingUser> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.UserManager.EnforcingUser> CREATOR;
   }
 
   @IntDef(flag=true, prefix={"RESTRICTION_"}, value={android.os.UserManager.RESTRICTION_NOT_SET, android.os.UserManager.RESTRICTION_SOURCE_SYSTEM, android.os.UserManager.RESTRICTION_SOURCE_DEVICE_OWNER, android.os.UserManager.RESTRICTION_SOURCE_PROFILE_OWNER}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface UserManager.UserRestrictionSource {
@@ -5588,7 +5632,7 @@
     method public String getAttributionTag();
     method public int getAttributionUid();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.WorkSource.WorkChain> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.WorkSource.WorkChain> CREATOR;
   }
 
 }
@@ -5654,7 +5698,7 @@
     method public boolean isGranted();
     method public boolean isStandard();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.permission.RuntimePermissionPresentationInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.permission.RuntimePermissionPresentationInfo> CREATOR;
   }
 
   public final class RuntimePermissionUsageInfo implements android.os.Parcelable {
@@ -5663,7 +5707,7 @@
     method public int getAppAccessCount();
     method @NonNull public CharSequence getName();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.permission.RuntimePermissionUsageInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.permission.RuntimePermissionUsageInfo> CREATOR;
   }
 
 }
@@ -5717,7 +5761,7 @@
     method public int describeContents();
     method @NonNull public android.content.ComponentName getComponentName();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.printservice.PrintServiceInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.printservice.PrintServiceInfo> CREATOR;
   }
 
 }
@@ -5734,7 +5778,7 @@
     method public CharSequence getPackageName();
     method public boolean recommendsMultiVendorService();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.printservice.recommendation.RecommendationInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.printservice.recommendation.RecommendationInfo> CREATOR;
   }
 
   public abstract class RecommendationService extends android.app.Service {
@@ -5782,28 +5826,22 @@
 
   public final class DeviceConfig {
     method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static void addOnPropertyChangedListener(@NonNull String, @NonNull java.util.concurrent.Executor, @NonNull android.provider.DeviceConfig.OnPropertyChangedListener);
+    method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static boolean getBoolean(String, String, boolean);
+    method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static float getFloat(String, String, float);
+    method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static int getInt(String, String, int);
+    method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static long getLong(String, String, long);
     method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static String getProperty(String, String);
+    method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static String getString(String, String, String);
     method public static void removeOnPropertyChangedListener(android.provider.DeviceConfig.OnPropertyChangedListener);
     method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static void resetToDefaults(int, @Nullable String);
     method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static boolean setProperty(String, String, String, boolean);
+    field public static final String NAMESPACE_ACTIVITY_MANAGER = "activity_manager";
     field public static final String NAMESPACE_AUTOFILL = "autofill";
     field public static final String NAMESPACE_CONTENT_CAPTURE = "content_capture";
     field public static final String NAMESPACE_GAME_DRIVER = "game_driver";
     field public static final String NAMESPACE_INPUT_NATIVE_BOOT = "input_native_boot";
     field public static final String NAMESPACE_NETD_NATIVE = "netd_native";
-  }
-
-  public static interface DeviceConfig.ActivityManager {
-    field public static final String KEY_COMPACT_ACTION_1 = "compact_action_1";
-    field public static final String KEY_COMPACT_ACTION_2 = "compact_action_2";
-    field public static final String KEY_COMPACT_STATSD_SAMPLE_RATE = "compact_statsd_sample_rate";
-    field public static final String KEY_COMPACT_THROTTLE_1 = "compact_throttle_1";
-    field public static final String KEY_COMPACT_THROTTLE_2 = "compact_throttle_2";
-    field public static final String KEY_COMPACT_THROTTLE_3 = "compact_throttle_3";
-    field public static final String KEY_COMPACT_THROTTLE_4 = "compact_throttle_4";
-    field public static final String KEY_MAX_CACHED_PROCESSES = "max_cached_processes";
-    field public static final String KEY_USE_COMPACTION = "use_compaction";
-    field public static final String NAMESPACE = "activity_manager";
+    field public static final String NAMESPACE_SYSTEMUI = "systemui";
   }
 
   public static interface DeviceConfig.ActivityManagerNativeBoot {
@@ -5833,14 +5871,6 @@
     field public static final String NAMESPACE = "media_native";
   }
 
-  public static interface DeviceConfig.NotificationAssistant {
-    field public static final String GENERATE_ACTIONS = "generate_actions";
-    field public static final String GENERATE_REPLIES = "generate_replies";
-    field public static final String MAX_MESSAGES_TO_EXTRACT = "max_messages_to_extract";
-    field public static final String MAX_SUGGESTIONS = "max_suggestions";
-    field public static final String NAMESPACE = "notification_assistant";
-  }
-
   public static interface DeviceConfig.OnPropertyChangedListener {
     method public void onPropertyChanged(String, String, String);
   }
@@ -6174,7 +6204,7 @@
     method @NonNull public byte[] getSecret();
     method public int getUserSecretType();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.security.keystore.recovery.KeyChainProtectionParams> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.security.keystore.recovery.KeyChainProtectionParams> CREATOR;
     field public static final int TYPE_LOCKSCREEN = 100; // 0x64
     field public static final int UI_FORMAT_PASSWORD = 2; // 0x2
     field public static final int UI_FORMAT_PATTERN = 3; // 0x3
@@ -6201,7 +6231,7 @@
     method @NonNull public java.security.cert.CertPath getTrustedHardwareCertPath();
     method @NonNull public java.util.List<android.security.keystore.recovery.WrappedApplicationKey> getWrappedApplicationKeys();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.security.keystore.recovery.KeyChainSnapshot> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.security.keystore.recovery.KeyChainSnapshot> CREATOR;
   }
 
   public final class KeyDerivationParams implements android.os.Parcelable {
@@ -6214,7 +6244,7 @@
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int ALGORITHM_SCRYPT = 2; // 0x2
     field public static final int ALGORITHM_SHA256 = 1; // 0x1
-    field public static final android.os.Parcelable.Creator<android.security.keystore.recovery.KeyDerivationParams> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.security.keystore.recovery.KeyDerivationParams> CREATOR;
   }
 
   public class LockScreenRequiredException extends java.security.GeneralSecurityException {
@@ -6262,7 +6292,7 @@
     method @NonNull public byte[] getEncryptedKeyMaterial();
     method @Nullable public byte[] getMetadata();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.security.keystore.recovery.WrappedApplicationKey> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.security.keystore.recovery.WrappedApplicationKey> CREATOR;
   }
 
   public static class WrappedApplicationKey.Builder {
@@ -6363,9 +6393,8 @@
 
   public static final class FillResponse.Builder {
     ctor public FillResponse.Builder();
-    method public android.service.autofill.augmented.FillResponse build();
-    method public android.service.autofill.augmented.FillResponse.Builder setFillWindow(@NonNull android.service.autofill.augmented.FillWindow);
-    method public android.service.autofill.augmented.FillResponse.Builder setIgnoredIds(@NonNull java.util.List<android.view.autofill.AutofillId>);
+    method @NonNull public android.service.autofill.augmented.FillResponse build();
+    method @NonNull public android.service.autofill.augmented.FillResponse.Builder setFillWindow(@NonNull android.service.autofill.augmented.FillWindow);
   }
 
   public final class FillWindow implements java.lang.AutoCloseable {
@@ -6413,11 +6442,11 @@
 
   public final class SnapshotData implements android.os.Parcelable {
     method public int describeContents();
-    method public android.app.assist.AssistContent getAssistContent();
-    method public android.os.Bundle getAssistData();
-    method public android.app.assist.AssistStructure getAssistStructure();
+    method @Nullable public android.app.assist.AssistContent getAssistContent();
+    method @NonNull public android.os.Bundle getAssistData();
+    method @NonNull public android.app.assist.AssistStructure getAssistStructure();
     method public void writeToParcel(@NonNull android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.contentcapture.SnapshotData> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.contentcapture.SnapshotData> CREATOR;
   }
 
 }
@@ -6444,7 +6473,7 @@
     method public int getResolvableErrors();
     method public int getResult();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.euicc.DownloadSubscriptionResult> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.euicc.DownloadSubscriptionResult> CREATOR;
   }
 
   public final class EuiccProfileInfo implements android.os.Parcelable {
@@ -6461,7 +6490,7 @@
     method public boolean hasPolicyRule(@android.service.euicc.EuiccProfileInfo.PolicyRule int);
     method public boolean hasPolicyRules();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.euicc.EuiccProfileInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.euicc.EuiccProfileInfo> CREATOR;
     field public static final int POLICY_RULE_DELETE_AFTER_DISABLING = 4; // 0x4
     field public static final int POLICY_RULE_DO_NOT_DELETE = 2; // 0x2
     field public static final int POLICY_RULE_DO_NOT_DISABLE = 1; // 0x1
@@ -6552,7 +6581,7 @@
     method @Nullable public java.util.List<android.telephony.euicc.DownloadableSubscription> getDownloadableSubscriptions();
     method public int getResult();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.euicc.GetDefaultDownloadableSubscriptionListResult> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.euicc.GetDefaultDownloadableSubscriptionListResult> CREATOR;
   }
 
   public final class GetDownloadableSubscriptionMetadataResult implements android.os.Parcelable {
@@ -6561,7 +6590,7 @@
     method @Nullable public android.telephony.euicc.DownloadableSubscription getDownloadableSubscription();
     method public int getResult();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.euicc.GetDownloadableSubscriptionMetadataResult> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.euicc.GetDownloadableSubscriptionMetadataResult> CREATOR;
   }
 
   public final class GetEuiccProfileInfoListResult implements android.os.Parcelable {
@@ -6571,7 +6600,7 @@
     method @Nullable public java.util.List<android.service.euicc.EuiccProfileInfo> getProfiles();
     method public int getResult();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.euicc.GetEuiccProfileInfoListResult> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.euicc.GetEuiccProfileInfoListResult> CREATOR;
   }
 
 }
@@ -6597,7 +6626,7 @@
     method public CharSequence getExplanation();
     method public String getId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.notification.SnoozeCriterion> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.notification.SnoozeCriterion> CREATOR;
   }
 
 }
@@ -6669,7 +6698,7 @@
     method public void setSelectProbability(float);
     method public void setTimeSpentScore(float);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.resolver.ResolverTarget> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.resolver.ResolverTarget> CREATOR;
   }
 
 }
@@ -6685,7 +6714,7 @@
     method public CharSequence getSummary();
     method public CharSequence getTitle();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.settings.suggestions.Suggestion> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.settings.suggestions.Suggestion> CREATOR;
     field public static final int FLAG_HAS_BUTTON = 1; // 0x1
   }
 
@@ -6799,7 +6828,7 @@
     method @Deprecated public int getSupportedRouteMask();
     method @Deprecated public boolean isMuted();
     method @Deprecated public void writeToParcel(android.os.Parcel, int);
-    field @Deprecated public static final android.os.Parcelable.Creator<android.telecom.AudioState> CREATOR;
+    field @Deprecated @NonNull public static final android.os.Parcelable.Creator<android.telecom.AudioState> CREATOR;
     field @Deprecated public static final int ROUTE_BLUETOOTH = 2; // 0x2
     field @Deprecated public static final int ROUTE_EARPIECE = 1; // 0x1
     field @Deprecated public static final int ROUTE_SPEAKER = 8; // 0x8
@@ -6857,7 +6886,7 @@
     field public static final int CALLTYPE_OUTGOING = 2; // 0x2
     field public static final int CALLTYPE_UNKNOWN = 0; // 0x0
     field public static final int CDMA_PHONE = 1; // 0x1
-    field public static final android.os.Parcelable.Creator<android.telecom.ParcelableCallAnalytics> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.ParcelableCallAnalytics> CREATOR;
     field public static final int GSM_PHONE = 2; // 0x2
     field public static final int IMS_PHONE = 4; // 0x4
     field public static final long MILLIS_IN_1_SECOND = 1000L; // 0x3e8L
@@ -6881,7 +6910,7 @@
     field public static final int BLOCK_CHECK_FINISHED = 105; // 0x69
     field public static final int BLOCK_CHECK_INITIATED = 104; // 0x68
     field public static final int CONFERENCE_WITH = 300; // 0x12c
-    field public static final android.os.Parcelable.Creator<android.telecom.ParcelableCallAnalytics.AnalyticsEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.ParcelableCallAnalytics.AnalyticsEvent> CREATOR;
     field public static final int CS_BOUND = 6; // 0x6
     field public static final int DIRECT_TO_VM_FINISHED = 103; // 0x67
     field public static final int DIRECT_TO_VM_INITIATED = 102; // 0x66
@@ -6921,7 +6950,7 @@
     field public static final int ACCEPT_TIMING = 0; // 0x0
     field public static final int BIND_CS_TIMING = 6; // 0x6
     field public static final int BLOCK_CHECK_FINISHED_TIMING = 9; // 0x9
-    field public static final android.os.Parcelable.Creator<android.telecom.ParcelableCallAnalytics.EventTiming> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.ParcelableCallAnalytics.EventTiming> CREATOR;
     field public static final int DIRECT_TO_VM_FINISHED_TIMING = 8; // 0x8
     field public static final int DISCONNECT_TIMING = 2; // 0x2
     field public static final int FILTERING_COMPLETED_TIMING = 10; // 0xa
@@ -6994,7 +7023,7 @@
     method public java.util.List<android.telecom.ParcelableCallAnalytics> getCallAnalytics();
     method public java.util.List<android.telecom.TelecomAnalytics.SessionTiming> getSessionTimings();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telecom.TelecomAnalytics> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.TelecomAnalytics> CREATOR;
   }
 
   public static final class TelecomAnalytics.SessionTiming implements android.os.Parcelable {
@@ -7003,7 +7032,7 @@
     method public Integer getKey();
     method public long getTime();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telecom.TelecomAnalytics.SessionTiming> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.TelecomAnalytics.SessionTiming> CREATOR;
     field public static final int CSW_ADD_CONFERENCE_CALL = 108; // 0x6c
     field public static final int CSW_HANDLE_CREATE_CONNECTION_COMPLETE = 100; // 0x64
     field public static final int CSW_REMOVE_CALL = 106; // 0x6a
@@ -7068,7 +7097,7 @@
     method public int getNetworkType();
     method public android.telephony.PreciseCallState getPreciseCallState();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.CallAttributes> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CallAttributes> CREATOR;
   }
 
   public final class CallQuality implements android.os.Parcelable {
@@ -7092,7 +7121,7 @@
     field public static final int CALL_QUALITY_GOOD = 1; // 0x1
     field public static final int CALL_QUALITY_NOT_AVAILABLE = 5; // 0x5
     field public static final int CALL_QUALITY_POOR = 3; // 0x3
-    field public static final android.os.Parcelable.Creator<android.telephony.CallQuality> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CallQuality> CREATOR;
   }
 
   public class CarrierConfigManager {
@@ -7113,7 +7142,7 @@
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int CARRIER_RESTRICTION_DEFAULT_ALLOWED = 1; // 0x1
     field public static final int CARRIER_RESTRICTION_DEFAULT_NOT_ALLOWED = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.telephony.CarrierRestrictionRules> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CarrierRestrictionRules> CREATOR;
     field public static final int MULTISIM_POLICY_NONE = 0; // 0x0
     field public static final int MULTISIM_POLICY_ONE_VALID_SIM_MUST_BE_PRESENT = 1; // 0x1
   }
@@ -7470,7 +7499,14 @@
     field public static final int VSNCP_TIMEOUT = 2236; // 0x8bc
   }
 
-  public class DisconnectCause {
+  public final class DataSpecificRegistrationStates implements android.os.Parcelable {
+    method public int describeContents();
+    method @NonNull public android.telephony.LteVopsSupportInfo getLteVopsSupportInfo();
+    method public void writeToParcel(android.os.Parcel, int);
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.DataSpecificRegistrationStates> CREATOR;
+  }
+
+  public final class DisconnectCause {
     field public static final int ALREADY_DIALING = 72; // 0x48
     field public static final int ANSWERED_ELSEWHERE = 52; // 0x34
     field public static final int BUSY = 4; // 0x4
@@ -7553,7 +7589,7 @@
     method public int getEmcBearerSupport();
     method public int getVopsSupport();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.LteVopsSupportInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.LteVopsSupportInfo> CREATOR;
     field public static final int LTE_STATUS_NOT_AVAILABLE = 1; // 0x1
     field public static final int LTE_STATUS_NOT_SUPPORTED = 3; // 0x3
     field public static final int LTE_STATUS_SUPPORTED = 2; // 0x2
@@ -7578,6 +7614,7 @@
     method public int getAccessNetworkTechnology();
     method public int[] getAvailableServices();
     method public android.telephony.CellIdentity getCellIdentity();
+    method @Nullable public android.telephony.DataSpecificRegistrationStates getDataSpecificStates();
     method public int getDomain();
     method public int getRegState();
     method public int getRejectCause();
@@ -7586,7 +7623,7 @@
     method public boolean isEmergencyEnabled();
     method public boolean isRoaming();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.NetworkRegistrationState> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.NetworkRegistrationState> CREATOR;
     field public static final int DOMAIN_CS = 1; // 0x1
     field public static final int DOMAIN_PS = 2; // 0x2
     field public static final int REG_STATE_DENIED = 3; // 0x3
@@ -7643,23 +7680,23 @@
     method public int describeContents();
     method public boolean matches(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.PhoneNumberRange> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.PhoneNumberRange> CREATOR;
   }
 
   public class PhoneStateListener {
     method public void onCallAttributesChanged(@NonNull android.telephony.CallAttributes);
-    method public void onCallDisconnectCauseChanged(int, int);
-    method public void onImsCallDisconnectCauseChanged(@NonNull android.telephony.ims.ImsReasonInfo);
-    method public void onPreciseCallStateChanged(android.telephony.PreciseCallState);
-    method public void onPreciseDataConnectionStateChanged(android.telephony.PreciseDataConnectionState);
+    method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onCallDisconnectCauseChanged(int, int);
+    method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onImsCallDisconnectCauseChanged(@NonNull android.telephony.ims.ImsReasonInfo);
+    method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onPreciseCallStateChanged(@NonNull android.telephony.PreciseCallState);
+    method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onPreciseDataConnectionStateChanged(@NonNull android.telephony.PreciseDataConnectionState);
     method public void onRadioPowerStateChanged(int);
     method public void onSrvccStateChanged(int);
     method public void onVoiceActivationStateChanged(int);
     field public static final int LISTEN_CALL_ATTRIBUTES_CHANGED = 67108864; // 0x4000000
-    field public static final int LISTEN_CALL_DISCONNECT_CAUSES = 33554432; // 0x2000000
-    field public static final int LISTEN_IMS_CALL_DISCONNECT_CAUSES = 134217728; // 0x8000000
-    field public static final int LISTEN_PRECISE_CALL_STATE = 2048; // 0x800
-    field public static final int LISTEN_PRECISE_DATA_CONNECTION_STATE = 4096; // 0x1000
+    field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_CALL_DISCONNECT_CAUSES = 33554432; // 0x2000000
+    field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_IMS_CALL_DISCONNECT_CAUSES = 134217728; // 0x8000000
+    field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_PRECISE_CALL_STATE = 2048; // 0x800
+    field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_PRECISE_DATA_CONNECTION_STATE = 4096; // 0x1000
     field public static final int LISTEN_RADIO_POWER_STATE_CHANGED = 8388608; // 0x800000
     field @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public static final int LISTEN_SRVCC_STATE_CHANGED = 16384; // 0x4000
     field public static final int LISTEN_VOICE_ACTIVATION_STATE = 131072; // 0x20000
@@ -7671,7 +7708,7 @@
     method public int getForegroundCallState();
     method public int getRingingCallState();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.PreciseCallState> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.PreciseCallState> CREATOR;
     field public static final int PRECISE_CALL_STATE_ACTIVE = 1; // 0x1
     field public static final int PRECISE_CALL_STATE_ALERTING = 4; // 0x4
     field public static final int PRECISE_CALL_STATE_DIALING = 3; // 0x3
@@ -7686,15 +7723,15 @@
 
   public final class PreciseDataConnectionState implements android.os.Parcelable {
     method public int describeContents();
-    method public String getDataConnectionApn();
+    method @Nullable public String getDataConnectionApn();
     method public int getDataConnectionApnTypeBitMask();
     method public int getDataConnectionFailCause();
     method public int getDataConnectionState();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.PreciseDataConnectionState> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.PreciseDataConnectionState> CREATOR;
   }
 
-  public class PreciseDisconnectCause {
+  public final class PreciseDisconnectCause {
     field public static final int ACCESS_CLASS_BLOCKED = 260; // 0x104
     field public static final int ACCESS_INFORMATION_DISCARDED = 43; // 0x2b
     field public static final int ACM_LIMIT_EXCEEDED = 68; // 0x44
@@ -7841,17 +7878,17 @@
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setDefaultSmsSubId(int);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setPreferredDataSubscriptionId(int, boolean, @NonNull java.util.concurrent.Executor, java.util.function.Consumer<java.lang.Integer>);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setSubscriptionEnabled(int, boolean);
-    field public static final android.net.Uri ADVANCED_CALLING_ENABLED_CONTENT_URI;
+    field @NonNull public static final android.net.Uri ADVANCED_CALLING_ENABLED_CONTENT_URI;
     field public static final int PROFILE_CLASS_DEFAULT = -1; // 0xffffffff
     field public static final int PROFILE_CLASS_OPERATIONAL = 2; // 0x2
     field public static final int PROFILE_CLASS_PROVISIONING = 1; // 0x1
     field public static final int PROFILE_CLASS_TESTING = 0; // 0x0
     field public static final int PROFILE_CLASS_UNSET = -1; // 0xffffffff
-    field public static final android.net.Uri VT_ENABLED_CONTENT_URI;
-    field public static final android.net.Uri WFC_ENABLED_CONTENT_URI;
-    field public static final android.net.Uri WFC_MODE_CONTENT_URI;
-    field public static final android.net.Uri WFC_ROAMING_ENABLED_CONTENT_URI;
-    field public static final android.net.Uri WFC_ROAMING_MODE_CONTENT_URI;
+    field @NonNull public static final android.net.Uri VT_ENABLED_CONTENT_URI;
+    field @NonNull public static final android.net.Uri WFC_ENABLED_CONTENT_URI;
+    field @NonNull public static final android.net.Uri WFC_MODE_CONTENT_URI;
+    field @NonNull public static final android.net.Uri WFC_ROAMING_ENABLED_CONTENT_URI;
+    field @NonNull public static final android.net.Uri WFC_ROAMING_MODE_CONTENT_URI;
   }
 
   public static class SubscriptionPlan.Builder {
@@ -7876,7 +7913,7 @@
     method public int getMinTime();
     method public int getSampleCount();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.TelephonyHistogram> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.TelephonyHistogram> CREATOR;
     field public static final int TELEPHONY_CATEGORY_RIL = 1; // 0x1
   }
 
@@ -7912,7 +7949,7 @@
     method @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public int getRadioPowerState();
     method public int getSimApplicationState();
     method public int getSimCardState();
-    method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getSimLocale();
+    method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public java.util.Locale getSimLocale();
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public long getSupportedRadioAccessFamily();
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public java.util.List<android.telephony.TelephonyHistogram> getTelephonyHistograms();
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public android.telephony.UiccSlotInfo[] getUiccSlotsInfo();
@@ -8017,11 +8054,11 @@
     method public String getCertificateHexString();
     method @Nullable public String getPackageName();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.UiccAccessRule> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.UiccAccessRule> CREATOR;
   }
 
   public class UiccSlotInfo implements android.os.Parcelable {
-    ctor public UiccSlotInfo(boolean, boolean, String, int, int, boolean);
+    ctor @Deprecated public UiccSlotInfo(boolean, boolean, String, int, int, boolean);
     method public int describeContents();
     method public String getCardId();
     method public int getCardStateInfo();
@@ -8029,12 +8066,13 @@
     method public boolean getIsEuicc();
     method public boolean getIsExtendedApduSupported();
     method public int getLogicalSlotIdx();
+    method public boolean isRemovable();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int CARD_STATE_INFO_ABSENT = 1; // 0x1
     field public static final int CARD_STATE_INFO_ERROR = 3; // 0x3
     field public static final int CARD_STATE_INFO_PRESENT = 2; // 0x2
     field public static final int CARD_STATE_INFO_RESTRICTED = 4; // 0x4
-    field public static final android.os.Parcelable.Creator<android.telephony.UiccSlotInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.UiccSlotInfo> CREATOR;
   }
 
   public abstract class VisualVoicemailService extends android.app.Service {
@@ -8062,7 +8100,7 @@
     method public int getStatus();
     method public int getSuggestedRetryTime();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.data.DataCallResponse> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.data.DataCallResponse> CREATOR;
   }
 
   public final class DataProfile implements android.os.Parcelable {
@@ -8241,7 +8279,7 @@
     method public String getTargetAddr();
     method public void writeToParcel(android.os.Parcel, int);
     field @android.telephony.euicc.EuiccNotification.Event public static final int ALL_EVENTS = 15; // 0xf
-    field public static final android.os.Parcelable.Creator<android.telephony.euicc.EuiccNotification> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.euicc.EuiccNotification> CREATOR;
     field public static final int EVENT_DELETE = 8; // 0x8
     field public static final int EVENT_DISABLE = 4; // 0x4
     field public static final int EVENT_ENABLE = 2; // 0x2
@@ -8256,7 +8294,7 @@
     method public int findIndex(@android.service.euicc.EuiccProfileInfo.PolicyRule int, android.service.carrier.CarrierIdentifier);
     method public boolean hasPolicyRuleFlag(int, @android.telephony.euicc.EuiccRulesAuthTable.PolicyRuleFlag int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.euicc.EuiccRulesAuthTable> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.euicc.EuiccRulesAuthTable> CREATOR;
     field public static final int POLICY_RULE_FLAG_CONSENT_REQUIRED = 1; // 0x1
   }
 
@@ -8290,7 +8328,7 @@
     field public static final int CDIV_CF_REASON_NOT_REACHABLE = 3; // 0x3
     field public static final int CDIV_CF_REASON_NO_REPLY = 2; // 0x2
     field public static final int CDIV_CF_REASON_UNCONDITIONAL = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.ImsCallForwardInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsCallForwardInfo> CREATOR;
     field public static final int STATUS_ACTIVE = 1; // 0x1
     field public static final int STATUS_NOT_ACTIVE = 0; // 0x0
     field public static final int TYPE_OF_ADDRESS_INTERNATIONAL = 145; // 0x91
@@ -8351,7 +8389,7 @@
     field public static final int CALL_TYPE_VT_NODIR = 7; // 0x7
     field public static final int CALL_TYPE_VT_RX = 6; // 0x6
     field public static final int CALL_TYPE_VT_TX = 5; // 0x5
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.ImsCallProfile> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsCallProfile> CREATOR;
     field public static final int DIALSTRING_NORMAL = 0; // 0x0
     field public static final int DIALSTRING_SS_CONF = 1; // 0x1
     field public static final int DIALSTRING_USSD = 2; // 0x2
@@ -8423,7 +8461,7 @@
     method public int describeContents();
     method public static int getConnectionStateForStatus(String);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.ImsConferenceState> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsConferenceState> CREATOR;
     field public static final String DISPLAY_TEXT = "display-text";
     field public static final String ENDPOINT = "endpoint";
     field public static final String SIP_STATUS_CODE = "sipstatuscode";
@@ -8467,7 +8505,7 @@
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int CALL_STATE_CONFIRMED = 1; // 0x1
     field public static final int CALL_STATE_TERMINATED = 2; // 0x2
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.ImsExternalCallState> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsExternalCallState> CREATOR;
   }
 
   public class ImsMmTelManager {
@@ -8482,14 +8520,14 @@
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isVtSettingEnabled();
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void registerImsRegistrationCallback(java.util.concurrent.Executor, @NonNull android.telephony.ims.ImsMmTelManager.RegistrationCallback) throws android.telephony.ims.ImsException;
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void registerMmTelCapabilityCallback(@NonNull java.util.concurrent.Executor, @NonNull android.telephony.ims.ImsMmTelManager.CapabilityCallback) throws android.telephony.ims.ImsException;
-    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setAdvancedCallingSetting(boolean);
+    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setAdvancedCallingSettingEnabled(boolean);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setRttCapabilitySetting(boolean);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setVoWiFiModeSetting(int);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setVoWiFiNonPersistent(boolean, int);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setVoWiFiRoamingModeSetting(int);
-    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setVoWiFiRoamingSetting(boolean);
-    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setVoWiFiSetting(boolean);
-    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setVtSetting(boolean);
+    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setVoWiFiRoamingSettingEnabled(boolean);
+    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setVoWiFiSettingEnabled(boolean);
+    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setVtSettingEnabled(boolean);
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void unregisterImsRegistrationCallback(@NonNull android.telephony.ims.ImsMmTelManager.RegistrationCallback);
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void unregisterMmTelCapabilityCallback(@NonNull android.telephony.ims.ImsMmTelManager.CapabilityCallback);
     field public static final int WIFI_MODE_CELLULAR_PREFERRED = 1; // 0x1
@@ -8504,10 +8542,10 @@
 
   public static class ImsMmTelManager.RegistrationCallback {
     ctor public ImsMmTelManager.RegistrationCallback();
-    method public void onDeregistered(android.telephony.ims.ImsReasonInfo);
     method public void onRegistered(int);
     method public void onRegistering(int);
     method public void onTechnologyChangeFailed(int, android.telephony.ims.ImsReasonInfo);
+    method public void onUnregistered(android.telephony.ims.ImsReasonInfo);
   }
 
   public final class ImsReasonInfo implements android.os.Parcelable {
@@ -8687,7 +8725,7 @@
     field public static final int CODE_UT_SS_MODIFIED_TO_SS = 824; // 0x338
     field public static final int CODE_UT_SS_MODIFIED_TO_USSD = 823; // 0x337
     field public static final int CODE_WIFI_LOST = 1407; // 0x57f
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.ImsReasonInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsReasonInfo> CREATOR;
     field public static final int EXTRA_CODE_CALL_RETRY_BY_SETTINGS = 3; // 0x3
     field public static final int EXTRA_CODE_CALL_RETRY_NORMAL = 1; // 0x1
     field public static final int EXTRA_CODE_CALL_RETRY_SILENT_REDIAL = 2; // 0x2
@@ -8728,7 +8766,7 @@
     method public boolean isTypeInterrogation();
     method public boolean isTypeUnConditional();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.ImsSsData> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsSsData> CREATOR;
     field public static final int RESULT_SUCCESS = 0; // 0x0
     field public static final int SERVICE_CLASS_DATA = 2; // 0x2
     field public static final int SERVICE_CLASS_DATA_CIRCUIT_ASYNC = 32; // 0x20
@@ -8800,7 +8838,7 @@
     field public static final int CLIR_STATUS_TEMPORARILY_ALLOWED = 4; // 0x4
     field public static final int CLIR_STATUS_TEMPORARILY_RESTRICTED = 3; // 0x3
     field public static final int CLIR_STATUS_UNKNOWN = 2; // 0x2
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.ImsSsInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsSsInfo> CREATOR;
     field public static final int DISABLED = 0; // 0x0
     field public static final int ENABLED = 1; // 0x1
     field public static final int NOT_REGISTERED = -1; // 0xffffffff
@@ -8824,12 +8862,12 @@
     method public int describeContents();
     method public int getAudioDirection();
     method public int getAudioQuality();
-    method public boolean getRttAudioSpeech();
     method public int getRttMode();
     method public int getVideoDirection();
     method public int getVideoQuality();
+    method public boolean isReceivingRttAudio();
     method public boolean isRttCall();
-    method public void setRttAudioSpeech(boolean);
+    method public void setReceivingRttAudio(boolean);
     method public void setRttMode(int);
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int AUDIO_QUALITY_AMR = 1; // 0x1
@@ -8853,7 +8891,7 @@
     field public static final int AUDIO_QUALITY_GSM_HR = 10; // 0xa
     field public static final int AUDIO_QUALITY_NONE = 0; // 0x0
     field public static final int AUDIO_QUALITY_QCELP13K = 3; // 0x3
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.ImsStreamMediaProfile> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsStreamMediaProfile> CREATOR;
     field public static final int DIRECTION_INACTIVE = 0; // 0x0
     field public static final int DIRECTION_INVALID = -1; // 0xffffffff
     field public static final int DIRECTION_RECEIVE = 1; // 0x1
@@ -8873,7 +8911,7 @@
     ctor public ImsSuppServiceNotification(int, int, int, int, String, String[]);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.ImsSuppServiceNotification> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsSuppServiceNotification> CREATOR;
     field public final int code;
     field public final String[] history;
     field public final int index;
@@ -8950,7 +8988,7 @@
     method public java.util.List<android.telephony.ims.feature.CapabilityChangeRequest.CapabilityPair> getCapabilitiesToDisable();
     method public java.util.List<android.telephony.ims.feature.CapabilityChangeRequest.CapabilityPair> getCapabilitiesToEnable();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.feature.CapabilityChangeRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.feature.CapabilityChangeRequest> CREATOR;
   }
 
   public static class CapabilityChangeRequest.CapabilityPair {
@@ -9112,7 +9150,7 @@
     method public int describeContents();
     method public java.util.Set<android.telephony.ims.stub.ImsFeatureConfiguration.FeatureSlotPair> getServiceFeatures();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.stub.ImsFeatureConfiguration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.stub.ImsFeatureConfiguration> CREATOR;
   }
 
   public static class ImsFeatureConfiguration.Builder {
@@ -9225,7 +9263,7 @@
     method public android.net.Uri getContentUri();
     method public android.net.Uri getFilePathUri();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.mbms.UriPathPair> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.mbms.UriPathPair> CREATOR;
   }
 
 }
@@ -9403,13 +9441,15 @@
     method public int getType();
     method @Nullable public android.view.contentcapture.ViewNode getViewNode();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.contentcapture.ContentCaptureEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.contentcapture.ContentCaptureEvent> CREATOR;
     field public static final int TYPE_CONTEXT_UPDATED = 6; // 0x6
-    field public static final int TYPE_INITIAL_VIEW_TREE_APPEARED = 5; // 0x5
-    field public static final int TYPE_INITIAL_VIEW_TREE_APPEARING = 4; // 0x4
+    field public static final int TYPE_SESSION_PAUSED = 8; // 0x8
+    field public static final int TYPE_SESSION_RESUMED = 7; // 0x7
     field public static final int TYPE_VIEW_APPEARED = 1; // 0x1
     field public static final int TYPE_VIEW_DISAPPEARED = 2; // 0x2
     field public static final int TYPE_VIEW_TEXT_CHANGED = 3; // 0x3
+    field public static final int TYPE_VIEW_TREE_APPEARED = 5; // 0x5
+    field public static final int TYPE_VIEW_TREE_APPEARING = 4; // 0x4
   }
 
   public final class ContentCaptureManager {
@@ -9795,7 +9835,7 @@
     method public default void onMovedToDisplay(int, android.content.res.Configuration);
     method public void onOverScrolled(int, int, boolean, boolean);
     method public default void onProvideAutofillVirtualStructure(android.view.ViewStructure, int);
-    method public default void onProvideContentCaptureStructure(android.view.ViewStructure, int);
+    method public default void onProvideContentCaptureStructure(@NonNull android.view.ViewStructure, int);
     method public void onProvideVirtualStructure(android.view.ViewStructure);
     method public void onScrollChanged(int, int, int, int);
     method public void onSizeChanged(int, int, int, int);
@@ -9823,7 +9863,7 @@
     ctor public WebViewProviderInfo(String, String, boolean, boolean, String[]);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.webkit.WebViewProviderInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.webkit.WebViewProviderInfo> CREATOR;
     field public final boolean availableByDefault;
     field public final String description;
     field public final boolean isFallback;
diff --git a/api/test-current.txt b/api/test-current.txt
index ba497d4..e38ebe6 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -217,7 +217,7 @@
     method @NonNull public String getOpName();
     method public long getRejectCount(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalOp> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalOp> CREATOR;
   }
 
   public static final class AppOpsManager.HistoricalOps implements android.os.Parcelable {
@@ -233,7 +233,7 @@
     method public void increaseRejectCount(int, int, @NonNull String, int, long);
     method public void offsetBeginAndEndTime(long);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalOps> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalOps> CREATOR;
   }
 
   public static final class AppOpsManager.HistoricalOpsRequest {
@@ -254,7 +254,7 @@
     method public int getOpCount();
     method @NonNull public String getPackageName();
     method public void writeToParcel(@NonNull android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalPackageOps> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalPackageOps> CREATOR;
   }
 
   public static final class AppOpsManager.HistoricalUidOps implements android.os.Parcelable {
@@ -264,13 +264,17 @@
     method @NonNull public android.app.AppOpsManager.HistoricalPackageOps getPackageOpsAt(int);
     method public int getUid();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalUidOps> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalUidOps> CREATOR;
   }
 
   public static interface AppOpsManager.OnOpActiveChangedListener {
     method public void onOpActiveChanged(int, int, String, boolean);
   }
 
+  public class DownloadManager {
+    field public static final String COLUMN_MEDIASTORE_URI = "mediastore_uri";
+  }
+
   public final class NotificationChannel implements android.os.Parcelable {
     method public boolean isImportanceLockedByOEM();
     method public void setImportanceLockedByOEM(boolean);
@@ -392,7 +396,7 @@
     method public int getPredictedTargetCount();
     method public String getUiSurface();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.prediction.AppPredictionContext> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.prediction.AppPredictionContext> CREATOR;
   }
 
   public static final class AppPredictionContext.Builder {
@@ -410,7 +414,7 @@
   public final class AppPredictionSessionId implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.prediction.AppPredictionSessionId> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.prediction.AppPredictionSessionId> CREATOR;
   }
 
   public final class AppPredictor {
@@ -438,7 +442,7 @@
     method @Nullable public android.content.pm.ShortcutInfo getShortcutInfo();
     method @NonNull public android.os.UserHandle getUser();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.prediction.AppTarget> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.prediction.AppTarget> CREATOR;
   }
 
   public final class AppTargetEvent implements android.os.Parcelable {
@@ -450,7 +454,7 @@
     field public static final int ACTION_DISMISS = 2; // 0x2
     field public static final int ACTION_LAUNCH = 1; // 0x1
     field public static final int ACTION_PIN = 3; // 0x3
-    field public static final android.os.Parcelable.Creator<android.app.prediction.AppTargetEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.prediction.AppTargetEvent> CREATOR;
   }
 
   public static final class AppTargetEvent.Builder {
@@ -463,20 +467,29 @@
     ctor public AppTargetId(@NonNull String);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.prediction.AppTargetId> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.prediction.AppTargetId> CREATOR;
   }
 
 }
 
 package android.app.role {
 
+  public interface OnRoleHoldersChangedListener {
+    method public void onRoleHoldersChanged(@NonNull String, @NonNull android.os.UserHandle);
+  }
+
   public final class RoleManager {
+    method @RequiresPermission("android.permission.OBSERVE_ROLE_HOLDERS") public void addOnRoleHoldersChangedListenerAsUser(@NonNull java.util.concurrent.Executor, @NonNull android.app.role.OnRoleHoldersChangedListener, @NonNull android.os.UserHandle);
     method @RequiresPermission("android.permission.MANAGE_ROLE_HOLDERS") public void addRoleHolderAsUser(@NonNull String, @NonNull String, int, @NonNull android.os.UserHandle, @NonNull java.util.concurrent.Executor, @NonNull android.app.role.RoleManagerCallback);
+    method @RequiresPermission("com.android.permissioncontroller.permission.MANAGE_ROLES_FROM_CONTROLLER") public boolean addRoleHolderFromController(@NonNull String, @NonNull String);
     method @RequiresPermission("android.permission.MANAGE_ROLE_HOLDERS") public void clearRoleHoldersAsUser(@NonNull String, int, @NonNull android.os.UserHandle, @NonNull java.util.concurrent.Executor, @NonNull android.app.role.RoleManagerCallback);
+    method @NonNull @RequiresPermission("com.android.permissioncontroller.permission.MANAGE_ROLES_FROM_CONTROLLER") public java.util.List<java.lang.String> getHeldRolesFromController(@NonNull String);
     method @NonNull @RequiresPermission("android.permission.MANAGE_ROLE_HOLDERS") public java.util.List<java.lang.String> getRoleHolders(@NonNull String);
     method @NonNull @RequiresPermission("android.permission.MANAGE_ROLE_HOLDERS") public java.util.List<java.lang.String> getRoleHoldersAsUser(@NonNull String, @NonNull android.os.UserHandle);
+    method @RequiresPermission("android.permission.OBSERVE_ROLE_HOLDERS") public void removeOnRoleHoldersChangedListenerAsUser(@NonNull android.app.role.OnRoleHoldersChangedListener, @NonNull android.os.UserHandle);
     method @RequiresPermission("android.permission.MANAGE_ROLE_HOLDERS") public void removeRoleHolderAsUser(@NonNull String, @NonNull String, int, @NonNull android.os.UserHandle, @NonNull java.util.concurrent.Executor, @NonNull android.app.role.RoleManagerCallback);
-    field public static final String ROLE_ASSISTANT = "android.app.role.ASSISTANT";
+    method @RequiresPermission("com.android.permissioncontroller.permission.MANAGE_ROLES_FROM_CONTROLLER") public boolean removeRoleHolderFromController(@NonNull String, @NonNull String);
+    method @RequiresPermission("com.android.permissioncontroller.permission.MANAGE_ROLES_FROM_CONTROLLER") public void setRoleNamesFromController(@NonNull java.util.List<java.lang.String>);
   }
 
   public interface RoleManagerCallback {
@@ -518,7 +531,7 @@
     method public int describeContents();
     method public static android.content.AutofillOptions forWhitelistingItself();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.AutofillOptions> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.AutofillOptions> CREATOR;
     field public boolean augmentedEnabled;
     field public final boolean compatModeEnabled;
     field public final int loggingLevel;
@@ -529,7 +542,7 @@
     method public int describeContents();
     method public static android.content.ContentCaptureOptions forWhitelistingItself();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.content.ContentCaptureOptions> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.content.ContentCaptureOptions> CREATOR;
     field public final int idleFlushingFrequencyMs;
     field public final int logHistorySize;
     field public final int loggingLevel;
@@ -559,6 +572,10 @@
     method public android.view.Display getDisplay();
   }
 
+  public class Intent implements java.lang.Cloneable android.os.Parcelable {
+    field public static final String EXTRA_ROLE_NAME = "android.intent.extra.ROLE_NAME";
+  }
+
 }
 
 package android.content.pm {
@@ -685,7 +702,6 @@
     method public static int getWALAutoCheckpoint();
     method public static int getWALConnectionPoolSize();
     method public static String getWALSyncMode();
-    method public static boolean isCompatibilityWalSupported();
     method public static int releaseMemory();
   }
 
@@ -739,13 +755,20 @@
     method public java.time.LocalDate getLocalDate();
     method public float[] getStats();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.display.AmbientBrightnessDayStats> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.display.AmbientBrightnessDayStats> CREATOR;
+  }
+
+  public class AmbientDisplayConfiguration {
+    ctor public AmbientDisplayConfiguration(android.content.Context);
+    method public boolean alwaysOnAvailable();
+    method public boolean alwaysOnAvailableForUser(int);
+    method public boolean alwaysOnEnabled(int);
   }
 
   public final class BrightnessChangeEvent implements android.os.Parcelable {
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessChangeEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessChangeEvent> CREATOR;
     field public final float batteryLevel;
     field public final float brightness;
     field public final long colorSampleDuration;
@@ -765,28 +788,28 @@
   public final class BrightnessConfiguration implements android.os.Parcelable {
     method public int describeContents();
     method @Nullable public android.hardware.display.BrightnessCorrection getCorrectionByCategory(int);
-    method @Nullable public android.hardware.display.BrightnessCorrection getCorrectionByPackageName(String);
+    method @Nullable public android.hardware.display.BrightnessCorrection getCorrectionByPackageName(@NonNull String);
     method public android.util.Pair<float[],float[]> getCurve();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessConfiguration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessConfiguration> CREATOR;
   }
 
   public static class BrightnessConfiguration.Builder {
     ctor public BrightnessConfiguration.Builder(float[], float[]);
-    method public android.hardware.display.BrightnessConfiguration.Builder addCorrectionByCategory(int, android.hardware.display.BrightnessCorrection);
-    method public android.hardware.display.BrightnessConfiguration.Builder addCorrectionByPackageName(String, android.hardware.display.BrightnessCorrection);
-    method public android.hardware.display.BrightnessConfiguration build();
+    method @NonNull public android.hardware.display.BrightnessConfiguration.Builder addCorrectionByCategory(int, @NonNull android.hardware.display.BrightnessCorrection);
+    method @NonNull public android.hardware.display.BrightnessConfiguration.Builder addCorrectionByPackageName(@NonNull String, @NonNull android.hardware.display.BrightnessCorrection);
+    method @NonNull public android.hardware.display.BrightnessConfiguration build();
     method public int getMaxCorrectionsByCategory();
     method public int getMaxCorrectionsByPackageName();
-    method public android.hardware.display.BrightnessConfiguration.Builder setDescription(@Nullable String);
+    method @NonNull public android.hardware.display.BrightnessConfiguration.Builder setDescription(@Nullable String);
   }
 
   public final class BrightnessCorrection implements android.os.Parcelable {
-    method public float apply(float);
+    method @FloatRange(from=0.0) public float apply(@FloatRange(from=0.0) float);
     method @NonNull public static android.hardware.display.BrightnessCorrection createScaleAndTranslateLog(float, float);
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessCorrection> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessCorrection> CREATOR;
   }
 
   public final class DisplayManager {
@@ -905,7 +928,7 @@
     field public static final int ACCURACY_BLOCK = 102; // 0x66
     field public static final int ACCURACY_CITY = 104; // 0x68
     field public static final int ACCURACY_FINE = 100; // 0x64
-    field public static final android.os.Parcelable.Creator<android.location.LocationRequest> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.location.LocationRequest> CREATOR;
     field public static final int POWER_HIGH = 203; // 0xcb
     field public static final int POWER_LOW = 201; // 0xc9
     field public static final int POWER_NONE = 200; // 0xc8
@@ -936,7 +959,7 @@
     method public int getInitialMarkMs();
     method public int getResumePlaybackMarkMs();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.media.BufferingParams> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.media.BufferingParams> CREATOR;
   }
 
   public static class BufferingParams.Builder {
@@ -1150,7 +1173,7 @@
     method public void setGateway(java.net.InetAddress);
     method public void setIpAddress(android.net.LinkAddress);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.StaticIpConfiguration> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.net.StaticIpConfiguration> CREATOR;
   }
 
   public class TrafficStats {
@@ -1407,8 +1430,8 @@
 
   public class Environment {
     method public static java.io.File buildPath(java.io.File, java.lang.String...);
-    method public static java.io.File getProductDirectory();
-    method public static java.io.File getStorageDirectory();
+    method @NonNull public static java.io.File getProductDirectory();
+    method @NonNull public static java.io.File getStorageDirectory();
   }
 
   public final class FileUtils {
@@ -1573,7 +1596,7 @@
     method public long getPrivacyPolicy();
     method public long getTimestamp();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.IncidentManager.IncidentReport> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.IncidentManager.IncidentReport> CREATOR;
   }
 
   public static class IncidentManager.PendingReport {
@@ -1597,7 +1620,7 @@
     method public void setAll(boolean);
     method public void setPrivacyPolicy(int);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.IncidentReportArgs> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.IncidentReportArgs> CREATOR;
   }
 
   public final class MessageQueue {
@@ -1644,7 +1667,7 @@
     method public int describeContents();
     method public void sendResult(@Nullable android.os.Bundle);
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.RemoteCallback> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.RemoteCallback> CREATOR;
   }
 
   public static interface RemoteCallback.OnResultListener {
@@ -1657,7 +1680,7 @@
   }
 
   public static final class StrictMode.ThreadPolicy.Builder {
-    method public android.os.StrictMode.ThreadPolicy.Builder detectExplicitGc();
+    method @NonNull public android.os.StrictMode.ThreadPolicy.Builder detectExplicitGc();
   }
 
   public static final class StrictMode.ViolationInfo implements android.os.Parcelable {
@@ -1669,7 +1692,7 @@
     method public Class<? extends android.os.strictmode.Violation> getViolationClass();
     method public String getViolationDetails();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.StrictMode.ViolationInfo> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.StrictMode.ViolationInfo> CREATOR;
     field public String broadcastIntentAction;
     field public int durationMillis;
     field public int numAnimationsRunning;
@@ -1724,7 +1747,7 @@
     method public android.os.VibrationEffect.OneShot scale(float, int);
     method public void validate();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.VibrationEffect.OneShot> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.VibrationEffect.OneShot> CREATOR;
   }
 
   public static class VibrationEffect.Prebaked extends android.os.VibrationEffect implements android.os.Parcelable {
@@ -1737,7 +1760,7 @@
     method public boolean shouldFallback();
     method public void validate();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.VibrationEffect.Prebaked> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.VibrationEffect.Prebaked> CREATOR;
   }
 
   public static class VibrationEffect.Waveform extends android.os.VibrationEffect implements android.os.Parcelable {
@@ -1750,7 +1773,7 @@
     method public android.os.VibrationEffect.Waveform scale(float, int);
     method public void validate();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.VibrationEffect.Waveform> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.VibrationEffect.Waveform> CREATOR;
   }
 
   public class VintfObject {
@@ -1824,7 +1847,7 @@
     method public int describeContents();
     method public android.os.health.HealthStats getHealthStats();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.os.health.HealthStatsParceler> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.os.health.HealthStatsParceler> CREATOR;
   }
 
   public class HealthStatsWriter {
@@ -1916,7 +1939,12 @@
 
   public final class DeviceConfig {
     method @RequiresPermission("android.permission.READ_DEVICE_CONFIG") public static void addOnPropertyChangedListener(@NonNull String, @NonNull java.util.concurrent.Executor, @NonNull android.provider.DeviceConfig.OnPropertyChangedListener);
+    method @RequiresPermission("android.permission.READ_DEVICE_CONFIG") public static boolean getBoolean(String, String, boolean);
+    method @RequiresPermission("android.permission.READ_DEVICE_CONFIG") public static float getFloat(String, String, float);
+    method @RequiresPermission("android.permission.READ_DEVICE_CONFIG") public static int getInt(String, String, int);
+    method @RequiresPermission("android.permission.READ_DEVICE_CONFIG") public static long getLong(String, String, long);
     method @RequiresPermission("android.permission.READ_DEVICE_CONFIG") public static String getProperty(String, String);
+    method @RequiresPermission("android.permission.READ_DEVICE_CONFIG") public static String getString(String, String, String);
     method public static void removeOnPropertyChangedListener(android.provider.DeviceConfig.OnPropertyChangedListener);
     method @RequiresPermission("android.permission.WRITE_DEVICE_CONFIG") public static void resetToDefaults(int, @Nullable String);
     method @RequiresPermission("android.permission.WRITE_DEVICE_CONFIG") public static boolean setProperty(String, String, String, boolean);
@@ -1952,6 +1980,7 @@
   public static final class Settings.Global extends android.provider.Settings.NameValueTable {
     field public static final String AUTOFILL_COMPAT_MODE_ALLOWED_PACKAGES = "autofill_compat_mode_allowed_packages";
     field public static final String AUTOMATIC_POWER_SAVER_MODE = "automatic_power_saver_mode";
+    field public static final String BATTERY_SAVER_CONSTANTS = "battery_saver_constants";
     field public static final String CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS = "captive_portal_fallback_probe_specs";
     field public static final String CAPTIVE_PORTAL_FALLBACK_URL = "captive_portal_fallback_url";
     field public static final String CAPTIVE_PORTAL_HTTPS_URL = "captive_portal_https_url";
@@ -1991,6 +2020,7 @@
     field public static final String AUTOFILL_USER_DATA_MIN_VALUE_LENGTH = "autofill_user_data_min_value_length";
     field public static final String CONTENT_CAPTURE_ENABLED = "content_capture_enabled";
     field public static final String DISABLED_PRINT_SERVICES = "disabled_print_services";
+    field public static final String DOZE_ALWAYS_ON = "doze_always_on";
     field @Deprecated public static final String ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES = "enabled_notification_policy_access_packages";
     field public static final String ENABLED_VR_LISTENERS = "enabled_vr_listeners";
     field public static final String LOCATION_ACCESS_CHECK_DELAY_MILLIS = "location_access_check_delay_millis";
@@ -2093,7 +2123,7 @@
     method public android.util.ArrayMap<java.lang.String,android.os.Bundle> getFieldClassificationArgs();
     method public String[] getValues();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.autofill.CompositeUserData> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.CompositeUserData> CREATOR;
   }
 
   public final class CustomDescription implements android.os.Parcelable {
@@ -2196,9 +2226,8 @@
 
   public static final class FillResponse.Builder {
     ctor public FillResponse.Builder();
-    method public android.service.autofill.augmented.FillResponse build();
-    method public android.service.autofill.augmented.FillResponse.Builder setFillWindow(@NonNull android.service.autofill.augmented.FillWindow);
-    method public android.service.autofill.augmented.FillResponse.Builder setIgnoredIds(@NonNull java.util.List<android.view.autofill.AutofillId>);
+    method @NonNull public android.service.autofill.augmented.FillResponse build();
+    method @NonNull public android.service.autofill.augmented.FillResponse.Builder setFillWindow(@NonNull android.service.autofill.augmented.FillWindow);
   }
 
   public final class FillWindow implements java.lang.AutoCloseable {
@@ -2236,11 +2265,11 @@
 
   public final class SnapshotData implements android.os.Parcelable {
     method public int describeContents();
-    method public android.app.assist.AssistContent getAssistContent();
-    method public android.os.Bundle getAssistData();
-    method public android.app.assist.AssistStructure getAssistStructure();
+    method @Nullable public android.app.assist.AssistContent getAssistContent();
+    method @NonNull public android.os.Bundle getAssistData();
+    method @NonNull public android.app.assist.AssistStructure getAssistStructure();
     method public void writeToParcel(@NonNull android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.contentcapture.SnapshotData> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.contentcapture.SnapshotData> CREATOR;
   }
 
 }
@@ -2263,7 +2292,7 @@
     method public CharSequence getExplanation();
     method public String getId();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.service.notification.SnoozeCriterion> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.service.notification.SnoozeCriterion> CREATOR;
   }
 
 }
@@ -2374,7 +2403,7 @@
     method public android.net.Uri getContentUri();
     method public android.net.Uri getFilePathUri();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.mbms.UriPathPair> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.mbms.UriPathPair> CREATOR;
   }
 
 }
@@ -2861,13 +2890,15 @@
     method public int getType();
     method @Nullable public android.view.contentcapture.ViewNode getViewNode();
     method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.view.contentcapture.ContentCaptureEvent> CREATOR;
+    field @NonNull public static final android.os.Parcelable.Creator<android.view.contentcapture.ContentCaptureEvent> CREATOR;
     field public static final int TYPE_CONTEXT_UPDATED = 6; // 0x6
-    field public static final int TYPE_INITIAL_VIEW_TREE_APPEARED = 5; // 0x5
-    field public static final int TYPE_INITIAL_VIEW_TREE_APPEARING = 4; // 0x4
+    field public static final int TYPE_SESSION_PAUSED = 8; // 0x8
+    field public static final int TYPE_SESSION_RESUMED = 7; // 0x7
     field public static final int TYPE_VIEW_APPEARED = 1; // 0x1
     field public static final int TYPE_VIEW_DISAPPEARED = 2; // 0x2
     field public static final int TYPE_VIEW_TEXT_CHANGED = 3; // 0x3
+    field public static final int TYPE_VIEW_TREE_APPEARED = 5; // 0x5
+    field public static final int TYPE_VIEW_TREE_APPEARING = 4; // 0x4
   }
 
   public final class ContentCaptureManager {
diff --git a/cmds/bootanimation/bootanim.rc b/cmds/bootanimation/bootanim.rc
index 469c964..3666d6a 100644
--- a/cmds/bootanimation/bootanim.rc
+++ b/cmds/bootanimation/bootanim.rc
@@ -2,6 +2,9 @@
     class core animation
     user graphics
     group graphics audio
+    # bootanimation depends on libandroidicu in the Runtime APEX.
+    # TODO(b/124939955): Remove this dependency on libandroidicu
+    updatable
     disabled
     oneshot
     writepid /dev/stune/top-app/tasks
diff --git a/cmds/idmap2/idmap2/Create.cpp b/cmds/idmap2/idmap2/Create.cpp
index 6703909..c416fa1 100644
--- a/cmds/idmap2/idmap2/Create.cpp
+++ b/cmds/idmap2/idmap2/Create.cpp
@@ -28,7 +28,6 @@
 #include "idmap2/FileUtils.h"
 #include "idmap2/Idmap.h"
 #include "idmap2/Policies.h"
-#include "idmap2/Result.h"
 #include "idmap2/SysTrace.h"
 
 using android::ApkAssets;
@@ -38,7 +37,6 @@
 using android::idmap2::PoliciesToBitmask;
 using android::idmap2::PolicyBitmask;
 using android::idmap2::PolicyFlags;
-using android::idmap2::Result;
 using android::idmap2::utils::kIdmapFilePermissionMask;
 using android::idmap2::utils::UidHasWriteAccessToPath;
 
@@ -77,9 +75,11 @@
   }
 
   PolicyBitmask fulfilled_policies = 0;
-  if (auto result = PoliciesToBitmask(policies, out_error)) {
-    fulfilled_policies |= *result;
+  auto conv_result = PoliciesToBitmask(policies);
+  if (conv_result) {
+    fulfilled_policies |= *conv_result;
   } else {
+    out_error << "error: " << conv_result.GetErrorMessage() << std::endl;
     return false;
   }
 
diff --git a/cmds/idmap2/idmap2/Lookup.cpp b/cmds/idmap2/idmap2/Lookup.cpp
index 553d8ca..83a40ef 100644
--- a/cmds/idmap2/idmap2/Lookup.cpp
+++ b/cmds/idmap2/idmap2/Lookup.cpp
@@ -53,6 +53,7 @@
 using android::StringPiece16;
 using android::base::StringPrintf;
 using android::idmap2::CommandLineOptions;
+using android::idmap2::Error;
 using android::idmap2::IdmapHeader;
 using android::idmap2::ResourceId;
 using android::idmap2::Result;
@@ -71,17 +72,17 @@
   ResourceId resid;
   resid = strtol(res.c_str(), &endptr, kBaseHex);
   if (*endptr == '\0') {
-    return {resid};
+    return resid;
   }
 
   // next, try to parse as a package:type/name string
   resid = am.GetResourceId(res, "", fallback_package);
   if (is_valid_resid(resid)) {
-    return {resid};
+    return resid;
   }
 
   // end of the road: res could not be parsed
-  return {};
+  return Error("failed to obtain resource id for %s", res.c_str());
 }
 
 Result<std::string> WARN_UNUSED GetValue(const AssetManager2& am, ResourceId resid) {
@@ -90,7 +91,7 @@
   uint32_t flags;
   ApkAssetsCookie cookie = am.GetResource(resid, false, 0, &value, &config, &flags);
   if (cookie == kInvalidCookie) {
-    return {};
+    return Error("no resource 0x%08x in asset manager", resid);
   }
 
   std::string out;
@@ -128,31 +129,31 @@
       out.append(StringPrintf("dataType=0x%02x data=0x%08x", value.dataType, value.data));
       break;
   }
-  return {out};
+  return out;
 }
 
 Result<std::string> GetTargetPackageNameFromManifest(const std::string& apk_path) {
   const auto zip = ZipFile::Open(apk_path);
   if (!zip) {
-    return {};
+    return Error("failed to open %s as zip", apk_path.c_str());
   }
   const auto entry = zip->Uncompress("AndroidManifest.xml");
   if (!entry) {
-    return {};
+    return Error("failed to uncompress AndroidManifest.xml in %s", apk_path.c_str());
   }
   const auto xml = Xml::Create(entry->buf, entry->size);
   if (!xml) {
-    return {};
+    return Error("failed to create XML buffer");
   }
   const auto tag = xml->FindTag("overlay");
   if (!tag) {
-    return {};
+    return Error("failed to find <overlay> tag");
   }
   const auto iter = tag->find("targetPackage");
   if (iter == tag->end()) {
-    return {};
+    return Error("failed to find targetPackage attribute");
   }
-  return {iter->second};
+  return iter->second;
 }
 }  // namespace
 
diff --git a/cmds/idmap2/idmap2/Scan.cpp b/cmds/idmap2/idmap2/Scan.cpp
index 873779f..e5f6223 100644
--- a/cmds/idmap2/idmap2/Scan.cpp
+++ b/cmds/idmap2/idmap2/Scan.cpp
@@ -142,9 +142,9 @@
   std::vector<InputOverlay> interesting_apks;
   for (const std::string& path : *apk_paths) {
     Result<OverlayManifestInfo> overlay_info =
-        ExtractOverlayManifestInfo(path, out_error,
-                                   /* assert_overlay */ false);
+        ExtractOverlayManifestInfo(path, /* assert_overlay */ false);
     if (!overlay_info) {
+      out_error << "error: " << overlay_info.GetErrorMessage() << std::endl;
       return false;
     }
 
@@ -163,9 +163,11 @@
 
     PolicyBitmask fulfilled_policies;
     if (!override_policies.empty()) {
-      if (Result<PolicyBitmask> result = PoliciesToBitmask(override_policies, out_error)) {
-        fulfilled_policies = *result;
+      auto conv_result = PoliciesToBitmask(override_policies);
+      if (conv_result) {
+        fulfilled_policies = *conv_result;
       } else {
+        out_error << "error: " << conv_result.GetErrorMessage() << std::endl;
         return false;
       }
     } else {
diff --git a/cmds/idmap2/idmap2d/Idmap2Service.cpp b/cmds/idmap2/idmap2d/Idmap2Service.cpp
index 0e4bd89..fa94414 100644
--- a/cmds/idmap2/idmap2d/Idmap2Service.cpp
+++ b/cmds/idmap2/idmap2d/Idmap2Service.cpp
@@ -34,7 +34,6 @@
 #include "idmap2/FileUtils.h"
 #include "idmap2/Idmap.h"
 #include "idmap2/Policies.h"
-#include "idmap2/Result.h"
 #include "idmap2/SysTrace.h"
 
 #include "idmap2d/Idmap2Service.h"
@@ -45,7 +44,6 @@
 using android::idmap2::Idmap;
 using android::idmap2::IdmapHeader;
 using android::idmap2::PolicyBitmask;
-using android::idmap2::Result;
 using android::idmap2::utils::kIdmapCacheDir;
 using android::idmap2::utils::kIdmapFilePermissionMask;
 using android::idmap2::utils::UidHasWriteAccessToPath;
diff --git a/cmds/idmap2/include/idmap2/Policies.h b/cmds/idmap2/include/idmap2/Policies.h
index eecee25..911d3f2 100644
--- a/cmds/idmap2/include/idmap2/Policies.h
+++ b/cmds/idmap2/include/idmap2/Policies.h
@@ -14,7 +14,6 @@
  * limitations under the License.
  */
 
-#include <ostream>
 #include <string>
 #include <vector>
 
@@ -33,8 +32,7 @@
 
 // Parses a the string representation of a set of policies into a bitmask. The format of the string
 // is the same as for the <policy> element.
-Result<PolicyBitmask> PoliciesToBitmask(const std::vector<std::string>& policies,
-                                        std::ostream& err);
+Result<PolicyBitmask> PoliciesToBitmask(const std::vector<std::string>& policies);
 
 }  // namespace android::idmap2
 
diff --git a/cmds/idmap2/include/idmap2/ResourceUtils.h b/cmds/idmap2/include/idmap2/ResourceUtils.h
index 22827ac..1d81c48 100644
--- a/cmds/idmap2/include/idmap2/ResourceUtils.h
+++ b/cmds/idmap2/include/idmap2/ResourceUtils.h
@@ -18,10 +18,8 @@
 #define IDMAP2_INCLUDE_IDMAP2_RESOURCEUTILS_H_
 
 #include <optional>
-#include <ostream>
 #include <string>
 
-#include "android-base/macros.h"
 #include "androidfw/AssetManager2.h"
 
 #include "idmap2/Idmap.h"
@@ -38,10 +36,9 @@
 };
 
 Result<OverlayManifestInfo> ExtractOverlayManifestInfo(const std::string& path,
-                                                       std::ostream& out_error,
                                                        bool assert_overlay = true);
 
-Result<std::string> WARN_UNUSED ResToTypeEntryName(const AssetManager2& am, ResourceId resid);
+Result<std::string> ResToTypeEntryName(const AssetManager2& am, ResourceId resid);
 
 }  // namespace android::idmap2::utils
 
diff --git a/cmds/idmap2/include/idmap2/Result.h b/cmds/idmap2/include/idmap2/Result.h
index d88dd51..41b15eb 100644
--- a/cmds/idmap2/include/idmap2/Result.h
+++ b/cmds/idmap2/include/idmap2/Result.h
@@ -17,7 +17,6 @@
 #ifndef IDMAP2_INCLUDE_IDMAP2_RESULT_H_
 #define IDMAP2_INCLUDE_IDMAP2_RESULT_H_
 
-#include <optional>
 #include <string>
 #include <utility>
 #include <variant>
@@ -26,13 +25,6 @@
 
 namespace android::idmap2 {
 
-template <typename T>
-using Result = std::optional<T>;
-
-static constexpr std::nullopt_t kResultError = std::nullopt;
-
-namespace v2 {
-
 using Unit = std::monostate;
 
 class Error {
@@ -148,8 +140,6 @@
   return std::holds_alternative<T>(data_);
 }
 
-}  // namespace v2
-
 }  // namespace android::idmap2
 
 #endif  // IDMAP2_INCLUDE_IDMAP2_RESULT_H_
diff --git a/cmds/idmap2/libidmap2/Idmap.cpp b/cmds/idmap2/libidmap2/Idmap.cpp
index ec498ff..a1341fb 100644
--- a/cmds/idmap2/libidmap2/Idmap.cpp
+++ b/cmds/idmap2/libidmap2/Idmap.cpp
@@ -121,7 +121,9 @@
 Result<uint32_t> GetCrc(const ZipFile& zip) {
   const Result<uint32_t> a = zip.Crc("resources.arsc");
   const Result<uint32_t> b = zip.Crc("AndroidManifest.xml");
-  return a && b ? Result<uint32_t>(*a ^ *b) : kResultError;
+  return a && b
+             ? Result<uint32_t>(*a ^ *b)
+             : Error("Couldn't get CRC for \"%s\"", a ? "AndroidManifest.xml" : "resources.arsc");
 }
 
 }  // namespace
@@ -355,9 +357,9 @@
     return nullptr;
   }
 
-  Result<utils::OverlayManifestInfo> overlay_info =
-      utils::ExtractOverlayManifestInfo(overlay_apk_path, out_error);
+  auto overlay_info = utils::ExtractOverlayManifestInfo(overlay_apk_path);
   if (!overlay_info) {
+    out_error << "error: " << overlay_info.GetErrorMessage() << std::endl;
     return nullptr;
   }
 
diff --git a/cmds/idmap2/libidmap2/Policies.cpp b/cmds/idmap2/libidmap2/Policies.cpp
index 6649288..c6ba87d 100644
--- a/cmds/idmap2/libidmap2/Policies.cpp
+++ b/cmds/idmap2/libidmap2/Policies.cpp
@@ -16,7 +16,6 @@
 
 #include <iterator>
 #include <map>
-#include <sstream>
 #include <string>
 #include <vector>
 
@@ -39,16 +38,14 @@
 };
 }  // namespace
 
-Result<PolicyBitmask> PoliciesToBitmask(const std::vector<std::string>& policies,
-                                        std::ostream& err) {
+Result<PolicyBitmask> PoliciesToBitmask(const std::vector<std::string>& policies) {
   PolicyBitmask bitmask = 0;
   for (const std::string& policy : policies) {
     const auto iter = kStringToFlag.find(policy);
     if (iter != kStringToFlag.end()) {
       bitmask |= iter->second;
     } else {
-      err << "error: unknown policy \"" << policy << "\"";
-      return kResultError;
+      return Error("unknown policy \"%s\"", policy.c_str());
     }
   }
 
diff --git a/cmds/idmap2/libidmap2/RawPrintVisitor.cpp b/cmds/idmap2/libidmap2/RawPrintVisitor.cpp
index b78e942..1149c90 100644
--- a/cmds/idmap2/libidmap2/RawPrintVisitor.cpp
+++ b/cmds/idmap2/libidmap2/RawPrintVisitor.cpp
@@ -75,7 +75,7 @@
                                             type_entry.GetEntryOffset() + i);
       const ResourceId overlay_resid =
           RESID(last_seen_package_id_, type_entry.GetOverlayTypeId(), entry);
-      Result<std::string> name;
+      Result<std::string> name(Error(""));
       if (target_package_loaded) {
         name = utils::ResToTypeEntryName(target_am_, target_resid);
       }
diff --git a/cmds/idmap2/libidmap2/ResourceUtils.cpp b/cmds/idmap2/libidmap2/ResourceUtils.cpp
index 7a984f3..a24836d 100644
--- a/cmds/idmap2/libidmap2/ResourceUtils.cpp
+++ b/cmds/idmap2/libidmap2/ResourceUtils.cpp
@@ -33,10 +33,10 @@
 
 namespace android::idmap2::utils {
 
-Result<std::string> WARN_UNUSED ResToTypeEntryName(const AssetManager2& am, ResourceId resid) {
+Result<std::string> ResToTypeEntryName(const AssetManager2& am, ResourceId resid) {
   AssetManager2::ResourceName name;
   if (!am.GetResourceName(resid, &name)) {
-    return {};
+    return Error("no resource 0x%08x in asset manager", resid);
   }
   std::string out;
   if (name.type != nullptr) {
@@ -50,36 +50,31 @@
   } else {
     out += Utf16ToUtf8(StringPiece16(name.entry16, name.entry_len));
   }
-  return {out};
+  return out;
 }
 
 Result<OverlayManifestInfo> ExtractOverlayManifestInfo(const std::string& path,
-                                                       std::ostream& out_error,
                                                        bool assert_overlay) {
   std::unique_ptr<const ZipFile> zip = ZipFile::Open(path);
   if (!zip) {
-    out_error << "error: failed to open " << path << " as a zip file" << std::endl;
-    return kResultError;
+    return Error("failed to open %s as a zip file", path.c_str());
   }
 
   std::unique_ptr<const MemoryChunk> entry = zip->Uncompress("AndroidManifest.xml");
   if (!entry) {
-    out_error << "error: failed to uncompress AndroidManifest.xml from " << path << std::endl;
-    return kResultError;
+    return Error("failed to uncompress AndroidManifest.xml from %s", path.c_str());
   }
 
   std::unique_ptr<const Xml> xml = Xml::Create(entry->buf, entry->size);
   if (!xml) {
-    out_error << "error: failed to parse AndroidManifest.xml from " << path << std::endl;
-    return kResultError;
+    return Error("failed to parse AndroidManifest.xml from %s", path.c_str());
   }
 
   OverlayManifestInfo info{};
   const auto tag = xml->FindTag("overlay");
   if (!tag) {
     if (assert_overlay) {
-      out_error << "error: <overlay> missing from AndroidManifest.xml of " << path << std::endl;
-      return kResultError;
+      return Error("<overlay> missing from AndroidManifest.xml of %s", path.c_str());
     }
     return info;
   }
@@ -87,8 +82,7 @@
   auto iter = tag->find("targetPackage");
   if (iter == tag->end()) {
     if (assert_overlay) {
-      out_error << "error: android:targetPackage missing from <overlay> of " << path << std::endl;
-      return kResultError;
+      return Error("android:targetPackage missing from <overlay> of %s", path.c_str());
     }
   } else {
     info.target_package = iter->second;
diff --git a/cmds/idmap2/libidmap2/Result.cpp b/cmds/idmap2/libidmap2/Result.cpp
index bd4fabd..471dab2 100644
--- a/cmds/idmap2/libidmap2/Result.cpp
+++ b/cmds/idmap2/libidmap2/Result.cpp
@@ -23,7 +23,7 @@
 namespace android::idmap2 {
 
 // NOLINTNEXTLINE(cert-dcl50-cpp)
-v2::Error::Error(const char* fmt, ...) {
+Error::Error(const char* fmt, ...) {
   va_list ap;
   va_start(ap, fmt);
   base::StringAppendV(&msg_, fmt, ap);
@@ -31,7 +31,7 @@
 }
 
 // NOLINTNEXTLINE(cert-dcl50-cpp)
-v2::Error::Error(const Error& parent, const char* fmt, ...) : msg_(parent.msg_) {
+Error::Error(const Error& parent, const char* fmt, ...) : msg_(parent.msg_) {
   msg_.append(" -> ");
 
   va_list ap;
diff --git a/cmds/idmap2/libidmap2/ZipFile.cpp b/cmds/idmap2/libidmap2/ZipFile.cpp
index 15ec3f9..0f07324 100644
--- a/cmds/idmap2/libidmap2/ZipFile.cpp
+++ b/cmds/idmap2/libidmap2/ZipFile.cpp
@@ -59,7 +59,10 @@
 Result<uint32_t> ZipFile::Crc(const std::string& entryPath) const {
   ::ZipEntry entry;
   int32_t status = ::FindEntry(handle_, ::ZipString(entryPath.c_str()), &entry);
-  return status == 0 ? Result<uint32_t>(entry.crc32) : kResultError;
+  if (status != 0) {
+    return Error("failed to find zip entry %s", entryPath.c_str());
+  }
+  return entry.crc32;
 }
 
 }  // namespace android::idmap2
diff --git a/cmds/idmap2/tests/FileUtilsTests.cpp b/cmds/idmap2/tests/FileUtilsTests.cpp
index 2e85eb6..34a0097 100644
--- a/cmds/idmap2/tests/FileUtilsTests.cpp
+++ b/cmds/idmap2/tests/FileUtilsTests.cpp
@@ -58,21 +58,15 @@
   });
   ASSERT_THAT(v, NotNull());
   ASSERT_EQ(v->size(), 10U);
-  ASSERT_EQ(
-      std::set<std::string>(v->begin(), v->end()),
-      std::set<std::string>(
-          {
-              root + "/target/target.apk",
-              root + "/target/target-no-overlayable.apk",
-              root + "/overlay/overlay.apk",
-              root + "/overlay/overlay-no-name.apk",
-              root + "/overlay/overlay-no-name-static.apk",
-              root + "/overlay/overlay-static-1.apk",
-              root + "/overlay/overlay-static-2.apk",
-              root + "/signature-overlay/signature-overlay.apk",
-              root + "/system-overlay/system-overlay.apk",
-              root + "/system-overlay-invalid/system-overlay-invalid.apk"
-          }));
+  ASSERT_EQ(std::set<std::string>(v->begin(), v->end()),
+            std::set<std::string>(
+                {root + "/target/target.apk", root + "/target/target-no-overlayable.apk",
+                 root + "/overlay/overlay.apk", root + "/overlay/overlay-no-name.apk",
+                 root + "/overlay/overlay-no-name-static.apk",
+                 root + "/overlay/overlay-static-1.apk", root + "/overlay/overlay-static-2.apk",
+                 root + "/signature-overlay/signature-overlay.apk",
+                 root + "/system-overlay/system-overlay.apk",
+                 root + "/system-overlay-invalid/system-overlay-invalid.apk"}));
 }
 
 TEST(FileUtilsTests, ReadFile) {
diff --git a/cmds/idmap2/tests/IdmapTests.cpp b/cmds/idmap2/tests/IdmapTests.cpp
index 53ec03b..bbfbad9 100644
--- a/cmds/idmap2/tests/IdmapTests.cpp
+++ b/cmds/idmap2/tests/IdmapTests.cpp
@@ -256,10 +256,10 @@
   ASSERT_EQ(types[0]->GetOverlayTypeId(), 0x01U);
   ASSERT_EQ(types[0]->GetEntryCount(), 4U);
   ASSERT_EQ(types[0]->GetEntryOffset(), 6U);
-  ASSERT_EQ(types[0]->GetEntry(0), 0x0000U);  // string/policy_public
-  ASSERT_EQ(types[0]->GetEntry(1), kNoEntry); // string/policy_signature
-  ASSERT_EQ(types[0]->GetEntry(2), 0x0001U);  // string/policy_system
-  ASSERT_EQ(types[0]->GetEntry(3), 0x0002U);  // string/policy_system_vendor
+  ASSERT_EQ(types[0]->GetEntry(0), 0x0000U);   // string/policy_public
+  ASSERT_EQ(types[0]->GetEntry(1), kNoEntry);  // string/policy_signature
+  ASSERT_EQ(types[0]->GetEntry(2), 0x0001U);   // string/policy_system
+  ASSERT_EQ(types[0]->GetEntry(3), 0x0002U);   // string/policy_system_vendor
 }
 
 TEST(IdmapOverlayableTests, CreateIdmapFromApkAssetsPolicySignature) {
@@ -267,7 +267,8 @@
   std::unique_ptr<const ApkAssets> target_apk = ApkAssets::Load(target_apk_path);
   ASSERT_THAT(target_apk, NotNull());
 
-  const std::string overlay_apk_path(GetTestDataPath() + "/signature-overlay/signature-overlay.apk");
+  const std::string overlay_apk_path(GetTestDataPath() +
+                                     "/signature-overlay/signature-overlay.apk");
   std::unique_ptr<const ApkAssets> overlay_apk = ApkAssets::Load(overlay_apk_path);
   ASSERT_THAT(overlay_apk, NotNull());
 
@@ -294,7 +295,7 @@
   ASSERT_EQ(types[0]->GetOverlayTypeId(), 0x01U);
   ASSERT_EQ(types[0]->GetEntryCount(), 1U);
   ASSERT_EQ(types[0]->GetEntryOffset(), 7U);
-  ASSERT_EQ(types[0]->GetEntry(0), 0x0000U); // string/policy_signature
+  ASSERT_EQ(types[0]->GetEntry(0), 0x0000U);  // string/policy_signature
 }
 
 TEST(IdmapOverlayableTests, CreateIdmapFromApkAssetsPolicySignatureNotFulfilled) {
@@ -302,7 +303,8 @@
   std::unique_ptr<const ApkAssets> target_apk = ApkAssets::Load(target_apk_path);
   ASSERT_THAT(target_apk, NotNull());
 
-  const std::string overlay_apk_path(GetTestDataPath() + "/signature-overlay/signature-overlay.apk");
+  const std::string overlay_apk_path(GetTestDataPath() +
+                                     "/signature-overlay/signature-overlay.apk");
   std::unique_ptr<const ApkAssets> overlay_apk = ApkAssets::Load(overlay_apk_path);
   ASSERT_THAT(overlay_apk, NotNull());
 
@@ -323,7 +325,7 @@
   ASSERT_EQ(data->GetHeader()->GetTypeCount(), 0U);
 
   const std::vector<std::unique_ptr<const IdmapData::TypeEntry>>& types = data->GetTypeEntries();
-  ASSERT_EQ(types.size(), 0U); // can't overlay, so contains nothing
+  ASSERT_EQ(types.size(), 0U);  // can't overlay, so contains nothing
 }
 
 // Overlays should abide by all overlayable restrictions if enforcement of overlayable is enabled.
@@ -359,10 +361,10 @@
   ASSERT_EQ(types[0]->GetOverlayTypeId(), 0x01U);
   ASSERT_EQ(types[0]->GetEntryCount(), 4U);
   ASSERT_EQ(types[0]->GetEntryOffset(), 6U);
-  ASSERT_EQ(types[0]->GetEntry(0), 0x0003U);  // string/policy_public
-  ASSERT_EQ(types[0]->GetEntry(1), kNoEntry); // string/policy_signature
-  ASSERT_EQ(types[0]->GetEntry(2), 0x0005U);  // string/policy_system
-  ASSERT_EQ(types[0]->GetEntry(3), 0x0006U);  // string/policy_system_vendor
+  ASSERT_EQ(types[0]->GetEntry(0), 0x0003U);   // string/policy_public
+  ASSERT_EQ(types[0]->GetEntry(1), kNoEntry);  // string/policy_signature
+  ASSERT_EQ(types[0]->GetEntry(2), 0x0005U);   // string/policy_system
+  ASSERT_EQ(types[0]->GetEntry(3), 0x0006U);   // string/policy_system_vendor
 }
 
 // Overlays should ignore all overlayable restrictions if enforcement of overlayable is disabled.
diff --git a/cmds/idmap2/tests/PoliciesTests.cpp b/cmds/idmap2/tests/PoliciesTests.cpp
index ab567ad..a76da53 100644
--- a/cmds/idmap2/tests/PoliciesTests.cpp
+++ b/cmds/idmap2/tests/PoliciesTests.cpp
@@ -27,44 +27,42 @@
 namespace android::idmap2 {
 
 TEST(PoliciesTests, PoliciesToBitmasks) {
-  const Result<PolicyBitmask> bitmask1 = PoliciesToBitmask({"system"}, std::cerr);
-  ASSERT_NE(bitmask1, kResultError);
-  ASSERT_EQ(bitmask1, PolicyFlags::POLICY_SYSTEM_PARTITION);
+  const auto bitmask1 = PoliciesToBitmask({"system"});
+  ASSERT_TRUE(bitmask1);
+  ASSERT_EQ(*bitmask1, PolicyFlags::POLICY_SYSTEM_PARTITION);
 
-  const Result<PolicyBitmask> bitmask2 = PoliciesToBitmask({"system", "vendor"}, std::cerr);
-  ASSERT_NE(bitmask2, kResultError);
-  ASSERT_EQ(bitmask2, PolicyFlags::POLICY_SYSTEM_PARTITION | PolicyFlags::POLICY_VENDOR_PARTITION);
+  const auto bitmask2 = PoliciesToBitmask({"system", "vendor"});
+  ASSERT_TRUE(bitmask2);
+  ASSERT_EQ(*bitmask2, PolicyFlags::POLICY_SYSTEM_PARTITION | PolicyFlags::POLICY_VENDOR_PARTITION);
 
-  const Result<PolicyBitmask> bitmask3 = PoliciesToBitmask({"vendor", "system"}, std::cerr);
-  ASSERT_NE(bitmask3, kResultError);
-  ASSERT_EQ(bitmask3, PolicyFlags::POLICY_SYSTEM_PARTITION | PolicyFlags::POLICY_VENDOR_PARTITION);
+  const auto bitmask3 = PoliciesToBitmask({"vendor", "system"});
+  ASSERT_TRUE(bitmask3);
+  ASSERT_EQ(*bitmask3, PolicyFlags::POLICY_SYSTEM_PARTITION | PolicyFlags::POLICY_VENDOR_PARTITION);
 
-  const Result<PolicyBitmask> bitmask4 =
-      PoliciesToBitmask({"public", "product", "system", "vendor"}, std::cerr);
-  ASSERT_NE(bitmask4, kResultError);
-  ASSERT_EQ(bitmask4, PolicyFlags::POLICY_PUBLIC | PolicyFlags::POLICY_PRODUCT_PARTITION |
-                          PolicyFlags::POLICY_SYSTEM_PARTITION |
-                          PolicyFlags::POLICY_VENDOR_PARTITION);
+  const auto bitmask4 = PoliciesToBitmask({"public", "product", "system", "vendor"});
+  ASSERT_TRUE(bitmask4);
+  ASSERT_EQ(*bitmask4, PolicyFlags::POLICY_PUBLIC | PolicyFlags::POLICY_PRODUCT_PARTITION |
+                           PolicyFlags::POLICY_SYSTEM_PARTITION |
+                           PolicyFlags::POLICY_VENDOR_PARTITION);
 
-  const Result<PolicyBitmask> bitmask5 =
-      PoliciesToBitmask({"system", "system", "system"}, std::cerr);
-  ASSERT_NE(bitmask5, kResultError);
-  ASSERT_EQ(bitmask5, PolicyFlags::POLICY_SYSTEM_PARTITION);
+  const auto bitmask5 = PoliciesToBitmask({"system", "system", "system"});
+  ASSERT_TRUE(bitmask5);
+  ASSERT_EQ(*bitmask5, PolicyFlags::POLICY_SYSTEM_PARTITION);
 
-  const Result<PolicyBitmask> bitmask6 = PoliciesToBitmask({""}, std::cerr);
-  ASSERT_EQ(bitmask6, kResultError);
+  const auto bitmask6 = PoliciesToBitmask({""});
+  ASSERT_FALSE(bitmask6);
 
-  const Result<PolicyBitmask> bitmask7 = PoliciesToBitmask({"foo"}, std::cerr);
-  ASSERT_EQ(bitmask7, kResultError);
+  const auto bitmask7 = PoliciesToBitmask({"foo"});
+  ASSERT_FALSE(bitmask7);
 
-  const Result<PolicyBitmask> bitmask8 = PoliciesToBitmask({"system", "foo"}, std::cerr);
-  ASSERT_EQ(bitmask8, kResultError);
+  const auto bitmask8 = PoliciesToBitmask({"system", "foo"});
+  ASSERT_FALSE(bitmask8);
 
-  const Result<PolicyBitmask> bitmask9 = PoliciesToBitmask({"system", ""}, std::cerr);
-  ASSERT_EQ(bitmask9, kResultError);
+  const auto bitmask9 = PoliciesToBitmask({"system", ""});
+  ASSERT_FALSE(bitmask9);
 
-  const Result<PolicyBitmask> bitmask10 = PoliciesToBitmask({"system "}, std::cerr);
-  ASSERT_EQ(bitmask10, kResultError);
+  const auto bitmask10 = PoliciesToBitmask({"system "});
+  ASSERT_FALSE(bitmask10);
 }
 
 }  // namespace android::idmap2
diff --git a/cmds/idmap2/tests/ResultTests.cpp b/cmds/idmap2/tests/ResultTests.cpp
index d82f0c4..5f4daed 100644
--- a/cmds/idmap2/tests/ResultTests.cpp
+++ b/cmds/idmap2/tests/ResultTests.cpp
@@ -32,28 +32,28 @@
 // Tests: Error
 
 TEST(ResultTests, ErrorTraits) {
-  ASSERT_TRUE(std::is_move_constructible<v2::Error>::value);
-  ASSERT_TRUE(std::is_move_assignable<v2::Error>::value);
-  ASSERT_TRUE(std::is_copy_constructible<v2::Error>::value);
-  ASSERT_TRUE(std::is_copy_assignable<v2::Error>::value);
+  ASSERT_TRUE(std::is_move_constructible<Error>::value);
+  ASSERT_TRUE(std::is_move_assignable<Error>::value);
+  ASSERT_TRUE(std::is_copy_constructible<Error>::value);
+  ASSERT_TRUE(std::is_copy_assignable<Error>::value);
 }
 
 TEST(ResultTests, ErrorCtorFormat) {
-  v2::Error e("%s=0x%08x", "resid", 0x7f010002);
+  Error e("%s=0x%08x", "resid", 0x7f010002);
   ASSERT_EQ(e.GetMessage(), "resid=0x7f010002");
 }
 
 TEST(ResultTests, ErrorPropagateParent) {
-  v2::Error e1("foo");
+  Error e1("foo");
   ASSERT_EQ(e1.GetMessage(), "foo");
 
-  v2::Error e2(e1, "bar");
+  Error e2(e1, "bar");
   ASSERT_EQ(e2.GetMessage(), "foo -> bar");
 
-  v2::Error e3(e2);  // NOLINT(performance-unnecessary-copy-initialization)
+  Error e3(e2);  // NOLINT(performance-unnecessary-copy-initialization)
   ASSERT_EQ(e3.GetMessage(), "foo -> bar");
 
-  v2::Error e4(e3, "%02d", 1);
+  Error e4(e3, "%02d", 1);
   ASSERT_EQ(e4.GetMessage(), "foo -> bar -> 01");
 }
 
@@ -61,13 +61,13 @@
 
 // Result(const Result&)
 TEST(ResultTests, CopyConstructor) {
-  v2::Result<uint32_t> r1(42U);
+  Result<uint32_t> r1(42U);
 
-  v2::Result<uint32_t> r2(r1);
+  Result<uint32_t> r2(r1);
   ASSERT_TRUE(r2);
   ASSERT_EQ(*r2, 42U);
 
-  v2::Result<uint32_t> r3 = r2;
+  Result<uint32_t> r3 = r2;
   ASSERT_TRUE(r3);
   ASSERT_EQ(*r3, 42U);
 }
@@ -75,23 +75,23 @@
 // Result(const T&)
 TEST(ResultTests, Constructor) {
   uint32_t v = 42U;
-  v2::Result<uint32_t> r1(v);
+  Result<uint32_t> r1(v);
   ASSERT_TRUE(r1);
   ASSERT_EQ(*r1, 42U);
 
-  v2::Error e("foo");
-  v2::Result<uint32_t> r2(e);
+  Error e("foo");
+  Result<uint32_t> r2(e);
   ASSERT_FALSE(r2);
   ASSERT_EQ(r2.GetErrorMessage(), "foo");
 }
 
 // Result(const T&&)
 TEST(ResultTests, MoveConstructor) {
-  v2::Result<uint32_t> r1(42U);
+  Result<uint32_t> r1(42U);
   ASSERT_TRUE(r1);
   ASSERT_EQ(*r1, 42U);
 
-  v2::Result<uint32_t> r2(v2::Error("foo"));
+  Result<uint32_t> r2(Error("foo"));
   ASSERT_FALSE(r2);
   ASSERT_EQ(r2.GetErrorMessage(), "foo");
 }
@@ -99,52 +99,52 @@
 // operator=
 TEST(ResultTests, CopyAssignmentOperator) {
   // note: 'Result<...> r2 = r1;' calls the copy ctor
-  v2::Result<uint32_t> r1(42U);
-  v2::Result<uint32_t> r2(0U);
+  Result<uint32_t> r1(42U);
+  Result<uint32_t> r2(0U);
   r2 = r1;
   ASSERT_TRUE(r2);
   ASSERT_EQ(*r2, 42U);
 
-  v2::Result<uint32_t> r3(v2::Error("foo"));
+  Result<uint32_t> r3(Error("foo"));
   r2 = r3;
   ASSERT_FALSE(r2);
   ASSERT_EQ(r2.GetErrorMessage(), "foo");
 }
 
 TEST(ResultTests, MoveAssignmentOperator) {
-  v2::Result<uint32_t> r(0U);
-  r = v2::Result<uint32_t>(42U);
+  Result<uint32_t> r(0U);
+  r = Result<uint32_t>(42U);
   ASSERT_TRUE(r);
   ASSERT_EQ(*r, 42U);
 
-  r = v2::Result<uint32_t>(v2::Error("foo"));
+  r = Result<uint32_t>(Error("foo"));
   ASSERT_FALSE(r);
   ASSERT_EQ(r.GetErrorMessage(), "foo");
 }
 
 // operator bool()
 TEST(ResultTests, BoolOperator) {
-  v2::Result<uint32_t> r1(42U);
+  Result<uint32_t> r1(42U);
   ASSERT_TRUE(r1);
   ASSERT_EQ(*r1, 42U);
 
-  v2::Result<uint32_t> r2(v2::Error("foo"));
+  Result<uint32_t> r2(Error("foo"));
   ASSERT_FALSE(r2);
   ASSERT_EQ(r2.GetErrorMessage(), "foo");
 }
 
 // operator*
 TEST(ResultTests, IndirectionOperator) {
-  const v2::Result<uint32_t> r1(42U);
+  const Result<uint32_t> r1(42U);
   ASSERT_TRUE(r1);
   ASSERT_EQ(*r1, 42U);
 
-  const v2::Result<Container> r2(Container{42U});
+  const Result<Container> r2(Container{42U});
   ASSERT_TRUE(r2);
   const Container& c = *r2;
   ASSERT_EQ(c.value, 42U);
 
-  v2::Result<Container> r3(Container{42U});
+  Result<Container> r3(Container{42U});
   ASSERT_TRUE(r3);
   ASSERT_EQ((*r3).value, 42U);
   (*r3).value = 0U;
@@ -153,11 +153,11 @@
 
 // operator->
 TEST(ResultTests, DereferenceOperator) {
-  const v2::Result<Container> r1(Container{42U});
+  const Result<Container> r1(Container{42U});
   ASSERT_TRUE(r1);
   ASSERT_EQ(r1->value, 42U);
 
-  v2::Result<Container> r2(Container{42U});
+  Result<Container> r2(Container{42U});
   ASSERT_TRUE(r2);
   ASSERT_EQ(r2->value, 42U);
   r2->value = 0U;
@@ -167,14 +167,14 @@
 // Tests: intended use of Result<T>
 
 TEST(ResultTests, ResultTraits) {
-  ASSERT_TRUE(std::is_move_constructible<v2::Result<uint32_t>>::value);
-  ASSERT_TRUE(std::is_move_assignable<v2::Result<uint32_t>>::value);
-  ASSERT_TRUE(std::is_copy_constructible<v2::Result<uint32_t>>::value);
-  ASSERT_TRUE(std::is_copy_assignable<v2::Result<uint32_t>>::value);
+  ASSERT_TRUE(std::is_move_constructible<Result<uint32_t>>::value);
+  ASSERT_TRUE(std::is_move_assignable<Result<uint32_t>>::value);
+  ASSERT_TRUE(std::is_copy_constructible<Result<uint32_t>>::value);
+  ASSERT_TRUE(std::is_copy_assignable<Result<uint32_t>>::value);
 }
 
 TEST(ResultTests, UnitTypeResult) {
-  v2::Result<v2::Unit> r(v2::Unit{});
+  Result<Unit> r(Unit{});
   ASSERT_TRUE(r);
 }
 
@@ -220,16 +220,16 @@
   ASSERT_FALSE(std::is_copy_assignable<RefCountContainer>::value);
 
   RefCountData rc{0, 0, 0, 0};
-  { v2::Result<RefCountContainer> r(RefCountContainer{rc}); }
+  { Result<RefCountContainer> r(RefCountContainer{rc}); }
   ASSERT_EQ(rc.ctor, 1);
   ASSERT_EQ(rc.copy_ctor, 1);
   ASSERT_EQ(rc.move, 0);
   ASSERT_EQ(rc.dtor, 2);
 }
 
-v2::Result<Container> CreateContainer(bool succeed) {
+Result<Container> CreateContainer(bool succeed) {
   if (!succeed) {
-    return v2::Error("foo");
+    return Error("foo");
   }
   return Container{42U};
 }
@@ -245,10 +245,10 @@
   ASSERT_EQ(r2.GetError().GetMessage(), "foo");
 }
 
-v2::Result<Container> FailToCreateContainer() {
+Result<Container> FailToCreateContainer() {
   auto container = CreateContainer(false);
   if (!container) {
-    return v2::Error(container.GetError(), "bar");
+    return Error(container.GetError(), "bar");
   }
   return container;
 }
@@ -264,9 +264,9 @@
   DISALLOW_COPY_AND_ASSIGN(NoCopyContainer);
 };
 
-v2::Result<std::unique_ptr<NoCopyContainer>> CreateNoCopyContainer(bool succeed) {
+Result<std::unique_ptr<NoCopyContainer>> CreateNoCopyContainer(bool succeed) {
   if (!succeed) {
-    return v2::Error("foo");
+    return Error("foo");
   }
   std::unique_ptr<NoCopyContainer> p(new NoCopyContainer{0U});
   p->value = 42U;
diff --git a/cmds/input/src/com/android/commands/input/Input.java b/cmds/input/src/com/android/commands/input/Input.java
index 0c861cf..a077745 100644
--- a/cmds/input/src/com/android/commands/input/Input.java
+++ b/cmds/input/src/com/android/commands/input/Input.java
@@ -196,7 +196,7 @@
             int repeatCount = 0;
 
             KeyEvent event = new KeyEvent(now, now, KeyEvent.ACTION_DOWN, keyCode, repeatCount,
-                    0 /*metaState*/, KeyCharacterMap.VIRTUAL_KEYBOARD, 0 /*scancode*/, 0/*flags*/,
+                    0 /*metaState*/, KeyCharacterMap.VIRTUAL_KEYBOARD, 0 /*scancode*/, 0 /*flags*/,
                     inputSource);
             event.setDisplayId(displayId);
 
diff --git a/cmds/sm/src/com/android/commands/sm/Sm.java b/cmds/sm/src/com/android/commands/sm/Sm.java
index be5a5bf..4a6f87f 100644
--- a/cmds/sm/src/com/android/commands/sm/Sm.java
+++ b/cmds/sm/src/com/android/commands/sm/Sm.java
@@ -103,6 +103,8 @@
             runSetVirtualDisk();
         } else if ("set-isolated-storage".equals(op)) {
             runIsolatedStorage();
+        } else if ("set-legacy-greylist".equals(op)) {
+            runLegacyGreylist();
         } else {
             throw new IllegalArgumentException();
         }
@@ -282,7 +284,7 @@
                 StorageManager.DEBUG_VIRTUAL_DISK);
     }
 
-    public void runIsolatedStorage() {
+    public void runIsolatedStorage() throws RemoteException {
         final int value;
         final int mask = StorageManager.DEBUG_ISOLATED_STORAGE_FORCE_ON
                 | StorageManager.DEBUG_ISOLATED_STORAGE_FORCE_OFF;
@@ -301,16 +303,13 @@
             default:
                 return;
         }
+        mSm.setDebugFlags(value, mask);
+    }
 
-        // Toggling isolated-storage state will result in a device reboot. So to avoid this command
-        // from erroring out (DeadSystemException), call setDebugFlags() in a separate thread.
-        new Thread(() -> {
-            try {
-                mSm.setDebugFlags(value, mask);
-            } catch (RemoteException e) {
-                Log.e(TAG, "Encountered an error!", e);
-            }
-        }).start();
+    public void runLegacyGreylist() throws RemoteException {
+        final boolean legacyGreylist = Boolean.parseBoolean(nextArg());
+        mSm.setDebugFlags(legacyGreylist ? StorageManager.DEBUG_LEGACY_GREYLIST : 0,
+                StorageManager.DEBUG_LEGACY_GREYLIST);
     }
 
     public void runIdleMaint() throws RemoteException {
diff --git a/cmds/statsd/Android.bp b/cmds/statsd/Android.bp
index f408655..ca48881 100644
--- a/cmds/statsd/Android.bp
+++ b/cmds/statsd/Android.bp
@@ -346,3 +346,9 @@
         javacflags: ["-XepDisableAllChecks"],
     },
 }
+
+// Filegroup for statsd config proto definition.
+filegroup {
+    name: "statsd-config-proto-def",
+    srcs: ["src/statsd_config.proto"],
+}
diff --git a/cmds/statsd/src/atoms.proto b/cmds/statsd/src/atoms.proto
index 78e994f..b647400 100644
--- a/cmds/statsd/src/atoms.proto
+++ b/cmds/statsd/src/atoms.proto
@@ -45,6 +45,7 @@
 import "frameworks/base/core/proto/android/stats/devicepolicy/device_policy.proto";
 import "frameworks/base/core/proto/android/stats/devicepolicy/device_policy_enums.proto";
 import "frameworks/base/core/proto/android/stats/launcher/launcher.proto";
+import "frameworks/base/core/proto/android/stats/style/style_enums.proto";
 import "frameworks/base/core/proto/android/telecomm/enums.proto";
 import "frameworks/base/core/proto/android/telephony/enums.proto";
 import "frameworks/base/core/proto/android/view/enums.proto";
@@ -247,6 +248,7 @@
         AssistGestureProgressReported assist_gesture_progress_reported = 176;
         TouchGestureClassified touch_gesture_classified = 177;
         HiddenApiUsed hidden_api_used = 178 [(allow_from_any_uid) = true];
+        StyleUIChanged style_ui_changed = 179;
     }
 
     // Pulled events will start at field 10000.
@@ -283,7 +285,7 @@
         CategorySize category_size = 10028;
         ProcStats proc_stats = 10029;
         BatteryVoltage battery_voltage = 10030;
-        NumBiometricsEnrolled num_fingerprints_enrolled = 10031;
+        NumFingerprintsEnrolled num_fingerprints_enrolled = 10031;
         DiskIo disk_io = 10032;
         PowerProfile power_profile = 10033;
         ProcStatsPkgProc proc_stats_pkg_proc = 10034;
@@ -300,7 +302,7 @@
         BatteryCycleCount battery_cycle_count = 10045;
         DebugElapsedClock debug_elapsed_clock = 10046;
         DebugFailingElapsedClock debug_failing_elapsed_clock = 10047;
-        NumBiometricsEnrolled num_faces_enrolled = 10048;
+        NumFacesEnrolled num_faces_enrolled = 10048;
         RoleHolder role_holder = 10049;
         DangerousPermissionState dangerous_permission_state = 10050;
         TrainInfo train_info = 10051;
@@ -2349,6 +2351,17 @@
     optional bool is_swipe_up_enabled = 5;
 }
 
+message StyleUIChanged {
+    optional android.stats.style.Action action = 1;
+    optional int32 color_package_hash = 2;
+    optional int32 font_package_hash  = 3;
+    optional int32 shape_package_hash = 4;
+    optional int32 clock_package_hash = 5;
+    optional int32 launcher_grid = 6;
+    optional int32 wallpaper_category_hash = 7;
+    optional int32 wallpaper_id_hash = 8;
+}
+
 /**
  * Logs when Settings UI has changed.
  *
@@ -4114,15 +4127,27 @@
  *
  * Pulled from StatsCompanionService, which queries <Biometric>Manager.
  */
-message NumBiometricsEnrolled {
+message NumFingerprintsEnrolled {
     // The associated user. Eg: 0 for owners, 10+ for others.
     // Defined in android/os/UserHandle.java
     optional int32 user = 1;
     // Number of fingerprints registered to that user.
-    optional int32 num_enrolled = 2;
+    optional int32 num_fingerprints_enrolled = 2;
 }
 
 /**
+ * Pulls the number of faces for each user.
+ *
+ * Pulled from StatsCompanionService, which queries <Biometric>Manager.
+ */
+message NumFacesEnrolled {
+    // The associated user. Eg: 0 for owners, 10+ for others.
+    // Defined in android/os/UserHandle.java
+    optional int32 user = 1;
+    // Number of faces registered to that user.
+    optional int32 num_faces_enrolled = 2;
+}
+/**
  * A mapping of role holder -> role
  */
 message RoleHolder {
@@ -5503,8 +5528,9 @@
     optional com.android.server.job.ConstraintEnum constraint = 3;
 
     enum State {
-        UNSATISFIED = 0;
-        SATISFIED = 1;
+        UNKNOWN = 0;
+        UNSATISFIED = 1;
+        SATISFIED = 2;
     }
     optional State state = 4;
 }
diff --git a/cmds/statsd/src/external/PowerStatsPuller.cpp b/cmds/statsd/src/external/PowerStatsPuller.cpp
index 71e5fa0..c56f9a2 100644
--- a/cmds/statsd/src/external/PowerStatsPuller.cpp
+++ b/cmds/statsd/src/external/PowerStatsPuller.cpp
@@ -39,17 +39,40 @@
 namespace os {
 namespace statsd {
 
-sp<android::hardware::power::stats::V1_0::IPowerStats> gPowerStatsHal = nullptr;
-std::mutex gPowerStatsHalMutex;
-bool gPowerStatsExist = true; // Initialized to ensure making a first attempt.
-std::vector<RailInfo> gRailInfo;
+static sp<android::hardware::power::stats::V1_0::IPowerStats> gPowerStatsHal = nullptr;
+static std::mutex gPowerStatsHalMutex;
+static bool gPowerStatsExist = true; // Initialized to ensure making a first attempt.
+static std::vector<RailInfo> gRailInfo;
 
-bool getPowerStatsHal() {
+struct PowerStatsPullerDeathRecipient : virtual public hardware::hidl_death_recipient {
+    virtual void serviceDied(uint64_t cookie,
+            const wp<android::hidl::base::V1_0::IBase>& who) override {
+        // The HAL just died. Reset all handles to HAL services.
+        std::lock_guard<std::mutex> lock(gPowerStatsHalMutex);
+        gPowerStatsHal = nullptr;
+    }
+};
+
+static sp<PowerStatsPullerDeathRecipient> gDeathRecipient = new PowerStatsPullerDeathRecipient();
+
+static bool getPowerStatsHalLocked() {
     if (gPowerStatsHal == nullptr && gPowerStatsExist) {
         gPowerStatsHal = android::hardware::power::stats::V1_0::IPowerStats::getService();
         if (gPowerStatsHal == nullptr) {
             ALOGW("Couldn't load power.stats HAL service");
             gPowerStatsExist = false;
+        } else {
+            // Link death recipient to power.stats service handle
+            hardware::Return<bool> linked = gPowerStatsHal->linkToDeath(gDeathRecipient, 0);
+            if (!linked.isOk()) {
+                ALOGE("Transaction error in linking to power.stats HAL death: %s",
+                        linked.description().c_str());
+                gPowerStatsHal = nullptr;
+                return false;
+            } else if (!linked) {
+                ALOGW("Unable to link to power.stats HAL death notifications");
+                // We should still continue even though linking failed
+            }
         }
     }
     return gPowerStatsHal != nullptr;
@@ -61,7 +84,7 @@
 bool PowerStatsPuller::PullInternal(vector<shared_ptr<LogEvent>>* data) {
     std::lock_guard<std::mutex> lock(gPowerStatsHalMutex);
 
-    if (!getPowerStatsHal()) {
+    if (!getPowerStatsHalLocked()) {
         ALOGE("power.stats Hal not loaded");
         return false;
     }
diff --git a/cmds/statsd/src/external/SubsystemSleepStatePuller.cpp b/cmds/statsd/src/external/SubsystemSleepStatePuller.cpp
index d822959..f6a4aea 100644
--- a/cmds/statsd/src/external/SubsystemSleepStatePuller.cpp
+++ b/cmds/statsd/src/external/SubsystemSleepStatePuller.cpp
@@ -60,41 +60,43 @@
 namespace os {
 namespace statsd {
 
-std::function<bool(vector<shared_ptr<LogEvent>>* data)> gPuller = {};
+static std::function<bool(vector<shared_ptr<LogEvent>>* data)> gPuller = {};
 
-sp<android::hardware::power::V1_0::IPower> gPowerHalV1_0 = nullptr;
-sp<android::hardware::power::V1_1::IPower> gPowerHalV1_1 = nullptr;
-sp<android::hardware::power::stats::V1_0::IPowerStats> gPowerStatsHalV1_0 = nullptr;
+static sp<android::hardware::power::V1_0::IPower> gPowerHalV1_0 = nullptr;
+static sp<android::hardware::power::V1_1::IPower> gPowerHalV1_1 = nullptr;
+static sp<android::hardware::power::stats::V1_0::IPowerStats> gPowerStatsHalV1_0 = nullptr;
 
-std::unordered_map<uint32_t, std::string> gEntityNames = {};
-std::unordered_map<uint32_t, std::unordered_map<uint32_t, std::string>> gStateNames = {};
+static std::unordered_map<uint32_t, std::string> gEntityNames = {};
+static std::unordered_map<uint32_t, std::unordered_map<uint32_t, std::string>> gStateNames = {};
 
-std::mutex gPowerHalMutex;
+static std::mutex gPowerHalMutex;
 
 // The caller must be holding gPowerHalMutex.
-void deinitPowerStatsLocked() {
+static void deinitPowerStatsLocked() {
     gPowerHalV1_0 = nullptr;
     gPowerHalV1_1 = nullptr;
     gPowerStatsHalV1_0 = nullptr;
 }
 
-struct PowerHalDeathRecipient : virtual public hardware::hidl_death_recipient {
+struct SubsystemSleepStatePullerDeathRecipient : virtual public hardware::hidl_death_recipient {
     virtual void serviceDied(uint64_t cookie,
-        const wp<android::hidl::base::V1_0::IBase>& who) override {
+            const wp<android::hidl::base::V1_0::IBase>& who) override {
+
         // The HAL just died. Reset all handles to HAL services.
         std::lock_guard<std::mutex> lock(gPowerHalMutex);
         deinitPowerStatsLocked();
     }
 };
 
-sp<PowerHalDeathRecipient> gDeathRecipient = new PowerHalDeathRecipient();
+static sp<SubsystemSleepStatePullerDeathRecipient> gDeathRecipient =
+        new SubsystemSleepStatePullerDeathRecipient();
 
 SubsystemSleepStatePuller::SubsystemSleepStatePuller() :
     StatsPuller(android::util::SUBSYSTEM_SLEEP_STATE) {
 }
 
 // The caller must be holding gPowerHalMutex.
-bool checkResultLocked(const Return<void> &ret, const char* function) {
+static bool checkResultLocked(const Return<void> &ret, const char* function) {
     if (!ret.isOk()) {
         ALOGE("%s failed: requested HAL service not available. Description: %s",
             function, ret.description().c_str());
@@ -108,7 +110,7 @@
 
 // The caller must be holding gPowerHalMutex.
 // gPowerStatsHalV1_0 must not be null
-bool initializePowerStats() {
+static bool initializePowerStats() {
     using android::hardware::power::stats::V1_0::Status;
 
     // Clear out previous content if we are re-initializing
@@ -155,7 +157,7 @@
 }
 
 // The caller must be holding gPowerHalMutex.
-bool getPowerStatsHalLocked() {
+static bool getPowerStatsHalLocked() {
     if(gPowerStatsHalV1_0 == nullptr) {
         gPowerStatsHalV1_0 = android::hardware::power::stats::V1_0::IPowerStats::getService();
         if (gPowerStatsHalV1_0 == nullptr) {
@@ -180,7 +182,7 @@
 }
 
 // The caller must be holding gPowerHalMutex.
-bool getIPowerStatsDataLocked(vector<shared_ptr<LogEvent>>* data) {
+static bool getIPowerStatsDataLocked(vector<shared_ptr<LogEvent>>* data) {
     using android::hardware::power::stats::V1_0::Status;
 
     if(!getPowerStatsHalLocked()) {
@@ -225,7 +227,7 @@
 }
 
 // The caller must be holding gPowerHalMutex.
-bool getPowerHalLocked() {
+static bool getPowerHalLocked() {
     if(gPowerHalV1_0 == nullptr) {
         gPowerHalV1_0 = android::hardware::power::V1_0::IPower::getService();
         if(gPowerHalV1_0 == nullptr) {
@@ -250,7 +252,7 @@
 }
 
 // The caller must be holding gPowerHalMutex.
-bool getIPowerDataLocked(vector<shared_ptr<LogEvent>>* data) {
+static bool getIPowerDataLocked(vector<shared_ptr<LogEvent>>* data) {
     using android::hardware::power::V1_0::Status;
 
     if(!getPowerHalLocked()) {
diff --git a/cmds/statsd/src/metrics/MetricProducer.h b/cmds/statsd/src/metrics/MetricProducer.h
index 99cb5d4..046f996 100644
--- a/cmds/statsd/src/metrics/MetricProducer.h
+++ b/cmds/statsd/src/metrics/MetricProducer.h
@@ -69,7 +69,7 @@
           mTimeBaseNs(timeBaseNs),
           mCurrentBucketStartTimeNs(timeBaseNs),
           mCurrentBucketNum(0),
-          mCondition(conditionIndex >= 0 ? ConditionState::kUnknown : ConditionState::kTrue),
+          mCondition(initialCondition(conditionIndex)),
           mConditionSliced(false),
           mWizard(wizard),
           mConditionTrackerIndex(conditionIndex),
@@ -82,6 +82,10 @@
 
     virtual ~MetricProducer(){};
 
+    ConditionState initialCondition(const int conditionIndex) const {
+        return conditionIndex >= 0 ? ConditionState::kUnknown : ConditionState::kTrue;
+    }
+
     /**
      * Forces this metric to split into a partial bucket right now. If we're past a full bucket, we
      * first call the standard flushing code to flush up to the latest full bucket. Then we call
diff --git a/cmds/statsd/src/metrics/ValueMetricProducer.cpp b/cmds/statsd/src/metrics/ValueMetricProducer.cpp
index 9de62a2..27ee570 100644
--- a/cmds/statsd/src/metrics/ValueMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/ValueMetricProducer.cpp
@@ -394,7 +394,7 @@
         invalidateCurrentBucket();
         // Something weird happened. If we received another event if the future, the condition might
         // be wrong.
-        mCondition = ConditionState::kUnknown;
+        mCondition = initialCondition(mConditionTrackerIndex);
     }
 
     // This part should alway be called.
diff --git a/config/hiddenapi-greylist.txt b/config/hiddenapi-greylist.txt
index aaff76e..e6ba40d 100644
--- a/config/hiddenapi-greylist.txt
+++ b/config/hiddenapi-greylist.txt
@@ -437,7 +437,6 @@
 Landroid/content/res/ConfigurationBoundResourceCache;-><init>()V
 Landroid/content/res/DrawableCache;-><init>()V
 Landroid/content/UndoManager;-><init>()V
-Landroid/database/BulkCursorProxy;->mRemote:Landroid/os/IBinder;
 Landroid/database/IContentObserver$Stub;-><init>()V
 Landroid/database/IContentObserver$Stub;->asInterface(Landroid/os/IBinder;)Landroid/database/IContentObserver;
 Landroid/database/IContentObserver;->onChange(ZLandroid/net/Uri;I)V
@@ -446,16 +445,13 @@
 Landroid/filterfw/GraphEnvironment;->addReferences([Ljava/lang/Object;)V
 Landroid/hardware/camera2/utils/HashCodeHelpers;->hashCode([I)I
 Landroid/hardware/display/IDisplayManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/hardware/display/IDisplayManager;
-Landroid/hardware/display/IDisplayManager;->getDisplayInfo(I)Landroid/view/DisplayInfo;
 Landroid/hardware/fingerprint/IFingerprintService$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Landroid/hardware/fingerprint/IFingerprintService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/hardware/fingerprint/IFingerprintService;
 Landroid/hardware/ICameraService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/hardware/ICameraService;
 Landroid/hardware/input/IInputManager$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Landroid/hardware/input/IInputManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/hardware/input/IInputManager;
 Landroid/hardware/input/IInputManager$Stub;->TRANSACTION_injectInputEvent:I
-Landroid/hardware/input/IInputManager;->injectInputEvent(Landroid/view/InputEvent;I)Z
 Landroid/hardware/location/IActivityRecognitionHardwareClient$Stub;-><init>()V
-Landroid/hardware/location/IActivityRecognitionHardwareClient;->onAvailabilityChanged(ZLandroid/hardware/location/IActivityRecognitionHardware;)V
 Landroid/hardware/location/IContextHubService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/hardware/location/IContextHubService;
 Landroid/hardware/usb/IUsbManager$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Landroid/hardware/usb/IUsbManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/hardware/usb/IUsbManager;
@@ -465,60 +461,33 @@
 Landroid/location/ICountryListener$Stub;-><init>()V
 Landroid/location/IGeocodeProvider$Stub;-><init>()V
 Landroid/location/IGeocodeProvider$Stub;->asInterface(Landroid/os/IBinder;)Landroid/location/IGeocodeProvider;
-Landroid/location/IGeocodeProvider;->getFromLocation(DDILandroid/location/GeocoderParams;Ljava/util/List;)Ljava/lang/String;
-Landroid/location/IGeocodeProvider;->getFromLocationName(Ljava/lang/String;DDDDILandroid/location/GeocoderParams;Ljava/util/List;)Ljava/lang/String;
 Landroid/location/IGeofenceProvider$Stub;-><init>()V
-Landroid/location/IGeofenceProvider;->setGeofenceHardware(Landroid/hardware/location/IGeofenceHardware;)V
 Landroid/location/ILocationListener$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Landroid/location/ILocationListener$Stub$Proxy;->mRemote:Landroid/os/IBinder;
 Landroid/location/ILocationListener$Stub;-><init>()V
 Landroid/location/ILocationListener$Stub;->asInterface(Landroid/os/IBinder;)Landroid/location/ILocationListener;
-Landroid/location/ILocationListener;->onLocationChanged(Landroid/location/Location;)V
-Landroid/location/ILocationListener;->onProviderDisabled(Ljava/lang/String;)V
-Landroid/location/ILocationListener;->onProviderEnabled(Ljava/lang/String;)V
-Landroid/location/ILocationListener;->onStatusChanged(Ljava/lang/String;ILandroid/os/Bundle;)V
 Landroid/location/ILocationManager$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Landroid/location/ILocationManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/location/ILocationManager;
 Landroid/location/ILocationManager$Stub;->TRANSACTION_getAllProviders:I
-Landroid/location/ILocationManager;->getAllProviders()Ljava/util/List;
 Landroid/location/INetInitiatedListener$Stub;-><init>()V
-Landroid/location/INetInitiatedListener;->sendNiResponse(II)Z
 Landroid/location/LocationManager$ListenerTransport;-><init>(Landroid/location/LocationManager;Landroid/location/LocationListener;Landroid/os/Looper;)V
 Landroid/Manifest$permission;->CAPTURE_SECURE_VIDEO_OUTPUT:Ljava/lang/String;
 Landroid/Manifest$permission;->CAPTURE_VIDEO_OUTPUT:Ljava/lang/String;
 Landroid/Manifest$permission;->READ_FRAME_BUFFER:Ljava/lang/String;
 Landroid/media/effect/SingleFilterEffect;-><init>(Landroid/media/effect/EffectContext;Ljava/lang/String;Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V
-Landroid/media/IAudioFocusDispatcher;->dispatchAudioFocusChange(ILjava/lang/String;)V
 Landroid/media/IAudioRoutesObserver$Stub;-><init>()V
 Landroid/media/IAudioService$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Landroid/media/IAudioService$Stub;-><init>()V
 Landroid/media/IAudioService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/media/IAudioService;
-Landroid/media/IAudioService;->getStreamMaxVolume(I)I
-Landroid/media/IAudioService;->getStreamVolume(I)I
-Landroid/media/IAudioService;->setStreamVolume(IIILjava/lang/String;)V
-Landroid/media/IAudioService;->startWatchingRoutes(Landroid/media/IAudioRoutesObserver;)Landroid/media/AudioRoutesInfo;
 Landroid/media/IMediaRouterService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/media/IMediaRouterService;
 Landroid/media/IMediaScannerListener$Stub;-><init>()V
 Landroid/media/IMediaScannerService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/media/IMediaScannerService;
-Landroid/media/IMediaScannerService;->requestScanFile(Ljava/lang/String;Ljava/lang/String;Landroid/media/IMediaScannerListener;)V
-Landroid/media/IMediaScannerService;->scanFile(Ljava/lang/String;Ljava/lang/String;)V
-Landroid/media/IRemoteDisplayCallback;->onStateChanged(Landroid/media/RemoteDisplayState;)V
 Landroid/media/IRingtonePlayer;->play(Landroid/os/IBinder;Landroid/net/Uri;Landroid/media/AudioAttributes;FZ)V
 Landroid/media/IVolumeController$Stub;->asInterface(Landroid/os/IBinder;)Landroid/media/IVolumeController;
 Landroid/media/MediaFile;-><init>()V
 Landroid/media/MediaScanner$MyMediaScannerClient;-><init>(Landroid/media/MediaScanner;)V
-Landroid/media/projection/IMediaProjectionManager;->hasProjectionPermission(ILjava/lang/String;)Z
 Landroid/media/session/ISessionManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/media/session/ISessionManager;
 Landroid/media/tv/ITvRemoteProvider$Stub;-><init>()V
-Landroid/media/tv/ITvRemoteServiceInput;->clearInputBridge(Landroid/os/IBinder;)V
-Landroid/media/tv/ITvRemoteServiceInput;->closeInputBridge(Landroid/os/IBinder;)V
-Landroid/media/tv/ITvRemoteServiceInput;->openInputBridge(Landroid/os/IBinder;Ljava/lang/String;III)V
-Landroid/media/tv/ITvRemoteServiceInput;->sendKeyDown(Landroid/os/IBinder;I)V
-Landroid/media/tv/ITvRemoteServiceInput;->sendKeyUp(Landroid/os/IBinder;I)V
-Landroid/media/tv/ITvRemoteServiceInput;->sendPointerDown(Landroid/os/IBinder;III)V
-Landroid/media/tv/ITvRemoteServiceInput;->sendPointerSync(Landroid/os/IBinder;)V
-Landroid/media/tv/ITvRemoteServiceInput;->sendPointerUp(Landroid/os/IBinder;I)V
-Landroid/media/tv/ITvRemoteServiceInput;->sendTimestamp(Landroid/os/IBinder;J)V
 Landroid/net/ConnectivityManager$PacketKeepaliveCallback;-><init>()V
 Landroid/net/IConnectivityManager$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Landroid/net/IConnectivityManager$Stub$Proxy;->getActiveLinkProperties()Landroid/net/LinkProperties;
@@ -530,41 +499,13 @@
 Landroid/net/IConnectivityManager$Stub$Proxy;->getTetheredIfaces()[Ljava/lang/String;
 Landroid/net/IConnectivityManager$Stub$Proxy;->mRemote:Landroid/os/IBinder;
 Landroid/net/IConnectivityManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/IConnectivityManager;
-Landroid/net/IConnectivityManager;->getActiveLinkProperties()Landroid/net/LinkProperties;
-Landroid/net/IConnectivityManager;->getActiveNetworkInfo()Landroid/net/NetworkInfo;
-Landroid/net/IConnectivityManager;->getAllNetworkInfo()[Landroid/net/NetworkInfo;
-Landroid/net/IConnectivityManager;->getAllNetworkState()[Landroid/net/NetworkState;
-Landroid/net/IConnectivityManager;->getLastTetherError(Ljava/lang/String;)I
-Landroid/net/IConnectivityManager;->getTetherableIfaces()[Ljava/lang/String;
-Landroid/net/IConnectivityManager;->getTetherableUsbRegexs()[Ljava/lang/String;
-Landroid/net/IConnectivityManager;->getTetherableWifiRegexs()[Ljava/lang/String;
-Landroid/net/IConnectivityManager;->getTetheredIfaces()[Ljava/lang/String;
-Landroid/net/IConnectivityManager;->getTetheringErroredIfaces()[Ljava/lang/String;
-Landroid/net/IConnectivityManager;->startLegacyVpn(Lcom/android/internal/net/VpnProfile;)V
 Landroid/net/INetworkManagementEventObserver$Stub;-><init>()V
 Landroid/net/INetworkPolicyListener$Stub;-><init>()V
 Landroid/net/INetworkPolicyManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/INetworkPolicyManager;
-Landroid/net/INetworkPolicyManager;->getNetworkQuotaInfo(Landroid/net/NetworkState;)Landroid/net/NetworkQuotaInfo;
-Landroid/net/INetworkPolicyManager;->getRestrictBackground()Z
-Landroid/net/INetworkPolicyManager;->getUidPolicy(I)I
-Landroid/net/INetworkPolicyManager;->setNetworkPolicies([Landroid/net/NetworkPolicy;)V
-Landroid/net/INetworkPolicyManager;->setRestrictBackground(Z)V
-Landroid/net/INetworkPolicyManager;->setUidPolicy(II)V
-Landroid/net/INetworkPolicyManager;->snoozeLimit(Landroid/net/NetworkTemplate;)V
 Landroid/net/INetworkScoreService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/INetworkScoreService;
 Landroid/net/INetworkStatsService$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Landroid/net/INetworkStatsService$Stub$Proxy;->getMobileIfaces()[Ljava/lang/String;
 Landroid/net/INetworkStatsService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/INetworkStatsService;
-Landroid/net/INetworkStatsService;->forceUpdate()V
-Landroid/net/INetworkStatsService;->getDataLayerSnapshotForUid(I)Landroid/net/NetworkStats;
-Landroid/net/INetworkStatsService;->getMobileIfaces()[Ljava/lang/String;
-Landroid/net/INetworkStatsService;->openSession()Landroid/net/INetworkStatsSession;
-Landroid/net/INetworkStatsService;->openSessionForUsageStats(ILjava/lang/String;)Landroid/net/INetworkStatsSession;
-Landroid/net/INetworkStatsSession;->close()V
-Landroid/net/INetworkStatsSession;->getHistoryForNetwork(Landroid/net/NetworkTemplate;I)Landroid/net/NetworkStatsHistory;
-Landroid/net/INetworkStatsSession;->getHistoryForUid(Landroid/net/NetworkTemplate;IIII)Landroid/net/NetworkStatsHistory;
-Landroid/net/INetworkStatsSession;->getSummaryForAllUid(Landroid/net/NetworkTemplate;JJZ)Landroid/net/NetworkStats;
-Landroid/net/INetworkStatsSession;->getSummaryForNetwork(Landroid/net/NetworkTemplate;JJ)Landroid/net/NetworkStats;
 Landroid/net/InterfaceConfiguration;-><init>()V
 Landroid/net/LinkProperties$ProvisioningChange;->values()[Landroid/net/LinkProperties$ProvisioningChange;
 Landroid/net/MobileLinkQualityInfo;-><init>()V
@@ -575,22 +516,12 @@
 Landroid/net/wifi/IWifiManager$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Landroid/net/wifi/IWifiManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/wifi/IWifiManager;
 Landroid/net/wifi/IWifiManager$Stub;->TRANSACTION_getScanResults:I
-Landroid/net/wifi/IWifiManager;->getCurrentNetwork()Landroid/net/Network;
-Landroid/net/wifi/IWifiManager;->getWifiApConfiguration()Landroid/net/wifi/WifiConfiguration;
-Landroid/net/wifi/IWifiManager;->getWifiApEnabledState()I
 Landroid/net/wifi/IWifiScanner$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Landroid/net/wifi/IWifiScanner$Stub$Proxy;->mRemote:Landroid/os/IBinder;
 Landroid/net/wifi/IWifiScanner$Stub;-><init>()V
 Landroid/net/wifi/IWifiScanner$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/wifi/IWifiScanner;
 Landroid/net/wifi/p2p/IWifiP2pManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/wifi/p2p/IWifiP2pManager;
 Landroid/nfc/INfcAdapter$Stub;->TRANSACTION_enable:I
-Landroid/nfc/INfcAdapterExtras;->authenticate(Ljava/lang/String;[B)V
-Landroid/nfc/INfcAdapterExtras;->close(Ljava/lang/String;Landroid/os/IBinder;)Landroid/os/Bundle;
-Landroid/nfc/INfcAdapterExtras;->getCardEmulationRoute(Ljava/lang/String;)I
-Landroid/nfc/INfcAdapterExtras;->getDriverName(Ljava/lang/String;)Ljava/lang/String;
-Landroid/nfc/INfcAdapterExtras;->open(Ljava/lang/String;Landroid/os/IBinder;)Landroid/os/Bundle;
-Landroid/nfc/INfcAdapterExtras;->setCardEmulationRoute(Ljava/lang/String;I)V
-Landroid/nfc/INfcAdapterExtras;->transceive(Ljava/lang/String;[B)Landroid/os/Bundle;
 Landroid/os/AsyncResult;-><init>(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Throwable;)V
 Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;
 Landroid/os/AsyncResult;->forMessage(Landroid/os/Message;)Landroid/os/AsyncResult;
@@ -1360,9 +1291,7 @@
 Landroid/R$styleable;->Window:[I
 Landroid/R$styleable;->Window_windowBackground:I
 Landroid/R$styleable;->Window_windowFrame:I
-Landroid/security/Credentials;->convertToPem([Ljava/security/cert/Certificate;)[B
 Landroid/security/IKeyChainService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/security/IKeyChainService;
-Landroid/security/IKeyChainService;->requestPrivateKey(Ljava/lang/String;)Ljava/lang/String;
 Landroid/security/keymaster/KeymasterBlobArgument;-><init>(ILandroid/os/Parcel;)V
 Landroid/security/keymaster/KeymasterBlobArgument;-><init>(I[B)V
 Landroid/security/keymaster/KeymasterBlobArgument;->blob:[B
@@ -1391,29 +1320,12 @@
 Landroid/service/dreams/IDreamManager;->getDreamComponents()[Landroid/content/ComponentName;
 Landroid/service/dreams/IDreamManager;->isDreaming()Z
 Landroid/service/dreams/IDreamManager;->setDreamComponents([Landroid/content/ComponentName;)V
-Landroid/service/euicc/IDeleteSubscriptionCallback;->onComplete(I)V
-Landroid/service/euicc/IEraseSubscriptionsCallback;->onComplete(I)V
 Landroid/service/euicc/IEuiccService$Stub;-><init>()V
-Landroid/service/euicc/IGetDefaultDownloadableSubscriptionListCallback;->onComplete(Landroid/service/euicc/GetDefaultDownloadableSubscriptionListResult;)V
-Landroid/service/euicc/IGetDownloadableSubscriptionMetadataCallback;->onComplete(Landroid/service/euicc/GetDownloadableSubscriptionMetadataResult;)V
-Landroid/service/euicc/IGetEidCallback;->onSuccess(Ljava/lang/String;)V
-Landroid/service/euicc/IGetEuiccInfoCallback;->onSuccess(Landroid/telephony/euicc/EuiccInfo;)V
-Landroid/service/euicc/IGetEuiccProfileInfoListCallback;->onComplete(Landroid/service/euicc/GetEuiccProfileInfoListResult;)V
-Landroid/service/euicc/IRetainSubscriptionsForFactoryResetCallback;->onComplete(I)V
-Landroid/service/euicc/ISwitchToSubscriptionCallback;->onComplete(I)V
-Landroid/service/euicc/IUpdateSubscriptionNicknameCallback;->onComplete(I)V
 Landroid/service/notification/INotificationListener$Stub;-><init>()V
 Landroid/service/persistentdata/IPersistentDataBlockService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/service/persistentdata/IPersistentDataBlockService;
 Landroid/service/vr/IVrManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/service/vr/IVrManager;
-Landroid/service/vr/IVrManager;->getVr2dDisplayId()I
-Landroid/service/vr/IVrManager;->getVrModeState()Z
 Landroid/service/wallpaper/IWallpaperConnection$Stub;-><init>()V
-Landroid/service/wallpaper/IWallpaperEngine;->destroy()V
-Landroid/service/wallpaper/IWallpaperEngine;->dispatchPointer(Landroid/view/MotionEvent;)V
-Landroid/service/wallpaper/IWallpaperEngine;->dispatchWallpaperCommand(Ljava/lang/String;IIILandroid/os/Bundle;)V
-Landroid/service/wallpaper/IWallpaperEngine;->setVisibility(Z)V
 Landroid/service/wallpaper/IWallpaperService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/service/wallpaper/IWallpaperService;
-Landroid/speech/IRecognitionListener;->onEvent(ILandroid/os/Bundle;)V
 Landroid/telecom/Log;->i(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V
 Landroid/telecom/Log;->w(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V
 Landroid/telephony/ims/compat/feature/MMTelFeature;-><init>()V
@@ -1424,10 +1336,6 @@
 Landroid/telephony/mbms/IMbmsStreamingSessionCallback$Stub;-><init>()V
 Landroid/telephony/mbms/IStreamingServiceCallback$Stub;-><init>()V
 Landroid/telephony/mbms/vendor/IMbmsStreamingService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/telephony/mbms/vendor/IMbmsStreamingService;
-Landroid/telephony/mbms/vendor/IMbmsStreamingService;->getPlaybackUri(ILjava/lang/String;)Landroid/net/Uri;
-Landroid/telephony/mbms/vendor/IMbmsStreamingService;->initialize(Landroid/telephony/mbms/IMbmsStreamingSessionCallback;I)I
-Landroid/telephony/mbms/vendor/IMbmsStreamingService;->requestUpdateStreamingServices(ILjava/util/List;)I
-Landroid/telephony/mbms/vendor/IMbmsStreamingService;->startStreaming(ILjava/lang/String;Landroid/telephony/mbms/IStreamingServiceCallback;)I
 Landroid/telephony/SmsCbCmasInfo;->getCategory()I
 Landroid/telephony/SmsCbCmasInfo;->getCertainty()I
 Landroid/telephony/SmsCbCmasInfo;->getMessageClass()I
@@ -1453,9 +1361,6 @@
 Landroid/telephony/SmsCbMessage;->isCmasMessage()Z
 Landroid/telephony/SmsCbMessage;->isEmergencyMessage()Z
 Landroid/telephony/TelephonyManager$MultiSimVariants;->values()[Landroid/telephony/TelephonyManager$MultiSimVariants;
-Landroid/test/AndroidTestCase;->getTestContext()Landroid/content/Context;
-Landroid/test/AndroidTestCase;->setTestContext(Landroid/content/Context;)V
-Landroid/test/InstrumentationTestCase;->runMethod(Ljava/lang/reflect/Method;I)V
 Landroid/util/Singleton;-><init>()V
 Landroid/util/XmlPullAttributes;-><init>(Lorg/xmlpull/v1/XmlPullParser;)V
 Landroid/util/XmlPullAttributes;->mParser:Lorg/xmlpull/v1/XmlPullParser;
@@ -1470,17 +1375,8 @@
 Landroid/view/autofill/IAutoFillManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/view/autofill/IAutoFillManager;
 Landroid/view/IAppTransitionAnimationSpecsFuture$Stub;-><init>()V
 Landroid/view/IDockedStackListener$Stub;-><init>()V
-Landroid/view/IRecentsAnimationController;->finish(Z)V
-Landroid/view/IRecentsAnimationController;->screenshotTask(I)Landroid/app/ActivityManager$TaskSnapshot;
-Landroid/view/IRecentsAnimationController;->setAnimationTargetsBehindSystemBars(Z)V
-Landroid/view/IRecentsAnimationController;->setInputConsumerEnabled(Z)V
 Landroid/view/IRecentsAnimationRunner$Stub;-><init>()V
-Landroid/view/IRecentsAnimationRunner;->onAnimationCanceled()V
-Landroid/view/IRecentsAnimationRunner;->onAnimationStart(Landroid/view/IRecentsAnimationController;[Landroid/view/RemoteAnimationTarget;Landroid/graphics/Rect;Landroid/graphics/Rect;)V
-Landroid/view/IRemoteAnimationFinishedCallback;->onAnimationFinished()V
 Landroid/view/IRemoteAnimationRunner$Stub;-><init>()V
-Landroid/view/IRemoteAnimationRunner;->onAnimationCancelled()V
-Landroid/view/IRemoteAnimationRunner;->onAnimationStart([Landroid/view/RemoteAnimationTarget;Landroid/view/IRemoteAnimationFinishedCallback;)V
 Landroid/view/IRotationWatcher$Stub;-><init>()V
 Landroid/view/IWindow$Stub;-><init>()V
 Landroid/view/IWindow$Stub;->asInterface(Landroid/os/IBinder;)Landroid/view/IWindow;
@@ -1492,44 +1388,7 @@
 Landroid/view/IWindowManager$Stub$Proxy;->watchRotation(Landroid/view/IRotationWatcher;I)I
 Landroid/view/IWindowManager$Stub;-><init>()V
 Landroid/view/IWindowManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/view/IWindowManager;
-Landroid/view/IWindowManager;->createInputConsumer(Landroid/os/IBinder;Ljava/lang/String;ILandroid/view/InputChannel;)V
-Landroid/view/IWindowManager;->destroyInputConsumer(Ljava/lang/String;I)Z
-Landroid/view/IWindowManager;->endProlongedAnimations()V
-Landroid/view/IWindowManager;->executeAppTransition()V
-Landroid/view/IWindowManager;->freezeRotation(I)V
-Landroid/view/IWindowManager;->getAnimationScale(I)F
-Landroid/view/IWindowManager;->getAnimationScales()[F
-Landroid/view/IWindowManager;->getBaseDisplaySize(ILandroid/graphics/Point;)V
-Landroid/view/IWindowManager;->getDockedStackSide()I
-Landroid/view/IWindowManager;->getInitialDisplayDensity(I)I
-Landroid/view/IWindowManager;->getInitialDisplaySize(ILandroid/graphics/Point;)V
-Landroid/view/IWindowManager;->getStableInsets(ILandroid/graphics/Rect;)V
-Landroid/view/IWindowManager;->hasNavigationBar(I)Z
-Landroid/view/IWindowManager;->isKeyguardLocked()Z
-Landroid/view/IWindowManager;->isKeyguardSecure()Z
-Landroid/view/IWindowManager;->isSafeModeEnabled()Z
-Landroid/view/IWindowManager;->lockNow(Landroid/os/Bundle;)V
-Landroid/view/IWindowManager;->overridePendingAppTransitionMultiThumbFuture(Landroid/view/IAppTransitionAnimationSpecsFuture;Landroid/os/IRemoteCallback;ZI)V
-Landroid/view/IWindowManager;->overridePendingAppTransitionRemote(Landroid/view/RemoteAnimationAdapter;I)V
-Landroid/view/IWindowManager;->registerDockedStackListener(Landroid/view/IDockedStackListener;)V
-Landroid/view/IWindowManager;->removeRotationWatcher(Landroid/view/IRotationWatcher;)V
-Landroid/view/IWindowManager;->setAnimationScale(IF)V
-Landroid/view/IWindowManager;->setAnimationScales([F)V
-Landroid/view/IWindowManager;->setNavBarVirtualKeyHapticFeedbackEnabled(Z)V
-Landroid/view/IWindowManager;->setShelfHeight(ZI)V
-Landroid/view/IWindowManager;->setStrictModeVisualIndicatorPreference(Ljava/lang/String;)V
-Landroid/view/IWindowManager;->thawRotation()V
 Landroid/view/IWindowSession$Stub;->asInterface(Landroid/os/IBinder;)Landroid/view/IWindowSession;
-Landroid/view/IWindowSession;->finishDrawing(Landroid/view/IWindow;)V
-Landroid/view/IWindowSession;->getInTouchMode()Z
-Landroid/view/IWindowSession;->performDrag(Landroid/view/IWindow;ILandroid/view/SurfaceControl;IFFFFLandroid/content/ClipData;)Landroid/os/IBinder;
-Landroid/view/IWindowSession;->performHapticFeedback(IZ)Z
-Landroid/view/IWindowSession;->remove(Landroid/view/IWindow;)V
-Landroid/view/IWindowSession;->setInTouchMode(Z)V
-Landroid/view/IWindowSession;->setTransparentRegion(Landroid/view/IWindow;Landroid/graphics/Region;)V
-Landroid/view/IWindowSession;->wallpaperCommandComplete(Landroid/os/IBinder;Landroid/os/Bundle;)V
-Landroid/view/IWindowSession;->wallpaperOffsetsComplete(Landroid/os/IBinder;)V
-Landroid/view/RenderNodeAnimator;->setDuration(J)Landroid/view/RenderNodeAnimator;
 Landroid/view/View$AttachInfo$InvalidateInfo;-><init>()V
 Landroid/view/View$CheckForLongPress;-><init>(Landroid/view/View;)V
 Landroid/view/View$ListenerInfo;-><init>()V
@@ -1538,9 +1397,6 @@
 Landroid/webkit/IWebViewUpdateService$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Landroid/webkit/IWebViewUpdateService$Stub$Proxy;->waitForAndGetProvider()Landroid/webkit/WebViewProviderResponse;
 Landroid/webkit/IWebViewUpdateService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/webkit/IWebViewUpdateService;
-Landroid/webkit/IWebViewUpdateService;->getCurrentWebViewPackageName()Ljava/lang/String;
-Landroid/webkit/IWebViewUpdateService;->getValidWebViewPackages()[Landroid/webkit/WebViewProviderInfo;
-Landroid/webkit/IWebViewUpdateService;->isFallbackPackage(Ljava/lang/String;)Z
 Landroid/widget/DigitalClock$FormatChangeObserver;-><init>(Landroid/widget/DigitalClock;)V
 Landroid/widget/QuickContactBadge$QueryHandler;-><init>(Landroid/widget/QuickContactBadge;Landroid/content/ContentResolver;)V
 Landroid/widget/RelativeLayout$DependencyGraph$Node;-><init>()V
@@ -1550,7 +1406,6 @@
 Lcom/android/ims/ImsCall;->reject(I)V
 Lcom/android/ims/ImsCall;->terminate(I)V
 Lcom/android/ims/ImsConfigListener$Stub;-><init>()V
-Lcom/android/ims/ImsConfigListener;->onSetFeatureResponse(IIII)V
 Lcom/android/ims/ImsEcbm;->exitEmergencyCallbackMode()V
 Lcom/android/ims/ImsManager;->getConfigInterface()Lcom/android/ims/ImsConfig;
 Lcom/android/ims/ImsManager;->getInstance(Landroid/content/Context;I)Lcom/android/ims/ImsManager;
@@ -1560,104 +1415,17 @@
 Lcom/android/ims/ImsUtInterface;->queryCallForward(ILjava/lang/String;Landroid/os/Message;)V
 Lcom/android/ims/internal/IImsCallSession$Stub;-><init>()V
 Lcom/android/ims/internal/IImsCallSession$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/ims/internal/IImsCallSession;
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionConferenceStateUpdated(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsConferenceState;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionHandover(Lcom/android/ims/internal/IImsCallSession;IILandroid/telephony/ims/ImsReasonInfo;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionHandoverFailed(Lcom/android/ims/internal/IImsCallSession;IILandroid/telephony/ims/ImsReasonInfo;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionHeld(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsCallProfile;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionHoldFailed(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsReasonInfo;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionHoldReceived(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsCallProfile;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionInviteParticipantsRequestDelivered(Lcom/android/ims/internal/IImsCallSession;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionInviteParticipantsRequestFailed(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsReasonInfo;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionMergeComplete(Lcom/android/ims/internal/IImsCallSession;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionMergeFailed(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsReasonInfo;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionMergeStarted(Lcom/android/ims/internal/IImsCallSession;Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsCallProfile;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionMultipartyStateChanged(Lcom/android/ims/internal/IImsCallSession;Z)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionProgressing(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsStreamMediaProfile;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionResumed(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsCallProfile;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionResumeFailed(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsReasonInfo;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionResumeReceived(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsCallProfile;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionStarted(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsCallProfile;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionStartFailed(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsReasonInfo;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionSuppServiceReceived(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsSuppServiceNotification;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionTerminated(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsReasonInfo;)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionTtyModeReceived(Lcom/android/ims/internal/IImsCallSession;I)V
-Lcom/android/ims/internal/IImsCallSessionListener;->callSessionUpdated(Lcom/android/ims/internal/IImsCallSession;Landroid/telephony/ims/ImsCallProfile;)V
 Lcom/android/ims/internal/IImsConfig$Stub;-><init>()V
 Lcom/android/ims/internal/IImsEcbm$Stub;-><init>()V
-Lcom/android/ims/internal/IImsRegistrationListener;->registrationAssociatedUriChanged([Landroid/net/Uri;)V
-Lcom/android/ims/internal/IImsRegistrationListener;->registrationChangeFailed(ILandroid/telephony/ims/ImsReasonInfo;)V
-Lcom/android/ims/internal/IImsRegistrationListener;->registrationConnected()V
-Lcom/android/ims/internal/IImsRegistrationListener;->registrationConnectedWithRadioTech(I)V
-Lcom/android/ims/internal/IImsRegistrationListener;->registrationDisconnected(Landroid/telephony/ims/ImsReasonInfo;)V
-Lcom/android/ims/internal/IImsRegistrationListener;->registrationFeatureCapabilityChanged(I[I[I)V
-Lcom/android/ims/internal/IImsRegistrationListener;->registrationProgressingWithRadioTech(I)V
-Lcom/android/ims/internal/IImsRegistrationListener;->voiceMessageCountUpdate(I)V
 Lcom/android/ims/internal/IImsService$Stub;-><init>()V
 Lcom/android/ims/internal/IImsService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/ims/internal/IImsService;
 Lcom/android/ims/internal/IImsUt$Stub;-><init>()V
-Lcom/android/ims/internal/IImsUtListener;->utConfigurationCallBarringQueried(Lcom/android/ims/internal/IImsUt;I[Landroid/telephony/ims/ImsSsInfo;)V
-Lcom/android/ims/internal/IImsUtListener;->utConfigurationCallForwardQueried(Lcom/android/ims/internal/IImsUt;I[Landroid/telephony/ims/ImsCallForwardInfo;)V
-Lcom/android/ims/internal/IImsUtListener;->utConfigurationCallWaitingQueried(Lcom/android/ims/internal/IImsUt;I[Landroid/telephony/ims/ImsSsInfo;)V
-Lcom/android/ims/internal/IImsUtListener;->utConfigurationQueried(Lcom/android/ims/internal/IImsUt;ILandroid/os/Bundle;)V
-Lcom/android/ims/internal/IImsUtListener;->utConfigurationQueryFailed(Lcom/android/ims/internal/IImsUt;ILandroid/telephony/ims/ImsReasonInfo;)V
-Lcom/android/ims/internal/IImsUtListener;->utConfigurationUpdated(Lcom/android/ims/internal/IImsUt;I)V
-Lcom/android/ims/internal/IImsUtListener;->utConfigurationUpdateFailed(Lcom/android/ims/internal/IImsUt;ILandroid/telephony/ims/ImsReasonInfo;)V
-Lcom/android/ims/internal/IImsVideoCallCallback;->changeCallDataUsage(J)V
-Lcom/android/ims/internal/IImsVideoCallCallback;->changeCameraCapabilities(Landroid/telecom/VideoProfile$CameraCapabilities;)V
-Lcom/android/ims/internal/IImsVideoCallCallback;->changePeerDimensions(II)V
-Lcom/android/ims/internal/IImsVideoCallCallback;->changeVideoQuality(I)V
-Lcom/android/ims/internal/IImsVideoCallCallback;->handleCallSessionEvent(I)V
-Lcom/android/ims/internal/IImsVideoCallCallback;->receiveSessionModifyRequest(Landroid/telecom/VideoProfile;)V
-Lcom/android/ims/internal/IImsVideoCallCallback;->receiveSessionModifyResponse(ILandroid/telecom/VideoProfile;Landroid/telecom/VideoProfile;)V
 Lcom/android/ims/internal/IImsVideoCallProvider$Stub;-><init>()V
-Lcom/android/ims/internal/IImsVideoCallProvider;->setCallback(Lcom/android/ims/internal/IImsVideoCallCallback;)V
 Lcom/android/ims/internal/ImsVideoCallProviderWrapper;-><init>(Lcom/android/ims/internal/IImsVideoCallProvider;)V
-Lcom/android/ims/internal/uce/options/IOptionsListener;->cmdStatus(Lcom/android/ims/internal/uce/options/OptionsCmdStatus;)V
-Lcom/android/ims/internal/uce/options/IOptionsListener;->getVersionCb(Ljava/lang/String;)V
-Lcom/android/ims/internal/uce/options/IOptionsListener;->incomingOptions(Ljava/lang/String;Lcom/android/ims/internal/uce/options/OptionsCapInfo;I)V
-Lcom/android/ims/internal/uce/options/IOptionsListener;->serviceAvailable(Lcom/android/ims/internal/uce/common/StatusCode;)V
-Lcom/android/ims/internal/uce/options/IOptionsListener;->serviceUnavailable(Lcom/android/ims/internal/uce/common/StatusCode;)V
-Lcom/android/ims/internal/uce/options/IOptionsListener;->sipResponseReceived(Ljava/lang/String;Lcom/android/ims/internal/uce/options/OptionsSipResponse;Lcom/android/ims/internal/uce/options/OptionsCapInfo;)V
 Lcom/android/ims/internal/uce/options/IOptionsService$Stub;-><init>()V
-Lcom/android/ims/internal/uce/options/IOptionsService;->addListener(ILcom/android/ims/internal/uce/options/IOptionsListener;Lcom/android/ims/internal/uce/common/UceLong;)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/options/IOptionsService;->getContactCap(ILjava/lang/String;I)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/options/IOptionsService;->getContactListCap(I[Ljava/lang/String;I)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/options/IOptionsService;->getMyInfo(II)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/options/IOptionsService;->getVersion(I)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/options/IOptionsService;->removeListener(ILcom/android/ims/internal/uce/common/UceLong;)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/options/IOptionsService;->responseIncomingOptions(IIILjava/lang/String;Lcom/android/ims/internal/uce/options/OptionsCapInfo;Z)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/options/IOptionsService;->setMyInfo(ILcom/android/ims/internal/uce/common/CapInfo;I)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/presence/IPresenceListener;->capInfoReceived(Ljava/lang/String;[Lcom/android/ims/internal/uce/presence/PresTupleInfo;)V
-Lcom/android/ims/internal/uce/presence/IPresenceListener;->cmdStatus(Lcom/android/ims/internal/uce/presence/PresCmdStatus;)V
-Lcom/android/ims/internal/uce/presence/IPresenceListener;->getVersionCb(Ljava/lang/String;)V
-Lcom/android/ims/internal/uce/presence/IPresenceListener;->listCapInfoReceived(Lcom/android/ims/internal/uce/presence/PresRlmiInfo;[Lcom/android/ims/internal/uce/presence/PresResInfo;)V
-Lcom/android/ims/internal/uce/presence/IPresenceListener;->publishTriggering(Lcom/android/ims/internal/uce/presence/PresPublishTriggerType;)V
-Lcom/android/ims/internal/uce/presence/IPresenceListener;->serviceAvailable(Lcom/android/ims/internal/uce/common/StatusCode;)V
-Lcom/android/ims/internal/uce/presence/IPresenceListener;->serviceUnAvailable(Lcom/android/ims/internal/uce/common/StatusCode;)V
-Lcom/android/ims/internal/uce/presence/IPresenceListener;->sipResponseReceived(Lcom/android/ims/internal/uce/presence/PresSipResponse;)V
-Lcom/android/ims/internal/uce/presence/IPresenceListener;->unpublishMessageSent()V
 Lcom/android/ims/internal/uce/presence/IPresenceService$Stub;-><init>()V
-Lcom/android/ims/internal/uce/presence/IPresenceService;->addListener(ILcom/android/ims/internal/uce/presence/IPresenceListener;Lcom/android/ims/internal/uce/common/UceLong;)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/presence/IPresenceService;->getContactCap(ILjava/lang/String;I)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/presence/IPresenceService;->getContactListCap(I[Ljava/lang/String;I)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/presence/IPresenceService;->getVersion(I)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/presence/IPresenceService;->publishMyCap(ILcom/android/ims/internal/uce/presence/PresCapInfo;I)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/presence/IPresenceService;->reenableService(II)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/presence/IPresenceService;->removeListener(ILcom/android/ims/internal/uce/common/UceLong;)Lcom/android/ims/internal/uce/common/StatusCode;
-Lcom/android/ims/internal/uce/presence/IPresenceService;->setNewFeatureTag(ILjava/lang/String;Lcom/android/ims/internal/uce/presence/PresServiceInfo;I)Lcom/android/ims/internal/uce/common/StatusCode;
 Lcom/android/ims/internal/uce/uceservice/IUceListener$Stub;-><init>()V
-Lcom/android/ims/internal/uce/uceservice/IUceListener;->setStatus(I)V
 Lcom/android/ims/internal/uce/uceservice/IUceService$Stub;-><init>()V
-Lcom/android/ims/internal/uce/uceservice/IUceService;->createOptionsService(Lcom/android/ims/internal/uce/options/IOptionsListener;Lcom/android/ims/internal/uce/common/UceLong;)I
-Lcom/android/ims/internal/uce/uceservice/IUceService;->createPresenceService(Lcom/android/ims/internal/uce/presence/IPresenceListener;Lcom/android/ims/internal/uce/common/UceLong;)I
-Lcom/android/ims/internal/uce/uceservice/IUceService;->destroyOptionsService(I)V
-Lcom/android/ims/internal/uce/uceservice/IUceService;->destroyPresenceService(I)V
-Lcom/android/ims/internal/uce/uceservice/IUceService;->getOptionsService()Lcom/android/ims/internal/uce/options/IOptionsService;
-Lcom/android/ims/internal/uce/uceservice/IUceService;->getPresenceService()Lcom/android/ims/internal/uce/presence/IPresenceService;
-Lcom/android/ims/internal/uce/uceservice/IUceService;->getServiceStatus()Z
-Lcom/android/ims/internal/uce/uceservice/IUceService;->isServiceStarted()Z
-Lcom/android/ims/internal/uce/uceservice/IUceService;->startService(Lcom/android/ims/internal/uce/uceservice/IUceListener;)Z
-Lcom/android/ims/internal/uce/uceservice/IUceService;->stopService()Z
 Lcom/android/internal/app/AlertActivity;-><init>()V
 Lcom/android/internal/app/AlertActivity;->mAlert:Lcom/android/internal/app/AlertController;
 Lcom/android/internal/app/AlertActivity;->mAlertParams:Lcom/android/internal/app/AlertController$AlertParams;
@@ -1688,22 +1456,12 @@
 Lcom/android/internal/app/IAppOpsService$Stub;->TRANSACTION_startOperation:I
 Lcom/android/internal/app/IAppOpsService$Stub;->TRANSACTION_startWatchingMode:I
 Lcom/android/internal/app/IAppOpsService$Stub;->TRANSACTION_stopWatchingMode:I
-Lcom/android/internal/app/IAppOpsService;->finishOperation(Landroid/os/IBinder;IILjava/lang/String;)V
-Lcom/android/internal/app/IAppOpsService;->getOpsForPackage(ILjava/lang/String;[I)Ljava/util/List;
-Lcom/android/internal/app/IAppOpsService;->getPackagesForOps([I)Ljava/util/List;
-Lcom/android/internal/app/IAppOpsService;->resetAllModes(ILjava/lang/String;)V
-Lcom/android/internal/app/IAppOpsService;->setMode(IILjava/lang/String;I)V
 Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Lcom/android/internal/app/IBatteryStats$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/app/IBatteryStats;
-Lcom/android/internal/app/IBatteryStats;->computeChargeTimeRemaining()J
-Lcom/android/internal/app/IBatteryStats;->getAwakeTimeBattery()J
-Lcom/android/internal/app/IBatteryStats;->getStatistics()[B
-Lcom/android/internal/app/IBatteryStats;->isCharging()Z
 Lcom/android/internal/app/IMediaContainerService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/app/IMediaContainerService;
 Lcom/android/internal/app/IntentForwarderActivity;->TAG:Ljava/lang/String;
 Lcom/android/internal/app/IVoiceInteractionManagerService$Stub$Proxy;->showSessionFromSession(Landroid/os/IBinder;Landroid/os/Bundle;I)Z
 Lcom/android/internal/app/IVoiceInteractionManagerService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/app/IVoiceInteractionManagerService;
-Lcom/android/internal/app/IVoiceInteractionManagerService;->getKeyphraseSoundModel(ILjava/lang/String;)Landroid/hardware/soundtrigger/SoundTrigger$KeyphraseSoundModel;
 Lcom/android/internal/app/LocaleHelper$LocaleInfoComparator;-><init>(Ljava/util/Locale;Z)V
 Lcom/android/internal/app/LocaleHelper$LocaleInfoComparator;->compare(Lcom/android/internal/app/LocaleStore$LocaleInfo;Lcom/android/internal/app/LocaleStore$LocaleInfo;)I
 Lcom/android/internal/app/LocaleHelper;->getDisplayCountry(Ljava/util/Locale;Ljava/util/Locale;)Ljava/lang/String;
@@ -1731,10 +1489,6 @@
 Lcom/android/internal/app/WindowDecorActionBar;->setShowHideAnimationEnabled(Z)V
 Lcom/android/internal/appwidget/IAppWidgetService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/appwidget/IAppWidgetService;
 Lcom/android/internal/appwidget/IAppWidgetService$Stub;->TRANSACTION_bindAppWidgetId:I
-Lcom/android/internal/appwidget/IAppWidgetService;->bindAppWidgetId(Ljava/lang/String;IILandroid/content/ComponentName;Landroid/os/Bundle;)Z
-Lcom/android/internal/appwidget/IAppWidgetService;->bindRemoteViewsService(Ljava/lang/String;ILandroid/content/Intent;Landroid/app/IApplicationThread;Landroid/os/IBinder;Landroid/app/IServiceConnection;I)Z
-Lcom/android/internal/appwidget/IAppWidgetService;->getAppWidgetIds(Landroid/content/ComponentName;)[I
-Lcom/android/internal/appwidget/IAppWidgetService;->getAppWidgetViews(Ljava/lang/String;I)Landroid/widget/RemoteViews;
 Lcom/android/internal/backup/IBackupTransport$Stub;-><init>()V
 Lcom/android/internal/content/PackageMonitor;-><init>()V
 Lcom/android/internal/database/SortCursor;-><init>([Landroid/database/Cursor;Ljava/lang/String;)V
@@ -1751,16 +1505,11 @@
 Lcom/android/internal/location/GpsNetInitiatedHandler;->mIsHexInput:Z
 Lcom/android/internal/location/ILocationProvider$Stub;-><init>()V
 Lcom/android/internal/location/ILocationProvider$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/location/ILocationProvider;
-Lcom/android/internal/location/ILocationProvider;->getStatus(Landroid/os/Bundle;)I
-Lcom/android/internal/location/ILocationProvider;->getStatusUpdateTime()J
 Lcom/android/internal/location/ILocationProvider;->sendExtraCommand(Ljava/lang/String;Landroid/os/Bundle;)V
 Lcom/android/internal/location/ILocationProvider;->setLocationProviderManager(Lcom/android/internal/location/ILocationProviderManager;)V
 Lcom/android/internal/location/ILocationProvider;->setRequest(Lcom/android/internal/location/ProviderRequest;Landroid/os/WorkSource;)V
 Lcom/android/internal/location/ILocationProviderManager$Stub;-><init>()V
 Lcom/android/internal/location/ILocationProviderManager$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/location/ILocationProviderManager;
-Lcom/android/internal/location/ILocationProviderManager;->onReportLocation(Landroid/location/Location;)V
-Lcom/android/internal/location/ILocationProviderManager;->onSetEnabled(Z)V
-Lcom/android/internal/location/ILocationProviderManager;->onSetProperties(Lcom/android/internal/location/ProviderProperties;)V
 Lcom/android/internal/logging/MetricsLogger;-><init>()V
 Lcom/android/internal/net/LegacyVpnInfo;-><init>()V
 Lcom/android/internal/net/VpnConfig;-><init>()V
@@ -1772,7 +1521,6 @@
 Lcom/android/internal/os/BinderInternal;->handleGc()V
 Lcom/android/internal/os/ClassLoaderFactory;->createClassloaderNamespace(Ljava/lang/ClassLoader;ILjava/lang/String;Ljava/lang/String;ZZ)Ljava/lang/String;
 Lcom/android/internal/os/IDropBoxManagerService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/os/IDropBoxManagerService;
-Lcom/android/internal/os/IDropBoxManagerService;->getNextEntry(Ljava/lang/String;JLjava/lang/String;)Landroid/os/DropBoxManager$Entry;
 Lcom/android/internal/os/ProcessCpuTracker$Stats;->name:Ljava/lang/String;
 Lcom/android/internal/os/ProcessCpuTracker$Stats;->rel_stime:I
 Lcom/android/internal/os/ProcessCpuTracker$Stats;->rel_uptime:J
@@ -1798,8 +1546,6 @@
 Lcom/android/internal/policy/DecorView;->mLastRightInset:I
 Lcom/android/internal/policy/DecorView;->mWindow:Lcom/android/internal/policy/PhoneWindow;
 Lcom/android/internal/policy/IKeyguardService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/policy/IKeyguardService;
-Lcom/android/internal/policy/IKeyguardService;->doKeyguardTimeout(Landroid/os/Bundle;)V
-Lcom/android/internal/policy/IKeyguardService;->setKeyguardEnabled(Z)V
 Lcom/android/internal/policy/IKeyguardStateCallback$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/policy/IKeyguardStateCallback;
 Lcom/android/internal/policy/PhoneFallbackEventHandler;-><init>(Landroid/content/Context;)V
 Lcom/android/internal/policy/PhoneFallbackEventHandler;->mContext:Landroid/content/Context;
@@ -2253,14 +1999,7 @@
 Lcom/android/internal/statusbar/IStatusBar$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/statusbar/IStatusBar;
 Lcom/android/internal/statusbar/IStatusBarService$Stub;-><init>()V
 Lcom/android/internal/statusbar/IStatusBarService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/statusbar/IStatusBarService;
-Lcom/android/internal/statusbar/IStatusBarService;->collapsePanels()V
-Lcom/android/internal/statusbar/IStatusBarService;->disable(ILandroid/os/IBinder;Ljava/lang/String;)V
-Lcom/android/internal/statusbar/IStatusBarService;->expandNotificationsPanel()V
-Lcom/android/internal/statusbar/IStatusBarService;->handleSystemKey(I)V
-Lcom/android/internal/statusbar/IStatusBarService;->removeIcon(Ljava/lang/String;)V
-Lcom/android/internal/statusbar/IStatusBarService;->setIconVisibility(Ljava/lang/String;Z)V
 Lcom/android/internal/telecom/ITelecomService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telecom/ITelecomService;
-Lcom/android/internal/telecom/ITelecomService;->getCallState()I
 Lcom/android/internal/telephony/BaseCommands;->mCallStateRegistrants:Landroid/os/RegistrantList;
 Lcom/android/internal/telephony/BaseCommands;->mCallWaitingInfoRegistrants:Landroid/os/RegistrantList;
 Lcom/android/internal/telephony/BaseCommands;->mCatCallSetUpRegistrant:Landroid/os/Registrant;
@@ -2887,7 +2626,6 @@
 Lcom/android/internal/telephony/GsmCdmaPhone;->notifyServiceStateChanged(Landroid/telephony/ServiceState;)V
 Lcom/android/internal/telephony/GsmCdmaPhone;->setOnEcbModeExitResponse(Landroid/os/Handler;ILjava/lang/Object;)V
 Lcom/android/internal/telephony/GsmCdmaPhone;->syncClirSetting()V
-Lcom/android/internal/telephony/ICarrierConfigLoader;->getConfigForSubId(ILjava/lang/String;)Landroid/os/PersistableBundle;
 Lcom/android/internal/telephony/IccCard;->getState()Lcom/android/internal/telephony/IccCardConstants$State;
 Lcom/android/internal/telephony/IccCard;->registerForNetworkLocked(Landroid/os/Handler;ILjava/lang/Object;)V
 Lcom/android/internal/telephony/IccCard;->supplyNetworkDepersonalization(Ljava/lang/String;Landroid/os/Message;)V
@@ -2909,15 +2647,8 @@
 Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->loge(Ljava/lang/String;)V
 Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mAdnCache:Lcom/android/internal/telephony/uicc/AdnRecordCache;
 Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mBaseHandler:Landroid/os/Handler;
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mCurrentApp:Lcom/android/internal/telephony/uicc/UiccCardApplication;
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mIs3gCard:Z
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mLock:Ljava/lang/Object;
 Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mPhone:Lcom/android/internal/telephony/Phone;
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mRecords:Ljava/util/List;
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mRecordSize:[I
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mSuccess:Z
 Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->updateEfForIccType(I)I
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->waitForResult(Ljava/util/concurrent/atomic/AtomicBoolean;)V
 Lcom/android/internal/telephony/IccProvider;-><init>()V
 Lcom/android/internal/telephony/IccProvider;->ADDRESS_BOOK_COLUMN_NAMES:[Ljava/lang/String;
 Lcom/android/internal/telephony/IccProvider;->DBG:Z
@@ -3100,8 +2831,6 @@
 Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;->getDeviceId(Ljava/lang/String;)Ljava/lang/String;
 Lcom/android/internal/telephony/IPhoneSubInfo$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telephony/IPhoneSubInfo;
 Lcom/android/internal/telephony/IPhoneSubInfo$Stub;->TRANSACTION_getDeviceId:I
-Lcom/android/internal/telephony/IPhoneSubInfo;->getIccSerialNumber(Ljava/lang/String;)Ljava/lang/String;
-Lcom/android/internal/telephony/IPhoneSubInfo;->getSubscriberId(Ljava/lang/String;)Ljava/lang/String;
 Lcom/android/internal/telephony/ISms$Stub;-><init>()V
 Lcom/android/internal/telephony/ISms$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telephony/ISms;
 Lcom/android/internal/telephony/ISub$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
@@ -3115,38 +2844,9 @@
 Lcom/android/internal/telephony/ITelephony$Stub;->TRANSACTION_call:I
 Lcom/android/internal/telephony/ITelephony$Stub;->TRANSACTION_dial:I
 Lcom/android/internal/telephony/ITelephony$Stub;->TRANSACTION_getDeviceId:I
-Lcom/android/internal/telephony/ITelephony;->call(Ljava/lang/String;Ljava/lang/String;)V
-Lcom/android/internal/telephony/ITelephony;->dial(Ljava/lang/String;)V
-Lcom/android/internal/telephony/ITelephony;->disableDataConnectivity()Z
-Lcom/android/internal/telephony/ITelephony;->disableLocationUpdates()V
-Lcom/android/internal/telephony/ITelephony;->enableDataConnectivity()Z
-Lcom/android/internal/telephony/ITelephony;->enableLocationUpdates()V
-Lcom/android/internal/telephony/ITelephony;->getActivePhoneType()I
-Lcom/android/internal/telephony/ITelephony;->getCallState()I
-Lcom/android/internal/telephony/ITelephony;->getDataActivity()I
-Lcom/android/internal/telephony/ITelephony;->getDataEnabled(I)Z
-Lcom/android/internal/telephony/ITelephony;->getDataState()I
-Lcom/android/internal/telephony/ITelephony;->getNetworkType()I
-Lcom/android/internal/telephony/ITelephony;->handlePinMmi(Ljava/lang/String;)Z
-Lcom/android/internal/telephony/ITelephony;->handlePinMmiForSubscriber(ILjava/lang/String;)Z
-Lcom/android/internal/telephony/ITelephony;->hasIccCard()Z
-Lcom/android/internal/telephony/ITelephony;->iccCloseLogicalChannel(II)Z
-Lcom/android/internal/telephony/ITelephony;->iccTransmitApduLogicalChannel(IIIIIIILjava/lang/String;)Ljava/lang/String;
-Lcom/android/internal/telephony/ITelephony;->isRadioOnForSubscriber(ILjava/lang/String;)Z
-Lcom/android/internal/telephony/ITelephony;->setRadio(Z)Z
-Lcom/android/internal/telephony/ITelephony;->supplyPin(Ljava/lang/String;)Z
-Lcom/android/internal/telephony/ITelephony;->toggleRadioOnOff()V
-Lcom/android/internal/telephony/ITelephony;->updateServiceLocation()V
 Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Lcom/android/internal/telephony/ITelephonyRegistry$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telephony/ITelephonyRegistry;
-Lcom/android/internal/telephony/ITelephonyRegistry;->listen(Ljava/lang/String;Lcom/android/internal/telephony/IPhoneStateListener;IZ)V
-Lcom/android/internal/telephony/ITelephonyRegistry;->notifyCallState(ILjava/lang/String;)V
-Lcom/android/internal/telephony/ITelephonyRegistry;->notifyCellInfo(Ljava/util/List;)V
-Lcom/android/internal/telephony/ITelephonyRegistry;->notifyDataConnectionFailed(Ljava/lang/String;)V
 Lcom/android/internal/telephony/IWapPushManager$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telephony/IWapPushManager;
-Lcom/android/internal/telephony/IWapPushManager;->addPackage(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZZ)Z
-Lcom/android/internal/telephony/IWapPushManager;->deletePackage(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z
-Lcom/android/internal/telephony/IWapPushManager;->updatePackage(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZZ)Z
 Lcom/android/internal/telephony/MccTable$MccEntry;->mIso:Ljava/lang/String;
 Lcom/android/internal/telephony/MccTable;->countryCodeForMcc(I)Ljava/lang/String;
 Lcom/android/internal/telephony/MccTable;->defaultLanguageForMcc(I)Ljava/lang/String;
@@ -3941,23 +3641,7 @@
 Lcom/android/internal/widget/ActionBarOverlayLayout;->setWindowCallback(Landroid/view/Window$Callback;)V
 Lcom/android/internal/widget/EditableInputConnection;-><init>(Landroid/widget/TextView;)V
 Lcom/android/internal/widget/ILockSettings$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/widget/ILockSettings;
-Lcom/android/internal/widget/ILockSettings;->getBoolean(Ljava/lang/String;ZI)Z
-Lcom/android/internal/widget/ILockSettings;->getLong(Ljava/lang/String;JI)J
-Lcom/android/internal/widget/ILockSettings;->getString(Ljava/lang/String;Ljava/lang/String;I)Ljava/lang/String;
-Lcom/android/internal/widget/ILockSettings;->havePassword(I)Z
-Lcom/android/internal/widget/ILockSettings;->havePattern(I)Z
-Lcom/android/internal/widget/ILockSettings;->setBoolean(Ljava/lang/String;ZI)V
-Lcom/android/internal/widget/ILockSettings;->setLong(Ljava/lang/String;JI)V
-Lcom/android/internal/widget/ILockSettings;->setString(Ljava/lang/String;Ljava/lang/String;I)V
 Lcom/android/internal/widget/IRemoteViewsFactory$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/widget/IRemoteViewsFactory;
-Lcom/android/internal/widget/IRemoteViewsFactory;->getCount()I
-Lcom/android/internal/widget/IRemoteViewsFactory;->getItemId(I)J
-Lcom/android/internal/widget/IRemoteViewsFactory;->getLoadingView()Landroid/widget/RemoteViews;
-Lcom/android/internal/widget/IRemoteViewsFactory;->getViewAt(I)Landroid/widget/RemoteViews;
-Lcom/android/internal/widget/IRemoteViewsFactory;->getViewTypeCount()I
-Lcom/android/internal/widget/IRemoteViewsFactory;->hasStableIds()Z
-Lcom/android/internal/widget/IRemoteViewsFactory;->isCreated()Z
-Lcom/android/internal/widget/IRemoteViewsFactory;->onDataSetChanged()V
 Lcom/android/internal/widget/LinearLayoutWithDefaultTouchRecepient;-><init>(Landroid/content/Context;)V
 Lcom/android/internal/widget/LinearLayoutWithDefaultTouchRecepient;->setDefaultTouchRecepient(Landroid/view/View;)V
 Lcom/android/internal/widget/LockPatternChecker;->checkPassword(Lcom/android/internal/widget/LockPatternUtils;Ljava/lang/String;ILcom/android/internal/widget/LockPatternChecker$OnCheckCallback;)Landroid/os/AsyncTask;
@@ -4489,9 +4173,6 @@
 Lgov/nist/javax/sip/address/SipUri;->setUserParam(Ljava/lang/String;)V
 Lgov/nist/javax/sip/parser/URLParser;-><init>(Ljava/lang/String;)V
 Lgov/nist/javax/sip/parser/URLParser;->sipURL(Z)Lgov/nist/javax/sip/address/SipUri;
-Ljunit/framework/TestCase;->fName:Ljava/lang/String;
-Ljunit/framework/TestSuite;->isPublicTestMethod(Ljava/lang/reflect/Method;)Z
-Ljunit/framework/TestSuite;->isTestMethod(Ljava/lang/reflect/Method;)Z
 Lorg/apache/xalan/extensions/ExpressionContext;->getContextNode()Lorg/w3c/dom/Node;
 Lorg/apache/xalan/extensions/ExpressionContext;->getErrorListener()Ljavax/xml/transform/ErrorListener;
 Lorg/apache/xalan/extensions/ExpressionContext;->getVariableOrParam(Lorg/apache/xml/utils/QName;)Lorg/apache/xpath/objects/XObject;
diff --git a/core/java/android/accessibilityservice/AccessibilityServiceInfo.java b/core/java/android/accessibilityservice/AccessibilityServiceInfo.java
index e86fa89..cf24b8e 100644
--- a/core/java/android/accessibilityservice/AccessibilityServiceInfo.java
+++ b/core/java/android/accessibilityservice/AccessibilityServiceInfo.java
@@ -1225,7 +1225,7 @@
     /**
      * @see Parcelable.Creator
      */
-    public static final Parcelable.Creator<AccessibilityServiceInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AccessibilityServiceInfo> CREATOR =
             new Parcelable.Creator<AccessibilityServiceInfo>() {
         public AccessibilityServiceInfo createFromParcel(Parcel parcel) {
             AccessibilityServiceInfo info = new AccessibilityServiceInfo();
diff --git a/core/java/android/accessibilityservice/GestureDescription.java b/core/java/android/accessibilityservice/GestureDescription.java
index 56f4ae2..a3e7ad5 100644
--- a/core/java/android/accessibilityservice/GestureDescription.java
+++ b/core/java/android/accessibilityservice/GestureDescription.java
@@ -455,7 +455,7 @@
             dest.writeFloat(mY);
         }
 
-        public static final Parcelable.Creator<TouchPoint> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<TouchPoint> CREATOR
                 = new Parcelable.Creator<TouchPoint>() {
             public TouchPoint createFromParcel(Parcel in) {
                 return new TouchPoint(in);
@@ -509,7 +509,7 @@
             dest.writeParcelableArray(touchPoints, flags);
         }
 
-        public static final Parcelable.Creator<GestureStep> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<GestureStep> CREATOR
                 = new Parcelable.Creator<GestureStep>() {
             public GestureStep createFromParcel(Parcel in) {
                 return new GestureStep(in);
diff --git a/core/java/android/accounts/Account.java b/core/java/android/accounts/Account.java
index d3b2238..2637764 100644
--- a/core/java/android/accounts/Account.java
+++ b/core/java/android/accounts/Account.java
@@ -124,7 +124,7 @@
         dest.writeString(accessId);
     }
 
-    public static final Creator<Account> CREATOR = new Creator<Account>() {
+    public static final @android.annotation.NonNull Creator<Account> CREATOR = new Creator<Account>() {
         public Account createFromParcel(Parcel source) {
             return new Account(source);
         }
diff --git a/core/java/android/accounts/AccountAuthenticatorResponse.java b/core/java/android/accounts/AccountAuthenticatorResponse.java
index bcc9f90..bb2e327 100644
--- a/core/java/android/accounts/AccountAuthenticatorResponse.java
+++ b/core/java/android/accounts/AccountAuthenticatorResponse.java
@@ -87,7 +87,7 @@
         dest.writeStrongBinder(mAccountAuthenticatorResponse.asBinder());
     }
 
-    public static final Creator<AccountAuthenticatorResponse> CREATOR =
+    public static final @android.annotation.NonNull Creator<AccountAuthenticatorResponse> CREATOR =
             new Creator<AccountAuthenticatorResponse>() {
         public AccountAuthenticatorResponse createFromParcel(Parcel source) {
             return new AccountAuthenticatorResponse(source);
diff --git a/core/java/android/accounts/AccountManagerResponse.java b/core/java/android/accounts/AccountManagerResponse.java
index 11c6e60..369a7c3 100644
--- a/core/java/android/accounts/AccountManagerResponse.java
+++ b/core/java/android/accounts/AccountManagerResponse.java
@@ -66,7 +66,7 @@
     }
 
     /** @hide */
-    public static final Creator<AccountManagerResponse> CREATOR =
+    public static final @android.annotation.NonNull Creator<AccountManagerResponse> CREATOR =
             new Creator<AccountManagerResponse>() {
         public AccountManagerResponse createFromParcel(Parcel source) {
             return new AccountManagerResponse(source);
diff --git a/core/java/android/accounts/AuthenticatorDescription.java b/core/java/android/accounts/AuthenticatorDescription.java
index 2360cec..5556394 100644
--- a/core/java/android/accounts/AuthenticatorDescription.java
+++ b/core/java/android/accounts/AuthenticatorDescription.java
@@ -134,7 +134,7 @@
     }
 
     /** Used to create the object from a parcel. */
-    public static final Creator<AuthenticatorDescription> CREATOR =
+    public static final @android.annotation.NonNull Creator<AuthenticatorDescription> CREATOR =
             new Creator<AuthenticatorDescription>() {
         /** @inheritDoc */
         public AuthenticatorDescription createFromParcel(Parcel source) {
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 91fc188..68b2de4 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -127,7 +127,6 @@
 import android.view.autofill.IAutofillWindowPresenter;
 import android.view.contentcapture.ContentCaptureContext;
 import android.view.contentcapture.ContentCaptureManager;
-import android.view.contentcapture.ContentCaptureSession;
 import android.widget.AdapterView;
 import android.widget.Toast;
 import android.widget.Toolbar;
@@ -1038,15 +1037,15 @@
     }
 
     /** @hide */ private static final int CONTENT_CAPTURE_START = 1;
-    /** @hide */ private static final int CONTENT_CAPTURE_PAUSE = 2;
-    /** @hide */ private static final int CONTENT_CAPTURE_RESUME = 3;
+    /** @hide */ private static final int CONTENT_CAPTURE_RESUME = 2;
+    /** @hide */ private static final int CONTENT_CAPTURE_PAUSE = 3;
     /** @hide */ private static final int CONTENT_CAPTURE_STOP = 4;
 
     /** @hide */
     @IntDef(prefix = { "CONTENT_CAPTURE_" }, value = {
             CONTENT_CAPTURE_START,
-            CONTENT_CAPTURE_PAUSE,
             CONTENT_CAPTURE_RESUME,
+            CONTENT_CAPTURE_PAUSE,
             CONTENT_CAPTURE_STOP
     })
     @Retention(RetentionPolicy.SOURCE)
@@ -1056,10 +1055,10 @@
         switch (type) {
             case CONTENT_CAPTURE_START:
                 return "START";
-            case CONTENT_CAPTURE_PAUSE:
-                return "PAUSE";
             case CONTENT_CAPTURE_RESUME:
                 return "RESUME";
+            case CONTENT_CAPTURE_PAUSE:
+                return "PAUSE";
             case CONTENT_CAPTURE_STOP:
                 return "STOP";
             default:
@@ -1086,16 +1085,16 @@
                             & WindowManager.LayoutParams.FLAG_SECURE) != 0) {
                         flags |= ContentCaptureContext.FLAG_DISABLED_BY_FLAG_SECURE;
                     }
-                    cm.onActivityStarted(mToken, getComponentName(), flags);
-                    break;
-                case CONTENT_CAPTURE_PAUSE:
-                    cm.flush(ContentCaptureSession.FLUSH_REASON_ACTIVITY_PAUSED);
+                    cm.onActivityCreated(mToken, getComponentName(), flags);
                     break;
                 case CONTENT_CAPTURE_RESUME:
-                    cm.flush(ContentCaptureSession.FLUSH_REASON_ACTIVITY_RESUMED);
+                    cm.onActivityResumed();
+                    break;
+                case CONTENT_CAPTURE_PAUSE:
+                    cm.onActivityPaused();
                     break;
                 case CONTENT_CAPTURE_STOP:
-                    cm.onActivityStopped();
+                    cm.onActivityDestroyed();
                     break;
                 default:
                     Log.wtf(TAG, "Invalid @ContentCaptureNotificationType: " + type);
@@ -1654,6 +1653,8 @@
         }
 
         mCalled = true;
+
+        notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_START);
     }
 
     /**
@@ -1697,7 +1698,6 @@
         if (mAutoFillResetNeeded) {
             getAutofillManager().onVisibleForAutofill();
         }
-        notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_START);
     }
 
     /**
@@ -1780,8 +1780,10 @@
                 }
             }
         }
-        mCalled = true;
+
         notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_RESUME);
+
+        mCalled = true;
     }
 
     /**
@@ -2197,8 +2199,9 @@
                 mAutoFillIgnoreFirstResumePause = false;
             }
         }
-        mCalled = true;
+
         notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_PAUSE);
+        mCalled = true;
     }
 
     /**
@@ -2388,7 +2391,6 @@
                         mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN));
             }
         }
-        notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_STOP);
         mEnterAnimationComplete = false;
     }
 
@@ -2459,6 +2461,8 @@
         }
 
         dispatchActivityDestroyed();
+
+        notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_STOP);
     }
 
     /**
@@ -3517,6 +3521,12 @@
      * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
      * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
      * the event).
+     *
+     * To receive this callback, you must return true from onKeyDown for the current
+     * event stream.
+     *
+     * @see KeyEvent.Callback#onKeyLongPress()
+     * @see KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
      */
     public boolean onKeyLongPress(int keyCode, KeyEvent event) {
         return false;
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index ee7288f..c067f9d 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -1345,7 +1345,7 @@
             mIconFilename = source.readInt() > 0 ? source.readString() : null;
         }
 
-        public static final Creator<TaskDescription> CREATOR
+        public static final @android.annotation.NonNull Creator<TaskDescription> CREATOR
                 = new Creator<TaskDescription>() {
             public TaskDescription createFromParcel(Parcel source) {
                 return new TaskDescription(source);
@@ -1431,7 +1431,7 @@
             super.writeToParcel(dest, flags);
         }
 
-        public static final Creator<RecentTaskInfo> CREATOR
+        public static final @android.annotation.NonNull Creator<RecentTaskInfo> CREATOR
                 = new Creator<RecentTaskInfo>() {
             public RecentTaskInfo createFromParcel(Parcel source) {
                 return new RecentTaskInfo(source);
@@ -1601,7 +1601,7 @@
             super.writeToParcel(dest, flags);
         }
 
-        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
+        public static final @android.annotation.NonNull Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
             public RunningTaskInfo createFromParcel(Parcel source) {
                 return new RunningTaskInfo(source);
             }
@@ -1936,7 +1936,7 @@
                     + " mIsTranslucent=" + mIsTranslucent;
         }
 
-        public static final Creator<TaskSnapshot> CREATOR = new Creator<TaskSnapshot>() {
+        public static final @android.annotation.NonNull Creator<TaskSnapshot> CREATOR = new Creator<TaskSnapshot>() {
             public TaskSnapshot createFromParcel(Parcel source) {
                 return new TaskSnapshot(source);
             }
@@ -2177,7 +2177,7 @@
             clientLabel = source.readInt();
         }
 
-        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
+        public static final @android.annotation.NonNull Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
             public RunningServiceInfo createFromParcel(Parcel source) {
                 return new RunningServiceInfo(source);
             }
@@ -2309,7 +2309,7 @@
             foregroundAppThreshold = source.readLong();
         }
 
-        public static final Creator<MemoryInfo> CREATOR
+        public static final @android.annotation.NonNull Creator<MemoryInfo> CREATOR
                 = new Creator<MemoryInfo>() {
             public MemoryInfo createFromParcel(Parcel source) {
                 return new MemoryInfo(source);
@@ -2440,7 +2440,7 @@
             configuration.readFromParcel(source);
         }
 
-        public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
+        public static final @android.annotation.NonNull Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
             @Override
             public StackInfo createFromParcel(Parcel source) {
                 return new StackInfo(source);
@@ -2646,7 +2646,7 @@
             stackTrace = source.readString();
         }
 
-        public static final Creator<ProcessErrorStateInfo> CREATOR =
+        public static final @android.annotation.NonNull Creator<ProcessErrorStateInfo> CREATOR =
                 new Creator<ProcessErrorStateInfo>() {
             public ProcessErrorStateInfo createFromParcel(Parcel source) {
                 return new ProcessErrorStateInfo(source);
@@ -3110,7 +3110,7 @@
             lastActivityTime = source.readLong();
         }
 
-        public static final Creator<RunningAppProcessInfo> CREATOR =
+        public static final @android.annotation.NonNull Creator<RunningAppProcessInfo> CREATOR =
             new Creator<RunningAppProcessInfo>() {
             public RunningAppProcessInfo createFromParcel(Parcel source) {
                 return new RunningAppProcessInfo(source);
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index 92302c5..b654258 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -182,6 +182,7 @@
 import java.lang.ref.WeakReference;
 import java.lang.reflect.Method;
 import java.net.InetAddress;
+import java.nio.file.Files;
 import java.text.DateFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -6954,6 +6955,25 @@
                 fd.setInt$(cr.openFileDescriptor(uri,
                         FileUtils.translateModePosixToString(mode)).detachFd());
                 return fd;
+            } catch (SecurityException e) {
+                throw new ErrnoException(e.getMessage(), OsConstants.EACCES);
+            } catch (FileNotFoundException e) {
+                throw new ErrnoException(e.getMessage(), OsConstants.ENOENT);
+            }
+        }
+
+        private void deleteDeprecatedDataPath(String path) throws ErrnoException {
+            final Uri uri = ContentResolver.translateDeprecatedDataPath(path);
+            Log.v(TAG, "Redirecting " + path + " to " + uri);
+
+            final ContentResolver cr = currentActivityThread().getApplication()
+                    .getContentResolver();
+            try {
+                if (cr.delete(uri, null, null) == 0) {
+                    throw new FileNotFoundException();
+                }
+            } catch (SecurityException e) {
+                throw new ErrnoException(e.getMessage(), OsConstants.EACCES);
             } catch (FileNotFoundException e) {
                 throw new ErrnoException(e.getMessage(), OsConstants.ENOENT);
             }
@@ -6993,6 +7013,42 @@
                 return super.stat(path);
             }
         }
+
+        @Override
+        public void unlink(String path) throws ErrnoException {
+            if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
+                deleteDeprecatedDataPath(path);
+            } else {
+                super.unlink(path);
+            }
+        }
+
+        @Override
+        public void remove(String path) throws ErrnoException {
+            if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
+                deleteDeprecatedDataPath(path);
+            } else {
+                super.remove(path);
+            }
+        }
+
+        @Override
+        public void rename(String oldPath, String newPath) throws ErrnoException {
+            try {
+                super.rename(oldPath, newPath);
+            } catch (ErrnoException e) {
+                if (e.errno == OsConstants.EXDEV) {
+                    Log.v(TAG, "Recovering failed rename " + oldPath + " to " + newPath);
+                    try {
+                        Files.move(new File(oldPath).toPath(), new File(newPath).toPath());
+                    } catch (IOException e2) {
+                        throw e;
+                    }
+                } else {
+                    throw e;
+                }
+            }
+        }
     }
 
     public static void main(String[] args) {
diff --git a/core/java/android/app/AlarmManager.java b/core/java/android/app/AlarmManager.java
index 2f0f14aa..3a34b79 100644
--- a/core/java/android/app/AlarmManager.java
+++ b/core/java/android/app/AlarmManager.java
@@ -1135,7 +1135,7 @@
             dest.writeParcelable(mShowIntent, flags);
         }
 
-        public static final Creator<AlarmClockInfo> CREATOR = new Creator<AlarmClockInfo>() {
+        public static final @android.annotation.NonNull Creator<AlarmClockInfo> CREATOR = new Creator<AlarmClockInfo>() {
             @Override
             public AlarmClockInfo createFromParcel(Parcel in) {
                 return new AlarmClockInfo(in);
diff --git a/core/java/android/app/AppComponentFactory.java b/core/java/android/app/AppComponentFactory.java
index ae63291..2cec7f0 100644
--- a/core/java/android/app/AppComponentFactory.java
+++ b/core/java/android/app/AppComponentFactory.java
@@ -27,6 +27,7 @@
  *
  * @see #instantiateApplication
  * @see #instantiateActivity
+ * @see #instantiateClassLoader
  * @see #instantiateService
  * @see #instantiateReceiver
  * @see #instantiateProvider
@@ -39,8 +40,10 @@
      * a custom class loader hierarchy.
      *
      * @param cl        The default classloader instantiated by platform.
+     * @param aInfo     Information about the application being loaded.
      */
-    public @NonNull ClassLoader instantiateClassLoader(@NonNull ClassLoader cl) {
+    public @NonNull ClassLoader instantiateClassLoader(@NonNull ClassLoader cl,
+            @NonNull ApplicationInfo aInfo) {
         return cl;
     }
 
@@ -133,19 +136,6 @@
         return (ContentProvider) cl.loadClass(className).newInstance();
     }
 
-    private ApplicationInfo mApplicationInfo = null;
-
-    void setApplicationInfo(ApplicationInfo info) {
-        mApplicationInfo = info;
-    }
-
-    /**
-     * Returns the ApplicationInfo associated with this package.
-     */
-    public ApplicationInfo getApplicationInfo() {
-        return mApplicationInfo;
-    }
-
     /**
      * @hide
      */
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index 040ad06..2e82e620 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -1984,7 +1984,7 @@
             }
         }
 
-        public static final Creator<PackageOps> CREATOR = new Creator<PackageOps>() {
+        public static final @android.annotation.NonNull Creator<PackageOps> CREATOR = new Creator<PackageOps>() {
             @Override public PackageOps createFromParcel(Parcel source) {
                 return new PackageOps(source);
             }
@@ -2192,7 +2192,7 @@
             mProxyPackageName = source.readString();
         }
 
-        public static final Creator<OpEntry> CREATOR = new Creator<OpEntry>() {
+        public static final @android.annotation.NonNull Creator<OpEntry> CREATOR = new Creator<OpEntry>() {
             @Override public OpEntry createFromParcel(Parcel source) {
                 return new OpEntry(source);
             }
@@ -2725,7 +2725,7 @@
                     + mBeginTimeMillis + " to:" + mEndTimeMillis + "]";
         }
 
-        public static final Creator<HistoricalOps> CREATOR = new Creator<HistoricalOps>() {
+        public static final @android.annotation.NonNull Creator<HistoricalOps> CREATOR = new Creator<HistoricalOps>() {
             @Override
             public @NonNull HistoricalOps createFromParcel(@NonNull Parcel parcel) {
                 return new HistoricalOps(parcel);
@@ -2935,7 +2935,7 @@
         }
 
 
-        public static final Creator<HistoricalUidOps> CREATOR = new Creator<HistoricalUidOps>() {
+        public static final @android.annotation.NonNull Creator<HistoricalUidOps> CREATOR = new Creator<HistoricalUidOps>() {
             @Override
             public @NonNull HistoricalUidOps createFromParcel(@NonNull Parcel parcel) {
                 return new HistoricalUidOps(parcel);
@@ -3167,7 +3167,7 @@
             return op;
         }
 
-        public static final Creator<HistoricalPackageOps> CREATOR =
+        public static final @android.annotation.NonNull Creator<HistoricalPackageOps> CREATOR =
                 new Creator<HistoricalPackageOps>() {
             @Override
             public @NonNull HistoricalPackageOps createFromParcel(@NonNull Parcel parcel) {
@@ -3589,7 +3589,7 @@
             }
         }
 
-        public static final Creator<HistoricalOp> CREATOR = new Creator<HistoricalOp>() {
+        public static final @android.annotation.NonNull Creator<HistoricalOp> CREATOR = new Creator<HistoricalOp>() {
             @Override
             public @NonNull HistoricalOp createFromParcel(@NonNull Parcel source) {
                 return new HistoricalOp(source);
diff --git a/core/java/android/app/ApplicationErrorReport.java b/core/java/android/app/ApplicationErrorReport.java
index 8874554..a0b3dc0 100644
--- a/core/java/android/app/ApplicationErrorReport.java
+++ b/core/java/android/app/ApplicationErrorReport.java
@@ -492,7 +492,7 @@
             return 0;
         }
 
-        public static final Parcelable.Creator<ParcelableCrashInfo> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<ParcelableCrashInfo> CREATOR =
                 new Parcelable.Creator<ParcelableCrashInfo>() {
                     @Override
                     public ParcelableCrashInfo createFromParcel(Parcel in) {
@@ -666,7 +666,7 @@
         }
     }
 
-    public static final Parcelable.Creator<ApplicationErrorReport> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ApplicationErrorReport> CREATOR
             = new Parcelable.Creator<ApplicationErrorReport>() {
         public ApplicationErrorReport createFromParcel(Parcel source) {
             return new ApplicationErrorReport(source);
diff --git a/core/java/android/app/AuthenticationRequiredException.java b/core/java/android/app/AuthenticationRequiredException.java
index 04e5e0a..0d87336 100644
--- a/core/java/android/app/AuthenticationRequiredException.java
+++ b/core/java/android/app/AuthenticationRequiredException.java
@@ -81,7 +81,7 @@
         mUserAction.writeToParcel(dest, flags);
     }
 
-    public static final Creator<AuthenticationRequiredException> CREATOR =
+    public static final @android.annotation.NonNull Creator<AuthenticationRequiredException> CREATOR =
             new Creator<AuthenticationRequiredException>() {
         @Override
         public AuthenticationRequiredException createFromParcel(Parcel source) {
diff --git a/core/java/android/app/AutomaticZenRule.java b/core/java/android/app/AutomaticZenRule.java
index fe23e21..4a826d1 100644
--- a/core/java/android/app/AutomaticZenRule.java
+++ b/core/java/android/app/AutomaticZenRule.java
@@ -304,7 +304,7 @@
                 configurationActivity, mZenPolicy, mModified, creationTime);
     }
 
-    public static final Parcelable.Creator<AutomaticZenRule> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AutomaticZenRule> CREATOR
             = new Parcelable.Creator<AutomaticZenRule>() {
         @Override
         public AutomaticZenRule createFromParcel(Parcel source) {
diff --git a/core/java/android/app/BackStackRecord.java b/core/java/android/app/BackStackRecord.java
index 46e6def..351e737 100644
--- a/core/java/android/app/BackStackRecord.java
+++ b/core/java/android/app/BackStackRecord.java
@@ -155,7 +155,7 @@
         dest.writeInt(mReorderingAllowed ? 1 : 0);
     }
 
-    public static final Parcelable.Creator<BackStackState> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<BackStackState> CREATOR
             = new Parcelable.Creator<BackStackState>() {
         public BackStackState createFromParcel(Parcel in) {
             return new BackStackState(in);
diff --git a/core/java/android/app/ContentProviderHolder.java b/core/java/android/app/ContentProviderHolder.java
index 2a13c71..004dca1a 100644
--- a/core/java/android/app/ContentProviderHolder.java
+++ b/core/java/android/app/ContentProviderHolder.java
@@ -61,7 +61,7 @@
         dest.writeInt(noReleaseNeeded ? 1 : 0);
     }
 
-    public static final Parcelable.Creator<ContentProviderHolder> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ContentProviderHolder> CREATOR
             = new Parcelable.Creator<ContentProviderHolder>() {
         @Override
         public ContentProviderHolder createFromParcel(Parcel source) {
diff --git a/core/java/android/app/DownloadManager.java b/core/java/android/app/DownloadManager.java
index fde1d29e..e20c490 100644
--- a/core/java/android/app/DownloadManager.java
+++ b/core/java/android/app/DownloadManager.java
@@ -21,6 +21,7 @@
 import android.annotation.SdkConstant.SdkConstantType;
 import android.annotation.SystemApi;
 import android.annotation.SystemService;
+import android.annotation.TestApi;
 import android.annotation.UnsupportedAppUsage;
 import android.content.ContentResolver;
 import android.content.ContentUris;
@@ -163,6 +164,10 @@
      */
     public static final String COLUMN_MEDIAPROVIDER_URI = Downloads.Impl.COLUMN_MEDIAPROVIDER_URI;
 
+    /** @hide */
+    @TestApi
+    public static final String COLUMN_MEDIASTORE_URI = Downloads.Impl.COLUMN_MEDIASTORE_URI;
+
     /**
      * @hide
      */
diff --git a/core/java/android/app/FragmentManager.java b/core/java/android/app/FragmentManager.java
index 5e7921b..68daf44 100644
--- a/core/java/android/app/FragmentManager.java
+++ b/core/java/android/app/FragmentManager.java
@@ -623,7 +623,7 @@
         dest.writeInt(mNextFragmentIndex);
     }
     
-    public static final Parcelable.Creator<FragmentManagerState> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<FragmentManagerState> CREATOR
             = new Parcelable.Creator<FragmentManagerState>() {
         public FragmentManagerState createFromParcel(Parcel in) {
             return new FragmentManagerState(in);
diff --git a/core/java/android/app/FragmentState.java b/core/java/android/app/FragmentState.java
index a61da3bb..a66f069 100644
--- a/core/java/android/app/FragmentState.java
+++ b/core/java/android/app/FragmentState.java
@@ -122,7 +122,7 @@
         dest.writeBundle(mSavedFragmentState);
     }
 
-    public static final Parcelable.Creator<FragmentState> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<FragmentState> CREATOR =
             new Parcelable.Creator<FragmentState>() {
                 @Override
                 public FragmentState createFromParcel(Parcel in) {
diff --git a/core/java/android/app/GrantedUriPermission.java b/core/java/android/app/GrantedUriPermission.java
index 9e84fe1..48d5b8c 100644
--- a/core/java/android/app/GrantedUriPermission.java
+++ b/core/java/android/app/GrantedUriPermission.java
@@ -54,7 +54,7 @@
         out.writeString(packageName);
     }
 
-    public static final Parcelable.Creator<GrantedUriPermission> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<GrantedUriPermission> CREATOR =
             new Parcelable.Creator<GrantedUriPermission>() {
                 @Override
                 public GrantedUriPermission createFromParcel(Parcel in) {
diff --git a/core/java/android/app/IActivityManager.aidl b/core/java/android/app/IActivityManager.aidl
index dcef9d2..5cbb599 100644
--- a/core/java/android/app/IActivityManager.aidl
+++ b/core/java/android/app/IActivityManager.aidl
@@ -204,6 +204,7 @@
     void setProcessImportant(in IBinder token, int pid, boolean isForeground, String reason);
     void setServiceForeground(in ComponentName className, in IBinder token,
             int id, in Notification notification, int flags, int foregroundServiceType);
+    int getForegroundServiceType(in ComponentName className, in IBinder token);
     boolean moveActivityTaskToBack(in IBinder token, boolean nonRoot);
     void getMemoryInfo(out ActivityManager.MemoryInfo outInfo);
     List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState();
@@ -489,4 +490,10 @@
 
     /** Returns a file descriptor that'll be closed when the system server process dies. */
     ParcelFileDescriptor getLifeMonitor();
+
+    /**
+     * Start user, if it us not already running, and bring it to foreground.
+     * unlockProgressListener can be null if monitoring progress is not necessary.
+     */
+    boolean startUserInForegroundWithListener(int userid, IProgressListener unlockProgressListener);
 }
diff --git a/core/java/android/app/IActivityTaskManager.aidl b/core/java/android/app/IActivityTaskManager.aidl
index 497d5ba..b16188f 100644
--- a/core/java/android/app/IActivityTaskManager.aidl
+++ b/core/java/android/app/IActivityTaskManager.aidl
@@ -129,6 +129,7 @@
     oneway void activityIdle(in IBinder token, in Configuration config,
             in boolean stopProfiling);
     void activityResumed(in IBinder token);
+    void activityTopResumedStateLost();
     void activityPaused(in IBinder token);
     void activityStopped(in IBinder token, in Bundle state,
             in PersistableBundle persistentState, in CharSequence description);
@@ -277,12 +278,8 @@
      *
      * @param showingKeyguard True if the keyguard is showing, false otherwise.
      * @param showingAod True if AOD is showing, false otherwise.
-     * @param secondaryDisplaysShowing The displayId's of the secondary displays on which the
-     * keyguard is showing, or {@code null} if there is no such display. Only meaningful if showing
-     * is {@code true}.
      */
-    void setLockScreenShown(boolean showingKeyguard, boolean showingAod,
-            in int[] secondaryDisplaysShowing);
+    void setLockScreenShown(boolean showingKeyguard, boolean showingAod);
     Bundle getAssistContextExtras(int requestType);
     boolean launchAssistIntent(in Intent intent, int requestType, in String hint, int userHandle,
             in Bundle args);
diff --git a/core/java/android/app/ITaskStackListener.aidl b/core/java/android/app/ITaskStackListener.aidl
index 8615f00..8c85ad1 100644
--- a/core/java/android/app/ITaskStackListener.aidl
+++ b/core/java/android/app/ITaskStackListener.aidl
@@ -81,6 +81,16 @@
             int requestedDisplayId);
 
     /**
+     * Called when an activity was requested to be launched on a secondary display but was rerouted
+     * to default display.
+     *
+     * @param taskInfo info about the Activity's task
+     * @param requestedDisplayId the id of the requested launch display
+     */
+    void onActivityLaunchOnSecondaryDisplayRerouted(in ActivityManager.RunningTaskInfo taskInfo,
+                int requestedDisplayId);
+
+    /**
      * Called when a task is added.
      *
      * @param taskId id of the task.
diff --git a/core/java/android/app/Instrumentation.java b/core/java/android/app/Instrumentation.java
index dda5569..4f94209 100644
--- a/core/java/android/app/Instrumentation.java
+++ b/core/java/android/app/Instrumentation.java
@@ -52,6 +52,7 @@
 import android.view.MotionEvent;
 import android.view.ViewConfiguration;
 import android.view.Window;
+import android.view.WindowManagerGlobal;
 
 import com.android.internal.content.ReferrerIntent;
 
@@ -1102,8 +1103,11 @@
         if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) == 0) {
             event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
         }
-        InputManager.getInstance().injectInputEvent(event,
-                InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);
+        try {
+            WindowManagerGlobal.getWindowManagerService().injectInputAfterTransactionsApplied(event,
+                    InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);
+        } catch (RemoteException e) {
+        }
     }
 
     /**
diff --git a/core/java/android/app/LoadedApk.java b/core/java/android/app/LoadedApk.java
index 5c4c005..5d186a2 100644
--- a/core/java/android/app/LoadedApk.java
+++ b/core/java/android/app/LoadedApk.java
@@ -232,7 +232,8 @@
         mResources = Resources.getSystem();
         mDefaultClassLoader = ClassLoader.getSystemClassLoader();
         mAppComponentFactory = createAppFactory(mApplicationInfo, mDefaultClassLoader);
-        mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader);
+        mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader,
+                new ApplicationInfo(mApplicationInfo));
     }
 
     /**
@@ -243,19 +244,15 @@
         mApplicationInfo = info;
         mDefaultClassLoader = classLoader;
         mAppComponentFactory = createAppFactory(info, mDefaultClassLoader);
-        mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader);
+        mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader,
+                new ApplicationInfo(mApplicationInfo));
     }
 
     private AppComponentFactory createAppFactory(ApplicationInfo appInfo, ClassLoader cl) {
         if (appInfo.appComponentFactory != null && cl != null) {
             try {
-                AppComponentFactory factory = (AppComponentFactory) cl.loadClass(
-                        appInfo.appComponentFactory).newInstance();
-                // Pass a copy of ApplicationInfo to the factory. Copying protects the framework
-                // from apps which would override the factory and change ApplicationInfo contents.
-                // ApplicationInfo is used to set up the default class loader.
-                factory.setApplicationInfo(new ApplicationInfo(appInfo));
-                return factory;
+                return (AppComponentFactory)
+                        cl.loadClass(appInfo.appComponentFactory).newInstance();
             } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                 Slog.e(TAG, "Unable to instantiate appComponentFactory", e);
             }
@@ -729,8 +726,8 @@
                 mDefaultClassLoader = ClassLoader.getSystemClassLoader();
             }
             mAppComponentFactory = createAppFactory(mApplicationInfo, mDefaultClassLoader);
-            mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader);
-
+            mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader,
+                    new ApplicationInfo(mApplicationInfo));
             return;
         }
 
@@ -821,7 +818,8 @@
             }
 
             if (mClassLoader == null) {
-                mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader);
+                mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader,
+                        new ApplicationInfo(mApplicationInfo));
             }
 
             return;
@@ -935,8 +933,10 @@
         // Call AppComponentFactory to select/create the main class loader of this app.
         // Since this may call code in the app, mDefaultClassLoader must be fully set up
         // before invoking the factory.
+        // Invoke with a copy of ApplicationInfo to protect against the app changing it.
         if (mClassLoader == null) {
-            mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader);
+            mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader,
+                    new ApplicationInfo(mApplicationInfo));
         }
     }
 
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index 2e7093d..e0cf561 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -1802,7 +1802,7 @@
             out.writeInt(mIsContextual ? 1 : 0);
         }
 
-        public static final Parcelable.Creator<Action> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<Action> CREATOR =
                 new Parcelable.Creator<Action>() {
             public Action createFromParcel(Parcel in) {
                 return new Action(in);
@@ -2731,7 +2731,7 @@
     /**
      * Parcelable.Creator that instantiates Notification objects
      */
-    public static final Parcelable.Creator<Notification> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Notification> CREATOR
             = new Parcelable.Creator<Notification>()
     {
         public Notification createFromParcel(Parcel parcel)
@@ -3471,6 +3471,7 @@
          * @param shortcutId the {@link ShortcutInfo#getId() id} of the shortcut this notification
          *                   supersedes
          */
+        @NonNull
         public Builder setShortcutId(String shortcutId) {
             mN.mShortcutId = shortcutId;
             return this;
@@ -3484,6 +3485,7 @@
          *
          * Note: This value might be ignored, for launchers that don't support badge icons.
          */
+        @NonNull
         public Builder setBadgeIconType(int icon) {
             mN.mBadgeIcon = icon;
             return this;
@@ -3499,6 +3501,7 @@
          *
          * <p> The default value is {@link #GROUP_ALERT_ALL}.</p>
          */
+        @NonNull
         public Builder setGroupAlertBehavior(@GroupAlertBehavior int groupAlertBehavior) {
             mN.mGroupAlertBehavior = groupAlertBehavior;
             return this;
@@ -3515,6 +3518,7 @@
          * outside of the notification shade on unlocked devices. When a user interacts with the
          * collapsed state, the bubble intent will be invoked and displayed.</b>
          */
+        @NonNull
         public Builder setBubbleMetadata(BubbleMetadata data) {
             mN.mBubbleMetadata = data;
             return this;
@@ -3530,6 +3534,7 @@
         /**
          * Specifies the channel the notification should be delivered on.
          */
+        @NonNull
         public Builder setChannelId(String channelId) {
             mN.mChannelId = channelId;
             return this;
@@ -3546,6 +3551,7 @@
          * Specifies a duration in milliseconds after which this notification should be canceled,
          * if it is not already canceled.
          */
+        @NonNull
         public Builder setTimeoutAfter(long durationMs) {
             mN.mTimeout = durationMs;
             return this;
@@ -3560,6 +3566,7 @@
          *
          * @see Notification#when
          */
+        @NonNull
         public Builder setWhen(long when) {
             mN.when = when;
             return this;
@@ -3571,6 +3578,7 @@
          * For apps targeting {@link android.os.Build.VERSION_CODES#N} and above, this defaults to
          * {@code false}. For earlier apps, the default is {@code true}.
          */
+        @NonNull
         public Builder setShowWhen(boolean show) {
             mN.extras.putBoolean(EXTRA_SHOW_WHEN, show);
             return this;
@@ -3591,6 +3599,7 @@
          * @see Notification#when
          * @see #setChronometerCountDown(boolean)
          */
+        @NonNull
         public Builder setUsesChronometer(boolean b) {
             mN.extras.putBoolean(EXTRA_SHOW_CHRONOMETER, b);
             return this;
@@ -3604,6 +3613,7 @@
          *
          * @see #setUsesChronometer(boolean)
          */
+        @NonNull
         public Builder setChronometerCountDown(boolean countDown) {
             mN.extras.putBoolean(EXTRA_CHRONOMETER_COUNT_DOWN, countDown);
             return this;
@@ -3623,6 +3633,7 @@
          *            A resource ID in the application's package of the drawable to use.
          * @see Notification#icon
          */
+        @NonNull
         public Builder setSmallIcon(@DrawableRes int icon) {
             return setSmallIcon(icon != 0
                     ? Icon.createWithResource(mContext, icon)
@@ -3640,6 +3651,7 @@
          * @see Notification#icon
          * @see Notification#iconLevel
          */
+        @NonNull
         public Builder setSmallIcon(@DrawableRes int icon, int level) {
             mN.iconLevel = level;
             return setSmallIcon(icon);
@@ -3653,6 +3665,7 @@
          * @param icon An Icon object to use.
          * @see Notification#icon
          */
+        @NonNull
         public Builder setSmallIcon(Icon icon) {
             mN.setSmallIcon(icon);
             if (icon != null && icon.getType() == Icon.TYPE_RESOURCE) {
@@ -3664,6 +3677,7 @@
         /**
          * Set the first line of text in the platform notification template.
          */
+        @NonNull
         public Builder setContentTitle(CharSequence title) {
             mN.extras.putCharSequence(EXTRA_TITLE, safeCharSequence(title));
             return this;
@@ -3672,6 +3686,7 @@
         /**
          * Set the second line of text in the platform notification template.
          */
+        @NonNull
         public Builder setContentText(CharSequence text) {
             mN.extras.putCharSequence(EXTRA_TEXT, safeCharSequence(text));
             return this;
@@ -3695,6 +3710,7 @@
          * same time on those versions; they occupy the same place.
          * </p>
          */
+        @NonNull
         public Builder setSubText(CharSequence text) {
             mN.extras.putCharSequence(EXTRA_SUB_TEXT, safeCharSequence(text));
             return this;
@@ -3713,6 +3729,7 @@
          * @param text
          * @return
          */
+        @NonNull
         public Builder setSettingsText(CharSequence text) {
             mN.mSettingsText = safeCharSequence(text);
             return this;
@@ -3732,6 +3749,7 @@
          * <p>Note: The reply text will only be shown on notifications that have least one action
          * with a {@code RemoteInput}.</p>
          */
+        @NonNull
         public Builder setRemoteInputHistory(CharSequence[] text) {
             if (text == null) {
                 mN.extras.putCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY, null);
@@ -3750,6 +3768,7 @@
          * Sets whether remote history entries view should have a spinner.
          * @hide
          */
+        @NonNull
         public Builder setShowRemoteInputSpinner(boolean showSpinner) {
             mN.extras.putBoolean(EXTRA_SHOW_REMOTE_INPUT_SPINNER, showSpinner);
             return this;
@@ -3759,6 +3778,7 @@
          * Sets whether smart reply buttons should be hidden.
          * @hide
          */
+        @NonNull
         public Builder setHideSmartReplies(boolean hideSmartReplies) {
             mN.extras.putBoolean(EXTRA_HIDE_SMART_REPLIES, hideSmartReplies);
             return this;
@@ -3768,6 +3788,7 @@
          * Sets the number of items this notification represents. May be displayed as a badge count
          * for Launchers that support badging.
          */
+        @NonNull
         public Builder setNumber(int number) {
             mN.number = number;
             return this;
@@ -3794,6 +3815,7 @@
          *
          * The platform template will represent this using a {@link ProgressBar}.
          */
+        @NonNull
         public Builder setProgress(int max, int progress, boolean indeterminate) {
             mN.extras.putInt(EXTRA_PROGRESS, progress);
             mN.extras.putInt(EXTRA_PROGRESS_MAX, max);
@@ -3817,6 +3839,7 @@
          * This will override the layout that would otherwise be constructed by this Builder
          * object.
          */
+        @NonNull
         public Builder setCustomContentView(RemoteViews contentView) {
             mN.contentView = contentView;
             return this;
@@ -3828,6 +3851,7 @@
          * This will override the expanded layout that would otherwise be constructed by this
          * Builder object.
          */
+        @NonNull
         public Builder setCustomBigContentView(RemoteViews contentView) {
             mN.bigContentView = contentView;
             return this;
@@ -3839,6 +3863,7 @@
          * This will override the heads-up layout that would otherwise be constructed by this
          * Builder object.
          */
+        @NonNull
         public Builder setCustomHeadsUpContentView(RemoteViews contentView) {
             mN.headsUpContentView = contentView;
             return this;
@@ -3855,6 +3880,7 @@
          *
          * @see Notification#contentIntent Notification.contentIntent
          */
+        @NonNull
         public Builder setContentIntent(PendingIntent intent) {
             mN.contentIntent = intent;
             return this;
@@ -3865,6 +3891,7 @@
          *
          * @see Notification#deleteIntent
          */
+        @NonNull
         public Builder setDeleteIntent(PendingIntent intent) {
             mN.deleteIntent = intent;
             return this;
@@ -3893,6 +3920,7 @@
          *
          * @see Notification#fullScreenIntent
          */
+        @NonNull
         public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
             mN.fullScreenIntent = intent;
             setFlag(FLAG_HIGH_PRIORITY, highPriority);
@@ -3904,6 +3932,7 @@
          *
          * @see Notification#tickerText
          */
+        @NonNull
         public Builder setTicker(CharSequence tickerText) {
             mN.tickerText = safeCharSequence(tickerText);
             return this;
@@ -3927,6 +3956,7 @@
          * in place of the {@link #setSmallIcon(Icon) small icon} (which will be placed in a small
          * badge atop the large icon).
          */
+        @NonNull
         public Builder setLargeIcon(Bitmap b) {
             return setLargeIcon(b != null ? Icon.createWithBitmap(b) : null);
         }
@@ -3938,6 +3968,7 @@
          * in place of the {@link #setSmallIcon(Icon) small icon} (which will be placed in a small
          * badge atop the large icon).
          */
+        @NonNull
         public Builder setLargeIcon(Icon icon) {
             mN.mLargeIcon = icon;
             mN.extras.putParcelable(EXTRA_LARGE_ICON, icon);
@@ -4045,6 +4076,7 @@
 
          * @see Notification#FLAG_ONGOING_EVENT
          */
+        @NonNull
         public Builder setOngoing(boolean ongoing) {
             setFlag(FLAG_ONGOING_EVENT, ongoing);
             return this;
@@ -4065,6 +4097,7 @@
          * @see #setColor(int)
          * @see MediaStyle#setMediaSession(MediaSession.Token)
          */
+        @NonNull
         public Builder setColorized(boolean colorize) {
             mN.extras.putBoolean(EXTRA_COLORIZED, colorize);
             return this;
@@ -4076,6 +4109,7 @@
          *
          * @see Notification#FLAG_ONLY_ALERT_ONCE
          */
+        @NonNull
         public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
             setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
             return this;
@@ -4086,6 +4120,7 @@
          *
          * @see Notification#FLAG_AUTO_CANCEL
          */
+        @NonNull
         public Builder setAutoCancel(boolean autoCancel) {
             setFlag(FLAG_AUTO_CANCEL, autoCancel);
             return this;
@@ -4097,6 +4132,7 @@
          * <p>Some notifications can be bridged to other devices for remote display.
          * This hint can be set to recommend this notification not be bridged.
          */
+        @NonNull
         public Builder setLocalOnly(boolean localOnly) {
             setFlag(FLAG_LOCAL_ONLY, localOnly);
             return this;
@@ -4138,6 +4174,7 @@
          *
          * @see Notification#category
          */
+        @NonNull
         public Builder setCategory(String category) {
             mN.category = category;
             return this;
@@ -4195,6 +4232,7 @@
          * @param person the person to add.
          * @see Notification#EXTRA_PEOPLE_LIST
          */
+        @NonNull
         public Builder addPerson(Person person) {
             mPersonList.add(person);
             return this;
@@ -4211,6 +4249,7 @@
          * @param groupKey The group key of the group.
          * @return this object for method chaining
          */
+        @NonNull
         public Builder setGroup(String groupKey) {
             mN.mGroupKey = groupKey;
             return this;
@@ -4224,6 +4263,7 @@
          * @param isGroupSummary Whether this notification should be a group summary.
          * @return this object for method chaining
          */
+        @NonNull
         public Builder setGroupSummary(boolean isGroupSummary) {
             setFlag(FLAG_GROUP_SUMMARY, isGroupSummary);
             return this;
@@ -4241,6 +4281,7 @@
          *
          * @see String#compareTo(String)
          */
+        @NonNull
         public Builder setSortKey(String sortKey) {
             mN.mSortKey = sortKey;
             return this;
@@ -4253,6 +4294,7 @@
          *
          * @see Notification#extras
          */
+        @NonNull
         public Builder addExtras(Bundle extras) {
             if (extras != null) {
                 mUserExtras.putAll(extras);
@@ -4272,6 +4314,7 @@
          *
          * @see Notification#extras
          */
+        @NonNull
         public Builder setExtras(Bundle extras) {
             if (extras != null) {
                 mUserExtras = extras;
@@ -4339,6 +4382,7 @@
          *
          * @param action The action to add.
          */
+        @NonNull
         public Builder addAction(Action action) {
             if (action != null) {
                 mActions.add(action);
@@ -4353,6 +4397,7 @@
          * @param actions
          * @return
          */
+        @NonNull
         public Builder setActions(Action... actions) {
             mActions.clear();
             for (int i = 0; i < actions.length; i++) {
@@ -4368,6 +4413,7 @@
          *
          * @param style Object responsible for modifying the notification style.
          */
+        @NonNull
         public Builder setStyle(Style style) {
             if (mStyle != style) {
                 mStyle = style;
@@ -4393,6 +4439,7 @@
          *
          * @return The same Builder.
          */
+        @NonNull
         public Builder setVisibility(@Visibility int visibility) {
             mN.visibility = visibility;
             return this;
@@ -4404,6 +4451,7 @@
          * @param n A replacement notification, presumably with some or all info redacted.
          * @return The same Builder.
          */
+        @NonNull
         public Builder setPublicVersion(Notification n) {
             if (n != null) {
                 mN.publicVersion = new Notification();
@@ -4418,6 +4466,7 @@
          * Apply an extender to this notification builder. Extenders may be used to add
          * metadata or change options on this builder.
          */
+        @NonNull
         public Builder extend(Extender extender) {
             extender.extend(this);
             return this;
@@ -4426,6 +4475,7 @@
         /**
          * @hide
          */
+        @NonNull
         public Builder setFlag(int mask, boolean value) {
             if (value) {
                 mN.flags |= mask;
@@ -4442,6 +4492,7 @@
          *
          * @return The same Builder.
          */
+        @NonNull
         public Builder setColor(@ColorInt int argb) {
             mN.color = argb;
             sanitizeColor();
@@ -5674,6 +5725,7 @@
          * Apply the unstyled operations and return a new {@link Notification} object.
          * @hide
          */
+        @NonNull
         public Notification buildUnstyled() {
             if (mActions.size() > 0) {
                 mN.actions = new Action[mActions.size()];
@@ -5694,6 +5746,7 @@
          * @param context The context for your application / activity.
          * @param n The notification to create a Builder from.
          */
+        @NonNull
         public static Notification.Builder recoverBuilder(Context context, Notification n) {
             // Re-create notification context so we can access app resources.
             ApplicationInfo applicationInfo = n.extras.getParcelable(
@@ -5718,6 +5771,7 @@
          * Determines whether the platform can generate contextual actions for a notification.
          * By default this is true.
          */
+        @NonNull
         public Builder setAllowSystemGeneratedContextualActions(boolean allowed) {
             mN.mAllowSystemGeneratedContextualActions = allowed;
             return this;
@@ -5735,6 +5789,7 @@
          * Combine all of the options that have been set and return a new {@link Notification}
          * object.
          */
+        @NonNull
         public Notification build() {
             // first, add any extras from the calling code
             if (mUserExtras != null) {
@@ -5793,7 +5848,8 @@
          *
          * @hide
          */
-        public Notification buildInto(Notification n) {
+        @NonNull
+        public Notification buildInto(@NonNull Notification n) {
             build().cloneInto(n, true);
             return n;
         }
@@ -8511,7 +8567,7 @@
             return (mFlags & FLAG_SUPPRESS_INITIAL_NOTIFICATION) != 0;
         }
 
-        public static final Parcelable.Creator<BubbleMetadata> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<BubbleMetadata> CREATOR =
                 new Parcelable.Creator<BubbleMetadata>() {
 
                     @Override
diff --git a/core/java/android/app/NotificationChannel.java b/core/java/android/app/NotificationChannel.java
index cfe27c7..5cdf85a 100644
--- a/core/java/android/app/NotificationChannel.java
+++ b/core/java/android/app/NotificationChannel.java
@@ -942,7 +942,7 @@
         return sb.toString();
     }
 
-    public static final Creator<NotificationChannel> CREATOR = new Creator<NotificationChannel>() {
+    public static final @android.annotation.NonNull Creator<NotificationChannel> CREATOR = new Creator<NotificationChannel>() {
         @Override
         public NotificationChannel createFromParcel(Parcel in) {
             return new NotificationChannel(in);
diff --git a/core/java/android/app/NotificationChannelGroup.java b/core/java/android/app/NotificationChannelGroup.java
index 34cd9f0..a8ee414 100644
--- a/core/java/android/app/NotificationChannelGroup.java
+++ b/core/java/android/app/NotificationChannelGroup.java
@@ -272,7 +272,7 @@
         return record;
     }
 
-    public static final Creator<NotificationChannelGroup> CREATOR =
+    public static final @android.annotation.NonNull Creator<NotificationChannelGroup> CREATOR =
             new Creator<NotificationChannelGroup>() {
         @Override
         public NotificationChannelGroup createFromParcel(Parcel in) {
diff --git a/core/java/android/app/NotificationManager.java b/core/java/android/app/NotificationManager.java
index 8207e0a..e252f78 100644
--- a/core/java/android/app/NotificationManager.java
+++ b/core/java/android/app/NotificationManager.java
@@ -1842,7 +1842,7 @@
             }
         }
 
-        public static final Parcelable.Creator<Policy> CREATOR = new Parcelable.Creator<Policy>() {
+        public static final @android.annotation.NonNull Parcelable.Creator<Policy> CREATOR = new Parcelable.Creator<Policy>() {
             @Override
             public Policy createFromParcel(Parcel in) {
                 return new Policy(in);
diff --git a/core/java/android/app/PendingIntent.java b/core/java/android/app/PendingIntent.java
index 55014eb..6f7a060 100644
--- a/core/java/android/app/PendingIntent.java
+++ b/core/java/android/app/PendingIntent.java
@@ -1208,7 +1208,7 @@
 
     }
 
-    public static final Parcelable.Creator<PendingIntent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<PendingIntent> CREATOR
             = new Parcelable.Creator<PendingIntent>() {
         public PendingIntent createFromParcel(Parcel in) {
             IBinder target = in.readStrongBinder();
diff --git a/core/java/android/app/Person.java b/core/java/android/app/Person.java
index 0abc998..14a5589 100644
--- a/core/java/android/app/Person.java
+++ b/core/java/android/app/Person.java
@@ -278,7 +278,7 @@
         }
     }
 
-    public static final Creator<Person> CREATOR = new Creator<Person>() {
+    public static final @android.annotation.NonNull Creator<Person> CREATOR = new Creator<Person>() {
         @Override
         public Person createFromParcel(Parcel in) {
             return new Person(in);
diff --git a/core/java/android/app/PictureInPictureArgs.java b/core/java/android/app/PictureInPictureArgs.java
index adcc495..3ee5173 100644
--- a/core/java/android/app/PictureInPictureArgs.java
+++ b/core/java/android/app/PictureInPictureArgs.java
@@ -346,7 +346,7 @@
         }
     }
 
-    public static final Creator<PictureInPictureArgs> CREATOR =
+    public static final @android.annotation.NonNull Creator<PictureInPictureArgs> CREATOR =
             new Creator<PictureInPictureArgs>() {
                 public PictureInPictureArgs createFromParcel(Parcel in) {
                     return new PictureInPictureArgs(in);
diff --git a/core/java/android/app/PictureInPictureParams.java b/core/java/android/app/PictureInPictureParams.java
index edaae75..bfd966c5 100644
--- a/core/java/android/app/PictureInPictureParams.java
+++ b/core/java/android/app/PictureInPictureParams.java
@@ -275,7 +275,7 @@
         }
     }
 
-    public static final Creator<PictureInPictureParams> CREATOR =
+    public static final @android.annotation.NonNull Creator<PictureInPictureParams> CREATOR =
             new Creator<PictureInPictureParams>() {
                 public PictureInPictureParams createFromParcel(Parcel in) {
                     return new PictureInPictureParams(in);
diff --git a/core/java/android/app/ProcessMemoryHighWaterMark.java b/core/java/android/app/ProcessMemoryHighWaterMark.java
index 5fea8ef..d1cae94 100644
--- a/core/java/android/app/ProcessMemoryHighWaterMark.java
+++ b/core/java/android/app/ProcessMemoryHighWaterMark.java
@@ -40,7 +40,7 @@
         rssHighWaterMarkInBytes = in.readLong();
     }
 
-    public static final Creator<ProcessMemoryHighWaterMark> CREATOR =
+    public static final @android.annotation.NonNull Creator<ProcessMemoryHighWaterMark> CREATOR =
             new Creator<ProcessMemoryHighWaterMark>() {
                 @Override
                 public ProcessMemoryHighWaterMark createFromParcel(Parcel in) {
diff --git a/core/java/android/app/ProcessMemoryState.java b/core/java/android/app/ProcessMemoryState.java
index 95d5d19..e28d79c 100644
--- a/core/java/android/app/ProcessMemoryState.java
+++ b/core/java/android/app/ProcessMemoryState.java
@@ -60,7 +60,7 @@
         startTimeNanos = in.readLong();
     }
 
-    public static final Creator<ProcessMemoryState> CREATOR = new Creator<ProcessMemoryState>() {
+    public static final @android.annotation.NonNull Creator<ProcessMemoryState> CREATOR = new Creator<ProcessMemoryState>() {
         @Override
         public ProcessMemoryState createFromParcel(Parcel in) {
             return new ProcessMemoryState(in);
diff --git a/core/java/android/app/ProfilerInfo.java b/core/java/android/app/ProfilerInfo.java
index 6fbe9c6..25589f8 100644
--- a/core/java/android/app/ProfilerInfo.java
+++ b/core/java/android/app/ProfilerInfo.java
@@ -148,7 +148,7 @@
         proto.end(token);
     }
 
-    public static final Parcelable.Creator<ProfilerInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ProfilerInfo> CREATOR =
             new Parcelable.Creator<ProfilerInfo>() {
                 @Override
                 public ProfilerInfo createFromParcel(Parcel in) {
diff --git a/core/java/android/app/RecoverableSecurityException.java b/core/java/android/app/RecoverableSecurityException.java
index 7cc3dab..21fb2a6 100644
--- a/core/java/android/app/RecoverableSecurityException.java
+++ b/core/java/android/app/RecoverableSecurityException.java
@@ -190,7 +190,7 @@
         mUserAction.writeToParcel(dest, flags);
     }
 
-    public static final Creator<RecoverableSecurityException> CREATOR =
+    public static final @android.annotation.NonNull Creator<RecoverableSecurityException> CREATOR =
             new Creator<RecoverableSecurityException>() {
         @Override
         public RecoverableSecurityException createFromParcel(Parcel source) {
diff --git a/core/java/android/app/RemoteAction.java b/core/java/android/app/RemoteAction.java
index c174665..1b13772 100644
--- a/core/java/android/app/RemoteAction.java
+++ b/core/java/android/app/RemoteAction.java
@@ -152,7 +152,7 @@
         pw.println();
     }
 
-    public static final Parcelable.Creator<RemoteAction> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<RemoteAction> CREATOR =
             new Parcelable.Creator<RemoteAction>() {
                 public RemoteAction createFromParcel(Parcel in) {
                     return new RemoteAction(in);
diff --git a/core/java/android/app/RemoteInput.java b/core/java/android/app/RemoteInput.java
index 392921e..36c524b 100644
--- a/core/java/android/app/RemoteInput.java
+++ b/core/java/android/app/RemoteInput.java
@@ -561,7 +561,7 @@
         out.writeArraySet(mAllowedDataTypes);
     }
 
-    public static final Creator<RemoteInput> CREATOR = new Creator<RemoteInput>() {
+    public static final @android.annotation.NonNull Creator<RemoteInput> CREATOR = new Creator<RemoteInput>() {
         @Override
         public RemoteInput createFromParcel(Parcel in) {
             return new RemoteInput(in);
diff --git a/core/java/android/app/ResultInfo.java b/core/java/android/app/ResultInfo.java
index d916c94..9ee0f31 100644
--- a/core/java/android/app/ResultInfo.java
+++ b/core/java/android/app/ResultInfo.java
@@ -67,7 +67,7 @@
     }
 
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
-    public static final Parcelable.Creator<ResultInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ResultInfo> CREATOR
             = new Parcelable.Creator<ResultInfo>() {
         public ResultInfo createFromParcel(Parcel in) {
             return new ResultInfo(in);
diff --git a/core/java/android/app/SearchDialog.java b/core/java/android/app/SearchDialog.java
index 4a45150..8493fb2 100644
--- a/core/java/android/app/SearchDialog.java
+++ b/core/java/android/app/SearchDialog.java
@@ -47,8 +47,10 @@
 import android.view.WindowManager;
 import android.view.inputmethod.InputMethodManager;
 import android.widget.AutoCompleteTextView;
+import android.widget.Filterable;
 import android.widget.ImageView;
 import android.widget.LinearLayout;
+import android.widget.ListPopupWindow;
 import android.widget.SearchView;
 import android.widget.TextView;
 
@@ -370,7 +372,10 @@
             updateSearchAppIcon();
             updateSearchBadge();
             if (isLandscapeMode(getContext())) {
-                mSearchAutoComplete.ensureImeVisible(true);
+                mSearchAutoComplete.setInputMethodMode(ListPopupWindow.INPUT_METHOD_NEEDED);
+                if (mSearchAutoComplete.isDropDownAlwaysVisible() || enoughToFilter()) {
+                    mSearchAutoComplete.showDropDown();
+                }
             }
         }
     }
@@ -381,6 +386,15 @@
                 == Configuration.ORIENTATION_LANDSCAPE;
     }
 
+    private boolean enoughToFilter() {
+        Filterable filterableAdapter = (Filterable) mSearchAutoComplete.getAdapter();
+        if (filterableAdapter == null || filterableAdapter.getFilter() == null) {
+            return false;
+        }
+
+        return mSearchAutoComplete.enoughToFilter();
+    }
+
     /**
      * Update the UI according to the info in the current value of {@link #mSearchable}.
      */
diff --git a/core/java/android/app/SearchableInfo.java b/core/java/android/app/SearchableInfo.java
index ae6d32a..a01cec7 100644
--- a/core/java/android/app/SearchableInfo.java
+++ b/core/java/android/app/SearchableInfo.java
@@ -800,7 +800,7 @@
     /**
      * Support for parcelable and aidl operations.
      */
-    public static final Parcelable.Creator<SearchableInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<SearchableInfo> CREATOR
     = new Parcelable.Creator<SearchableInfo>() {
         public SearchableInfo createFromParcel(Parcel in) {
             return new SearchableInfo(in);
diff --git a/core/java/android/app/Service.java b/core/java/android/app/Service.java
index f116e13..1f91b3f 100644
--- a/core/java/android/app/Service.java
+++ b/core/java/android/app/Service.java
@@ -27,6 +27,7 @@
 import android.content.Context;
 import android.content.ContextWrapper;
 import android.content.Intent;
+import android.content.pm.ServiceInfo;
 import android.content.pm.ServiceInfo.ForegroundServiceType;
 import android.content.res.Configuration;
 import android.os.Build;
@@ -733,7 +734,7 @@
    * {@link android.R.attr#foregroundServiceType} flags.
    * @throws IllegalArgumentException if param foregroundServiceType is not subset of manifest
    *     attribute {@link android.R.attr#foregroundServiceType}.
-   * @see {@link android.content.pm.ServiceInfo} for the set of FOREGROUND_SERVICE_TYPE flags.
+   * @see android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_MANIFEST
    */
     public final void startForeground(int id, @NonNull Notification notification,
             @ForegroundServiceType int foregroundServiceType) {
@@ -775,6 +776,30 @@
     }
 
     /**
+     * If the service has become a foreground service by calling
+     * {@link #startForeground(int, Notification)}
+     * or {@link #startForeground(int, Notification, int)}, {@link #getForegroundServiceType()}
+     * returns the current foreground service type.
+     *
+     * <p>If there is no foregroundServiceType specified
+     * in manifest, {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_NONE} is returned. </p>
+     *
+     * <p>If the service is not a foreground service,
+     * {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_NONE} is returned.</p>
+     *
+     * @return current foreground service type flags.
+     */
+    public final @ForegroundServiceType int getForegroundServiceType() {
+        int ret = ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
+        try {
+            ret = mActivityManager.getForegroundServiceType(
+                    new ComponentName(this, mClassName), mToken);
+        } catch (RemoteException ex) {
+        }
+        return ret;
+    }
+
+    /**
      * Print the Service's state into the given stream.  This gets invoked if
      * you run "adb shell dumpsys activity service &lt;yourservicename&gt;"
      * (note that for this command to work, the service must be running, and
diff --git a/core/java/android/app/ServiceStartArgs.java b/core/java/android/app/ServiceStartArgs.java
index f030cba..0b000af5 100644
--- a/core/java/android/app/ServiceStartArgs.java
+++ b/core/java/android/app/ServiceStartArgs.java
@@ -58,7 +58,7 @@
         }
     }
 
-    public static final Parcelable.Creator<ServiceStartArgs> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ServiceStartArgs> CREATOR
             = new Parcelable.Creator<ServiceStartArgs>() {
         public ServiceStartArgs createFromParcel(Parcel in) {
             return new ServiceStartArgs(in);
diff --git a/core/java/android/app/StatusBarManager.java b/core/java/android/app/StatusBarManager.java
index 077652c..9ff363d 100644
--- a/core/java/android/app/StatusBarManager.java
+++ b/core/java/android/app/StatusBarManager.java
@@ -17,7 +17,9 @@
 package android.app;
 
 import android.annotation.IntDef;
+import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.annotation.RequiresPermission;
 import android.annotation.SystemApi;
 import android.annotation.SystemService;
 import android.annotation.UnsupportedAppUsage;
@@ -364,6 +366,7 @@
      * @hide
      */
     @SystemApi
+    @RequiresPermission(android.Manifest.permission.STATUS_BAR)
     public void setDisabledForSetup(boolean disabled) {
         try {
             final int userId = Binder.getCallingUserHandle().getIdentifier();
@@ -387,6 +390,8 @@
      * @hide
      */
     @SystemApi
+    @RequiresPermission(android.Manifest.permission.STATUS_BAR)
+    @NonNull
     public DisableInfo getDisableInfo() {
         try {
             final int userId = Binder.getCallingUserHandle().getIdentifier();
@@ -518,7 +523,7 @@
          * @hide
          */
         @SystemApi
-        public boolean areNoComponentsDisabled() {
+        public boolean areAllComponentsEnabled() {
             return !mStatusBarExpansion && !mNavigateHome && !mNotificationPeeking && !mRecents
                     && !mSearch;
         }
diff --git a/core/java/android/app/TaskStackListener.java b/core/java/android/app/TaskStackListener.java
index fcc76ac..47ad6d7 100644
--- a/core/java/android/app/TaskStackListener.java
+++ b/core/java/android/app/TaskStackListener.java
@@ -85,6 +85,12 @@
     }
 
     @Override
+    @UnsupportedAppUsage
+    public void onActivityLaunchOnSecondaryDisplayRerouted(ActivityManager.RunningTaskInfo taskInfo,
+            int requestedDisplayId) throws RemoteException {
+    }
+
+    @Override
     public void onTaskCreated(int taskId, ComponentName componentName) throws RemoteException {
     }
 
diff --git a/core/java/android/app/VoiceInteractor.java b/core/java/android/app/VoiceInteractor.java
index 823c427..36ba78b 100644
--- a/core/java/android/app/VoiceInteractor.java
+++ b/core/java/android/app/VoiceInteractor.java
@@ -500,7 +500,7 @@
                 dest.writeBundle(mExtras);
             }
 
-            public static final Parcelable.Creator<Option> CREATOR
+            public static final @android.annotation.NonNull Parcelable.Creator<Option> CREATOR
                     = new Parcelable.Creator<Option>() {
                 public Option createFromParcel(Parcel in) {
                     return new Option(in);
@@ -869,7 +869,7 @@
             dest.writeCharSequence(mVisualPrompt);
         }
 
-        public static final Creator<Prompt> CREATOR
+        public static final @android.annotation.NonNull Creator<Prompt> CREATOR
                 = new Creator<Prompt>() {
             public Prompt createFromParcel(Parcel in) {
                 return new Prompt(in);
diff --git a/core/java/android/app/Vr2dDisplayProperties.java b/core/java/android/app/Vr2dDisplayProperties.java
index 1752131..bcb8592 100644
--- a/core/java/android/app/Vr2dDisplayProperties.java
+++ b/core/java/android/app/Vr2dDisplayProperties.java
@@ -112,7 +112,7 @@
         dest.writeInt(mRemovedFlags);
     }
 
-    public static final Parcelable.Creator<Vr2dDisplayProperties> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Vr2dDisplayProperties> CREATOR
             = new Parcelable.Creator<Vr2dDisplayProperties>() {
         @Override
         public Vr2dDisplayProperties createFromParcel(Parcel source) {
diff --git a/core/java/android/app/WaitResult.java b/core/java/android/app/WaitResult.java
index ad9f680..d65be9b 100644
--- a/core/java/android/app/WaitResult.java
+++ b/core/java/android/app/WaitResult.java
@@ -86,7 +86,7 @@
         dest.writeInt(launchState);
     }
 
-    public static final Parcelable.Creator<WaitResult> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<WaitResult> CREATOR
             = new Parcelable.Creator<WaitResult>() {
         @Override
         public WaitResult createFromParcel(Parcel source) {
diff --git a/core/java/android/app/WallpaperColors.java b/core/java/android/app/WallpaperColors.java
index 38a98d3c8..6765d0b 100644
--- a/core/java/android/app/WallpaperColors.java
+++ b/core/java/android/app/WallpaperColors.java
@@ -260,7 +260,7 @@
         mColorHints = colorHints;
     }
 
-    public static final Creator<WallpaperColors> CREATOR = new Creator<WallpaperColors>() {
+    public static final @android.annotation.NonNull Creator<WallpaperColors> CREATOR = new Creator<WallpaperColors>() {
         @Override
         public WallpaperColors createFromParcel(Parcel in) {
             return new WallpaperColors(in);
diff --git a/core/java/android/app/WallpaperInfo.java b/core/java/android/app/WallpaperInfo.java
index 28c79aa..c2be4b0 100644
--- a/core/java/android/app/WallpaperInfo.java
+++ b/core/java/android/app/WallpaperInfo.java
@@ -423,7 +423,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<WallpaperInfo> CREATOR = new Parcelable.Creator<WallpaperInfo>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<WallpaperInfo> CREATOR = new Parcelable.Creator<WallpaperInfo>() {
         public WallpaperInfo createFromParcel(Parcel source) {
             return new WallpaperInfo(source);
         }
diff --git a/core/java/android/app/WindowConfiguration.java b/core/java/android/app/WindowConfiguration.java
index e0a15a5..affc8b9 100644
--- a/core/java/android/app/WindowConfiguration.java
+++ b/core/java/android/app/WindowConfiguration.java
@@ -239,7 +239,7 @@
     }
 
     /** @hide */
-    public static final Creator<WindowConfiguration> CREATOR = new Creator<WindowConfiguration>() {
+    public static final @android.annotation.NonNull Creator<WindowConfiguration> CREATOR = new Creator<WindowConfiguration>() {
         @Override
         public WindowConfiguration createFromParcel(Parcel in) {
             return new WindowConfiguration(in);
diff --git a/core/java/android/app/admin/ConnectEvent.java b/core/java/android/app/admin/ConnectEvent.java
index d511c57..dc32384 100644
--- a/core/java/android/app/admin/ConnectEvent.java
+++ b/core/java/android/app/admin/ConnectEvent.java
@@ -72,7 +72,7 @@
                 mPackageName);
     }
 
-    public static final Parcelable.Creator<ConnectEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ConnectEvent> CREATOR
             = new Parcelable.Creator<ConnectEvent>() {
         @Override
         public ConnectEvent createFromParcel(Parcel in) {
diff --git a/core/java/android/app/admin/DeviceAdminInfo.java b/core/java/android/app/admin/DeviceAdminInfo.java
index 121161e..00903c4 100644
--- a/core/java/android/app/admin/DeviceAdminInfo.java
+++ b/core/java/android/app/admin/DeviceAdminInfo.java
@@ -525,7 +525,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<DeviceAdminInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<DeviceAdminInfo> CREATOR =
             new Parcelable.Creator<DeviceAdminInfo>() {
         public DeviceAdminInfo createFromParcel(Parcel source) {
             return new DeviceAdminInfo(source);
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index a32e01f..d593ad1 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -59,7 +59,6 @@
 import android.os.Bundle;
 import android.os.ParcelFileDescriptor;
 import android.os.Parcelable;
-import android.os.ParcelableException;
 import android.os.PersistableBundle;
 import android.os.Process;
 import android.os.RemoteCallback;
@@ -1453,7 +1452,7 @@
      * Constant for {@link #getPasswordComplexity()}: password satisfies one of the following:
      * <ul>
      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
-     * least 4
+     * least 8
      * <li>alphabetic, length at least 6
      * <li>alphanumeric, length at least 6
      * </ul>
diff --git a/core/java/android/app/admin/DnsEvent.java b/core/java/android/app/admin/DnsEvent.java
index a2d704b..aade934 100644
--- a/core/java/android/app/admin/DnsEvent.java
+++ b/core/java/android/app/admin/DnsEvent.java
@@ -101,7 +101,7 @@
                 mIpAddressesCount, mTimestamp, mPackageName);
     }
 
-    public static final Parcelable.Creator<DnsEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<DnsEvent> CREATOR
             = new Parcelable.Creator<DnsEvent>() {
         @Override
         public DnsEvent createFromParcel(Parcel in) {
diff --git a/core/java/android/app/admin/NetworkEvent.java b/core/java/android/app/admin/NetworkEvent.java
index 947e4fe..c00ec83 100644
--- a/core/java/android/app/admin/NetworkEvent.java
+++ b/core/java/android/app/admin/NetworkEvent.java
@@ -85,7 +85,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<NetworkEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<NetworkEvent> CREATOR
             = new Parcelable.Creator<NetworkEvent>() {
         public NetworkEvent createFromParcel(Parcel in) {
             final int initialPosition = in.dataPosition();
diff --git a/core/java/android/app/admin/PasswordMetrics.java b/core/java/android/app/admin/PasswordMetrics.java
index e5df2c7..d71d355 100644
--- a/core/java/android/app/admin/PasswordMetrics.java
+++ b/core/java/android/app/admin/PasswordMetrics.java
@@ -210,7 +210,7 @@
         dest.writeInt(nonLetter);
     }
 
-    public static final Parcelable.Creator<PasswordMetrics> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<PasswordMetrics> CREATOR
             = new Parcelable.Creator<PasswordMetrics>() {
         public PasswordMetrics createFromParcel(Parcel in) {
             return new PasswordMetrics(in);
@@ -221,7 +221,10 @@
         }
     };
 
-    public static PasswordMetrics computeForPassword(@NonNull String password) {
+    /**
+     * Returns the {@code PasswordMetrics} for a given password
+     */
+    public static PasswordMetrics computeForPassword(@NonNull byte[] password) {
         // Analyse the characters used
         int letters = 0;
         int upperCase = 0;
@@ -229,9 +232,9 @@
         int numeric = 0;
         int symbols = 0;
         int nonLetter = 0;
-        final int length = password.length();
+        final int length = password.length;
         for (int i = 0; i < length; i++) {
-            switch (categoryChar(password.charAt(i))) {
+            switch (categoryChar((char) password[i])) {
                 case CHAR_LOWER_CASE:
                     letters++;
                     lowerCase++;
@@ -296,7 +299,7 @@
         return false;
     }
 
-    /*
+    /**
      * Returns the maximum length of a sequential characters. A sequence is defined as
      * monotonically increasing characters with a constant interval or the same character repeated.
      *
@@ -310,19 +313,19 @@
      * maxLengthSequence(";;;;") == 4 (anything that repeats)
      * maxLengthSequence(":;<=>") == 1  (ordered, but not composed of alphas or digits)
      *
-     * @param string the pass
+     * @param bytes the pass
      * @return the number of sequential letters or digits
      */
-    public static int maxLengthSequence(@NonNull String string) {
-        if (string.length() == 0) return 0;
-        char previousChar = string.charAt(0);
+    public static int maxLengthSequence(@NonNull byte[] bytes) {
+        if (bytes.length == 0) return 0;
+        char previousChar = (char) bytes[0];
         @CharacterCatagory int category = categoryChar(previousChar); //current sequence category
         int diff = 0; //difference between two consecutive characters
         boolean hasDiff = false; //if we are currently targeting a sequence
         int maxLength = 0; //maximum length of a sequence already found
         int startSequence = 0; //where the current sequence started
-        for (int current = 1; current < string.length(); current++) {
-            char currentChar = string.charAt(current);
+        for (int current = 1; current < bytes.length; current++) {
+            char currentChar = (char) bytes[current];
             @CharacterCatagory int categoryCurrent = categoryChar(currentChar);
             int currentDiff = (int) currentChar - (int) previousChar;
             if (categoryCurrent != category || Math.abs(currentDiff) > maxDiffCategory(category)) {
@@ -341,7 +344,7 @@
             }
             previousChar = currentChar;
         }
-        maxLength = Math.max(maxLength, string.length() - startSequence);
+        maxLength = Math.max(maxLength, bytes.length - startSequence);
         return maxLength;
     }
 
diff --git a/core/java/android/app/admin/SecurityLog.java b/core/java/android/app/admin/SecurityLog.java
index 170c802..6386573 100644
--- a/core/java/android/app/admin/SecurityLog.java
+++ b/core/java/android/app/admin/SecurityLog.java
@@ -602,7 +602,7 @@
             dest.writeByteArray(mEvent.getBytes());
         }
 
-        public static final Parcelable.Creator<SecurityEvent> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SecurityEvent> CREATOR =
                 new Parcelable.Creator<SecurityEvent>() {
             @Override
             public SecurityEvent createFromParcel(Parcel source) {
diff --git a/core/java/android/app/admin/SystemUpdateInfo.java b/core/java/android/app/admin/SystemUpdateInfo.java
index b0376b5..4019290 100644
--- a/core/java/android/app/admin/SystemUpdateInfo.java
+++ b/core/java/android/app/admin/SystemUpdateInfo.java
@@ -111,7 +111,7 @@
         return mSecurityPatchState;
     }
 
-    public static final Creator<SystemUpdateInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<SystemUpdateInfo> CREATOR =
             new Creator<SystemUpdateInfo>() {
                 @Override
                 public SystemUpdateInfo createFromParcel(Parcel in) {
diff --git a/core/java/android/app/admin/SystemUpdatePolicy.java b/core/java/android/app/admin/SystemUpdatePolicy.java
index dd72845..2ba2c04 100644
--- a/core/java/android/app/admin/SystemUpdatePolicy.java
+++ b/core/java/android/app/admin/SystemUpdatePolicy.java
@@ -280,7 +280,7 @@
             dest.writeString(getMessage());
         }
 
-        public static final Parcelable.Creator<ValidationFailedException> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<ValidationFailedException> CREATOR =
                 new Parcelable.Creator<ValidationFailedException>() {
             @Override
             public ValidationFailedException createFromParcel(Parcel source) {
@@ -710,7 +710,7 @@
         }
     }
 
-    public static final Parcelable.Creator<SystemUpdatePolicy> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<SystemUpdatePolicy> CREATOR =
             new Parcelable.Creator<SystemUpdatePolicy>() {
 
                 @Override
diff --git a/core/java/android/app/assist/AssistContent.java b/core/java/android/app/assist/AssistContent.java
index ff7e181..db6ae4f 100644
--- a/core/java/android/app/assist/AssistContent.java
+++ b/core/java/android/app/assist/AssistContent.java
@@ -216,7 +216,7 @@
         writeToParcelInternal(dest, flags);
     }
 
-    public static final Parcelable.Creator<AssistContent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AssistContent> CREATOR
             = new Parcelable.Creator<AssistContent>() {
         public AssistContent createFromParcel(Parcel in) {
             return new AssistContent(in);
diff --git a/core/java/android/app/assist/AssistStructure.java b/core/java/android/app/assist/AssistStructure.java
index 2b1e7cd..ed3a296 100644
--- a/core/java/android/app/assist/AssistStructure.java
+++ b/core/java/android/app/assist/AssistStructure.java
@@ -2074,7 +2074,7 @@
         }
 
         @SuppressWarnings("hiding")
-        public static final Creator<HtmlInfoNode> CREATOR = new Creator<HtmlInfoNode>() {
+        public static final @android.annotation.NonNull Creator<HtmlInfoNode> CREATOR = new Creator<HtmlInfoNode>() {
             @Override
             public HtmlInfoNode createFromParcel(Parcel parcel) {
                 // Always go through the builder to ensure the data ingested by
@@ -2430,7 +2430,7 @@
         }
     }
 
-    public static final Parcelable.Creator<AssistStructure> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AssistStructure> CREATOR
             = new Parcelable.Creator<AssistStructure>() {
         @Override
         public AssistStructure createFromParcel(Parcel in) {
diff --git a/core/java/android/app/backup/BackupProgress.java b/core/java/android/app/backup/BackupProgress.java
index 32e6212..56f69fb 100644
--- a/core/java/android/app/backup/BackupProgress.java
+++ b/core/java/android/app/backup/BackupProgress.java
@@ -52,7 +52,7 @@
         out.writeLong(bytesTransferred);
     }
 
-    public static final Creator<BackupProgress> CREATOR = new Creator<BackupProgress>() {
+    public static final @android.annotation.NonNull Creator<BackupProgress> CREATOR = new Creator<BackupProgress>() {
         public BackupProgress createFromParcel(Parcel in) {
             return new BackupProgress(in);
         }
diff --git a/core/java/android/app/backup/RestoreDescription.java b/core/java/android/app/backup/RestoreDescription.java
index 0250326..7854394 100644
--- a/core/java/android/app/backup/RestoreDescription.java
+++ b/core/java/android/app/backup/RestoreDescription.java
@@ -89,7 +89,7 @@
         out.writeInt(mDataType);
     }
 
-    public static final Parcelable.Creator<RestoreDescription> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<RestoreDescription> CREATOR
             = new Parcelable.Creator<RestoreDescription>() {
         public RestoreDescription createFromParcel(Parcel in) {
             final RestoreDescription unparceled = new RestoreDescription(in);
diff --git a/core/java/android/app/backup/RestoreSet.java b/core/java/android/app/backup/RestoreSet.java
index 4a6316c..6759346 100644
--- a/core/java/android/app/backup/RestoreSet.java
+++ b/core/java/android/app/backup/RestoreSet.java
@@ -69,7 +69,7 @@
         out.writeLong(token);
     }
 
-    public static final Parcelable.Creator<RestoreSet> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<RestoreSet> CREATOR
             = new Parcelable.Creator<RestoreSet>() {
         public RestoreSet createFromParcel(Parcel in) {
             return new RestoreSet(in);
diff --git a/core/java/android/app/contentsuggestions/ClassificationsRequest.java b/core/java/android/app/contentsuggestions/ClassificationsRequest.java
index 9bb39e5..1b50015 100644
--- a/core/java/android/app/contentsuggestions/ClassificationsRequest.java
+++ b/core/java/android/app/contentsuggestions/ClassificationsRequest.java
@@ -71,7 +71,7 @@
         dest.writeBundle(mExtras);
     }
 
-    public static final Creator<ClassificationsRequest> CREATOR =
+    public static final @android.annotation.NonNull Creator<ClassificationsRequest> CREATOR =
             new Creator<ClassificationsRequest>() {
         @Override
         public ClassificationsRequest createFromParcel(Parcel source) {
diff --git a/core/java/android/app/contentsuggestions/ContentClassification.java b/core/java/android/app/contentsuggestions/ContentClassification.java
index 2a00b40..2317e4a 100644
--- a/core/java/android/app/contentsuggestions/ContentClassification.java
+++ b/core/java/android/app/contentsuggestions/ContentClassification.java
@@ -71,7 +71,7 @@
         dest.writeBundle(mExtras);
     }
 
-    public static final Creator<ContentClassification> CREATOR =
+    public static final @android.annotation.NonNull Creator<ContentClassification> CREATOR =
             new Creator<ContentClassification>() {
         @Override
         public ContentClassification createFromParcel(Parcel source) {
diff --git a/core/java/android/app/contentsuggestions/ContentSelection.java b/core/java/android/app/contentsuggestions/ContentSelection.java
index 16b4f3f..4c83f59 100644
--- a/core/java/android/app/contentsuggestions/ContentSelection.java
+++ b/core/java/android/app/contentsuggestions/ContentSelection.java
@@ -71,7 +71,7 @@
         dest.writeBundle(mExtras);
     }
 
-    public static final Creator<ContentSelection> CREATOR =
+    public static final @android.annotation.NonNull Creator<ContentSelection> CREATOR =
             new Creator<ContentSelection>() {
         @Override
         public ContentSelection createFromParcel(Parcel source) {
diff --git a/core/java/android/app/contentsuggestions/SelectionsRequest.java b/core/java/android/app/contentsuggestions/SelectionsRequest.java
index e3c8bc5..257f98d 100644
--- a/core/java/android/app/contentsuggestions/SelectionsRequest.java
+++ b/core/java/android/app/contentsuggestions/SelectionsRequest.java
@@ -81,7 +81,7 @@
         dest.writeBundle(mExtras);
     }
 
-    public static final Creator<SelectionsRequest> CREATOR =
+    public static final @android.annotation.NonNull Creator<SelectionsRequest> CREATOR =
             new Creator<SelectionsRequest>() {
         @Override
         public SelectionsRequest createFromParcel(Parcel source) {
diff --git a/core/java/android/app/job/JobInfo.java b/core/java/android/app/job/JobInfo.java
index e7fe161..907d1f7 100644
--- a/core/java/android/app/job/JobInfo.java
+++ b/core/java/android/app/job/JobInfo.java
@@ -870,7 +870,7 @@
         out.writeInt(this.flags);
     }
 
-    public static final Creator<JobInfo> CREATOR = new Creator<JobInfo>() {
+    public static final @android.annotation.NonNull Creator<JobInfo> CREATOR = new Creator<JobInfo>() {
         @Override
         public JobInfo createFromParcel(Parcel in) {
             return new JobInfo(in);
@@ -963,7 +963,7 @@
             out.writeInt(mFlags);
         }
 
-        public static final Creator<TriggerContentUri> CREATOR = new Creator<TriggerContentUri>() {
+        public static final @android.annotation.NonNull Creator<TriggerContentUri> CREATOR = new Creator<TriggerContentUri>() {
             @Override
             public TriggerContentUri createFromParcel(Parcel in) {
                 return new TriggerContentUri(in);
diff --git a/core/java/android/app/job/JobParameters.java b/core/java/android/app/job/JobParameters.java
index 3cc56ae..dadfe3d 100644
--- a/core/java/android/app/job/JobParameters.java
+++ b/core/java/android/app/job/JobParameters.java
@@ -344,7 +344,7 @@
         dest.writeString(debugStopReason);
     }
 
-    public static final Creator<JobParameters> CREATOR = new Creator<JobParameters>() {
+    public static final @android.annotation.NonNull Creator<JobParameters> CREATOR = new Creator<JobParameters>() {
         @Override
         public JobParameters createFromParcel(Parcel in) {
             return new JobParameters(in);
diff --git a/core/java/android/app/job/JobSnapshot.java b/core/java/android/app/job/JobSnapshot.java
index ceeaab7..2c58908 100644
--- a/core/java/android/app/job/JobSnapshot.java
+++ b/core/java/android/app/job/JobSnapshot.java
@@ -105,7 +105,7 @@
         out.writeBoolean(mIsRunnable);
     }
 
-    public static final Creator<JobSnapshot> CREATOR = new Creator<JobSnapshot>() {
+    public static final @android.annotation.NonNull Creator<JobSnapshot> CREATOR = new Creator<JobSnapshot>() {
         @Override
         public JobSnapshot createFromParcel(Parcel in) {
             return new JobSnapshot(in);
diff --git a/core/java/android/app/job/JobWorkItem.java b/core/java/android/app/job/JobWorkItem.java
index f804681..a055ab4 100644
--- a/core/java/android/app/job/JobWorkItem.java
+++ b/core/java/android/app/job/JobWorkItem.java
@@ -214,7 +214,7 @@
         out.writeInt(mWorkId);
     }
 
-    public static final Parcelable.Creator<JobWorkItem> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<JobWorkItem> CREATOR
             = new Parcelable.Creator<JobWorkItem>() {
         public JobWorkItem createFromParcel(Parcel in) {
             return new JobWorkItem(in);
diff --git a/core/java/android/app/prediction/AppPredictionContext.java b/core/java/android/app/prediction/AppPredictionContext.java
index 2fbe6e36..2da4671 100644
--- a/core/java/android/app/prediction/AppPredictionContext.java
+++ b/core/java/android/app/prediction/AppPredictionContext.java
@@ -101,7 +101,7 @@
     /**
      * @see Parcelable.Creator
      */
-    public static final Parcelable.Creator<AppPredictionContext> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AppPredictionContext> CREATOR =
             new Parcelable.Creator<AppPredictionContext>() {
                 public AppPredictionContext createFromParcel(Parcel parcel) {
                     return new AppPredictionContext(parcel);
diff --git a/core/java/android/app/prediction/AppPredictionSessionId.java b/core/java/android/app/prediction/AppPredictionSessionId.java
index 1e76c24..1c5d8b4 100644
--- a/core/java/android/app/prediction/AppPredictionSessionId.java
+++ b/core/java/android/app/prediction/AppPredictionSessionId.java
@@ -75,7 +75,7 @@
     /**
      * @see Parcelable.Creator
      */
-    public static final Parcelable.Creator<AppPredictionSessionId> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AppPredictionSessionId> CREATOR =
             new Parcelable.Creator<AppPredictionSessionId>() {
                 public AppPredictionSessionId createFromParcel(Parcel parcel) {
                     return new AppPredictionSessionId(parcel);
diff --git a/core/java/android/app/prediction/AppTarget.java b/core/java/android/app/prediction/AppTarget.java
index b924cec..752c92b 100644
--- a/core/java/android/app/prediction/AppTarget.java
+++ b/core/java/android/app/prediction/AppTarget.java
@@ -183,7 +183,7 @@
     /**
      * @see Parcelable.Creator
      */
-    public static final Parcelable.Creator<AppTarget> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AppTarget> CREATOR =
             new Parcelable.Creator<AppTarget>() {
                 public AppTarget createFromParcel(Parcel parcel) {
                     return new AppTarget(parcel);
diff --git a/core/java/android/app/prediction/AppTargetEvent.java b/core/java/android/app/prediction/AppTargetEvent.java
index 37e41de..01452df 100644
--- a/core/java/android/app/prediction/AppTargetEvent.java
+++ b/core/java/android/app/prediction/AppTargetEvent.java
@@ -122,7 +122,7 @@
     /**
      * @see Creator
      */
-    public static final Creator<AppTargetEvent> CREATOR =
+    public static final @android.annotation.NonNull Creator<AppTargetEvent> CREATOR =
             new Creator<AppTargetEvent>() {
                 public AppTargetEvent createFromParcel(Parcel parcel) {
                     return new AppTargetEvent(parcel);
diff --git a/core/java/android/app/prediction/AppTargetId.java b/core/java/android/app/prediction/AppTargetId.java
index 639ba78..aa2ec1f 100644
--- a/core/java/android/app/prediction/AppTargetId.java
+++ b/core/java/android/app/prediction/AppTargetId.java
@@ -83,7 +83,7 @@
     /**
      * @see Creator
      */
-    public static final Creator<AppTargetId> CREATOR =
+    public static final @android.annotation.NonNull Creator<AppTargetId> CREATOR =
             new Creator<AppTargetId>() {
                 public AppTargetId createFromParcel(Parcel parcel) {
                     return new AppTargetId(parcel);
diff --git a/core/java/android/app/role/OnRoleHoldersChangedListener.java b/core/java/android/app/role/OnRoleHoldersChangedListener.java
index 5958deb..d6f7679 100644
--- a/core/java/android/app/role/OnRoleHoldersChangedListener.java
+++ b/core/java/android/app/role/OnRoleHoldersChangedListener.java
@@ -18,6 +18,7 @@
 
 import android.annotation.NonNull;
 import android.annotation.SystemApi;
+import android.annotation.TestApi;
 import android.os.UserHandle;
 
 /**
@@ -26,6 +27,7 @@
  * @hide
  */
 @SystemApi
+@TestApi
 public interface OnRoleHoldersChangedListener {
 
     /**
diff --git a/core/java/android/app/role/RoleManager.java b/core/java/android/app/role/RoleManager.java
index edd3ef98..c665cb23 100644
--- a/core/java/android/app/role/RoleManager.java
+++ b/core/java/android/app/role/RoleManager.java
@@ -71,10 +71,8 @@
     /**
      * The name of the assistant app role.
      *
-     * @hide
+     * @see android.service.voice.VoiceInteractionService
      */
-    @SystemApi
-    @TestApi
     public static final String ROLE_ASSISTANT = "android.app.role.ASSISTANT";
 
     /**
@@ -149,9 +147,6 @@
      * place the call through a call redirection service.
      *
      * @see android.telecom.CallRedirectionService
-     *
-     * TODO: STOPSHIP: Make name of required roles public API
-     * @hide
      */
     public static final String ROLE_CALL_REDIRECTION = "android.app.role.CALL_REDIRECTION";
 
@@ -159,9 +154,6 @@
      * The name of the call screening and caller id role.
      *
      * @see android.telecom.CallScreeningService
-     *
-     * TODO: STOPSHIP: Make name of required roles public API
-     * @hide
      */
     public static final String ROLE_CALL_SCREENING = "android.app.role.CALL_SCREENING";
 
@@ -475,6 +467,7 @@
      */
     @RequiresPermission(Manifest.permission.OBSERVE_ROLE_HOLDERS)
     @SystemApi
+    @TestApi
     public void addOnRoleHoldersChangedListenerAsUser(@CallbackExecutor @NonNull Executor executor,
             @NonNull OnRoleHoldersChangedListener listener, @NonNull UserHandle user) {
         Preconditions.checkNotNull(executor, "executor cannot be null");
@@ -520,6 +513,7 @@
      */
     @RequiresPermission(Manifest.permission.OBSERVE_ROLE_HOLDERS)
     @SystemApi
+    @TestApi
     public void removeOnRoleHoldersChangedListenerAsUser(
             @NonNull OnRoleHoldersChangedListener listener, @NonNull UserHandle user) {
         Preconditions.checkNotNull(listener, "listener cannot be null");
@@ -561,6 +555,7 @@
      */
     @RequiresPermission(PERMISSION_MANAGE_ROLES_FROM_CONTROLLER)
     @SystemApi
+    @TestApi
     public void setRoleNamesFromController(@NonNull List<String> roleNames) {
         Preconditions.checkNotNull(roleNames, "roleNames cannot be null");
         try {
@@ -591,6 +586,7 @@
      */
     @RequiresPermission(PERMISSION_MANAGE_ROLES_FROM_CONTROLLER)
     @SystemApi
+    @TestApi
     public boolean addRoleHolderFromController(@NonNull String roleName,
             @NonNull String packageName) {
         Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
@@ -623,6 +619,7 @@
      */
     @RequiresPermission(PERMISSION_MANAGE_ROLES_FROM_CONTROLLER)
     @SystemApi
+    @TestApi
     public boolean removeRoleHolderFromController(@NonNull String roleName,
             @NonNull String packageName) {
         Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
@@ -642,9 +639,10 @@
      *
      * @hide
      */
+    @NonNull
     @RequiresPermission(PERMISSION_MANAGE_ROLES_FROM_CONTROLLER)
     @SystemApi
-    @NonNull
+    @TestApi
     public List<String> getHeldRolesFromController(@NonNull String packageName) {
         Preconditions.checkStringNotEmpty(packageName, "packageName cannot be null or empty");
         try {
diff --git a/core/java/android/app/servertransaction/ActivityConfigurationChangeItem.java b/core/java/android/app/servertransaction/ActivityConfigurationChangeItem.java
index 8ee9e53..0d4e16b 100644
--- a/core/java/android/app/servertransaction/ActivityConfigurationChangeItem.java
+++ b/core/java/android/app/servertransaction/ActivityConfigurationChangeItem.java
@@ -86,7 +86,7 @@
         mConfiguration = in.readTypedObject(Configuration.CREATOR);
     }
 
-    public static final Creator<ActivityConfigurationChangeItem> CREATOR =
+    public static final @android.annotation.NonNull Creator<ActivityConfigurationChangeItem> CREATOR =
             new Creator<ActivityConfigurationChangeItem>() {
         public ActivityConfigurationChangeItem createFromParcel(Parcel in) {
             return new ActivityConfigurationChangeItem(in);
diff --git a/core/java/android/app/servertransaction/ActivityRelaunchItem.java b/core/java/android/app/servertransaction/ActivityRelaunchItem.java
index d8a7463..9844de7 100644
--- a/core/java/android/app/servertransaction/ActivityRelaunchItem.java
+++ b/core/java/android/app/servertransaction/ActivityRelaunchItem.java
@@ -130,7 +130,7 @@
         mPreserveWindow = in.readBoolean();
     }
 
-    public static final Creator<ActivityRelaunchItem> CREATOR =
+    public static final @android.annotation.NonNull Creator<ActivityRelaunchItem> CREATOR =
             new Creator<ActivityRelaunchItem>() {
                 public ActivityRelaunchItem createFromParcel(Parcel in) {
                     return new ActivityRelaunchItem(in);
diff --git a/core/java/android/app/servertransaction/ActivityResultItem.java b/core/java/android/app/servertransaction/ActivityResultItem.java
index bab17dc..52ec3e6 100644
--- a/core/java/android/app/servertransaction/ActivityResultItem.java
+++ b/core/java/android/app/servertransaction/ActivityResultItem.java
@@ -88,7 +88,7 @@
         mResultInfoList = in.createTypedArrayList(ResultInfo.CREATOR);
     }
 
-    public static final Parcelable.Creator<ActivityResultItem> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ActivityResultItem> CREATOR =
             new Parcelable.Creator<ActivityResultItem>() {
         public ActivityResultItem createFromParcel(Parcel in) {
             return new ActivityResultItem(in);
diff --git a/core/java/android/app/servertransaction/ClientTransaction.java b/core/java/android/app/servertransaction/ClientTransaction.java
index f1d87ac..b08e5973 100644
--- a/core/java/android/app/servertransaction/ClientTransaction.java
+++ b/core/java/android/app/servertransaction/ClientTransaction.java
@@ -204,7 +204,7 @@
         }
     }
 
-    public static final Creator<ClientTransaction> CREATOR =
+    public static final @android.annotation.NonNull Creator<ClientTransaction> CREATOR =
             new Creator<ClientTransaction>() {
         public ClientTransaction createFromParcel(Parcel in) {
             return new ClientTransaction(in);
diff --git a/core/java/android/app/servertransaction/ConfigurationChangeItem.java b/core/java/android/app/servertransaction/ConfigurationChangeItem.java
index 4ab7251..0f244d0 100644
--- a/core/java/android/app/servertransaction/ConfigurationChangeItem.java
+++ b/core/java/android/app/servertransaction/ConfigurationChangeItem.java
@@ -78,7 +78,7 @@
         mConfiguration = in.readTypedObject(Configuration.CREATOR);
     }
 
-    public static final Creator<ConfigurationChangeItem> CREATOR =
+    public static final @android.annotation.NonNull Creator<ConfigurationChangeItem> CREATOR =
             new Creator<ConfigurationChangeItem>() {
         public ConfigurationChangeItem createFromParcel(Parcel in) {
             return new ConfigurationChangeItem(in);
diff --git a/core/java/android/app/servertransaction/DestroyActivityItem.java b/core/java/android/app/servertransaction/DestroyActivityItem.java
index 5941486..3ee7614 100644
--- a/core/java/android/app/servertransaction/DestroyActivityItem.java
+++ b/core/java/android/app/servertransaction/DestroyActivityItem.java
@@ -92,7 +92,7 @@
         mConfigChanges = in.readInt();
     }
 
-    public static final Creator<DestroyActivityItem> CREATOR =
+    public static final @android.annotation.NonNull Creator<DestroyActivityItem> CREATOR =
             new Creator<DestroyActivityItem>() {
         public DestroyActivityItem createFromParcel(Parcel in) {
             return new DestroyActivityItem(in);
diff --git a/core/java/android/app/servertransaction/LaunchActivityItem.java b/core/java/android/app/servertransaction/LaunchActivityItem.java
index ed793bf..db22f8d 100644
--- a/core/java/android/app/servertransaction/LaunchActivityItem.java
+++ b/core/java/android/app/servertransaction/LaunchActivityItem.java
@@ -148,7 +148,7 @@
                 in.readTypedObject(ProfilerInfo.CREATOR));
     }
 
-    public static final Creator<LaunchActivityItem> CREATOR =
+    public static final @android.annotation.NonNull Creator<LaunchActivityItem> CREATOR =
             new Creator<LaunchActivityItem>() {
         public LaunchActivityItem createFromParcel(Parcel in) {
             return new LaunchActivityItem(in);
diff --git a/core/java/android/app/servertransaction/MoveToDisplayItem.java b/core/java/android/app/servertransaction/MoveToDisplayItem.java
index b3dddfb3..f6d3dbd 100644
--- a/core/java/android/app/servertransaction/MoveToDisplayItem.java
+++ b/core/java/android/app/servertransaction/MoveToDisplayItem.java
@@ -83,7 +83,7 @@
         mConfiguration = in.readTypedObject(Configuration.CREATOR);
     }
 
-    public static final Creator<MoveToDisplayItem> CREATOR = new Creator<MoveToDisplayItem>() {
+    public static final @android.annotation.NonNull Creator<MoveToDisplayItem> CREATOR = new Creator<MoveToDisplayItem>() {
         public MoveToDisplayItem createFromParcel(Parcel in) {
             return new MoveToDisplayItem(in);
         }
diff --git a/core/java/android/app/servertransaction/MultiWindowModeChangeItem.java b/core/java/android/app/servertransaction/MultiWindowModeChangeItem.java
index c3022d6..b150717 100644
--- a/core/java/android/app/servertransaction/MultiWindowModeChangeItem.java
+++ b/core/java/android/app/servertransaction/MultiWindowModeChangeItem.java
@@ -81,7 +81,7 @@
         mOverrideConfig = in.readTypedObject(Configuration.CREATOR);
     }
 
-    public static final Creator<MultiWindowModeChangeItem> CREATOR =
+    public static final @android.annotation.NonNull Creator<MultiWindowModeChangeItem> CREATOR =
             new Creator<MultiWindowModeChangeItem>() {
         public MultiWindowModeChangeItem createFromParcel(Parcel in) {
             return new MultiWindowModeChangeItem(in);
diff --git a/core/java/android/app/servertransaction/NewIntentItem.java b/core/java/android/app/servertransaction/NewIntentItem.java
index 4f28cd2..4c7f56d 100644
--- a/core/java/android/app/servertransaction/NewIntentItem.java
+++ b/core/java/android/app/servertransaction/NewIntentItem.java
@@ -92,7 +92,7 @@
         mIntents = in.createTypedArrayList(ReferrerIntent.CREATOR);
     }
 
-    public static final Parcelable.Creator<NewIntentItem> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<NewIntentItem> CREATOR =
             new Parcelable.Creator<NewIntentItem>() {
         public NewIntentItem createFromParcel(Parcel in) {
             return new NewIntentItem(in);
diff --git a/core/java/android/app/servertransaction/PauseActivityItem.java b/core/java/android/app/servertransaction/PauseActivityItem.java
index cae93b3..f65c843 100644
--- a/core/java/android/app/servertransaction/PauseActivityItem.java
+++ b/core/java/android/app/servertransaction/PauseActivityItem.java
@@ -130,7 +130,7 @@
         mDontReport = in.readBoolean();
     }
 
-    public static final Creator<PauseActivityItem> CREATOR =
+    public static final @android.annotation.NonNull Creator<PauseActivityItem> CREATOR =
             new Creator<PauseActivityItem>() {
         public PauseActivityItem createFromParcel(Parcel in) {
             return new PauseActivityItem(in);
diff --git a/core/java/android/app/servertransaction/PipModeChangeItem.java b/core/java/android/app/servertransaction/PipModeChangeItem.java
index b999cd7..1955897 100644
--- a/core/java/android/app/servertransaction/PipModeChangeItem.java
+++ b/core/java/android/app/servertransaction/PipModeChangeItem.java
@@ -79,7 +79,7 @@
         mOverrideConfig = in.readTypedObject(Configuration.CREATOR);
     }
 
-    public static final Creator<PipModeChangeItem> CREATOR =
+    public static final @android.annotation.NonNull Creator<PipModeChangeItem> CREATOR =
             new Creator<PipModeChangeItem>() {
         public PipModeChangeItem createFromParcel(Parcel in) {
             return new PipModeChangeItem(in);
diff --git a/core/java/android/app/servertransaction/ResumeActivityItem.java b/core/java/android/app/servertransaction/ResumeActivityItem.java
index a5b6f7c..905076b 100644
--- a/core/java/android/app/servertransaction/ResumeActivityItem.java
+++ b/core/java/android/app/servertransaction/ResumeActivityItem.java
@@ -128,7 +128,7 @@
         mIsForward = in.readBoolean();
     }
 
-    public static final Creator<ResumeActivityItem> CREATOR =
+    public static final @android.annotation.NonNull Creator<ResumeActivityItem> CREATOR =
             new Creator<ResumeActivityItem>() {
         public ResumeActivityItem createFromParcel(Parcel in) {
             return new ResumeActivityItem(in);
diff --git a/core/java/android/app/servertransaction/StopActivityItem.java b/core/java/android/app/servertransaction/StopActivityItem.java
index 87db206..63efa6f 100644
--- a/core/java/android/app/servertransaction/StopActivityItem.java
+++ b/core/java/android/app/servertransaction/StopActivityItem.java
@@ -95,7 +95,7 @@
         mConfigChanges = in.readInt();
     }
 
-    public static final Creator<StopActivityItem> CREATOR =
+    public static final @android.annotation.NonNull Creator<StopActivityItem> CREATOR =
             new Creator<StopActivityItem>() {
         public StopActivityItem createFromParcel(Parcel in) {
             return new StopActivityItem(in);
diff --git a/core/java/android/app/servertransaction/TopResumedActivityChangeItem.java b/core/java/android/app/servertransaction/TopResumedActivityChangeItem.java
index 4064a02..c7e4c36 100644
--- a/core/java/android/app/servertransaction/TopResumedActivityChangeItem.java
+++ b/core/java/android/app/servertransaction/TopResumedActivityChangeItem.java
@@ -17,9 +17,11 @@
 
 import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
 
+import android.app.ActivityTaskManager;
 import android.app.ClientTransactionHandler;
 import android.os.IBinder;
 import android.os.Parcel;
+import android.os.RemoteException;
 import android.os.Trace;
 
 /**
@@ -38,6 +40,26 @@
         Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
     }
 
+    @Override
+    public void postExecute(ClientTransactionHandler client, IBinder token,
+            PendingTransactionActions pendingActions) {
+        if (mOnTop) {
+            return;
+        }
+
+        // The loss of top resumed state can always be reported immediately in postExecute
+        // because only three cases are possible:
+        // 1. Activity is in RESUMED state now and it just handled the callback in #execute().
+        // 2. Activity wasn't RESUMED yet, which means that it didn't receive the top state yet.
+        // 3. Activity is PAUSED or in other lifecycle state after PAUSED. In this case top resumed
+        // state loss was already called right before pausing.
+        try {
+            ActivityTaskManager.getService().activityTopResumedStateLost();
+        } catch (RemoteException ex) {
+            throw ex.rethrowFromSystemServer();
+        }
+    }
+
 
     // ObjectPoolItem implementation
 
@@ -75,7 +97,7 @@
         mOnTop = in.readBoolean();
     }
 
-    public static final Creator<TopResumedActivityChangeItem> CREATOR =
+    public static final @android.annotation.NonNull Creator<TopResumedActivityChangeItem> CREATOR =
             new Creator<TopResumedActivityChangeItem>() {
                 public TopResumedActivityChangeItem createFromParcel(Parcel in) {
                     return new TopResumedActivityChangeItem(in);
diff --git a/core/java/android/app/servertransaction/WindowVisibilityItem.java b/core/java/android/app/servertransaction/WindowVisibilityItem.java
index d9956b1..115d1ec 100644
--- a/core/java/android/app/servertransaction/WindowVisibilityItem.java
+++ b/core/java/android/app/servertransaction/WindowVisibilityItem.java
@@ -34,7 +34,8 @@
     @Override
     public void execute(ClientTransactionHandler client, IBinder token,
             PendingTransactionActions pendingActions) {
-        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityShowWindow");
+        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER,
+                mShowWindow ? "activityShowWindow" : "activityHideWindow");
         client.handleWindowVisibility(token, mShowWindow);
         Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
     }
@@ -75,7 +76,7 @@
         mShowWindow = in.readBoolean();
     }
 
-    public static final Creator<WindowVisibilityItem> CREATOR =
+    public static final @android.annotation.NonNull Creator<WindowVisibilityItem> CREATOR =
             new Creator<WindowVisibilityItem>() {
         public WindowVisibilityItem createFromParcel(Parcel in) {
             return new WindowVisibilityItem(in);
diff --git a/core/java/android/app/slice/Slice.java b/core/java/android/app/slice/Slice.java
index d1aec04..a7319f6 100644
--- a/core/java/android/app/slice/Slice.java
+++ b/core/java/android/app/slice/Slice.java
@@ -543,7 +543,7 @@
         }
     }
 
-    public static final Creator<Slice> CREATOR = new Creator<Slice>() {
+    public static final @android.annotation.NonNull Creator<Slice> CREATOR = new Creator<Slice>() {
         @Override
         public Slice createFromParcel(Parcel in) {
             return new Slice(in);
diff --git a/core/java/android/app/slice/SliceItem.java b/core/java/android/app/slice/SliceItem.java
index c058a14..ed32a1b 100644
--- a/core/java/android/app/slice/SliceItem.java
+++ b/core/java/android/app/slice/SliceItem.java
@@ -378,7 +378,7 @@
         throw new RuntimeException("Unsupported type " + type);
     }
 
-    public static final Creator<SliceItem> CREATOR = new Creator<SliceItem>() {
+    public static final @android.annotation.NonNull Creator<SliceItem> CREATOR = new Creator<SliceItem>() {
         @Override
         public SliceItem createFromParcel(Parcel in) {
             return new SliceItem(in);
diff --git a/core/java/android/app/slice/SliceSpec.java b/core/java/android/app/slice/SliceSpec.java
index b3790e2..b1080e0 100644
--- a/core/java/android/app/slice/SliceSpec.java
+++ b/core/java/android/app/slice/SliceSpec.java
@@ -108,7 +108,7 @@
         return String.format("SliceSpec{%s,%d}", mType, mRevision);
     }
 
-    public static final Creator<SliceSpec> CREATOR = new Creator<SliceSpec>() {
+    public static final @android.annotation.NonNull Creator<SliceSpec> CREATOR = new Creator<SliceSpec>() {
         @Override
         public SliceSpec createFromParcel(Parcel source) {
             return new SliceSpec(source);
diff --git a/core/java/android/app/timedetector/TimeSignal.java b/core/java/android/app/timedetector/TimeSignal.java
index 7ba03cc..da21794 100644
--- a/core/java/android/app/timedetector/TimeSignal.java
+++ b/core/java/android/app/timedetector/TimeSignal.java
@@ -33,7 +33,7 @@
  */
 public final class TimeSignal implements Parcelable {
 
-    public static final Parcelable.Creator<TimeSignal> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TimeSignal> CREATOR =
             new Parcelable.Creator<TimeSignal>() {
                 public TimeSignal createFromParcel(Parcel in) {
                     return TimeSignal.createFromParcel(in);
diff --git a/core/java/android/app/timezone/DistroFormatVersion.java b/core/java/android/app/timezone/DistroFormatVersion.java
index be732e4..04e3142 100644
--- a/core/java/android/app/timezone/DistroFormatVersion.java
+++ b/core/java/android/app/timezone/DistroFormatVersion.java
@@ -45,7 +45,7 @@
         mMinorVersion = Utils.validateVersion("minor", minorVersion);
     }
 
-    public static final Creator<DistroFormatVersion> CREATOR = new Creator<DistroFormatVersion>() {
+    public static final @android.annotation.NonNull Creator<DistroFormatVersion> CREATOR = new Creator<DistroFormatVersion>() {
         public DistroFormatVersion createFromParcel(Parcel in) {
             int majorVersion = in.readInt();
             int minorVersion = in.readInt();
diff --git a/core/java/android/app/timezone/DistroRulesVersion.java b/core/java/android/app/timezone/DistroRulesVersion.java
index a680594..3fae161 100644
--- a/core/java/android/app/timezone/DistroRulesVersion.java
+++ b/core/java/android/app/timezone/DistroRulesVersion.java
@@ -46,7 +46,7 @@
         mRevision = validateVersion("revision", revision);
     }
 
-    public static final Creator<DistroRulesVersion> CREATOR = new Creator<DistroRulesVersion>() {
+    public static final @android.annotation.NonNull Creator<DistroRulesVersion> CREATOR = new Creator<DistroRulesVersion>() {
         public DistroRulesVersion createFromParcel(Parcel in) {
             String rulesVersion = in.readString();
             int revision = in.readInt();
diff --git a/core/java/android/app/timezone/RulesState.java b/core/java/android/app/timezone/RulesState.java
index e86d348..d35967d 100644
--- a/core/java/android/app/timezone/RulesState.java
+++ b/core/java/android/app/timezone/RulesState.java
@@ -33,7 +33,7 @@
  *
  * <p>The following properties are included:
  * <dl>
- *     <dt>systemRulesVersion</dt>
+ *     <dt>baseRulesVersion</dt>
  *     <dd>the IANA rules version that shipped with the OS. Always present. e.g. "2017a".</dd>
  *     <dt>distroFormatVersionSupported</dt>
  *     <dd>the distro format version supported by this device. Always present.</dd>
@@ -98,7 +98,7 @@
     private static final byte BYTE_FALSE = 0;
     private static final byte BYTE_TRUE = 1;
 
-    private final String mSystemRulesVersion;
+    private final String mBaseRulesVersion;
     private final DistroFormatVersion mDistroFormatVersionSupported;
     private final boolean mOperationInProgress;
     @StagedOperationType private final int mStagedOperationType;
@@ -106,13 +106,13 @@
     @DistroStatus private final int mDistroStatus;
     @Nullable private final DistroRulesVersion mInstalledDistroRulesVersion;
 
-    public RulesState(String systemRulesVersion, DistroFormatVersion distroFormatVersionSupported,
+    public RulesState(String baseRulesVersion, DistroFormatVersion distroFormatVersionSupported,
             boolean operationInProgress,
             @StagedOperationType int stagedOperationType,
             @Nullable DistroRulesVersion stagedDistroRulesVersion,
             @DistroStatus int distroStatus,
             @Nullable DistroRulesVersion installedDistroRulesVersion) {
-        this.mSystemRulesVersion = validateRulesVersion("systemRulesVersion", systemRulesVersion);
+        this.mBaseRulesVersion = validateRulesVersion("baseRulesVersion", baseRulesVersion);
         this.mDistroFormatVersionSupported =
                 validateNotNull("distroFormatVersionSupported", distroFormatVersionSupported);
         this.mOperationInProgress = operationInProgress;
@@ -132,8 +132,8 @@
                 "installedDistroRulesVersion", installedDistroRulesVersion);
     }
 
-    public String getSystemRulesVersion() {
-        return mSystemRulesVersion;
+    public String getBaseRulesVersion() {
+        return mBaseRulesVersion;
     }
 
     public boolean isOperationInProgress() {
@@ -172,17 +172,17 @@
     }
 
     /**
-     * Returns true if the system image data files contain IANA rules data that are newer than the
+     * Returns true if the base data files contain IANA rules data that are newer than the
      * distro IANA rules version supplied, i.e. true when the version specified would be "worse"
-     * than the one that is in the system image. Returns false if the system image version is the
+     * than the one that is in the base data. Returns false if the base version is the
      * same or older, i.e. false when the version specified would be "better" than the one that is
-     * in the system image.
+     * in the base set.
      */
-    public boolean isSystemVersionNewerThan(DistroRulesVersion distroRulesVersion) {
-        return mSystemRulesVersion.compareTo(distroRulesVersion.getRulesVersion()) > 0;
+    public boolean isBaseVersionNewerThan(DistroRulesVersion distroRulesVersion) {
+        return mBaseRulesVersion.compareTo(distroRulesVersion.getRulesVersion()) > 0;
     }
 
-    public static final Parcelable.Creator<RulesState> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<RulesState> CREATOR =
             new Parcelable.Creator<RulesState>() {
         public RulesState createFromParcel(Parcel in) {
             return RulesState.createFromParcel(in);
@@ -194,14 +194,14 @@
     };
 
     private static RulesState createFromParcel(Parcel in) {
-        String systemRulesVersion = in.readString();
+        String baseRulesVersion = in.readString();
         DistroFormatVersion distroFormatVersionSupported = in.readParcelable(null);
         boolean operationInProgress = in.readByte() == BYTE_TRUE;
         int distroStagedState = in.readByte();
         DistroRulesVersion stagedDistroRulesVersion = in.readParcelable(null);
         int installedDistroStatus = in.readByte();
         DistroRulesVersion installedDistroRulesVersion = in.readParcelable(null);
-        return new RulesState(systemRulesVersion, distroFormatVersionSupported, operationInProgress,
+        return new RulesState(baseRulesVersion, distroFormatVersionSupported, operationInProgress,
                 distroStagedState, stagedDistroRulesVersion,
                 installedDistroStatus, installedDistroRulesVersion);
     }
@@ -213,7 +213,7 @@
 
     @Override
     public void writeToParcel(Parcel out, int flags) {
-        out.writeString(mSystemRulesVersion);
+        out.writeString(mBaseRulesVersion);
         out.writeParcelable(mDistroFormatVersionSupported, 0);
         out.writeByte(mOperationInProgress ? BYTE_TRUE : BYTE_FALSE);
         out.writeByte((byte) mStagedOperationType);
@@ -242,7 +242,7 @@
         if (mDistroStatus != that.mDistroStatus) {
             return false;
         }
-        if (!mSystemRulesVersion.equals(that.mSystemRulesVersion)) {
+        if (!mBaseRulesVersion.equals(that.mBaseRulesVersion)) {
             return false;
         }
         if (!mDistroFormatVersionSupported.equals(that.mDistroFormatVersionSupported)) {
@@ -259,7 +259,7 @@
 
     @Override
     public int hashCode() {
-        int result = mSystemRulesVersion.hashCode();
+        int result = mBaseRulesVersion.hashCode();
         result = 31 * result + mDistroFormatVersionSupported.hashCode();
         result = 31 * result + (mOperationInProgress ? 1 : 0);
         result = 31 * result + mStagedOperationType;
@@ -275,7 +275,7 @@
     @Override
     public String toString() {
         return "RulesState{"
-                + "mSystemRulesVersion='" + mSystemRulesVersion + '\''
+                + "mBaseRulesVersion='" + mBaseRulesVersion + '\''
                 + ", mDistroFormatVersionSupported=" + mDistroFormatVersionSupported
                 + ", mOperationInProgress=" + mOperationInProgress
                 + ", mStagedOperationType=" + mStagedOperationType
diff --git a/core/java/android/app/usage/AppStandbyInfo.java b/core/java/android/app/usage/AppStandbyInfo.java
index 51fe0e2..ebdbf83 100644
--- a/core/java/android/app/usage/AppStandbyInfo.java
+++ b/core/java/android/app/usage/AppStandbyInfo.java
@@ -50,7 +50,7 @@
         dest.writeInt(mStandbyBucket);
     }
 
-    public static final Creator<AppStandbyInfo> CREATOR = new Creator<AppStandbyInfo>() {
+    public static final @android.annotation.NonNull Creator<AppStandbyInfo> CREATOR = new Creator<AppStandbyInfo>() {
         @Override
         public AppStandbyInfo createFromParcel(Parcel source) {
             return new AppStandbyInfo(source);
diff --git a/core/java/android/app/usage/CacheQuotaHint.java b/core/java/android/app/usage/CacheQuotaHint.java
index 1d5c2b0..b92d538 100644
--- a/core/java/android/app/usage/CacheQuotaHint.java
+++ b/core/java/android/app/usage/CacheQuotaHint.java
@@ -140,7 +140,7 @@
         }
     }
 
-    public static final Parcelable.Creator<CacheQuotaHint> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CacheQuotaHint> CREATOR =
             new Creator<CacheQuotaHint>() {
                 @Override
                 public CacheQuotaHint createFromParcel(Parcel in) {
diff --git a/core/java/android/app/usage/ConfigurationStats.java b/core/java/android/app/usage/ConfigurationStats.java
index 87a737d..da3b769 100644
--- a/core/java/android/app/usage/ConfigurationStats.java
+++ b/core/java/android/app/usage/ConfigurationStats.java
@@ -146,7 +146,7 @@
         dest.writeInt(mActivationCount);
     }
 
-    public static final Creator<ConfigurationStats> CREATOR = new Creator<ConfigurationStats>() {
+    public static final @android.annotation.NonNull Creator<ConfigurationStats> CREATOR = new Creator<ConfigurationStats>() {
         @Override
         public ConfigurationStats createFromParcel(Parcel source) {
             ConfigurationStats stats = new ConfigurationStats();
diff --git a/core/java/android/app/usage/EventStats.java b/core/java/android/app/usage/EventStats.java
index ea95a05..7ada092 100644
--- a/core/java/android/app/usage/EventStats.java
+++ b/core/java/android/app/usage/EventStats.java
@@ -160,7 +160,7 @@
         dest.writeInt(mCount);
     }
 
-    public static final Creator<EventStats> CREATOR = new Creator<EventStats>() {
+    public static final @android.annotation.NonNull Creator<EventStats> CREATOR = new Creator<EventStats>() {
         @Override
         public EventStats createFromParcel(Parcel in) {
             EventStats stats = new EventStats();
diff --git a/core/java/android/app/usage/ExternalStorageStats.java b/core/java/android/app/usage/ExternalStorageStats.java
index f00e5c2..3a51207 100644
--- a/core/java/android/app/usage/ExternalStorageStats.java
+++ b/core/java/android/app/usage/ExternalStorageStats.java
@@ -131,7 +131,7 @@
         dest.writeLong(obbBytes);
     }
 
-    public static final Creator<ExternalStorageStats> CREATOR = new Creator<ExternalStorageStats>() {
+    public static final @android.annotation.NonNull Creator<ExternalStorageStats> CREATOR = new Creator<ExternalStorageStats>() {
         @Override
         public ExternalStorageStats createFromParcel(Parcel in) {
             return new ExternalStorageStats(in);
diff --git a/core/java/android/app/usage/StorageStats.java b/core/java/android/app/usage/StorageStats.java
index 3a27751..a2ff159 100644
--- a/core/java/android/app/usage/StorageStats.java
+++ b/core/java/android/app/usage/StorageStats.java
@@ -106,7 +106,7 @@
         dest.writeLong(cacheBytes);
     }
 
-    public static final Creator<StorageStats> CREATOR = new Creator<StorageStats>() {
+    public static final @android.annotation.NonNull Creator<StorageStats> CREATOR = new Creator<StorageStats>() {
         @Override
         public StorageStats createFromParcel(Parcel in) {
             return new StorageStats(in);
diff --git a/core/java/android/app/usage/UsageEvents.java b/core/java/android/app/usage/UsageEvents.java
index fafea34..0d0e466 100644
--- a/core/java/android/app/usage/UsageEvents.java
+++ b/core/java/android/app/usage/UsageEvents.java
@@ -880,7 +880,7 @@
         dest.writeBlob(data.marshall());
     }
 
-    public static final Creator<UsageEvents> CREATOR = new Creator<UsageEvents>() {
+    public static final @android.annotation.NonNull Creator<UsageEvents> CREATOR = new Creator<UsageEvents>() {
         @Override
         public UsageEvents createFromParcel(Parcel source) {
             return new UsageEvents(source);
diff --git a/core/java/android/app/usage/UsageStats.java b/core/java/android/app/usage/UsageStats.java
index 97efa01..2c021cc 100644
--- a/core/java/android/app/usage/UsageStats.java
+++ b/core/java/android/app/usage/UsageStats.java
@@ -636,7 +636,7 @@
         return bundle;
     }
 
-    public static final Creator<UsageStats> CREATOR = new Creator<UsageStats>() {
+    public static final @android.annotation.NonNull Creator<UsageStats> CREATOR = new Creator<UsageStats>() {
         @Override
         public UsageStats createFromParcel(Parcel in) {
             UsageStats stats = new UsageStats();
diff --git a/core/java/android/app/usage/UsageStatsManager.java b/core/java/android/app/usage/UsageStatsManager.java
index dc5bdc6..d34e6d3 100644
--- a/core/java/android/app/usage/UsageStatsManager.java
+++ b/core/java/android/app/usage/UsageStatsManager.java
@@ -195,6 +195,8 @@
     /** @hide */
     public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_START = 0x000D;
     /** @hide */
+    public static final int REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED = 0x000E;
+    /** @hide */
     public static final int REASON_SUB_PREDICTED_RESTORED       = 0x0001;
 
 
@@ -779,7 +781,7 @@
             android.Manifest.permission.SUSPEND_APPS,
             android.Manifest.permission.OBSERVE_APP_USAGE})
     public void registerAppUsageLimitObserver(int observerId, @NonNull String[] observedEntities,
-            long timeLimit, @NonNull TimeUnit timeUnit, PendingIntent callbackIntent) {
+            long timeLimit, @NonNull TimeUnit timeUnit, @Nullable PendingIntent callbackIntent) {
         try {
             mService.registerAppUsageLimitObserver(observerId, observedEntities,
                     timeUnit.toMillis(timeLimit), callbackIntent, mContext.getOpPackageName());
@@ -972,6 +974,9 @@
                     case REASON_SUB_USAGE_EXEMPTED_SYNC_START:
                         sb.append("-es");
                         break;
+                    case REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED:
+                        sb.append("-uss");
+                        break;
                 }
                 break;
         }
diff --git a/core/java/android/app/usage/UsageStatsManagerInternal.java b/core/java/android/app/usage/UsageStatsManagerInternal.java
index 43ce521..bbec6b3 100644
--- a/core/java/android/app/usage/UsageStatsManagerInternal.java
+++ b/core/java/android/app/usage/UsageStatsManagerInternal.java
@@ -257,12 +257,14 @@
             int numDeferredJobs, long timeSinceLastJobRun);
 
     /**
-     * Report a sync is scheduled by a foreground app.
+     * Report a sync that was scheduled.
      *
      * @param packageName name of the package that owns the sync adapter.
      * @param userId which user the app is associated with
+     * @param exempted is sync app standby exempted
      */
-    public abstract void reportExemptedSyncScheduled(String packageName, @UserIdInt int userId);
+    public abstract void reportSyncScheduled(String packageName, @UserIdInt int userId,
+                                             boolean exempted);
 
     /**
      * Report a sync that was scheduled by a foreground app is about to be executed.
diff --git a/core/java/android/appwidget/AppWidgetProviderInfo.java b/core/java/android/appwidget/AppWidgetProviderInfo.java
index d148afb..2faa900 100644
--- a/core/java/android/appwidget/AppWidgetProviderInfo.java
+++ b/core/java/android/appwidget/AppWidgetProviderInfo.java
@@ -446,7 +446,7 @@
     /**
      * Parcelable.Creator that instantiates AppWidgetProviderInfo objects
      */
-    public static final Parcelable.Creator<AppWidgetProviderInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AppWidgetProviderInfo> CREATOR
             = new Parcelable.Creator<AppWidgetProviderInfo>()
     {
         public AppWidgetProviderInfo createFromParcel(Parcel parcel)
diff --git a/core/java/android/appwidget/PendingHostUpdate.java b/core/java/android/appwidget/PendingHostUpdate.java
index 5780319..e1bf159 100644
--- a/core/java/android/appwidget/PendingHostUpdate.java
+++ b/core/java/android/appwidget/PendingHostUpdate.java
@@ -112,7 +112,7 @@
     /**
      * Parcelable.Creator that instantiates PendingHostUpdate objects
      */
-    public static final Parcelable.Creator<PendingHostUpdate> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<PendingHostUpdate> CREATOR
             = new Parcelable.Creator<PendingHostUpdate>() {
         public PendingHostUpdate createFromParcel(Parcel parcel) {
             return new PendingHostUpdate(parcel);
diff --git a/core/java/android/bluetooth/BluetoothActivityEnergyInfo.java b/core/java/android/bluetooth/BluetoothActivityEnergyInfo.java
index 43b79db..df065bf 100644
--- a/core/java/android/bluetooth/BluetoothActivityEnergyInfo.java
+++ b/core/java/android/bluetooth/BluetoothActivityEnergyInfo.java
@@ -76,7 +76,7 @@
                 + " }";
     }
 
-    public static final Parcelable.Creator<BluetoothActivityEnergyInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothActivityEnergyInfo> CREATOR =
             new Parcelable.Creator<BluetoothActivityEnergyInfo>() {
                 public BluetoothActivityEnergyInfo createFromParcel(Parcel in) {
                     return new BluetoothActivityEnergyInfo(in);
diff --git a/core/java/android/bluetooth/BluetoothAudioConfig.java b/core/java/android/bluetooth/BluetoothAudioConfig.java
index a441056..9591a70 100644
--- a/core/java/android/bluetooth/BluetoothAudioConfig.java
+++ b/core/java/android/bluetooth/BluetoothAudioConfig.java
@@ -64,7 +64,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<BluetoothAudioConfig> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothAudioConfig> CREATOR =
             new Parcelable.Creator<BluetoothAudioConfig>() {
                 public BluetoothAudioConfig createFromParcel(Parcel in) {
                     int sampleRate = in.readInt();
diff --git a/core/java/android/bluetooth/BluetoothAvrcpPlayerSettings.java b/core/java/android/bluetooth/BluetoothAvrcpPlayerSettings.java
index 3d3d80e..30aea1a 100644
--- a/core/java/android/bluetooth/BluetoothAvrcpPlayerSettings.java
+++ b/core/java/android/bluetooth/BluetoothAvrcpPlayerSettings.java
@@ -118,7 +118,7 @@
         }
     }
 
-    public static final Parcelable.Creator<BluetoothAvrcpPlayerSettings> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothAvrcpPlayerSettings> CREATOR =
             new Parcelable.Creator<BluetoothAvrcpPlayerSettings>() {
         public BluetoothAvrcpPlayerSettings createFromParcel(Parcel in) {
             return new BluetoothAvrcpPlayerSettings(in);
diff --git a/core/java/android/bluetooth/BluetoothClass.java b/core/java/android/bluetooth/BluetoothClass.java
index 1edbacb..260e2fb 100755
--- a/core/java/android/bluetooth/BluetoothClass.java
+++ b/core/java/android/bluetooth/BluetoothClass.java
@@ -94,7 +94,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<BluetoothClass> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothClass> CREATOR =
             new Parcelable.Creator<BluetoothClass>() {
                 public BluetoothClass createFromParcel(Parcel in) {
                     return new BluetoothClass(in.readInt());
diff --git a/core/java/android/bluetooth/BluetoothCodecConfig.java b/core/java/android/bluetooth/BluetoothCodecConfig.java
index c9d0ef2..591c418 100644
--- a/core/java/android/bluetooth/BluetoothCodecConfig.java
+++ b/core/java/android/bluetooth/BluetoothCodecConfig.java
@@ -247,7 +247,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<BluetoothCodecConfig> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothCodecConfig> CREATOR =
             new Parcelable.Creator<BluetoothCodecConfig>() {
                 public BluetoothCodecConfig createFromParcel(Parcel in) {
                     final int codecType = in.readInt();
diff --git a/core/java/android/bluetooth/BluetoothCodecStatus.java b/core/java/android/bluetooth/BluetoothCodecStatus.java
index 2cb7b2d..8eae2b4 100644
--- a/core/java/android/bluetooth/BluetoothCodecStatus.java
+++ b/core/java/android/bluetooth/BluetoothCodecStatus.java
@@ -108,7 +108,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<BluetoothCodecStatus> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothCodecStatus> CREATOR =
             new Parcelable.Creator<BluetoothCodecStatus>() {
                 public BluetoothCodecStatus createFromParcel(Parcel in) {
                     final BluetoothCodecConfig codecConfig = in.readTypedObject(
diff --git a/core/java/android/bluetooth/BluetoothDevice.java b/core/java/android/bluetooth/BluetoothDevice.java
index 4d8dc35..f718415 100644
--- a/core/java/android/bluetooth/BluetoothDevice.java
+++ b/core/java/android/bluetooth/BluetoothDevice.java
@@ -959,7 +959,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<BluetoothDevice> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothDevice> CREATOR =
             new Parcelable.Creator<BluetoothDevice>() {
                 public BluetoothDevice createFromParcel(Parcel in) {
                     return new BluetoothDevice(in.readString());
diff --git a/core/java/android/bluetooth/BluetoothGattCharacteristic.java b/core/java/android/bluetooth/BluetoothGattCharacteristic.java
index 6d46b3a..edacf3e 100644
--- a/core/java/android/bluetooth/BluetoothGattCharacteristic.java
+++ b/core/java/android/bluetooth/BluetoothGattCharacteristic.java
@@ -302,7 +302,7 @@
         out.writeTypedList(mDescriptors);
     }
 
-    public static final Parcelable.Creator<BluetoothGattCharacteristic> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothGattCharacteristic> CREATOR =
             new Parcelable.Creator<BluetoothGattCharacteristic>() {
         public BluetoothGattCharacteristic createFromParcel(Parcel in) {
             return new BluetoothGattCharacteristic(in);
diff --git a/core/java/android/bluetooth/BluetoothGattDescriptor.java b/core/java/android/bluetooth/BluetoothGattDescriptor.java
index 3ffbb9e..0783cd2 100644
--- a/core/java/android/bluetooth/BluetoothGattDescriptor.java
+++ b/core/java/android/bluetooth/BluetoothGattDescriptor.java
@@ -177,7 +177,7 @@
         out.writeInt(mPermissions);
     }
 
-    public static final Parcelable.Creator<BluetoothGattDescriptor> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothGattDescriptor> CREATOR =
             new Parcelable.Creator<BluetoothGattDescriptor>() {
         public BluetoothGattDescriptor createFromParcel(Parcel in) {
             return new BluetoothGattDescriptor(in);
diff --git a/core/java/android/bluetooth/BluetoothGattIncludedService.java b/core/java/android/bluetooth/BluetoothGattIncludedService.java
index bccf20e..5580619 100644
--- a/core/java/android/bluetooth/BluetoothGattIncludedService.java
+++ b/core/java/android/bluetooth/BluetoothGattIncludedService.java
@@ -64,7 +64,7 @@
         out.writeInt(mServiceType);
     }
 
-    public static final Parcelable.Creator<BluetoothGattIncludedService> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothGattIncludedService> CREATOR =
             new Parcelable.Creator<BluetoothGattIncludedService>() {
         public BluetoothGattIncludedService createFromParcel(Parcel in) {
             return new BluetoothGattIncludedService(in);
diff --git a/core/java/android/bluetooth/BluetoothGattService.java b/core/java/android/bluetooth/BluetoothGattService.java
index 8e740ee..c20faf9 100644
--- a/core/java/android/bluetooth/BluetoothGattService.java
+++ b/core/java/android/bluetooth/BluetoothGattService.java
@@ -165,7 +165,7 @@
         out.writeTypedList(includedServices);
     }
 
-    public static final Parcelable.Creator<BluetoothGattService> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothGattService> CREATOR =
             new Parcelable.Creator<BluetoothGattService>() {
         public BluetoothGattService createFromParcel(Parcel in) {
             return new BluetoothGattService(in);
diff --git a/core/java/android/bluetooth/BluetoothHeadsetClientCall.java b/core/java/android/bluetooth/BluetoothHeadsetClientCall.java
index e02a2f4..7165dd5 100644
--- a/core/java/android/bluetooth/BluetoothHeadsetClientCall.java
+++ b/core/java/android/bluetooth/BluetoothHeadsetClientCall.java
@@ -280,7 +280,7 @@
     /**
      * {@link Parcelable.Creator} interface implementation.
      */
-    public static final Parcelable.Creator<BluetoothHeadsetClientCall> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothHeadsetClientCall> CREATOR =
             new Parcelable.Creator<BluetoothHeadsetClientCall>() {
                 @Override
                 public BluetoothHeadsetClientCall createFromParcel(Parcel in) {
diff --git a/core/java/android/bluetooth/BluetoothHealthAppConfiguration.java b/core/java/android/bluetooth/BluetoothHealthAppConfiguration.java
index 9788bbf..88e06e5 100644
--- a/core/java/android/bluetooth/BluetoothHealthAppConfiguration.java
+++ b/core/java/android/bluetooth/BluetoothHealthAppConfiguration.java
@@ -90,7 +90,7 @@
      * {@link BluetoothDevice#createL2capChannel(int)}
      */
     @Deprecated
-    public static final Parcelable.Creator<BluetoothHealthAppConfiguration> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothHealthAppConfiguration> CREATOR =
             new Parcelable.Creator<BluetoothHealthAppConfiguration>() {
                 @Override
                 public BluetoothHealthAppConfiguration createFromParcel(Parcel in) {
diff --git a/core/java/android/bluetooth/BluetoothHidDeviceAppQosSettings.java b/core/java/android/bluetooth/BluetoothHidDeviceAppQosSettings.java
index a485b89..b21ebe5 100644
--- a/core/java/android/bluetooth/BluetoothHidDeviceAppQosSettings.java
+++ b/core/java/android/bluetooth/BluetoothHidDeviceAppQosSettings.java
@@ -98,7 +98,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<BluetoothHidDeviceAppQosSettings> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothHidDeviceAppQosSettings> CREATOR =
             new Parcelable.Creator<BluetoothHidDeviceAppQosSettings>() {
 
                 @Override
diff --git a/core/java/android/bluetooth/BluetoothHidDeviceAppSdpSettings.java b/core/java/android/bluetooth/BluetoothHidDeviceAppSdpSettings.java
index 2f0b44f..4e1a2aa 100644
--- a/core/java/android/bluetooth/BluetoothHidDeviceAppSdpSettings.java
+++ b/core/java/android/bluetooth/BluetoothHidDeviceAppSdpSettings.java
@@ -92,7 +92,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<BluetoothHidDeviceAppSdpSettings> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothHidDeviceAppSdpSettings> CREATOR =
             new Parcelable.Creator<BluetoothHidDeviceAppSdpSettings>() {
 
                 @Override
diff --git a/core/java/android/bluetooth/BluetoothMasInstance.java b/core/java/android/bluetooth/BluetoothMasInstance.java
index 7a31328..b64d049 100644
--- a/core/java/android/bluetooth/BluetoothMasInstance.java
+++ b/core/java/android/bluetooth/BluetoothMasInstance.java
@@ -57,7 +57,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<BluetoothMasInstance> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BluetoothMasInstance> CREATOR =
             new Parcelable.Creator<BluetoothMasInstance>() {
                 public BluetoothMasInstance createFromParcel(Parcel in) {
                     return new BluetoothMasInstance(in.readInt(), in.readString(),
diff --git a/core/java/android/bluetooth/OobData.java b/core/java/android/bluetooth/OobData.java
index d632572..0d0c6ab 100644
--- a/core/java/android/bluetooth/OobData.java
+++ b/core/java/android/bluetooth/OobData.java
@@ -98,7 +98,7 @@
         out.writeByteArray(mLeSecureConnectionsRandom);
     }
 
-    public static final Parcelable.Creator<OobData> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<OobData> CREATOR =
             new Parcelable.Creator<OobData>() {
         public OobData createFromParcel(Parcel in) {
             return new OobData(in);
diff --git a/core/java/android/bluetooth/UidTraffic.java b/core/java/android/bluetooth/UidTraffic.java
index cef362b..2ee786a 100644
--- a/core/java/android/bluetooth/UidTraffic.java
+++ b/core/java/android/bluetooth/UidTraffic.java
@@ -95,7 +95,7 @@
                 + mTxBytes + '}';
     }
 
-    public static final Creator<UidTraffic> CREATOR = new Creator<UidTraffic>() {
+    public static final @android.annotation.NonNull Creator<UidTraffic> CREATOR = new Creator<UidTraffic>() {
         @Override
         public UidTraffic createFromParcel(Parcel source) {
             return new UidTraffic(source);
diff --git a/core/java/android/bluetooth/le/AdvertiseData.java b/core/java/android/bluetooth/le/AdvertiseData.java
index b65c31d1d..5fd8258 100644
--- a/core/java/android/bluetooth/le/AdvertiseData.java
+++ b/core/java/android/bluetooth/le/AdvertiseData.java
@@ -159,7 +159,7 @@
         dest.writeByte((byte) (getIncludeDeviceName() ? 1 : 0));
     }
 
-    public static final Parcelable.Creator<AdvertiseData> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AdvertiseData> CREATOR =
             new Creator<AdvertiseData>() {
                 @Override
                 public AdvertiseData[] newArray(int size) {
diff --git a/core/java/android/bluetooth/le/AdvertiseSettings.java b/core/java/android/bluetooth/le/AdvertiseSettings.java
index 35e232c7..7129d76 100644
--- a/core/java/android/bluetooth/le/AdvertiseSettings.java
+++ b/core/java/android/bluetooth/le/AdvertiseSettings.java
@@ -139,7 +139,7 @@
         dest.writeInt(mAdvertiseTimeoutMillis);
     }
 
-    public static final Parcelable.Creator<AdvertiseSettings> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AdvertiseSettings> CREATOR =
             new Creator<AdvertiseSettings>() {
                 @Override
                 public AdvertiseSettings[] newArray(int size) {
diff --git a/core/java/android/bluetooth/le/AdvertisingSetParameters.java b/core/java/android/bluetooth/le/AdvertisingSetParameters.java
index 0c0291eb..e39b198 100644
--- a/core/java/android/bluetooth/le/AdvertisingSetParameters.java
+++ b/core/java/android/bluetooth/le/AdvertisingSetParameters.java
@@ -227,7 +227,7 @@
         dest.writeInt(mTxPowerLevel);
     }
 
-    public static final Parcelable.Creator<AdvertisingSetParameters> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AdvertisingSetParameters> CREATOR =
             new Creator<AdvertisingSetParameters>() {
                 @Override
                 public AdvertisingSetParameters[] newArray(int size) {
diff --git a/core/java/android/bluetooth/le/PeriodicAdvertisingReport.java b/core/java/android/bluetooth/le/PeriodicAdvertisingReport.java
index 73a2e74..7a8c2c6 100644
--- a/core/java/android/bluetooth/le/PeriodicAdvertisingReport.java
+++ b/core/java/android/bluetooth/le/PeriodicAdvertisingReport.java
@@ -171,7 +171,7 @@
                 + ", data=" + Objects.toString(mData) + ", timestampNanos=" + mTimestampNanos + '}';
     }
 
-    public static final Parcelable.Creator<PeriodicAdvertisingReport> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PeriodicAdvertisingReport> CREATOR =
             new Creator<PeriodicAdvertisingReport>() {
                 @Override
                 public PeriodicAdvertisingReport createFromParcel(Parcel source) {
diff --git a/core/java/android/bluetooth/le/ResultStorageDescriptor.java b/core/java/android/bluetooth/le/ResultStorageDescriptor.java
index 63bdf69..796c815 100644
--- a/core/java/android/bluetooth/le/ResultStorageDescriptor.java
+++ b/core/java/android/bluetooth/le/ResultStorageDescriptor.java
@@ -78,7 +78,7 @@
         mLength = in.readInt();
     }
 
-    public static final Parcelable.Creator<ResultStorageDescriptor> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ResultStorageDescriptor> CREATOR =
             new Creator<ResultStorageDescriptor>() {
         @Override
         public ResultStorageDescriptor createFromParcel(Parcel source) {
diff --git a/core/java/android/bluetooth/le/ScanFilter.java b/core/java/android/bluetooth/le/ScanFilter.java
index c5d435b..78140cf 100644
--- a/core/java/android/bluetooth/le/ScanFilter.java
+++ b/core/java/android/bluetooth/le/ScanFilter.java
@@ -161,7 +161,7 @@
     /**
      * A {@link android.os.Parcelable.Creator} to create {@link ScanFilter} from parcel.
      */
-    public static final Creator<ScanFilter> CREATOR =
+    public static final @android.annotation.NonNull Creator<ScanFilter> CREATOR =
             new Creator<ScanFilter>() {
 
         @Override
diff --git a/core/java/android/bluetooth/le/ScanResult.java b/core/java/android/bluetooth/le/ScanResult.java
index f87a47f..855d345 100644
--- a/core/java/android/bluetooth/le/ScanResult.java
+++ b/core/java/android/bluetooth/le/ScanResult.java
@@ -338,7 +338,7 @@
                 + ", periodicAdvertisingInterval=" + mPeriodicAdvertisingInterval + '}';
     }
 
-    public static final Parcelable.Creator<ScanResult> CREATOR = new Creator<ScanResult>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<ScanResult> CREATOR = new Creator<ScanResult>() {
         @Override
         public ScanResult createFromParcel(Parcel source) {
             return new ScanResult(source);
diff --git a/core/java/android/bluetooth/le/ScanSettings.java b/core/java/android/bluetooth/le/ScanSettings.java
index 8fdcba8..504118e 100644
--- a/core/java/android/bluetooth/le/ScanSettings.java
+++ b/core/java/android/bluetooth/le/ScanSettings.java
@@ -242,7 +242,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<ScanSettings> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ScanSettings> CREATOR =
             new Creator<ScanSettings>() {
         @Override
         public ScanSettings[] newArray(int size) {
diff --git a/core/java/android/companion/AssociationRequest.java b/core/java/android/companion/AssociationRequest.java
index db54f08..e4114c6 100644
--- a/core/java/android/companion/AssociationRequest.java
+++ b/core/java/android/companion/AssociationRequest.java
@@ -105,7 +105,7 @@
         return 0;
     }
 
-    public static final Creator<AssociationRequest> CREATOR = new Creator<AssociationRequest>() {
+    public static final @android.annotation.NonNull Creator<AssociationRequest> CREATOR = new Creator<AssociationRequest>() {
         @Override
         public AssociationRequest createFromParcel(Parcel in) {
             return new AssociationRequest(in);
diff --git a/core/java/android/companion/BluetoothDeviceFilter.java b/core/java/android/companion/BluetoothDeviceFilter.java
index 7507e17..fe0123c 100644
--- a/core/java/android/companion/BluetoothDeviceFilter.java
+++ b/core/java/android/companion/BluetoothDeviceFilter.java
@@ -146,7 +146,7 @@
         return 0;
     }
 
-    public static final Creator<BluetoothDeviceFilter> CREATOR
+    public static final @android.annotation.NonNull Creator<BluetoothDeviceFilter> CREATOR
             = new Creator<BluetoothDeviceFilter>() {
         @Override
         public BluetoothDeviceFilter createFromParcel(Parcel in) {
diff --git a/core/java/android/companion/BluetoothLeDeviceFilter.java b/core/java/android/companion/BluetoothLeDeviceFilter.java
index 1de931e..37c9cb6 100644
--- a/core/java/android/companion/BluetoothLeDeviceFilter.java
+++ b/core/java/android/companion/BluetoothLeDeviceFilter.java
@@ -247,7 +247,7 @@
                 '}';
     }
 
-    public static final Creator<BluetoothLeDeviceFilter> CREATOR
+    public static final @android.annotation.NonNull Creator<BluetoothLeDeviceFilter> CREATOR
             = new Creator<BluetoothLeDeviceFilter>() {
         @Override
         public BluetoothLeDeviceFilter createFromParcel(Parcel in) {
diff --git a/core/java/android/companion/WifiDeviceFilter.java b/core/java/android/companion/WifiDeviceFilter.java
index b6e704c..62098d5 100644
--- a/core/java/android/companion/WifiDeviceFilter.java
+++ b/core/java/android/companion/WifiDeviceFilter.java
@@ -98,7 +98,7 @@
         return 0;
     }
 
-    public static final Creator<WifiDeviceFilter> CREATOR
+    public static final @android.annotation.NonNull Creator<WifiDeviceFilter> CREATOR
             = new Creator<WifiDeviceFilter>() {
         @Override
         public WifiDeviceFilter createFromParcel(Parcel in) {
diff --git a/core/java/android/content/AutofillOptions.java b/core/java/android/content/AutofillOptions.java
index fd7e52a..0d25f4d 100644
--- a/core/java/android/content/AutofillOptions.java
+++ b/core/java/android/content/AutofillOptions.java
@@ -110,7 +110,7 @@
         parcel.writeBoolean(augmentedEnabled);
     }
 
-    public static final Parcelable.Creator<AutofillOptions> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AutofillOptions> CREATOR =
             new Parcelable.Creator<AutofillOptions>() {
 
                 @Override
diff --git a/core/java/android/content/ClipData.java b/core/java/android/content/ClipData.java
index 8777b67..88e2c22 100644
--- a/core/java/android/content/ClipData.java
+++ b/core/java/android/content/ClipData.java
@@ -1176,7 +1176,7 @@
         }
     }
 
-    public static final Parcelable.Creator<ClipData> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ClipData> CREATOR =
         new Parcelable.Creator<ClipData>() {
 
             @Override
diff --git a/core/java/android/content/ClipDescription.java b/core/java/android/content/ClipDescription.java
index 19295fc..29acd5d 100644
--- a/core/java/android/content/ClipDescription.java
+++ b/core/java/android/content/ClipDescription.java
@@ -380,7 +380,7 @@
         mTimeStamp = in.readLong();
     }
 
-    public static final Parcelable.Creator<ClipDescription> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ClipDescription> CREATOR =
         new Parcelable.Creator<ClipDescription>() {
 
             public ClipDescription createFromParcel(Parcel source) {
diff --git a/core/java/android/content/ComponentName.java b/core/java/android/content/ComponentName.java
index e6ffe8b4..a5460e9 100644
--- a/core/java/android/content/ComponentName.java
+++ b/core/java/android/content/ComponentName.java
@@ -376,7 +376,7 @@
         return pkg != null ? new ComponentName(pkg, in) : null;
     }
 
-    public static final Parcelable.Creator<ComponentName> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ComponentName> CREATOR
             = new Parcelable.Creator<ComponentName>() {
         public ComponentName createFromParcel(Parcel in) {
             return new ComponentName(in);
diff --git a/core/java/android/content/ContentCaptureOptions.java b/core/java/android/content/ContentCaptureOptions.java
index 2fe9f14..6be0bea 100644
--- a/core/java/android/content/ContentCaptureOptions.java
+++ b/core/java/android/content/ContentCaptureOptions.java
@@ -149,7 +149,7 @@
         parcel.writeArraySet(whitelistedComponents);
     }
 
-    public static final Parcelable.Creator<ContentCaptureOptions> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ContentCaptureOptions> CREATOR =
             new Parcelable.Creator<ContentCaptureOptions>() {
 
                 @Override
diff --git a/core/java/android/content/ContentProvider.java b/core/java/android/content/ContentProvider.java
index e06322df..ddfe755 100644
--- a/core/java/android/content/ContentProvider.java
+++ b/core/java/android/content/ContentProvider.java
@@ -209,9 +209,10 @@
      * @hide
      */
     class Transport extends ContentProviderNative {
-        AppOpsManager mAppOpsManager = null;
-        int mReadOp = AppOpsManager.OP_NONE;
-        int mWriteOp = AppOpsManager.OP_NONE;
+        volatile AppOpsManager mAppOpsManager = null;
+        volatile int mReadOp = AppOpsManager.OP_NONE;
+        volatile int mWriteOp = AppOpsManager.OP_NONE;
+        volatile ContentInterface mInterface = ContentProvider.this;
 
         ContentProvider getContentProvider() {
             return ContentProvider.this;
@@ -245,9 +246,11 @@
                 Cursor cursor;
                 final String original = setCallingPackage(callingPkg);
                 try {
-                    cursor = ContentProvider.this.query(
+                    cursor = mInterface.query(
                             uri, projection, queryArgs,
                             CancellationSignal.fromTransport(cancellationSignal));
+                } catch (RemoteException e) {
+                    throw e.rethrowAsRuntimeException();
                 } finally {
                     setCallingPackage(original);
                 }
@@ -261,9 +264,11 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "query");
             final String original = setCallingPackage(callingPkg);
             try {
-                return ContentProvider.this.query(
+                return mInterface.query(
                         uri, projection, queryArgs,
                         CancellationSignal.fromTransport(cancellationSignal));
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 setCallingPackage(original);
                 Trace.traceEnd(TRACE_TAG_DATABASE);
@@ -277,7 +282,9 @@
             uri = maybeGetUriWithoutUserId(uri);
             Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
             try {
-                return ContentProvider.this.getType(uri);
+                return mInterface.getType(uri);
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 Trace.traceEnd(TRACE_TAG_DATABASE);
             }
@@ -299,7 +306,9 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
             final String original = setCallingPackage(callingPkg);
             try {
-                return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
+                return maybeAddUserId(mInterface.insert(uri, initialValues), userId);
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 setCallingPackage(original);
                 Trace.traceEnd(TRACE_TAG_DATABASE);
@@ -316,7 +325,9 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
             final String original = setCallingPackage(callingPkg);
             try {
-                return ContentProvider.this.bulkInsert(uri, initialValues);
+                return mInterface.bulkInsert(uri, initialValues);
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 setCallingPackage(original);
                 Trace.traceEnd(TRACE_TAG_DATABASE);
@@ -357,7 +368,7 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
             final String original = setCallingPackage(callingPkg);
             try {
-                ContentProviderResult[] results = ContentProvider.this.applyBatch(authority,
+                ContentProviderResult[] results = mInterface.applyBatch(authority,
                         operations);
                 if (results != null) {
                     for (int i = 0; i < results.length ; i++) {
@@ -368,6 +379,8 @@
                     }
                 }
                 return results;
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 setCallingPackage(original);
                 Trace.traceEnd(TRACE_TAG_DATABASE);
@@ -384,7 +397,9 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
             final String original = setCallingPackage(callingPkg);
             try {
-                return ContentProvider.this.delete(uri, selection, selectionArgs);
+                return mInterface.delete(uri, selection, selectionArgs);
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 setCallingPackage(original);
                 Trace.traceEnd(TRACE_TAG_DATABASE);
@@ -402,7 +417,9 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "update");
             final String original = setCallingPackage(callingPkg);
             try {
-                return ContentProvider.this.update(uri, values, selection, selectionArgs);
+                return mInterface.update(uri, values, selection, selectionArgs);
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 setCallingPackage(original);
                 Trace.traceEnd(TRACE_TAG_DATABASE);
@@ -419,8 +436,10 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
             final String original = setCallingPackage(callingPkg);
             try {
-                return ContentProvider.this.openFile(
+                return mInterface.openFile(
                         uri, mode, CancellationSignal.fromTransport(cancellationSignal));
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 setCallingPackage(original);
                 Trace.traceEnd(TRACE_TAG_DATABASE);
@@ -437,8 +456,10 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
             final String original = setCallingPackage(callingPkg);
             try {
-                return ContentProvider.this.openAssetFile(
+                return mInterface.openAssetFile(
                         uri, mode, CancellationSignal.fromTransport(cancellationSignal));
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 setCallingPackage(original);
                 Trace.traceEnd(TRACE_TAG_DATABASE);
@@ -453,7 +474,9 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "call");
             final String original = setCallingPackage(callingPkg);
             try {
-                return ContentProvider.this.call(authority, method, arg, extras);
+                return mInterface.call(authority, method, arg, extras);
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 setCallingPackage(original);
                 Trace.traceEnd(TRACE_TAG_DATABASE);
@@ -467,7 +490,9 @@
             uri = maybeGetUriWithoutUserId(uri);
             Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
             try {
-                return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
+                return mInterface.getStreamTypes(uri, mimeTypeFilter);
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 Trace.traceEnd(TRACE_TAG_DATABASE);
             }
@@ -483,8 +508,10 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
             final String original = setCallingPackage(callingPkg);
             try {
-                return ContentProvider.this.openTypedAssetFile(
+                return mInterface.openTypedAssetFile(
                         uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 setCallingPackage(original);
                 Trace.traceEnd(TRACE_TAG_DATABASE);
@@ -507,7 +534,9 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
             final String original = setCallingPackage(callingPkg);
             try {
-                return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
+                return maybeAddUserId(mInterface.canonicalize(uri), userId);
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 setCallingPackage(original);
                 Trace.traceEnd(TRACE_TAG_DATABASE);
@@ -525,7 +554,9 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
             final String original = setCallingPackage(callingPkg);
             try {
-                return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
+                return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
+            } catch (RemoteException e) {
+                throw e.rethrowAsRuntimeException();
             } finally {
                 setCallingPackage(original);
                 Trace.traceEnd(TRACE_TAG_DATABASE);
@@ -543,7 +574,7 @@
             Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
             final String original = setCallingPackage(callingPkg);
             try {
-                return ContentProvider.this.refresh(uri, args,
+                return mInterface.refresh(uri, args,
                         CancellationSignal.fromTransport(cancellationSignal));
             } finally {
                 setCallingPackage(original);
@@ -986,6 +1017,15 @@
         return mTransport.mAppOpsManager;
     }
 
+    /** @hide */
+    public final void setTransportLoggingEnabled(boolean enabled) {
+        if (enabled) {
+            mTransport.mInterface = new LoggingContentInterface(getClass().getSimpleName(), this);
+        } else {
+            mTransport.mInterface = this;
+        }
+    }
+
     /**
      * Implement this to initialize your content provider on startup.
      * This method is called for all registered content providers on the
diff --git a/core/java/android/content/ContentProviderOperation.java b/core/java/android/content/ContentProviderOperation.java
index 6a3fa6b2..a41b5d3 100644
--- a/core/java/android/content/ContentProviderOperation.java
+++ b/core/java/android/content/ContentProviderOperation.java
@@ -460,7 +460,7 @@
         return 0;
     }
 
-    public static final Creator<ContentProviderOperation> CREATOR =
+    public static final @android.annotation.NonNull Creator<ContentProviderOperation> CREATOR =
             new Creator<ContentProviderOperation>() {
         public ContentProviderOperation createFromParcel(Parcel source) {
             return new ContentProviderOperation(source);
diff --git a/core/java/android/content/ContentProviderResult.java b/core/java/android/content/ContentProviderResult.java
index 4196f27..d90173c 100644
--- a/core/java/android/content/ContentProviderResult.java
+++ b/core/java/android/content/ContentProviderResult.java
@@ -71,7 +71,7 @@
         return 0;
     }
 
-    public static final Creator<ContentProviderResult> CREATOR =
+    public static final @android.annotation.NonNull Creator<ContentProviderResult> CREATOR =
             new Creator<ContentProviderResult>() {
         public ContentProviderResult createFromParcel(Parcel source) {
             return new ContentProviderResult(source);
diff --git a/core/java/android/content/ContentValues.java b/core/java/android/content/ContentValues.java
index 06d0f66..eafeed2 100644
--- a/core/java/android/content/ContentValues.java
+++ b/core/java/android/content/ContentValues.java
@@ -497,7 +497,7 @@
         return mMap.keySet();
     }
 
-    public static final Parcelable.Creator<ContentValues> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ContentValues> CREATOR =
             new Parcelable.Creator<ContentValues>() {
         @Override
         public ContentValues createFromParcel(Parcel in) {
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index b67349f..d3b8e29 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -27,6 +27,7 @@
 import android.annotation.SdkConstant;
 import android.annotation.SdkConstant.SdkConstantType;
 import android.annotation.SystemApi;
+import android.annotation.TestApi;
 import android.annotation.UnsupportedAppUsage;
 import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
@@ -855,7 +856,7 @@
         /**
          * Used to read a ShortcutIconResource from a Parcel.
          */
-        public static final Parcelable.Creator<ShortcutIconResource> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<ShortcutIconResource> CREATOR =
             new Parcelable.Creator<ShortcutIconResource>() {
 
                 public ShortcutIconResource createFromParcel(Parcel source) {
@@ -1902,6 +1903,7 @@
      * @hide
      */
     @SystemApi
+    @TestApi
     public static final String EXTRA_ROLE_NAME = "android.intent.extra.ROLE_NAME";
 
     /**
@@ -10344,7 +10346,7 @@
         out.writeBundle(mExtras);
     }
 
-    public static final Parcelable.Creator<Intent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Intent> CREATOR
             = new Parcelable.Creator<Intent>() {
         public Intent createFromParcel(Parcel in) {
             return new Intent(in);
diff --git a/core/java/android/content/IntentFilter.java b/core/java/android/content/IntentFilter.java
index 36d8a37..9d52363 100644
--- a/core/java/android/content/IntentFilter.java
+++ b/core/java/android/content/IntentFilter.java
@@ -1896,7 +1896,7 @@
         }
     }
 
-    public static final Parcelable.Creator<IntentFilter> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<IntentFilter> CREATOR
             = new Parcelable.Creator<IntentFilter>() {
         public IntentFilter createFromParcel(Parcel source) {
             return new IntentFilter(source);
diff --git a/core/java/android/content/IntentSender.java b/core/java/android/content/IntentSender.java
index bfd1a43..ec0bac4 100644
--- a/core/java/android/content/IntentSender.java
+++ b/core/java/android/content/IntentSender.java
@@ -316,7 +316,7 @@
         out.writeStrongBinder(mTarget.asBinder());
     }
 
-    public static final Parcelable.Creator<IntentSender> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<IntentSender> CREATOR
             = new Parcelable.Creator<IntentSender>() {
         public IntentSender createFromParcel(Parcel in) {
             IBinder target = in.readStrongBinder();
diff --git a/core/java/android/content/LocusId.java b/core/java/android/content/LocusId.java
index 9548f9c..2142cf3 100644
--- a/core/java/android/content/LocusId.java
+++ b/core/java/android/content/LocusId.java
@@ -98,15 +98,17 @@
         dest.writeParcelable(mUri, flags);
     }
 
-    public static final Parcelable.Creator<LocusId> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<LocusId> CREATOR =
             new Parcelable.Creator<LocusId>() {
 
+        @NonNull
         @Override
         public LocusId createFromParcel(Parcel source) {
             final Uri uri = source.readParcelable(null);
             return new LocusId(uri);
         }
 
+        @NonNull
         @Override
         public LocusId[] newArray(int size) {
             return new LocusId[size];
diff --git a/core/java/android/content/LoggingContentInterface.java b/core/java/android/content/LoggingContentInterface.java
new file mode 100644
index 0000000..26d01b9
--- /dev/null
+++ b/core/java/android/content/LoggingContentInterface.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.content;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.res.AssetFileDescriptor;
+import android.database.Cursor;
+import android.database.DatabaseUtils;
+import android.net.Uri;
+import android.os.Binder;
+import android.os.Bundle;
+import android.os.CancellationSignal;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+import android.util.Log;
+
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+/**
+ * Instance of {@link ContentInterface} that logs all inputs and outputs while
+ * delegating to another {@link ContentInterface}.
+ *
+ * @hide
+ */
+public class LoggingContentInterface implements ContentInterface {
+    private final String tag;
+    private final ContentInterface delegate;
+
+    public LoggingContentInterface(String tag, ContentInterface delegate) {
+        this.tag = tag;
+        this.delegate = delegate;
+    }
+
+    private void log(String method, Object res, Object... args) {
+        // First, force-unparcel any bundles so we can log them
+        for (Object arg : args) {
+            if (arg instanceof Bundle) {
+                ((Bundle) arg).size();
+            }
+        }
+
+        final StringBuilder sb = new StringBuilder();
+        sb.append("callingUid=").append(Binder.getCallingUid()).append(' ');
+        sb.append(method);
+        sb.append('(').append(deepToString(args)).append(')');
+        if (res instanceof Cursor) {
+            sb.append('\n');
+            DatabaseUtils.dumpCursor((Cursor) res, sb);
+        } else {
+            sb.append(" = ").append(deepToString(res));
+        }
+        Log.v(tag, sb.toString());
+    }
+
+    private String deepToString(Object value) {
+        if (value != null && value.getClass().isArray()) {
+            return Arrays.deepToString((Object[]) value);
+        } else {
+            return String.valueOf(value);
+        }
+    }
+
+    @Override
+    public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
+            @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal)
+            throws RemoteException {
+        final Cursor res = delegate.query(uri, projection, queryArgs, cancellationSignal);
+        log("query", res, uri, projection, queryArgs, cancellationSignal);
+        return res;
+    }
+
+    @Override
+    public @Nullable String getType(@NonNull Uri uri) throws RemoteException {
+        final String res = delegate.getType(uri);
+        log("getType", res, uri);
+        return res;
+    }
+
+    @Override
+    public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter)
+            throws RemoteException {
+        final String[] res = delegate.getStreamTypes(uri, mimeTypeFilter);
+        log("getStreamTypes", res, uri, mimeTypeFilter);
+        return res;
+    }
+
+    @Override
+    public @Nullable Uri canonicalize(@NonNull Uri uri) throws RemoteException {
+        final Uri res = delegate.canonicalize(uri);
+        log("canonicalize", res, uri);
+        return res;
+    }
+
+    @Override
+    public @Nullable Uri uncanonicalize(@NonNull Uri uri) throws RemoteException {
+        final Uri res = delegate.uncanonicalize(uri);
+        log("uncanonicalize", res, uri);
+        return res;
+    }
+
+    @Override
+    public boolean refresh(@NonNull Uri uri, @Nullable Bundle args,
+            @Nullable CancellationSignal cancellationSignal) throws RemoteException {
+        final boolean res = delegate.refresh(uri, args, cancellationSignal);
+        log("refresh", res, uri, args, cancellationSignal);
+        return res;
+    }
+
+    @Override
+    public @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues initialValues)
+            throws RemoteException {
+        final Uri res = delegate.insert(uri, initialValues);
+        log("insert", res, uri, initialValues);
+        return res;
+    }
+
+    @Override
+    public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] initialValues)
+            throws RemoteException {
+        final int res = delegate.bulkInsert(uri, initialValues);
+        log("bulkInsert", res, uri, initialValues);
+        return res;
+    }
+
+    @Override
+    public int delete(@NonNull Uri uri, @Nullable String selection,
+            @Nullable String[] selectionArgs) throws RemoteException {
+        final int res = delegate.delete(uri, selection, selectionArgs);
+        log("delete", res, uri, selection, selectionArgs);
+        return res;
+    }
+
+    @Override
+    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection,
+            @Nullable String[] selectionArgs) throws RemoteException {
+        final int res = delegate.update(uri, values, selection, selectionArgs);
+        log("update", res, uri, values, selection, selectionArgs);
+        return res;
+    }
+
+    @Override
+    public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
+            @Nullable CancellationSignal signal) throws RemoteException, FileNotFoundException {
+        final ParcelFileDescriptor res = delegate.openFile(uri, mode, signal);
+        log("openFile", res, uri, mode, signal);
+        return res;
+    }
+
+    @Override
+    public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
+            @Nullable CancellationSignal signal) throws RemoteException, FileNotFoundException {
+        final AssetFileDescriptor res = delegate.openAssetFile(uri, mode, signal);
+        log("openAssetFile", res, uri, mode, signal);
+        return res;
+    }
+
+    @Override
+    public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
+            @NonNull String mimeTypeFilter, @Nullable Bundle opts,
+            @Nullable CancellationSignal signal) throws RemoteException, FileNotFoundException {
+        final AssetFileDescriptor res = delegate.openTypedAssetFile(uri, mimeTypeFilter, opts, signal);
+        log("openTypedAssetFile", res, uri, mimeTypeFilter, opts, signal);
+        return res;
+    }
+
+    @Override
+    public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
+            @NonNull ArrayList<ContentProviderOperation> operations)
+            throws RemoteException, OperationApplicationException {
+        final ContentProviderResult[] res = delegate.applyBatch(authority, operations);
+        log("applyBatch", res, authority, operations);
+        return res;
+    }
+
+    @Override
+    public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
+            @Nullable String arg, @Nullable Bundle extras) throws RemoteException {
+        final Bundle res = delegate.call(authority, method, arg, extras);
+        log("call", res, authority, method, arg, extras);
+        return res;
+    }
+}
diff --git a/core/java/android/content/PeriodicSync.java b/core/java/android/content/PeriodicSync.java
index 0441ccc..a075148 100644
--- a/core/java/android/content/PeriodicSync.java
+++ b/core/java/android/content/PeriodicSync.java
@@ -104,7 +104,7 @@
         dest.writeLong(flexTime);
     }
 
-    public static final Creator<PeriodicSync> CREATOR = new Creator<PeriodicSync>() {
+    public static final @android.annotation.NonNull Creator<PeriodicSync> CREATOR = new Creator<PeriodicSync>() {
         @Override
         public PeriodicSync createFromParcel(Parcel source) {
             return new PeriodicSync(source);
diff --git a/core/java/android/content/RestrictionEntry.java b/core/java/android/content/RestrictionEntry.java
index 0473475..010992c 100644
--- a/core/java/android/content/RestrictionEntry.java
+++ b/core/java/android/content/RestrictionEntry.java
@@ -531,7 +531,7 @@
         dest.writeParcelableArray(mRestrictions, 0);
     }
 
-    public static final Creator<RestrictionEntry> CREATOR = new Creator<RestrictionEntry>() {
+    public static final @android.annotation.NonNull Creator<RestrictionEntry> CREATOR = new Creator<RestrictionEntry>() {
         public RestrictionEntry createFromParcel(Parcel source) {
             return new RestrictionEntry(source);
         }
diff --git a/core/java/android/content/SyncAdapterType.java b/core/java/android/content/SyncAdapterType.java
index 6cd4841..8c8fe5a 100644
--- a/core/java/android/content/SyncAdapterType.java
+++ b/core/java/android/content/SyncAdapterType.java
@@ -241,7 +241,7 @@
                 source.readString());
     }
 
-    public static final Creator<SyncAdapterType> CREATOR = new Creator<SyncAdapterType>() {
+    public static final @android.annotation.NonNull Creator<SyncAdapterType> CREATOR = new Creator<SyncAdapterType>() {
         public SyncAdapterType createFromParcel(Parcel source) {
             return new SyncAdapterType(source);
         }
diff --git a/core/java/android/content/SyncInfo.java b/core/java/android/content/SyncInfo.java
index 403cbcb..d3f2eed 100644
--- a/core/java/android/content/SyncInfo.java
+++ b/core/java/android/content/SyncInfo.java
@@ -106,7 +106,7 @@
 
     /** @hide */
     @UnsupportedAppUsage
-    public static final Creator<SyncInfo> CREATOR = new Creator<SyncInfo>() {
+    public static final @android.annotation.NonNull Creator<SyncInfo> CREATOR = new Creator<SyncInfo>() {
         public SyncInfo createFromParcel(Parcel in) {
             return new SyncInfo(in);
         }
diff --git a/core/java/android/content/SyncRequest.java b/core/java/android/content/SyncRequest.java
index c18b282..5f1f180 100644
--- a/core/java/android/content/SyncRequest.java
+++ b/core/java/android/content/SyncRequest.java
@@ -122,7 +122,7 @@
         return mSyncRunTimeSecs;
     }
 
-    public static final Creator<SyncRequest> CREATOR = new Creator<SyncRequest>() {
+    public static final @android.annotation.NonNull Creator<SyncRequest> CREATOR = new Creator<SyncRequest>() {
 
         @Override
         public SyncRequest createFromParcel(Parcel in) {
diff --git a/core/java/android/content/SyncResult.java b/core/java/android/content/SyncResult.java
index f67d7f5..8280f8e 100644
--- a/core/java/android/content/SyncResult.java
+++ b/core/java/android/content/SyncResult.java
@@ -235,7 +235,7 @@
         stats.clear();
     }
 
-    public static final Creator<SyncResult> CREATOR = new Creator<SyncResult>() {
+    public static final @android.annotation.NonNull Creator<SyncResult> CREATOR = new Creator<SyncResult>() {
         public SyncResult createFromParcel(Parcel in) {
             return new SyncResult(in);
         }
diff --git a/core/java/android/content/SyncStats.java b/core/java/android/content/SyncStats.java
index b7f2a85..03b2250e 100644
--- a/core/java/android/content/SyncStats.java
+++ b/core/java/android/content/SyncStats.java
@@ -166,7 +166,7 @@
         dest.writeLong(numSkippedEntries);
     }
 
-    public static final Creator<SyncStats> CREATOR = new Creator<SyncStats>() {
+    public static final @android.annotation.NonNull Creator<SyncStats> CREATOR = new Creator<SyncStats>() {
         public SyncStats createFromParcel(Parcel in) {
             return new SyncStats(in);
         }
diff --git a/core/java/android/content/SyncStatusInfo.java b/core/java/android/content/SyncStatusInfo.java
index a9065ca..3f64515 100644
--- a/core/java/android/content/SyncStatusInfo.java
+++ b/core/java/android/content/SyncStatusInfo.java
@@ -401,7 +401,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Creator<SyncStatusInfo> CREATOR = new Creator<SyncStatusInfo>() {
+    public static final @android.annotation.NonNull Creator<SyncStatusInfo> CREATOR = new Creator<SyncStatusInfo>() {
         public SyncStatusInfo createFromParcel(Parcel in) {
             return new SyncStatusInfo(in);
         }
diff --git a/core/java/android/content/UriPermission.java b/core/java/android/content/UriPermission.java
index df9200d..d3a9cb8 100644
--- a/core/java/android/content/UriPermission.java
+++ b/core/java/android/content/UriPermission.java
@@ -103,7 +103,7 @@
         dest.writeLong(mPersistedTime);
     }
 
-    public static final Creator<UriPermission> CREATOR = new Creator<UriPermission>() {
+    public static final @android.annotation.NonNull Creator<UriPermission> CREATOR = new Creator<UriPermission>() {
         @Override
         public UriPermission createFromParcel(Parcel source) {
             return new UriPermission(source);
diff --git a/core/java/android/content/om/OverlayInfo.java b/core/java/android/content/om/OverlayInfo.java
index 1989f06..999d986 100644
--- a/core/java/android/content/om/OverlayInfo.java
+++ b/core/java/android/content/om/OverlayInfo.java
@@ -264,7 +264,7 @@
         dest.writeBoolean(isStatic);
     }
 
-    public static final Parcelable.Creator<OverlayInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<OverlayInfo> CREATOR =
             new Parcelable.Creator<OverlayInfo>() {
         @Override
         public OverlayInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/content/pm/ActivityInfo.java b/core/java/android/content/pm/ActivityInfo.java
index 7cc4391..415c242 100644
--- a/core/java/android/content/pm/ActivityInfo.java
+++ b/core/java/android/content/pm/ActivityInfo.java
@@ -1314,7 +1314,7 @@
         }
     }
 
-    public static final Parcelable.Creator<ActivityInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ActivityInfo> CREATOR
             = new Parcelable.Creator<ActivityInfo>() {
         public ActivityInfo createFromParcel(Parcel source) {
             return new ActivityInfo(source);
diff --git a/core/java/android/content/pm/AndroidTestBaseUpdater.java b/core/java/android/content/pm/AndroidTestBaseUpdater.java
index 2aaac02..6a1778c 100644
--- a/core/java/android/content/pm/AndroidTestBaseUpdater.java
+++ b/core/java/android/content/pm/AndroidTestBaseUpdater.java
@@ -19,11 +19,12 @@
 import static android.content.pm.SharedLibraryNames.ANDROID_TEST_RUNNER;
 
 import android.content.pm.PackageParser.Package;
+import android.os.Build;
 
 import com.android.internal.annotations.VisibleForTesting;
 
 /**
- * Updates a package to ensure that if it targets < P that the android.test.base library is
+ * Updates a package to ensure that if it targets <= P that the android.test.base library is
  * included by default.
  *
  * <p>This is separated out so that it can be conditionally included at build time depending on
@@ -37,12 +38,17 @@
 @VisibleForTesting
 public class AndroidTestBaseUpdater extends PackageSharedLibraryUpdater {
 
+    private static boolean apkTargetsApiLevelLessThanOrEqualToP(Package pkg) {
+        int targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
+        return targetSdkVersion <= Build.VERSION_CODES.P;
+    }
+
     @Override
     public void updatePackage(Package pkg) {
-        // Packages targeted at <= O_MR1 expect the classes in the android.test.base library
+        // Packages targeted at <= P expect the classes in the android.test.base library
         // to be accessible so this maintains backward compatibility by adding the
         // android.test.base library to those packages.
-        if (apkTargetsApiLevelLessThanOrEqualToOMR1(pkg)) {
+        if (apkTargetsApiLevelLessThanOrEqualToP(pkg)) {
             prefixRequiredLibrary(pkg, ANDROID_TEST_BASE);
         } else {
             // If a package already depends on android.test.runner then add a dependency on
diff --git a/core/java/android/content/pm/ApplicationInfo.java b/core/java/android/content/pm/ApplicationInfo.java
index 6c6fcb2..4f09d5a 100644
--- a/core/java/android/content/pm/ApplicationInfo.java
+++ b/core/java/android/content/pm/ApplicationInfo.java
@@ -662,6 +662,14 @@
      */
     public static final int PRIVATE_FLAG_ALLOW_CLEAR_USER_DATA_ON_FAILED_RESTORE = 1 << 26;
 
+    /**
+     * Value for {@link #privateFlags}: true if the application allows its audio playback
+     * to be captured by other apps.
+     *
+     * @hide
+     */
+    public static final int PRIVATE_FLAG_ALLOW_AUDIO_PLAYBACK_CAPTURE  = 1 << 27;
+
     /** @hide */
     @IntDef(flag = true, prefix = { "PRIVATE_FLAG_" }, value = {
             PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE,
@@ -688,7 +696,8 @@
             PRIVATE_FLAG_VENDOR,
             PRIVATE_FLAG_VIRTUAL_PRELOAD,
             PRIVATE_FLAG_HAS_FRAGILE_USER_DATA,
-            PRIVATE_FLAG_ALLOW_CLEAR_USER_DATA_ON_FAILED_RESTORE
+            PRIVATE_FLAG_ALLOW_CLEAR_USER_DATA_ON_FAILED_RESTORE,
+            PRIVATE_FLAG_ALLOW_AUDIO_PLAYBACK_CAPTURE
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface ApplicationInfoPrivateFlags {}
@@ -1342,6 +1351,8 @@
             }
             pw.println(prefix + "HiddenApiEnforcementPolicy=" + getHiddenApiEnforcementPolicy());
             pw.println(prefix + "usesNonSdkApi=" + usesNonSdkApi());
+            pw.println(prefix + "allowsPlaybackCapture="
+                        + (isAudioPlaybackCaptureAllowed() ? "true" : "false"));
         }
         super.dumpBack(pw, prefix);
     }
@@ -1625,7 +1636,7 @@
         dest.writeString(zygotePreloadName);
     }
 
-    public static final Parcelable.Creator<ApplicationInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ApplicationInfo> CREATOR
             = new Parcelable.Creator<ApplicationInfo>() {
         public ApplicationInfo createFromParcel(Parcel source) {
             return new ApplicationInfo(source);
@@ -1790,6 +1801,17 @@
         return (privateFlags & PRIVATE_FLAG_HAS_FRAGILE_USER_DATA) != 0;
     }
 
+    /**
+     * Whether an app allows its playback audio to be captured by other apps.
+     *
+     * @return {@code true} if the app indicates that its audio can be captured by other apps.
+     *
+     * @hide
+     */
+    public boolean isAudioPlaybackCaptureAllowed() {
+        return (privateFlags & PRIVATE_FLAG_ALLOW_AUDIO_PLAYBACK_CAPTURE) != 0;
+    }
+
     private boolean isAllowedToUseHiddenApis() {
         if (isSignedWithPlatformKey()) {
             return true;
diff --git a/core/java/android/content/pm/BaseParceledListSlice.java b/core/java/android/content/pm/BaseParceledListSlice.java
index a3e5d6d..4178309 100644
--- a/core/java/android/content/pm/BaseParceledListSlice.java
+++ b/core/java/android/content/pm/BaseParceledListSlice.java
@@ -128,8 +128,8 @@
     private static void verifySameType(final Class<?> expected, final Class<?> actual) {
         if (!actual.equals(expected)) {
             throw new IllegalArgumentException("Can't unparcel type "
-                    + actual.getName() + " in list of type "
-                    + expected.getName());
+                    + (actual == null ? null : actual.getName()) + " in list of type "
+                    + (expected == null ? null : expected.getName()));
         }
     }
 
diff --git a/core/java/android/content/pm/ChangedPackages.java b/core/java/android/content/pm/ChangedPackages.java
index b78c71d..950a29a 100644
--- a/core/java/android/content/pm/ChangedPackages.java
+++ b/core/java/android/content/pm/ChangedPackages.java
@@ -71,7 +71,7 @@
         return mPackageNames;
     }
 
-    public static final Parcelable.Creator<ChangedPackages> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ChangedPackages> CREATOR =
             new Parcelable.Creator<ChangedPackages>() {
         public ChangedPackages createFromParcel(Parcel in) {
             return new ChangedPackages(in);
diff --git a/core/java/android/content/pm/ConfigurationInfo.java b/core/java/android/content/pm/ConfigurationInfo.java
index 8edd436..20494e9 100644
--- a/core/java/android/content/pm/ConfigurationInfo.java
+++ b/core/java/android/content/pm/ConfigurationInfo.java
@@ -113,7 +113,7 @@
         dest.writeInt(reqGlEsVersion);
     }
 
-    public static final Creator<ConfigurationInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<ConfigurationInfo> CREATOR =
         new Creator<ConfigurationInfo>() {
         public ConfigurationInfo createFromParcel(Parcel source) {
             return new ConfigurationInfo(source);
diff --git a/core/java/android/content/pm/FeatureGroupInfo.java b/core/java/android/content/pm/FeatureGroupInfo.java
index 79a6eea..38c8f74 100644
--- a/core/java/android/content/pm/FeatureGroupInfo.java
+++ b/core/java/android/content/pm/FeatureGroupInfo.java
@@ -49,7 +49,7 @@
         dest.writeTypedArray(features, flags);
     }
 
-    public static final Creator<FeatureGroupInfo> CREATOR = new Creator<FeatureGroupInfo>() {
+    public static final @android.annotation.NonNull Creator<FeatureGroupInfo> CREATOR = new Creator<FeatureGroupInfo>() {
         @Override
         public FeatureGroupInfo createFromParcel(Parcel source) {
             FeatureGroupInfo group = new FeatureGroupInfo();
diff --git a/core/java/android/content/pm/FeatureInfo.java b/core/java/android/content/pm/FeatureInfo.java
index ff9fd8e..dc576e8 100644
--- a/core/java/android/content/pm/FeatureInfo.java
+++ b/core/java/android/content/pm/FeatureInfo.java
@@ -126,7 +126,7 @@
         proto.end(token);
     }
 
-    public static final Creator<FeatureInfo> CREATOR = new Creator<FeatureInfo>() {
+    public static final @android.annotation.NonNull Creator<FeatureInfo> CREATOR = new Creator<FeatureInfo>() {
         @Override
         public FeatureInfo createFromParcel(Parcel source) {
             return new FeatureInfo(source);
diff --git a/core/java/android/content/pm/InstantAppInfo.java b/core/java/android/content/pm/InstantAppInfo.java
index cb04fc3..24d6a07 100644
--- a/core/java/android/content/pm/InstantAppInfo.java
+++ b/core/java/android/content/pm/InstantAppInfo.java
@@ -136,7 +136,7 @@
         parcel.writeParcelable(mApplicationInfo, flags);
     }
 
-    public static final Creator<InstantAppInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<InstantAppInfo> CREATOR =
             new Creator<InstantAppInfo>() {
         @Override
         public InstantAppInfo createFromParcel(Parcel parcel) {
diff --git a/core/java/android/content/pm/InstantAppIntentFilter.java b/core/java/android/content/pm/InstantAppIntentFilter.java
index 257ab967..7c63406 100644
--- a/core/java/android/content/pm/InstantAppIntentFilter.java
+++ b/core/java/android/content/pm/InstantAppIntentFilter.java
@@ -68,7 +68,7 @@
         out.writeList(mFilters);
     }
 
-    public static final Parcelable.Creator<InstantAppIntentFilter> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<InstantAppIntentFilter> CREATOR
             = new Parcelable.Creator<InstantAppIntentFilter>() {
         @Override
         public InstantAppIntentFilter createFromParcel(Parcel in) {
diff --git a/core/java/android/content/pm/InstantAppResolveInfo.java b/core/java/android/content/pm/InstantAppResolveInfo.java
index 8184361..4c963a6 100644
--- a/core/java/android/content/pm/InstantAppResolveInfo.java
+++ b/core/java/android/content/pm/InstantAppResolveInfo.java
@@ -208,7 +208,7 @@
         out.writeLong(mVersionCode);
     }
 
-    public static final Parcelable.Creator<InstantAppResolveInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<InstantAppResolveInfo> CREATOR
             = new Parcelable.Creator<InstantAppResolveInfo>() {
         public InstantAppResolveInfo createFromParcel(Parcel in) {
             return new InstantAppResolveInfo(in);
@@ -383,7 +383,7 @@
         }
 
         @SuppressWarnings("hiding")
-        public static final Parcelable.Creator<InstantAppDigest> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<InstantAppDigest> CREATOR =
                 new Parcelable.Creator<InstantAppDigest>() {
             @Override
             public InstantAppDigest createFromParcel(Parcel in) {
diff --git a/core/java/android/content/pm/InstrumentationInfo.java b/core/java/android/content/pm/InstrumentationInfo.java
index fb2e4a04..574a1ee 100644
--- a/core/java/android/content/pm/InstrumentationInfo.java
+++ b/core/java/android/content/pm/InstrumentationInfo.java
@@ -176,7 +176,7 @@
         dest.writeInt((functionalTest == false) ? 0 : 1);
     }
 
-    public static final Parcelable.Creator<InstrumentationInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<InstrumentationInfo> CREATOR
             = new Parcelable.Creator<InstrumentationInfo>() {
         public InstrumentationInfo createFromParcel(Parcel source) {
             return new InstrumentationInfo(source);
diff --git a/core/java/android/content/pm/IntentFilterVerificationInfo.java b/core/java/android/content/pm/IntentFilterVerificationInfo.java
index 068973b..67bda2c 100644
--- a/core/java/android/content/pm/IntentFilterVerificationInfo.java
+++ b/core/java/android/content/pm/IntentFilterVerificationInfo.java
@@ -246,7 +246,7 @@
         dest.writeStringList(new ArrayList<>(mDomains));
     }
 
-    public static final Creator<IntentFilterVerificationInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<IntentFilterVerificationInfo> CREATOR =
             new Creator<IntentFilterVerificationInfo>() {
                 public IntentFilterVerificationInfo createFromParcel(Parcel source) {
                     return new IntentFilterVerificationInfo(source);
diff --git a/core/java/android/content/pm/KeySet.java b/core/java/android/content/pm/KeySet.java
index 643db7e..5c1d35e 100644
--- a/core/java/android/content/pm/KeySet.java
+++ b/core/java/android/content/pm/KeySet.java
@@ -63,7 +63,7 @@
      * Implement Parcelable
      * @hide
      */
-    public static final Parcelable.Creator<KeySet> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<KeySet> CREATOR
             = new Parcelable.Creator<KeySet>() {
 
         /**
diff --git a/core/java/android/content/pm/LabeledIntent.java b/core/java/android/content/pm/LabeledIntent.java
index 68b0046..ae41252 100644
--- a/core/java/android/content/pm/LabeledIntent.java
+++ b/core/java/android/content/pm/LabeledIntent.java
@@ -180,7 +180,7 @@
         mIcon = in.readInt();
     }
     
-    public static final Creator<LabeledIntent> CREATOR
+    public static final @android.annotation.NonNull Creator<LabeledIntent> CREATOR
             = new Creator<LabeledIntent>() {
         public LabeledIntent createFromParcel(Parcel source) {
             return new LabeledIntent(source);
diff --git a/core/java/android/content/pm/LauncherApps.java b/core/java/android/content/pm/LauncherApps.java
index f87ce82..38ea43e 100644
--- a/core/java/android/content/pm/LauncherApps.java
+++ b/core/java/android/content/pm/LauncherApps.java
@@ -795,7 +795,8 @@
      * @throws SecurityException when the caller is not the active launcher.
      */
     @Nullable
-    public LauncherApps.AppUsageLimit getAppUsageLimit(String packageName, UserHandle user) {
+    public LauncherApps.AppUsageLimit getAppUsageLimit(@NonNull String packageName,
+            @NonNull UserHandle user) {
         try {
             return mService.getAppUsageLimit(mContext.getPackageName(), packageName, user);
         } catch (RemoteException re) {
@@ -1724,7 +1725,7 @@
             dest.writeStrongBinder(mInner.asBinder());
         }
 
-        public static final Creator<PinItemRequest> CREATOR =
+        public static final @android.annotation.NonNull Creator<PinItemRequest> CREATOR =
                 new Creator<PinItemRequest>() {
                     public PinItemRequest createFromParcel(Parcel source) {
                         return new PinItemRequest(source);
@@ -1784,7 +1785,7 @@
             mUsageRemaining = source.readLong();
         }
 
-        public static final Creator<AppUsageLimit> CREATOR = new Creator<AppUsageLimit>() {
+        public static final @android.annotation.NonNull Creator<AppUsageLimit> CREATOR = new Creator<AppUsageLimit>() {
             @Override
             public AppUsageLimit createFromParcel(Parcel source) {
                 return new AppUsageLimit(source);
diff --git a/core/java/android/content/pm/ModuleInfo.java b/core/java/android/content/pm/ModuleInfo.java
index 044e87d..d930c92 100644
--- a/core/java/android/content/pm/ModuleInfo.java
+++ b/core/java/android/content/pm/ModuleInfo.java
@@ -134,7 +134,7 @@
         mHidden = source.readBoolean();
     }
 
-    public static final Parcelable.Creator<ModuleInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ModuleInfo> CREATOR =
             new Parcelable.Creator<ModuleInfo>() {
         public ModuleInfo createFromParcel(Parcel source) {
             return new ModuleInfo(source);
diff --git a/core/java/android/content/pm/OrgApacheHttpLegacyUpdater.java b/core/java/android/content/pm/OrgApacheHttpLegacyUpdater.java
index 7790067..707443b 100644
--- a/core/java/android/content/pm/OrgApacheHttpLegacyUpdater.java
+++ b/core/java/android/content/pm/OrgApacheHttpLegacyUpdater.java
@@ -18,6 +18,7 @@
 import static android.content.pm.SharedLibraryNames.ORG_APACHE_HTTP_LEGACY;
 
 import android.content.pm.PackageParser.Package;
+import android.os.Build;
 
 import com.android.internal.annotations.VisibleForTesting;
 
@@ -30,6 +31,11 @@
 @VisibleForTesting
 public class OrgApacheHttpLegacyUpdater extends PackageSharedLibraryUpdater {
 
+    private static boolean apkTargetsApiLevelLessThanOrEqualToOMR1(Package pkg) {
+        int targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
+        return targetSdkVersion < Build.VERSION_CODES.P;
+    }
+
     @Override
     public void updatePackage(Package pkg) {
         // Packages targeted at <= O_MR1 expect the classes in the org.apache.http.legacy library
diff --git a/core/java/android/content/pm/PackageBackwardCompatibility.java b/core/java/android/content/pm/PackageBackwardCompatibility.java
index b19196a..4331bd4 100644
--- a/core/java/android/content/pm/PackageBackwardCompatibility.java
+++ b/core/java/android/content/pm/PackageBackwardCompatibility.java
@@ -116,7 +116,7 @@
 
     private final PackageSharedLibraryUpdater[] mPackageUpdaters;
 
-    public PackageBackwardCompatibility(
+    private PackageBackwardCompatibility(
             boolean bootClassPathContainsATB, PackageSharedLibraryUpdater[] packageUpdaters) {
         this.mBootClassPathContainsATB = bootClassPathContainsATB;
         this.mPackageUpdaters = packageUpdaters;
diff --git a/core/java/android/content/pm/PackageInfo.java b/core/java/android/content/pm/PackageInfo.java
index 27a5b39..725d601 100644
--- a/core/java/android/content/pm/PackageInfo.java
+++ b/core/java/android/content/pm/PackageInfo.java
@@ -489,7 +489,7 @@
         dest.writeBoolean(isApex);
     }
 
-    public static final Parcelable.Creator<PackageInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<PackageInfo> CREATOR
             = new Parcelable.Creator<PackageInfo>() {
         @Override
         public PackageInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/content/pm/PackageInfoLite.java b/core/java/android/content/pm/PackageInfoLite.java
index b878a95..f5442ec 100644
--- a/core/java/android/content/pm/PackageInfoLite.java
+++ b/core/java/android/content/pm/PackageInfoLite.java
@@ -118,7 +118,7 @@
     }
 
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
-    public static final Parcelable.Creator<PackageInfoLite> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<PackageInfoLite> CREATOR
             = new Parcelable.Creator<PackageInfoLite>() {
         public PackageInfoLite createFromParcel(Parcel source) {
             return new PackageInfoLite(source);
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 5e70ecb..a5464c2 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -2565,6 +2565,14 @@
     public static final String FEATURE_PC = "android.hardware.type.pc";
 
     /**
+     * Feature for {@link #getSystemAvailableFeatures} and
+     * {@link #hasSystemFeature}: This is a foldable device. Properties such as
+     * the display size may change in response to being folded.
+     */
+    @SdkConstant(SdkConstantType.FEATURE)
+    public static final String FEATURE_FOLDABLE = "android.hardware.type.foldable";
+
+    /**
      * Feature for {@link #getSystemAvailableFeatures} and {@link #hasSystemFeature}:
      * The device supports printing.
      */
diff --git a/core/java/android/content/pm/PackageManagerInternal.java b/core/java/android/content/pm/PackageManagerInternal.java
index 270e387..2c1842c 100644
--- a/core/java/android/content/pm/PackageManagerInternal.java
+++ b/core/java/android/content/pm/PackageManagerInternal.java
@@ -160,6 +160,14 @@
          * @return whether the default browser was successfully set.
          */
         boolean setDefaultBrowser(@Nullable String packageName, @UserIdInt int userId);
+
+        /**
+         * Set the package name of the default browser asynchronously.
+         *
+         * @param packageName package name of the default browser, or {@code null} to remove
+         * @param userId the user id
+         */
+        void setDefaultBrowserAsync(@Nullable String packageName, @UserIdInt int userId);
     }
 
     /**
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 4db7d0a..a006f23 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -3756,6 +3756,12 @@
             ai.privateFlags |= ApplicationInfo.PRIVATE_FLAG_ALLOW_CLEAR_USER_DATA_ON_FAILED_RESTORE;
         }
 
+        if (sa.getBoolean(
+                R.styleable.AndroidManifestApplication_allowAudioPlaybackCapture,
+                owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.Q)) {
+            ai.privateFlags |= ApplicationInfo.PRIVATE_FLAG_ALLOW_AUDIO_PLAYBACK_CAPTURE;
+        }
+
         ai.maxAspectRatio = sa.getFloat(R.styleable.AndroidManifestApplication_maxAspectRatio, 0);
         ai.minAspectRatio = sa.getFloat(R.styleable.AndroidManifestApplication_minAspectRatio, 0);
 
@@ -6402,7 +6408,7 @@
             this.pastSigningCertificates = in.createTypedArray(Signature.CREATOR);
         }
 
-        public static final Creator<SigningDetails> CREATOR = new Creator<SigningDetails>() {
+        public static final @android.annotation.NonNull Creator<SigningDetails> CREATOR = new Creator<SigningDetails>() {
             @Override
             public SigningDetails createFromParcel(Parcel source) {
                 if (source.readBoolean()) {
@@ -8438,6 +8444,21 @@
     public static PackageInfo generatePackageInfoFromApex(File apexFile, boolean collectCerts)
             throws PackageParserException {
         PackageInfo pi = new PackageInfo();
+        int parseFlags = 0;
+        if (collectCerts) {
+            parseFlags |= PARSE_COLLECT_CERTIFICATES;
+            try {
+                if (apexFile.getCanonicalPath().startsWith("/system")) {
+                    // Don't need verify the APK integrity of APEXes on /system, just like
+                    // we don't do that for APKs.
+                    // TODO(b/126514108): we may be able to do this for APEXes on /data as well.
+                    parseFlags |= PARSE_IS_SYSTEM_DIR;
+                }
+            } catch (IOException e) {
+                throw new PackageParserException(INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION,
+                        "Failed to get path for " + apexFile.getPath(), e);
+            }
+        }
 
         // TODO(b/123086053) properly fill in the ApplicationInfo with data from AndroidManifest
         // Add ApplicationInfo to the PackageInfo.
@@ -8452,8 +8473,7 @@
 
         // TODO(b/123052859): We should avoid these repeated calls to parseApkLite each time
         // we want to generate information for APEX modules.
-        PackageParser.ApkLite apk = PackageParser.parseApkLite(apexFile,
-            collectCerts ? PackageParser.PARSE_COLLECT_CERTIFICATES : 0);
+        PackageParser.ApkLite apk = PackageParser.parseApkLite(apexFile, parseFlags);
 
         pi.packageName = apk.packageName;
         ai.packageName = apk.packageName;
diff --git a/core/java/android/content/pm/PackageSharedLibraryUpdater.java b/core/java/android/content/pm/PackageSharedLibraryUpdater.java
index b14b321..1565d9c 100644
--- a/core/java/android/content/pm/PackageSharedLibraryUpdater.java
+++ b/core/java/android/content/pm/PackageSharedLibraryUpdater.java
@@ -17,7 +17,6 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.os.Build;
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.ArrayUtils;
@@ -60,11 +59,6 @@
                 || ArrayUtils.contains(usesOptionalLibraries, apacheHttpLegacy);
     }
 
-    static boolean apkTargetsApiLevelLessThanOrEqualToOMR1(PackageParser.Package pkg) {
-        int targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
-        return targetSdkVersion < Build.VERSION_CODES.P;
-    }
-
     /**
      * Add an implicit dependency.
      *
diff --git a/core/java/android/content/pm/PackageStats.java b/core/java/android/content/pm/PackageStats.java
index d3e86a3..b0fecfa 100644
--- a/core/java/android/content/pm/PackageStats.java
+++ b/core/java/android/content/pm/PackageStats.java
@@ -79,7 +79,7 @@
     /** Size of the package's OBBs placed on external media. */
     public long externalObbSize;
 
-    public static final Parcelable.Creator<PackageStats> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<PackageStats> CREATOR
             = new Parcelable.Creator<PackageStats>() {
         public PackageStats createFromParcel(Parcel in) {
             return new PackageStats(in);
diff --git a/core/java/android/content/pm/PathPermission.java b/core/java/android/content/pm/PathPermission.java
index 7e49d7d..11c9a7d 100644
--- a/core/java/android/content/pm/PathPermission.java
+++ b/core/java/android/content/pm/PathPermission.java
@@ -55,7 +55,7 @@
         mWritePermission = src.readString();
     }
     
-    public static final Parcelable.Creator<PathPermission> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<PathPermission> CREATOR
             = new Parcelable.Creator<PathPermission>() {
         public PathPermission createFromParcel(Parcel source) {
             return new PathPermission(source);
diff --git a/core/java/android/content/pm/PermissionGroupInfo.java b/core/java/android/content/pm/PermissionGroupInfo.java
index f21612a..3a87eca 100644
--- a/core/java/android/content/pm/PermissionGroupInfo.java
+++ b/core/java/android/content/pm/PermissionGroupInfo.java
@@ -166,7 +166,7 @@
         dest.writeInt(priority);
     }
 
-    public static final Creator<PermissionGroupInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<PermissionGroupInfo> CREATOR =
             new Creator<PermissionGroupInfo>() {
         public PermissionGroupInfo createFromParcel(Parcel source) {
             return new PermissionGroupInfo(source);
diff --git a/core/java/android/content/pm/PermissionInfo.java b/core/java/android/content/pm/PermissionInfo.java
index e245234..b093867 100644
--- a/core/java/android/content/pm/PermissionInfo.java
+++ b/core/java/android/content/pm/PermissionInfo.java
@@ -551,7 +551,7 @@
         return (protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0;
     }
 
-    public static final Creator<PermissionInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<PermissionInfo> CREATOR =
         new Creator<PermissionInfo>() {
         @Override
         public PermissionInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/content/pm/ProviderInfo.java b/core/java/android/content/pm/ProviderInfo.java
index f06a628..07d42dc 100644
--- a/core/java/android/content/pm/ProviderInfo.java
+++ b/core/java/android/content/pm/ProviderInfo.java
@@ -158,7 +158,7 @@
         out.writeInt(isSyncable ? 1 : 0);
     }
 
-    public static final Parcelable.Creator<ProviderInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ProviderInfo> CREATOR
             = new Parcelable.Creator<ProviderInfo>() {
         public ProviderInfo createFromParcel(Parcel in) {
             return new ProviderInfo(in);
diff --git a/core/java/android/content/pm/ResolveInfo.java b/core/java/android/content/pm/ResolveInfo.java
index 894de94..1734182 100644
--- a/core/java/android/content/pm/ResolveInfo.java
+++ b/core/java/android/content/pm/ResolveInfo.java
@@ -445,7 +445,7 @@
         dest.writeInt(isInstantAppAvailable ? 1 : 0);
     }
 
-    public static final Creator<ResolveInfo> CREATOR
+    public static final @android.annotation.NonNull Creator<ResolveInfo> CREATOR
             = new Creator<ResolveInfo>() {
         public ResolveInfo createFromParcel(Parcel source) {
             return new ResolveInfo(source);
diff --git a/core/java/android/content/pm/ServiceInfo.java b/core/java/android/content/pm/ServiceInfo.java
index 4a2f800..cd40c95 100644
--- a/core/java/android/content/pm/ServiceInfo.java
+++ b/core/java/android/content/pm/ServiceInfo.java
@@ -217,7 +217,7 @@
         dest.writeInt(mForegroundServiceType);
     }
 
-    public static final Creator<ServiceInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<ServiceInfo> CREATOR =
         new Creator<ServiceInfo>() {
         public ServiceInfo createFromParcel(Parcel source) {
             return new ServiceInfo(source);
diff --git a/core/java/android/content/pm/SharedLibraryInfo.java b/core/java/android/content/pm/SharedLibraryInfo.java
index 35609c9..13c49a0 100644
--- a/core/java/android/content/pm/SharedLibraryInfo.java
+++ b/core/java/android/content/pm/SharedLibraryInfo.java
@@ -342,7 +342,7 @@
         }
     }
 
-    public static final Parcelable.Creator<SharedLibraryInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<SharedLibraryInfo> CREATOR =
             new Parcelable.Creator<SharedLibraryInfo>() {
         public SharedLibraryInfo createFromParcel(Parcel source) {
             return new SharedLibraryInfo(source);
diff --git a/core/java/android/content/pm/ShortcutInfo.java b/core/java/android/content/pm/ShortcutInfo.java
index b155325..d5273db 100644
--- a/core/java/android/content/pm/ShortcutInfo.java
+++ b/core/java/android/content/pm/ShortcutInfo.java
@@ -18,6 +18,7 @@
 import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.annotation.SystemApi;
 import android.annotation.TestApi;
 import android.annotation.UnsupportedAppUsage;
 import android.annotation.UserIdInt;
@@ -1482,6 +1483,7 @@
      * @hide
      */
     @Nullable
+    @SystemApi
     public Person[] getPersons() {
         return clonePersons(mPersons);
     }
@@ -2048,7 +2050,7 @@
         dest.writeParcelableArray(mPersons, flags);
     }
 
-    public static final Creator<ShortcutInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<ShortcutInfo> CREATOR =
             new Creator<ShortcutInfo>() {
                 public ShortcutInfo createFromParcel(Parcel source) {
                     return new ShortcutInfo(source);
diff --git a/core/java/android/content/pm/ShortcutManager.java b/core/java/android/content/pm/ShortcutManager.java
index 849fd03..2287243 100644
--- a/core/java/android/content/pm/ShortcutManager.java
+++ b/core/java/android/content/pm/ShortcutManager.java
@@ -624,7 +624,7 @@
             dest.writeParcelable(mTargetComponent, flags);
         }
 
-        public static final Parcelable.Creator<ShareShortcutInfo> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<ShareShortcutInfo> CREATOR =
                 new Parcelable.Creator<ShareShortcutInfo>() {
                     public ShareShortcutInfo createFromParcel(Parcel in) {
                         return new ShareShortcutInfo(in);
@@ -644,6 +644,7 @@
      * @return True if the package has any share target definitions, False otherwise.
      * @hide
      */
+    @SystemApi
     public boolean hasShareTargets(@NonNull String packageName) {
         try {
             return mService.hasShareTargets(mContext.getPackageName(), packageName,
diff --git a/core/java/android/content/pm/Signature.java b/core/java/android/content/pm/Signature.java
index 349bb69..25a4dca 100644
--- a/core/java/android/content/pm/Signature.java
+++ b/core/java/android/content/pm/Signature.java
@@ -262,7 +262,7 @@
         dest.writeByteArray(mSignature);
     }
 
-    public static final Parcelable.Creator<Signature> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Signature> CREATOR
             = new Parcelable.Creator<Signature>() {
         public Signature createFromParcel(Parcel source) {
             return new Signature(source);
diff --git a/core/java/android/content/pm/SigningInfo.java b/core/java/android/content/pm/SigningInfo.java
index ef87403..d14be9c 100644
--- a/core/java/android/content/pm/SigningInfo.java
+++ b/core/java/android/content/pm/SigningInfo.java
@@ -124,7 +124,7 @@
         mSigningDetails.writeToParcel(dest, parcelableFlags);
     }
 
-    public static final Parcelable.Creator<SigningInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<SigningInfo> CREATOR =
             new Parcelable.Creator<SigningInfo>() {
         @Override
         public SigningInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/content/pm/SuspendDialogInfo.java b/core/java/android/content/pm/SuspendDialogInfo.java
index 53b52f5..db8f8c2 100644
--- a/core/java/android/content/pm/SuspendDialogInfo.java
+++ b/core/java/android/content/pm/SuspendDialogInfo.java
@@ -261,7 +261,7 @@
         mNeutralButtonTextResId = b.mNeutralButtonTextResId;
     }
 
-    public static final Creator<SuspendDialogInfo> CREATOR = new Creator<SuspendDialogInfo>() {
+    public static final @android.annotation.NonNull Creator<SuspendDialogInfo> CREATOR = new Creator<SuspendDialogInfo>() {
         @Override
         public SuspendDialogInfo createFromParcel(Parcel source) {
             return new SuspendDialogInfo(source);
diff --git a/core/java/android/content/pm/UserInfo.java b/core/java/android/content/pm/UserInfo.java
index b75ed35..2b1b32e 100644
--- a/core/java/android/content/pm/UserInfo.java
+++ b/core/java/android/content/pm/UserInfo.java
@@ -289,7 +289,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Parcelable.Creator<UserInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<UserInfo> CREATOR
             = new Parcelable.Creator<UserInfo>() {
         public UserInfo createFromParcel(Parcel source) {
             return new UserInfo(source);
diff --git a/core/java/android/content/pm/VerificationParams.java b/core/java/android/content/pm/VerificationParams.java
index f90d295..f072167 100644
--- a/core/java/android/content/pm/VerificationParams.java
+++ b/core/java/android/content/pm/VerificationParams.java
@@ -198,7 +198,7 @@
         mInstallerUid = source.readInt();
     }
 
-    public static final Parcelable.Creator<VerificationParams> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<VerificationParams> CREATOR =
             new Parcelable.Creator<VerificationParams>() {
         public VerificationParams createFromParcel(Parcel source) {
                 return new VerificationParams(source);
diff --git a/core/java/android/content/pm/VerifierDeviceIdentity.java b/core/java/android/content/pm/VerifierDeviceIdentity.java
index 90be6f31..f29aaec 100644
--- a/core/java/android/content/pm/VerifierDeviceIdentity.java
+++ b/core/java/android/content/pm/VerifierDeviceIdentity.java
@@ -230,7 +230,7 @@
         dest.writeLong(mIdentity);
     }
 
-    public static final Parcelable.Creator<VerifierDeviceIdentity> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<VerifierDeviceIdentity> CREATOR
             = new Parcelable.Creator<VerifierDeviceIdentity>() {
         public VerifierDeviceIdentity createFromParcel(Parcel source) {
             return new VerifierDeviceIdentity(source);
diff --git a/core/java/android/content/pm/VerifierInfo.java b/core/java/android/content/pm/VerifierInfo.java
index b4e72e6..224ca62 100644
--- a/core/java/android/content/pm/VerifierInfo.java
+++ b/core/java/android/content/pm/VerifierInfo.java
@@ -72,7 +72,7 @@
         dest.writeSerializable(publicKey);
     }
 
-    public static final Parcelable.Creator<VerifierInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<VerifierInfo> CREATOR
             = new Parcelable.Creator<VerifierInfo>() {
         public VerifierInfo createFromParcel(Parcel source) {
             return new VerifierInfo(source);
diff --git a/core/java/android/content/pm/VersionedPackage.java b/core/java/android/content/pm/VersionedPackage.java
index 3953466..3e22eb2 100644
--- a/core/java/android/content/pm/VersionedPackage.java
+++ b/core/java/android/content/pm/VersionedPackage.java
@@ -106,7 +106,7 @@
         parcel.writeLong(mVersionCode);
     }
 
-    public static final Creator<VersionedPackage> CREATOR = new Creator<VersionedPackage>() {
+    public static final @android.annotation.NonNull Creator<VersionedPackage> CREATOR = new Creator<VersionedPackage>() {
         @Override
         public VersionedPackage createFromParcel(Parcel source) {
             return new VersionedPackage(source);
diff --git a/core/java/android/content/pm/permission/RuntimePermissionPresentationInfo.java b/core/java/android/content/pm/permission/RuntimePermissionPresentationInfo.java
index 9fa863c..97312c44 100644
--- a/core/java/android/content/pm/permission/RuntimePermissionPresentationInfo.java
+++ b/core/java/android/content/pm/permission/RuntimePermissionPresentationInfo.java
@@ -101,7 +101,7 @@
         parcel.writeInt(mFlags);
     }
 
-    public static final Creator<RuntimePermissionPresentationInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<RuntimePermissionPresentationInfo> CREATOR =
             new Creator<RuntimePermissionPresentationInfo>() {
         public RuntimePermissionPresentationInfo createFromParcel(Parcel source) {
             return new RuntimePermissionPresentationInfo(source);
diff --git a/core/java/android/content/res/AssetFileDescriptor.java b/core/java/android/content/res/AssetFileDescriptor.java
index b6cbf08..2ba5579 100644
--- a/core/java/android/content/res/AssetFileDescriptor.java
+++ b/core/java/android/content/res/AssetFileDescriptor.java
@@ -370,7 +370,7 @@
         }
     }
 
-    public static final Parcelable.Creator<AssetFileDescriptor> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AssetFileDescriptor> CREATOR
             = new Parcelable.Creator<AssetFileDescriptor>() {
         public AssetFileDescriptor createFromParcel(Parcel in) {
             return new AssetFileDescriptor(in);
diff --git a/core/java/android/content/res/ColorStateList.java b/core/java/android/content/res/ColorStateList.java
index 16b9726..b5b097b 100644
--- a/core/java/android/content/res/ColorStateList.java
+++ b/core/java/android/content/res/ColorStateList.java
@@ -727,7 +727,7 @@
         dest.writeIntArray(mColors);
     }
 
-    public static final Parcelable.Creator<ColorStateList> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ColorStateList> CREATOR =
             new Parcelable.Creator<ColorStateList>() {
         @Override
         public ColorStateList[] newArray(int size) {
diff --git a/core/java/android/content/res/CompatibilityInfo.java b/core/java/android/content/res/CompatibilityInfo.java
index 7d101b8..a99a0b5 100644
--- a/core/java/android/content/res/CompatibilityInfo.java
+++ b/core/java/android/content/res/CompatibilityInfo.java
@@ -613,7 +613,7 @@
     }
 
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
-    public static final Parcelable.Creator<CompatibilityInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<CompatibilityInfo> CREATOR
             = new Parcelable.Creator<CompatibilityInfo>() {
         @Override
         public CompatibilityInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/content/res/Configuration.java b/core/java/android/content/res/Configuration.java
index 8a92017..8b02cae 100644
--- a/core/java/android/content/res/Configuration.java
+++ b/core/java/android/content/res/Configuration.java
@@ -1829,7 +1829,7 @@
         seq = source.readInt();
     }
 
-    public static final Parcelable.Creator<Configuration> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Configuration> CREATOR
             = new Parcelable.Creator<Configuration>() {
         public Configuration createFromParcel(Parcel source) {
             return new Configuration(source);
diff --git a/core/java/android/content/res/ObbInfo.java b/core/java/android/content/res/ObbInfo.java
index 1d10b4f..8af27ca 100644
--- a/core/java/android/content/res/ObbInfo.java
+++ b/core/java/android/content/res/ObbInfo.java
@@ -88,7 +88,7 @@
         dest.writeByteArray(salt);
     }
 
-    public static final Parcelable.Creator<ObbInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ObbInfo> CREATOR
             = new Parcelable.Creator<ObbInfo>() {
         public ObbInfo createFromParcel(Parcel source) {
             return new ObbInfo(source);
diff --git a/core/java/android/content/rollback/PackageRollbackInfo.java b/core/java/android/content/rollback/PackageRollbackInfo.java
index 7e5532c..03810f5 100644
--- a/core/java/android/content/rollback/PackageRollbackInfo.java
+++ b/core/java/android/content/rollback/PackageRollbackInfo.java
@@ -208,7 +208,7 @@
         out.writeBoolean(mIsApex);
     }
 
-    public static final Parcelable.Creator<PackageRollbackInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PackageRollbackInfo> CREATOR =
             new Parcelable.Creator<PackageRollbackInfo>() {
         public PackageRollbackInfo createFromParcel(Parcel in) {
             return new PackageRollbackInfo(in);
diff --git a/core/java/android/content/rollback/RollbackInfo.java b/core/java/android/content/rollback/RollbackInfo.java
index 0cde6ba..29b99e0 100644
--- a/core/java/android/content/rollback/RollbackInfo.java
+++ b/core/java/android/content/rollback/RollbackInfo.java
@@ -17,12 +17,10 @@
 package android.content.rollback;
 
 import android.annotation.SystemApi;
-import android.content.pm.PackageInstaller;
 import android.content.pm.VersionedPackage;
 import android.os.Parcel;
 import android.os.Parcelable;
 
-import java.util.Collections;
 import java.util.List;
 
 /**
@@ -44,13 +42,7 @@
     private final List<VersionedPackage> mCausePackages;
 
     private final boolean mIsStaged;
-    private final int mCommittedSessionId;
-
-    /** @hide */
-    public RollbackInfo(int rollbackId, List<PackageRollbackInfo> packages, boolean isStaged) {
-        this(rollbackId, packages, isStaged, Collections.emptyList(),
-                PackageInstaller.SessionInfo.INVALID_ID);
-    }
+    private int mCommittedSessionId;
 
     /** @hide */
     public RollbackInfo(int rollbackId, List<PackageRollbackInfo> packages, boolean isStaged,
@@ -101,6 +93,14 @@
     }
 
     /**
+     * Sets the session ID for the committed rollback for staged rollbacks.
+     * @hide
+     */
+    public void setCommittedSessionId(int sessionId) {
+        mCommittedSessionId = sessionId;
+    }
+
+    /**
      * Gets the list of package versions that motivated this rollback.
      * As provided to {@link #commitRollback} when the rollback was committed.
      * This is only applicable for rollbacks that have been committed.
@@ -123,7 +123,7 @@
         out.writeInt(mCommittedSessionId);
     }
 
-    public static final Parcelable.Creator<RollbackInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<RollbackInfo> CREATOR =
             new Parcelable.Creator<RollbackInfo>() {
         public RollbackInfo createFromParcel(Parcel in) {
             return new RollbackInfo(in);
diff --git a/core/java/android/content/rollback/RollbackManager.java b/core/java/android/content/rollback/RollbackManager.java
index 2788f82..c043491 100644
--- a/core/java/android/content/rollback/RollbackManager.java
+++ b/core/java/android/content/rollback/RollbackManager.java
@@ -187,7 +187,8 @@
     /**
      * Expire the rollback data for a given package.
      * This API is meant to facilitate testing of rollback logic for
-     * expiring rollback data.
+     * expiring rollback data. Removes rollback data for available and
+     * recently committed rollbacks that contain the given package.
      *
      * @param packageName the name of the package to expire data for.
      * @throws SecurityException if the caller does not have the
diff --git a/core/java/android/database/BulkCursorDescriptor.java b/core/java/android/database/BulkCursorDescriptor.java
index c1e5e63..80a0319 100644
--- a/core/java/android/database/BulkCursorDescriptor.java
+++ b/core/java/android/database/BulkCursorDescriptor.java
@@ -26,7 +26,7 @@
  * {@hide}
  */
 public final class BulkCursorDescriptor implements Parcelable {
-    public static final Parcelable.Creator<BulkCursorDescriptor> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BulkCursorDescriptor> CREATOR =
             new Parcelable.Creator<BulkCursorDescriptor>() {
         @Override
         public BulkCursorDescriptor createFromParcel(Parcel in) {
diff --git a/core/java/android/database/BulkCursorNative.java b/core/java/android/database/BulkCursorNative.java
index d3c11e7..77a13cf 100644
--- a/core/java/android/database/BulkCursorNative.java
+++ b/core/java/android/database/BulkCursorNative.java
@@ -16,6 +16,7 @@
 
 package android.database;
 
+import android.annotation.UnsupportedAppUsage;
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.IBinder;
@@ -138,6 +139,7 @@
 
 
 final class BulkCursorProxy implements IBulkCursor {
+    @UnsupportedAppUsage
     private IBinder mRemote;
     private Bundle mExtras;
 
diff --git a/core/java/android/database/Cursor.java b/core/java/android/database/Cursor.java
index 1379138..2afb755 100644
--- a/core/java/android/database/Cursor.java
+++ b/core/java/android/database/Cursor.java
@@ -17,6 +17,7 @@
 package android.database;
 
 import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.content.ContentResolver;
 import android.net.Uri;
 import android.os.Bundle;
@@ -473,7 +474,7 @@
      * ContentResolver.registerContentObserver} to find out about changes to this Cursor's
      * data. May be null if no notification URI has been set.
      */
-    default List<Uri> getNotificationUris() {
+    default @Nullable List<Uri> getNotificationUris() {
         final Uri notifyUri = getNotificationUri();
         return notifyUri == null ? null : Arrays.asList(notifyUri);
     }
diff --git a/core/java/android/database/CursorWindow.java b/core/java/android/database/CursorWindow.java
index d9443d9..44bd883 100644
--- a/core/java/android/database/CursorWindow.java
+++ b/core/java/android/database/CursorWindow.java
@@ -709,7 +709,7 @@
         }
     }
 
-    public static final Parcelable.Creator<CursorWindow> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<CursorWindow> CREATOR
             = new Parcelable.Creator<CursorWindow>() {
         public CursorWindow createFromParcel(Parcel source) {
             return new CursorWindow(source);
diff --git a/core/java/android/database/sqlite/SQLiteCompatibilityWalFlags.java b/core/java/android/database/sqlite/SQLiteCompatibilityWalFlags.java
index 8ea1db2..a269072 100644
--- a/core/java/android/database/sqlite/SQLiteCompatibilityWalFlags.java
+++ b/core/java/android/database/sqlite/SQLiteCompatibilityWalFlags.java
@@ -40,8 +40,7 @@
     private static final String TAG = "SQLiteCompatibilityWalFlags";
 
     private static volatile boolean sInitialized;
-    private static volatile boolean sFlagsSet;
-    private static volatile boolean sCompatibilityWalSupported;
+    private static volatile boolean sLegacyCompatibilityWalEnabled;
     private static volatile String sWALSyncMode;
     private static volatile long sTruncateSize = -1;
     // This flag is used to avoid recursive initialization due to circular dependency on Settings
@@ -54,18 +53,9 @@
      * @hide
      */
     @VisibleForTesting
-    public static boolean areFlagsSet() {
+    public static boolean isLegacyCompatibilityWalEnabled() {
         initIfNeeded();
-        return sFlagsSet;
-    }
-
-    /**
-     * @hide
-     */
-    @VisibleForTesting
-    public static boolean isCompatibilityWalSupported() {
-        initIfNeeded();
-        return sCompatibilityWalSupported;
+        return sLegacyCompatibilityWalEnabled;
     }
 
     /**
@@ -74,6 +64,14 @@
     @VisibleForTesting
     public static String getWALSyncMode() {
         initIfNeeded();
+        // The configurable WAL sync mode should only ever be used if the legacy compatibility
+        // WAL is enabled. It should *not* have any effect if app developers explicitly turn on
+        // WAL for their database using setWriteAheadLoggingEnabled. Throwing an exception here
+        // adds an extra layer of checking that we never use it in the wrong place.
+        if (!sLegacyCompatibilityWalEnabled) {
+            throw new IllegalStateException("isLegacyCompatibilityWalEnabled() == false");
+        }
+
         return sWALSyncMode;
     }
 
@@ -131,13 +129,12 @@
             sInitialized = true;
             return;
         }
-        sCompatibilityWalSupported = parser.getBoolean("compatibility_wal_supported",
-                SQLiteGlobal.isCompatibilityWalSupported());
+        sLegacyCompatibilityWalEnabled = parser.getBoolean(
+                "legacy_compatibility_wal_enabled", false);
         sWALSyncMode = parser.getString("wal_syncmode", SQLiteGlobal.getWALSyncMode());
         sTruncateSize = parser.getInt("truncate_size", -1);
-        Log.i(TAG, "Read compatibility WAL flags: compatibility_wal_supported="
-                + sCompatibilityWalSupported + ", wal_syncmode=" + sWALSyncMode);
-        sFlagsSet = true;
+        Log.i(TAG, "Read compatibility WAL flags: legacy_compatibility_wal_enabled="
+                + sLegacyCompatibilityWalEnabled + ", wal_syncmode=" + sWALSyncMode);
         sInitialized = true;
     }
 
@@ -148,8 +145,7 @@
     @TestApi
     public static void reset() {
         sInitialized = false;
-        sFlagsSet = false;
-        sCompatibilityWalSupported = false;
+        sLegacyCompatibilityWalEnabled = false;
         sWALSyncMode = null;
     }
 }
diff --git a/core/java/android/database/sqlite/SQLiteConnection.java b/core/java/android/database/sqlite/SQLiteConnection.java
index 3c8e236..3844794 100644
--- a/core/java/android/database/sqlite/SQLiteConnection.java
+++ b/core/java/android/database/sqlite/SQLiteConnection.java
@@ -300,12 +300,13 @@
                     (mConfiguration.openFlags & SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING) != 0;
             // Use compatibility WAL unless an app explicitly set journal/synchronous mode
             // or DISABLE_COMPATIBILITY_WAL flag is set
-            final boolean useCompatibilityWal = mConfiguration.useCompatibilityWal();
-            if (walEnabled || useCompatibilityWal) {
+            final boolean isCompatibilityWalEnabled =
+                    mConfiguration.isLegacyCompatibilityWalEnabled();
+            if (walEnabled || isCompatibilityWalEnabled) {
                 setJournalMode("WAL");
                 if (mConfiguration.syncMode != null) {
                     setSyncMode(mConfiguration.syncMode);
-                } else if (useCompatibilityWal && SQLiteCompatibilityWalFlags.areFlagsSet()) {
+                } else if (isCompatibilityWalEnabled) {
                     setSyncMode(SQLiteCompatibilityWalFlags.getWALSyncMode());
                 } else {
                     setSyncMode(SQLiteGlobal.getWALSyncMode());
@@ -504,7 +505,7 @@
                 != mConfiguration.foreignKeyConstraintsEnabled;
         boolean walModeChanged = ((configuration.openFlags ^ mConfiguration.openFlags)
                 & (SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING
-                | SQLiteDatabase.DISABLE_COMPATIBILITY_WAL)) != 0;
+                | SQLiteDatabase.ENABLE_LEGACY_COMPATIBILITY_WAL)) != 0;
         boolean localeChanged = !configuration.locale.equals(mConfiguration.locale);
 
         // Update configuration parameters.
diff --git a/core/java/android/database/sqlite/SQLiteConnectionPool.java b/core/java/android/database/sqlite/SQLiteConnectionPool.java
index dbc1766..852f8f2 100644
--- a/core/java/android/database/sqlite/SQLiteConnectionPool.java
+++ b/core/java/android/database/sqlite/SQLiteConnectionPool.java
@@ -321,7 +321,7 @@
             // We should do in-place switching when transitioning from compatibility WAL
             // to rollback journal. Otherwise transient connection state will be lost
             boolean onlyCompatWalChanged = (mConfiguration.openFlags ^ configuration.openFlags)
-                    == SQLiteDatabase.DISABLE_COMPATIBILITY_WAL;
+                    == SQLiteDatabase.ENABLE_LEGACY_COMPATIBILITY_WAL;
 
             if (!onlyCompatWalChanged && mConfiguration.openFlags != configuration.openFlags) {
                 // If we are changing open flags and WAL mode at the same time, then
@@ -1113,19 +1113,18 @@
             if (directories != null) {
                 directories.add(new File(mConfiguration.path).getParent());
             }
+            boolean isCompatibilityWalEnabled = mConfiguration.isLegacyCompatibilityWalEnabled();
             printer.println("Connection pool for " + mConfiguration.path + ":");
             printer.println("  Open: " + mIsOpen);
             printer.println("  Max connections: " + mMaxConnectionPoolSize);
             printer.println("  Total execution time: " + mTotalExecutionTimeCounter);
             printer.println("  Configuration: openFlags=" + mConfiguration.openFlags
-                    + ", useCompatibilityWal=" + mConfiguration.useCompatibilityWal()
+                    + ", isLegacyCompatibilityWalEnabled=" + isCompatibilityWalEnabled
                     + ", journalMode=" + TextUtils.emptyIfNull(mConfiguration.journalMode)
                     + ", syncMode=" + TextUtils.emptyIfNull(mConfiguration.syncMode));
 
-            if (SQLiteCompatibilityWalFlags.areFlagsSet()) {
-                printer.println("  Compatibility WAL settings: compatibility_wal_supported="
-                        + SQLiteCompatibilityWalFlags
-                        .isCompatibilityWalSupported() + ", wal_syncmode="
+            if (isCompatibilityWalEnabled) {
+                printer.println("  Compatibility WAL enabled: wal_syncmode="
                         + SQLiteCompatibilityWalFlags.getWALSyncMode());
             }
             if (mConfiguration.isLookasideConfigSet()) {
diff --git a/core/java/android/database/sqlite/SQLiteDatabase.java b/core/java/android/database/sqlite/SQLiteDatabase.java
index ae456af..dffbd89 100644
--- a/core/java/android/database/sqlite/SQLiteDatabase.java
+++ b/core/java/android/database/sqlite/SQLiteDatabase.java
@@ -266,12 +266,17 @@
      */
     public static final int ENABLE_WRITE_AHEAD_LOGGING = 0x20000000;
 
+
+    // Note: The below value was only used on Android Pie.
+    // public static final int DISABLE_COMPATIBILITY_WAL = 0x40000000;
+
     /**
-     * Open flag: Flag for {@link #openDatabase} to disable Compatibility WAL when opening database.
+     * Open flag: Flag for {@link #openDatabase} to enable the legacy Compatibility WAL when opening
+     * database.
      *
      * @hide
      */
-    public static final int DISABLE_COMPATIBILITY_WAL = 0x40000000;
+    public static final int ENABLE_LEGACY_COMPATIBILITY_WAL = 0x80000000;
 
     /**
      * Absolute max value that can be set by {@link #setMaxSqlCacheSize(int)}.
@@ -309,10 +314,8 @@
         mConfigurationLocked.idleConnectionTimeoutMs = effectiveTimeoutMs;
         mConfigurationLocked.journalMode = journalMode;
         mConfigurationLocked.syncMode = syncMode;
-        if (!SQLiteGlobal.isCompatibilityWalSupported() || (
-                SQLiteCompatibilityWalFlags.areFlagsSet() && !SQLiteCompatibilityWalFlags
-                        .isCompatibilityWalSupported())) {
-            mConfigurationLocked.openFlags |= DISABLE_COMPATIBILITY_WAL;
+        if (SQLiteCompatibilityWalFlags.isLegacyCompatibilityWalEnabled()) {
+            mConfigurationLocked.openFlags |= ENABLE_LEGACY_COMPATIBILITY_WAL;
         }
     }
 
@@ -2123,15 +2126,18 @@
             throwIfNotOpenLocked();
 
             final int oldFlags = mConfigurationLocked.openFlags;
-            final boolean walDisabled = (oldFlags & ENABLE_WRITE_AHEAD_LOGGING) == 0;
-            final boolean compatibilityWalDisabled = (oldFlags & DISABLE_COMPATIBILITY_WAL) != 0;
-            if (walDisabled && compatibilityWalDisabled) {
+            final boolean walEnabled = (oldFlags & ENABLE_WRITE_AHEAD_LOGGING) != 0;
+            final boolean compatibilityWalEnabled =
+                    (oldFlags & ENABLE_LEGACY_COMPATIBILITY_WAL) != 0;
+            // WAL was never enabled for this database, so there's nothing left to do.
+            if (!walEnabled && !compatibilityWalEnabled) {
                 return;
             }
 
+            // If an app explicitly disables WAL, it takes priority over any directive
+            // to use the legacy "compatibility WAL" mode.
             mConfigurationLocked.openFlags &= ~ENABLE_WRITE_AHEAD_LOGGING;
-            // If an app explicitly disables WAL, compatibility mode should be disabled too
-            mConfigurationLocked.openFlags |= DISABLE_COMPATIBILITY_WAL;
+            mConfigurationLocked.openFlags &= ~ENABLE_LEGACY_COMPATIBILITY_WAL;
 
             try {
                 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
diff --git a/core/java/android/database/sqlite/SQLiteDatabaseConfiguration.java b/core/java/android/database/sqlite/SQLiteDatabaseConfiguration.java
index 48f1021..fcdaf0a 100644
--- a/core/java/android/database/sqlite/SQLiteDatabaseConfiguration.java
+++ b/core/java/android/database/sqlite/SQLiteDatabaseConfiguration.java
@@ -17,6 +17,7 @@
 package android.database.sqlite;
 
 import android.annotation.UnsupportedAppUsage;
+
 import java.util.ArrayList;
 import java.util.Locale;
 import java.util.regex.Pattern;
@@ -197,9 +198,9 @@
         return path.equalsIgnoreCase(MEMORY_DB_PATH);
     }
 
-    boolean useCompatibilityWal() {
+    boolean isLegacyCompatibilityWalEnabled() {
         return journalMode == null && syncMode == null
-                && (openFlags & SQLiteDatabase.DISABLE_COMPATIBILITY_WAL) == 0;
+                && (openFlags & SQLiteDatabase.ENABLE_LEGACY_COMPATIBILITY_WAL) != 0;
     }
 
     private static String stripPathForLogs(String path) {
diff --git a/core/java/android/database/sqlite/SQLiteGlobal.java b/core/java/android/database/sqlite/SQLiteGlobal.java
index ff286fd..d796003 100644
--- a/core/java/android/database/sqlite/SQLiteGlobal.java
+++ b/core/java/android/database/sqlite/SQLiteGlobal.java
@@ -91,16 +91,6 @@
     }
 
     /**
-     * Returns true if compatibility WAL mode is supported. In this mode, only
-     * database journal mode is changed. Connection pool will use at most one connection.
-     */
-    public static boolean isCompatibilityWalSupported() {
-        return SystemProperties.getBoolean("debug.sqlite.compatibility_wal_supported",
-                Resources.getSystem().getBoolean(
-                        com.android.internal.R.bool.db_compatibility_wal_supported));
-    }
-
-    /**
      * Gets the journal size limit in bytes.
      */
     public static int getJournalSizeLimit() {
diff --git a/core/java/android/database/sqlite/SQLiteOpenHelper.java b/core/java/android/database/sqlite/SQLiteOpenHelper.java
index 0e869c8..8163c4d 100644
--- a/core/java/android/database/sqlite/SQLiteOpenHelper.java
+++ b/core/java/android/database/sqlite/SQLiteOpenHelper.java
@@ -202,8 +202,9 @@
                 }
                 mOpenParamsBuilder.setWriteAheadLoggingEnabled(enabled);
             }
+
             // Compatibility WAL is disabled if an app disables or enables WAL
-            mOpenParamsBuilder.addOpenFlags(SQLiteDatabase.DISABLE_COMPATIBILITY_WAL);
+            mOpenParamsBuilder.removeOpenFlags(SQLiteDatabase.ENABLE_LEGACY_COMPATIBILITY_WAL);
         }
     }
 
diff --git a/core/java/android/database/sqlite/SQLiteQueryBuilder.java b/core/java/android/database/sqlite/SQLiteQueryBuilder.java
index 03e8507..a73a719 100644
--- a/core/java/android/database/sqlite/SQLiteQueryBuilder.java
+++ b/core/java/android/database/sqlite/SQLiteQueryBuilder.java
@@ -89,7 +89,7 @@
      *
      * @return the list of tables being queried
      */
-    public String getTables() {
+    public @Nullable String getTables() {
         return mTables;
     }
 
@@ -101,7 +101,7 @@
      *
      * @param inTables the list of tables to query on
      */
-    public void setTables(String inTables) {
+    public void setTables(@Nullable String inTables) {
         mTables = inTables;
     }
 
@@ -170,7 +170,7 @@
      *
      * @param columnMap maps from the user column names to the database column names
      */
-    public void setProjectionMap(Map<String, String> columnMap) {
+    public void setProjectionMap(@Nullable Map<String, String> columnMap) {
         mProjectionMap = columnMap;
     }
 
@@ -178,7 +178,7 @@
      * Gets the projection map for the query, as last configured by
      * {@link #setProjectionMap(Map)}.
      */
-    public Map<String, String> getProjectionMap() {
+    public @Nullable Map<String, String> getProjectionMap() {
         return mProjectionMap;
     }
 
@@ -189,7 +189,7 @@
      *
      * @hide
      */
-    public void setProjectionGreylist(List<Pattern> projectionGreylist) {
+    public void setProjectionGreylist(@Nullable List<Pattern> projectionGreylist) {
         mProjectionGreylist = projectionGreylist;
     }
 
@@ -199,7 +199,7 @@
      *
      * @hide
      */
-    public List<Pattern> getProjectionGreylist() {
+    public @Nullable List<Pattern> getProjectionGreylist() {
         return mProjectionGreylist;
     }
 
@@ -210,7 +210,7 @@
      *
      * @param factory the factory to use.
      */
-    public void setCursorFactory(SQLiteDatabase.CursorFactory factory) {
+    public void setCursorFactory(@Nullable SQLiteDatabase.CursorFactory factory) {
         mFactory = factory;
     }
 
@@ -218,7 +218,7 @@
      * Sets the cursor factory to be used for the query, as last configured by
      * {@link #setCursorFactory(android.database.sqlite.SQLiteDatabase.CursorFactory)}.
      */
-    public SQLiteDatabase.CursorFactory getCursorFactory() {
+    public @Nullable SQLiteDatabase.CursorFactory getCursorFactory() {
         return mFactory;
     }
 
diff --git a/core/java/android/gesture/Gesture.java b/core/java/android/gesture/Gesture.java
index c6a2a87..08920c1 100644
--- a/core/java/android/gesture/Gesture.java
+++ b/core/java/android/gesture/Gesture.java
@@ -280,7 +280,7 @@
         return gesture;
     }
 
-    public static final Parcelable.Creator<Gesture> CREATOR = new Parcelable.Creator<Gesture>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<Gesture> CREATOR = new Parcelable.Creator<Gesture>() {
         public Gesture createFromParcel(Parcel in) {
             Gesture gesture = null;
             final long gestureID = in.readLong();
diff --git a/core/java/android/hardware/CameraInfo.java b/core/java/android/hardware/CameraInfo.java
index 53da0ce..072be50 100644
--- a/core/java/android/hardware/CameraInfo.java
+++ b/core/java/android/hardware/CameraInfo.java
@@ -45,7 +45,7 @@
         info.orientation = in.readInt();
     }
 
-    public static final Parcelable.Creator<CameraInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CameraInfo> CREATOR =
             new Parcelable.Creator<CameraInfo>() {
         @Override
         public CameraInfo createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/CameraStatus.java b/core/java/android/hardware/CameraStatus.java
index bc97e38..08b5b77 100644
--- a/core/java/android/hardware/CameraStatus.java
+++ b/core/java/android/hardware/CameraStatus.java
@@ -47,7 +47,7 @@
         status = in.readInt();
     }
 
-    public static final Parcelable.Creator<CameraStatus> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CameraStatus> CREATOR =
             new Parcelable.Creator<CameraStatus>() {
         @Override
         public CameraStatus createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/HardwareBuffer.java b/core/java/android/hardware/HardwareBuffer.java
index 87cffc9..c569e05 100644
--- a/core/java/android/hardware/HardwareBuffer.java
+++ b/core/java/android/hardware/HardwareBuffer.java
@@ -376,7 +376,7 @@
         nWriteHardwareBufferToParcel(mNativeObject, dest);
     }
 
-    public static final Parcelable.Creator<HardwareBuffer> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<HardwareBuffer> CREATOR =
             new Parcelable.Creator<HardwareBuffer>() {
         public HardwareBuffer createFromParcel(Parcel in) {
             long nativeObject = nReadHardwareBufferFromParcel(in);
diff --git a/core/java/android/hardware/biometrics/BiometricPrompt.java b/core/java/android/hardware/biometrics/BiometricPrompt.java
index baf972b..c64e48f 100644
--- a/core/java/android/hardware/biometrics/BiometricPrompt.java
+++ b/core/java/android/hardware/biometrics/BiometricPrompt.java
@@ -139,7 +139,7 @@
          * @param title
          * @return
          */
-        public Builder setTitle(@NonNull CharSequence title) {
+        @NonNull public Builder setTitle(@NonNull CharSequence title) {
             mBundle.putCharSequence(KEY_TITLE, title);
             return this;
         }
@@ -150,7 +150,7 @@
          * @hide
          */
         @RequiresPermission(USE_BIOMETRIC_INTERNAL)
-        public Builder setUseDefaultTitle() {
+        @NonNull public Builder setUseDefaultTitle() {
             mBundle.putBoolean(KEY_USE_DEFAULT_TITLE, true);
             return this;
         }
@@ -160,7 +160,7 @@
          * @param subtitle
          * @return
          */
-        public Builder setSubtitle(@NonNull CharSequence subtitle) {
+        @NonNull public Builder setSubtitle(@NonNull CharSequence subtitle) {
             mBundle.putCharSequence(KEY_SUBTITLE, subtitle);
             return this;
         }
@@ -170,7 +170,7 @@
          * @param description
          * @return
          */
-        public Builder setDescription(@NonNull CharSequence description) {
+        @NonNull public Builder setDescription(@NonNull CharSequence description) {
             mBundle.putCharSequence(KEY_DESCRIPTION, description);
             return this;
         }
@@ -182,7 +182,7 @@
          * @return
          * @hide
          */
-        public Builder setPositiveButton(@NonNull CharSequence text,
+        @NonNull public Builder setPositiveButton(@NonNull CharSequence text,
                 @NonNull @CallbackExecutor Executor executor,
                 @NonNull DialogInterface.OnClickListener listener) {
             if (TextUtils.isEmpty(text)) {
@@ -210,7 +210,7 @@
          * @param text
          * @return
          */
-        public Builder setNegativeButton(@NonNull CharSequence text,
+        @NonNull public Builder setNegativeButton(@NonNull CharSequence text,
                 @NonNull @CallbackExecutor Executor executor,
                 @NonNull DialogInterface.OnClickListener listener) {
             if (TextUtils.isEmpty(text)) {
@@ -245,7 +245,7 @@
          *
          * @param requireConfirmation
          */
-        public Builder setRequireConfirmation(boolean requireConfirmation) {
+        @NonNull public Builder setRequireConfirmation(boolean requireConfirmation) {
             mBundle.putBoolean(KEY_REQUIRE_CONFIRMATION, requireConfirmation);
             return this;
         }
@@ -255,7 +255,8 @@
          * option to authenticate with their device PIN, pattern, or password. Developers should
          * first check {@link KeyguardManager#isDeviceSecure()} before enabling this. If the device
          * is not secure, {@link BiometricPrompt#BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL} will be
-         * returned in {@link AuthenticationCallback#onAuthenticationError(int, CharSequence)}}
+         * returned in {@link AuthenticationCallback#onAuthenticationError(int, CharSequence)}}.
+         * Defaults to false.
          *
          * Note that {@link #setNegativeButton(CharSequence, Executor,
          * DialogInterface.OnClickListener)} should not be set if this is set to true.
@@ -264,7 +265,7 @@
          *               credentials (PIN, pattern, or password).
          * @return
          */
-        public Builder setAllowDeviceCredential(boolean enable) {
+        @NonNull public Builder setAllowDeviceCredential(boolean enable) {
             mBundle.putBoolean(KEY_ALLOW_DEVICE_CREDENTIAL, enable);
             return this;
         }
@@ -274,7 +275,7 @@
          * @return a {@link BiometricPrompt}
          * @throws IllegalArgumentException if any of the required fields are not set.
          */
-        public BiometricPrompt build() {
+        @NonNull public BiometricPrompt build() {
             final CharSequence title = mBundle.getCharSequence(KEY_TITLE);
             final CharSequence negative = mBundle.getCharSequence(KEY_NEGATIVE_TEXT);
             final boolean useDefaultTitle = mBundle.getBoolean(KEY_USE_DEFAULT_TITLE);
@@ -616,8 +617,15 @@
             mExecutor = executor;
             mAuthenticationCallback = callback;
             final long sessionId = crypto != null ? crypto.getOpId() : 0;
-            mService.authenticate(mToken, sessionId, userId, mBiometricServiceReceiver,
-                    mContext.getOpPackageName(), mBundle);
+            if (BiometricManager.hasBiometrics(mContext)) {
+                mService.authenticate(mToken, sessionId, userId, mBiometricServiceReceiver,
+                        mContext.getOpPackageName(), mBundle);
+            } else {
+                mExecutor.execute(() -> {
+                    callback.onAuthenticationError(BiometricPrompt.BIOMETRIC_ERROR_HW_NOT_PRESENT,
+                            mContext.getString(R.string.biometric_error_hw_unavailable));
+                });
+            }
         } catch (RemoteException e) {
             Log.e(TAG, "Remote exception while authenticating", e);
             mExecutor.execute(() -> {
diff --git a/core/java/android/hardware/biometrics/BiometricSourceType.java b/core/java/android/hardware/biometrics/BiometricSourceType.java
index 4a08cf2..f35958f 100644
--- a/core/java/android/hardware/biometrics/BiometricSourceType.java
+++ b/core/java/android/hardware/biometrics/BiometricSourceType.java
@@ -37,7 +37,7 @@
         dest.writeString(name());
     }
 
-    public static final Creator<BiometricSourceType> CREATOR = new Creator<BiometricSourceType>() {
+    public static final @android.annotation.NonNull Creator<BiometricSourceType> CREATOR = new Creator<BiometricSourceType>() {
         @Override
         public BiometricSourceType createFromParcel(final Parcel source) {
             return BiometricSourceType.valueOf(source.readString());
diff --git a/core/java/android/hardware/camera2/CameraCharacteristics.java b/core/java/android/hardware/camera2/CameraCharacteristics.java
index 0e4ff78..f7b7ef2 100644
--- a/core/java/android/hardware/camera2/CameraCharacteristics.java
+++ b/core/java/android/hardware/camera2/CameraCharacteristics.java
@@ -682,6 +682,7 @@
      * @see CaptureRequest#COLOR_CORRECTION_ABERRATION_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> COLOR_CORRECTION_AVAILABLE_ABERRATION_MODES =
             new Key<int[]>("android.colorCorrection.availableAberrationModes", int[].class);
 
@@ -700,6 +701,7 @@
      * @see CaptureRequest#CONTROL_AE_ANTIBANDING_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> CONTROL_AE_AVAILABLE_ANTIBANDING_MODES =
             new Key<int[]>("android.control.aeAvailableAntibandingModes", int[].class);
 
@@ -725,6 +727,7 @@
      * @see CaptureRequest#CONTROL_AE_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> CONTROL_AE_AVAILABLE_MODES =
             new Key<int[]>("android.control.aeAvailableModes", int[].class);
 
@@ -764,6 +767,7 @@
      * @see CaptureRequest#CONTROL_AE_TARGET_FPS_RANGE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Range<Integer>[]> CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES =
             new Key<android.util.Range<Integer>[]>("android.control.aeAvailableTargetFpsRanges", new TypeReference<android.util.Range<Integer>[]>() {{ }});
 
@@ -784,6 +788,7 @@
      * @see CaptureRequest#CONTROL_AE_EXPOSURE_COMPENSATION
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Range<Integer>> CONTROL_AE_COMPENSATION_RANGE =
             new Key<android.util.Range<Integer>>("android.control.aeCompensationRange", new TypeReference<android.util.Range<Integer>>() {{ }});
 
@@ -801,6 +806,7 @@
      * @see CaptureRequest#CONTROL_AE_EXPOSURE_COMPENSATION
      */
     @PublicKey
+    @NonNull
     public static final Key<Rational> CONTROL_AE_COMPENSATION_STEP =
             new Key<Rational>("android.control.aeCompensationStep", Rational.class);
 
@@ -825,6 +831,7 @@
      * @see CameraCharacteristics#LENS_INFO_MINIMUM_FOCUS_DISTANCE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> CONTROL_AF_AVAILABLE_MODES =
             new Key<int[]>("android.control.afAvailableModes", int[].class);
 
@@ -848,6 +855,7 @@
      * @see CaptureRequest#CONTROL_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> CONTROL_AVAILABLE_EFFECTS =
             new Key<int[]>("android.control.availableEffects", int[].class);
 
@@ -871,6 +879,7 @@
      * @see CameraCharacteristics#STATISTICS_INFO_MAX_FACE_COUNT
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> CONTROL_AVAILABLE_SCENE_MODES =
             new Key<int[]>("android.control.availableSceneModes", int[].class);
 
@@ -885,6 +894,7 @@
      * @see CaptureRequest#CONTROL_VIDEO_STABILIZATION_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES =
             new Key<int[]>("android.control.availableVideoStabilizationModes", int[].class);
 
@@ -909,6 +919,7 @@
      * @see CaptureRequest#CONTROL_AWB_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> CONTROL_AWB_AVAILABLE_MODES =
             new Key<int[]>("android.control.awbAvailableModes", int[].class);
 
@@ -945,6 +956,7 @@
      * @see CaptureRequest#CONTROL_AE_REGIONS
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<Integer> CONTROL_MAX_REGIONS_AE =
             new Key<Integer>("android.control.maxRegionsAe", int.class);
@@ -961,6 +973,7 @@
      * @see CaptureRequest#CONTROL_AWB_REGIONS
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<Integer> CONTROL_MAX_REGIONS_AWB =
             new Key<Integer>("android.control.maxRegionsAwb", int.class);
@@ -977,6 +990,7 @@
      * @see CaptureRequest#CONTROL_AF_REGIONS
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<Integer> CONTROL_MAX_REGIONS_AF =
             new Key<Integer>("android.control.maxRegionsAf", int.class);
@@ -1025,7 +1039,7 @@
      * normal capture session, or it will cause request error.</p>
      * <p><b>Range of valid values:</b><br></p>
      * <p>For each configuration, the fps_max &gt;= 120fps.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1046,6 +1060,7 @@
      * @see CaptureRequest#CONTROL_AE_LOCK
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> CONTROL_AE_LOCK_AVAILABLE =
             new Key<Boolean>("android.control.aeLockAvailable", boolean.class);
 
@@ -1058,6 +1073,7 @@
      * @see CaptureRequest#CONTROL_AWB_LOCK
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> CONTROL_AWB_LOCK_AVAILABLE =
             new Key<Boolean>("android.control.awbLockAvailable", boolean.class);
 
@@ -1074,6 +1090,7 @@
      * @see CaptureRequest#CONTROL_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> CONTROL_AVAILABLE_MODES =
             new Key<int[]>("android.control.availableModes", int[].class);
 
@@ -1088,12 +1105,13 @@
      * present, and if a device does not support post RAW sensitivity boost, it will
      * list <code>(100, 100)</code> in this key.</p>
      * <p><b>Units</b>: ISO arithmetic units, the same as {@link CaptureRequest#SENSOR_SENSITIVITY android.sensor.sensitivity}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#CONTROL_POST_RAW_SENSITIVITY_BOOST
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Range<Integer>> CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE =
             new Key<android.util.Range<Integer>>("android.control.postRawSensitivityBoostRange", new TypeReference<android.util.Range<Integer>>() {{ }});
 
@@ -1105,7 +1123,7 @@
      * list FAST.</p>
      * <p><b>Range of valid values:</b><br>
      * Any value listed in {@link CaptureRequest#EDGE_MODE android.edge.mode}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1114,6 +1132,7 @@
      * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> EDGE_AVAILABLE_EDGE_MODES =
             new Key<int[]>("android.edge.availableEdgeModes", int[].class);
 
@@ -1126,6 +1145,7 @@
      * This key is available on all devices.</p>
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> FLASH_INFO_AVAILABLE =
             new Key<Boolean>("android.flash.info.available", boolean.class);
 
@@ -1135,11 +1155,12 @@
      * <p>FULL mode camera devices will always support FAST.</p>
      * <p><b>Range of valid values:</b><br>
      * Any value listed in {@link CaptureRequest#HOT_PIXEL_MODE android.hotPixel.mode}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#HOT_PIXEL_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> HOT_PIXEL_AVAILABLE_HOT_PIXEL_MODES =
             new Key<int[]>("android.hotPixel.availableHotPixelModes", int[].class);
 
@@ -1167,6 +1188,7 @@
      * @see CaptureRequest#JPEG_THUMBNAIL_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Size[]> JPEG_AVAILABLE_THUMBNAIL_SIZES =
             new Key<android.util.Size[]>("android.jpeg.availableThumbnailSizes", android.util.Size[].class);
 
@@ -1178,7 +1200,7 @@
      * <p>If the camera device supports a variable aperture, the aperture values
      * in this list will be sorted in ascending order.</p>
      * <p><b>Units</b>: The aperture f-number</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1187,6 +1209,7 @@
      * @see CaptureRequest#LENS_APERTURE
      */
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_INFO_AVAILABLE_APERTURES =
             new Key<float[]>("android.lens.info.availableApertures", float[].class);
 
@@ -1199,7 +1222,7 @@
      * <p><b>Units</b>: Exposure value (EV)</p>
      * <p><b>Range of valid values:</b><br></p>
      * <p>Values are &gt;= 0</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1208,6 +1231,7 @@
      * @see CaptureRequest#LENS_FILTER_DENSITY
      */
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_INFO_AVAILABLE_FILTER_DENSITIES =
             new Key<float[]>("android.lens.info.availableFilterDensities", float[].class);
 
@@ -1226,6 +1250,7 @@
      * @see CaptureRequest#LENS_FOCAL_LENGTH
      */
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_INFO_AVAILABLE_FOCAL_LENGTHS =
             new Key<float[]>("android.lens.info.availableFocalLengths", float[].class);
 
@@ -1236,7 +1261,7 @@
      * contain only OFF.</p>
      * <p><b>Range of valid values:</b><br>
      * Any value listed in {@link CaptureRequest#LENS_OPTICAL_STABILIZATION_MODE android.lens.opticalStabilizationMode}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1245,6 +1270,7 @@
      * @see CaptureRequest#LENS_OPTICAL_STABILIZATION_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION =
             new Key<int[]>("android.lens.info.availableOpticalStabilization", int[].class);
 
@@ -1256,7 +1282,7 @@
      * <p><b>Range of valid values:</b><br>
      * If lens is fixed focus, &gt;= 0. If lens has focuser unit, the value is
      * within <code>(0.0f, {@link CameraCharacteristics#LENS_INFO_MINIMUM_FOCUS_DISTANCE android.lens.info.minimumFocusDistance}]</code></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1267,6 +1293,7 @@
      * @see CameraCharacteristics#LENS_INFO_MINIMUM_FOCUS_DISTANCE
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> LENS_INFO_HYPERFOCAL_DISTANCE =
             new Key<Float>("android.lens.info.hyperfocalDistance", float.class);
 
@@ -1278,7 +1305,7 @@
      * <p><b>Units</b>: See {@link CameraCharacteristics#LENS_INFO_FOCUS_DISTANCE_CALIBRATION android.lens.info.focusDistanceCalibration} for details</p>
      * <p><b>Range of valid values:</b><br>
      * &gt;= 0</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1288,6 +1315,7 @@
      * @see CameraCharacteristics#LENS_INFO_FOCUS_DISTANCE_CALIBRATION
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> LENS_INFO_MINIMUM_FOCUS_DISTANCE =
             new Key<Float>("android.lens.info.minimumFocusDistance", float.class);
 
@@ -1297,7 +1325,7 @@
      * must be smaller than 64x64.</p>
      * <p><b>Range of valid values:</b><br>
      * Both values &gt;= 1</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1329,7 +1357,7 @@
      *   <li>{@link #LENS_INFO_FOCUS_DISTANCE_CALIBRATION_APPROXIMATE APPROXIMATE}</li>
      *   <li>{@link #LENS_INFO_FOCUS_DISTANCE_CALIBRATION_CALIBRATED CALIBRATED}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1344,6 +1372,7 @@
      * @see #LENS_INFO_FOCUS_DISTANCE_CALIBRATION_CALIBRATED
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> LENS_INFO_FOCUS_DISTANCE_CALIBRATION =
             new Key<Integer>("android.lens.info.focusDistanceCalibration", int.class);
 
@@ -1362,6 +1391,7 @@
      * @see #LENS_FACING_EXTERNAL
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> LENS_FACING =
             new Key<Integer>("android.lens.facing", int.class);
 
@@ -1396,10 +1426,11 @@
      *  <code>p'</code> is in the camera-oriented coordinate system.</p>
      * <p><b>Units</b>:
      * Quaternion coefficients</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      */
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_POSE_ROTATION =
             new Key<float[]>("android.lens.poseRotation", float[].class);
 
@@ -1432,7 +1463,7 @@
      * the center of the primary gyroscope on the device. The axis definitions are the same as
      * with PRIMARY_CAMERA.</p>
      * <p><b>Units</b>: Meters</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#LENS_DISTORTION
@@ -1441,6 +1472,7 @@
      * @see CameraCharacteristics#LENS_POSE_ROTATION
      */
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_POSE_TRANSLATION =
             new Key<float[]>("android.lens.poseTranslation", float[].class);
 
@@ -1504,7 +1536,7 @@
      * Pixels in the
      * {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize}
      * coordinate system.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#LENS_DISTORTION
@@ -1514,6 +1546,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_INTRINSIC_CALIBRATION =
             new Key<float[]>("android.lens.intrinsicCalibration", float[].class);
 
@@ -1548,7 +1581,7 @@
      * <p>The distortion model used is the Brown-Conrady model.</p>
      * <p><b>Units</b>:
      * Unitless coefficients.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#LENS_INTRINSIC_CALIBRATION
@@ -1561,6 +1594,7 @@
      */
     @Deprecated
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_RADIAL_DISTORTION =
             new Key<float[]>("android.lens.radialDistortion", float[].class);
 
@@ -1573,7 +1607,7 @@
      *   <li>{@link #LENS_POSE_REFERENCE_PRIMARY_CAMERA PRIMARY_CAMERA}</li>
      *   <li>{@link #LENS_POSE_REFERENCE_GYROSCOPE GYROSCOPE}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#LENS_POSE_TRANSLATION
@@ -1581,6 +1615,7 @@
      * @see #LENS_POSE_REFERENCE_GYROSCOPE
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> LENS_POSE_REFERENCE =
             new Key<Integer>("android.lens.poseReference", int.class);
 
@@ -1615,13 +1650,14 @@
      * <p>The distortion model used is the Brown-Conrady model.</p>
      * <p><b>Units</b>:
      * Unitless coefficients.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#LENS_INTRINSIC_CALIBRATION
      * @see CameraCharacteristics#LENS_RADIAL_DISTORTION
      */
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_DISTORTION =
             new Key<float[]>("android.lens.distortion", float[].class);
 
@@ -1634,7 +1670,7 @@
      * <p>Legacy-capability camera devices will only support FAST mode.</p>
      * <p><b>Range of valid values:</b><br>
      * Any value listed in {@link CaptureRequest#NOISE_REDUCTION_MODE android.noiseReduction.mode}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1643,6 +1679,7 @@
      * @see CaptureRequest#NOISE_REDUCTION_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES =
             new Key<int[]>("android.noiseReduction.availableNoiseReductionModes", int[].class);
 
@@ -1655,7 +1692,7 @@
      * future versions of camera service. This quirk will stop
      * working at that point; DO NOT USE without careful
      * consideration of future support.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @deprecated
      * <p>Not used in HALv3 or newer; replaced by better partials mechanism</p>
 
@@ -1728,6 +1765,7 @@
      * @see CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<Integer> REQUEST_MAX_NUM_OUTPUT_RAW =
             new Key<Integer>("android.request.maxNumOutputRaw", int.class);
@@ -1764,6 +1802,7 @@
      * @see CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<Integer> REQUEST_MAX_NUM_OUTPUT_PROC =
             new Key<Integer>("android.request.maxNumOutputProc", int.class);
@@ -1790,6 +1829,7 @@
      * @see CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<Integer> REQUEST_MAX_NUM_OUTPUT_PROC_STALLING =
             new Key<Integer>("android.request.maxNumOutputProcStalling", int.class);
@@ -1809,7 +1849,7 @@
      * should be JPEG.</p>
      * <p><b>Range of valid values:</b><br></p>
      * <p>0 or 1.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1817,6 +1857,7 @@
      * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> REQUEST_MAX_NUM_INPUT_STREAMS =
             new Key<Integer>("android.request.maxNumInputStreams", int.class);
 
@@ -1841,6 +1882,7 @@
      * @see CaptureResult#REQUEST_PIPELINE_DEPTH
      */
     @PublicKey
+    @NonNull
     public static final Key<Byte> REQUEST_PIPELINE_MAX_DEPTH =
             new Key<Byte>("android.request.pipelineMaxDepth", byte.class);
 
@@ -1861,9 +1903,10 @@
      * partial results.</p>
      * <p><b>Range of valid values:</b><br>
      * &gt;= 1</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> REQUEST_PARTIAL_RESULT_COUNT =
             new Key<Integer>("android.request.partialResultCount", int.class);
 
@@ -1923,6 +1966,7 @@
      * @see #REQUEST_AVAILABLE_CAPABILITIES_SECURE_IMAGE_DATA
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> REQUEST_AVAILABLE_CAPABILITIES =
             new Key<int[]>("android.request.availableCapabilities", int[].class);
 
@@ -2036,7 +2080,7 @@
      * {@link CaptureRequest.Builder#getPhysicalCameraKey }. Capture requests that contain
      * individual physical device requests must be built via
      * {@link android.hardware.camera2.CameraDevice#createCaptureRequest(int, Set)}.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2067,7 +2111,7 @@
      * camera device for output streams.</p>
      * <p>All camera devices will support JPEG and YUV_420_888 formats.</p>
      * <p>When set to YUV_420_888, application can access the YUV420 data directly.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @deprecated
      * <p>Not used in HALv3 or newer</p>
 
@@ -2089,7 +2133,7 @@
      * <p><b>Units</b>: Nanoseconds</p>
      * <p><b>Range of valid values:</b><br>
      * TODO: Remove property.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @deprecated
      * <p>Not used in HALv3 or newer</p>
 
@@ -2105,7 +2149,7 @@
      * sensor maximum resolution (defined by {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize}).</p>
      * <p><b>Range of valid values:</b><br>
      * TODO: Remove property.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
      * @deprecated
@@ -2135,6 +2179,7 @@
      * @see CaptureRequest#SCALER_CROP_REGION
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> SCALER_AVAILABLE_MAX_DIGITAL_ZOOM =
             new Key<Float>("android.scaler.availableMaxDigitalZoom", float.class);
 
@@ -2148,7 +2193,7 @@
      * <p>When multiple streams are configured, the minimum frame duration will
      * be &gt;= max(individual stream min durations).</p>
      * <p><b>Units</b>: Nanoseconds</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @deprecated
      * <p>Not used in HALv3 or newer</p>
 
@@ -2172,7 +2217,7 @@
      * can provide.</p>
      * <p>Please reference the documentation for the image data destination to
      * check if it limits the maximum size for image data.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @deprecated
      * <p>Not used in HALv3 or newer</p>
 
@@ -2257,7 +2302,7 @@
      * </tr>
      * </tbody>
      * </table>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
      * @see CameraCharacteristics#REQUEST_MAX_NUM_INPUT_STREAMS
@@ -2551,6 +2596,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<android.hardware.camera2.params.StreamConfigurationMap> SCALER_STREAM_CONFIGURATION_MAP =
             new Key<android.hardware.camera2.params.StreamConfigurationMap>("android.scaler.streamConfigurationMap", android.hardware.camera2.params.StreamConfigurationMap.class);
@@ -2579,6 +2625,7 @@
      * @see #SCALER_CROPPING_TYPE_FREEFORM
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SCALER_CROPPING_TYPE =
             new Key<Integer>("android.scaler.croppingType", int.class);
 
@@ -2591,7 +2638,7 @@
      * power and performance efficient for specific use cases. For more information about
      * retrieving the suggestions see
      * {@link android.hardware.camera2.CameraCharacteristics#getRecommendedStreamConfigurationMap }.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @hide
      */
     public static final Key<android.hardware.camera2.params.RecommendedStreamConfiguration[]> SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS =
@@ -2607,7 +2654,7 @@
      * If set, the information will be available in the ZERO_SHUTTER_LAG recommended stream
      * configuration see
      * {@link android.hardware.camera2.CameraCharacteristics#getRecommendedStreamConfigurationMap }.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @hide
      */
     public static final Key<android.hardware.camera2.params.ReprocessFormatsMap> SCALER_AVAILABLE_RECOMMENDED_INPUT_OUTPUT_FORMATS_MAP =
@@ -2634,7 +2681,7 @@
      * physical camera not independently exposed in
      * {@link android.hardware.camera2.CameraManager#getCameraIdList } or is not backward
      * compatible.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2642,6 +2689,7 @@
      * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<android.hardware.camera2.params.MandatoryStreamCombination[]> SCALER_MANDATORY_STREAM_COMBINATIONS =
             new Key<android.hardware.camera2.params.MandatoryStreamCombination[]>("android.scaler.mandatoryStreamCombinations", android.hardware.camera2.params.MandatoryStreamCombination[].class);
@@ -2681,6 +2729,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.graphics.Rect> SENSOR_INFO_ACTIVE_ARRAY_SIZE =
             new Key<android.graphics.Rect>("android.sensor.info.activeArraySize", android.graphics.Rect.class);
 
@@ -2691,7 +2740,7 @@
      * as defined in ISO 12232:2006.</p>
      * <p><b>Range of valid values:</b><br>
      * Min &lt;= 100, Max &gt;= 800</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2700,6 +2749,7 @@
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Range<Integer>> SENSOR_INFO_SENSITIVITY_RANGE =
             new Key<android.util.Range<Integer>>("android.sensor.info.sensitivityRange", new TypeReference<android.util.Range<Integer>>() {{ }});
 
@@ -2718,7 +2768,7 @@
      *   <li>{@link #SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_MONO MONO}</li>
      *   <li>{@link #SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_NIR NIR}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2733,6 +2783,7 @@
      * @see #SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_NIR
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SENSOR_INFO_COLOR_FILTER_ARRANGEMENT =
             new Key<Integer>("android.sensor.info.colorFilterArrangement", int.class);
 
@@ -2744,7 +2795,7 @@
      * The minimum exposure time will be less than 100 us. For FULL
      * capability devices ({@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} == FULL),
      * the maximum exposure time will be greater than 100ms.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2753,6 +2804,7 @@
      * @see CaptureRequest#SENSOR_EXPOSURE_TIME
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Range<Long>> SENSOR_INFO_EXPOSURE_TIME_RANGE =
             new Key<android.util.Range<Long>>("android.sensor.info.exposureTimeRange", new TypeReference<android.util.Range<Long>>() {{ }});
 
@@ -2768,7 +2820,7 @@
      * <p><b>Range of valid values:</b><br>
      * For FULL capability devices
      * ({@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} == FULL), at least 100ms.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2777,6 +2829,7 @@
      * @see CaptureRequest#SENSOR_FRAME_DURATION
      */
     @PublicKey
+    @NonNull
     public static final Key<Long> SENSOR_INFO_MAX_FRAME_DURATION =
             new Key<Long>("android.sensor.info.maxFrameDuration", long.class);
 
@@ -2791,6 +2844,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PIXEL_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.SizeF> SENSOR_INFO_PHYSICAL_SIZE =
             new Key<android.util.SizeF>("android.sensor.info.physicalSize", android.util.SizeF.class);
 
@@ -2816,6 +2870,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Size> SENSOR_INFO_PIXEL_ARRAY_SIZE =
             new Key<android.util.Size>("android.sensor.info.pixelArraySize", android.util.Size.class);
 
@@ -2837,13 +2892,14 @@
      * by the camera device, which provides more accurate white level values.</p>
      * <p><b>Range of valid values:</b><br>
      * &gt; 255 (8-bit output)</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#SENSOR_BLACK_LEVEL_PATTERN
      * @see CaptureResult#SENSOR_DYNAMIC_WHITE_LEVEL
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SENSOR_INFO_WHITE_LEVEL =
             new Key<Integer>("android.sensor.info.whiteLevel", int.class);
 
@@ -2863,6 +2919,7 @@
      * @see #SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SENSOR_INFO_TIMESTAMP_SOURCE =
             new Key<Integer>("android.sensor.info.timestampSource", int.class);
 
@@ -2875,11 +2932,12 @@
      * See {@link CameraCharacteristics#REQUEST_MAX_NUM_OUTPUT_RAW android.request.maxNumOutputRaw} for a list of RAW image formats.</p>
      * <p>This key will be <code>null</code> for all devices do not report this information.
      * Devices with RAW capability will always report this information in this key.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#REQUEST_MAX_NUM_OUTPUT_RAW
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> SENSOR_INFO_LENS_SHADING_APPLIED =
             new Key<Boolean>("android.sensor.info.lensShadingApplied", boolean.class);
 
@@ -2945,6 +3003,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.graphics.Rect> SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE =
             new Key<android.graphics.Rect>("android.sensor.info.preCorrectionActiveArraySize", android.graphics.Rect.class);
 
@@ -2986,7 +3045,7 @@
      *   <li>{@link #SENSOR_REFERENCE_ILLUMINANT1_D50 D50}</li>
      *   <li>{@link #SENSOR_REFERENCE_ILLUMINANT1_ISO_STUDIO_TUNGSTEN ISO_STUDIO_TUNGSTEN}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#SENSOR_CALIBRATION_TRANSFORM1
@@ -3014,6 +3073,7 @@
      * @see #SENSOR_REFERENCE_ILLUMINANT1_ISO_STUDIO_TUNGSTEN
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SENSOR_REFERENCE_ILLUMINANT1 =
             new Key<Integer>("android.sensor.referenceIlluminant1", int.class);
 
@@ -3030,7 +3090,7 @@
      * the camera device has RAW capability.</p>
      * <p><b>Range of valid values:</b><br>
      * Any value listed in {@link CameraCharacteristics#SENSOR_REFERENCE_ILLUMINANT1 android.sensor.referenceIlluminant1}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#SENSOR_CALIBRATION_TRANSFORM2
@@ -3039,6 +3099,7 @@
      * @see CameraCharacteristics#SENSOR_REFERENCE_ILLUMINANT1
      */
     @PublicKey
+    @NonNull
     public static final Key<Byte> SENSOR_REFERENCE_ILLUMINANT2 =
             new Key<Byte>("android.sensor.referenceIlluminant2", byte.class);
 
@@ -3055,12 +3116,13 @@
      * ({@link CameraCharacteristics#SENSOR_REFERENCE_ILLUMINANT1 android.sensor.referenceIlluminant1}).</p>
      * <p>Starting from Android Q, this key will not be present for a MONOCHROME camera, even if
      * the camera device has RAW capability.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#SENSOR_REFERENCE_ILLUMINANT1
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_CALIBRATION_TRANSFORM1 =
             new Key<android.hardware.camera2.params.ColorSpaceTransform>("android.sensor.calibrationTransform1", android.hardware.camera2.params.ColorSpaceTransform.class);
 
@@ -3080,12 +3142,13 @@
      * illuminant is present.</p>
      * <p>Starting from Android Q, this key will not be present for a MONOCHROME camera, even if
      * the camera device has RAW capability.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#SENSOR_REFERENCE_ILLUMINANT2
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_CALIBRATION_TRANSFORM2 =
             new Key<android.hardware.camera2.params.ColorSpaceTransform>("android.sensor.calibrationTransform2", android.hardware.camera2.params.ColorSpaceTransform.class);
 
@@ -3106,12 +3169,13 @@
      * (i.e. no chromatic adaptation will be applied by this transform).</p>
      * <p>Starting from Android Q, this key will not be present for a MONOCHROME camera, even if
      * the camera device has RAW capability.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#SENSOR_REFERENCE_ILLUMINANT1
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_COLOR_TRANSFORM1 =
             new Key<android.hardware.camera2.params.ColorSpaceTransform>("android.sensor.colorTransform1", android.hardware.camera2.params.ColorSpaceTransform.class);
 
@@ -3134,12 +3198,13 @@
      * illuminant is present.</p>
      * <p>Starting from Android Q, this key will not be present for a MONOCHROME camera, even if
      * the camera device has RAW capability.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#SENSOR_REFERENCE_ILLUMINANT2
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_COLOR_TRANSFORM2 =
             new Key<android.hardware.camera2.params.ColorSpaceTransform>("android.sensor.colorTransform2", android.hardware.camera2.params.ColorSpaceTransform.class);
 
@@ -3158,12 +3223,13 @@
      * CIE XYZ colorspace.</p>
      * <p>Starting from Android Q, this key will not be present for a MONOCHROME camera, even if
      * the camera device has RAW capability.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#SENSOR_REFERENCE_ILLUMINANT1
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_FORWARD_MATRIX1 =
             new Key<android.hardware.camera2.params.ColorSpaceTransform>("android.sensor.forwardMatrix1", android.hardware.camera2.params.ColorSpaceTransform.class);
 
@@ -3184,12 +3250,13 @@
      * illuminant is present.</p>
      * <p>Starting from Android Q, this key will not be present for a MONOCHROME camera, even if
      * the camera device has RAW capability.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#SENSOR_REFERENCE_ILLUMINANT2
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.ColorSpaceTransform> SENSOR_FORWARD_MATRIX2 =
             new Key<android.hardware.camera2.params.ColorSpaceTransform>("android.sensor.forwardMatrix2", android.hardware.camera2.params.ColorSpaceTransform.class);
 
@@ -3215,7 +3282,7 @@
      * <p>For a MONOCHROME camera device, all of the 2x2 channels must have the same values.</p>
      * <p><b>Range of valid values:</b><br>
      * &gt;= 0 for each.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureResult#SENSOR_DYNAMIC_BLACK_LEVEL
      * @see CameraCharacteristics#SENSOR_INFO_COLOR_FILTER_ARRANGEMENT
@@ -3224,6 +3291,7 @@
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.BlackLevelPattern> SENSOR_BLACK_LEVEL_PATTERN =
             new Key<android.hardware.camera2.params.BlackLevelPattern>("android.sensor.blackLevelPattern", android.hardware.camera2.params.BlackLevelPattern.class);
 
@@ -3234,7 +3302,7 @@
      * equal to this, all applied gain must be analog. For
      * values above this, the gain applied can be a mix of analog and
      * digital.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3243,6 +3311,7 @@
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SENSOR_MAX_ANALOG_SENSITIVITY =
             new Key<Integer>("android.sensor.maxAnalogSensitivity", int.class);
 
@@ -3258,6 +3327,7 @@
      * <p>This key is available on all devices.</p>
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SENSOR_ORIENTATION =
             new Key<Integer>("android.sensor.orientation", int.class);
 
@@ -3267,11 +3337,12 @@
      * <p>Defaults to OFF, and always includes OFF if defined.</p>
      * <p><b>Range of valid values:</b><br>
      * Any value listed in {@link CaptureRequest#SENSOR_TEST_PATTERN_MODE android.sensor.testPatternMode}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#SENSOR_TEST_PATTERN_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> SENSOR_AVAILABLE_TEST_PATTERN_MODES =
             new Key<int[]>("android.sensor.availableTestPatternModes", int[].class);
 
@@ -3291,13 +3362,14 @@
      * black level of each captured raw images.</p>
      * <p>When this key is reported, the {@link CaptureResult#SENSOR_DYNAMIC_BLACK_LEVEL android.sensor.dynamicBlackLevel} and
      * {@link CaptureResult#SENSOR_DYNAMIC_WHITE_LEVEL android.sensor.dynamicWhiteLevel} will also be reported.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#SENSOR_BLACK_LEVEL_PATTERN
      * @see CaptureResult#SENSOR_DYNAMIC_BLACK_LEVEL
      * @see CaptureResult#SENSOR_DYNAMIC_WHITE_LEVEL
      */
     @PublicKey
+    @NonNull
     public static final Key<android.graphics.Rect[]> SENSOR_OPTICAL_BLACK_REGIONS =
             new Key<android.graphics.Rect[]>("android.sensor.opticalBlackRegions", android.graphics.Rect[].class);
 
@@ -3314,6 +3386,7 @@
      * @see CaptureRequest#SHADING_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> SHADING_AVAILABLE_MODES =
             new Key<int[]>("android.shading.availableModes", int[].class);
 
@@ -3328,6 +3401,7 @@
      * @see CaptureRequest#STATISTICS_FACE_DETECT_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES =
             new Key<int[]>("android.statistics.info.availableFaceDetectModes", int[].class);
 
@@ -3341,6 +3415,7 @@
      * <p>This key is available on all devices.</p>
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> STATISTICS_INFO_MAX_FACE_COUNT =
             new Key<Integer>("android.statistics.info.maxFaceCount", int.class);
 
@@ -3352,11 +3427,12 @@
      * <p>ON is always supported on devices with the RAW capability.</p>
      * <p><b>Range of valid values:</b><br>
      * Any value listed in {@link CaptureRequest#STATISTICS_HOT_PIXEL_MAP_MODE android.statistics.hotPixelMapMode}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#STATISTICS_HOT_PIXEL_MAP_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<boolean[]> STATISTICS_INFO_AVAILABLE_HOT_PIXEL_MAP_MODES =
             new Key<boolean[]>("android.statistics.info.availableHotPixelMapModes", boolean[].class);
 
@@ -3369,11 +3445,12 @@
      * LEGACY mode devices will always only support OFF.</p>
      * <p><b>Range of valid values:</b><br>
      * Any value listed in {@link CaptureRequest#STATISTICS_LENS_SHADING_MAP_MODE android.statistics.lensShadingMapMode}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#STATISTICS_LENS_SHADING_MAP_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> STATISTICS_INFO_AVAILABLE_LENS_SHADING_MAP_MODES =
             new Key<int[]>("android.statistics.info.availableLensShadingMapModes", int[].class);
 
@@ -3384,11 +3461,12 @@
      * contain only OFF.</p>
      * <p><b>Range of valid values:</b><br>
      * Any value listed in {@link CaptureRequest#STATISTICS_OIS_DATA_MODE android.statistics.oisDataMode}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#STATISTICS_OIS_DATA_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> STATISTICS_INFO_AVAILABLE_OIS_DATA_MODES =
             new Key<int[]>("android.statistics.info.availableOisDataModes", int[].class);
 
@@ -3401,7 +3479,7 @@
      * <p>The output curves in the result metadata may have a different number
      * of points than the input curves, and will represent the actual
      * hardware curves used as closely as possible when linearly interpolated.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3410,6 +3488,7 @@
      * @see CaptureRequest#TONEMAP_CURVE
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> TONEMAP_MAX_CURVE_POINTS =
             new Key<Integer>("android.tonemap.maxCurvePoints", int.class);
 
@@ -3425,7 +3504,7 @@
      * <p>This includes all FULL level devices.</p>
      * <p><b>Range of valid values:</b><br>
      * Any value listed in {@link CaptureRequest#TONEMAP_MODE android.tonemap.mode}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3434,6 +3513,7 @@
      * @see CaptureRequest#TONEMAP_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> TONEMAP_AVAILABLE_TONE_MAP_MODES =
             new Key<int[]>("android.tonemap.availableToneMapModes", int[].class);
 
@@ -3443,7 +3523,7 @@
      * <ul>
      *   <li>{@link #LED_AVAILABLE_LEDS_TRANSMIT TRANSMIT}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @see #LED_AVAILABLE_LEDS_TRANSMIT
      * @hide
      */
@@ -3534,6 +3614,7 @@
      * @see #INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> INFO_SUPPORTED_HARDWARE_LEVEL =
             new Key<Integer>("android.info.supportedHardwareLevel", int.class);
 
@@ -3543,9 +3624,10 @@
      * <p>This can be used in {@link android.media.ExifInterface#TAG_IMAGE_DESCRIPTION TAG_IMAGE_DESCRIPTION}
      * in jpeg EXIF. This key may be absent if no version information is available on the
      * device.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      */
     @PublicKey
+    @NonNull
     public static final Key<String> INFO_VERSION =
             new Key<String>("android.info.version", String.class);
 
@@ -3572,6 +3654,7 @@
      * @see #SYNC_MAX_LATENCY_UNKNOWN
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SYNC_MAX_LATENCY =
             new Key<Integer>("android.sync.maxLatency", int.class);
 
@@ -3598,7 +3681,7 @@
      * <p><b>Units</b>: Number of frames.</p>
      * <p><b>Range of valid values:</b><br>
      * &lt;= 4</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3607,6 +3690,7 @@
      * @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> REPROCESS_MAX_CAPTURE_STALL =
             new Key<Integer>("android.reprocess.maxCaptureStall", int.class);
 
@@ -3625,7 +3709,7 @@
      * the format in this list as <code>(HAL_PIXEL_FORMAT_BLOB,
      * android.depth.maxDepthSamples, 1, OUTPUT)</code> in addition to
      * the entries for HAL_PIXEL_FORMAT_Y16.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3650,7 +3734,7 @@
      * android.scaler.availableStallDurations for more details about
      * calculating the max frame rate.</p>
      * <p><b>Units</b>: (format, width, height, ns) x n</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3674,7 +3758,7 @@
      * <p>All depth output stream formats may have a nonzero stall
      * duration.</p>
      * <p><b>Units</b>: (format, width, height, ns) x n</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3697,7 +3781,7 @@
      * need to emit a specific pattern or wavelength of light to
      * measure depth values, which causes the color image to be
      * corrupted during depth measurement.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3705,6 +3789,7 @@
      * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> DEPTH_DEPTH_IS_EXCLUSIVE =
             new Key<Boolean>("android.depth.depthIsExclusive", boolean.class);
 
@@ -3717,7 +3802,7 @@
      * power and performance efficient for specific use cases. For more information about
      * retrieving the suggestions see
      * {@link android.hardware.camera2.CameraCharacteristics#getRecommendedStreamConfigurationMap }.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @hide
      */
     public static final Key<android.hardware.camera2.params.RecommendedStreamConfiguration[]> DEPTH_AVAILABLE_RECOMMENDED_DEPTH_STREAM_CONFIGURATIONS =
@@ -3736,7 +3821,7 @@
      * the same aspect ratio can have dynamic depth dataspace
      * stream configuration. {@link CameraCharacteristics#DEPTH_DEPTH_IS_EXCLUSIVE android.depth.depthIsExclusive} also
      * needs to be set to FALSE.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#DEPTH_DEPTH_IS_EXCLUSIVE
      * @hide
@@ -3755,7 +3840,7 @@
      * <p>The minimum frame duration of a stream (of a particular format, size)
      * is the same regardless of whether the stream is input or output.</p>
      * <p><b>Units</b>: (format, width, height, ns) x n</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @hide
      */
     public static final Key<android.hardware.camera2.params.StreamConfigurationDuration[]> DEPTH_AVAILABLE_DYNAMIC_DEPTH_MIN_FRAME_DURATIONS =
@@ -3770,7 +3855,7 @@
      * <p>All dynamic depth output streams may have a nonzero stall
      * duration.</p>
      * <p><b>Units</b>: (format, width, height, ns) x n</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @hide
      */
     public static final Key<android.hardware.camera2.params.StreamConfigurationDuration[]> DEPTH_AVAILABLE_DYNAMIC_DEPTH_STALL_DURATIONS =
@@ -3785,7 +3870,7 @@
      * value of this tag will be ['2', '\0', '3', '\0'].</p>
      * <p>The number of physical camera IDs must be no less than 2.</p>
      * <p><b>Units</b>: UTF-8 null-terminated string</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3811,7 +3896,7 @@
      *   <li>{@link #LOGICAL_MULTI_CAMERA_SENSOR_SYNC_TYPE_APPROXIMATE APPROXIMATE}</li>
      *   <li>{@link #LOGICAL_MULTI_CAMERA_SENSOR_SYNC_TYPE_CALIBRATED CALIBRATED}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3821,6 +3906,7 @@
      * @see #LOGICAL_MULTI_CAMERA_SENSOR_SYNC_TYPE_CALIBRATED
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> LOGICAL_MULTI_CAMERA_SENSOR_SYNC_TYPE =
             new Key<Integer>("android.logicalMultiCamera.sensorSyncType", int.class);
 
@@ -3831,11 +3917,12 @@
      * All devices that support this API will list both FAST and HIGH_QUALITY.</p>
      * <p><b>Range of valid values:</b><br>
      * Any value listed in {@link CaptureRequest#DISTORTION_CORRECTION_MODE android.distortionCorrection.mode}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#DISTORTION_CORRECTION_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> DISTORTION_CORRECTION_AVAILABLE_MODES =
             new Key<int[]>("android.distortionCorrection.availableModes", int[].class);
 
@@ -3849,7 +3936,7 @@
      * image format as required by the device's hardware level and capabilities.</p>
      * <p>All the static, control, and dynamic metadata tags related to JPEG apply to HEIC formats.
      * Configuring JPEG and HEIC streams at the same time is not supported.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3872,7 +3959,7 @@
      * android.scaler.availableStallDurations for more details about
      * calculating the max frame rate.</p>
      * <p><b>Units</b>: (format, width, height, ns) x n</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3896,7 +3983,7 @@
      * <p>All HEIC output stream formats may have a nonzero stall
      * duration.</p>
      * <p><b>Units</b>: (format, width, height, ns) x n</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3913,4 +4000,7 @@
 
 
 
+
+
+
 }
diff --git a/core/java/android/hardware/camera2/CaptureRequest.java b/core/java/android/hardware/camera2/CaptureRequest.java
index 5250701..da1bfe4 100644
--- a/core/java/android/hardware/camera2/CaptureRequest.java
+++ b/core/java/android/hardware/camera2/CaptureRequest.java
@@ -493,7 +493,7 @@
         return HashCodeHelpers.hashCodeGeneric(mPhysicalCameraSettings, mSurfaceSet, mUserTag);
     }
 
-    public static final Parcelable.Creator<CaptureRequest> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CaptureRequest> CREATOR =
             new Parcelable.Creator<CaptureRequest>() {
         @Override
         public CaptureRequest createFromParcel(Parcel in) {
@@ -978,7 +978,7 @@
      *   <li>{@link #COLOR_CORRECTION_MODE_FAST FAST}</li>
      *   <li>{@link #COLOR_CORRECTION_MODE_HIGH_QUALITY HIGH_QUALITY}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -992,6 +992,7 @@
      * @see #COLOR_CORRECTION_MODE_HIGH_QUALITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> COLOR_CORRECTION_MODE =
             new Key<Integer>("android.colorCorrection.mode", int.class);
 
@@ -1010,7 +1011,7 @@
      * <p>The valid range of each matrix element varies on different devices, but
      * values within [-1.5, 3.0] are guaranteed not to be clipped.</p>
      * <p><b>Units</b>: Unitless scale factors</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1019,6 +1020,7 @@
      * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.ColorSpaceTransform> COLOR_CORRECTION_TRANSFORM =
             new Key<android.hardware.camera2.params.ColorSpaceTransform>("android.colorCorrection.transform", android.hardware.camera2.params.ColorSpaceTransform.class);
 
@@ -1037,7 +1039,7 @@
      * device allows gains below 1.0, this is usually not recommended because
      * this can create color artifacts.</p>
      * <p><b>Units</b>: Unitless gain factors</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1046,6 +1048,7 @@
      * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.RggbChannelVector> COLOR_CORRECTION_GAINS =
             new Key<android.hardware.camera2.params.RggbChannelVector>("android.colorCorrection.gains", android.hardware.camera2.params.RggbChannelVector.class);
 
@@ -1078,6 +1081,7 @@
      * @see #COLOR_CORRECTION_ABERRATION_MODE_HIGH_QUALITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> COLOR_CORRECTION_ABERRATION_MODE =
             new Key<Integer>("android.colorCorrection.aberrationMode", int.class);
 
@@ -1134,6 +1138,7 @@
      * @see #CONTROL_AE_ANTIBANDING_MODE_AUTO
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AE_ANTIBANDING_MODE =
             new Key<Integer>("android.control.aeAntibandingMode", int.class);
 
@@ -1167,6 +1172,7 @@
      * @see CaptureResult#CONTROL_AE_STATE
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AE_EXPOSURE_COMPENSATION =
             new Key<Integer>("android.control.aeExposureCompensation", int.class);
 
@@ -1217,6 +1223,7 @@
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> CONTROL_AE_LOCK =
             new Key<Boolean>("android.control.aeLock", boolean.class);
 
@@ -1269,6 +1276,7 @@
      * @see #CONTROL_AE_MODE_ON_EXTERNAL_FLASH
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AE_MODE =
             new Key<Integer>("android.control.aeMode", int.class);
 
@@ -1320,7 +1328,7 @@
      * Coordinates must be between <code>[(0,0), (width, height))</code> of
      * {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize}
      * depending on distortion correction capability and mode</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#CONTROL_MAX_REGIONS_AE
      * @see CaptureRequest#DISTORTION_CORRECTION_MODE
@@ -1329,6 +1337,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AE_REGIONS =
             new Key<android.hardware.camera2.params.MeteringRectangle[]>("android.control.aeRegions", android.hardware.camera2.params.MeteringRectangle[].class);
 
@@ -1349,6 +1358,7 @@
      * @see CaptureRequest#SENSOR_FRAME_DURATION
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Range<Integer>> CONTROL_AE_TARGET_FPS_RANGE =
             new Key<android.util.Range<Integer>>("android.control.aeTargetFpsRange", new TypeReference<android.util.Range<Integer>>() {{ }});
 
@@ -1407,7 +1417,7 @@
      *   <li>{@link #CONTROL_AE_PRECAPTURE_TRIGGER_START START}</li>
      *   <li>{@link #CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL CANCEL}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1422,6 +1432,7 @@
      * @see #CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AE_PRECAPTURE_TRIGGER =
             new Key<Integer>("android.control.aePrecaptureTrigger", int.class);
 
@@ -1463,6 +1474,7 @@
      * @see #CONTROL_AF_MODE_EDOF
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AF_MODE =
             new Key<Integer>("android.control.afMode", int.class);
 
@@ -1515,7 +1527,7 @@
      * Coordinates must be between <code>[(0,0), (width, height))</code> of
      * {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize}
      * depending on distortion correction capability and mode</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#CONTROL_MAX_REGIONS_AF
      * @see CaptureRequest#DISTORTION_CORRECTION_MODE
@@ -1524,6 +1536,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AF_REGIONS =
             new Key<android.hardware.camera2.params.MeteringRectangle[]>("android.control.afRegions", android.hardware.camera2.params.MeteringRectangle[].class);
 
@@ -1561,6 +1574,7 @@
      * @see #CONTROL_AF_TRIGGER_CANCEL
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AF_TRIGGER =
             new Key<Integer>("android.control.afTrigger", int.class);
 
@@ -1591,6 +1605,7 @@
      * @see CaptureRequest#CONTROL_AWB_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> CONTROL_AWB_LOCK =
             new Key<Boolean>("android.control.awbLock", boolean.class);
 
@@ -1651,6 +1666,7 @@
      * @see #CONTROL_AWB_MODE_SHADE
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AWB_MODE =
             new Key<Integer>("android.control.awbMode", int.class);
 
@@ -1703,7 +1719,7 @@
      * Coordinates must be between <code>[(0,0), (width, height))</code> of
      * {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize}
      * depending on distortion correction capability and mode</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#CONTROL_MAX_REGIONS_AWB
      * @see CaptureRequest#DISTORTION_CORRECTION_MODE
@@ -1712,6 +1728,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AWB_REGIONS =
             new Key<android.hardware.camera2.params.MeteringRectangle[]>("android.control.awbRegions", android.hardware.camera2.params.MeteringRectangle[].class);
 
@@ -1754,6 +1771,7 @@
      * @see #CONTROL_CAPTURE_INTENT_MOTION_TRACKING
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_CAPTURE_INTENT =
             new Key<Integer>("android.control.captureIntent", int.class);
 
@@ -1793,6 +1811,7 @@
      * @see #CONTROL_EFFECT_MODE_AQUA
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_EFFECT_MODE =
             new Key<Integer>("android.control.effectMode", int.class);
 
@@ -1833,6 +1852,7 @@
      * @see #CONTROL_MODE_OFF_KEEP_STATE
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_MODE =
             new Key<Integer>("android.control.mode", int.class);
 
@@ -1900,6 +1920,7 @@
      * @see #CONTROL_SCENE_MODE_HDR
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_SCENE_MODE =
             new Key<Integer>("android.control.sceneMode", int.class);
 
@@ -1943,6 +1964,7 @@
      * @see #CONTROL_VIDEO_STABILIZATION_MODE_ON
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_VIDEO_STABILIZATION_MODE =
             new Key<Integer>("android.control.videoStabilizationMode", int.class);
 
@@ -1969,7 +1991,7 @@
      * <p><b>Units</b>: ISO arithmetic units, the same as {@link CaptureRequest#SENSOR_SENSITIVITY android.sensor.sensitivity}</p>
      * <p><b>Range of valid values:</b><br>
      * {@link CameraCharacteristics#CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE android.control.postRawSensitivityBoostRange}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#CONTROL_AE_MODE
      * @see CaptureRequest#CONTROL_MODE
@@ -1978,6 +2000,7 @@
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_POST_RAW_SENSITIVITY_BOOST =
             new Key<Integer>("android.control.postRawSensitivityBoost", int.class);
 
@@ -2005,12 +2028,13 @@
      * <p>For applications targeting SDK versions older than O, the value of enableZsl in all
      * capture templates is always <code>false</code> if present.</p>
      * <p>For application-operated ZSL, use CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG template.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#CONTROL_CAPTURE_INTENT
      * @see CaptureResult#SENSOR_TIMESTAMP
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> CONTROL_ENABLE_ZSL =
             new Key<Boolean>("android.control.enableZsl", boolean.class);
 
@@ -2045,7 +2069,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#EDGE_AVAILABLE_EDGE_MODES android.edge.availableEdgeModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2059,6 +2083,7 @@
      * @see #EDGE_MODE_ZERO_SHUTTER_LAG
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> EDGE_MODE =
             new Key<Integer>("android.edge.mode", int.class);
 
@@ -2094,6 +2119,7 @@
      * @see #FLASH_MODE_TORCH
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> FLASH_MODE =
             new Key<Integer>("android.flash.mode", int.class);
 
@@ -2110,7 +2136,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#HOT_PIXEL_AVAILABLE_HOT_PIXEL_MODES android.hotPixel.availableHotPixelModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#HOT_PIXEL_AVAILABLE_HOT_PIXEL_MODES
      * @see #HOT_PIXEL_MODE_OFF
@@ -2118,6 +2144,7 @@
      * @see #HOT_PIXEL_MODE_HIGH_QUALITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> HOT_PIXEL_MODE =
             new Key<Integer>("android.hotPixel.mode", int.class);
 
@@ -2130,6 +2157,7 @@
      * <p>This key is available on all devices.</p>
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<android.location.Location> JPEG_GPS_LOCATION =
             new Key<android.location.Location>("android.jpeg.gpsLocation", android.location.Location.class);
@@ -2211,6 +2239,7 @@
      * @see CameraCharacteristics#SENSOR_ORIENTATION
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> JPEG_ORIENTATION =
             new Key<Integer>("android.jpeg.orientation", int.class);
 
@@ -2224,6 +2253,7 @@
      * <p>This key is available on all devices.</p>
      */
     @PublicKey
+    @NonNull
     public static final Key<Byte> JPEG_QUALITY =
             new Key<Byte>("android.jpeg.quality", byte.class);
 
@@ -2236,6 +2266,7 @@
      * <p>This key is available on all devices.</p>
      */
     @PublicKey
+    @NonNull
     public static final Key<Byte> JPEG_THUMBNAIL_QUALITY =
             new Key<Byte>("android.jpeg.thumbnailQuality", byte.class);
 
@@ -2275,6 +2306,7 @@
      * @see CaptureRequest#JPEG_ORIENTATION
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Size> JPEG_THUMBNAIL_SIZE =
             new Key<android.util.Size>("android.jpeg.thumbnailSize", android.util.Size.class);
 
@@ -2298,7 +2330,7 @@
      * <p><b>Units</b>: The f-number (f/N)</p>
      * <p><b>Range of valid values:</b><br>
      * {@link CameraCharacteristics#LENS_INFO_AVAILABLE_APERTURES android.lens.info.availableApertures}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2312,6 +2344,7 @@
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> LENS_APERTURE =
             new Key<Float>("android.lens.aperture", float.class);
 
@@ -2332,7 +2365,7 @@
      * <p><b>Units</b>: Exposure Value (EV)</p>
      * <p><b>Range of valid values:</b><br>
      * {@link CameraCharacteristics#LENS_INFO_AVAILABLE_FILTER_DENSITIES android.lens.info.availableFilterDensities}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2342,6 +2375,7 @@
      * @see CaptureResult#LENS_STATE
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> LENS_FILTER_DENSITY =
             new Key<Float>("android.lens.filterDensity", float.class);
 
@@ -2367,6 +2401,7 @@
      * @see CaptureResult#LENS_STATE
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> LENS_FOCAL_LENGTH =
             new Key<Float>("android.lens.focalLength", float.class);
 
@@ -2387,7 +2422,7 @@
      * <p><b>Units</b>: See {@link CameraCharacteristics#LENS_INFO_FOCUS_DISTANCE_CALIBRATION android.lens.info.focusDistanceCalibration} for details</p>
      * <p><b>Range of valid values:</b><br>
      * &gt;= 0</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2399,6 +2434,7 @@
      * @see CaptureResult#LENS_STATE
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> LENS_FOCUS_DISTANCE =
             new Key<Float>("android.lens.focusDistance", float.class);
 
@@ -2429,7 +2465,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION android.lens.info.availableOpticalStabilization}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2441,6 +2477,7 @@
      * @see #LENS_OPTICAL_STABILIZATION_MODE_ON
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> LENS_OPTICAL_STABILIZATION_MODE =
             new Key<Integer>("android.lens.opticalStabilizationMode", int.class);
 
@@ -2481,7 +2518,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES android.noiseReduction.availableNoiseReductionModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2496,6 +2533,7 @@
      * @see #NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> NOISE_REDUCTION_MODE =
             new Key<Integer>("android.noiseReduction.mode", int.class);
 
@@ -2506,7 +2544,7 @@
      * <p><b>Units</b>: arbitrary integer assigned by application</p>
      * <p><b>Range of valid values:</b><br>
      * Any int</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @hide
      */
     public static final Key<Integer> REQUEST_ID =
@@ -2570,6 +2608,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.graphics.Rect> SCALER_CROP_REGION =
             new Key<android.graphics.Rect>("android.scaler.cropRegion", android.graphics.Rect.class);
 
@@ -2584,7 +2623,7 @@
      * <p><b>Units</b>: Nanoseconds</p>
      * <p><b>Range of valid values:</b><br>
      * {@link CameraCharacteristics#SENSOR_INFO_EXPOSURE_TIME_RANGE android.sensor.info.exposureTimeRange}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2595,6 +2634,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_EXPOSURE_TIME_RANGE
      */
     @PublicKey
+    @NonNull
     public static final Key<Long> SENSOR_EXPOSURE_TIME =
             new Key<Long>("android.sensor.exposureTime", long.class);
 
@@ -2665,7 +2705,7 @@
      * <p><b>Range of valid values:</b><br>
      * See {@link CameraCharacteristics#SENSOR_INFO_MAX_FRAME_DURATION android.sensor.info.maxFrameDuration}, {@link android.hardware.camera2.params.StreamConfigurationMap }.
      * The duration is capped to <code>max(duration, exposureTime + overhead)</code>.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2676,6 +2716,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_MAX_FRAME_DURATION
      */
     @PublicKey
+    @NonNull
     public static final Key<Long> SENSOR_FRAME_DURATION =
             new Key<Long>("android.sensor.frameDuration", long.class);
 
@@ -2696,7 +2737,7 @@
      * <p><b>Units</b>: ISO arithmetic units</p>
      * <p><b>Range of valid values:</b><br>
      * {@link CameraCharacteristics#SENSOR_INFO_SENSITIVITY_RANGE android.sensor.info.sensitivityRange}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2708,6 +2749,7 @@
      * @see CameraCharacteristics#SENSOR_MAX_ANALOG_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SENSOR_SENSITIVITY =
             new Key<Integer>("android.sensor.sensitivity", int.class);
 
@@ -2720,11 +2762,12 @@
      * output.</p>
      * <p>For example, a sensor with RAW10 Bayer output would use the
      * 10 most significant bits from each color channel.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#SENSOR_TEST_PATTERN_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> SENSOR_TEST_PATTERN_DATA =
             new Key<int[]>("android.sensor.testPatternData", int[].class);
 
@@ -2749,7 +2792,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#SENSOR_AVAILABLE_TEST_PATTERN_MODES android.sensor.availableTestPatternModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#SENSOR_AVAILABLE_TEST_PATTERN_MODES
      * @see #SENSOR_TEST_PATTERN_MODE_OFF
@@ -2760,6 +2803,7 @@
      * @see #SENSOR_TEST_PATTERN_MODE_CUSTOM1
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SENSOR_TEST_PATTERN_MODE =
             new Key<Integer>("android.sensor.testPatternMode", int.class);
 
@@ -2797,7 +2841,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#SHADING_AVAILABLE_MODES android.shading.availableModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2813,6 +2857,7 @@
      * @see #SHADING_MODE_HIGH_QUALITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SHADING_MODE =
             new Key<Integer>("android.shading.mode", int.class);
 
@@ -2838,6 +2883,7 @@
      * @see #STATISTICS_FACE_DETECT_MODE_FULL
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> STATISTICS_FACE_DETECT_MODE =
             new Key<Integer>("android.statistics.faceDetectMode", int.class);
 
@@ -2847,12 +2893,13 @@
      * If set to <code>false</code>, no hot pixel map will be returned.</p>
      * <p><b>Range of valid values:</b><br>
      * {@link CameraCharacteristics#STATISTICS_INFO_AVAILABLE_HOT_PIXEL_MAP_MODES android.statistics.info.availableHotPixelMapModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureResult#STATISTICS_HOT_PIXEL_MAP
      * @see CameraCharacteristics#STATISTICS_INFO_AVAILABLE_HOT_PIXEL_MAP_MODES
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> STATISTICS_HOT_PIXEL_MAP_MODE =
             new Key<Boolean>("android.statistics.hotPixelMapMode", boolean.class);
 
@@ -2870,7 +2917,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#STATISTICS_INFO_AVAILABLE_LENS_SHADING_MAP_MODES android.statistics.info.availableLensShadingMapModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2881,6 +2928,7 @@
      * @see #STATISTICS_LENS_SHADING_MAP_MODE_ON
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> STATISTICS_LENS_SHADING_MAP_MODE =
             new Key<Integer>("android.statistics.lensShadingMapMode", int.class);
 
@@ -2900,13 +2948,14 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#STATISTICS_INFO_AVAILABLE_OIS_DATA_MODES android.statistics.info.availableOisDataModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#STATISTICS_INFO_AVAILABLE_OIS_DATA_MODES
      * @see #STATISTICS_OIS_DATA_MODE_OFF
      * @see #STATISTICS_OIS_DATA_MODE_ON
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> STATISTICS_OIS_DATA_MODE =
             new Key<Integer>("android.statistics.oisDataMode", int.class);
 
@@ -2915,7 +2964,7 @@
      * channel, to use when {@link CaptureRequest#TONEMAP_MODE android.tonemap.mode} is
      * CONTRAST_CURVE.</p>
      * <p>See android.tonemap.curveRed for more details.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2932,7 +2981,7 @@
      * channel, to use when {@link CaptureRequest#TONEMAP_MODE android.tonemap.mode} is
      * CONTRAST_CURVE.</p>
      * <p>See android.tonemap.curveRed for more details.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2993,7 +3042,7 @@
      * <p><b>Range of valid values:</b><br>
      * 0-1 on both input and output coordinates, normalized
      * as a floating-point value such that 0 == black and 1 == white.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3054,7 +3103,7 @@
      *   (0.8000, 0.9063), (0.8667, 0.9389), (0.9333, 0.9701), (1.0000, 1.0000) ]
      * </code></pre>
      * <p><img alt="sRGB tonemapping curve" src="/reference/images/camera2/metadata/android.tonemap.curveRed/srgb_tonemap.png" /></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3064,6 +3113,7 @@
      * @see CaptureRequest#TONEMAP_MODE
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<android.hardware.camera2.params.TonemapCurve> TONEMAP_CURVE =
             new Key<android.hardware.camera2.params.TonemapCurve>("android.tonemap.curve", android.hardware.camera2.params.TonemapCurve.class);
@@ -3098,7 +3148,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#TONEMAP_AVAILABLE_TONE_MAP_MODES android.tonemap.availableToneMapModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3114,6 +3164,7 @@
      * @see #TONEMAP_MODE_PRESET_CURVE
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> TONEMAP_MODE =
             new Key<Integer>("android.tonemap.mode", int.class);
 
@@ -3130,11 +3181,12 @@
      * value will be returned in capture result.</p>
      * <p>The valid range of gamma value varies on different devices, but values
      * within [1.0, 5.0] are guaranteed not to be clipped.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#TONEMAP_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> TONEMAP_GAMMA =
             new Key<Float>("android.tonemap.gamma", float.class);
 
@@ -3153,13 +3205,14 @@
      *   <li>{@link #TONEMAP_PRESET_CURVE_SRGB SRGB}</li>
      *   <li>{@link #TONEMAP_PRESET_CURVE_REC709 REC709}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#TONEMAP_MODE
      * @see #TONEMAP_PRESET_CURVE_SRGB
      * @see #TONEMAP_PRESET_CURVE_REC709
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> TONEMAP_PRESET_CURVE =
             new Key<Integer>("android.tonemap.presetCurve", int.class);
 
@@ -3174,7 +3227,7 @@
      * data is stored locally on the device.</p>
      * <p>The LED <em>may</em> be off if a trusted application is using the data that
      * doesn't violate the above rules.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @hide
      */
     public static final Key<Boolean> LED_TRANSMIT =
@@ -3218,7 +3271,7 @@
      * possible, only overriding the lock to OFF when changes to
      * other request parameters require a black level recalculation
      * or reset.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3226,6 +3279,7 @@
      * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> BLACK_LEVEL_LOCK =
             new Key<Boolean>("android.blackLevel.lock", boolean.class);
 
@@ -3265,7 +3319,7 @@
      * <p><b>Units</b>: Relative exposure time increase factor.</p>
      * <p><b>Range of valid values:</b><br>
      * &gt;= 1.0</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3276,6 +3330,7 @@
      * @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> REPROCESS_EFFECTIVE_EXPOSURE_FACTOR =
             new Key<Float>("android.reprocess.effectiveExposureFactor", float.class);
 
@@ -3322,7 +3377,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#DISTORTION_CORRECTION_AVAILABLE_MODES android.distortionCorrection.availableModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#CONTROL_AE_REGIONS
      * @see CaptureRequest#CONTROL_AF_REGIONS
@@ -3338,6 +3393,7 @@
      * @see #DISTORTION_CORRECTION_MODE_HIGH_QUALITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> DISTORTION_CORRECTION_MODE =
             new Key<Integer>("android.distortionCorrection.mode", int.class);
 
@@ -3347,4 +3403,7 @@
 
 
 
+
+
+
 }
diff --git a/core/java/android/hardware/camera2/CaptureResult.java b/core/java/android/hardware/camera2/CaptureResult.java
index 13ad092..0900f3b 100644
--- a/core/java/android/hardware/camera2/CaptureResult.java
+++ b/core/java/android/hardware/camera2/CaptureResult.java
@@ -437,7 +437,7 @@
      *   <li>{@link #COLOR_CORRECTION_MODE_FAST FAST}</li>
      *   <li>{@link #COLOR_CORRECTION_MODE_HIGH_QUALITY HIGH_QUALITY}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -451,6 +451,7 @@
      * @see #COLOR_CORRECTION_MODE_HIGH_QUALITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> COLOR_CORRECTION_MODE =
             new Key<Integer>("android.colorCorrection.mode", int.class);
 
@@ -469,7 +470,7 @@
      * <p>The valid range of each matrix element varies on different devices, but
      * values within [-1.5, 3.0] are guaranteed not to be clipped.</p>
      * <p><b>Units</b>: Unitless scale factors</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -478,6 +479,7 @@
      * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.ColorSpaceTransform> COLOR_CORRECTION_TRANSFORM =
             new Key<android.hardware.camera2.params.ColorSpaceTransform>("android.colorCorrection.transform", android.hardware.camera2.params.ColorSpaceTransform.class);
 
@@ -496,7 +498,7 @@
      * device allows gains below 1.0, this is usually not recommended because
      * this can create color artifacts.</p>
      * <p><b>Units</b>: Unitless gain factors</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -505,6 +507,7 @@
      * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.RggbChannelVector> COLOR_CORRECTION_GAINS =
             new Key<android.hardware.camera2.params.RggbChannelVector>("android.colorCorrection.gains", android.hardware.camera2.params.RggbChannelVector.class);
 
@@ -537,6 +540,7 @@
      * @see #COLOR_CORRECTION_ABERRATION_MODE_HIGH_QUALITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> COLOR_CORRECTION_ABERRATION_MODE =
             new Key<Integer>("android.colorCorrection.aberrationMode", int.class);
 
@@ -593,6 +597,7 @@
      * @see #CONTROL_AE_ANTIBANDING_MODE_AUTO
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AE_ANTIBANDING_MODE =
             new Key<Integer>("android.control.aeAntibandingMode", int.class);
 
@@ -626,6 +631,7 @@
      * @see CaptureResult#CONTROL_AE_STATE
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AE_EXPOSURE_COMPENSATION =
             new Key<Integer>("android.control.aeExposureCompensation", int.class);
 
@@ -676,6 +682,7 @@
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> CONTROL_AE_LOCK =
             new Key<Boolean>("android.control.aeLock", boolean.class);
 
@@ -728,6 +735,7 @@
      * @see #CONTROL_AE_MODE_ON_EXTERNAL_FLASH
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AE_MODE =
             new Key<Integer>("android.control.aeMode", int.class);
 
@@ -779,7 +787,7 @@
      * Coordinates must be between <code>[(0,0), (width, height))</code> of
      * {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize}
      * depending on distortion correction capability and mode</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#CONTROL_MAX_REGIONS_AE
      * @see CaptureRequest#DISTORTION_CORRECTION_MODE
@@ -788,6 +796,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AE_REGIONS =
             new Key<android.hardware.camera2.params.MeteringRectangle[]>("android.control.aeRegions", android.hardware.camera2.params.MeteringRectangle[].class);
 
@@ -808,6 +817,7 @@
      * @see CaptureRequest#SENSOR_FRAME_DURATION
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Range<Integer>> CONTROL_AE_TARGET_FPS_RANGE =
             new Key<android.util.Range<Integer>>("android.control.aeTargetFpsRange", new TypeReference<android.util.Range<Integer>>() {{ }});
 
@@ -866,7 +876,7 @@
      *   <li>{@link #CONTROL_AE_PRECAPTURE_TRIGGER_START START}</li>
      *   <li>{@link #CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL CANCEL}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -881,6 +891,7 @@
      * @see #CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AE_PRECAPTURE_TRIGGER =
             new Key<Integer>("android.control.aePrecaptureTrigger", int.class);
 
@@ -1108,7 +1119,7 @@
      *   <li>{@link #CONTROL_AE_STATE_FLASH_REQUIRED FLASH_REQUIRED}</li>
      *   <li>{@link #CONTROL_AE_STATE_PRECAPTURE PRECAPTURE}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -1129,6 +1140,7 @@
      * @see #CONTROL_AE_STATE_PRECAPTURE
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AE_STATE =
             new Key<Integer>("android.control.aeState", int.class);
 
@@ -1170,6 +1182,7 @@
      * @see #CONTROL_AF_MODE_EDOF
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AF_MODE =
             new Key<Integer>("android.control.afMode", int.class);
 
@@ -1222,7 +1235,7 @@
      * Coordinates must be between <code>[(0,0), (width, height))</code> of
      * {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize}
      * depending on distortion correction capability and mode</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#CONTROL_MAX_REGIONS_AF
      * @see CaptureRequest#DISTORTION_CORRECTION_MODE
@@ -1231,6 +1244,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AF_REGIONS =
             new Key<android.hardware.camera2.params.MeteringRectangle[]>("android.control.afRegions", android.hardware.camera2.params.MeteringRectangle[].class);
 
@@ -1268,6 +1282,7 @@
      * @see #CONTROL_AF_TRIGGER_CANCEL
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AF_TRIGGER =
             new Key<Integer>("android.control.afTrigger", int.class);
 
@@ -1677,6 +1692,7 @@
      * @see #CONTROL_AF_STATE_PASSIVE_UNFOCUSED
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AF_STATE =
             new Key<Integer>("android.control.afState", int.class);
 
@@ -1707,6 +1723,7 @@
      * @see CaptureRequest#CONTROL_AWB_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> CONTROL_AWB_LOCK =
             new Key<Boolean>("android.control.awbLock", boolean.class);
 
@@ -1767,6 +1784,7 @@
      * @see #CONTROL_AWB_MODE_SHADE
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AWB_MODE =
             new Key<Integer>("android.control.awbMode", int.class);
 
@@ -1819,7 +1837,7 @@
      * Coordinates must be between <code>[(0,0), (width, height))</code> of
      * {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize}
      * depending on distortion correction capability and mode</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#CONTROL_MAX_REGIONS_AWB
      * @see CaptureRequest#DISTORTION_CORRECTION_MODE
@@ -1828,6 +1846,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.MeteringRectangle[]> CONTROL_AWB_REGIONS =
             new Key<android.hardware.camera2.params.MeteringRectangle[]>("android.control.awbRegions", android.hardware.camera2.params.MeteringRectangle[].class);
 
@@ -1870,6 +1889,7 @@
      * @see #CONTROL_CAPTURE_INTENT_MOTION_TRACKING
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_CAPTURE_INTENT =
             new Key<Integer>("android.control.captureIntent", int.class);
 
@@ -1997,7 +2017,7 @@
      *   <li>{@link #CONTROL_AWB_STATE_CONVERGED CONVERGED}</li>
      *   <li>{@link #CONTROL_AWB_STATE_LOCKED LOCKED}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2013,6 +2033,7 @@
      * @see #CONTROL_AWB_STATE_LOCKED
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AWB_STATE =
             new Key<Integer>("android.control.awbState", int.class);
 
@@ -2052,6 +2073,7 @@
      * @see #CONTROL_EFFECT_MODE_AQUA
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_EFFECT_MODE =
             new Key<Integer>("android.control.effectMode", int.class);
 
@@ -2092,6 +2114,7 @@
      * @see #CONTROL_MODE_OFF_KEEP_STATE
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_MODE =
             new Key<Integer>("android.control.mode", int.class);
 
@@ -2159,6 +2182,7 @@
      * @see #CONTROL_SCENE_MODE_HDR
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_SCENE_MODE =
             new Key<Integer>("android.control.sceneMode", int.class);
 
@@ -2202,6 +2226,7 @@
      * @see #CONTROL_VIDEO_STABILIZATION_MODE_ON
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_VIDEO_STABILIZATION_MODE =
             new Key<Integer>("android.control.videoStabilizationMode", int.class);
 
@@ -2228,7 +2253,7 @@
      * <p><b>Units</b>: ISO arithmetic units, the same as {@link CaptureRequest#SENSOR_SENSITIVITY android.sensor.sensitivity}</p>
      * <p><b>Range of valid values:</b><br>
      * {@link CameraCharacteristics#CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE android.control.postRawSensitivityBoostRange}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#CONTROL_AE_MODE
      * @see CaptureRequest#CONTROL_MODE
@@ -2237,6 +2262,7 @@
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_POST_RAW_SENSITIVITY_BOOST =
             new Key<Integer>("android.control.postRawSensitivityBoost", int.class);
 
@@ -2264,12 +2290,13 @@
      * <p>For applications targeting SDK versions older than O, the value of enableZsl in all
      * capture templates is always <code>false</code> if present.</p>
      * <p>For application-operated ZSL, use CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG template.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#CONTROL_CAPTURE_INTENT
      * @see CaptureResult#SENSOR_TIMESTAMP
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> CONTROL_ENABLE_ZSL =
             new Key<Boolean>("android.control.enableZsl", boolean.class);
 
@@ -2287,11 +2314,12 @@
      *   <li>{@link #CONTROL_AF_SCENE_CHANGE_NOT_DETECTED NOT_DETECTED}</li>
      *   <li>{@link #CONTROL_AF_SCENE_CHANGE_DETECTED DETECTED}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @see #CONTROL_AF_SCENE_CHANGE_NOT_DETECTED
      * @see #CONTROL_AF_SCENE_CHANGE_DETECTED
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> CONTROL_AF_SCENE_CHANGE =
             new Key<Integer>("android.control.afSceneChange", int.class);
 
@@ -2326,7 +2354,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#EDGE_AVAILABLE_EDGE_MODES android.edge.availableEdgeModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2340,6 +2368,7 @@
      * @see #EDGE_MODE_ZERO_SHUTTER_LAG
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> EDGE_MODE =
             new Key<Integer>("android.edge.mode", int.class);
 
@@ -2375,6 +2404,7 @@
      * @see #FLASH_MODE_TORCH
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> FLASH_MODE =
             new Key<Integer>("android.flash.mode", int.class);
 
@@ -2402,7 +2432,7 @@
      *   <li>{@link #FLASH_STATE_FIRED FIRED}</li>
      *   <li>{@link #FLASH_STATE_PARTIAL PARTIAL}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2418,6 +2448,7 @@
      * @see #FLASH_STATE_PARTIAL
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> FLASH_STATE =
             new Key<Integer>("android.flash.state", int.class);
 
@@ -2434,7 +2465,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#HOT_PIXEL_AVAILABLE_HOT_PIXEL_MODES android.hotPixel.availableHotPixelModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#HOT_PIXEL_AVAILABLE_HOT_PIXEL_MODES
      * @see #HOT_PIXEL_MODE_OFF
@@ -2442,6 +2473,7 @@
      * @see #HOT_PIXEL_MODE_HIGH_QUALITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> HOT_PIXEL_MODE =
             new Key<Integer>("android.hotPixel.mode", int.class);
 
@@ -2454,6 +2486,7 @@
      * <p>This key is available on all devices.</p>
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<android.location.Location> JPEG_GPS_LOCATION =
             new Key<android.location.Location>("android.jpeg.gpsLocation", android.location.Location.class);
@@ -2535,6 +2568,7 @@
      * @see CameraCharacteristics#SENSOR_ORIENTATION
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> JPEG_ORIENTATION =
             new Key<Integer>("android.jpeg.orientation", int.class);
 
@@ -2548,6 +2582,7 @@
      * <p>This key is available on all devices.</p>
      */
     @PublicKey
+    @NonNull
     public static final Key<Byte> JPEG_QUALITY =
             new Key<Byte>("android.jpeg.quality", byte.class);
 
@@ -2560,6 +2595,7 @@
      * <p>This key is available on all devices.</p>
      */
     @PublicKey
+    @NonNull
     public static final Key<Byte> JPEG_THUMBNAIL_QUALITY =
             new Key<Byte>("android.jpeg.thumbnailQuality", byte.class);
 
@@ -2599,6 +2635,7 @@
      * @see CaptureRequest#JPEG_ORIENTATION
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Size> JPEG_THUMBNAIL_SIZE =
             new Key<android.util.Size>("android.jpeg.thumbnailSize", android.util.Size.class);
 
@@ -2622,7 +2659,7 @@
      * <p><b>Units</b>: The f-number (f/N)</p>
      * <p><b>Range of valid values:</b><br>
      * {@link CameraCharacteristics#LENS_INFO_AVAILABLE_APERTURES android.lens.info.availableApertures}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2636,6 +2673,7 @@
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> LENS_APERTURE =
             new Key<Float>("android.lens.aperture", float.class);
 
@@ -2656,7 +2694,7 @@
      * <p><b>Units</b>: Exposure Value (EV)</p>
      * <p><b>Range of valid values:</b><br>
      * {@link CameraCharacteristics#LENS_INFO_AVAILABLE_FILTER_DENSITIES android.lens.info.availableFilterDensities}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2666,6 +2704,7 @@
      * @see CaptureResult#LENS_STATE
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> LENS_FILTER_DENSITY =
             new Key<Float>("android.lens.filterDensity", float.class);
 
@@ -2691,6 +2730,7 @@
      * @see CaptureResult#LENS_STATE
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> LENS_FOCAL_LENGTH =
             new Key<Float>("android.lens.focalLength", float.class);
 
@@ -2701,7 +2741,7 @@
      * <p><b>Units</b>: See {@link CameraCharacteristics#LENS_INFO_FOCUS_DISTANCE_CALIBRATION android.lens.info.focusDistanceCalibration} for details</p>
      * <p><b>Range of valid values:</b><br>
      * &gt;= 0</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2710,6 +2750,7 @@
      * @see CameraCharacteristics#LENS_INFO_FOCUS_DISTANCE_CALIBRATION
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> LENS_FOCUS_DISTANCE =
             new Key<Float>("android.lens.focusDistance", float.class);
 
@@ -2722,7 +2763,7 @@
      * far); see {@link CameraCharacteristics#LENS_INFO_FOCUS_DISTANCE_CALIBRATION android.lens.info.focusDistanceCalibration} for details.</p>
      * <p><b>Range of valid values:</b><br>
      * &gt;=0</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2731,6 +2772,7 @@
      * @see CameraCharacteristics#LENS_INFO_FOCUS_DISTANCE_CALIBRATION
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Pair<Float,Float>> LENS_FOCUS_RANGE =
             new Key<android.util.Pair<Float,Float>>("android.lens.focusRange", new TypeReference<android.util.Pair<Float,Float>>() {{ }});
 
@@ -2761,7 +2803,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION android.lens.info.availableOpticalStabilization}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2773,6 +2815,7 @@
      * @see #LENS_OPTICAL_STABILIZATION_MODE_ON
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> LENS_OPTICAL_STABILIZATION_MODE =
             new Key<Integer>("android.lens.opticalStabilizationMode", int.class);
 
@@ -2802,7 +2845,7 @@
      *   <li>{@link #LENS_STATE_STATIONARY STATIONARY}</li>
      *   <li>{@link #LENS_STATE_MOVING MOVING}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -2820,6 +2863,7 @@
      * @see #LENS_STATE_MOVING
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> LENS_STATE =
             new Key<Integer>("android.lens.state", int.class);
 
@@ -2854,10 +2898,11 @@
      *  <code>p'</code> is in the camera-oriented coordinate system.</p>
      * <p><b>Units</b>:
      * Quaternion coefficients</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      */
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_POSE_ROTATION =
             new Key<float[]>("android.lens.poseRotation", float[].class);
 
@@ -2890,7 +2935,7 @@
      * the center of the primary gyroscope on the device. The axis definitions are the same as
      * with PRIMARY_CAMERA.</p>
      * <p><b>Units</b>: Meters</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#LENS_DISTORTION
@@ -2899,6 +2944,7 @@
      * @see CameraCharacteristics#LENS_POSE_ROTATION
      */
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_POSE_TRANSLATION =
             new Key<float[]>("android.lens.poseTranslation", float[].class);
 
@@ -2962,7 +3008,7 @@
      * Pixels in the
      * {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize}
      * coordinate system.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#LENS_DISTORTION
@@ -2972,6 +3018,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_INTRINSIC_CALIBRATION =
             new Key<float[]>("android.lens.intrinsicCalibration", float[].class);
 
@@ -3006,7 +3053,7 @@
      * <p>The distortion model used is the Brown-Conrady model.</p>
      * <p><b>Units</b>:
      * Unitless coefficients.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#LENS_INTRINSIC_CALIBRATION
@@ -3019,6 +3066,7 @@
      */
     @Deprecated
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_RADIAL_DISTORTION =
             new Key<float[]>("android.lens.radialDistortion", float[].class);
 
@@ -3053,13 +3101,14 @@
      * <p>The distortion model used is the Brown-Conrady model.</p>
      * <p><b>Units</b>:
      * Unitless coefficients.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Permission {@link android.Manifest.permission#CAMERA } is needed to access this property</b></p>
      *
      * @see CameraCharacteristics#LENS_INTRINSIC_CALIBRATION
      * @see CameraCharacteristics#LENS_RADIAL_DISTORTION
      */
     @PublicKey
+    @NonNull
     public static final Key<float[]> LENS_DISTORTION =
             new Key<float[]>("android.lens.distortion", float[].class);
 
@@ -3100,7 +3149,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES android.noiseReduction.availableNoiseReductionModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3115,6 +3164,7 @@
      * @see #NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> NOISE_REDUCTION_MODE =
             new Key<Integer>("android.noiseReduction.mode", int.class);
 
@@ -3134,7 +3184,7 @@
      * only be used by the camera device if quirks.usePartialResult is set to 1.</p>
      * <p><b>Range of valid values:</b><br>
      * Optional. Default value is FINAL.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @deprecated
      * <p>Not used in HALv3 or newer</p>
 
@@ -3152,7 +3202,7 @@
      * <p><b>Units</b>: count of frames</p>
      * <p><b>Range of valid values:</b><br>
      * &gt; 0</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @deprecated
      * <p>Not used in HALv3 or newer</p>
 
@@ -3169,7 +3219,7 @@
      * <p><b>Units</b>: arbitrary integer assigned by application</p>
      * <p><b>Range of valid values:</b><br>
      * Any int</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @hide
      */
     public static final Key<Integer> REQUEST_ID =
@@ -3190,6 +3240,7 @@
      * @see CameraCharacteristics#REQUEST_PIPELINE_MAX_DEPTH
      */
     @PublicKey
+    @NonNull
     public static final Key<Byte> REQUEST_PIPELINE_DEPTH =
             new Key<Byte>("android.request.pipelineDepth", byte.class);
 
@@ -3251,6 +3302,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.graphics.Rect> SCALER_CROP_REGION =
             new Key<android.graphics.Rect>("android.scaler.cropRegion", android.graphics.Rect.class);
 
@@ -3265,7 +3317,7 @@
      * <p><b>Units</b>: Nanoseconds</p>
      * <p><b>Range of valid values:</b><br>
      * {@link CameraCharacteristics#SENSOR_INFO_EXPOSURE_TIME_RANGE android.sensor.info.exposureTimeRange}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3276,6 +3328,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_EXPOSURE_TIME_RANGE
      */
     @PublicKey
+    @NonNull
     public static final Key<Long> SENSOR_EXPOSURE_TIME =
             new Key<Long>("android.sensor.exposureTime", long.class);
 
@@ -3346,7 +3399,7 @@
      * <p><b>Range of valid values:</b><br>
      * See {@link CameraCharacteristics#SENSOR_INFO_MAX_FRAME_DURATION android.sensor.info.maxFrameDuration}, {@link android.hardware.camera2.params.StreamConfigurationMap }.
      * The duration is capped to <code>max(duration, exposureTime + overhead)</code>.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3357,6 +3410,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_MAX_FRAME_DURATION
      */
     @PublicKey
+    @NonNull
     public static final Key<Long> SENSOR_FRAME_DURATION =
             new Key<Long>("android.sensor.frameDuration", long.class);
 
@@ -3377,7 +3431,7 @@
      * <p><b>Units</b>: ISO arithmetic units</p>
      * <p><b>Range of valid values:</b><br>
      * {@link CameraCharacteristics#SENSOR_INFO_SENSITIVITY_RANGE android.sensor.info.sensitivityRange}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3389,6 +3443,7 @@
      * @see CameraCharacteristics#SENSOR_MAX_ANALOG_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SENSOR_SENSITIVITY =
             new Key<Integer>("android.sensor.sensitivity", int.class);
 
@@ -3419,6 +3474,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_TIMESTAMP_SOURCE
      */
     @PublicKey
+    @NonNull
     public static final Key<Long> SENSOR_TIMESTAMP =
             new Key<Long>("android.sensor.timestamp", long.class);
 
@@ -3433,9 +3489,10 @@
      * <p>The order of the values is R, G, B; where R is in the lowest index.</p>
      * <p>Starting from Android Q, this key will not be present for a MONOCHROME camera, even if
      * the camera device has RAW capability.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      */
     @PublicKey
+    @NonNull
     public static final Key<Rational[]> SENSOR_NEUTRAL_COLOR_POINT =
             new Key<Rational[]>("android.sensor.neutralColorPoint", Rational[].class);
 
@@ -3460,11 +3517,12 @@
      * Adobe DNG specification for the NoiseProfile tag.</p>
      * <p>For a MONOCHROME camera, there is only one color channel. So the noise model coefficients
      * will only contain one S and one O.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#SENSOR_INFO_COLOR_FILTER_ARRANGEMENT
      */
     @PublicKey
+    @NonNull
     public static final Key<android.util.Pair<Double,Double>[]> SENSOR_NOISE_PROFILE =
             new Key<android.util.Pair<Double,Double>[]>("android.sensor.noiseProfile", new TypeReference<android.util.Pair<Double,Double>[]>() {{ }});
 
@@ -3504,9 +3562,10 @@
      * the camera device has RAW capability.</p>
      * <p><b>Range of valid values:</b><br></p>
      * <p>&gt;= 0</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> SENSOR_GREEN_SPLIT =
             new Key<Float>("android.sensor.greenSplit", float.class);
 
@@ -3519,11 +3578,12 @@
      * output.</p>
      * <p>For example, a sensor with RAW10 Bayer output would use the
      * 10 most significant bits from each color channel.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#SENSOR_TEST_PATTERN_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<int[]> SENSOR_TEST_PATTERN_DATA =
             new Key<int[]>("android.sensor.testPatternData", int[].class);
 
@@ -3548,7 +3608,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#SENSOR_AVAILABLE_TEST_PATTERN_MODES android.sensor.availableTestPatternModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#SENSOR_AVAILABLE_TEST_PATTERN_MODES
      * @see #SENSOR_TEST_PATTERN_MODE_OFF
@@ -3559,6 +3619,7 @@
      * @see #SENSOR_TEST_PATTERN_MODE_CUSTOM1
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SENSOR_TEST_PATTERN_MODE =
             new Key<Integer>("android.sensor.testPatternMode", int.class);
 
@@ -3575,7 +3636,7 @@
      * <p><b>Range of valid values:</b><br>
      * &gt;= 0 and &lt;
      * {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputMinFrameDuration }.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3584,6 +3645,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<Long> SENSOR_ROLLING_SHUTTER_SKEW =
             new Key<Long>("android.sensor.rollingShutterSkew", long.class);
 
@@ -3617,7 +3679,7 @@
      * camera device advertises this key via {@link android.hardware.camera2.CameraCharacteristics#getAvailableCaptureResultKeys }.</p>
      * <p><b>Range of valid values:</b><br>
      * &gt;= 0 for each.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#SENSOR_BLACK_LEVEL_PATTERN
      * @see CameraCharacteristics#SENSOR_INFO_COLOR_FILTER_ARRANGEMENT
@@ -3625,6 +3687,7 @@
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<float[]> SENSOR_DYNAMIC_BLACK_LEVEL =
             new Key<float[]>("android.sensor.dynamicBlackLevel", float[].class);
 
@@ -3640,7 +3703,7 @@
      * {@link android.hardware.camera2.CameraCharacteristics#getAvailableCaptureRequestKeys }.</p>
      * <p><b>Range of valid values:</b><br>
      * &gt;= 0</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#SENSOR_BLACK_LEVEL_PATTERN
      * @see CameraCharacteristics#SENSOR_INFO_WHITE_LEVEL
@@ -3648,6 +3711,7 @@
      * @see CaptureRequest#SENSOR_SENSITIVITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SENSOR_DYNAMIC_WHITE_LEVEL =
             new Key<Integer>("android.sensor.dynamicWhiteLevel", int.class);
 
@@ -3685,7 +3749,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#SHADING_AVAILABLE_MODES android.shading.availableModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3701,6 +3765,7 @@
      * @see #SHADING_MODE_HIGH_QUALITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> SHADING_MODE =
             new Key<Integer>("android.shading.mode", int.class);
 
@@ -3726,6 +3791,7 @@
      * @see #STATISTICS_FACE_DETECT_MODE_FULL
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> STATISTICS_FACE_DETECT_MODE =
             new Key<Integer>("android.statistics.faceDetectMode", int.class);
 
@@ -3818,6 +3884,7 @@
      * @see CaptureRequest#STATISTICS_FACE_DETECT_MODE
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<android.hardware.camera2.params.Face[]> STATISTICS_FACES =
             new Key<android.hardware.camera2.params.Face[]>("android.statistics.faces", android.hardware.camera2.params.Face[].class);
@@ -3886,7 +3953,7 @@
      * </code></pre>
      * <p><b>Range of valid values:</b><br>
      * Each gain factor is &gt;= 1</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -3896,6 +3963,7 @@
      * @see CameraCharacteristics#SENSOR_INFO_LENS_SHADING_APPLIED
      */
     @PublicKey
+    @NonNull
     public static final Key<android.hardware.camera2.params.LensShadingMap> STATISTICS_LENS_SHADING_CORRECTION_MAP =
             new Key<android.hardware.camera2.params.LensShadingMap>("android.statistics.lensShadingCorrectionMap", android.hardware.camera2.params.LensShadingMap.class);
 
@@ -3976,7 +4044,7 @@
      * formats.</p>
      * <p><b>Range of valid values:</b><br>
      * Each gain factor is &gt;= 1</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -4001,7 +4069,7 @@
      * see {@link CaptureRequest#COLOR_CORRECTION_GAINS android.colorCorrection.gains} for details.</p>
      * <p>This value should always be calculated by the auto-white balance (AWB) block,
      * regardless of the android.control.* current values.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#COLOR_CORRECTION_GAINS
      * @deprecated
@@ -4029,7 +4097,7 @@
      * capture settings and color transforms are set by the application.</p>
      * <p>This value should always be calculated by the auto-white balance (AWB) block,
      * regardless of the android.control.* current values.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @deprecated
      * <p>Never fully implemented or specified; do not use</p>
 
@@ -4061,7 +4129,7 @@
      *   <li>{@link #STATISTICS_SCENE_FLICKER_50HZ 50HZ}</li>
      *   <li>{@link #STATISTICS_SCENE_FLICKER_60HZ 60HZ}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -4075,6 +4143,7 @@
      * @see #STATISTICS_SCENE_FLICKER_60HZ
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> STATISTICS_SCENE_FLICKER =
             new Key<Integer>("android.statistics.sceneFlicker", int.class);
 
@@ -4084,12 +4153,13 @@
      * If set to <code>false</code>, no hot pixel map will be returned.</p>
      * <p><b>Range of valid values:</b><br>
      * {@link CameraCharacteristics#STATISTICS_INFO_AVAILABLE_HOT_PIXEL_MAP_MODES android.statistics.info.availableHotPixelMapModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureResult#STATISTICS_HOT_PIXEL_MAP
      * @see CameraCharacteristics#STATISTICS_INFO_AVAILABLE_HOT_PIXEL_MAP_MODES
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> STATISTICS_HOT_PIXEL_MAP_MODE =
             new Key<Boolean>("android.statistics.hotPixelMapMode", boolean.class);
 
@@ -4105,12 +4175,13 @@
      * <p>n &lt;= number of pixels on the sensor.
      * The <code>(x, y)</code> coordinates must be bounded by
      * {@link CameraCharacteristics#SENSOR_INFO_PIXEL_ARRAY_SIZE android.sensor.info.pixelArraySize}.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
      * @see CameraCharacteristics#SENSOR_INFO_PIXEL_ARRAY_SIZE
      */
     @PublicKey
+    @NonNull
     public static final Key<android.graphics.Point[]> STATISTICS_HOT_PIXEL_MAP =
             new Key<android.graphics.Point[]>("android.statistics.hotPixelMap", android.graphics.Point[].class);
 
@@ -4128,7 +4199,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#STATISTICS_INFO_AVAILABLE_LENS_SHADING_MAP_MODES android.statistics.info.availableLensShadingMapModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -4139,6 +4210,7 @@
      * @see #STATISTICS_LENS_SHADING_MAP_MODE_ON
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> STATISTICS_LENS_SHADING_MAP_MODE =
             new Key<Integer>("android.statistics.lensShadingMapMode", int.class);
 
@@ -4158,13 +4230,14 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#STATISTICS_INFO_AVAILABLE_OIS_DATA_MODES android.statistics.info.availableOisDataModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CameraCharacteristics#STATISTICS_INFO_AVAILABLE_OIS_DATA_MODES
      * @see #STATISTICS_OIS_DATA_MODE_OFF
      * @see #STATISTICS_OIS_DATA_MODE_ON
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> STATISTICS_OIS_DATA_MODE =
             new Key<Integer>("android.statistics.oisDataMode", int.class);
 
@@ -4173,7 +4246,7 @@
      * <p>The array contains the timestamps of OIS samples. The timestamps are in the same
      * timebase as and comparable to {@link CaptureResult#SENSOR_TIMESTAMP android.sensor.timestamp}.</p>
      * <p><b>Units</b>: nanoseconds</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureResult#SENSOR_TIMESTAMP
      * @hide
@@ -4194,7 +4267,7 @@
      * since the scaling of OIS shifts would depend on the specific spot on the sensor the shift
      * is needed.</p>
      * <p><b>Units</b>: Pixels in active array.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @hide
      */
     public static final Key<float[]> STATISTICS_OIS_X_SHIFTS =
@@ -4213,7 +4286,7 @@
      * since the scaling of OIS shifts would depend on the specific spot on the sensor the shift
      * is needed.</p>
      * <p><b>Units</b>: Pixels in active array.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @hide
      */
     public static final Key<float[]> STATISTICS_OIS_Y_SHIFTS =
@@ -4235,9 +4308,10 @@
      * supporting devices). They are always reported in pre-correction active array coordinates,
      * since the scaling of OIS shifts would depend on the specific spot on the sensor the shift
      * is needed.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<android.hardware.camera2.params.OisSample[]> STATISTICS_OIS_SAMPLES =
             new Key<android.hardware.camera2.params.OisSample[]>("android.statistics.oisSamples", android.hardware.camera2.params.OisSample[].class);
@@ -4247,7 +4321,7 @@
      * channel, to use when {@link CaptureRequest#TONEMAP_MODE android.tonemap.mode} is
      * CONTRAST_CURVE.</p>
      * <p>See android.tonemap.curveRed for more details.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -4264,7 +4338,7 @@
      * channel, to use when {@link CaptureRequest#TONEMAP_MODE android.tonemap.mode} is
      * CONTRAST_CURVE.</p>
      * <p>See android.tonemap.curveRed for more details.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -4325,7 +4399,7 @@
      * <p><b>Range of valid values:</b><br>
      * 0-1 on both input and output coordinates, normalized
      * as a floating-point value such that 0 == black and 1 == white.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -4386,7 +4460,7 @@
      *   (0.8000, 0.9063), (0.8667, 0.9389), (0.9333, 0.9701), (1.0000, 1.0000) ]
      * </code></pre>
      * <p><img alt="sRGB tonemapping curve" src="/reference/images/camera2/metadata/android.tonemap.curveRed/srgb_tonemap.png" /></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -4396,6 +4470,7 @@
      * @see CaptureRequest#TONEMAP_MODE
      */
     @PublicKey
+    @NonNull
     @SyntheticKey
     public static final Key<android.hardware.camera2.params.TonemapCurve> TONEMAP_CURVE =
             new Key<android.hardware.camera2.params.TonemapCurve>("android.tonemap.curve", android.hardware.camera2.params.TonemapCurve.class);
@@ -4430,7 +4505,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#TONEMAP_AVAILABLE_TONE_MAP_MODES android.tonemap.availableToneMapModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -4446,6 +4521,7 @@
      * @see #TONEMAP_MODE_PRESET_CURVE
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> TONEMAP_MODE =
             new Key<Integer>("android.tonemap.mode", int.class);
 
@@ -4462,11 +4538,12 @@
      * value will be returned in capture result.</p>
      * <p>The valid range of gamma value varies on different devices, but values
      * within [1.0, 5.0] are guaranteed not to be clipped.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#TONEMAP_MODE
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> TONEMAP_GAMMA =
             new Key<Float>("android.tonemap.gamma", float.class);
 
@@ -4485,13 +4562,14 @@
      *   <li>{@link #TONEMAP_PRESET_CURVE_SRGB SRGB}</li>
      *   <li>{@link #TONEMAP_PRESET_CURVE_REC709 REC709}</li>
      * </ul></p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#TONEMAP_MODE
      * @see #TONEMAP_PRESET_CURVE_SRGB
      * @see #TONEMAP_PRESET_CURVE_REC709
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> TONEMAP_PRESET_CURVE =
             new Key<Integer>("android.tonemap.presetCurve", int.class);
 
@@ -4506,7 +4584,7 @@
      * data is stored locally on the device.</p>
      * <p>The LED <em>may</em> be off if a trusted application is using the data that
      * doesn't violate the above rules.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * @hide
      */
     public static final Key<Boolean> LED_TRANSMIT =
@@ -4519,7 +4597,7 @@
      * ON if {@link CaptureRequest#BLACK_LEVEL_LOCK android.blackLevel.lock} was ON in the capture request, unless
      * a change in other capture settings forced the camera device to
      * perform a black level reset.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Full capability</b> -
      * Present on all camera devices that report being {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_FULL HARDWARE_LEVEL_FULL} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -4528,6 +4606,7 @@
      * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
      */
     @PublicKey
+    @NonNull
     public static final Key<Boolean> BLACK_LEVEL_LOCK =
             new Key<Boolean>("android.blackLevel.lock", boolean.class);
 
@@ -4637,7 +4716,7 @@
      * <p><b>Units</b>: Relative exposure time increase factor.</p>
      * <p><b>Range of valid values:</b><br>
      * &gt;= 1.0</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      * <p><b>Limited capability</b> -
      * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
      * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
@@ -4648,6 +4727,7 @@
      * @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
      */
     @PublicKey
+    @NonNull
     public static final Key<Float> REPROCESS_EFFECTIVE_EXPOSURE_FACTOR =
             new Key<Float>("android.reprocess.effectiveExposureFactor", float.class);
 
@@ -4662,9 +4742,10 @@
      * cameras when application changes FOCAL_LENGTH or SCALER_CROP_REGION.
      * At the time of lens switch, this result metadata reflects the new active physical camera
      * ID.</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      */
     @PublicKey
+    @NonNull
     public static final Key<String> LOGICAL_MULTI_CAMERA_ACTIVE_PHYSICAL_ID =
             new Key<String>("android.logicalMultiCamera.activePhysicalId", String.class);
 
@@ -4711,7 +4792,7 @@
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#DISTORTION_CORRECTION_AVAILABLE_MODES android.distortionCorrection.availableModes}</p>
-     * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+     * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
      *
      * @see CaptureRequest#CONTROL_AE_REGIONS
      * @see CaptureRequest#CONTROL_AF_REGIONS
@@ -4727,6 +4808,7 @@
      * @see #DISTORTION_CORRECTION_MODE_HIGH_QUALITY
      */
     @PublicKey
+    @NonNull
     public static final Key<Integer> DISTORTION_CORRECTION_MODE =
             new Key<Integer>("android.distortionCorrection.mode", int.class);
 
@@ -4736,4 +4818,7 @@
 
 
 
+
+
+
 }
diff --git a/core/java/android/hardware/camera2/impl/CameraMetadataNative.java b/core/java/android/hardware/camera2/impl/CameraMetadataNative.java
index 65026b6..1cdf235 100644
--- a/core/java/android/hardware/camera2/impl/CameraMetadataNative.java
+++ b/core/java/android/hardware/camera2/impl/CameraMetadataNative.java
@@ -350,7 +350,7 @@
         return newObject;
     }
 
-    public static final Parcelable.Creator<CameraMetadataNative> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CameraMetadataNative> CREATOR =
             new Parcelable.Creator<CameraMetadataNative>() {
         @Override
         public CameraMetadataNative createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/camera2/impl/CaptureResultExtras.java b/core/java/android/hardware/camera2/impl/CaptureResultExtras.java
index 40535e2..edc3d91 100644
--- a/core/java/android/hardware/camera2/impl/CaptureResultExtras.java
+++ b/core/java/android/hardware/camera2/impl/CaptureResultExtras.java
@@ -30,7 +30,7 @@
     private int partialResultCount;
     private int errorStreamId;
 
-    public static final Parcelable.Creator<CaptureResultExtras> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CaptureResultExtras> CREATOR =
             new Parcelable.Creator<CaptureResultExtras>() {
         @Override
         public CaptureResultExtras createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/camera2/impl/PhysicalCaptureResultInfo.java b/core/java/android/hardware/camera2/impl/PhysicalCaptureResultInfo.java
index 30eaf13..09619d0 100644
--- a/core/java/android/hardware/camera2/impl/PhysicalCaptureResultInfo.java
+++ b/core/java/android/hardware/camera2/impl/PhysicalCaptureResultInfo.java
@@ -27,7 +27,7 @@
     private String cameraId;
     private CameraMetadataNative cameraMetadata;
 
-    public static final Parcelable.Creator<PhysicalCaptureResultInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PhysicalCaptureResultInfo> CREATOR =
             new Parcelable.Creator<PhysicalCaptureResultInfo>() {
         @Override
         public PhysicalCaptureResultInfo createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/camera2/params/OutputConfiguration.java b/core/java/android/hardware/camera2/params/OutputConfiguration.java
index cb33659..d7db1f5 100644
--- a/core/java/android/hardware/camera2/params/OutputConfiguration.java
+++ b/core/java/android/hardware/camera2/params/OutputConfiguration.java
@@ -626,7 +626,7 @@
         return mSurfaceGroupId;
     }
 
-    public static final Parcelable.Creator<OutputConfiguration> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<OutputConfiguration> CREATOR =
             new Parcelable.Creator<OutputConfiguration>() {
         @Override
         public OutputConfiguration createFromParcel(Parcel source) {
diff --git a/core/java/android/hardware/camera2/params/SessionConfiguration.java b/core/java/android/hardware/camera2/params/SessionConfiguration.java
index 3ea58ad..555ff9a 100644
--- a/core/java/android/hardware/camera2/params/SessionConfiguration.java
+++ b/core/java/android/hardware/camera2/params/SessionConfiguration.java
@@ -134,7 +134,7 @@
         mOutputConfigurations = outConfigs;
     }
 
-    public static final Parcelable.Creator<SessionConfiguration> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<SessionConfiguration> CREATOR =
             new Parcelable.Creator<SessionConfiguration> () {
         @Override
         public SessionConfiguration createFromParcel(Parcel source) {
diff --git a/core/java/android/hardware/camera2/params/VendorTagDescriptor.java b/core/java/android/hardware/camera2/params/VendorTagDescriptor.java
index ea424e5..4845ec3 100644
--- a/core/java/android/hardware/camera2/params/VendorTagDescriptor.java
+++ b/core/java/android/hardware/camera2/params/VendorTagDescriptor.java
@@ -32,7 +32,7 @@
     private VendorTagDescriptor(Parcel source) {
     }
 
-    public static final Parcelable.Creator<VendorTagDescriptor> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<VendorTagDescriptor> CREATOR =
             new Parcelable.Creator<VendorTagDescriptor>() {
         @Override
         public VendorTagDescriptor createFromParcel(Parcel source) {
diff --git a/core/java/android/hardware/camera2/params/VendorTagDescriptorCache.java b/core/java/android/hardware/camera2/params/VendorTagDescriptorCache.java
index 1f92f6d..450b70b 100644
--- a/core/java/android/hardware/camera2/params/VendorTagDescriptorCache.java
+++ b/core/java/android/hardware/camera2/params/VendorTagDescriptorCache.java
@@ -32,7 +32,7 @@
     private VendorTagDescriptorCache(Parcel source) {
     }
 
-    public static final Parcelable.Creator<VendorTagDescriptorCache> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<VendorTagDescriptorCache> CREATOR =
             new Parcelable.Creator<VendorTagDescriptorCache>() {
         @Override
         public VendorTagDescriptorCache createFromParcel(Parcel source) {
diff --git a/core/java/android/hardware/camera2/utils/LongParcelable.java b/core/java/android/hardware/camera2/utils/LongParcelable.java
index c89b339..d36736e 100644
--- a/core/java/android/hardware/camera2/utils/LongParcelable.java
+++ b/core/java/android/hardware/camera2/utils/LongParcelable.java
@@ -32,7 +32,7 @@
         this.number = number;
     }
 
-    public static final Parcelable.Creator<LongParcelable> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<LongParcelable> CREATOR =
             new Parcelable.Creator<LongParcelable>() {
         @Override
         public LongParcelable createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/camera2/utils/SubmitInfo.java b/core/java/android/hardware/camera2/utils/SubmitInfo.java
index d1692b5..9df09c4 100644
--- a/core/java/android/hardware/camera2/utils/SubmitInfo.java
+++ b/core/java/android/hardware/camera2/utils/SubmitInfo.java
@@ -43,7 +43,7 @@
         mLastFrameNumber = lastFrameNumber;
     }
 
-    public static final Parcelable.Creator<SubmitInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<SubmitInfo> CREATOR =
             new Parcelable.Creator<SubmitInfo>() {
         @Override
         public SubmitInfo createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/display/AmbientBrightnessDayStats.java b/core/java/android/hardware/display/AmbientBrightnessDayStats.java
index 1aa2557..b25ef8d 100644
--- a/core/java/android/hardware/display/AmbientBrightnessDayStats.java
+++ b/core/java/android/hardware/display/AmbientBrightnessDayStats.java
@@ -121,7 +121,7 @@
         mStats = source.createFloatArray();
     }
 
-    public static final Creator<AmbientBrightnessDayStats> CREATOR =
+    public static final @android.annotation.NonNull Creator<AmbientBrightnessDayStats> CREATOR =
             new Creator<AmbientBrightnessDayStats>() {
 
                 @Override
diff --git a/core/java/com/android/internal/hardware/AmbientDisplayConfiguration.java b/core/java/android/hardware/display/AmbientDisplayConfiguration.java
similarity index 80%
rename from core/java/com/android/internal/hardware/AmbientDisplayConfiguration.java
rename to core/java/android/hardware/display/AmbientDisplayConfiguration.java
index e19a32e..b122f19 100644
--- a/core/java/com/android/internal/hardware/AmbientDisplayConfiguration.java
+++ b/core/java/android/hardware/display/AmbientDisplayConfiguration.java
@@ -11,11 +11,12 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
  */
 
-package com.android.internal.hardware;
+package android.hardware.display;
 
+import android.annotation.TestApi;
 import android.content.Context;
 import android.os.Build;
 import android.os.SystemProperties;
@@ -24,16 +25,25 @@
 
 import com.android.internal.R;
 
+/**
+ * AmbientDisplayConfiguration encapsulates reading access to the configuration of ambient display.
+ *
+ * {@hide}
+ */
+@TestApi
 public class AmbientDisplayConfiguration {
 
     private final Context mContext;
     private final boolean mAlwaysOnByDefault;
 
+    /** {@hide} */
+    @TestApi
     public AmbientDisplayConfiguration(Context context) {
         mContext = context;
         mAlwaysOnByDefault = mContext.getResources().getBoolean(R.bool.config_dozeAlwaysOnEnabled);
     }
 
+    /** {@hide} */
     public boolean enabled(int user) {
         return pulseOnNotificationEnabled(user)
                 || pulseOnLongPressEnabled(user)
@@ -41,63 +51,83 @@
                 || wakeScreenGestureEnabled(user);
     }
 
+    /** {@hide} */
     public boolean pulseOnNotificationEnabled(int user) {
-        return boolSettingDefaultOn(Settings.Secure.DOZE_ENABLED, user) && pulseOnNotificationAvailable();
+        return boolSettingDefaultOn(Settings.Secure.DOZE_ENABLED, user)
+                && pulseOnNotificationAvailable();
     }
 
+    /** {@hide} */
     public boolean pulseOnNotificationAvailable() {
         return ambientDisplayAvailable();
     }
 
+    /** {@hide} */
     public boolean pickupGestureEnabled(int user) {
         return boolSettingDefaultOn(Settings.Secure.DOZE_PICK_UP_GESTURE, user)
                 && dozePickupSensorAvailable();
     }
 
+    /** {@hide} */
     public boolean dozePickupSensorAvailable() {
         return mContext.getResources().getBoolean(R.bool.config_dozePulsePickup);
     }
 
+    /** {@hide} */
     public boolean tapGestureEnabled(int user) {
         return boolSettingDefaultOn(Settings.Secure.DOZE_TAP_SCREEN_GESTURE, user)
                 && tapSensorAvailable();
     }
 
+    /** {@hide} */
     public boolean tapSensorAvailable() {
         return !TextUtils.isEmpty(tapSensorType());
     }
 
+    /** {@hide} */
     public boolean doubleTapGestureEnabled(int user) {
         return boolSettingDefaultOn(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE, user)
                 && doubleTapSensorAvailable();
     }
 
+    /** {@hide} */
     public boolean doubleTapSensorAvailable() {
         return !TextUtils.isEmpty(doubleTapSensorType());
     }
 
+    /** {@hide} */
     public boolean wakeScreenGestureAvailable() {
         return mContext.getResources()
                 .getBoolean(R.bool.config_dozeWakeLockScreenSensorAvailable);
     }
 
+    /** {@hide} */
     public boolean wakeScreenGestureEnabled(int user) {
         return boolSettingDefaultOn(Settings.Secure.DOZE_WAKE_SCREEN_GESTURE, user)
                 && wakeScreenGestureAvailable();
     }
 
+    /** {@hide} */
+    public long getWakeLockScreenDebounce() {
+        return mContext.getResources().getInteger(R.integer.config_dozeWakeLockScreenDebounce);
+    }
+
+    /** {@hide} */
     public String doubleTapSensorType() {
         return mContext.getResources().getString(R.string.config_dozeDoubleTapSensorType);
     }
 
+    /** {@hide} */
     public String tapSensorType() {
         return mContext.getResources().getString(R.string.config_dozeTapSensorType);
     }
 
+    /** {@hide} */
     public String longPressSensorType() {
         return mContext.getResources().getString(R.string.config_dozeLongPressSensorType);
     }
 
+    /** {@hide} */
     public boolean pulseOnLongPressEnabled(int user) {
         return pulseOnLongPressAvailable() && boolSettingDefaultOff(
                 Settings.Secure.DOZE_PULSE_ON_LONG_PRESS, user);
@@ -107,28 +137,49 @@
         return !TextUtils.isEmpty(longPressSensorType());
     }
 
+    /**
+     * Returns if Always-on-Display functionality is enabled on the display for a specified user.
+     *
+     * {@hide}
+     */
+    @TestApi
     public boolean alwaysOnEnabled(int user) {
         return boolSetting(Settings.Secure.DOZE_ALWAYS_ON, user, mAlwaysOnByDefault ? 1 : 0)
                 && alwaysOnAvailable() && !accessibilityInversionEnabled(user);
     }
 
+    /**
+     * Returns if Always-on-Display functionality is available on the display.
+     *
+     * {@hide}
+     */
+    @TestApi
     public boolean alwaysOnAvailable() {
         return (alwaysOnDisplayDebuggingEnabled() || alwaysOnDisplayAvailable())
                 && ambientDisplayAvailable();
     }
 
+    /**
+     * Returns if Always-on-Display functionality is available on the display for a specified user.
+     *
+     *  {@hide}
+     */
+    @TestApi
     public boolean alwaysOnAvailableForUser(int user) {
         return alwaysOnAvailable() && !accessibilityInversionEnabled(user);
     }
 
+    /** {@hide} */
     public String ambientDisplayComponent() {
         return mContext.getResources().getString(R.string.config_dozeComponent);
     }
 
+    /** {@hide} */
     public boolean accessibilityInversionEnabled(int user) {
         return boolSettingDefaultOff(Settings.Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, user);
     }
 
+    /** {@hide} */
     public boolean ambientDisplayAvailable() {
         return !TextUtils.isEmpty(ambientDisplayComponent());
     }
@@ -141,7 +192,6 @@
         return SystemProperties.getBoolean("debug.doze.aod", false) && Build.IS_DEBUGGABLE;
     }
 
-
     private boolean boolSettingDefaultOn(String name, int user) {
         return boolSetting(name, user, 1);
     }
diff --git a/core/java/android/hardware/display/BrightnessChangeEvent.java b/core/java/android/hardware/display/BrightnessChangeEvent.java
index c6186bb..7fa1cfb 100644
--- a/core/java/android/hardware/display/BrightnessChangeEvent.java
+++ b/core/java/android/hardware/display/BrightnessChangeEvent.java
@@ -153,7 +153,7 @@
         colorSampleDuration = source.readLong();
     }
 
-    public static final Creator<BrightnessChangeEvent> CREATOR =
+    public static final @android.annotation.NonNull Creator<BrightnessChangeEvent> CREATOR =
             new Creator<BrightnessChangeEvent>() {
                 public BrightnessChangeEvent createFromParcel(Parcel source) {
                     return new BrightnessChangeEvent(source);
diff --git a/core/java/android/hardware/display/BrightnessConfiguration.java b/core/java/android/hardware/display/BrightnessConfiguration.java
index 8c74ddc..5b63dcf 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.NonNull;
 import android.annotation.Nullable;
 import android.annotation.SystemApi;
 import android.annotation.TestApi;
@@ -93,7 +94,7 @@
      *
      */
     @Nullable
-    public BrightnessCorrection getCorrectionByPackageName(String packageName) {
+    public BrightnessCorrection getCorrectionByPackageName(@NonNull String packageName) {
         return mCorrectionsByPackageName.get(packageName);
     }
 
@@ -106,7 +107,7 @@
      * @return The matching brightness correction, or null.
      */
     @Nullable
-    public BrightnessCorrection getCorrectionByCategory(int category) {
+    public BrightnessCorrection getCorrectionByCategory(@ApplicationInfo.Category int category) {
         return mCorrectionsByCategory.get(category);
     }
 
@@ -197,7 +198,7 @@
                 && Objects.equals(mDescription, other.mDescription);
     }
 
-    public static final Creator<BrightnessConfiguration> CREATOR =
+    public static final @android.annotation.NonNull Creator<BrightnessConfiguration> CREATOR =
             new Creator<BrightnessConfiguration>() {
         public BrightnessConfiguration createFromParcel(Parcel in) {
             float[] lux = in.createFloatArray();
@@ -238,7 +239,7 @@
      *
      * @hide
      */
-    public void saveToXml(XmlSerializer serializer) throws IOException {
+    public void saveToXml(@NonNull XmlSerializer serializer) throws IOException {
         serializer.startTag(null, TAG_BRIGHTNESS_CURVE);
         if (mDescription != null) {
             serializer.attribute(null, ATTR_DESCRIPTION, mDescription);
@@ -284,7 +285,7 @@
      *
      * @hide
      */
-    public static BrightnessConfiguration loadFromXml(XmlPullParser parser)
+    public static BrightnessConfiguration loadFromXml(@NonNull XmlPullParser parser)
             throws IOException, XmlPullParserException {
         String description = null;
         List<Float> luxList = new ArrayList<>();
@@ -443,8 +444,11 @@
          *      {@link #getMaxCorrectionsByPackageName}).
          *
          */
-        public Builder addCorrectionByPackageName(String packageName,
-                BrightnessCorrection correction) {
+        @NonNull
+        public Builder addCorrectionByPackageName(@NonNull String packageName,
+                @NonNull BrightnessCorrection correction) {
+            Objects.requireNonNull(packageName, "packageName must not be null");
+            Objects.requireNonNull(correction, "correction must not be null");
             if (mCorrectionsByPackageName.size() >= getMaxCorrectionsByPackageName()) {
                 throw new IllegalArgumentException("Too many corrections by package name");
             }
@@ -469,8 +473,10 @@
          *      {@link #getMaxCorrectionsByCategory}).
          *
          */
+        @NonNull
         public Builder addCorrectionByCategory(@ApplicationInfo.Category int category,
-                BrightnessCorrection correction) {
+                @NonNull BrightnessCorrection correction) {
+            Objects.requireNonNull(correction, "correction must not be null");
             if (mCorrectionsByCategory.size() >= getMaxCorrectionsByCategory()) {
                 throw new IllegalArgumentException("Too many corrections by category");
             }
@@ -484,6 +490,7 @@
          * @param description brief text describing the curve pushed. It maybe truncated
          *                    and will not be displayed in the UI
          */
+        @NonNull
         public Builder setDescription(@Nullable String description) {
             mDescription = description;
             return this;
@@ -492,6 +499,7 @@
         /**
          * Builds the {@link BrightnessConfiguration}.
          */
+        @NonNull
         public BrightnessConfiguration build() {
             if (mCurveLux == null || mCurveNits == null) {
                 throw new IllegalStateException("A curve must be set!");
diff --git a/core/java/android/hardware/display/BrightnessCorrection.java b/core/java/android/hardware/display/BrightnessCorrection.java
index 6a073ff..b029acc 100644
--- a/core/java/android/hardware/display/BrightnessCorrection.java
+++ b/core/java/android/hardware/display/BrightnessCorrection.java
@@ -16,6 +16,7 @@
 
 package android.hardware.display;
 
+import android.annotation.FloatRange;
 import android.annotation.NonNull;
 import android.annotation.SystemApi;
 import android.annotation.TestApi;
@@ -59,15 +60,15 @@
 
     /**
      * Creates a BrightnessCorrection that given {@code brightness}, corrects it to be
-     * {@code exp(scale * log(brightness) + translate)}.
+     * {@code exp(scale * ln(brightness) + translate)}.
      *
      * @param scale
-     *      How much to scale the log brightness.
+     *      How much to scale the log (base e) brightness.
      * @param translate
-     *      How much to translate the log brightness.
+     *      How much to translate the log (base e) brightness.
      *
      * @return A BrightnessCorrection that given {@code brightness}, corrects it to be
-     * {@code exp(scale * log(brightness) + translate)}.
+     * {@code exp(scale * ln(brightness) + translate)}.
      *
      * @throws IllegalArgumentException
      *      - scale or translate are NaN.
@@ -87,7 +88,8 @@
      *
      * @return The corrected brightness.
      */
-    public float apply(float brightness) {
+    @FloatRange(from = 0.0)
+    public float apply(@FloatRange(from = 0.0) float brightness) {
         return mImplementation.apply(brightness);
     }
 
@@ -118,7 +120,7 @@
         return mImplementation.hashCode();
     }
 
-    public static final Creator<BrightnessCorrection> CREATOR =
+    public static final @android.annotation.NonNull Creator<BrightnessCorrection> CREATOR =
             new Creator<BrightnessCorrection>() {
                 public BrightnessCorrection createFromParcel(Parcel in) {
                     final int type = in.readInt();
@@ -202,7 +204,7 @@
 
     /**
      * A BrightnessCorrection that given {@code brightness}, corrects it to be
-     * {@code exp(scale * log(brightness) + translate)}.
+     * {@code exp(scale * ln(brightness) + translate)}.
      */
     private static class ScaleAndTranslateLog implements BrightnessCorrectionImplementation {
         private static final float MIN_SCALE = 0.5f;
diff --git a/core/java/android/hardware/display/Curve.java b/core/java/android/hardware/display/Curve.java
index 41f66f5..0010515 100644
--- a/core/java/android/hardware/display/Curve.java
+++ b/core/java/android/hardware/display/Curve.java
@@ -37,7 +37,7 @@
         return mY;
     }
 
-    public static final Creator<Curve> CREATOR = new Creator<Curve>() {
+    public static final @android.annotation.NonNull Creator<Curve> CREATOR = new Creator<Curve>() {
         public Curve createFromParcel(Parcel in) {
             float[] x = in.createFloatArray();
             float[] y = in.createFloatArray();
diff --git a/core/java/android/hardware/display/IDisplayManager.aidl b/core/java/android/hardware/display/IDisplayManager.aidl
index 5ea8bd6..edd2051 100644
--- a/core/java/android/hardware/display/IDisplayManager.aidl
+++ b/core/java/android/hardware/display/IDisplayManager.aidl
@@ -30,6 +30,7 @@
 
 /** @hide */
 interface IDisplayManager {
+    @UnsupportedAppUsage
     DisplayInfo getDisplayInfo(int displayId);
     int[] getDisplayIds();
 
diff --git a/core/java/android/hardware/display/Time.java b/core/java/android/hardware/display/Time.java
index b943ac6..87e5b38 100644
--- a/core/java/android/hardware/display/Time.java
+++ b/core/java/android/hardware/display/Time.java
@@ -62,7 +62,7 @@
         return LocalTime.of(mHour, mMinute, mSecond, mNano);
     }
 
-    public static final Parcelable.Creator<Time> CREATOR = new Parcelable.Creator<Time>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<Time> CREATOR = new Parcelable.Creator<Time>() {
 
         @Override
         public Time createFromParcel(Parcel source) {
diff --git a/core/java/android/hardware/display/WifiDisplay.java b/core/java/android/hardware/display/WifiDisplay.java
index 12486e8..55e6051 100644
--- a/core/java/android/hardware/display/WifiDisplay.java
+++ b/core/java/android/hardware/display/WifiDisplay.java
@@ -40,7 +40,7 @@
 
     public static final WifiDisplay[] EMPTY_ARRAY = new WifiDisplay[0];
 
-    public static final Creator<WifiDisplay> CREATOR = new Creator<WifiDisplay>() {
+    public static final @android.annotation.NonNull Creator<WifiDisplay> CREATOR = new Creator<WifiDisplay>() {
         public WifiDisplay createFromParcel(Parcel in) {
             String deviceAddress = in.readString();
             String deviceName = in.readString();
diff --git a/core/java/android/hardware/display/WifiDisplaySessionInfo.java b/core/java/android/hardware/display/WifiDisplaySessionInfo.java
index 33d2725..9fb85f9 100644
--- a/core/java/android/hardware/display/WifiDisplaySessionInfo.java
+++ b/core/java/android/hardware/display/WifiDisplaySessionInfo.java
@@ -36,7 +36,7 @@
     private final String mPassphrase;
     private final String mIP;
 
-    public static final Creator<WifiDisplaySessionInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiDisplaySessionInfo> CREATOR =
             new Creator<WifiDisplaySessionInfo>() {
         @Override
         public WifiDisplaySessionInfo createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/display/WifiDisplayStatus.java b/core/java/android/hardware/display/WifiDisplayStatus.java
index c267834..1973e51 100644
--- a/core/java/android/hardware/display/WifiDisplayStatus.java
+++ b/core/java/android/hardware/display/WifiDisplayStatus.java
@@ -69,7 +69,7 @@
     @UnsupportedAppUsage
     public static final int DISPLAY_STATE_CONNECTED = 2;
 
-    public static final Creator<WifiDisplayStatus> CREATOR = new Creator<WifiDisplayStatus>() {
+    public static final @android.annotation.NonNull Creator<WifiDisplayStatus> CREATOR = new Creator<WifiDisplayStatus>() {
         public WifiDisplayStatus createFromParcel(Parcel in) {
             int featureState = in.readInt();
             int scanState = in.readInt();
diff --git a/core/java/android/hardware/face/Face.java b/core/java/android/hardware/face/Face.java
index d6724d7..b90fafe 100644
--- a/core/java/android/hardware/face/Face.java
+++ b/core/java/android/hardware/face/Face.java
@@ -54,7 +54,7 @@
         out.writeLong(getDeviceId());
     }
 
-    public static final Parcelable.Creator<Face> CREATOR = new Parcelable.Creator<Face>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<Face> CREATOR = new Parcelable.Creator<Face>() {
             public Face createFromParcel(Parcel in) {
                 return new Face(in);
             }
diff --git a/core/java/android/hardware/fingerprint/Fingerprint.java b/core/java/android/hardware/fingerprint/Fingerprint.java
index bbd3d05..57e52d9 100644
--- a/core/java/android/hardware/fingerprint/Fingerprint.java
+++ b/core/java/android/hardware/fingerprint/Fingerprint.java
@@ -55,7 +55,7 @@
         out.writeInt(mGroupId);
     }
 
-    public static final Parcelable.Creator<Fingerprint> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Fingerprint> CREATOR
             = new Parcelable.Creator<Fingerprint>() {
         public Fingerprint createFromParcel(Parcel in) {
             return new Fingerprint(in);
diff --git a/core/java/android/hardware/hdmi/HdmiDeviceInfo.java b/core/java/android/hardware/hdmi/HdmiDeviceInfo.java
index 48ea9a6..1362116 100644
--- a/core/java/android/hardware/hdmi/HdmiDeviceInfo.java
+++ b/core/java/android/hardware/hdmi/HdmiDeviceInfo.java
@@ -116,7 +116,7 @@
     /**
      * A helper class to deserialize {@link HdmiDeviceInfo} for a parcel.
      */
-    public static final Parcelable.Creator<HdmiDeviceInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<HdmiDeviceInfo> CREATOR =
             new Parcelable.Creator<HdmiDeviceInfo>() {
                 @Override
                 public HdmiDeviceInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/hardware/hdmi/HdmiHotplugEvent.java b/core/java/android/hardware/hdmi/HdmiHotplugEvent.java
index 9476742..07cbdcc 100644
--- a/core/java/android/hardware/hdmi/HdmiHotplugEvent.java
+++ b/core/java/android/hardware/hdmi/HdmiHotplugEvent.java
@@ -83,7 +83,7 @@
         dest.writeByte((byte) (mConnected ? 1 : 0));
     }
 
-    public static final Parcelable.Creator<HdmiHotplugEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<HdmiHotplugEvent> CREATOR
             = new Parcelable.Creator<HdmiHotplugEvent>() {
         /**
          * Rebuilds a {@link HdmiHotplugEvent} previously stored with
diff --git a/core/java/android/hardware/hdmi/HdmiPortInfo.java b/core/java/android/hardware/hdmi/HdmiPortInfo.java
index 1f0f45a..f17cfba 100644
--- a/core/java/android/hardware/hdmi/HdmiPortInfo.java
+++ b/core/java/android/hardware/hdmi/HdmiPortInfo.java
@@ -126,7 +126,7 @@
     /**
      * A helper class to deserialize {@link HdmiPortInfo} for a parcel.
      */
-    public static final Parcelable.Creator<HdmiPortInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<HdmiPortInfo> CREATOR =
             new Parcelable.Creator<HdmiPortInfo>() {
                 @Override
                 public HdmiPortInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/hardware/input/IInputManager.aidl b/core/java/android/hardware/input/IInputManager.aidl
index 64448fd..2923bbf 100644
--- a/core/java/android/hardware/input/IInputManager.aidl
+++ b/core/java/android/hardware/input/IInputManager.aidl
@@ -45,6 +45,7 @@
 
     // Injects an input event into the system.  To inject into windows owned by other
     // applications, the caller must have the INJECT_EVENTS permission.
+    @UnsupportedAppUsage
     boolean injectInputEvent(in InputEvent ev, int mode);
 
     // Calibrate input device position
diff --git a/core/java/android/hardware/input/InputDeviceIdentifier.java b/core/java/android/hardware/input/InputDeviceIdentifier.java
index 801da88..26f2393 100644
--- a/core/java/android/hardware/input/InputDeviceIdentifier.java
+++ b/core/java/android/hardware/input/InputDeviceIdentifier.java
@@ -83,7 +83,7 @@
         return Objects.hash(mDescriptor, mVendorId, mProductId);
     }
 
-    public static final Parcelable.Creator<InputDeviceIdentifier> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<InputDeviceIdentifier> CREATOR =
             new Parcelable.Creator<InputDeviceIdentifier>() {
 
         @Override
diff --git a/core/java/android/hardware/input/KeyboardLayout.java b/core/java/android/hardware/input/KeyboardLayout.java
index d395578..5bdbae3 100644
--- a/core/java/android/hardware/input/KeyboardLayout.java
+++ b/core/java/android/hardware/input/KeyboardLayout.java
@@ -39,7 +39,7 @@
     private final int mVendorId;
     private final int mProductId;
 
-    public static final Parcelable.Creator<KeyboardLayout> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<KeyboardLayout> CREATOR =
             new Parcelable.Creator<KeyboardLayout>() {
         public KeyboardLayout createFromParcel(Parcel source) {
             return new KeyboardLayout(source);
diff --git a/core/java/android/hardware/input/TouchCalibration.java b/core/java/android/hardware/input/TouchCalibration.java
index 025fad0..7a6eba2 100644
--- a/core/java/android/hardware/input/TouchCalibration.java
+++ b/core/java/android/hardware/input/TouchCalibration.java
@@ -28,7 +28,7 @@
 
     public static final TouchCalibration IDENTITY = new TouchCalibration();
 
-    public static final Parcelable.Creator<TouchCalibration> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<TouchCalibration> CREATOR
             = new Parcelable.Creator<TouchCalibration>() {
         public TouchCalibration createFromParcel(Parcel in) {
             return new TouchCalibration(in);
diff --git a/core/java/android/hardware/location/ActivityChangedEvent.java b/core/java/android/hardware/location/ActivityChangedEvent.java
index 16cfe6e..d538f57 100644
--- a/core/java/android/hardware/location/ActivityChangedEvent.java
+++ b/core/java/android/hardware/location/ActivityChangedEvent.java
@@ -46,7 +46,7 @@
         return mActivityRecognitionEvents;
     }
 
-    public static final Creator<ActivityChangedEvent> CREATOR =
+    public static final @android.annotation.NonNull Creator<ActivityChangedEvent> CREATOR =
             new Creator<ActivityChangedEvent>() {
         @Override
         public ActivityChangedEvent createFromParcel(Parcel source) {
diff --git a/core/java/android/hardware/location/ActivityRecognitionEvent.java b/core/java/android/hardware/location/ActivityRecognitionEvent.java
index 190030a..08ce86f 100644
--- a/core/java/android/hardware/location/ActivityRecognitionEvent.java
+++ b/core/java/android/hardware/location/ActivityRecognitionEvent.java
@@ -47,7 +47,7 @@
         return mTimestampNs;
     }
 
-    public static final Creator<ActivityRecognitionEvent> CREATOR =
+    public static final @android.annotation.NonNull Creator<ActivityRecognitionEvent> CREATOR =
             new Creator<ActivityRecognitionEvent>() {
         @Override
         public ActivityRecognitionEvent createFromParcel(Parcel source) {
diff --git a/core/java/android/hardware/location/ContextHubInfo.java b/core/java/android/hardware/location/ContextHubInfo.java
index 51daa92..b5da381 100644
--- a/core/java/android/hardware/location/ContextHubInfo.java
+++ b/core/java/android/hardware/location/ContextHubInfo.java
@@ -345,7 +345,7 @@
         out.writeTypedArray(mMemoryRegions, flags);
     }
 
-    public static final Parcelable.Creator<ContextHubInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ContextHubInfo> CREATOR
             = new Parcelable.Creator<ContextHubInfo>() {
         public ContextHubInfo createFromParcel(Parcel in) {
             return new ContextHubInfo(in);
diff --git a/core/java/android/hardware/location/ContextHubMessage.java b/core/java/android/hardware/location/ContextHubMessage.java
index e1c69d7..bf10048 100644
--- a/core/java/android/hardware/location/ContextHubMessage.java
+++ b/core/java/android/hardware/location/ContextHubMessage.java
@@ -125,7 +125,7 @@
         out.writeByteArray(mData);
     }
 
-    public static final Parcelable.Creator<ContextHubMessage> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ContextHubMessage> CREATOR
             = new Parcelable.Creator<ContextHubMessage>() {
         public ContextHubMessage createFromParcel(Parcel in) {
             return new ContextHubMessage(in);
diff --git a/core/java/android/hardware/location/GeofenceHardwareMonitorEvent.java b/core/java/android/hardware/location/GeofenceHardwareMonitorEvent.java
index 7079237..fbbf687 100644
--- a/core/java/android/hardware/location/GeofenceHardwareMonitorEvent.java
+++ b/core/java/android/hardware/location/GeofenceHardwareMonitorEvent.java
@@ -72,7 +72,7 @@
         return mLocation;
     }
 
-    public static final Creator<GeofenceHardwareMonitorEvent> CREATOR =
+    public static final @android.annotation.NonNull Creator<GeofenceHardwareMonitorEvent> CREATOR =
             new Creator<GeofenceHardwareMonitorEvent>() {
                 @Override
                 public GeofenceHardwareMonitorEvent createFromParcel(Parcel source) {
diff --git a/core/java/android/hardware/location/GeofenceHardwareRequestParcelable.java b/core/java/android/hardware/location/GeofenceHardwareRequestParcelable.java
index d3311f5..df13ade 100644
--- a/core/java/android/hardware/location/GeofenceHardwareRequestParcelable.java
+++ b/core/java/android/hardware/location/GeofenceHardwareRequestParcelable.java
@@ -134,7 +134,7 @@
     /**
      * Method definitions to support Parcelable operations.
      */
-    public static final Parcelable.Creator<GeofenceHardwareRequestParcelable> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<GeofenceHardwareRequestParcelable> CREATOR =
             new Parcelable.Creator<GeofenceHardwareRequestParcelable>() {
         @Override
         public GeofenceHardwareRequestParcelable createFromParcel(Parcel parcel) {
diff --git a/core/java/android/hardware/location/IActivityRecognitionHardwareClient.aidl b/core/java/android/hardware/location/IActivityRecognitionHardwareClient.aidl
index 3fe645c..2dfaf60 100644
--- a/core/java/android/hardware/location/IActivityRecognitionHardwareClient.aidl
+++ b/core/java/android/hardware/location/IActivityRecognitionHardwareClient.aidl
@@ -32,5 +32,6 @@
      * @param isSupported whether the platform has hardware support for the feature
      * @param instance the available instance to provide access to the feature
      */
+    @UnsupportedAppUsage
     void onAvailabilityChanged(in boolean isSupported, in IActivityRecognitionHardware instance);
 }
diff --git a/core/java/android/hardware/location/MemoryRegion.java b/core/java/android/hardware/location/MemoryRegion.java
index 3d9e859..ecd369a 100644
--- a/core/java/android/hardware/location/MemoryRegion.java
+++ b/core/java/android/hardware/location/MemoryRegion.java
@@ -147,7 +147,7 @@
         mIsExecutable = source.readInt() != 0;
     }
 
-    public static final Parcelable.Creator<MemoryRegion> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<MemoryRegion> CREATOR
             = new Parcelable.Creator<MemoryRegion>() {
         public MemoryRegion createFromParcel(Parcel in) {
             return new MemoryRegion(in);
diff --git a/core/java/android/hardware/location/NanoApp.java b/core/java/android/hardware/location/NanoApp.java
index 62e7182..3fbb069 100644
--- a/core/java/android/hardware/location/NanoApp.java
+++ b/core/java/android/hardware/location/NanoApp.java
@@ -359,7 +359,7 @@
         out.writeByteArray(mAppBinary);
     }
 
-    public static final Parcelable.Creator<NanoApp> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<NanoApp> CREATOR
             = new Parcelable.Creator<NanoApp>() {
         public NanoApp createFromParcel(Parcel in) {
             return new NanoApp(in);
diff --git a/core/java/android/hardware/location/NanoAppBinary.java b/core/java/android/hardware/location/NanoAppBinary.java
index ba01ca2..b311a92 100644
--- a/core/java/android/hardware/location/NanoAppBinary.java
+++ b/core/java/android/hardware/location/NanoAppBinary.java
@@ -237,7 +237,7 @@
         out.writeByteArray(mNanoAppBinary);
     }
 
-    public static final Creator<NanoAppBinary> CREATOR =
+    public static final @android.annotation.NonNull Creator<NanoAppBinary> CREATOR =
             new Creator<NanoAppBinary>() {
                 @Override
                 public NanoAppBinary createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/location/NanoAppFilter.java b/core/java/android/hardware/location/NanoAppFilter.java
index 562065e..0700dd1 100644
--- a/core/java/android/hardware/location/NanoAppFilter.java
+++ b/core/java/android/hardware/location/NanoAppFilter.java
@@ -139,7 +139,7 @@
                 + ", vendorMask: " + mAppIdVendorMask;
     }
 
-    public static final Parcelable.Creator<NanoAppFilter> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<NanoAppFilter> CREATOR
             = new Parcelable.Creator<NanoAppFilter>() {
         public NanoAppFilter createFromParcel(Parcel in) {
             return new NanoAppFilter(in);
diff --git a/core/java/android/hardware/location/NanoAppInstanceInfo.java b/core/java/android/hardware/location/NanoAppInstanceInfo.java
index 2db6a79..a6c754d 100644
--- a/core/java/android/hardware/location/NanoAppInstanceInfo.java
+++ b/core/java/android/hardware/location/NanoAppInstanceInfo.java
@@ -208,7 +208,7 @@
         out.writeIntArray(mOutputEvents);
     }
 
-    public static final Parcelable.Creator<NanoAppInstanceInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<NanoAppInstanceInfo> CREATOR
             = new Parcelable.Creator<NanoAppInstanceInfo>() {
         public NanoAppInstanceInfo createFromParcel(Parcel in) {
             return new NanoAppInstanceInfo(in);
diff --git a/core/java/android/hardware/location/NanoAppMessage.java b/core/java/android/hardware/location/NanoAppMessage.java
index 9f90d59..d5e3529 100644
--- a/core/java/android/hardware/location/NanoAppMessage.java
+++ b/core/java/android/hardware/location/NanoAppMessage.java
@@ -134,7 +134,7 @@
         out.writeByteArray(mMessageBody);
     }
 
-    public static final Creator<NanoAppMessage> CREATOR =
+    public static final @android.annotation.NonNull Creator<NanoAppMessage> CREATOR =
             new Creator<NanoAppMessage>() {
                 @Override
                 public NanoAppMessage createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/location/NanoAppState.java b/core/java/android/hardware/location/NanoAppState.java
index d05277d..8de7ecd 100644
--- a/core/java/android/hardware/location/NanoAppState.java
+++ b/core/java/android/hardware/location/NanoAppState.java
@@ -75,7 +75,7 @@
         out.writeInt(mIsEnabled ? 1 : 0);
     }
 
-    public static final Creator<NanoAppState> CREATOR =
+    public static final @android.annotation.NonNull Creator<NanoAppState> CREATOR =
             new Creator<NanoAppState>() {
                 @Override
                 public NanoAppState createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/radio/Announcement.java b/core/java/android/hardware/radio/Announcement.java
index 166fe60..8febed3 100644
--- a/core/java/android/hardware/radio/Announcement.java
+++ b/core/java/android/hardware/radio/Announcement.java
@@ -108,7 +108,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<Announcement> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<Announcement> CREATOR =
             new Parcelable.Creator<Announcement>() {
         public Announcement createFromParcel(Parcel in) {
             return new Announcement(in);
diff --git a/core/java/android/hardware/radio/ProgramList.java b/core/java/android/hardware/radio/ProgramList.java
index e6f523c..69f9273 100644
--- a/core/java/android/hardware/radio/ProgramList.java
+++ b/core/java/android/hardware/radio/ProgramList.java
@@ -304,7 +304,7 @@
             return 0;
         }
 
-        public static final Parcelable.Creator<Filter> CREATOR = new Parcelable.Creator<Filter>() {
+        public static final @android.annotation.NonNull Parcelable.Creator<Filter> CREATOR = new Parcelable.Creator<Filter>() {
             public Filter createFromParcel(Parcel in) {
                 return new Filter(in);
             }
@@ -409,7 +409,7 @@
             return 0;
         }
 
-        public static final Parcelable.Creator<Chunk> CREATOR = new Parcelable.Creator<Chunk>() {
+        public static final @android.annotation.NonNull Parcelable.Creator<Chunk> CREATOR = new Parcelable.Creator<Chunk>() {
             public Chunk createFromParcel(Parcel in) {
                 return new Chunk(in);
             }
diff --git a/core/java/android/hardware/radio/ProgramSelector.java b/core/java/android/hardware/radio/ProgramSelector.java
index 90d407c..277a186 100644
--- a/core/java/android/hardware/radio/ProgramSelector.java
+++ b/core/java/android/hardware/radio/ProgramSelector.java
@@ -534,7 +534,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<ProgramSelector> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ProgramSelector> CREATOR =
             new Parcelable.Creator<ProgramSelector>() {
         public ProgramSelector createFromParcel(Parcel in) {
             return new ProgramSelector(in);
@@ -632,7 +632,7 @@
             return 0;
         }
 
-        public static final Parcelable.Creator<Identifier> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<Identifier> CREATOR =
                 new Parcelable.Creator<Identifier>() {
             public Identifier createFromParcel(Parcel in) {
                 return new Identifier(in);
diff --git a/core/java/android/hardware/radio/RadioManager.java b/core/java/android/hardware/radio/RadioManager.java
index 8263bb8..92653d18 100644
--- a/core/java/android/hardware/radio/RadioManager.java
+++ b/core/java/android/hardware/radio/RadioManager.java
@@ -448,7 +448,7 @@
             mVendorInfo = Utils.readStringMap(in);
         }
 
-        public static final Parcelable.Creator<ModuleProperties> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<ModuleProperties> CREATOR
                 = new Parcelable.Creator<ModuleProperties>() {
             public ModuleProperties createFromParcel(Parcel in) {
                 return new ModuleProperties(in);
@@ -625,7 +625,7 @@
             return type;
         }
 
-        public static final Parcelable.Creator<BandDescriptor> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<BandDescriptor> CREATOR
                 = new Parcelable.Creator<BandDescriptor>() {
             public BandDescriptor createFromParcel(Parcel in) {
                 int type = lookupTypeFromParcel(in);
@@ -762,7 +762,7 @@
             mEa = in.readByte() == 1;
         }
 
-        public static final Parcelable.Creator<FmBandDescriptor> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<FmBandDescriptor> CREATOR
                 = new Parcelable.Creator<FmBandDescriptor>() {
             public FmBandDescriptor createFromParcel(Parcel in) {
                 return new FmBandDescriptor(in);
@@ -855,7 +855,7 @@
             mStereo = in.readByte() == 1;
         }
 
-        public static final Parcelable.Creator<AmBandDescriptor> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<AmBandDescriptor> CREATOR
                 = new Parcelable.Creator<AmBandDescriptor>() {
             public AmBandDescriptor createFromParcel(Parcel in) {
                 return new AmBandDescriptor(in);
@@ -966,7 +966,7 @@
         }
 
 
-        public static final Parcelable.Creator<BandConfig> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<BandConfig> CREATOR
                 = new Parcelable.Creator<BandConfig>() {
             public BandConfig createFromParcel(Parcel in) {
                 int type = BandDescriptor.lookupTypeFromParcel(in);
@@ -1099,7 +1099,7 @@
             mEa = in.readByte() == 1;
         }
 
-        public static final Parcelable.Creator<FmBandConfig> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<FmBandConfig> CREATOR
                 = new Parcelable.Creator<FmBandConfig>() {
             public FmBandConfig createFromParcel(Parcel in) {
                 return new FmBandConfig(in);
@@ -1295,7 +1295,7 @@
             mStereo = in.readByte() == 1;
         }
 
-        public static final Parcelable.Creator<AmBandConfig> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<AmBandConfig> CREATOR
                 = new Parcelable.Creator<AmBandConfig>() {
             public AmBandConfig createFromParcel(Parcel in) {
                 return new AmBandConfig(in);
@@ -1628,7 +1628,7 @@
             mVendorInfo = Utils.readStringMap(in);
         }
 
-        public static final Parcelable.Creator<ProgramInfo> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<ProgramInfo> CREATOR
                 = new Parcelable.Creator<ProgramInfo>() {
             public ProgramInfo createFromParcel(Parcel in) {
                 return new ProgramInfo(in);
diff --git a/core/java/android/hardware/radio/RadioMetadata.java b/core/java/android/hardware/radio/RadioMetadata.java
index baa7a50..1cbb171 100644
--- a/core/java/android/hardware/radio/RadioMetadata.java
+++ b/core/java/android/hardware/radio/RadioMetadata.java
@@ -225,7 +225,7 @@
             out.writeInt(mTimezoneOffsetMinutes);
         }
 
-        public static final Parcelable.Creator<Clock> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<Clock> CREATOR
                 = new Parcelable.Creator<Clock>() {
             public Clock createFromParcel(Parcel in) {
                 return new Clock(in);
@@ -426,7 +426,7 @@
         return NATIVE_KEY_MAPPING.get(nativeKey, null);
     }
 
-    public static final Parcelable.Creator<RadioMetadata> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<RadioMetadata> CREATOR =
             new Parcelable.Creator<RadioMetadata>() {
                 @Override
                 public RadioMetadata createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/soundtrigger/SoundTrigger.java b/core/java/android/hardware/soundtrigger/SoundTrigger.java
index dc4f0b7..cf3395a 100644
--- a/core/java/android/hardware/soundtrigger/SoundTrigger.java
+++ b/core/java/android/hardware/soundtrigger/SoundTrigger.java
@@ -140,7 +140,7 @@
             this.returnsTriggerInEvent = returnsTriggerInEvent;
         }
 
-        public static final Parcelable.Creator<ModuleProperties> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<ModuleProperties> CREATOR
                 = new Parcelable.Creator<ModuleProperties>() {
             public ModuleProperties createFromParcel(Parcel in) {
                 return ModuleProperties.fromParcel(in);
@@ -326,7 +326,7 @@
             this.users = users;
         }
 
-        public static final Parcelable.Creator<Keyphrase> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<Keyphrase> CREATOR
                 = new Parcelable.Creator<Keyphrase>() {
             public Keyphrase createFromParcel(Parcel in) {
                 return Keyphrase.fromParcel(in);
@@ -436,7 +436,7 @@
             this.keyphrases = keyphrases;
         }
 
-        public static final Parcelable.Creator<KeyphraseSoundModel> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<KeyphraseSoundModel> CREATOR
                 = new Parcelable.Creator<KeyphraseSoundModel>() {
             public KeyphraseSoundModel createFromParcel(Parcel in) {
                 return KeyphraseSoundModel.fromParcel(in);
@@ -516,7 +516,7 @@
      ****************************************************************************/
     public static class GenericSoundModel extends SoundModel implements Parcelable {
 
-        public static final Parcelable.Creator<GenericSoundModel> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<GenericSoundModel> CREATOR
                 = new Parcelable.Creator<GenericSoundModel>() {
             public GenericSoundModel createFromParcel(Parcel in) {
                 return GenericSoundModel.fromParcel(in);
@@ -746,7 +746,7 @@
         }
 
         /** @hide */
-        public static final Parcelable.Creator<RecognitionEvent> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<RecognitionEvent> CREATOR
                 = new Parcelable.Creator<RecognitionEvent>() {
             public RecognitionEvent createFromParcel(Parcel in) {
                 return RecognitionEvent.fromParcel(in);
@@ -920,7 +920,7 @@
             this.data = data;
         }
 
-        public static final Parcelable.Creator<RecognitionConfig> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<RecognitionConfig> CREATOR
                 = new Parcelable.Creator<RecognitionConfig>() {
             public RecognitionConfig createFromParcel(Parcel in) {
                 return RecognitionConfig.fromParcel(in);
@@ -983,7 +983,7 @@
             this.confidenceLevel = confidenceLevel;
         }
 
-        public static final Parcelable.Creator<ConfidenceLevel> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<ConfidenceLevel> CREATOR
                 = new Parcelable.Creator<ConfidenceLevel>() {
             public ConfidenceLevel createFromParcel(Parcel in) {
                 return ConfidenceLevel.fromParcel(in);
@@ -1077,7 +1077,7 @@
             this.confidenceLevels = confidenceLevels;
         }
 
-        public static final Parcelable.Creator<KeyphraseRecognitionExtra> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<KeyphraseRecognitionExtra> CREATOR
                 = new Parcelable.Creator<KeyphraseRecognitionExtra>() {
             public KeyphraseRecognitionExtra createFromParcel(Parcel in) {
                 return KeyphraseRecognitionExtra.fromParcel(in);
@@ -1169,7 +1169,7 @@
             this.keyphraseExtras = keyphraseExtras;
         }
 
-        public static final Parcelable.Creator<KeyphraseRecognitionEvent> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<KeyphraseRecognitionEvent> CREATOR
                 = new Parcelable.Creator<KeyphraseRecognitionEvent>() {
             public KeyphraseRecognitionEvent createFromParcel(Parcel in) {
                 return KeyphraseRecognitionEvent.fromParcelForKeyphrase(in);
@@ -1290,7 +1290,7 @@
                     data);
         }
 
-        public static final Parcelable.Creator<GenericRecognitionEvent> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<GenericRecognitionEvent> CREATOR
                 = new Parcelable.Creator<GenericRecognitionEvent>() {
             public GenericRecognitionEvent createFromParcel(Parcel in) {
                 return GenericRecognitionEvent.fromParcelForGeneric(in);
@@ -1357,7 +1357,7 @@
             this.data = data;
         }
 
-        public static final Parcelable.Creator<SoundModelEvent> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<SoundModelEvent> CREATOR
                 = new Parcelable.Creator<SoundModelEvent>() {
             public SoundModelEvent createFromParcel(Parcel in) {
                 return SoundModelEvent.fromParcel(in);
diff --git a/core/java/android/hardware/usb/ParcelableUsbPort.java b/core/java/android/hardware/usb/ParcelableUsbPort.java
index 30388af..19655ed 100644
--- a/core/java/android/hardware/usb/ParcelableUsbPort.java
+++ b/core/java/android/hardware/usb/ParcelableUsbPort.java
@@ -89,7 +89,7 @@
         dest.writeBoolean(mSupportsEnableContaminantPresenceDetection);
     }
 
-    public static final Creator<ParcelableUsbPort> CREATOR =
+    public static final @android.annotation.NonNull Creator<ParcelableUsbPort> CREATOR =
             new Creator<ParcelableUsbPort>() {
                 @Override
                 public ParcelableUsbPort createFromParcel(Parcel in) {
diff --git a/core/java/android/hardware/usb/UsbAccessory.java b/core/java/android/hardware/usb/UsbAccessory.java
index b418d43..a76e4ad 100644
--- a/core/java/android/hardware/usb/UsbAccessory.java
+++ b/core/java/android/hardware/usb/UsbAccessory.java
@@ -215,7 +215,7 @@
                             ", mSerialNumberReader=" + mSerialNumberReader + "]";
     }
 
-    public static final Parcelable.Creator<UsbAccessory> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<UsbAccessory> CREATOR =
         new Parcelable.Creator<UsbAccessory>() {
         public UsbAccessory createFromParcel(Parcel in) {
             String manufacturer = in.readString();
diff --git a/core/java/android/hardware/usb/UsbConfiguration.java b/core/java/android/hardware/usb/UsbConfiguration.java
index 6ce4201..66269cb 100644
--- a/core/java/android/hardware/usb/UsbConfiguration.java
+++ b/core/java/android/hardware/usb/UsbConfiguration.java
@@ -165,7 +165,7 @@
         return builder.toString();
     }
 
-    public static final Parcelable.Creator<UsbConfiguration> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<UsbConfiguration> CREATOR =
         new Parcelable.Creator<UsbConfiguration>() {
         public UsbConfiguration createFromParcel(Parcel in) {
             int id = in.readInt();
diff --git a/core/java/android/hardware/usb/UsbDevice.java b/core/java/android/hardware/usb/UsbDevice.java
index b08212c..08c9eea 100644
--- a/core/java/android/hardware/usb/UsbDevice.java
+++ b/core/java/android/hardware/usb/UsbDevice.java
@@ -300,7 +300,7 @@
         return builder.toString();
     }
 
-    public static final Parcelable.Creator<UsbDevice> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<UsbDevice> CREATOR =
         new Parcelable.Creator<UsbDevice>() {
         public UsbDevice createFromParcel(Parcel in) {
             String name = in.readString();
diff --git a/core/java/android/hardware/usb/UsbEndpoint.java b/core/java/android/hardware/usb/UsbEndpoint.java
index c346700..82117e7 100644
--- a/core/java/android/hardware/usb/UsbEndpoint.java
+++ b/core/java/android/hardware/usb/UsbEndpoint.java
@@ -133,7 +133,7 @@
                 ",mMaxPacketSize=" + mMaxPacketSize + ",mInterval=" + mInterval +"]";
     }
 
-    public static final Parcelable.Creator<UsbEndpoint> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<UsbEndpoint> CREATOR =
         new Parcelable.Creator<UsbEndpoint>() {
         public UsbEndpoint createFromParcel(Parcel in) {
             int address = in.readInt();
diff --git a/core/java/android/hardware/usb/UsbInterface.java b/core/java/android/hardware/usb/UsbInterface.java
index 4b5278c..5cb55a2 100644
--- a/core/java/android/hardware/usb/UsbInterface.java
+++ b/core/java/android/hardware/usb/UsbInterface.java
@@ -162,7 +162,7 @@
         return builder.toString();
     }
 
-    public static final Parcelable.Creator<UsbInterface> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<UsbInterface> CREATOR =
         new Parcelable.Creator<UsbInterface>() {
         public UsbInterface createFromParcel(Parcel in) {
             int id = in.readInt();
diff --git a/core/java/android/hardware/usb/UsbPortStatus.java b/core/java/android/hardware/usb/UsbPortStatus.java
index 426dba8..5e9a410 100644
--- a/core/java/android/hardware/usb/UsbPortStatus.java
+++ b/core/java/android/hardware/usb/UsbPortStatus.java
@@ -352,7 +352,7 @@
         dest.writeInt(mContaminantDetectionStatus);
     }
 
-    public static final Parcelable.Creator<UsbPortStatus> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<UsbPortStatus> CREATOR =
             new Parcelable.Creator<UsbPortStatus>() {
         @Override
         public UsbPortStatus createFromParcel(Parcel in) {
diff --git a/core/java/android/net/CaptivePortal.java b/core/java/android/net/CaptivePortal.java
index 3ab35e1..f208724 100644
--- a/core/java/android/net/CaptivePortal.java
+++ b/core/java/android/net/CaptivePortal.java
@@ -61,7 +61,7 @@
         out.writeStrongBinder(mBinder);
     }
 
-    public static final Parcelable.Creator<CaptivePortal> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<CaptivePortal> CREATOR
             = new Parcelable.Creator<CaptivePortal>() {
         @Override
         public CaptivePortal createFromParcel(Parcel in) {
diff --git a/core/java/android/net/ConnectionInfo.java b/core/java/android/net/ConnectionInfo.java
index 58d0e05..4514a84 100644
--- a/core/java/android/net/ConnectionInfo.java
+++ b/core/java/android/net/ConnectionInfo.java
@@ -54,7 +54,7 @@
         out.writeInt(remote.getPort());
     }
 
-    public static final Creator<ConnectionInfo> CREATOR = new Creator<ConnectionInfo>() {
+    public static final @android.annotation.NonNull Creator<ConnectionInfo> CREATOR = new Creator<ConnectionInfo>() {
         public ConnectionInfo createFromParcel(Parcel in) {
             int protocol = in.readInt();
             InetAddress localAddress;
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index c1bce5e..64ed322 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -3684,7 +3684,8 @@
     /**
      * Registers to receive notifications about all networks which satisfy the given
      * {@link NetworkRequest}.  The callbacks will continue to be called until
-     * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
+     * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
+     * called.
      *
      * @param request {@link NetworkRequest} describing this request.
      * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
@@ -3700,7 +3701,8 @@
     /**
      * Registers to receive notifications about all networks which satisfy the given
      * {@link NetworkRequest}.  The callbacks will continue to be called until
-     * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
+     * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
+     * called.
      *
      * @param request {@link NetworkRequest} describing this request.
      * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
diff --git a/core/java/android/net/ConnectivityMetricsEvent.java b/core/java/android/net/ConnectivityMetricsEvent.java
index 394ac42..522add1 100644
--- a/core/java/android/net/ConnectivityMetricsEvent.java
+++ b/core/java/android/net/ConnectivityMetricsEvent.java
@@ -51,7 +51,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Parcelable.Creator<ConnectivityMetricsEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ConnectivityMetricsEvent> CREATOR
             = new Parcelable.Creator<ConnectivityMetricsEvent> (){
         public ConnectivityMetricsEvent createFromParcel(Parcel source) {
             return new ConnectivityMetricsEvent(source);
diff --git a/core/java/android/net/DataUsageRequest.java b/core/java/android/net/DataUsageRequest.java
index ac9a5a3..0ac8f7e7 100644
--- a/core/java/android/net/DataUsageRequest.java
+++ b/core/java/android/net/DataUsageRequest.java
@@ -69,7 +69,7 @@
         dest.writeLong(thresholdInBytes);
     }
 
-    public static final Creator<DataUsageRequest> CREATOR =
+    public static final @android.annotation.NonNull Creator<DataUsageRequest> CREATOR =
             new Creator<DataUsageRequest>() {
                 @Override
                 public DataUsageRequest createFromParcel(Parcel in) {
diff --git a/core/java/android/net/DhcpInfo.java b/core/java/android/net/DhcpInfo.java
index 788d7d9..98bab44 100644
--- a/core/java/android/net/DhcpInfo.java
+++ b/core/java/android/net/DhcpInfo.java
@@ -84,7 +84,7 @@
     }
 
     /** Implement the Parcelable interface {@hide} */
-    public static final Creator<DhcpInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<DhcpInfo> CREATOR =
         new Creator<DhcpInfo>() {
             public DhcpInfo createFromParcel(Parcel in) {
                 DhcpInfo info = new DhcpInfo();
diff --git a/core/java/android/net/DhcpResults.java b/core/java/android/net/DhcpResults.java
index 6f9e65f..1a3a6f8 100644
--- a/core/java/android/net/DhcpResults.java
+++ b/core/java/android/net/DhcpResults.java
@@ -164,7 +164,7 @@
     /**
      * Implement the Parcelable interface
      */
-    public static final Creator<DhcpResults> CREATOR =
+    public static final @android.annotation.NonNull Creator<DhcpResults> CREATOR =
         new Creator<DhcpResults>() {
             public DhcpResults createFromParcel(Parcel in) {
                 return readFromParcel(in);
diff --git a/core/java/android/net/IConnectivityManager.aidl b/core/java/android/net/IConnectivityManager.aidl
index 87c62d2..6728712 100644
--- a/core/java/android/net/IConnectivityManager.aidl
+++ b/core/java/android/net/IConnectivityManager.aidl
@@ -47,10 +47,12 @@
 {
     Network getActiveNetwork();
     Network getActiveNetworkForUid(int uid, boolean ignoreBlocked);
+    @UnsupportedAppUsage
     NetworkInfo getActiveNetworkInfo();
     NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked);
     NetworkInfo getNetworkInfo(int networkType);
     NetworkInfo getNetworkInfoForUid(in Network network, int uid, boolean ignoreBlocked);
+    @UnsupportedAppUsage
     NetworkInfo[] getAllNetworkInfo();
     Network getNetworkForType(int networkType);
     Network[] getAllNetworks();
@@ -58,12 +60,14 @@
 
     boolean isNetworkSupported(int networkType);
 
+    @UnsupportedAppUsage
     LinkProperties getActiveLinkProperties();
     LinkProperties getLinkPropertiesForType(int networkType);
     LinkProperties getLinkProperties(in Network network);
 
     NetworkCapabilities getNetworkCapabilities(in Network network);
 
+    @UnsupportedAppUsage
     NetworkState[] getAllNetworkState();
 
     NetworkQuotaInfo getActiveNetworkQuotaInfo();
@@ -75,6 +79,7 @@
 
     int untether(String iface, String callerPkg);
 
+    @UnsupportedAppUsage
     int getLastTetherError(String iface);
 
     boolean isTetheringSupported(String callerPkg);
@@ -84,16 +89,21 @@
 
     void stopTethering(int type, String callerPkg);
 
+    @UnsupportedAppUsage
     String[] getTetherableIfaces();
 
+    @UnsupportedAppUsage
     String[] getTetheredIfaces();
 
+    @UnsupportedAppUsage
     String[] getTetheringErroredIfaces();
 
     String[] getTetheredDhcpRanges();
 
+    @UnsupportedAppUsage
     String[] getTetherableUsbRegexs();
 
+    @UnsupportedAppUsage
     String[] getTetherableWifiRegexs();
 
     String[] getTetherableBluetoothRegexs();
@@ -118,12 +128,11 @@
 
     VpnConfig getVpnConfig(int userId);
 
+    @UnsupportedAppUsage
     void startLegacyVpn(in VpnProfile profile);
 
     LegacyVpnInfo getLegacyVpnInfo(int userId);
 
-    VpnInfo[] getAllVpnInfo();
-
     boolean updateLockdownVpn();
     boolean isAlwaysOnVpnPackageSupported(int userId, String packageName);
     boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown,
diff --git a/core/java/android/net/INetworkPolicyManager.aidl b/core/java/android/net/INetworkPolicyManager.aidl
index e92302a..385cb1d 100644
--- a/core/java/android/net/INetworkPolicyManager.aidl
+++ b/core/java/android/net/INetworkPolicyManager.aidl
@@ -31,9 +31,11 @@
 interface INetworkPolicyManager {
 
     /** Control UID policies. */
+    @UnsupportedAppUsage
     void setUidPolicy(int uid, int policy);
     void addUidPolicy(int uid, int policy);
     void removeUidPolicy(int uid, int policy);
+    @UnsupportedAppUsage
     int getUidPolicy(int uid);
     int[] getUidsWithPolicy(int policy);
 
@@ -41,14 +43,18 @@
     void unregisterListener(INetworkPolicyListener listener);
 
     /** Control network policies atomically. */
+    @UnsupportedAppUsage
     void setNetworkPolicies(in NetworkPolicy[] policies);
     NetworkPolicy[] getNetworkPolicies(String callingPackage);
 
     /** Snooze limit on policy matching given template. */
+    @UnsupportedAppUsage
     void snoozeLimit(in NetworkTemplate template);
 
     /** Control if background data is restricted system-wide. */
+    @UnsupportedAppUsage
     void setRestrictBackground(boolean restrictBackground);
+    @UnsupportedAppUsage
     boolean getRestrictBackground();
 
     /** Callback used to change internal state on tethering */
@@ -64,6 +70,7 @@
     void setDeviceIdleMode(boolean enabled);
     void setWifiMeteredOverride(String networkId, int meteredOverride);
 
+    @UnsupportedAppUsage
     NetworkQuotaInfo getNetworkQuotaInfo(in NetworkState state);
 
     SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage);
diff --git a/core/java/android/net/INetworkStatsService.aidl b/core/java/android/net/INetworkStatsService.aidl
index 8e6f272..41efc50 100644
--- a/core/java/android/net/INetworkStatsService.aidl
+++ b/core/java/android/net/INetworkStatsService.aidl
@@ -19,16 +19,19 @@
 import android.net.DataUsageRequest;
 import android.net.INetworkStatsSession;
 import android.net.Network;
+import android.net.NetworkState;
 import android.net.NetworkStats;
 import android.net.NetworkStatsHistory;
 import android.net.NetworkTemplate;
 import android.os.IBinder;
 import android.os.Messenger;
+import com.android.internal.net.VpnInfo;
 
 /** {@hide} */
 interface INetworkStatsService {
 
     /** Start a statistics query session. */
+    @UnsupportedAppUsage
     INetworkStatsSession openSession();
 
     /** Start a statistics query session. If calling package is profile or device owner then it is
@@ -37,9 +40,11 @@
      *  PACKAGE_USAGE_STATS permission is always checked. If PACKAGE_USAGE_STATS is not granted
      *  READ_NETWORK_USAGE_STATS is checked for.
      */
+    @UnsupportedAppUsage
     INetworkStatsSession openSessionForUsageStats(int flags, String callingPackage);
 
     /** Return data layer snapshot of UID network usage. */
+    @UnsupportedAppUsage
     NetworkStats getDataLayerSnapshotForUid(int uid);
 
     /** Get a detailed snapshot of stats since boot for all UIDs.
@@ -52,14 +57,20 @@
     NetworkStats getDetailedUidStats(in String[] requiredIfaces);
 
     /** Return set of any ifaces associated with mobile networks since boot. */
+    @UnsupportedAppUsage
     String[] getMobileIfaces();
 
     /** Increment data layer count of operations performed for UID and tag. */
     void incrementOperationCount(int uid, int tag, int operationCount);
 
     /** Force update of ifaces. */
-    void forceUpdateIfaces(in Network[] defaultNetworks);
+    void forceUpdateIfaces(
+         in Network[] defaultNetworks,
+         in VpnInfo[] vpnArray,
+         in NetworkState[] networkStates,
+         in String activeIface);
     /** Force update of statistics. */
+    @UnsupportedAppUsage
     void forceUpdate();
 
     /** Registers a callback on data usage. */
diff --git a/core/java/android/net/INetworkStatsSession.aidl b/core/java/android/net/INetworkStatsSession.aidl
index 5229a3b..f13f2cb 100644
--- a/core/java/android/net/INetworkStatsSession.aidl
+++ b/core/java/android/net/INetworkStatsSession.aidl
@@ -27,13 +27,17 @@
     NetworkStats getDeviceSummaryForNetwork(in NetworkTemplate template, long start, long end);
 
     /** Return network layer usage summary for traffic that matches template. */
+    @UnsupportedAppUsage
     NetworkStats getSummaryForNetwork(in NetworkTemplate template, long start, long end);
     /** Return historical network layer stats for traffic that matches template. */
+    @UnsupportedAppUsage
     NetworkStatsHistory getHistoryForNetwork(in NetworkTemplate template, int fields);
 
     /** Return network layer usage summary per UID for traffic that matches template. */
+    @UnsupportedAppUsage
     NetworkStats getSummaryForAllUid(in NetworkTemplate template, long start, long end, boolean includeTags);
     /** Return historical network layer stats for specific UID traffic that matches template. */
+    @UnsupportedAppUsage
     NetworkStatsHistory getHistoryForUid(in NetworkTemplate template, int uid, int set, int tag, int fields);
     /** Return historical network layer stats for specific UID traffic that matches template. */
     NetworkStatsHistory getHistoryIntervalForUid(in NetworkTemplate template, int uid, int set, int tag, int fields, long start, long end);
@@ -41,6 +45,7 @@
     /** Return array of uids that have stats and are accessible to the calling user */
     int[] getRelevantUids();
 
+    @UnsupportedAppUsage
     void close();
 
 }
diff --git a/core/java/android/net/InterfaceConfiguration.java b/core/java/android/net/InterfaceConfiguration.java
index b9d49c1..c638491 100644
--- a/core/java/android/net/InterfaceConfiguration.java
+++ b/core/java/android/net/InterfaceConfiguration.java
@@ -194,7 +194,7 @@
         }
     }
 
-    public static final Creator<InterfaceConfiguration> CREATOR = new Creator<
+    public static final @android.annotation.NonNull Creator<InterfaceConfiguration> CREATOR = new Creator<
             InterfaceConfiguration>() {
         public InterfaceConfiguration createFromParcel(Parcel in) {
             InterfaceConfiguration info = new InterfaceConfiguration();
diff --git a/core/java/android/net/IpConfiguration.java b/core/java/android/net/IpConfiguration.java
index 3319f33..2af82d7 100644
--- a/core/java/android/net/IpConfiguration.java
+++ b/core/java/android/net/IpConfiguration.java
@@ -189,7 +189,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<IpConfiguration> CREATOR =
+    public static final @android.annotation.NonNull Creator<IpConfiguration> CREATOR =
         new Creator<IpConfiguration>() {
             public IpConfiguration createFromParcel(Parcel in) {
                 IpConfiguration config = new IpConfiguration();
diff --git a/core/java/android/net/IpPrefix.java b/core/java/android/net/IpPrefix.java
index 175263f..21bbd30 100644
--- a/core/java/android/net/IpPrefix.java
+++ b/core/java/android/net/IpPrefix.java
@@ -285,7 +285,7 @@
     /**
      * Implement the Parcelable interface.
      */
-    public static final Creator<IpPrefix> CREATOR =
+    public static final @android.annotation.NonNull Creator<IpPrefix> CREATOR =
             new Creator<IpPrefix>() {
                 public IpPrefix createFromParcel(Parcel in) {
                     byte[] address = in.createByteArray();
diff --git a/core/java/android/net/IpSecAlgorithm.java b/core/java/android/net/IpSecAlgorithm.java
index 8034bb6..38d9883 100644
--- a/core/java/android/net/IpSecAlgorithm.java
+++ b/core/java/android/net/IpSecAlgorithm.java
@@ -191,7 +191,7 @@
     }
 
     /** Parcelable Creator */
-    public static final Parcelable.Creator<IpSecAlgorithm> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<IpSecAlgorithm> CREATOR =
             new Parcelable.Creator<IpSecAlgorithm>() {
                 public IpSecAlgorithm createFromParcel(Parcel in) {
                     final String name = in.readString();
diff --git a/core/java/android/net/IpSecConfig.java b/core/java/android/net/IpSecConfig.java
index 3552655..a64014f 100644
--- a/core/java/android/net/IpSecConfig.java
+++ b/core/java/android/net/IpSecConfig.java
@@ -322,7 +322,7 @@
         return strBuilder.toString();
     }
 
-    public static final Parcelable.Creator<IpSecConfig> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<IpSecConfig> CREATOR =
             new Parcelable.Creator<IpSecConfig>() {
                 public IpSecConfig createFromParcel(Parcel in) {
                     return new IpSecConfig(in);
diff --git a/core/java/android/net/IpSecSpiResponse.java b/core/java/android/net/IpSecSpiResponse.java
index 71dfa03..f99e570 100644
--- a/core/java/android/net/IpSecSpiResponse.java
+++ b/core/java/android/net/IpSecSpiResponse.java
@@ -65,7 +65,7 @@
         spi = in.readInt();
     }
 
-    public static final Parcelable.Creator<IpSecSpiResponse> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<IpSecSpiResponse> CREATOR =
             new Parcelable.Creator<IpSecSpiResponse>() {
                 public IpSecSpiResponse createFromParcel(Parcel in) {
                     return new IpSecSpiResponse(in);
diff --git a/core/java/android/net/IpSecTransformResponse.java b/core/java/android/net/IpSecTransformResponse.java
index cfc1762..a384889 100644
--- a/core/java/android/net/IpSecTransformResponse.java
+++ b/core/java/android/net/IpSecTransformResponse.java
@@ -60,7 +60,7 @@
         resourceId = in.readInt();
     }
 
-    public static final Parcelable.Creator<IpSecTransformResponse> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<IpSecTransformResponse> CREATOR =
             new Parcelable.Creator<IpSecTransformResponse>() {
                 public IpSecTransformResponse createFromParcel(Parcel in) {
                     return new IpSecTransformResponse(in);
diff --git a/core/java/android/net/IpSecTunnelInterfaceResponse.java b/core/java/android/net/IpSecTunnelInterfaceResponse.java
index c23d831..e3411e0 100644
--- a/core/java/android/net/IpSecTunnelInterfaceResponse.java
+++ b/core/java/android/net/IpSecTunnelInterfaceResponse.java
@@ -65,7 +65,7 @@
         interfaceName = in.readString();
     }
 
-    public static final Parcelable.Creator<IpSecTunnelInterfaceResponse> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<IpSecTunnelInterfaceResponse> CREATOR =
             new Parcelable.Creator<IpSecTunnelInterfaceResponse>() {
                 public IpSecTunnelInterfaceResponse createFromParcel(Parcel in) {
                     return new IpSecTunnelInterfaceResponse(in);
diff --git a/core/java/android/net/IpSecUdpEncapResponse.java b/core/java/android/net/IpSecUdpEncapResponse.java
index 4679267..4e7ba9b 100644
--- a/core/java/android/net/IpSecUdpEncapResponse.java
+++ b/core/java/android/net/IpSecUdpEncapResponse.java
@@ -83,7 +83,7 @@
         fileDescriptor = in.readParcelable(ParcelFileDescriptor.class.getClassLoader());
     }
 
-    public static final Parcelable.Creator<IpSecUdpEncapResponse> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<IpSecUdpEncapResponse> CREATOR =
             new Parcelable.Creator<IpSecUdpEncapResponse>() {
                 public IpSecUdpEncapResponse createFromParcel(Parcel in) {
                     return new IpSecUdpEncapResponse(in);
diff --git a/core/java/android/net/KeepalivePacketData.java b/core/java/android/net/KeepalivePacketData.java
index 18726f7..9b8b732 100644
--- a/core/java/android/net/KeepalivePacketData.java
+++ b/core/java/android/net/KeepalivePacketData.java
@@ -105,7 +105,7 @@
     }
 
     /** Parcelable Creator */
-    public static final Parcelable.Creator<KeepalivePacketData> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<KeepalivePacketData> CREATOR =
             new Parcelable.Creator<KeepalivePacketData>() {
                 public KeepalivePacketData createFromParcel(Parcel in) {
                     return new KeepalivePacketData(in);
diff --git a/core/java/android/net/LinkAddress.java b/core/java/android/net/LinkAddress.java
index 8d779aa..dcf64d5 100644
--- a/core/java/android/net/LinkAddress.java
+++ b/core/java/android/net/LinkAddress.java
@@ -356,7 +356,7 @@
     /**
      * Implement the Parcelable interface.
      */
-    public static final Creator<LinkAddress> CREATOR =
+    public static final @android.annotation.NonNull Creator<LinkAddress> CREATOR =
         new Creator<LinkAddress>() {
             public LinkAddress createFromParcel(Parcel in) {
                 InetAddress address = null;
diff --git a/core/java/android/net/LinkProperties.java b/core/java/android/net/LinkProperties.java
index 42db0fd..b52b15e 100644
--- a/core/java/android/net/LinkProperties.java
+++ b/core/java/android/net/LinkProperties.java
@@ -1574,7 +1574,7 @@
     /**
      * Implement the Parcelable interface.
      */
-    public static final Creator<LinkProperties> CREATOR =
+    public static final @android.annotation.NonNull Creator<LinkProperties> CREATOR =
         new Creator<LinkProperties>() {
             public LinkProperties createFromParcel(Parcel in) {
                 LinkProperties netProp = new LinkProperties();
diff --git a/core/java/android/net/LinkQualityInfo.java b/core/java/android/net/LinkQualityInfo.java
index b6f8825..3c5d474 100644
--- a/core/java/android/net/LinkQualityInfo.java
+++ b/core/java/android/net/LinkQualityInfo.java
@@ -111,7 +111,7 @@
     /**
      * @hide
      */
-    public static final Creator<LinkQualityInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<LinkQualityInfo> CREATOR =
             new Creator<LinkQualityInfo>() {
                 public LinkQualityInfo createFromParcel(Parcel in) {
                     int objectType = in.readInt();
diff --git a/core/java/android/net/MacAddress.java b/core/java/android/net/MacAddress.java
index 77d83f5..aa8e010 100644
--- a/core/java/android/net/MacAddress.java
+++ b/core/java/android/net/MacAddress.java
@@ -167,7 +167,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<MacAddress> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<MacAddress> CREATOR =
             new Parcelable.Creator<MacAddress>() {
                 public MacAddress createFromParcel(Parcel in) {
                     return new MacAddress(in.readLong());
diff --git a/core/java/android/net/MatchAllNetworkSpecifier.java b/core/java/android/net/MatchAllNetworkSpecifier.java
index 7aafc93..ab4f627 100644
--- a/core/java/android/net/MatchAllNetworkSpecifier.java
+++ b/core/java/android/net/MatchAllNetworkSpecifier.java
@@ -68,7 +68,7 @@
         // Nothing to write.
     }
 
-    public static final Parcelable.Creator<MatchAllNetworkSpecifier> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<MatchAllNetworkSpecifier> CREATOR =
             new Parcelable.Creator<MatchAllNetworkSpecifier>() {
         public MatchAllNetworkSpecifier createFromParcel(Parcel in) {
             return new MatchAllNetworkSpecifier();
diff --git a/core/java/android/net/Network.java b/core/java/android/net/Network.java
index e04b5fc..0fafdf7 100644
--- a/core/java/android/net/Network.java
+++ b/core/java/android/net/Network.java
@@ -470,7 +470,7 @@
         dest.writeInt(netId);
     }
 
-    public static final Creator<Network> CREATOR =
+    public static final @android.annotation.NonNull Creator<Network> CREATOR =
         new Creator<Network>() {
             public Network createFromParcel(Parcel in) {
                 int netId = in.readInt();
diff --git a/core/java/android/net/NetworkCapabilities.java b/core/java/android/net/NetworkCapabilities.java
index 1d2d81d..a17ebcb 100644
--- a/core/java/android/net/NetworkCapabilities.java
+++ b/core/java/android/net/NetworkCapabilities.java
@@ -1442,7 +1442,7 @@
         dest.writeString(mSSID);
     }
 
-    public static final Creator<NetworkCapabilities> CREATOR =
+    public static final @android.annotation.NonNull Creator<NetworkCapabilities> CREATOR =
         new Creator<NetworkCapabilities>() {
             @Override
             public NetworkCapabilities createFromParcel(Parcel in) {
diff --git a/core/java/android/net/NetworkInfo.java b/core/java/android/net/NetworkInfo.java
index 89d9961..cd83531 100644
--- a/core/java/android/net/NetworkInfo.java
+++ b/core/java/android/net/NetworkInfo.java
@@ -557,7 +557,7 @@
         }
     }
 
-    public static final Creator<NetworkInfo> CREATOR = new Creator<NetworkInfo>() {
+    public static final @android.annotation.NonNull Creator<NetworkInfo> CREATOR = new Creator<NetworkInfo>() {
         @Override
         public NetworkInfo createFromParcel(Parcel in) {
             int netType = in.readInt();
diff --git a/core/java/android/net/NetworkKey.java b/core/java/android/net/NetworkKey.java
index 31a74dc..0a9a3c8 100644
--- a/core/java/android/net/NetworkKey.java
+++ b/core/java/android/net/NetworkKey.java
@@ -178,7 +178,7 @@
         }
     }
 
-    public static final Parcelable.Creator<NetworkKey> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<NetworkKey> CREATOR =
             new Parcelable.Creator<NetworkKey>() {
                 @Override
                 public NetworkKey createFromParcel(Parcel in) {
diff --git a/core/java/android/net/NetworkMisc.java b/core/java/android/net/NetworkMisc.java
index c0487b5..ed0b61e 100644
--- a/core/java/android/net/NetworkMisc.java
+++ b/core/java/android/net/NetworkMisc.java
@@ -100,7 +100,7 @@
         out.writeInt(skip464xlat ? 1 : 0);
     }
 
-    public static final Creator<NetworkMisc> CREATOR = new Creator<NetworkMisc>() {
+    public static final @android.annotation.NonNull Creator<NetworkMisc> CREATOR = new Creator<NetworkMisc>() {
         @Override
         public NetworkMisc createFromParcel(Parcel in) {
             NetworkMisc networkMisc = new NetworkMisc();
diff --git a/core/java/android/net/NetworkPolicy.java b/core/java/android/net/NetworkPolicy.java
index f8973eb..33baebb 100644
--- a/core/java/android/net/NetworkPolicy.java
+++ b/core/java/android/net/NetworkPolicy.java
@@ -237,7 +237,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Creator<NetworkPolicy> CREATOR = new Creator<NetworkPolicy>() {
+    public static final @android.annotation.NonNull Creator<NetworkPolicy> CREATOR = new Creator<NetworkPolicy>() {
         @Override
         public NetworkPolicy createFromParcel(Parcel in) {
             return new NetworkPolicy(in);
diff --git a/core/java/android/net/NetworkQuotaInfo.java b/core/java/android/net/NetworkQuotaInfo.java
index e7182f7..a46cdde 100644
--- a/core/java/android/net/NetworkQuotaInfo.java
+++ b/core/java/android/net/NetworkQuotaInfo.java
@@ -62,7 +62,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Creator<NetworkQuotaInfo> CREATOR = new Creator<NetworkQuotaInfo>() {
+    public static final @android.annotation.NonNull Creator<NetworkQuotaInfo> CREATOR = new Creator<NetworkQuotaInfo>() {
         @Override
         public NetworkQuotaInfo createFromParcel(Parcel in) {
             return new NetworkQuotaInfo(in);
diff --git a/core/java/android/net/NetworkRequest.java b/core/java/android/net/NetworkRequest.java
index 9508217..dcb027d 100644
--- a/core/java/android/net/NetworkRequest.java
+++ b/core/java/android/net/NetworkRequest.java
@@ -363,7 +363,7 @@
         dest.writeInt(requestId);
         dest.writeString(type.name());
     }
-    public static final Creator<NetworkRequest> CREATOR =
+    public static final @android.annotation.NonNull Creator<NetworkRequest> CREATOR =
         new Creator<NetworkRequest>() {
             public NetworkRequest createFromParcel(Parcel in) {
                 NetworkCapabilities nc = NetworkCapabilities.CREATOR.createFromParcel(in);
diff --git a/core/java/android/net/NetworkScorerAppData.java b/core/java/android/net/NetworkScorerAppData.java
index 1734b34..116e39e 100644
--- a/core/java/android/net/NetworkScorerAppData.java
+++ b/core/java/android/net/NetworkScorerAppData.java
@@ -61,7 +61,7 @@
         return 0;
     }
 
-    public static final Creator<NetworkScorerAppData> CREATOR =
+    public static final @android.annotation.NonNull Creator<NetworkScorerAppData> CREATOR =
             new Creator<NetworkScorerAppData>() {
                 @Override
                 public NetworkScorerAppData createFromParcel(Parcel in) {
diff --git a/core/java/android/net/NetworkState.java b/core/java/android/net/NetworkState.java
index 97fb3fb..292cf50 100644
--- a/core/java/android/net/NetworkState.java
+++ b/core/java/android/net/NetworkState.java
@@ -87,7 +87,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Creator<NetworkState> CREATOR = new Creator<NetworkState>() {
+    public static final @android.annotation.NonNull Creator<NetworkState> CREATOR = new Creator<NetworkState>() {
         @Override
         public NetworkState createFromParcel(Parcel in) {
             return new NetworkState(in);
diff --git a/core/java/android/net/NetworkStats.java b/core/java/android/net/NetworkStats.java
index 9cf582b..e892b65 100644
--- a/core/java/android/net/NetworkStats.java
+++ b/core/java/android/net/NetworkStats.java
@@ -1153,7 +1153,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Creator<NetworkStats> CREATOR = new Creator<NetworkStats>() {
+    public static final @android.annotation.NonNull Creator<NetworkStats> CREATOR = new Creator<NetworkStats>() {
         @Override
         public NetworkStats createFromParcel(Parcel in) {
             return new NetworkStats(in);
diff --git a/core/java/android/net/NetworkStatsHistory.java b/core/java/android/net/NetworkStatsHistory.java
index d53e032..f61260e 100644
--- a/core/java/android/net/NetworkStatsHistory.java
+++ b/core/java/android/net/NetworkStatsHistory.java
@@ -719,7 +719,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Creator<NetworkStatsHistory> CREATOR = new Creator<NetworkStatsHistory>() {
+    public static final @android.annotation.NonNull Creator<NetworkStatsHistory> CREATOR = new Creator<NetworkStatsHistory>() {
         @Override
         public NetworkStatsHistory createFromParcel(Parcel in) {
             return new NetworkStatsHistory(in);
diff --git a/core/java/android/net/NetworkTemplate.java b/core/java/android/net/NetworkTemplate.java
index bb75c63..d42fce3 100644
--- a/core/java/android/net/NetworkTemplate.java
+++ b/core/java/android/net/NetworkTemplate.java
@@ -482,7 +482,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Creator<NetworkTemplate> CREATOR = new Creator<NetworkTemplate>() {
+    public static final @android.annotation.NonNull Creator<NetworkTemplate> CREATOR = new Creator<NetworkTemplate>() {
         @Override
         public NetworkTemplate createFromParcel(Parcel in) {
             return new NetworkTemplate(in);
diff --git a/core/java/android/net/ProxyInfo.java b/core/java/android/net/ProxyInfo.java
index ef2269a..807c467 100644
--- a/core/java/android/net/ProxyInfo.java
+++ b/core/java/android/net/ProxyInfo.java
@@ -342,7 +342,7 @@
         dest.writeStringArray(mParsedExclusionList);
     }
 
-    public static final Creator<ProxyInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<ProxyInfo> CREATOR =
         new Creator<ProxyInfo>() {
             public ProxyInfo createFromParcel(Parcel in) {
                 String host = null;
diff --git a/core/java/android/net/RouteInfo.java b/core/java/android/net/RouteInfo.java
index 5c0f758..c1c8f6e 100644
--- a/core/java/android/net/RouteInfo.java
+++ b/core/java/android/net/RouteInfo.java
@@ -486,7 +486,7 @@
     /**
      * Implement the Parcelable interface.
      */
-    public static final Creator<RouteInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<RouteInfo> CREATOR =
         new Creator<RouteInfo>() {
         public RouteInfo createFromParcel(Parcel in) {
             IpPrefix dest = in.readParcelable(null);
diff --git a/core/java/android/net/RssiCurve.java b/core/java/android/net/RssiCurve.java
index 5b81f52..a173b0c 100644
--- a/core/java/android/net/RssiCurve.java
+++ b/core/java/android/net/RssiCurve.java
@@ -209,7 +209,7 @@
         return sb.toString();
     }
 
-    public static final Creator<RssiCurve> CREATOR =
+    public static final @android.annotation.NonNull Creator<RssiCurve> CREATOR =
             new Creator<RssiCurve>() {
                 @Override
                 public RssiCurve createFromParcel(Parcel in) {
diff --git a/core/java/android/net/SSLCertificateSocketFactory.java b/core/java/android/net/SSLCertificateSocketFactory.java
index 90dccb5..45860b3 100644
--- a/core/java/android/net/SSLCertificateSocketFactory.java
+++ b/core/java/android/net/SSLCertificateSocketFactory.java
@@ -23,8 +23,7 @@
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.os.RoSystemProperties;
-import com.android.org.conscrypt.Conscrypt;
-import com.android.org.conscrypt.OpenSSLContextImpl;
+import com.android.org.conscrypt.ClientSessionContext;
 import com.android.org.conscrypt.OpenSSLSocketImpl;
 import com.android.org.conscrypt.SSLClientSessionCache;
 
@@ -33,6 +32,8 @@
 import java.net.Socket;
 import java.net.SocketException;
 import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
 import java.security.PrivateKey;
 import java.security.cert.X509Certificate;
 
@@ -40,6 +41,7 @@
 import javax.net.ssl.HostnameVerifier;
 import javax.net.ssl.HttpsURLConnection;
 import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLException;
 import javax.net.ssl.SSLPeerUnverifiedException;
 import javax.net.ssl.SSLSession;
@@ -251,11 +253,12 @@
     private SSLSocketFactory makeSocketFactory(
             KeyManager[] keyManagers, TrustManager[] trustManagers) {
         try {
-            OpenSSLContextImpl sslContext =  (OpenSSLContextImpl) Conscrypt.newPreferredSSLContextSpi();
-            sslContext.engineInit(keyManagers, trustManagers, null);
-            sslContext.engineGetClientSessionContext().setPersistentCache(mSessionCache);
-            return sslContext.engineGetSocketFactory();
-        } catch (KeyManagementException e) {
+            SSLContext sslContext = SSLContext.getInstance("TLS", "AndroidOpenSSL");
+            sslContext.init(keyManagers, trustManagers, null);
+            ((ClientSessionContext) sslContext.getClientSessionContext())
+                .setPersistentCache(mSessionCache);
+            return sslContext.getSocketFactory();
+        } catch (KeyManagementException | NoSuchAlgorithmException | NoSuchProviderException e) {
             Log.wtf(TAG, e);
             return (SSLSocketFactory) SSLSocketFactory.getDefault();  // Fallback
         }
diff --git a/core/java/android/net/ScoredNetwork.java b/core/java/android/net/ScoredNetwork.java
index e38d227..effc1aa 100644
--- a/core/java/android/net/ScoredNetwork.java
+++ b/core/java/android/net/ScoredNetwork.java
@@ -302,7 +302,7 @@
         return NetworkBadging.BADGING_NONE;
     }
 
-    public static final Parcelable.Creator<ScoredNetwork> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ScoredNetwork> CREATOR =
             new Parcelable.Creator<ScoredNetwork>() {
                 @Override
                 public ScoredNetwork createFromParcel(Parcel in) {
diff --git a/core/java/android/net/StaticIpConfiguration.java b/core/java/android/net/StaticIpConfiguration.java
index 99cf3a9..8b264ee 100644
--- a/core/java/android/net/StaticIpConfiguration.java
+++ b/core/java/android/net/StaticIpConfiguration.java
@@ -212,7 +212,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<StaticIpConfiguration> CREATOR =
+    public static final @android.annotation.NonNull Creator<StaticIpConfiguration> CREATOR =
         new Creator<StaticIpConfiguration>() {
             public StaticIpConfiguration createFromParcel(Parcel in) {
                 return readFromParcel(in);
diff --git a/core/java/android/net/StringNetworkSpecifier.java b/core/java/android/net/StringNetworkSpecifier.java
index b5d12f9..21dee55 100644
--- a/core/java/android/net/StringNetworkSpecifier.java
+++ b/core/java/android/net/StringNetworkSpecifier.java
@@ -69,7 +69,7 @@
         dest.writeString(specifier);
     }
 
-    public static final Parcelable.Creator<StringNetworkSpecifier> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<StringNetworkSpecifier> CREATOR =
             new Parcelable.Creator<StringNetworkSpecifier>() {
         public StringNetworkSpecifier createFromParcel(Parcel in) {
             return new StringNetworkSpecifier(in.readString());
diff --git a/core/java/android/net/TcpKeepalivePacketData.java b/core/java/android/net/TcpKeepalivePacketData.java
index f07dfb6..99d36c5 100644
--- a/core/java/android/net/TcpKeepalivePacketData.java
+++ b/core/java/android/net/TcpKeepalivePacketData.java
@@ -194,7 +194,7 @@
     }
 
     /** Parcelable Creator. */
-    public static final Parcelable.Creator<TcpKeepalivePacketData> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TcpKeepalivePacketData> CREATOR =
             new Parcelable.Creator<TcpKeepalivePacketData>() {
                 public TcpKeepalivePacketData createFromParcel(Parcel in) {
                     return new TcpKeepalivePacketData(in);
diff --git a/core/java/android/net/UidRange.java b/core/java/android/net/UidRange.java
index 793c82d..d4a4cf4 100644
--- a/core/java/android/net/UidRange.java
+++ b/core/java/android/net/UidRange.java
@@ -91,7 +91,7 @@
      * The parceling code is autogenerated by the superclass.
      */
 
-    public static final Creator<UidRange> CREATOR =
+    public static final @android.annotation.NonNull Creator<UidRange> CREATOR =
         new Creator<UidRange>() {
             @Override
             public UidRange createFromParcel(Parcel in) {
diff --git a/core/java/android/net/Uri.java b/core/java/android/net/Uri.java
index af3ee09..fdf5321 100644
--- a/core/java/android/net/Uri.java
+++ b/core/java/android/net/Uri.java
@@ -402,7 +402,7 @@
                 }
                 return builder.toString();
             } else if (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")
-                    || scheme.equalsIgnoreCase("ftp")) {
+                    || scheme.equalsIgnoreCase("ftp") || scheme.equalsIgnoreCase("rtsp")) {
                 ssp = "//" + ((getHost() != null) ? getHost() : "")
                         + ((getPort() != -1) ? (":" + getPort()) : "")
                         + "/...";
@@ -1799,7 +1799,7 @@
     /**
      * Reads Uris from Parcels.
      */
-    public static final Parcelable.Creator<Uri> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Uri> CREATOR
             = new Parcelable.Creator<Uri>() {
         public Uri createFromParcel(Parcel in) {
             int type = in.readInt();
diff --git a/core/java/android/net/VpnService.java b/core/java/android/net/VpnService.java
index 784f233..ebb1ae4 100644
--- a/core/java/android/net/VpnService.java
+++ b/core/java/android/net/VpnService.java
@@ -19,6 +19,7 @@
 import static android.system.OsConstants.AF_INET;
 import static android.system.OsConstants.AF_INET6;
 
+import android.annotation.NonNull;
 import android.annotation.RequiresPermission;
 import android.annotation.SystemApi;
 import android.annotation.UnsupportedAppUsage;
@@ -512,7 +513,7 @@
          * Sets an HTTP proxy for the VPN network. This proxy is only a recommendation
          * and it is possible that some apps will ignore it.
          */
-        public Builder setHttpProxy(ProxyInfo proxyInfo) {
+        public Builder setHttpProxy(@NonNull ProxyInfo proxyInfo) {
             mConfig.proxyInfo = proxyInfo;
             return this;
         }
diff --git a/core/java/android/net/WifiKey.java b/core/java/android/net/WifiKey.java
index 68b505d..e3a93a8 100644
--- a/core/java/android/net/WifiKey.java
+++ b/core/java/android/net/WifiKey.java
@@ -110,7 +110,7 @@
         return "WifiKey[SSID=" + ssid + ",BSSID=" + bssid + "]";
     }
 
-    public static final Creator<WifiKey> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiKey> CREATOR =
             new Creator<WifiKey>() {
                 @Override
                 public WifiKey createFromParcel(Parcel in) {
diff --git a/core/java/android/net/metrics/ApfProgramEvent.java b/core/java/android/net/metrics/ApfProgramEvent.java
index 8601005..b30d8cb 100644
--- a/core/java/android/net/metrics/ApfProgramEvent.java
+++ b/core/java/android/net/metrics/ApfProgramEvent.java
@@ -185,7 +185,7 @@
     }
 
     /** @hide */
-    public static final Parcelable.Creator<ApfProgramEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ApfProgramEvent> CREATOR
             = new Parcelable.Creator<ApfProgramEvent>() {
         public ApfProgramEvent createFromParcel(Parcel in) {
             return new ApfProgramEvent(in);
diff --git a/core/java/android/net/metrics/ApfStats.java b/core/java/android/net/metrics/ApfStats.java
index 844a134..e1c8888 100644
--- a/core/java/android/net/metrics/ApfStats.java
+++ b/core/java/android/net/metrics/ApfStats.java
@@ -264,7 +264,7 @@
     }
 
     /** @hide */
-    public static final Parcelable.Creator<ApfStats> CREATOR = new Parcelable.Creator<ApfStats>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<ApfStats> CREATOR = new Parcelable.Creator<ApfStats>() {
         public ApfStats createFromParcel(Parcel in) {
             return new ApfStats(in);
         }
diff --git a/core/java/android/net/metrics/DhcpClientEvent.java b/core/java/android/net/metrics/DhcpClientEvent.java
index 3008115..e4faea9 100644
--- a/core/java/android/net/metrics/DhcpClientEvent.java
+++ b/core/java/android/net/metrics/DhcpClientEvent.java
@@ -98,7 +98,7 @@
     }
 
     /** @hide */
-    public static final Parcelable.Creator<DhcpClientEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<DhcpClientEvent> CREATOR
         = new Parcelable.Creator<DhcpClientEvent>() {
         public DhcpClientEvent createFromParcel(Parcel in) {
             return new DhcpClientEvent(in);
diff --git a/core/java/android/net/metrics/DhcpErrorEvent.java b/core/java/android/net/metrics/DhcpErrorEvent.java
index 18fde80..91318a2 100644
--- a/core/java/android/net/metrics/DhcpErrorEvent.java
+++ b/core/java/android/net/metrics/DhcpErrorEvent.java
@@ -87,7 +87,7 @@
     }
 
     /** @hide */
-    public static final Parcelable.Creator<DhcpErrorEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<DhcpErrorEvent> CREATOR
         = new Parcelable.Creator<DhcpErrorEvent>() {
         public DhcpErrorEvent createFromParcel(Parcel in) {
             return new DhcpErrorEvent(in);
diff --git a/core/java/android/net/metrics/IpManagerEvent.java b/core/java/android/net/metrics/IpManagerEvent.java
index 013e353..9d358d1 100644
--- a/core/java/android/net/metrics/IpManagerEvent.java
+++ b/core/java/android/net/metrics/IpManagerEvent.java
@@ -84,7 +84,7 @@
     }
 
     /** @hide */
-    public static final Parcelable.Creator<IpManagerEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<IpManagerEvent> CREATOR
         = new Parcelable.Creator<IpManagerEvent>() {
         public IpManagerEvent createFromParcel(Parcel in) {
             return new IpManagerEvent(in);
diff --git a/core/java/android/net/metrics/IpReachabilityEvent.java b/core/java/android/net/metrics/IpReachabilityEvent.java
index c736297..80c8211 100644
--- a/core/java/android/net/metrics/IpReachabilityEvent.java
+++ b/core/java/android/net/metrics/IpReachabilityEvent.java
@@ -74,7 +74,7 @@
     }
 
     /** @hide */
-    public static final Parcelable.Creator<IpReachabilityEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<IpReachabilityEvent> CREATOR
         = new Parcelable.Creator<IpReachabilityEvent>() {
         public IpReachabilityEvent createFromParcel(Parcel in) {
             return new IpReachabilityEvent(in);
diff --git a/core/java/android/net/metrics/NetworkEvent.java b/core/java/android/net/metrics/NetworkEvent.java
index f5b2ff1..ed58843 100644
--- a/core/java/android/net/metrics/NetworkEvent.java
+++ b/core/java/android/net/metrics/NetworkEvent.java
@@ -101,7 +101,7 @@
     }
 
     /** @hide */
-    public static final Parcelable.Creator<NetworkEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<NetworkEvent> CREATOR
         = new Parcelable.Creator<NetworkEvent>() {
         public NetworkEvent createFromParcel(Parcel in) {
             return new NetworkEvent(in);
diff --git a/core/java/android/net/metrics/RaEvent.java b/core/java/android/net/metrics/RaEvent.java
index 04a2e6e..0d43f12 100644
--- a/core/java/android/net/metrics/RaEvent.java
+++ b/core/java/android/net/metrics/RaEvent.java
@@ -97,7 +97,7 @@
     }
 
     /** @hide */
-    public static final Parcelable.Creator<RaEvent> CREATOR = new Parcelable.Creator<RaEvent>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<RaEvent> CREATOR = new Parcelable.Creator<RaEvent>() {
         public RaEvent createFromParcel(Parcel in) {
             return new RaEvent(in);
         }
diff --git a/core/java/android/net/metrics/ValidationProbeEvent.java b/core/java/android/net/metrics/ValidationProbeEvent.java
index 42e8aa6..052758d 100644
--- a/core/java/android/net/metrics/ValidationProbeEvent.java
+++ b/core/java/android/net/metrics/ValidationProbeEvent.java
@@ -79,7 +79,7 @@
     }
 
     /**
-     * Utility to create an instance of {@link ApfProgramEvent}.
+     * Utility to create an instance of {@link ValidationProbeEvent}.
      */
     public static class Builder {
         private long mDurationMs;
@@ -133,7 +133,7 @@
     }
 
     /** @hide */
-    public static final Parcelable.Creator<ValidationProbeEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ValidationProbeEvent> CREATOR
         = new Parcelable.Creator<ValidationProbeEvent>() {
         public ValidationProbeEvent createFromParcel(Parcel in) {
             return new ValidationProbeEvent(in);
diff --git a/core/java/android/net/nsd/DnsSdTxtRecord.java b/core/java/android/net/nsd/DnsSdTxtRecord.java
index 2f20d44..e4a91c5 100644
--- a/core/java/android/net/nsd/DnsSdTxtRecord.java
+++ b/core/java/android/net/nsd/DnsSdTxtRecord.java
@@ -310,7 +310,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<DnsSdTxtRecord> CREATOR =
+    public static final @android.annotation.NonNull Creator<DnsSdTxtRecord> CREATOR =
         new Creator<DnsSdTxtRecord>() {
             public DnsSdTxtRecord createFromParcel(Parcel in) {
                 DnsSdTxtRecord info = new DnsSdTxtRecord();
diff --git a/core/java/android/net/nsd/NsdServiceInfo.java b/core/java/android/net/nsd/NsdServiceInfo.java
index 9ba17ed..459b140 100644
--- a/core/java/android/net/nsd/NsdServiceInfo.java
+++ b/core/java/android/net/nsd/NsdServiceInfo.java
@@ -355,7 +355,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<NsdServiceInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<NsdServiceInfo> CREATOR =
         new Creator<NsdServiceInfo>() {
             public NsdServiceInfo createFromParcel(Parcel in) {
                 NsdServiceInfo info = new NsdServiceInfo();
diff --git a/core/java/android/nfc/ApduList.java b/core/java/android/nfc/ApduList.java
index 85b0547..027141d 100644
--- a/core/java/android/nfc/ApduList.java
+++ b/core/java/android/nfc/ApduList.java
@@ -24,7 +24,7 @@
         return commands;
     }
 
-    public static final Parcelable.Creator<ApduList> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ApduList> CREATOR =
         new Parcelable.Creator<ApduList>() {
         @Override
         public ApduList createFromParcel(Parcel in) {
diff --git a/core/java/android/nfc/BeamShareData.java b/core/java/android/nfc/BeamShareData.java
index 918ec3d..ed3b74a 100644
--- a/core/java/android/nfc/BeamShareData.java
+++ b/core/java/android/nfc/BeamShareData.java
@@ -42,7 +42,7 @@
         dest.writeInt(this.flags);
     }
 
-    public static final Parcelable.Creator<BeamShareData> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BeamShareData> CREATOR =
             new Parcelable.Creator<BeamShareData>() {
         @Override
         public BeamShareData createFromParcel(Parcel source) {
diff --git a/core/java/android/nfc/INfcAdapterExtras.aidl b/core/java/android/nfc/INfcAdapterExtras.aidl
index 41ebf63..dd260bc 100644
--- a/core/java/android/nfc/INfcAdapterExtras.aidl
+++ b/core/java/android/nfc/INfcAdapterExtras.aidl
@@ -23,11 +23,18 @@
  * {@hide}
  */
 interface INfcAdapterExtras {
+    @UnsupportedAppUsage
     Bundle open(in String pkg, IBinder b);
+    @UnsupportedAppUsage
     Bundle close(in String pkg, IBinder b);
+    @UnsupportedAppUsage
     Bundle transceive(in String pkg, in byte[] data_in);
+    @UnsupportedAppUsage
     int getCardEmulationRoute(in String pkg);
+    @UnsupportedAppUsage
     void setCardEmulationRoute(in String pkg, int route);
+    @UnsupportedAppUsage
     void authenticate(in String pkg, in byte[] token);
+    @UnsupportedAppUsage
     String getDriverName(in String pkg);
 }
diff --git a/core/java/android/nfc/NdefMessage.java b/core/java/android/nfc/NdefMessage.java
index 0bb1108..57d79c8 100644
--- a/core/java/android/nfc/NdefMessage.java
+++ b/core/java/android/nfc/NdefMessage.java
@@ -213,7 +213,7 @@
         dest.writeTypedArray(mRecords, flags);
     }
 
-    public static final Parcelable.Creator<NdefMessage> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<NdefMessage> CREATOR =
             new Parcelable.Creator<NdefMessage>() {
         @Override
         public NdefMessage createFromParcel(Parcel in) {
diff --git a/core/java/android/nfc/NdefRecord.java b/core/java/android/nfc/NdefRecord.java
index b0090ca..5044a86 100644
--- a/core/java/android/nfc/NdefRecord.java
+++ b/core/java/android/nfc/NdefRecord.java
@@ -992,7 +992,7 @@
         dest.writeByteArray(mPayload);
     }
 
-    public static final Parcelable.Creator<NdefRecord> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<NdefRecord> CREATOR =
             new Parcelable.Creator<NdefRecord>() {
         @Override
         public NdefRecord createFromParcel(Parcel in) {
diff --git a/core/java/android/nfc/Tag.java b/core/java/android/nfc/Tag.java
index ce684cf..5a4c465 100644
--- a/core/java/android/nfc/Tag.java
+++ b/core/java/android/nfc/Tag.java
@@ -421,7 +421,7 @@
         }
     }
 
-    public static final Parcelable.Creator<Tag> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<Tag> CREATOR =
             new Parcelable.Creator<Tag>() {
         @Override
         public Tag createFromParcel(Parcel in) {
diff --git a/core/java/android/nfc/TechListParcel.java b/core/java/android/nfc/TechListParcel.java
index 396f0f1..90645dd 100644
--- a/core/java/android/nfc/TechListParcel.java
+++ b/core/java/android/nfc/TechListParcel.java
@@ -47,7 +47,7 @@
         }
     }
 
-    public static final Creator<TechListParcel> CREATOR = new Creator<TechListParcel>() {
+    public static final @android.annotation.NonNull Creator<TechListParcel> CREATOR = new Creator<TechListParcel>() {
         @Override
         public TechListParcel createFromParcel(Parcel source) {
             int count = source.readInt();
diff --git a/core/java/android/nfc/TransceiveResult.java b/core/java/android/nfc/TransceiveResult.java
index 3538825..7992094 100644
--- a/core/java/android/nfc/TransceiveResult.java
+++ b/core/java/android/nfc/TransceiveResult.java
@@ -67,7 +67,7 @@
         }
     }
 
-    public static final Parcelable.Creator<TransceiveResult> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TransceiveResult> CREATOR =
             new Parcelable.Creator<TransceiveResult>() {
         @Override
         public TransceiveResult createFromParcel(Parcel in) {
diff --git a/core/java/android/nfc/cardemulation/AidGroup.java b/core/java/android/nfc/cardemulation/AidGroup.java
index 63776c4..77b5552 100644
--- a/core/java/android/nfc/cardemulation/AidGroup.java
+++ b/core/java/android/nfc/cardemulation/AidGroup.java
@@ -132,7 +132,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Parcelable.Creator<AidGroup> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AidGroup> CREATOR =
             new Parcelable.Creator<AidGroup>() {
 
         @Override
diff --git a/core/java/android/nfc/cardemulation/ApduServiceInfo.java b/core/java/android/nfc/cardemulation/ApduServiceInfo.java
index 911ec84..6f9858c 100644
--- a/core/java/android/nfc/cardemulation/ApduServiceInfo.java
+++ b/core/java/android/nfc/cardemulation/ApduServiceInfo.java
@@ -540,7 +540,7 @@
     };
 
     @UnsupportedAppUsage
-    public static final Parcelable.Creator<ApduServiceInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ApduServiceInfo> CREATOR =
             new Parcelable.Creator<ApduServiceInfo>() {
         @Override
         public ApduServiceInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/nfc/cardemulation/NfcFServiceInfo.java b/core/java/android/nfc/cardemulation/NfcFServiceInfo.java
index 1d3f9c2..bda14299 100644
--- a/core/java/android/nfc/cardemulation/NfcFServiceInfo.java
+++ b/core/java/android/nfc/cardemulation/NfcFServiceInfo.java
@@ -289,7 +289,7 @@
         dest.writeString(mT3tPmm);
     };
 
-    public static final Parcelable.Creator<NfcFServiceInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<NfcFServiceInfo> CREATOR =
             new Parcelable.Creator<NfcFServiceInfo>() {
         @Override
         public NfcFServiceInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/os/BatteryProperty.java b/core/java/android/os/BatteryProperty.java
index b7e7b17..b40988a 100644
--- a/core/java/android/os/BatteryProperty.java
+++ b/core/java/android/os/BatteryProperty.java
@@ -67,7 +67,7 @@
         p.writeLong(mValueLong);
     }
 
-    public static final Parcelable.Creator<BatteryProperty> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<BatteryProperty> CREATOR
         = new Parcelable.Creator<BatteryProperty>() {
         public BatteryProperty createFromParcel(Parcel p) {
             return new BatteryProperty(p);
diff --git a/core/java/android/os/BatterySaverPolicyConfig.java b/core/java/android/os/BatterySaverPolicyConfig.java
index a107a7a..af7d11d 100644
--- a/core/java/android/os/BatterySaverPolicyConfig.java
+++ b/core/java/android/os/BatterySaverPolicyConfig.java
@@ -111,7 +111,7 @@
                 Math.min(in.readInt(), PowerManager.MAX_LOCATION_MODE));
     }
 
-    public static final Creator<BatterySaverPolicyConfig> CREATOR =
+    public static final @android.annotation.NonNull Creator<BatterySaverPolicyConfig> CREATOR =
             new Creator<BatterySaverPolicyConfig>() {
                 @Override
                 public BatterySaverPolicyConfig createFromParcel(Parcel in) {
diff --git a/core/java/android/os/BugreportManager.java b/core/java/android/os/BugreportManager.java
index 27f7e22..684369a 100644
--- a/core/java/android/os/BugreportManager.java
+++ b/core/java/android/os/BugreportManager.java
@@ -59,7 +59,8 @@
                 BUGREPORT_ERROR_INVALID_INPUT,
                 BUGREPORT_ERROR_RUNTIME,
                 BUGREPORT_ERROR_USER_DENIED_CONSENT,
-                BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT
+                BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT,
+                BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS
         })
 
         /** Possible error codes taking a bugreport can encounter */
@@ -81,6 +82,10 @@
         public static final int BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT =
                 IDumpstateListener.BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT;
 
+        /** There is currently a bugreport running. The caller should try again later. */
+        public static final int BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS =
+                IDumpstateListener.BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS;
+
         /**
          * Called when there is a progress update.
          * @param progress the progress in [0.0, 100.0]
@@ -96,6 +101,9 @@
          * <p>If {@code BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT} is passed, then the consent timed
          * out, but the bugreport could be available in the internal directory of dumpstate for
          * manual retrieval.
+         *
+         * <p> If {@code BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS} is passed, then the
+         * caller should try later, as only one bugreport can be in progress at a time.
          */
         public void onError(@BugreportErrorCode int errorCode) {}
 
diff --git a/core/java/android/os/Bundle.java b/core/java/android/os/Bundle.java
index 7ae5a67..8e6a554 100644
--- a/core/java/android/os/Bundle.java
+++ b/core/java/android/os/Bundle.java
@@ -1196,7 +1196,7 @@
         }
     }
 
-    public static final Parcelable.Creator<Bundle> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<Bundle> CREATOR =
         new Parcelable.Creator<Bundle>() {
         @Override
         public Bundle createFromParcel(Parcel in) {
diff --git a/core/java/android/os/CpuUsageInfo.java b/core/java/android/os/CpuUsageInfo.java
index 54caa15..444579f 100644
--- a/core/java/android/os/CpuUsageInfo.java
+++ b/core/java/android/os/CpuUsageInfo.java
@@ -23,7 +23,7 @@
     private long mActive;
     private long mTotal;
 
-    public static final Parcelable.Creator<CpuUsageInfo> CREATOR = new
+    public static final @android.annotation.NonNull Parcelable.Creator<CpuUsageInfo> CREATOR = new
             Parcelable.Creator<CpuUsageInfo>() {
                     public CpuUsageInfo createFromParcel(Parcel in) {
                         return new CpuUsageInfo(in);
diff --git a/core/java/android/os/Debug.java b/core/java/android/os/Debug.java
index 149ef54..a395ed4 100644
--- a/core/java/android/os/Debug.java
+++ b/core/java/android/os/Debug.java
@@ -859,7 +859,7 @@
             otherStats = source.createIntArray();
         }
 
-        public static final Creator<MemoryInfo> CREATOR = new Creator<MemoryInfo>() {
+        public static final @android.annotation.NonNull Creator<MemoryInfo> CREATOR = new Creator<MemoryInfo>() {
             public MemoryInfo createFromParcel(Parcel source) {
                 return new MemoryInfo(source);
             }
diff --git a/core/java/android/os/DropBoxManager.java b/core/java/android/os/DropBoxManager.java
index eeae25e..1be7b6b 100644
--- a/core/java/android/os/DropBoxManager.java
+++ b/core/java/android/os/DropBoxManager.java
@@ -227,7 +227,7 @@
             return (mFlags & IS_GZIPPED) != 0 ? new GZIPInputStream(is) : is;
         }
 
-        public static final Parcelable.Creator<Entry> CREATOR = new Parcelable.Creator() {
+        public static final @android.annotation.NonNull Parcelable.Creator<Entry> CREATOR = new Parcelable.Creator() {
             public Entry[] newArray(int size) { return new Entry[size]; }
             public Entry createFromParcel(Parcel in) {
                 String tag = in.readString();
diff --git a/core/java/android/os/Environment.java b/core/java/android/os/Environment.java
index 0aed981..b3e35b6 100644
--- a/core/java/android/os/Environment.java
+++ b/core/java/android/os/Environment.java
@@ -16,6 +16,7 @@
 
 package android.os;
 
+import android.annotation.NonNull;
 import android.annotation.SystemApi;
 import android.annotation.TestApi;
 import android.app.admin.DevicePolicyManager;
@@ -155,13 +156,13 @@
      * Return root of the "system" partition holding the core Android OS.
      * Always present and mounted read-only.
      */
-    public static File getRootDirectory() {
+    public static @NonNull File getRootDirectory() {
         return DIR_ANDROID_ROOT;
     }
 
     /** {@hide} */
     @TestApi
-    public static File getStorageDirectory() {
+    public static @NonNull File getStorageDirectory() {
         return DIR_ANDROID_STORAGE;
     }
 
@@ -172,7 +173,7 @@
      * @hide
      */
     @SystemApi
-    public static File getOemDirectory() {
+    public static @NonNull File getOemDirectory() {
         return DIR_OEM_ROOT;
     }
 
@@ -183,7 +184,7 @@
      * @hide
      */
     @SystemApi
-    public static File getOdmDirectory() {
+    public static @NonNull File getOdmDirectory() {
         return DIR_ODM_ROOT;
     }
 
@@ -193,7 +194,7 @@
      * @hide
      */
     @SystemApi
-    public static File getVendorDirectory() {
+    public static @NonNull File getVendorDirectory() {
         return DIR_VENDOR_ROOT;
     }
 
@@ -205,7 +206,7 @@
      */
     @SystemApi
     @TestApi
-    public static File getProductDirectory() {
+    public static @NonNull File getProductDirectory() {
         return DIR_PRODUCT_ROOT;
     }
 
@@ -216,7 +217,7 @@
      * @hide
      */
     @SystemApi
-    public static File getProductServicesDirectory() {
+    public static @NonNull File getProductServicesDirectory() {
         return DIR_PRODUCT_SERVICES_ROOT;
     }
 
diff --git a/core/java/android/os/ExternalVibration.java b/core/java/android/os/ExternalVibration.java
index 69ab1d9..b93bef8 100644
--- a/core/java/android/os/ExternalVibration.java
+++ b/core/java/android/os/ExternalVibration.java
@@ -156,7 +156,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<ExternalVibration> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ExternalVibration> CREATOR =
             new Parcelable.Creator<ExternalVibration>() {
                 @Override
                 public ExternalVibration createFromParcel(Parcel in) {
diff --git a/core/java/android/os/FileObserver.java b/core/java/android/os/FileObserver.java
index da03895..330bde5 100644
--- a/core/java/android/os/FileObserver.java
+++ b/core/java/android/os/FileObserver.java
@@ -16,11 +16,14 @@
 
 package android.os;
 
+import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.util.Log;
 
 import java.io.File;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
 import java.lang.ref.WeakReference;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -45,6 +48,24 @@
  * keep a reference to the FileObserver instance from some other live object.</p>
  */
 public abstract class FileObserver {
+    /** @hide */
+    @IntDef(flag = true, value = {
+            ACCESS,
+            MODIFY,
+            ATTRIB,
+            CLOSE_WRITE,
+            CLOSE_NOWRITE,
+            OPEN,
+            MOVED_FROM,
+            MOVED_TO,
+            CREATE,
+            DELETE,
+            DELETE_SELF,
+            MOVE_SELF
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface NotifyEventType {}
+
     /** Event type: Data was read from a file */
     public static final int ACCESS = 0x00000001;
     /** Event type: Data was written to a file */
@@ -71,6 +92,7 @@
     public static final int MOVE_SELF = 0x00000800;
 
     /** Event mask: All valid event types, combined */
+    @NotifyEventType
     public static final int ALL_EVENTS = ACCESS | MODIFY | ATTRIB | CLOSE_WRITE
             | CLOSE_NOWRITE | OPEN | MOVED_FROM | MOVED_TO | DELETE | CREATE
             | DELETE_SELF | MOVE_SELF;
@@ -90,7 +112,8 @@
             observe(m_fd);
         }
 
-        public int[] startWatching(List<File> files, int mask, FileObserver observer) {
+        public int[] startWatching(List<File> files,
+                @NotifyEventType int mask, FileObserver observer) {
             final int count = files.size();
             final String[] paths = new String[count];
             for (int i = 0; i < count; ++i) {
@@ -118,7 +141,7 @@
             stopWatching(m_fd, descriptors);
         }
 
-        public void onEvent(int wfd, int mask, String path) {
+        public void onEvent(int wfd, @NotifyEventType int mask, String path) {
             // look up our observer, fixing up the map if necessary...
             FileObserver observer = null;
 
@@ -144,7 +167,8 @@
 
         private native int init();
         private native void observe(int fd);
-        private native void startWatching(int fd, String[] paths, int mask, int[] wfds);
+        private native void startWatching(int fd, String[] paths,
+                @NotifyEventType int mask, int[] wfds);
         private native void stopWatching(int fd, int[] wfds);
     }
 
@@ -197,7 +221,7 @@
      * @deprecated use {@link #FileObserver(File, int)} instead.
      */
     @Deprecated
-    public FileObserver(String path, int mask) {
+    public FileObserver(String path, @NotifyEventType int mask) {
         this(new File(path), mask);
     }
 
@@ -209,7 +233,7 @@
      * @param file The file or directory to monitor
      * @param mask The event or events (added together) to watch for
      */
-    public FileObserver(@NonNull File file, int mask) {
+    public FileObserver(@NonNull File file, @NotifyEventType int mask) {
         this(Arrays.asList(file), mask);
     }
 
@@ -220,7 +244,7 @@
      * @param files The files or directories to monitor
      * @param mask The event or events (added together) to watch for
      */
-    public FileObserver(@NonNull List<File> files, int mask) {
+    public FileObserver(@NonNull List<File> files, @NotifyEventType int mask) {
         mFiles = files;
         mMask = mask;
     }
diff --git a/core/java/android/os/IncidentManager.java b/core/java/android/os/IncidentManager.java
index a1c7b08..0bdf6f1 100644
--- a/core/java/android/os/IncidentManager.java
+++ b/core/java/android/os/IncidentManager.java
@@ -323,7 +323,7 @@
         /**
          * {@link Parcelable.Creator Creator} for {@link IncidentReport}.
          */
-        public static final Parcelable.Creator<IncidentReport> CREATOR = new Parcelable.Creator() {
+        public static final @android.annotation.NonNull Parcelable.Creator<IncidentReport> CREATOR = new Parcelable.Creator() {
             /**
              * @inheritDoc
              */
diff --git a/core/java/android/os/IncidentReportArgs.java b/core/java/android/os/IncidentReportArgs.java
index 8d44727..1bdfd94 100644
--- a/core/java/android/os/IncidentReportArgs.java
+++ b/core/java/android/os/IncidentReportArgs.java
@@ -93,7 +93,7 @@
         mPrivacyPolicy = in.readInt();
     }
 
-    public static final Parcelable.Creator<IncidentReportArgs> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<IncidentReportArgs> CREATOR
             = new Parcelable.Creator<IncidentReportArgs>() {
         public IncidentReportArgs createFromParcel(Parcel in) {
             return new IncidentReportArgs(in);
diff --git a/core/java/android/os/LocaleList.java b/core/java/android/os/LocaleList.java
index 1420e2f..a9da080 100644
--- a/core/java/android/os/LocaleList.java
+++ b/core/java/android/os/LocaleList.java
@@ -256,7 +256,7 @@
         mStringRepresentation = sb.toString();
     }
 
-    public static final Parcelable.Creator<LocaleList> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<LocaleList> CREATOR
             = new Parcelable.Creator<LocaleList>() {
         @Override
         public LocaleList createFromParcel(Parcel source) {
diff --git a/core/java/android/os/Message.java b/core/java/android/os/Message.java
index 5d5e5e2..317579e 100644
--- a/core/java/android/os/Message.java
+++ b/core/java/android/os/Message.java
@@ -595,7 +595,7 @@
         proto.end(messageToken);
     }
 
-    public static final Parcelable.Creator<Message> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Message> CREATOR
             = new Parcelable.Creator<Message>() {
         public Message createFromParcel(Parcel source) {
             Message msg = Message.obtain();
diff --git a/core/java/android/os/Messenger.java b/core/java/android/os/Messenger.java
index f362f56..ed5c470 100644
--- a/core/java/android/os/Messenger.java
+++ b/core/java/android/os/Messenger.java
@@ -95,7 +95,7 @@
         out.writeStrongBinder(mTarget.asBinder());
     }
 
-    public static final Parcelable.Creator<Messenger> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Messenger> CREATOR
             = new Parcelable.Creator<Messenger>() {
         public Messenger createFromParcel(Parcel in) {
             IBinder target = in.readStrongBinder();
diff --git a/core/java/android/os/ParcelFileDescriptor.java b/core/java/android/os/ParcelFileDescriptor.java
index d68eeed..7a8727c 100644
--- a/core/java/android/os/ParcelFileDescriptor.java
+++ b/core/java/android/os/ParcelFileDescriptor.java
@@ -1032,7 +1032,7 @@
         }
     }
 
-    public static final Parcelable.Creator<ParcelFileDescriptor> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ParcelFileDescriptor> CREATOR
             = new Parcelable.Creator<ParcelFileDescriptor>() {
         @Override
         public ParcelFileDescriptor createFromParcel(Parcel in) {
diff --git a/core/java/android/os/ParcelUuid.java b/core/java/android/os/ParcelUuid.java
index 5b45ac2..cc50c89 100644
--- a/core/java/android/os/ParcelUuid.java
+++ b/core/java/android/os/ParcelUuid.java
@@ -109,7 +109,7 @@
        return (this.mUuid.equals(that.mUuid));
    }
 
-   public static final Parcelable.Creator<ParcelUuid> CREATOR =
+   public static final @android.annotation.NonNull Parcelable.Creator<ParcelUuid> CREATOR =
                new Parcelable.Creator<ParcelUuid>() {
         @UnsupportedAppUsage
         public ParcelUuid createFromParcel(Parcel source) {
diff --git a/core/java/android/os/ParcelableException.java b/core/java/android/os/ParcelableException.java
index 7f71905..81b9d15 100644
--- a/core/java/android/os/ParcelableException.java
+++ b/core/java/android/os/ParcelableException.java
@@ -76,7 +76,7 @@
         writeToParcel(dest, getCause());
     }
 
-    public static final Creator<ParcelableException> CREATOR = new Creator<ParcelableException>() {
+    public static final @android.annotation.NonNull Creator<ParcelableException> CREATOR = new Creator<ParcelableException>() {
         @Override
         public ParcelableException createFromParcel(Parcel source) {
             return new ParcelableException(readFromParcel(source));
diff --git a/core/java/android/os/PatternMatcher.java b/core/java/android/os/PatternMatcher.java
index 76b2142..ef03e8c 100644
--- a/core/java/android/os/PatternMatcher.java
+++ b/core/java/android/os/PatternMatcher.java
@@ -158,7 +158,7 @@
         mParsedPattern = src.createIntArray();
     }
     
-    public static final Parcelable.Creator<PatternMatcher> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<PatternMatcher> CREATOR
             = new Parcelable.Creator<PatternMatcher>() {
         public PatternMatcher createFromParcel(Parcel source) {
             return new PatternMatcher(source);
diff --git a/core/java/android/os/PersistableBundle.java b/core/java/android/os/PersistableBundle.java
index 40eceb8..6f1bf71 100644
--- a/core/java/android/os/PersistableBundle.java
+++ b/core/java/android/os/PersistableBundle.java
@@ -212,7 +212,7 @@
         }
     }
 
-    public static final Parcelable.Creator<PersistableBundle> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PersistableBundle> CREATOR =
             new Parcelable.Creator<PersistableBundle>() {
                 @Override
                 public PersistableBundle createFromParcel(Parcel in) {
diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java
index 6bd1f2b..4b32df7 100644
--- a/core/java/android/os/PowerManager.java
+++ b/core/java/android/os/PowerManager.java
@@ -694,9 +694,11 @@
             ServiceType.BATTERY_STATS,
             ServiceType.DATA_SAVER,
             ServiceType.FORCE_ALL_APPS_STANDBY,
+            ServiceType.FORCE_BACKGROUND_CHECK,
             ServiceType.OPTIONAL_SENSORS,
             ServiceType.AOD,
             ServiceType.QUICK_DOZE,
+            ServiceType.NIGHT_MODE,
     })
     public @interface ServiceType {
         int NULL = 0;
@@ -1569,7 +1571,7 @@
     @LocationPowerSaveMode
     public int getLocationPowerSaveMode() {
         final PowerSaveState powerSaveState = getPowerSaveState(ServiceType.LOCATION);
-        if (!powerSaveState.globalBatterySaverEnabled) {
+        if (!powerSaveState.batterySaverEnabled) {
             return LOCATION_MODE_NO_CHANGE;
         }
         return powerSaveState.locationMode;
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index 9e97e37..cd43b42 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -505,7 +505,6 @@
      * @param invokeWith null-ok the command to invoke with.
      * @param packageName null-ok the name of the package this process belongs to.
      * @param packagesForUid null-ok all the packages with the same uid as this process.
-     * @param visibleVols null-ok storage volumes that can be accessed by this process.
      * @param zygoteArgs Additional arguments to supply to the zygote process.
      * 
      * @return An object that describes the result of the attempt to start the process.
@@ -525,13 +524,12 @@
                                   @Nullable String invokeWith,
                                   @Nullable String packageName,
                                   @Nullable String[] packagesForUid,
-                                  @Nullable String[] visibleVols,
                                   @Nullable String sandboxId,
                                   @Nullable String[] zygoteArgs) {
         return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
                     runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                     abi, instructionSet, appDataDir, invokeWith, packageName,
-                    packagesForUid, visibleVols, sandboxId, /*useBlastulaPool=*/ true, zygoteArgs);
+                    packagesForUid, sandboxId, /*useBlastulaPool=*/ true, zygoteArgs);
     }
 
     /** @hide */
@@ -547,13 +545,12 @@
                                   @Nullable String invokeWith,
                                   @Nullable String packageName,
                                   @Nullable String[] packagesForUid,
-                                  @Nullable String[] visibleVols,
                                   @Nullable String sandboxId,
                                   @Nullable String[] zygoteArgs) {
         return WebViewZygote.getProcess().start(processClass, niceName, uid, gid, gids,
                     runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                     abi, instructionSet, appDataDir, invokeWith, packageName,
-                    packagesForUid, visibleVols, sandboxId, /*useBlastulaPool=*/ false, zygoteArgs);
+                    packagesForUid, sandboxId, /*useBlastulaPool=*/ false, zygoteArgs);
     }
 
     /**
diff --git a/core/java/android/os/RemoteCallback.java b/core/java/android/os/RemoteCallback.java
index 5914739..22cf404 100644
--- a/core/java/android/os/RemoteCallback.java
+++ b/core/java/android/os/RemoteCallback.java
@@ -94,7 +94,7 @@
         parcel.writeStrongBinder(mCallback.asBinder());
     }
 
-    public static final Parcelable.Creator<RemoteCallback> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<RemoteCallback> CREATOR
             = new Parcelable.Creator<RemoteCallback>() {
         public RemoteCallback createFromParcel(Parcel parcel) {
             return new RemoteCallback(parcel);
diff --git a/core/java/android/os/ResultReceiver.java b/core/java/android/os/ResultReceiver.java
index 34a66b6..f2d8fe4 100644
--- a/core/java/android/os/ResultReceiver.java
+++ b/core/java/android/os/ResultReceiver.java
@@ -125,7 +125,7 @@
         mReceiver = IResultReceiver.Stub.asInterface(in.readStrongBinder());
     }
     
-    public static final Parcelable.Creator<ResultReceiver> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ResultReceiver> CREATOR
             = new Parcelable.Creator<ResultReceiver>() {
         public ResultReceiver createFromParcel(Parcel in) {
             return new ResultReceiver(in);
diff --git a/core/java/android/os/SharedMemory.java b/core/java/android/os/SharedMemory.java
index e6c7a17..395485b 100644
--- a/core/java/android/os/SharedMemory.java
+++ b/core/java/android/os/SharedMemory.java
@@ -270,7 +270,7 @@
         dest.writeFileDescriptor(mFileDescriptor);
     }
 
-    public static final Parcelable.Creator<SharedMemory> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<SharedMemory> CREATOR =
             new Parcelable.Creator<SharedMemory>() {
         @Override
         public SharedMemory createFromParcel(Parcel source) {
diff --git a/core/java/android/os/ShellCallback.java b/core/java/android/os/ShellCallback.java
index 6a62424..632f6c8 100644
--- a/core/java/android/os/ShellCallback.java
+++ b/core/java/android/os/ShellCallback.java
@@ -110,7 +110,7 @@
         }
     }
 
-    public static final Parcelable.Creator<ShellCallback> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ShellCallback> CREATOR
             = new Parcelable.Creator<ShellCallback>() {
         public ShellCallback createFromParcel(Parcel in) {
             return new ShellCallback(in);
diff --git a/core/java/android/os/StatsDimensionsValue.java b/core/java/android/os/StatsDimensionsValue.java
index 257cc52..da13ea1 100644
--- a/core/java/android/os/StatsDimensionsValue.java
+++ b/core/java/android/os/StatsDimensionsValue.java
@@ -264,7 +264,7 @@
     /**
      * Parcelable Creator for StatsDimensionsValue.
      */
-    public static final Parcelable.Creator<StatsDimensionsValue> CREATOR = new
+    public static final @android.annotation.NonNull Parcelable.Creator<StatsDimensionsValue> CREATOR = new
             Parcelable.Creator<StatsDimensionsValue>() {
                 public StatsDimensionsValue createFromParcel(Parcel in) {
                     return new StatsDimensionsValue(in);
diff --git a/core/java/android/os/StatsLogEventWrapper.java b/core/java/android/os/StatsLogEventWrapper.java
index 2334242..89c9bb2 100644
--- a/core/java/android/os/StatsLogEventWrapper.java
+++ b/core/java/android/os/StatsLogEventWrapper.java
@@ -54,7 +54,7 @@
     /**
      * Boilerplate for Parcel.
      */
-    public static final Parcelable.Creator<StatsLogEventWrapper> CREATOR = new
+    public static final @android.annotation.NonNull Parcelable.Creator<StatsLogEventWrapper> CREATOR = new
             Parcelable.Creator<StatsLogEventWrapper>() {
                 public StatsLogEventWrapper createFromParcel(Parcel in) {
                     return new StatsLogEventWrapper(in);
diff --git a/core/java/android/os/StrictMode.java b/core/java/android/os/StrictMode.java
index 5ff6e55..f0b83d8 100644
--- a/core/java/android/os/StrictMode.java
+++ b/core/java/android/os/StrictMode.java
@@ -482,7 +482,7 @@
              * <p>As of the Gingerbread release this includes network and disk operations but will
              * likely expand in future releases.
              */
-            public Builder detectAll() {
+            public @NonNull Builder detectAll() {
                 detectDiskReads();
                 detectDiskWrites();
                 detectNetwork();
@@ -501,52 +501,52 @@
             }
 
             /** Disable the detection of everything. */
-            public Builder permitAll() {
+            public @NonNull Builder permitAll() {
                 return disable(DETECT_THREAD_ALL);
             }
 
             /** Enable detection of network operations. */
-            public Builder detectNetwork() {
+            public @NonNull Builder detectNetwork() {
                 return enable(DETECT_THREAD_NETWORK);
             }
 
             /** Disable detection of network operations. */
-            public Builder permitNetwork() {
+            public @NonNull Builder permitNetwork() {
                 return disable(DETECT_THREAD_NETWORK);
             }
 
             /** Enable detection of disk reads. */
-            public Builder detectDiskReads() {
+            public @NonNull Builder detectDiskReads() {
                 return enable(DETECT_THREAD_DISK_READ);
             }
 
             /** Disable detection of disk reads. */
-            public Builder permitDiskReads() {
+            public @NonNull Builder permitDiskReads() {
                 return disable(DETECT_THREAD_DISK_READ);
             }
 
             /** Enable detection of slow calls. */
-            public Builder detectCustomSlowCalls() {
+            public @NonNull Builder detectCustomSlowCalls() {
                 return enable(DETECT_THREAD_CUSTOM);
             }
 
             /** Disable detection of slow calls. */
-            public Builder permitCustomSlowCalls() {
+            public @NonNull Builder permitCustomSlowCalls() {
                 return disable(DETECT_THREAD_CUSTOM);
             }
 
             /** Disable detection of mismatches between defined resource types and getter calls. */
-            public Builder permitResourceMismatches() {
+            public @NonNull Builder permitResourceMismatches() {
                 return disable(DETECT_THREAD_RESOURCE_MISMATCH);
             }
 
             /** Detect unbuffered input/output operations. */
-            public Builder detectUnbufferedIo() {
+            public @NonNull Builder detectUnbufferedIo() {
                 return enable(DETECT_THREAD_UNBUFFERED_IO);
             }
 
             /** Disable detection of unbuffered input/output operations. */
-            public Builder permitUnbufferedIo() {
+            public @NonNull Builder permitUnbufferedIo() {
                 return disable(DETECT_THREAD_UNBUFFERED_IO);
             }
 
@@ -562,17 +562,17 @@
              * call will return a value without crashing; however, the developer should format the
              * resource as an integer to avoid unnecessary type conversion.
              */
-            public Builder detectResourceMismatches() {
+            public @NonNull Builder detectResourceMismatches() {
                 return enable(DETECT_THREAD_RESOURCE_MISMATCH);
             }
 
             /** Enable detection of disk writes. */
-            public Builder detectDiskWrites() {
+            public @NonNull Builder detectDiskWrites() {
                 return enable(DETECT_THREAD_DISK_WRITE);
             }
 
             /** Disable detection of disk writes. */
-            public Builder permitDiskWrites() {
+            public @NonNull Builder permitDiskWrites() {
                 return disable(DETECT_THREAD_DISK_WRITE);
             }
 
@@ -582,7 +582,7 @@
              * @hide
              */
             @TestApi
-            public Builder detectExplicitGc() {
+            public @NonNull Builder detectExplicitGc() {
                 // TODO(b/3400644): Un-hide this for next API update
                 // TODO(b/3400644): Un-hide ExplicitGcViolation for next API update
                 // TODO(b/3400644): Make DETECT_EXPLICIT_GC a @TestApi for next API update
@@ -595,7 +595,7 @@
              *
              * @hide
              */
-            public Builder permitExplicitGc() {
+            public @NonNull Builder permitExplicitGc() {
                 // TODO(b/3400644): Un-hide this for next API update
                 return disable(DETECT_THREAD_EXPLICIT_GC);
             }
@@ -604,7 +604,7 @@
              * Show an annoying dialog to the developer on detected violations, rate-limited to be
              * only a little annoying.
              */
-            public Builder penaltyDialog() {
+            public @NonNull Builder penaltyDialog() {
                 return enable(PENALTY_DIALOG);
             }
 
@@ -616,7 +616,7 @@
              * <p>Unlike {@link #penaltyDeathOnNetwork}, this applies to disk reads, disk writes,
              * and network usage if their corresponding detect flags are set.
              */
-            public Builder penaltyDeath() {
+            public @NonNull Builder penaltyDeath() {
                 return enable(PENALTY_DEATH);
             }
 
@@ -627,17 +627,17 @@
              *
              * <p>In the Honeycomb or later SDKs, this is on by default.
              */
-            public Builder penaltyDeathOnNetwork() {
+            public @NonNull Builder penaltyDeathOnNetwork() {
                 return enable(PENALTY_DEATH_ON_NETWORK);
             }
 
             /** Flash the screen during a violation. */
-            public Builder penaltyFlashScreen() {
+            public @NonNull Builder penaltyFlashScreen() {
                 return enable(PENALTY_FLASH);
             }
 
             /** Log detected violations to the system log. */
-            public Builder penaltyLog() {
+            public @NonNull Builder penaltyLog() {
                 return enable(PENALTY_LOG);
             }
 
@@ -646,7 +646,7 @@
              * android.os.DropBoxManager DropBox} on policy violation. Intended mostly for platform
              * integrators doing beta user field data collection.
              */
-            public Builder penaltyDropBox() {
+            public @NonNull Builder penaltyDropBox() {
                 return enable(PENALTY_DROPBOX);
             }
 
@@ -654,7 +654,7 @@
              * Call #{@link OnThreadViolationListener#onThreadViolation(Violation)} on specified
              * executor every violation.
              */
-            public Builder penaltyListener(
+            public @NonNull Builder penaltyListener(
                     @NonNull Executor executor, @NonNull OnThreadViolationListener listener) {
                 if (executor == null) {
                     throw new NullPointerException("executor must not be null");
@@ -665,7 +665,7 @@
             }
 
             /** @removed */
-            public Builder penaltyListener(
+            public @NonNull Builder penaltyListener(
                     @NonNull OnThreadViolationListener listener, @NonNull Executor executor) {
                 return penaltyListener(executor, listener);
             }
@@ -782,7 +782,7 @@
              * Set an upper bound on how many instances of a class can be in memory at once. Helps
              * to prevent object leaks.
              */
-            public Builder setClassInstanceLimit(Class klass, int instanceLimit) {
+            public @NonNull Builder setClassInstanceLimit(Class klass, int instanceLimit) {
                 if (klass == null) {
                     throw new NullPointerException("klass == null");
                 }
@@ -803,12 +803,12 @@
             }
 
             /** Detect leaks of {@link android.app.Activity} subclasses. */
-            public Builder detectActivityLeaks() {
+            public @NonNull Builder detectActivityLeaks() {
                 return enable(DETECT_VM_ACTIVITY_LEAKS);
             }
 
             /** @hide */
-            public Builder permitActivityLeaks() {
+            public @NonNull Builder permitActivityLeaks() {
                 return disable(DETECT_VM_ACTIVITY_LEAKS);
             }
 
@@ -819,7 +819,7 @@
              * enabled may not be detected. To ensure that all such API accesses are detected,
              * you should apply this policy as early as possible after process creation.
              */
-            public Builder detectNonSdkApiUsage() {
+            public @NonNull Builder detectNonSdkApiUsage() {
                 return enable(DETECT_VM_NON_SDK_API_USAGE);
             }
 
@@ -829,7 +829,7 @@
              * continue to restrict or warn on access to methods that are not part of the
              * public SDK.
              */
-            public Builder permitNonSdkApiUsage() {
+            public @NonNull Builder permitNonSdkApiUsage() {
                 return disable(DETECT_VM_NON_SDK_API_USAGE);
             }
 
@@ -839,7 +839,7 @@
              * <p>In the Honeycomb release this includes leaks of SQLite cursors, Activities, and
              * other closable objects but will likely expand in future releases.
              */
-            public Builder detectAll() {
+            public @NonNull Builder detectAll() {
                 detectLeakedSqlLiteObjects();
 
                 final int targetSdk = VMRuntime.getRuntime().getTargetSdkVersion();
@@ -881,7 +881,7 @@
              * <p>You always want to explicitly close your SQLite cursors to avoid unnecessary
              * database contention and temporary memory leaks.
              */
-            public Builder detectLeakedSqlLiteObjects() {
+            public @NonNull Builder detectLeakedSqlLiteObjects() {
                 return enable(DETECT_VM_CURSOR_LEAKS);
             }
 
@@ -892,7 +892,7 @@
              * <p>You always want to explicitly close such objects to avoid unnecessary resources
              * leaks.
              */
-            public Builder detectLeakedClosableObjects() {
+            public @NonNull Builder detectLeakedClosableObjects() {
                 return enable(DETECT_VM_CLOSABLE_LEAKS);
             }
 
@@ -900,7 +900,7 @@
              * Detect when a {@link BroadcastReceiver} or {@link ServiceConnection} is leaked during
              * {@link Context} teardown.
              */
-            public Builder detectLeakedRegistrationObjects() {
+            public @NonNull Builder detectLeakedRegistrationObjects() {
                 return enable(DETECT_VM_REGISTRATION_LEAKS);
             }
 
@@ -919,7 +919,7 @@
              * @see android.support.v4.content.FileProvider
              * @see Intent#FLAG_GRANT_READ_URI_PERMISSION
              */
-            public Builder detectFileUriExposure() {
+            public @NonNull Builder detectFileUriExposure() {
                 return enable(DETECT_VM_FILE_URI_EXPOSURE);
             }
 
@@ -938,7 +938,7 @@
              * <p>This inspects both IPv4/IPv6 and TCP/UDP network traffic, but it may be subject to
              * false positives, such as when STARTTLS protocols or HTTP proxies are used.
              */
-            public Builder detectCleartextNetwork() {
+            public @NonNull Builder detectCleartextNetwork() {
                 return enable(DETECT_VM_CLEARTEXT_NETWORK);
             }
 
@@ -954,7 +954,7 @@
              * @see Intent#FLAG_GRANT_READ_URI_PERMISSION
              * @see Intent#FLAG_GRANT_WRITE_URI_PERMISSION
              */
-            public Builder detectContentUriWithoutPermission() {
+            public @NonNull Builder detectContentUriWithoutPermission() {
                 return enable(DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION);
             }
 
@@ -969,12 +969,12 @@
              * @see TrafficStats#tagSocket(java.net.Socket)
              * @see TrafficStats#tagDatagramSocket(java.net.DatagramSocket)
              */
-            public Builder detectUntaggedSockets() {
+            public @NonNull Builder detectUntaggedSockets() {
                 return enable(DETECT_VM_UNTAGGED_SOCKET);
             }
 
             /** @hide */
-            public Builder permitUntaggedSockets() {
+            public @NonNull Builder permitUntaggedSockets() {
                 return disable(DETECT_VM_UNTAGGED_SOCKET);
             }
 
@@ -992,12 +992,12 @@
              * <li>{@link PackageManager#MATCH_DIRECT_BOOT_AUTO}
              * </ul>
              */
-            public Builder detectImplicitDirectBoot() {
+            public @NonNull Builder detectImplicitDirectBoot() {
                 return enable(DETECT_VM_IMPLICIT_DIRECT_BOOT);
             }
 
             /** @hide */
-            public Builder permitImplicitDirectBoot() {
+            public @NonNull Builder permitImplicitDirectBoot() {
                 return disable(DETECT_VM_IMPLICIT_DIRECT_BOOT);
             }
 
@@ -1014,12 +1014,12 @@
              * @see Context#createCredentialProtectedStorageContext()
              * @see Context#createDeviceProtectedStorageContext()
              */
-            public Builder detectCredentialProtectedWhileLocked() {
+            public @NonNull Builder detectCredentialProtectedWhileLocked() {
                 return enable(DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED);
             }
 
             /** @hide */
-            public Builder permitCredentialProtectedWhileLocked() {
+            public @NonNull Builder permitCredentialProtectedWhileLocked() {
                 return disable(DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED);
             }
 
@@ -1028,7 +1028,7 @@
              * penalties so you'll still get your logging or other violations before the process
              * dies.
              */
-            public Builder penaltyDeath() {
+            public @NonNull Builder penaltyDeath() {
                 return enable(PENALTY_DEATH);
             }
 
@@ -1037,7 +1037,7 @@
              *
              * @see #detectCleartextNetwork()
              */
-            public Builder penaltyDeathOnCleartextNetwork() {
+            public @NonNull Builder penaltyDeathOnCleartextNetwork() {
                 return enable(PENALTY_DEATH_ON_CLEARTEXT_NETWORK);
             }
 
@@ -1047,12 +1047,12 @@
              *
              * @see #detectFileUriExposure()
              */
-            public Builder penaltyDeathOnFileUriExposure() {
+            public @NonNull Builder penaltyDeathOnFileUriExposure() {
                 return enable(PENALTY_DEATH_ON_FILE_URI_EXPOSURE);
             }
 
             /** Log detected violations to the system log. */
-            public Builder penaltyLog() {
+            public @NonNull Builder penaltyLog() {
                 return enable(PENALTY_LOG);
             }
 
@@ -1061,14 +1061,14 @@
              * android.os.DropBoxManager DropBox} on policy violation. Intended mostly for platform
              * integrators doing beta user field data collection.
              */
-            public Builder penaltyDropBox() {
+            public @NonNull Builder penaltyDropBox() {
                 return enable(PENALTY_DROPBOX);
             }
 
             /**
              * Call #{@link OnVmViolationListener#onVmViolation(Violation)} on every violation.
              */
-            public Builder penaltyListener(
+            public @NonNull Builder penaltyListener(
                     @NonNull Executor executor, @NonNull OnVmViolationListener listener) {
                 if (executor == null) {
                     throw new NullPointerException("executor must not be null");
@@ -1079,7 +1079,7 @@
             }
 
             /** @removed */
-            public Builder penaltyListener(
+            public @NonNull Builder penaltyListener(
                     @NonNull OnVmViolationListener listener, @NonNull Executor executor) {
                 return penaltyListener(executor, listener);
             }
@@ -2853,7 +2853,7 @@
             return 0;
         }
 
-        public static final Parcelable.Creator<ViolationInfo> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<ViolationInfo> CREATOR =
                 new Parcelable.Creator<ViolationInfo>() {
                     @Override
                     public ViolationInfo createFromParcel(Parcel in) {
diff --git a/core/java/android/os/Temperature.java b/core/java/android/os/Temperature.java
index eee2b52..be7e824 100644
--- a/core/java/android/os/Temperature.java
+++ b/core/java/android/os/Temperature.java
@@ -177,7 +177,7 @@
         p.writeInt(mStatus);
     }
 
-    public static final Parcelable.Creator<Temperature> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<Temperature> CREATOR =
             new Parcelable.Creator<Temperature>() {
                 @Override
                 public Temperature createFromParcel(Parcel p) {
diff --git a/core/java/android/os/UserHandle.java b/core/java/android/os/UserHandle.java
index 40c48a0..82d1b1a 100644
--- a/core/java/android/os/UserHandle.java
+++ b/core/java/android/os/UserHandle.java
@@ -481,7 +481,7 @@
         return h != USER_NULL ? new UserHandle(h) : null;
     }
     
-    public static final Parcelable.Creator<UserHandle> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<UserHandle> CREATOR
             = new Parcelable.Creator<UserHandle>() {
         public UserHandle createFromParcel(Parcel in) {
             return new UserHandle(in);
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index 0673755..7f73dab 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -3021,7 +3021,7 @@
             userRestrictionSource = in.readInt();
         }
 
-        public static final Creator<EnforcingUser> CREATOR = new Creator<EnforcingUser>() {
+        public static final @android.annotation.NonNull Creator<EnforcingUser> CREATOR = new Creator<EnforcingUser>() {
             @Override
             public EnforcingUser createFromParcel(Parcel in) {
                 return new EnforcingUser(in);
diff --git a/core/java/android/os/VibrationEffect.java b/core/java/android/os/VibrationEffect.java
index 99fb608..44add87 100644
--- a/core/java/android/os/VibrationEffect.java
+++ b/core/java/android/os/VibrationEffect.java
@@ -240,7 +240,7 @@
      *
      * @return The desired effect.
      */
-    public static VibrationEffect createPrebaked(@EffectType int effectId) {
+    public static VibrationEffect createPredefined(@EffectType int effectId) {
         return get(effectId, true);
     }
 
@@ -471,7 +471,7 @@
             out.writeInt(mAmplitude);
         }
 
-        public static final Parcelable.Creator<OneShot> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<OneShot> CREATOR =
             new Parcelable.Creator<OneShot>() {
                 @Override
                 public OneShot createFromParcel(Parcel in) {
@@ -659,7 +659,7 @@
         }
 
 
-        public static final Parcelable.Creator<Waveform> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<Waveform> CREATOR =
             new Parcelable.Creator<Waveform>() {
                 @Override
                 public Waveform createFromParcel(Parcel in) {
@@ -796,7 +796,7 @@
             out.writeInt(mEffectStrength);
         }
 
-        public static final Parcelable.Creator<Prebaked> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<Prebaked> CREATOR =
             new Parcelable.Creator<Prebaked>() {
                 @Override
                 public Prebaked createFromParcel(Parcel in) {
@@ -811,7 +811,7 @@
             };
     }
 
-    public static final Parcelable.Creator<VibrationEffect> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<VibrationEffect> CREATOR =
             new Parcelable.Creator<VibrationEffect>() {
                 @Override
                 public VibrationEffect createFromParcel(Parcel in) {
diff --git a/core/java/android/os/WorkSource.java b/core/java/android/os/WorkSource.java
index 76fe560..9980ade 100644
--- a/core/java/android/os/WorkSource.java
+++ b/core/java/android/os/WorkSource.java
@@ -1030,7 +1030,7 @@
             dest.writeStringArray(mTags);
         }
 
-        public static final Parcelable.Creator<WorkChain> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<WorkChain> CREATOR =
                 new Parcelable.Creator<WorkChain>() {
                     public WorkChain createFromParcel(Parcel in) {
                         return new WorkChain(in);
@@ -1171,7 +1171,7 @@
         proto.end(workSourceToken);
     }
 
-    public static final Parcelable.Creator<WorkSource> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<WorkSource> CREATOR
             = new Parcelable.Creator<WorkSource>() {
         public WorkSource createFromParcel(Parcel in) {
             return new WorkSource(in);
diff --git a/core/java/android/os/ZygoteProcess.java b/core/java/android/os/ZygoteProcess.java
index de378b0..650232f 100644
--- a/core/java/android/os/ZygoteProcess.java
+++ b/core/java/android/os/ZygoteProcess.java
@@ -27,7 +27,6 @@
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.os.Zygote;
-import com.android.internal.util.Preconditions;
 
 import java.io.BufferedWriter;
 import java.io.DataInputStream;
@@ -122,8 +121,9 @@
                 new LocalSocketAddress(Zygote.BLASTULA_POOL_SECONDARY_SOCKET_NAME,
                                        LocalSocketAddress.Namespace.RESERVED);
 
-        // TODO (chriswailes): Uncomment when the blastula pool can be enabled.
-//        fetchBlastulaPoolEnabledProp();
+        if (fetchBlastulaPoolEnabledProp()) {
+            informZygotesOfBlastulaPoolStatus();
+        }
     }
 
     public ZygoteProcess(LocalSocketAddress primarySocketAddress,
@@ -253,6 +253,11 @@
     private int mHiddenApiAccessLogSampleRate;
 
     /**
+     * Proportion of hidden API accesses that should be logged to statslog; 0 - 0x10000.
+     */
+    private int mHiddenApiAccessStatslogSampleRate;
+
+    /**
      * The state of the connection to the primary zygote.
      */
     private ZygoteState primaryZygoteState;
@@ -305,7 +310,6 @@
      * @param invokeWith null-ok the command to invoke with.
      * @param packageName null-ok the name of the package this process belongs to.
      * @param packagesForUid null-ok all the packages with the same uid as this process.
-     * @param visibleVols null-ok storage volumes that can be accessed by this process.
      * @param zygoteArgs Additional arguments to supply to the zygote process.
      *
      * @return An object that describes the result of the attempt to start the process.
@@ -323,23 +327,19 @@
                                                   @Nullable String invokeWith,
                                                   @Nullable String packageName,
                                                   @Nullable String[] packagesForUid,
-                                                  @Nullable String[] visibleVols,
                                                   @Nullable String sandboxId,
                                                   boolean useBlastulaPool,
                                                   @Nullable String[] zygoteArgs) {
-        if (fetchBlastulaPoolEnabledProp()) {
-            // TODO (chriswailes): Send the appropriate command to the zygotes
-            Log.i(LOG_TAG, "Blastula pool enabled property set to: " + mBlastulaPoolEnabled);
-
-            // This can't be enabled yet, but we do want to test this code path.
-            mBlastulaPoolEnabled = false;
+        // TODO (chriswailes): Is there a better place to check this value?
+        if (fetchBlastulaPoolEnabledPropWithMinInterval()) {
+            informZygotesOfBlastulaPoolStatus();
         }
 
         try {
             return startViaZygote(processClass, niceName, uid, gid, gids,
                     runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                     abi, instructionSet, appDataDir, invokeWith, /*startChildZygote=*/false,
-                    packageName, packagesForUid, visibleVols, sandboxId,
+                    packageName, packagesForUid, sandboxId,
                     useBlastulaPool, zygoteArgs);
         } catch (ZygoteStartFailedEx ex) {
             Log.e(LOG_TAG,
@@ -387,7 +387,7 @@
      * @throws ZygoteStartFailedEx if process start failed for any reason
      */
     @GuardedBy("mLock")
-    private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
+    private Process.ProcessStartResult zygoteSendArgsAndGetResult(
             ZygoteState zygoteState, boolean useBlastulaPool, ArrayList<String> args)
             throws ZygoteStartFailedEx {
         // Throw early if any of the arguments are malformed. This means we can
@@ -415,7 +415,7 @@
         Process.ProcessStartResult result = new Process.ProcessStartResult();
 
         // TODO (chriswailes): Move branch body into separate function.
-        if (useBlastulaPool && isValidBlastulaCommand(args)) {
+        if (useBlastulaPool && mBlastulaPoolEnabled && isValidBlastulaCommand(args)) {
             LocalSocket blastulaSessionSocket = null;
 
             try {
@@ -444,7 +444,7 @@
                 // If there was an IOException using the blastula pool we will log the error and
                 // attempt to start the process through the Zygote.
                 Log.e(LOG_TAG, "IO Exception while communicating with blastula pool - "
-                               + ex.toString());
+                               + ex.getMessage());
             } finally {
                 try {
                     blastulaSessionSocket.close();
@@ -492,6 +492,7 @@
         "--start-child-zygote",
         "--set-api-blacklist-exemptions",
         "--hidden-api-log-sampling-rate",
+        "--hidden-api-statslog-sampling-rate",
         "--invoke-with"
     };
 
@@ -531,7 +532,6 @@
      * that has its state cloned from this zygote process.
      * @param packageName null-ok the name of the package this process belongs to.
      * @param packagesForUid null-ok all the packages with the same uid as this process.
-     * @param visibleVols null-ok storage volumes that can be accessed by this process.
      * @param extraArgs Additional arguments to supply to the zygote process.
      * @return An object that describes the result of the attempt to start the process.
      * @throws ZygoteStartFailedEx if process start failed for any reason
@@ -550,7 +550,6 @@
                                                       boolean startChildZygote,
                                                       @Nullable String packageName,
                                                       @Nullable String[] packagesForUid,
-                                                      @Nullable String[] visibleVols,
                                                       @Nullable String sandboxId,
                                                       boolean useBlastulaPool,
                                                       @Nullable String[] extraArgs)
@@ -638,19 +637,6 @@
             argsForZygote.add(sb.toString());
         }
 
-        if (visibleVols != null && visibleVols.length > 0) {
-            final StringBuilder sb = new StringBuilder();
-            sb.append("--visible-vols=");
-
-            for (int i = 0; i < visibleVols.length; ++i) {
-                if (i != 0) {
-                    sb.append(',');
-                }
-                sb.append(visibleVols[i]);
-            }
-            argsForZygote.add(sb.toString());
-        }
-
         if (sandboxId != null) {
             argsForZygote.add("--sandbox-id=" + sandboxId);
         }
@@ -665,7 +651,7 @@
 
         synchronized(mLock) {
             return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
-                                              useBlastulaPool && mBlastulaPoolEnabled,
+                                              useBlastulaPool,
                                               argsForZygote);
         }
     }
@@ -685,6 +671,10 @@
                             Boolean.parseBoolean(BLASTULA_POOL_ENABLED_DEFAULT));
         }
 
+        if (origVal != mBlastulaPoolEnabled) {
+            Log.i(LOG_TAG, "blastulaPoolEnabled = " + mBlastulaPoolEnabled);
+        }
+
         return origVal != mBlastulaPoolEnabled;
     }
 
@@ -792,6 +782,21 @@
         }
     }
 
+    /**
+     * Set the precentage of detected hidden API accesses that are logged to the new event log.
+     *
+     * <p>This rate will take affect for all new processes forked from the zygote after this call.
+     *
+     * @param rate An integer between 0 and 0x10000 inclusive. 0 means no event logging.
+     */
+    public void setHiddenApiAccessStatslogSampleRate(int rate) {
+        synchronized (mLock) {
+            mHiddenApiAccessStatslogSampleRate = rate;
+            maybeSetHiddenApiAccessStatslogSampleRate(primaryZygoteState);
+            maybeSetHiddenApiAccessStatslogSampleRate(secondaryZygoteState);
+        }
+    }
+
     @GuardedBy("mLock")
     private boolean maybeSetApiBlacklistExemptions(ZygoteState state, boolean sendIfEmpty) {
         if (state == null || state.isClosed()) {
@@ -846,6 +851,59 @@
         }
     }
 
+    private void maybeSetHiddenApiAccessStatslogSampleRate(ZygoteState state) {
+        if (state == null || state.isClosed()) {
+            return;
+        }
+        if (mHiddenApiAccessStatslogSampleRate == -1) {
+            return;
+        }
+        try {
+            state.mZygoteOutputWriter.write(Integer.toString(1));
+            state.mZygoteOutputWriter.newLine();
+            state.mZygoteOutputWriter.write("--hidden-api-statslog-sampling-rate="
+                    + Integer.toString(mHiddenApiAccessStatslogSampleRate));
+            state.mZygoteOutputWriter.newLine();
+            state.mZygoteOutputWriter.flush();
+            int status = state.mZygoteInputStream.readInt();
+            if (status != 0) {
+                Slog.e(LOG_TAG, "Failed to set hidden API statslog sampling rate; status "
+                        + status);
+            }
+        } catch (IOException ioe) {
+            Slog.e(LOG_TAG, "Failed to set hidden API statslog sampling rate", ioe);
+        }
+    }
+
+    /**
+     * Creates a ZygoteState for the primary zygote if it doesn't exist or has been disconnected.
+     */
+    @GuardedBy("mLock")
+    private void attemptConnectionToPrimaryZygote() throws IOException {
+        if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
+            primaryZygoteState =
+                    ZygoteState.connect(mZygoteSocketAddress, mBlastulaPoolSocketAddress);
+
+            maybeSetApiBlacklistExemptions(primaryZygoteState, false);
+            maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
+        }
+    }
+
+    /**
+     * Creates a ZygoteState for the secondary zygote if it doesn't exist or has been disconnected.
+     */
+    @GuardedBy("mLock")
+    private void attemptConnectionToSecondaryZygote() throws IOException {
+        if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
+            secondaryZygoteState =
+                    ZygoteState.connect(mZygoteSecondarySocketAddress,
+                            mBlastulaPoolSecondarySocketAddress);
+
+            maybeSetApiBlacklistExemptions(secondaryZygoteState, false);
+            maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
+        }
+    }
+
     /**
      * Tries to open a session socket to a Zygote process with a compatible ABI if one is not
      * already open. If a compatible session socket is already open that session socket is returned.
@@ -853,43 +911,22 @@
      * appropriate one.  Requires that mLock be held.
      */
     @GuardedBy("mLock")
-    private ZygoteState openZygoteSocketIfNeeded(String abi)
-            throws ZygoteStartFailedEx {
+    private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
+        try {
+            attemptConnectionToPrimaryZygote();
 
-        Preconditions.checkState(Thread.holdsLock(mLock), "ZygoteProcess lock not held");
-
-        if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
-            try {
-                primaryZygoteState =
-                    ZygoteState.connect(mZygoteSocketAddress, mBlastulaPoolSocketAddress);
-            } catch (IOException ioe) {
-                throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
+            if (primaryZygoteState.matches(abi)) {
+                return primaryZygoteState;
             }
 
-            maybeSetApiBlacklistExemptions(primaryZygoteState, false);
-            maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
-        }
+            // The primary zygote didn't match. Try the secondary.
+            attemptConnectionToSecondaryZygote();
 
-        if (primaryZygoteState.matches(abi)) {
-            return primaryZygoteState;
-        }
-
-        // The primary zygote didn't match. Try the secondary.
-        if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
-            try {
-                secondaryZygoteState =
-                    ZygoteState.connect(mZygoteSecondarySocketAddress,
-                                        mBlastulaPoolSecondarySocketAddress);
-            } catch (IOException ioe) {
-                throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
+            if (secondaryZygoteState.matches(abi)) {
+                return secondaryZygoteState;
             }
-
-            maybeSetApiBlacklistExemptions(secondaryZygoteState, false);
-            maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
-        }
-
-        if (secondaryZygoteState.matches(abi)) {
-            return secondaryZygoteState;
+        } catch (IOException ioe) {
+            throw new ZygoteStartFailedEx("Error connecting to zygote", ioe);
         }
 
         throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
@@ -1015,6 +1052,57 @@
     }
 
     /**
+     * Sends messages to the zygotes telling them to change the status of their blastula pools.  If
+     * this notification fails the ZygoteProcess will fall back to the previous behavior.
+     */
+    private void informZygotesOfBlastulaPoolStatus() {
+        final String command = "1\n--blastula-pool-enabled=" + mBlastulaPoolEnabled + "\n";
+
+        synchronized (mLock) {
+            try {
+                attemptConnectionToPrimaryZygote();
+
+                primaryZygoteState.mZygoteOutputWriter.write(command);
+                primaryZygoteState.mZygoteOutputWriter.flush();
+            } catch (IOException ioe) {
+                mBlastulaPoolEnabled = !mBlastulaPoolEnabled;
+                Log.w(LOG_TAG, "Failed to inform zygotes of blastula pool status: "
+                        + ioe.getMessage());
+                return;
+            }
+
+            try {
+                attemptConnectionToSecondaryZygote();
+
+                try {
+                    secondaryZygoteState.mZygoteOutputWriter.write(command);
+                    secondaryZygoteState.mZygoteOutputWriter.flush();
+
+                    // Wait for the secondary Zygote to finish its work.
+                    secondaryZygoteState.mZygoteInputStream.readInt();
+                } catch (IOException ioe) {
+                    throw new IllegalStateException(
+                            "Blastula pool state change cause an irrecoverable error",
+                            ioe);
+                }
+            } catch (IOException ioe) {
+                // No secondary zygote present.  This is expected on some devices.
+            }
+
+            // Wait for the response from the primary zygote here so the primary/secondary zygotes
+            // can work concurrently.
+            try {
+                // Wait for the primary zygote to finish its work.
+                primaryZygoteState.mZygoteInputStream.readInt();
+            } catch (IOException ioe) {
+                throw new IllegalStateException(
+                        "Blastula pool state change cause an irrecoverable error",
+                        ioe);
+            }
+        }
+    }
+
+    /**
      * Starts a new zygote process as a child of this zygote. This is used to create
      * secondary zygotes that inherit data from the zygote that this object
      * communicates with. This returns a new ZygoteProcess representing a connection
@@ -1061,7 +1149,7 @@
                     gids, runtimeFlags, 0 /* mountExternal */, 0 /* targetSdkVersion */, seInfo,
                     abi, instructionSet, null /* appDataDir */, null /* invokeWith */,
                     true /* startChildZygote */, null /* packageName */,
-                    null /* packagesForUid */, null /* visibleVolumes */, null /* sandboxId */,
+                    null /* packagesForUid */, null /* sandboxId */,
                     false /* useBlastulaPool */, extraArgs);
         } catch (ZygoteStartFailedEx ex) {
             throw new RuntimeException("Starting child-zygote through Zygote failed", ex);
diff --git a/core/java/android/os/connectivity/CellularBatteryStats.java b/core/java/android/os/connectivity/CellularBatteryStats.java
index c99ecb32..2e09040 100644
--- a/core/java/android/os/connectivity/CellularBatteryStats.java
+++ b/core/java/android/os/connectivity/CellularBatteryStats.java
@@ -46,7 +46,7 @@
   private long[] mTxTimeMs;
   private long mMonitoredRailChargeConsumedMaMs;
 
-  public static final Parcelable.Creator<CellularBatteryStats> CREATOR = new
+  public static final @android.annotation.NonNull Parcelable.Creator<CellularBatteryStats> CREATOR = new
       Parcelable.Creator<CellularBatteryStats>() {
         public CellularBatteryStats createFromParcel(Parcel in) {
           return new CellularBatteryStats(in);
diff --git a/core/java/android/os/connectivity/GpsBatteryStats.java b/core/java/android/os/connectivity/GpsBatteryStats.java
index f2ac5ef..ef03caa 100644
--- a/core/java/android/os/connectivity/GpsBatteryStats.java
+++ b/core/java/android/os/connectivity/GpsBatteryStats.java
@@ -33,7 +33,7 @@
   private long mEnergyConsumedMaMs;
   private long[] mTimeInGpsSignalQualityLevel;
 
-  public static final Parcelable.Creator<GpsBatteryStats> CREATOR = new
+  public static final @android.annotation.NonNull Parcelable.Creator<GpsBatteryStats> CREATOR = new
       Parcelable.Creator<GpsBatteryStats>() {
         public GpsBatteryStats createFromParcel(Parcel in) {
           return new GpsBatteryStats(in);
diff --git a/core/java/android/os/connectivity/WifiBatteryStats.java b/core/java/android/os/connectivity/WifiBatteryStats.java
index 3639c71..9d2d5d8 100644
--- a/core/java/android/os/connectivity/WifiBatteryStats.java
+++ b/core/java/android/os/connectivity/WifiBatteryStats.java
@@ -46,7 +46,7 @@
   private long[] mTimeInRxSignalStrengthLevelMs;
   private long mMonitoredRailChargeConsumedMaMs;
 
-  public static final Parcelable.Creator<WifiBatteryStats> CREATOR = new
+  public static final @android.annotation.NonNull Parcelable.Creator<WifiBatteryStats> CREATOR = new
       Parcelable.Creator<WifiBatteryStats>() {
         public WifiBatteryStats createFromParcel(Parcel in) {
           return new WifiBatteryStats(in);
diff --git a/core/java/android/os/health/HealthStatsParceler.java b/core/java/android/os/health/HealthStatsParceler.java
index d358a2e..de98359 100644
--- a/core/java/android/os/health/HealthStatsParceler.java
+++ b/core/java/android/os/health/HealthStatsParceler.java
@@ -41,7 +41,7 @@
     private HealthStatsWriter mWriter;
     private HealthStats mHealthStats;
 
-    public static final Parcelable.Creator<HealthStatsParceler> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<HealthStatsParceler> CREATOR
             = new Parcelable.Creator<HealthStatsParceler>() {
         public HealthStatsParceler createFromParcel(Parcel in) {
             return new HealthStatsParceler(in);
diff --git a/core/java/android/os/health/TimerStat.java b/core/java/android/os/health/TimerStat.java
index 6af1faf..4aaa85f 100644
--- a/core/java/android/os/health/TimerStat.java
+++ b/core/java/android/os/health/TimerStat.java
@@ -34,7 +34,7 @@
     /**
      * The CREATOR instance for use by aidl Binder interfaces.
      */
-    public static final Parcelable.Creator<TimerStat> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<TimerStat> CREATOR
             = new Parcelable.Creator<TimerStat>() {
         public TimerStat createFromParcel(Parcel in) {
             return new TimerStat(in);
diff --git a/core/java/android/os/storage/DiskInfo.java b/core/java/android/os/storage/DiskInfo.java
index 828f1c3..b797324 100644
--- a/core/java/android/os/storage/DiskInfo.java
+++ b/core/java/android/os/storage/DiskInfo.java
@@ -198,7 +198,7 @@
     }
 
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
-    public static final Creator<DiskInfo> CREATOR = new Creator<DiskInfo>() {
+    public static final @android.annotation.NonNull Creator<DiskInfo> CREATOR = new Creator<DiskInfo>() {
         @Override
         public DiskInfo createFromParcel(Parcel in) {
             return new DiskInfo(in);
diff --git a/core/java/android/os/storage/StorageManager.java b/core/java/android/os/storage/StorageManager.java
index 90a5f76..27e3914 100644
--- a/core/java/android/os/storage/StorageManager.java
+++ b/core/java/android/os/storage/StorageManager.java
@@ -136,6 +136,8 @@
     public static final String PROP_ISOLATED_STORAGE = "persist.sys.isolated_storage";
     /** {@hide} */
     public static final String PROP_ISOLATED_STORAGE_SNAPSHOT = "sys.isolated_storage_snapshot";
+    /** {@hide} */
+    public static final String PROP_LEGACY_GREYLIST = "persist.sys.legacy_greylist";
 
     /** {@hide} */
     public static final String PROP_FORCE_AUDIO = "persist.fw.force_audio";
@@ -233,6 +235,8 @@
     public static final int DEBUG_ISOLATED_STORAGE_FORCE_ON = 1 << 6;
     /** {@hide} */
     public static final int DEBUG_ISOLATED_STORAGE_FORCE_OFF = 1 << 7;
+    /** {@hide} */
+    public static final int DEBUG_LEGACY_GREYLIST = 1 << 8;
 
     /** {@hide} */
     public static final int FLAG_STORAGE_DE = IInstalld.FLAG_STORAGE_DE;
diff --git a/core/java/android/os/storage/StorageManagerInternal.java b/core/java/android/os/storage/StorageManagerInternal.java
index 03b2c2c..f1c3138 100644
--- a/core/java/android/os/storage/StorageManagerInternal.java
+++ b/core/java/android/os/storage/StorageManagerInternal.java
@@ -109,11 +109,6 @@
             @Nullable String sharedUserId, int userId);
 
     /**
-     * @return Labels of storage volumes that are visible to the given userId.
-     */
-    public abstract String[] getVisibleVolumesForUser(int userId);
-
-    /**
      * A listener for reset events in the StorageManagerService.
      */
     public interface ResetListener {
diff --git a/core/java/android/os/storage/StorageVolume.java b/core/java/android/os/storage/StorageVolume.java
index 714a061..225ecfa 100644
--- a/core/java/android/os/storage/StorageVolume.java
+++ b/core/java/android/os/storage/StorageVolume.java
@@ -431,7 +431,7 @@
         pw.decreaseIndent();
     }
 
-    public static final Creator<StorageVolume> CREATOR = new Creator<StorageVolume>() {
+    public static final @android.annotation.NonNull Creator<StorageVolume> CREATOR = new Creator<StorageVolume>() {
         @Override
         public StorageVolume createFromParcel(Parcel in) {
             return new StorageVolume(in);
diff --git a/core/java/android/os/storage/VolumeInfo.java b/core/java/android/os/storage/VolumeInfo.java
index 5d310e1..7699a05 100644
--- a/core/java/android/os/storage/VolumeInfo.java
+++ b/core/java/android/os/storage/VolumeInfo.java
@@ -527,7 +527,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Creator<VolumeInfo> CREATOR = new Creator<VolumeInfo>() {
+    public static final @android.annotation.NonNull Creator<VolumeInfo> CREATOR = new Creator<VolumeInfo>() {
         @Override
         public VolumeInfo createFromParcel(Parcel in) {
             return new VolumeInfo(in);
diff --git a/core/java/android/os/storage/VolumeRecord.java b/core/java/android/os/storage/VolumeRecord.java
index bc2d55a..b6ee261 100644
--- a/core/java/android/os/storage/VolumeRecord.java
+++ b/core/java/android/os/storage/VolumeRecord.java
@@ -130,7 +130,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Creator<VolumeRecord> CREATOR = new Creator<VolumeRecord>() {
+    public static final @android.annotation.NonNull Creator<VolumeRecord> CREATOR = new Creator<VolumeRecord>() {
         @Override
         public VolumeRecord createFromParcel(Parcel in) {
             return new VolumeRecord(in);
diff --git a/core/java/android/permission/RuntimePermissionPresentationInfo.java b/core/java/android/permission/RuntimePermissionPresentationInfo.java
index ed7b05c..d66789f 100644
--- a/core/java/android/permission/RuntimePermissionPresentationInfo.java
+++ b/core/java/android/permission/RuntimePermissionPresentationInfo.java
@@ -97,7 +97,7 @@
         parcel.writeInt(mFlags);
     }
 
-    public static final Creator<RuntimePermissionPresentationInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<RuntimePermissionPresentationInfo> CREATOR =
             new Creator<RuntimePermissionPresentationInfo>() {
         public RuntimePermissionPresentationInfo createFromParcel(Parcel source) {
             return new RuntimePermissionPresentationInfo(source);
diff --git a/core/java/android/permission/RuntimePermissionUsageInfo.java b/core/java/android/permission/RuntimePermissionUsageInfo.java
index af1a1be..9f954f7 100644
--- a/core/java/android/permission/RuntimePermissionUsageInfo.java
+++ b/core/java/android/permission/RuntimePermissionUsageInfo.java
@@ -83,7 +83,7 @@
         parcel.writeInt(mNumUsers);
     }
 
-    public static final Creator<RuntimePermissionUsageInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<RuntimePermissionUsageInfo> CREATOR =
             new Creator<RuntimePermissionUsageInfo>() {
         public RuntimePermissionUsageInfo createFromParcel(Parcel source) {
             return new RuntimePermissionUsageInfo(source);
diff --git a/core/java/android/preference/DialogPreference.java b/core/java/android/preference/DialogPreference.java
index 96c8589..8880296 100644
--- a/core/java/android/preference/DialogPreference.java
+++ b/core/java/android/preference/DialogPreference.java
@@ -519,7 +519,7 @@
             super(superState);
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/preference/EditTextPreference.java b/core/java/android/preference/EditTextPreference.java
index c09cec8..74c5e3e 100644
--- a/core/java/android/preference/EditTextPreference.java
+++ b/core/java/android/preference/EditTextPreference.java
@@ -234,7 +234,7 @@
             super(superState);
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/preference/ListPreference.java b/core/java/android/preference/ListPreference.java
index 14c1dc81..830de525 100644
--- a/core/java/android/preference/ListPreference.java
+++ b/core/java/android/preference/ListPreference.java
@@ -348,7 +348,7 @@
             super(superState);
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/preference/MultiCheckPreference.java b/core/java/android/preference/MultiCheckPreference.java
index e3d0e26..4b854ad 100644
--- a/core/java/android/preference/MultiCheckPreference.java
+++ b/core/java/android/preference/MultiCheckPreference.java
@@ -329,7 +329,7 @@
             super(superState);
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/preference/MultiSelectListPreference.java b/core/java/android/preference/MultiSelectListPreference.java
index 43182d9..3d80717 100644
--- a/core/java/android/preference/MultiSelectListPreference.java
+++ b/core/java/android/preference/MultiSelectListPreference.java
@@ -279,7 +279,7 @@
             dest.writeStringArray(values.toArray(new String[0]));
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/preference/Preference.java b/core/java/android/preference/Preference.java
index 3c1ba9d..e82e60d 100644
--- a/core/java/android/preference/Preference.java
+++ b/core/java/android/preference/Preference.java
@@ -2108,7 +2108,7 @@
             super(superState);
         }
 
-        public static final Parcelable.Creator<BaseSavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<BaseSavedState> CREATOR =
                 new Parcelable.Creator<BaseSavedState>() {
                     public BaseSavedState createFromParcel(Parcel in) {
                         return new BaseSavedState(in);
diff --git a/core/java/android/preference/PreferenceActivity.java b/core/java/android/preference/PreferenceActivity.java
index eab5937..4750971 100644
--- a/core/java/android/preference/PreferenceActivity.java
+++ b/core/java/android/preference/PreferenceActivity.java
@@ -518,7 +518,7 @@
             readFromParcel(in);
         }
 
-        public static final Creator<Header> CREATOR = new Creator<Header>() {
+        public static final @android.annotation.NonNull Creator<Header> CREATOR = new Creator<Header>() {
             public Header createFromParcel(Parcel source) {
                 return new Header(source);
             }
diff --git a/core/java/android/preference/PreferenceScreen.java b/core/java/android/preference/PreferenceScreen.java
index c7653c8..a353dbc 100644
--- a/core/java/android/preference/PreferenceScreen.java
+++ b/core/java/android/preference/PreferenceScreen.java
@@ -315,7 +315,7 @@
             super(superState);
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/preference/SeekBarPreference.java b/core/java/android/preference/SeekBarPreference.java
index f789e31..99ab9db 100644
--- a/core/java/android/preference/SeekBarPreference.java
+++ b/core/java/android/preference/SeekBarPreference.java
@@ -249,7 +249,7 @@
         }
 
         @SuppressWarnings("unused")
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/preference/TwoStatePreference.java b/core/java/android/preference/TwoStatePreference.java
index 454472a..bb771d7 100644
--- a/core/java/android/preference/TwoStatePreference.java
+++ b/core/java/android/preference/TwoStatePreference.java
@@ -278,7 +278,7 @@
             super(superState);
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/preference/VolumePreference.java b/core/java/android/preference/VolumePreference.java
index 92d848a..a2d5a23 100644
--- a/core/java/android/preference/VolumePreference.java
+++ b/core/java/android/preference/VolumePreference.java
@@ -236,7 +236,7 @@
             super(superState);
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/print/PageRange.java b/core/java/android/print/PageRange.java
index 2941283..1345038 100644
--- a/core/java/android/print/PageRange.java
+++ b/core/java/android/print/PageRange.java
@@ -162,7 +162,7 @@
         return builder.toString();
     }
 
-    public static final Parcelable.Creator<PageRange> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PageRange> CREATOR =
             new Creator<PageRange>() {
         @Override
         public PageRange createFromParcel(Parcel parcel) {
diff --git a/core/java/android/print/PrintAttributes.java b/core/java/android/print/PrintAttributes.java
index f0d9a0c..e607ced 100644
--- a/core/java/android/print/PrintAttributes.java
+++ b/core/java/android/print/PrintAttributes.java
@@ -1465,7 +1465,7 @@
         }
     }
 
-    public static final Parcelable.Creator<PrintAttributes> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PrintAttributes> CREATOR =
             new Creator<PrintAttributes>() {
         @Override
         public PrintAttributes createFromParcel(Parcel parcel) {
diff --git a/core/java/android/print/PrintDocumentInfo.java b/core/java/android/print/PrintDocumentInfo.java
index 55c902e..e10c507 100644
--- a/core/java/android/print/PrintDocumentInfo.java
+++ b/core/java/android/print/PrintDocumentInfo.java
@@ -367,7 +367,7 @@
         }
     }
 
-    public static final Parcelable.Creator<PrintDocumentInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PrintDocumentInfo> CREATOR =
             new Creator<PrintDocumentInfo>() {
         @Override
         public PrintDocumentInfo createFromParcel(Parcel parcel) {
diff --git a/core/java/android/print/PrintJobId.java b/core/java/android/print/PrintJobId.java
index 186ae9b..606cbb8 100644
--- a/core/java/android/print/PrintJobId.java
+++ b/core/java/android/print/PrintJobId.java
@@ -109,7 +109,7 @@
         return new PrintJobId(string);
     }
 
-    public static final Parcelable.Creator<PrintJobId> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PrintJobId> CREATOR =
             new Parcelable.Creator<PrintJobId>() {
         @Override
         public PrintJobId createFromParcel(Parcel parcel) {
diff --git a/core/java/android/print/PrintJobInfo.java b/core/java/android/print/PrintJobInfo.java
index 41f261b..25f383c 100644
--- a/core/java/android/print/PrintJobInfo.java
+++ b/core/java/android/print/PrintJobInfo.java
@@ -881,7 +881,7 @@
         }
     }
 
-    public static final Parcelable.Creator<PrintJobInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PrintJobInfo> CREATOR =
             new Creator<PrintJobInfo>() {
         @Override
         public PrintJobInfo createFromParcel(Parcel parcel) {
diff --git a/core/java/android/print/PrinterCapabilitiesInfo.java b/core/java/android/print/PrinterCapabilitiesInfo.java
index 01c23f6..e465d3b 100644
--- a/core/java/android/print/PrinterCapabilitiesInfo.java
+++ b/core/java/android/print/PrinterCapabilitiesInfo.java
@@ -646,7 +646,7 @@
         }
     }
 
-    public static final Parcelable.Creator<PrinterCapabilitiesInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PrinterCapabilitiesInfo> CREATOR =
             new Parcelable.Creator<PrinterCapabilitiesInfo>() {
         @Override
         public PrinterCapabilitiesInfo createFromParcel(Parcel parcel) {
diff --git a/core/java/android/print/PrinterId.java b/core/java/android/print/PrinterId.java
index 659e56f..42570c6 100644
--- a/core/java/android/print/PrinterId.java
+++ b/core/java/android/print/PrinterId.java
@@ -124,7 +124,7 @@
         return builder.toString();
     }
 
-    public static final Parcelable.Creator<PrinterId> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PrinterId> CREATOR =
             new Creator<PrinterId>() {
         @Override
         public PrinterId createFromParcel(Parcel parcel) {
diff --git a/core/java/android/print/PrinterInfo.java b/core/java/android/print/PrinterInfo.java
index e79cc65..4d5ccc0 100644
--- a/core/java/android/print/PrinterInfo.java
+++ b/core/java/android/print/PrinterInfo.java
@@ -563,7 +563,7 @@
         }
     }
 
-    public static final Parcelable.Creator<PrinterInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PrinterInfo> CREATOR =
             new Parcelable.Creator<PrinterInfo>() {
         @Override
         public PrinterInfo createFromParcel(Parcel parcel) {
diff --git a/core/java/android/printservice/PrintServiceInfo.java b/core/java/android/printservice/PrintServiceInfo.java
index 57f1229..565843e 100644
--- a/core/java/android/printservice/PrintServiceInfo.java
+++ b/core/java/android/printservice/PrintServiceInfo.java
@@ -328,7 +328,7 @@
         return builder.toString();
     }
 
-    public static final Parcelable.Creator<PrintServiceInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PrintServiceInfo> CREATOR =
             new Parcelable.Creator<PrintServiceInfo>() {
         @Override
         public PrintServiceInfo createFromParcel(Parcel parcel) {
diff --git a/core/java/android/printservice/recommendation/RecommendationInfo.java b/core/java/android/printservice/recommendation/RecommendationInfo.java
index a327956..156f182 100644
--- a/core/java/android/printservice/recommendation/RecommendationInfo.java
+++ b/core/java/android/printservice/recommendation/RecommendationInfo.java
@@ -182,7 +182,7 @@
      *
      * @see #RecommendationInfo(Parcel)
      */
-    public static final Creator<RecommendationInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<RecommendationInfo> CREATOR =
             new Creator<RecommendationInfo>() {
                 @Override
                 public RecommendationInfo createFromParcel(Parcel in) {
diff --git a/core/java/android/provider/CalendarContract.java b/core/java/android/provider/CalendarContract.java
index 3e5bd4b..5d34aa6 100644
--- a/core/java/android/provider/CalendarContract.java
+++ b/core/java/android/provider/CalendarContract.java
@@ -183,6 +183,22 @@
     public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
 
     /**
+     * The content:// style URL for the top-level cross-profile calendar uris.
+     * {@link android.database.ContentObserver} for this URL in the primary profile will be
+     * notified when there is a change in the managed profile calendar provider.
+     *
+     * @see Events#ENTERPRISE_CONTENT_URI
+     * @see Calendars#ENTERPRISE_CONTENT_URI
+     * @see Instances#ENTERPRISE_CONTENT_URI
+     * @see Instances#ENTERPRISE_CONTENT_BY_DAY_URI
+     * @see Instances#ENTERPRISE_CONTENT_SEARCH_URI
+     * @see Instances#ENTERPRISE_CONTENT_SEARCH_BY_DAY_URI
+     * @hide
+     */
+    public static final Uri ENTERPRISE_CONTENT_URI = Uri.parse(
+            "content://" + AUTHORITY + "/enterprise");
+
+    /**
      * An optional insert, update or delete URI parameter that allows the caller
      * to specify that it is a sync adapter. The default value is false. If set
      * to true, the modified row is not marked as "dirty" (needs to be synced)
diff --git a/core/java/android/provider/DeviceConfig.java b/core/java/android/provider/DeviceConfig.java
index 868a36b..010e3b1 100644
--- a/core/java/android/provider/DeviceConfig.java
+++ b/core/java/android/provider/DeviceConfig.java
@@ -55,6 +55,15 @@
     public static final Uri CONTENT_URI = Uri.parse("content://" + Settings.AUTHORITY + "/config");
 
     /**
+     * Namespace for activity manager related features. These features will be applied
+     * immediately upon change.
+     *
+     * @hide
+     */
+    @SystemApi
+    public static final String NAMESPACE_ACTIVITY_MANAGER = "activity_manager";
+
+    /**
      * Namespace for all Game Driver features.
      *
      * @hide
@@ -100,27 +109,12 @@
     public static final String NAMESPACE_NETD_NATIVE = "netd_native";
 
     /**
-     * Namespace for features related to the ExtServices Notification Assistant.
-     * These features are applied immediately.
+     * Namespace for System UI related features.
      *
      * @hide
      */
     @SystemApi
-    public interface NotificationAssistant {
-        String NAMESPACE = "notification_assistant";
-        /**
-         * Whether the Notification Assistant should generate replies for notifications.
-         */
-        String GENERATE_REPLIES = "generate_replies";
-        /**
-         * Whether the Notification Assistant should generate contextual actions for notifications.
-         */
-        String GENERATE_ACTIONS = "generate_actions";
-
-        String MAX_MESSAGES_TO_EXTRACT = "max_messages_to_extract";
-
-        String MAX_SUGGESTIONS = "max_suggestions";
-    }
+    public static final String NAMESPACE_SYSTEMUI = "systemui";
 
     /**
      * Namespace for all runtime related features.
@@ -197,6 +191,7 @@
      */
     @SystemApi
     public interface MediaNative {
+        /** The flag namespace for media native features. */
         String NAMESPACE = "media_native";
     }
 
@@ -295,35 +290,6 @@
     }
 
     /**
-     * Namespace for activity manager related features. These features will be applied
-     * immediately upon change.
-     *
-     * @hide
-     */
-    @SystemApi
-    public interface ActivityManager {
-        String NAMESPACE = "activity_manager";
-
-        /**
-         * App compaction flags. See {@link com.android.server.am.AppCompactor}.
-         */
-        String KEY_USE_COMPACTION = "use_compaction";
-        String KEY_COMPACT_ACTION_1 = "compact_action_1";
-        String KEY_COMPACT_ACTION_2 = "compact_action_2";
-        String KEY_COMPACT_THROTTLE_1 = "compact_throttle_1";
-        String KEY_COMPACT_THROTTLE_2 = "compact_throttle_2";
-        String KEY_COMPACT_THROTTLE_3 = "compact_throttle_3";
-        String KEY_COMPACT_THROTTLE_4 = "compact_throttle_4";
-        String KEY_COMPACT_STATSD_SAMPLE_RATE = "compact_statsd_sample_rate";
-
-        /**
-         * Maximum number of cached processes. See
-         * {@link com.android.server.am.ActivityManagerConstants}.
-         */
-        String KEY_MAX_CACHED_PROCESSES = "max_cached_processes";
-    }
-
-    /**
      * Namespace for {@link AttentionManagerService} related features.
      *
      * @hide
@@ -426,6 +392,110 @@
     }
 
     /**
+     * Look up the String value of a property for a particular namespace.
+     *
+     * @param namespace    The namespace containing the property to look up.
+     * @param name         The name of the property to look up.
+     * @param defaultValue The value to return if the property does not exist or has no non-null
+     *                     value.
+     * @return the corresponding value, or defaultValue if none exists.
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    @RequiresPermission(READ_DEVICE_CONFIG)
+    public static String getString(String namespace, String name, String defaultValue) {
+        String value = getProperty(namespace, name);
+        return value != null ? value : defaultValue;
+    }
+
+    /**
+     * Look up the boolean value of a property for a particular namespace.
+     *
+     * @param namespace The namespace containing the property to look up.
+     * @param name      The name of the property to look up.
+     * @param defaultValue The value to return if the property does not exist or has no non-null
+     *                     value.
+     * @return the corresponding value, or defaultValue if none exists.
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    @RequiresPermission(READ_DEVICE_CONFIG)
+    public static boolean getBoolean(String namespace, String name, boolean defaultValue) {
+        String value = getProperty(namespace, name);
+        return value != null ? Boolean.parseBoolean(value) : defaultValue;
+    }
+
+    /**
+     * Look up the int value of a property for a particular namespace.
+     *
+     * @param namespace The namespace containing the property to look up.
+     * @param name      The name of the property to look up.
+     * @param defaultValue The value to return if the property does not exist, has no non-null
+     *                     value, or fails to parse into an int.
+     * @return the corresponding value, or defaultValue if either none exists or it does not parse.
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    @RequiresPermission(READ_DEVICE_CONFIG)
+    public static int getInt(String namespace, String name, int defaultValue) {
+        String value = getProperty(namespace, name);
+        try {
+            return Integer.parseInt(value);
+        } catch (NumberFormatException e) {
+            return defaultValue;
+        }
+    }
+
+    /**
+     * Look up the long value of a property for a particular namespace.
+     *
+     * @param namespace The namespace containing the property to look up.
+     * @param name      The name of the property to look up.
+     * @param defaultValue The value to return if the property does not exist, has no non-null
+     *                     value, or fails to parse into a long.
+     * @return the corresponding value, or defaultValue if either none exists or it does not parse.
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    @RequiresPermission(READ_DEVICE_CONFIG)
+    public static long getLong(String namespace, String name, long defaultValue) {
+        String value = getProperty(namespace, name);
+        try {
+            return Long.parseLong(value);
+        } catch (NumberFormatException e) {
+            return defaultValue;
+        }
+    }
+
+    /**
+     * Look up the float value of a property for a particular namespace.
+     *
+     * @param namespace The namespace containing the property to look up.
+     * @param name      The name of the property to look up.
+     * @param defaultValue The value to return if the property does not exist, has no non-null
+     *                     value, or fails to parse into a float.
+     * @return the corresponding value, or defaultValue if either none exists or it does not parse.
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    @RequiresPermission(READ_DEVICE_CONFIG)
+    public static float getFloat(String namespace, String name, float defaultValue) {
+        String value = getProperty(namespace, name);
+        try {
+            return Float.parseFloat(value);
+        } catch (NumberFormatException e) {
+            return defaultValue;
+        } catch (NullPointerException e) {
+            return defaultValue;
+        }
+    }
+
+    /**
      * Create a new property with the the provided name and value in the provided namespace, or
      * update the value of such a property if it already exists. The same name can exist in multiple
      * namespaces and might have different values in any or all namespaces.
diff --git a/core/java/android/provider/DocumentsContract.java b/core/java/android/provider/DocumentsContract.java
index d282967..49567b2 100644
--- a/core/java/android/provider/DocumentsContract.java
+++ b/core/java/android/provider/DocumentsContract.java
@@ -1794,7 +1794,7 @@
             return 0;
         }
 
-        public static final Creator<Path> CREATOR = new Creator<Path>() {
+        public static final @android.annotation.NonNull Creator<Path> CREATOR = new Creator<Path>() {
             @Override
             public Path createFromParcel(Parcel in) {
                 final String rootId = in.readString();
diff --git a/core/java/android/provider/MediaStore.java b/core/java/android/provider/MediaStore.java
index 643307e..a34ac70 100644
--- a/core/java/android/provider/MediaStore.java
+++ b/core/java/android/provider/MediaStore.java
@@ -529,7 +529,6 @@
      *
      * @see MediaColumns#IS_PENDING
      * @see MediaStore#setIncludePending(Uri)
-     * @see MediaStore#createPending(Context, PendingParams)
      */
     public static @NonNull Uri setIncludePending(@NonNull Uri uri) {
         return setIncludePending(uri.buildUpon()).build();
@@ -586,7 +585,9 @@
      * @see MediaColumns#IS_PENDING
      * @see MediaStore#setIncludePending(Uri)
      * @see MediaStore#createPending(Context, PendingParams)
+     * @removed
      */
+    @Deprecated
     public static @NonNull Uri createPending(@NonNull Context context,
             @NonNull PendingParams params) {
         return context.getContentResolver().insert(params.insertUri, params.insertValues);
@@ -599,14 +600,19 @@
      *
      * @param uri token which was previously returned from
      *            {@link #createPending(Context, PendingParams)}.
+     * @removed
      */
+    @Deprecated
     public static @NonNull PendingSession openPending(@NonNull Context context, @NonNull Uri uri) {
         return new PendingSession(context, uri);
     }
 
     /**
      * Parameters that describe a pending media item.
+     *
+     * @removed
      */
+    @Deprecated
     public static class PendingParams {
         /** {@hide} */
         public final Uri insertUri;
@@ -711,7 +717,10 @@
      * expected to have a short lifetime, and owners should either
      * {@link PendingSession#publish()} or {@link PendingSession#abandon()} a
      * pending item within a few hours after first creating it.
+     *
+     * @removed
      */
+    @Deprecated
     public static class PendingSession implements AutoCloseable {
         /** {@hide} */
         private final Context mContext;
@@ -976,9 +985,7 @@
          * Flag indicating if a media item is pending, and still being inserted
          * by its owner.
          *
-         * @see MediaColumns#IS_PENDING
          * @see MediaStore#setIncludePending(Uri)
-         * @see MediaStore#createPending(Context, PendingParams)
          */
         @Column(Cursor.FIELD_TYPE_INTEGER)
         public static final String IS_PENDING = "is_pending";
@@ -998,12 +1005,8 @@
 
         /**
          * The time the media item should be considered expired. Typically only
-         * meaningful in the context of {@link #IS_PENDING} or
-         * {@link #IS_TRASHED}.
-         *
-         * @removed
+         * meaningful in the context of {@link #IS_PENDING}.
          */
-        @Deprecated
         @CurrentTimeSecondsLong
         @Column(Cursor.FIELD_TYPE_INTEGER)
         public static final String DATE_EXPIRES = "date_expires";
@@ -1030,8 +1033,6 @@
         /**
          * The primary directory name this media exists under. The value may be
          * {@code NULL} if the media doesn't have a primary directory name.
-         *
-         * @see PendingParams#setPrimaryDirectory(String)
          */
         @Column(Cursor.FIELD_TYPE_STRING)
         public static final String PRIMARY_DIRECTORY = "primary_directory";
@@ -1039,8 +1040,6 @@
         /**
          * The secondary directory name this media exists under. The value may
          * be {@code NULL} if the media doesn't have a secondary directory name.
-         *
-         * @see PendingParams#setSecondaryDirectory(String)
          */
         @Column(Cursor.FIELD_TYPE_STRING)
         public static final String SECONDARY_DIRECTORY = "secondary_directory";
@@ -1292,12 +1291,7 @@
     }
 
     /**
-     * Container for downloaded files.
-     *
-     * <p>
-     * Querying for downloads from this table will return files contributed via
-     * {@link PendingSession} and also ones which were downloaded using
-     * {@link android.app.DownloadManager} APIs.
+     * Collection of downloaded items.
      */
     public static final class Downloads implements DownloadColumns {
         private Downloads() {}
@@ -1305,6 +1299,7 @@
         /**
          * The content:// style URI for the internal storage.
          */
+        @NonNull
         public static final Uri INTERNAL_CONTENT_URI =
                 getContentUri("internal");
 
@@ -1312,6 +1307,7 @@
          * The content:// style URI for the "primary" external storage
          * volume.
          */
+        @NonNull
         public static final Uri EXTERNAL_CONTENT_URI =
                 getContentUri("external");
 
@@ -1336,13 +1332,13 @@
          * @param volumeName the name of the volume to get the URI for
          * @return the URI to the image media table on the given volume
          */
-        public static Uri getContentUri(String volumeName) {
+        public static @NonNull Uri getContentUri(@NonNull String volumeName) {
             return AUTHORITY_URI.buildUpon().appendPath(volumeName)
                     .appendPath("downloads").build();
         }
 
         /** @hide */
-        public static Uri getContentUriForPath(@NonNull String path) {
+        public static @NonNull Uri getContentUriForPath(@NonNull String path) {
             return getContentUri(getVolumeName(new File(path)));
         }
 
@@ -1620,9 +1616,9 @@
              * @param name The name of the image
              * @param description The description of the image
              * @return The URL to the newly created image
-             * @deprecated inserting of images should be performed through
-             *             {@link MediaStore#createPending(Context, PendingParams)},
-             *             which offers richer control over lifecycle.
+             * @deprecated inserting of images should be performed using
+             *             {@link MediaColumns#IS_PENDING}, which offers richer
+             *             control over lifecycle.
              */
             @Deprecated
             public static final String insertImage(ContentResolver cr, String imagePath,
@@ -1651,9 +1647,9 @@
              * @param description The description of the image
              * @return The URL to the newly created image, or <code>null</code> if the image failed to be stored
              *              for any reason.
-             * @deprecated inserting of images should be performed through
-             *             {@link MediaStore#createPending(Context, PendingParams)},
-             *             which offers richer control over lifecycle.
+             * @deprecated inserting of images should be performed using
+             *             {@link MediaColumns#IS_PENDING}, which offers richer
+             *             control over lifecycle.
              */
             @Deprecated
             public static final String insertImage(ContentResolver cr, Bitmap source,
@@ -3180,7 +3176,7 @@
      * {@link MediaStore.Images.Media#getContentUri(String)} to query media at
      * that location.
      */
-    public static @NonNull Set<String> getAllVolumeNames(Context context) {
+    public static @NonNull Set<String> getAllVolumeNames(@NonNull Context context) {
         final StorageManager sm = context.getSystemService(StorageManager.class);
         final Set<String> volumeNames = new ArraySet<>();
         volumeNames.add(VOLUME_INTERNAL);
@@ -3354,7 +3350,7 @@
      *         if no equivalent was found.
      * @see #getMediaUri(Context, Uri)
      */
-    public static Uri getDocumentUri(Context context, Uri mediaUri) {
+    public static @Nullable Uri getDocumentUri(@NonNull Context context, @NonNull Uri mediaUri) {
         final ContentResolver resolver = context.getContentResolver();
         final List<UriPermission> uriPermissions = resolver.getPersistedUriPermissions();
 
@@ -3384,7 +3380,7 @@
      *         equivalent was found.
      * @see #getDocumentUri(Context, Uri)
      */
-    public static Uri getMediaUri(Context context, Uri documentUri) {
+    public static @Nullable Uri getMediaUri(@NonNull Context context, @NonNull Uri documentUri) {
         final ContentResolver resolver = context.getContentResolver();
         final List<UriPermission> uriPermissions = resolver.getPersistedUriPermissions();
 
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 1588718..d395a9f 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -7483,6 +7483,7 @@
          * @hide
          */
         @SystemApi
+        @TestApi
         public static final String DOZE_ALWAYS_ON = "doze_always_on";
 
         private static final Validator DOZE_ALWAYS_ON_VALIDATOR = BOOLEAN_VALIDATOR;
@@ -9044,7 +9045,6 @@
          * Whether applying ramping ringer on incoming phone call ringtone.
          * <p>1 = apply ramping ringer
          * <p>0 = do not apply ramping ringer
-         * @hide
          */
         public static final String APPLY_RAMPING_RINGER = "apply_ramping_ringer";
 
@@ -11417,7 +11417,7 @@
         /**
          * Feature flag to enable or disable the activity starts logging feature.
          * Type: int (0 for false, 1 for true)
-         * Default: 0
+         * Default: 1
          * @hide
          */
         public static final String ACTIVITY_STARTS_LOGGING_ENABLED
@@ -11523,6 +11523,7 @@
          * @hide
          * @see com.android.server.power.batterysaver.BatterySaverPolicy
          */
+        @TestApi
         public static final String BATTERY_SAVER_CONSTANTS = "battery_saver_constants";
 
         /**
@@ -11946,6 +11947,7 @@
          * bcast_deferral               (long)
          * bcast_deferral_decay_factor  (float)
          * bcast_deferral_floor         (long)
+         * bcast_allow_bg_activity_start_timeout    (long)
          * </pre>
          *
          * @hide
@@ -13374,8 +13376,8 @@
                 "hidden_api_blacklist_exemptions";
 
         /**
-         * Sampling rate for hidden API access event logs, as an integer in the range 0 to 0x10000
-         * inclusive.
+         * Sampling rate for hidden API access event logs with libmetricslogger, as an integer in
+         * the range 0 to 0x10000 inclusive.
          *
          * @hide
          */
@@ -13383,6 +13385,15 @@
                 "hidden_api_access_log_sampling_rate";
 
         /**
+         * Sampling rate for hidden API access event logging with statslog, as an integer in the
+         * range 0 to 0x10000 inclusive.
+         *
+         * @hide
+         */
+        public static final String HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE =
+                "hidden_api_access_statslog_sampling_rate";
+
+        /**
          * Hidden API enforcement policy for apps.
          *
          * Values correspond to @{@link
@@ -14199,10 +14210,24 @@
          * Configuration flags for SQLite Compatibility WAL. Encoded as a key-value list, separated
          * by commas. E.g.: compatibility_wal_supported=true, wal_syncmode=OFF
          *
-         * Supported keys:
-         * compatibility_wal_supported      (boolean)
-         * wal_syncmode       (String)
-         * truncate_size      (int)
+         * Supported keys:<br/>
+         * <li>
+         * <ul> {@code legacy_compatibility_wal_enabled} : A {code boolean} flag that determines
+         * whether or not "compatibility WAL" mode is enabled by default. This is a legacy flag
+         * and is honoured on Android Q and higher. This flag will be removed in a future release.
+         * </ul>
+         * <ul> {@code wal_syncmode} : A {@code String} representing the synchronization mode to use
+         * when WAL is enabled, either via {@code legacy_compatibility_wal_enabled} or using the
+         * obsolete {@code compatibility_wal_supported} flag.
+         * </ul>
+         * <ul> {@code truncate_size} : A {@code int} flag that specifies the truncate size of the
+         * WAL journal.
+         * </ul>
+         * <ul> {@code compatibility_wal_supported} : A {code boolean} flag that specifies whether
+         * the legacy "compatibility WAL" mode is enabled by default. This flag is obsolete and is
+         * only supported on Android Pie.
+         * </ul>
+         * </li>
          *
          * @hide
          */
diff --git a/core/java/android/security/KeystoreArguments.java b/core/java/android/security/KeystoreArguments.java
index 7d85ca7..e634234 100644
--- a/core/java/android/security/KeystoreArguments.java
+++ b/core/java/android/security/KeystoreArguments.java
@@ -29,7 +29,7 @@
     public byte[][] args;
 
     @UnsupportedAppUsage
-    public static final Parcelable.Creator<KeystoreArguments> CREATOR = new
+    public static final @android.annotation.NonNull Parcelable.Creator<KeystoreArguments> CREATOR = new
             Parcelable.Creator<KeystoreArguments>() {
                 public KeystoreArguments createFromParcel(Parcel in) {
                     return new KeystoreArguments(in);
diff --git a/core/java/android/security/keymaster/ExportResult.java b/core/java/android/security/keymaster/ExportResult.java
index 1ab79fb..1be5ae9 100644
--- a/core/java/android/security/keymaster/ExportResult.java
+++ b/core/java/android/security/keymaster/ExportResult.java
@@ -34,7 +34,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Parcelable.Creator<ExportResult> CREATOR = new
+    public static final @android.annotation.NonNull Parcelable.Creator<ExportResult> CREATOR = new
             Parcelable.Creator<ExportResult>() {
                 public ExportResult createFromParcel(Parcel in) {
                     return new ExportResult(in);
diff --git a/core/java/android/security/keymaster/KeyAttestationApplicationId.java b/core/java/android/security/keymaster/KeyAttestationApplicationId.java
index 8e585f4b..670f30e1b 100644
--- a/core/java/android/security/keymaster/KeyAttestationApplicationId.java
+++ b/core/java/android/security/keymaster/KeyAttestationApplicationId.java
@@ -55,7 +55,7 @@
         dest.writeTypedArray(mAttestationPackageInfos, flags);
     }
 
-    public static final Parcelable.Creator<KeyAttestationApplicationId> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<KeyAttestationApplicationId> CREATOR
             = new Parcelable.Creator<KeyAttestationApplicationId>() {
         @Override
         public KeyAttestationApplicationId createFromParcel(Parcel source) {
diff --git a/core/java/android/security/keymaster/KeyAttestationPackageInfo.java b/core/java/android/security/keymaster/KeyAttestationPackageInfo.java
index a93d1e1..c0b8d8d 100644
--- a/core/java/android/security/keymaster/KeyAttestationPackageInfo.java
+++ b/core/java/android/security/keymaster/KeyAttestationPackageInfo.java
@@ -74,7 +74,7 @@
         dest.writeTypedArray(mPackageSignatures, flags);
     }
 
-    public static final Parcelable.Creator<KeyAttestationPackageInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<KeyAttestationPackageInfo> CREATOR
             = new Parcelable.Creator<KeyAttestationPackageInfo>() {
         @Override
         public KeyAttestationPackageInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/security/keymaster/KeyCharacteristics.java b/core/java/android/security/keymaster/KeyCharacteristics.java
index a4fe75d..2eb2cef 100644
--- a/core/java/android/security/keymaster/KeyCharacteristics.java
+++ b/core/java/android/security/keymaster/KeyCharacteristics.java
@@ -32,7 +32,7 @@
     public KeymasterArguments swEnforced;
     public KeymasterArguments hwEnforced;
 
-    public static final Parcelable.Creator<KeyCharacteristics> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<KeyCharacteristics> CREATOR =
             new Parcelable.Creator<KeyCharacteristics>() {
                 @Override
                 public KeyCharacteristics createFromParcel(Parcel in) {
diff --git a/core/java/android/security/keymaster/KeymasterArgument.java b/core/java/android/security/keymaster/KeymasterArgument.java
index 6ad53a4..8b86d41 100644
--- a/core/java/android/security/keymaster/KeymasterArgument.java
+++ b/core/java/android/security/keymaster/KeymasterArgument.java
@@ -30,7 +30,7 @@
 abstract class KeymasterArgument implements Parcelable {
     public final int tag;
 
-    public static final Parcelable.Creator<KeymasterArgument> CREATOR = new
+    public static final @android.annotation.NonNull Parcelable.Creator<KeymasterArgument> CREATOR = new
             Parcelable.Creator<KeymasterArgument>() {
                 @Override
                 public KeymasterArgument createFromParcel(Parcel in) {
diff --git a/core/java/android/security/keymaster/KeymasterArguments.java b/core/java/android/security/keymaster/KeymasterArguments.java
index 5aa0f91..d2dbdec 100644
--- a/core/java/android/security/keymaster/KeymasterArguments.java
+++ b/core/java/android/security/keymaster/KeymasterArguments.java
@@ -42,7 +42,7 @@
     private List<KeymasterArgument> mArguments;
 
     @UnsupportedAppUsage
-    public static final Parcelable.Creator<KeymasterArguments> CREATOR = new
+    public static final @android.annotation.NonNull Parcelable.Creator<KeymasterArguments> CREATOR = new
             Parcelable.Creator<KeymasterArguments>() {
                 @Override
                 public KeymasterArguments createFromParcel(Parcel in) {
diff --git a/core/java/android/security/keymaster/KeymasterBlob.java b/core/java/android/security/keymaster/KeymasterBlob.java
index 0659a22..6a2024f 100644
--- a/core/java/android/security/keymaster/KeymasterBlob.java
+++ b/core/java/android/security/keymaster/KeymasterBlob.java
@@ -30,7 +30,7 @@
         this.blob = blob;
     }
     @UnsupportedAppUsage
-    public static final Parcelable.Creator<KeymasterBlob> CREATOR = new
+    public static final @android.annotation.NonNull Parcelable.Creator<KeymasterBlob> CREATOR = new
             Parcelable.Creator<KeymasterBlob>() {
                 public KeymasterBlob createFromParcel(Parcel in) {
                     return new KeymasterBlob(in);
diff --git a/core/java/android/security/keymaster/KeymasterCertificateChain.java b/core/java/android/security/keymaster/KeymasterCertificateChain.java
index 00a1a1c..4bad462 100644
--- a/core/java/android/security/keymaster/KeymasterCertificateChain.java
+++ b/core/java/android/security/keymaster/KeymasterCertificateChain.java
@@ -32,7 +32,7 @@
 
     private List<byte[]> mCertificates;
 
-    public static final Parcelable.Creator<KeymasterCertificateChain> CREATOR = new
+    public static final @android.annotation.NonNull Parcelable.Creator<KeymasterCertificateChain> CREATOR = new
             Parcelable.Creator<KeymasterCertificateChain>() {
                 public KeymasterCertificateChain createFromParcel(Parcel in) {
                     return new KeymasterCertificateChain(in);
diff --git a/core/java/android/security/keymaster/OperationResult.java b/core/java/android/security/keymaster/OperationResult.java
index bc4f360..c278eb3 100644
--- a/core/java/android/security/keymaster/OperationResult.java
+++ b/core/java/android/security/keymaster/OperationResult.java
@@ -35,7 +35,7 @@
     public final KeymasterArguments outParams;
 
     @UnsupportedAppUsage
-    public static final Parcelable.Creator<OperationResult> CREATOR = new
+    public static final @android.annotation.NonNull Parcelable.Creator<OperationResult> CREATOR = new
             Parcelable.Creator<OperationResult>() {
                 @Override
                 public OperationResult createFromParcel(Parcel in) {
diff --git a/core/java/android/security/keystore/recovery/KeyChainProtectionParams.java b/core/java/android/security/keystore/recovery/KeyChainProtectionParams.java
index 4af1af5..8f6b6ec 100644
--- a/core/java/android/security/keystore/recovery/KeyChainProtectionParams.java
+++ b/core/java/android/security/keystore/recovery/KeyChainProtectionParams.java
@@ -236,7 +236,7 @@
         Arrays.fill(mSecret, (byte) 0);
     }
 
-    public static final Parcelable.Creator<KeyChainProtectionParams> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<KeyChainProtectionParams> CREATOR =
             new Parcelable.Creator<KeyChainProtectionParams>() {
         public KeyChainProtectionParams createFromParcel(Parcel in) {
             return new KeyChainProtectionParams(in);
diff --git a/core/java/android/security/keystore/recovery/KeyChainSnapshot.java b/core/java/android/security/keystore/recovery/KeyChainSnapshot.java
index 035b226..18517aa 100644
--- a/core/java/android/security/keystore/recovery/KeyChainSnapshot.java
+++ b/core/java/android/security/keystore/recovery/KeyChainSnapshot.java
@@ -147,7 +147,7 @@
         return mEncryptedRecoveryKeyBlob;
     }
 
-    public static final Creator<KeyChainSnapshot> CREATOR =
+    public static final @android.annotation.NonNull Creator<KeyChainSnapshot> CREATOR =
             new Creator<KeyChainSnapshot>() {
         public KeyChainSnapshot createFromParcel(Parcel in) {
             return new KeyChainSnapshot(in);
diff --git a/core/java/android/security/keystore/recovery/KeyDerivationParams.java b/core/java/android/security/keystore/recovery/KeyDerivationParams.java
index 5165f0c..6d1533e 100644
--- a/core/java/android/security/keystore/recovery/KeyDerivationParams.java
+++ b/core/java/android/security/keystore/recovery/KeyDerivationParams.java
@@ -140,7 +140,7 @@
         return mMemoryDifficulty;
     }
 
-    public static final Parcelable.Creator<KeyDerivationParams> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<KeyDerivationParams> CREATOR =
             new Parcelable.Creator<KeyDerivationParams>() {
         public KeyDerivationParams createFromParcel(Parcel in) {
                 return new KeyDerivationParams(in);
diff --git a/core/java/android/security/keystore/recovery/RecoveryCertPath.java b/core/java/android/security/keystore/recovery/RecoveryCertPath.java
index f3604fe..04e965f 100644
--- a/core/java/android/security/keystore/recovery/RecoveryCertPath.java
+++ b/core/java/android/security/keystore/recovery/RecoveryCertPath.java
@@ -74,7 +74,7 @@
         mEncodedCertPath = in.createByteArray();
     }
 
-    public static final Parcelable.Creator<RecoveryCertPath> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<RecoveryCertPath> CREATOR =
             new Parcelable.Creator<RecoveryCertPath>() {
         public RecoveryCertPath createFromParcel(Parcel in) {
             return new RecoveryCertPath(in);
diff --git a/core/java/android/security/keystore/recovery/WrappedApplicationKey.java b/core/java/android/security/keystore/recovery/WrappedApplicationKey.java
index dbfd655..c6e6272 100644
--- a/core/java/android/security/keystore/recovery/WrappedApplicationKey.java
+++ b/core/java/android/security/keystore/recovery/WrappedApplicationKey.java
@@ -143,7 +143,7 @@
         return mMetadata;
     }
 
-    public static final Parcelable.Creator<WrappedApplicationKey> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<WrappedApplicationKey> CREATOR =
             new Parcelable.Creator<WrappedApplicationKey>() {
                 public WrappedApplicationKey createFromParcel(Parcel in) {
                     return new WrappedApplicationKey(in);
diff --git a/core/java/android/service/autofill/AutofillFieldClassificationService.java b/core/java/android/service/autofill/AutofillFieldClassificationService.java
index 2612917..5f64755 100644
--- a/core/java/android/service/autofill/AutofillFieldClassificationService.java
+++ b/core/java/android/service/autofill/AutofillFieldClassificationService.java
@@ -349,7 +349,7 @@
             }
         }
 
-        public static final Creator<Scores> CREATOR = new Creator<Scores>() {
+        public static final @android.annotation.NonNull Creator<Scores> CREATOR = new Creator<Scores>() {
             @Override
             public Scores createFromParcel(Parcel parcel) {
                 return new Scores(parcel);
diff --git a/core/java/android/service/autofill/BatchUpdates.java b/core/java/android/service/autofill/BatchUpdates.java
index 2ba0376..e0b1c2f 100644
--- a/core/java/android/service/autofill/BatchUpdates.java
+++ b/core/java/android/service/autofill/BatchUpdates.java
@@ -187,7 +187,7 @@
         }
         dest.writeParcelable(mUpdates, flags);
     }
-    public static final Parcelable.Creator<BatchUpdates> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BatchUpdates> CREATOR =
             new Parcelable.Creator<BatchUpdates>() {
         @Override
         public BatchUpdates createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/CharSequenceTransformation.java b/core/java/android/service/autofill/CharSequenceTransformation.java
index 271707a..e3e8844 100644
--- a/core/java/android/service/autofill/CharSequenceTransformation.java
+++ b/core/java/android/service/autofill/CharSequenceTransformation.java
@@ -208,7 +208,7 @@
         parcel.writeStringArray(substs);
     }
 
-    public static final Parcelable.Creator<CharSequenceTransformation> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CharSequenceTransformation> CREATOR =
             new Parcelable.Creator<CharSequenceTransformation>() {
         @Override
         public CharSequenceTransformation createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/CompositeUserData.java b/core/java/android/service/autofill/CompositeUserData.java
index 2df4ddf..c7dc15a 100644
--- a/core/java/android/service/autofill/CompositeUserData.java
+++ b/core/java/android/service/autofill/CompositeUserData.java
@@ -191,7 +191,7 @@
         parcel.writeParcelable(mPackageUserData, 0);
     }
 
-    public static final Parcelable.Creator<CompositeUserData> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CompositeUserData> CREATOR =
             new Parcelable.Creator<CompositeUserData>() {
                 @Override
                 public CompositeUserData createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/CustomDescription.java b/core/java/android/service/autofill/CustomDescription.java
index fdbb1c2..ea87f4f 100644
--- a/core/java/android/service/autofill/CustomDescription.java
+++ b/core/java/android/service/autofill/CustomDescription.java
@@ -425,7 +425,7 @@
             dest.writeParcelableArray(values, flags);
         }
     }
-    public static final Parcelable.Creator<CustomDescription> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CustomDescription> CREATOR =
             new Parcelable.Creator<CustomDescription>() {
         @Override
         public CustomDescription createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/Dataset.java b/core/java/android/service/autofill/Dataset.java
index f8408be..d53e62a 100644
--- a/core/java/android/service/autofill/Dataset.java
+++ b/core/java/android/service/autofill/Dataset.java
@@ -500,7 +500,7 @@
         parcel.writeString(mId);
     }
 
-    public static final Creator<Dataset> CREATOR = new Creator<Dataset>() {
+    public static final @android.annotation.NonNull Creator<Dataset> CREATOR = new Creator<Dataset>() {
         @Override
         public Dataset createFromParcel(Parcel parcel) {
             // Always go through the builder to ensure the data ingested by
@@ -572,7 +572,7 @@
         }
 
         @SuppressWarnings("hiding")
-        public static final Creator<DatasetFieldFilter> CREATOR =
+        public static final @android.annotation.NonNull Creator<DatasetFieldFilter> CREATOR =
                 new Creator<DatasetFieldFilter>() {
 
             @Override
diff --git a/core/java/android/service/autofill/DateTransformation.java b/core/java/android/service/autofill/DateTransformation.java
index ec24a09..338ba74 100644
--- a/core/java/android/service/autofill/DateTransformation.java
+++ b/core/java/android/service/autofill/DateTransformation.java
@@ -111,7 +111,7 @@
         parcel.writeSerializable(mDateFormat);
     }
 
-    public static final Parcelable.Creator<DateTransformation> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<DateTransformation> CREATOR =
             new Parcelable.Creator<DateTransformation>() {
         @Override
         public DateTransformation createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/DateValueSanitizer.java b/core/java/android/service/autofill/DateValueSanitizer.java
index 4f797f4..707bab1 100644
--- a/core/java/android/service/autofill/DateValueSanitizer.java
+++ b/core/java/android/service/autofill/DateValueSanitizer.java
@@ -108,7 +108,7 @@
         parcel.writeSerializable(mDateFormat);
     }
 
-    public static final Parcelable.Creator<DateValueSanitizer> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<DateValueSanitizer> CREATOR =
             new Parcelable.Creator<DateValueSanitizer>() {
         @Override
         public DateValueSanitizer createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/FillContext.java b/core/java/android/service/autofill/FillContext.java
index 535c00b..70f434c 100644
--- a/core/java/android/service/autofill/FillContext.java
+++ b/core/java/android/service/autofill/FillContext.java
@@ -49,6 +49,7 @@
 public final class FillContext implements Parcelable {
     private final int mRequestId;
     private final @NonNull AssistStructure mStructure;
+    private final @NonNull AutofillId mFocusedId;
 
     /**
      * Lookup table AutofillId->ViewNode to speed up {@link #findViewNodesByAutofillIds}
@@ -58,13 +59,15 @@
 
 
     /** @hide */
-    public FillContext(int requestId, @NonNull AssistStructure structure) {
+    public FillContext(int requestId, @NonNull AssistStructure structure,
+            @NonNull AutofillId autofillId) {
         mRequestId = requestId;
         mStructure = structure;
+        mFocusedId = autofillId;
     }
 
     private FillContext(Parcel parcel) {
-        this(parcel.readInt(), parcel.readParcelable(null));
+        this(parcel.readInt(), parcel.readParcelable(null), parcel.readParcelable(null));
     }
 
     /**
@@ -82,15 +85,24 @@
     /**
      * @return The screen content.
      */
+    @NonNull
     public AssistStructure getStructure() {
         return mStructure;
     }
 
+    /**
+     * @return the AutofillId of the view that triggered autofill.
+     */
+    @NonNull
+    public AutofillId getFocusedId() {
+        return mFocusedId;
+    }
+
     @Override
     public String toString() {
         if (!sDebug)  return super.toString();
 
-        return "FillContext [reqId=" + mRequestId + "]";
+        return "FillContext [reqId=" + mRequestId + ", focusedId=" + mFocusedId + "]";
     }
 
     @Override
@@ -102,6 +114,7 @@
     public void writeToParcel(Parcel parcel, int flags) {
         parcel.writeInt(mRequestId);
         parcel.writeParcelable(mStructure, flags);
+        parcel.writeParcelable(mFocusedId, flags);
     }
 
     /**
@@ -177,14 +190,16 @@
         return foundNodes;
     }
 
-    public static final Parcelable.Creator<FillContext> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<FillContext> CREATOR =
             new Parcelable.Creator<FillContext>() {
         @Override
+        @NonNull
         public FillContext createFromParcel(Parcel parcel) {
             return new FillContext(parcel);
         }
 
         @Override
+        @NonNull
         public FillContext[] newArray(int size) {
             return new FillContext[size];
         }
diff --git a/core/java/android/service/autofill/FillEventHistory.java b/core/java/android/service/autofill/FillEventHistory.java
index 6e5bacf..c65e773 100644
--- a/core/java/android/service/autofill/FillEventHistory.java
+++ b/core/java/android/service/autofill/FillEventHistory.java
@@ -517,7 +517,7 @@
         }
     }
 
-    public static final Parcelable.Creator<FillEventHistory> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<FillEventHistory> CREATOR =
             new Parcelable.Creator<FillEventHistory>() {
                 @Override
                 public FillEventHistory createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/FillRequest.java b/core/java/android/service/autofill/FillRequest.java
index 1d0c987..66864c6 100644
--- a/core/java/android/service/autofill/FillRequest.java
+++ b/core/java/android/service/autofill/FillRequest.java
@@ -71,6 +71,14 @@
      */
     public static final int FLAG_COMPATIBILITY_MODE_REQUEST = 0x2;
 
+    // Private flags below start from the highest-significative bit (0x80000000)
+    /**
+     * Request was only triggered for augmented autofill.
+     *
+     * @hide
+     */
+    public static final int FLAG_AUGMENTED_AUTOFILL_REQUEST = 0x80000000;
+
     /** @hide */
     public static final int INVALID_REQUEST_ID = Integer.MIN_VALUE;
 
@@ -115,7 +123,8 @@
     /**
      * Gets the flags associated with this request.
      *
-     * @see #FLAG_MANUAL_REQUEST
+     * @return any combination of {@link #FLAG_MANUAL_REQUEST} and
+     *         {@link #FLAG_COMPATIBILITY_MODE_REQUEST}.
      */
     public @RequestFlags int getFlags() {
         return mFlags;
@@ -167,7 +176,7 @@
         parcel.writeInt(mFlags);
     }
 
-    public static final Parcelable.Creator<FillRequest> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<FillRequest> CREATOR =
             new Parcelable.Creator<FillRequest>() {
         @Override
         public FillRequest createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/FillResponse.java b/core/java/android/service/autofill/FillResponse.java
index 93ee8c3..257114c 100644
--- a/core/java/android/service/autofill/FillResponse.java
+++ b/core/java/android/service/autofill/FillResponse.java
@@ -658,7 +658,7 @@
         parcel.writeInt(mRequestId);
     }
 
-    public static final Parcelable.Creator<FillResponse> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<FillResponse> CREATOR =
             new Parcelable.Creator<FillResponse>() {
         @Override
         public FillResponse createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/ImageTransformation.java b/core/java/android/service/autofill/ImageTransformation.java
index 4afda24..12376e8 100644
--- a/core/java/android/service/autofill/ImageTransformation.java
+++ b/core/java/android/service/autofill/ImageTransformation.java
@@ -242,7 +242,7 @@
         parcel.writeCharSequenceArray(contentDescriptions);
     }
 
-    public static final Parcelable.Creator<ImageTransformation> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ImageTransformation> CREATOR =
             new Parcelable.Creator<ImageTransformation>() {
         @Override
         public ImageTransformation createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/LuhnChecksumValidator.java b/core/java/android/service/autofill/LuhnChecksumValidator.java
index c56ae84..ef0bd74 100644
--- a/core/java/android/service/autofill/LuhnChecksumValidator.java
+++ b/core/java/android/service/autofill/LuhnChecksumValidator.java
@@ -124,7 +124,7 @@
         parcel.writeParcelableArray(mIds, flags);
     }
 
-    public static final Parcelable.Creator<LuhnChecksumValidator> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<LuhnChecksumValidator> CREATOR =
             new Parcelable.Creator<LuhnChecksumValidator>() {
         @Override
         public LuhnChecksumValidator createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/NegationValidator.java b/core/java/android/service/autofill/NegationValidator.java
index a963f9f..2f098e2 100644
--- a/core/java/android/service/autofill/NegationValidator.java
+++ b/core/java/android/service/autofill/NegationValidator.java
@@ -64,7 +64,7 @@
         dest.writeParcelable(mValidator, flags);
     }
 
-    public static final Parcelable.Creator<NegationValidator> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<NegationValidator> CREATOR =
             new Parcelable.Creator<NegationValidator>() {
         @Override
         public NegationValidator createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/OptionalValidators.java b/core/java/android/service/autofill/OptionalValidators.java
index 7aec59f..7189c88 100644
--- a/core/java/android/service/autofill/OptionalValidators.java
+++ b/core/java/android/service/autofill/OptionalValidators.java
@@ -79,7 +79,7 @@
         dest.writeParcelableArray(mValidators, flags);
     }
 
-    public static final Parcelable.Creator<OptionalValidators> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<OptionalValidators> CREATOR =
             new Parcelable.Creator<OptionalValidators>() {
         @Override
         public OptionalValidators createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/RegexValidator.java b/core/java/android/service/autofill/RegexValidator.java
index 9dfe78d..8cb67d0 100644
--- a/core/java/android/service/autofill/RegexValidator.java
+++ b/core/java/android/service/autofill/RegexValidator.java
@@ -93,7 +93,7 @@
         parcel.writeSerializable(mRegex);
     }
 
-    public static final Parcelable.Creator<RegexValidator> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<RegexValidator> CREATOR =
             new Parcelable.Creator<RegexValidator>() {
         @Override
         public RegexValidator createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/RequiredValidators.java b/core/java/android/service/autofill/RequiredValidators.java
index 9e1db2b..619eba0 100644
--- a/core/java/android/service/autofill/RequiredValidators.java
+++ b/core/java/android/service/autofill/RequiredValidators.java
@@ -78,7 +78,7 @@
         dest.writeParcelableArray(mValidators, flags);
     }
 
-    public static final Parcelable.Creator<RequiredValidators> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<RequiredValidators> CREATOR =
             new Parcelable.Creator<RequiredValidators>() {
         @Override
         public RequiredValidators createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/SaveInfo.java b/core/java/android/service/autofill/SaveInfo.java
index dfaf49a..94b9d05 100644
--- a/core/java/android/service/autofill/SaveInfo.java
+++ b/core/java/android/service/autofill/SaveInfo.java
@@ -776,7 +776,7 @@
         parcel.writeInt(mFlags);
     }
 
-    public static final Parcelable.Creator<SaveInfo> CREATOR = new Parcelable.Creator<SaveInfo>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<SaveInfo> CREATOR = new Parcelable.Creator<SaveInfo>() {
         @Override
         public SaveInfo createFromParcel(Parcel parcel) {
 
diff --git a/core/java/android/service/autofill/SaveRequest.java b/core/java/android/service/autofill/SaveRequest.java
index c9b5b55..5dd07c4 100644
--- a/core/java/android/service/autofill/SaveRequest.java
+++ b/core/java/android/service/autofill/SaveRequest.java
@@ -101,7 +101,7 @@
         parcel.writeStringList(mDatasetIds);
     }
 
-    public static final Creator<SaveRequest> CREATOR =
+    public static final @android.annotation.NonNull Creator<SaveRequest> CREATOR =
             new Creator<SaveRequest>() {
         @Override
         public SaveRequest createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/TextValueSanitizer.java b/core/java/android/service/autofill/TextValueSanitizer.java
index a8c080a..cc48fcb 100644
--- a/core/java/android/service/autofill/TextValueSanitizer.java
+++ b/core/java/android/service/autofill/TextValueSanitizer.java
@@ -116,7 +116,7 @@
         parcel.writeString(mSubst);
     }
 
-    public static final Parcelable.Creator<TextValueSanitizer> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TextValueSanitizer> CREATOR =
             new Parcelable.Creator<TextValueSanitizer>() {
         @Override
         public TextValueSanitizer createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/UserData.java b/core/java/android/service/autofill/UserData.java
index a793e09..cea0496 100644
--- a/core/java/android/service/autofill/UserData.java
+++ b/core/java/android/service/autofill/UserData.java
@@ -435,7 +435,7 @@
         parcel.writeMap(mCategoryArgs);
     }
 
-    public static final Parcelable.Creator<UserData> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<UserData> CREATOR =
             new Parcelable.Creator<UserData>() {
         @Override
         public UserData createFromParcel(Parcel parcel) {
diff --git a/core/java/android/service/autofill/VisibilitySetterAction.java b/core/java/android/service/autofill/VisibilitySetterAction.java
index 9f977d7..e29a23f 100644
--- a/core/java/android/service/autofill/VisibilitySetterAction.java
+++ b/core/java/android/service/autofill/VisibilitySetterAction.java
@@ -70,7 +70,7 @@
     /**
      * Builder for {@link VisibilitySetterAction} objects.
      */
-    public static class Builder {
+    public static final class Builder {
         private final SparseIntArray mVisibilities = new SparseIntArray();
         private boolean mDestroyed;
 
@@ -96,6 +96,7 @@
          * @throws IllegalArgumentException if visibility is not one of {@link View#VISIBLE},
          * {@link View#INVISIBLE}, or {@link View#GONE}.
          */
+        @NonNull
         public Builder setVisibility(@IdRes int id, @Visibility int visibility) {
             throwIfDestroyed();
             switch (visibility) {
@@ -111,6 +112,7 @@
         /**
          * Creates a new {@link VisibilitySetterAction} instance.
          */
+        @NonNull
         public VisibilitySetterAction build() {
             throwIfDestroyed();
             mDestroyed = true;
@@ -145,8 +147,10 @@
         parcel.writeSparseIntArray(mVisibilities);
     }
 
-    public static final Parcelable.Creator<VisibilitySetterAction> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<VisibilitySetterAction> CREATOR =
             new Parcelable.Creator<VisibilitySetterAction>() {
+
+        @NonNull
         @Override
         public VisibilitySetterAction createFromParcel(Parcel parcel) {
             // Always go through the builder to ensure the data ingested by
@@ -165,6 +169,7 @@
             return builder == null ? null : builder.build();
         }
 
+        @NonNull
         @Override
         public VisibilitySetterAction[] newArray(int size) {
             return new VisibilitySetterAction[size];
diff --git a/core/java/android/service/autofill/augmented/AugmentedAutofillService.java b/core/java/android/service/autofill/augmented/AugmentedAutofillService.java
index 792eda7..463eae68 100644
--- a/core/java/android/service/autofill/augmented/AugmentedAutofillService.java
+++ b/core/java/android/service/autofill/augmented/AugmentedAutofillService.java
@@ -209,7 +209,7 @@
         } else {
             // TODO(b/123099468): figure out if it's ok to reuse the proxy; add logging
             if (DEBUG) Log.d(TAG, "Reusing proxy for session " + sessionId);
-            proxy.update(focusedId, focusedValue);
+            proxy.update(focusedId, focusedValue, callback);
         }
         // TODO(b/123101711): set cancellation signal
         final CancellationSignal cancellationSignal = null;
@@ -299,13 +299,14 @@
         private final Object mLock = new Object();
         private final IAugmentedAutofillManagerClient mClient;
         private final int mSessionId;
-        private final IFillCallback mCallback;
         public final int taskId;
         public final ComponentName componentName;
         @GuardedBy("mLock")
         private AutofillId mFocusedId;
         @GuardedBy("mLock")
         private AutofillValue mFocusedValue;
+        @GuardedBy("mLock")
+        private IFillCallback mCallback;
 
         /**
          * Id of the last field that cause the Autofill UI to be shown.
@@ -316,8 +317,8 @@
         private AutofillId mLastShownId;
 
         // Objects used to log metrics
-        private final long mRequestTime;
-        private long mOnSuccessTime;
+        private final long mFirstRequestTime;
+        private long mFirstOnSuccessTime;
         private long mUiFirstShownTime;
         private long mUiFirstDestroyedTime;
 
@@ -338,7 +339,7 @@
             this.componentName = componentName;
             this.mFocusedId = focusedId;
             this.mFocusedValue = focusedValue;
-            this.mRequestTime = requestTime;
+            this.mFirstRequestTime = requestTime;
             // TODO(b/123099468): linkToDeath
         }
 
@@ -400,11 +401,18 @@
             mClient.requestHideFillUi(mSessionId, mFocusedId);
         }
 
-        private void update(@NonNull AutofillId focusedId, @NonNull AutofillValue focusedValue) {
+        private void update(@NonNull AutofillId focusedId, @NonNull AutofillValue focusedValue,
+                @NonNull IFillCallback callback) {
             synchronized (mLock) {
                 // TODO(b/123099468): should we close the popupwindow if the focused id changed?
                 mFocusedId = focusedId;
                 mFocusedValue = focusedValue;
+                if (mCallback != null) {
+                    // TODO(b/123101711): we need to check whether the previous request was
+                    //  completed or not, and if not, cancel it first.
+                    Slog.d(TAG, "mCallback is updated.");
+                }
+                mCallback = callback;
             }
         }
 
@@ -426,11 +434,11 @@
         public void report(@ReportEvent int event) {
             switch (event) {
                 case REPORT_EVENT_ON_SUCCESS:
-                    if (mOnSuccessTime == 0) {
-                        mOnSuccessTime = SystemClock.elapsedRealtime();
+                    if (mFirstOnSuccessTime == 0) {
+                        mFirstOnSuccessTime = SystemClock.elapsedRealtime();
                         if (DEBUG) {
-                            Slog.d(TAG, "Service responsed in "
-                                    + TimeUtils.formatDuration(mOnSuccessTime - mRequestTime));
+                            Slog.d(TAG, "Service responded in " + TimeUtils.formatDuration(
+                                    mFirstOnSuccessTime - mFirstRequestTime));
                         }
                     }
                     try {
@@ -443,8 +451,8 @@
                     if (mUiFirstShownTime == 0) {
                         mUiFirstShownTime = SystemClock.elapsedRealtime();
                         if (DEBUG) {
-                            Slog.d(TAG, "UI shown in "
-                                    + TimeUtils.formatDuration(mUiFirstShownTime - mRequestTime));
+                            Slog.d(TAG, "UI shown in " + TimeUtils.formatDuration(
+                                    mUiFirstShownTime - mFirstRequestTime));
                         }
                     }
                     break;
@@ -452,9 +460,8 @@
                     if (mUiFirstDestroyedTime == 0) {
                         mUiFirstDestroyedTime = SystemClock.elapsedRealtime();
                         if (DEBUG) {
-                            Slog.d(TAG, "UI destroyed in "
-                                    + TimeUtils.formatDuration(
-                                            mUiFirstDestroyedTime - mRequestTime));
+                            Slog.d(TAG, "UI destroyed in " + TimeUtils.formatDuration(
+                                    mUiFirstDestroyedTime - mFirstRequestTime));
                         }
                     }
                     break;
@@ -486,20 +493,20 @@
                 pw.print(prefix); pw.println("smartSuggestion:");
                 mSmartSuggestion.dump(prefix2, pw);
             }
-            if (mOnSuccessTime > 0) {
-                final long responseTime = mOnSuccessTime - mRequestTime;
+            if (mFirstOnSuccessTime > 0) {
+                final long responseTime = mFirstOnSuccessTime - mFirstRequestTime;
                 pw.print(prefix); pw.print("response time: ");
                 TimeUtils.formatDuration(responseTime, pw); pw.println();
             }
 
             if (mUiFirstShownTime > 0) {
-                final long uiRenderingTime = mUiFirstShownTime - mRequestTime;
+                final long uiRenderingTime = mUiFirstShownTime - mFirstRequestTime;
                 pw.print(prefix); pw.print("UI rendering time: ");
                 TimeUtils.formatDuration(uiRenderingTime, pw); pw.println();
             }
 
             if (mUiFirstDestroyedTime > 0) {
-                final long uiTotalTime = mUiFirstDestroyedTime - mRequestTime;
+                final long uiTotalTime = mUiFirstDestroyedTime - mFirstRequestTime;
                 pw.print(prefix); pw.print("UI life time: ");
                 TimeUtils.formatDuration(uiTotalTime, pw); pw.println();
             }
@@ -510,6 +517,7 @@
                 if (mFillWindow != null) {
                     if (DEBUG) Log.d(TAG, "destroying window");
                     mFillWindow.destroy();
+                    mFillWindow = null;
                 }
             }
         }
diff --git a/core/java/android/service/autofill/augmented/FillResponse.java b/core/java/android/service/autofill/augmented/FillResponse.java
index 2ac406c..48a3c1b 100644
--- a/core/java/android/service/autofill/augmented/FillResponse.java
+++ b/core/java/android/service/autofill/augmented/FillResponse.java
@@ -19,9 +19,6 @@
 import android.annotation.Nullable;
 import android.annotation.SystemApi;
 import android.annotation.TestApi;
-import android.view.autofill.AutofillId;
-
-import java.util.List;
 
 /**
  * Response to a {@link FillRequest}.
@@ -63,6 +60,7 @@
          *
          * @return this builder
          */
+        @NonNull
         public Builder setFillWindow(@NonNull FillWindow fillWindow) {
             // TODO(b/123100712): check not null / unit test / throw exception if FillWindow not
             // updated yet
@@ -71,19 +69,6 @@
         }
 
         /**
-         * Tells the Android System that the given {@code ids} should not trigger further
-         * {@link FillRequest requests} when focused.
-         *
-         * @param ids ids of the fields that should be ignored
-         *
-         * @return this builder
-         */
-        public Builder setIgnoredIds(@NonNull List<AutofillId> ids) {
-            // TODO(b/123100695): implement / check not null / unit test
-            return this;
-        }
-
-        /**
          * Builds a new {@link FillResponse} instance.
          *
          * @throws IllegalStateException if any of the following conditions occur:
@@ -95,6 +80,7 @@
          *
          * @return A built response.
          */
+        @NonNull
         public FillResponse build() {
             // TODO(b/123100712): check conditions / add unit test
             return new FillResponse(this);
diff --git a/core/java/android/service/autofill/augmented/FillWindow.java b/core/java/android/service/autofill/augmented/FillWindow.java
index 6e06754..bd532a3 100644
--- a/core/java/android/service/autofill/augmented/FillWindow.java
+++ b/core/java/android/service/autofill/augmented/FillWindow.java
@@ -82,6 +82,8 @@
     private Rect mBounds;
 
     @GuardedBy("mLock")
+    private boolean mUpdateCalled;
+    @GuardedBy("mLock")
     private boolean mDestroyed;
 
     private AutofillProxy mProxy;
@@ -103,6 +105,7 @@
         }
         // TODO(b/123100712): add test case for null
         Preconditions.checkNotNull(area);
+        Preconditions.checkNotNull(area.proxy);
         Preconditions.checkNotNull(rootView);
         // TODO(b/123100712): must check the area is a valid object returned by
         // SmartSuggestionParams, throw IAE if not
@@ -149,6 +152,7 @@
             if (DEBUG) {
                 Log.d(TAG, "Created FillWindow: params= " + smartSuggestion + " view=" + rootView);
             }
+            mUpdateCalled = true;
             mDestroyed = false;
             mProxy.setFillWindow(this);
             return true;
@@ -237,8 +241,10 @@
         }
         synchronized (mLock) {
             if (mDestroyed) return;
-            hide();
-            mProxy.report(AutofillProxy.REPORT_EVENT_UI_DESTROYED);
+            if (mUpdateCalled) {
+                hide();
+                mProxy.report(AutofillProxy.REPORT_EVENT_UI_DESTROYED);
+            }
             mDestroyed = true;
             mCloseGuard.close();
         }
@@ -266,6 +272,7 @@
     public void dump(@NonNull String prefix, @NonNull PrintWriter pw) {
         synchronized (this) {
             pw.print(prefix); pw.print("destroyed: "); pw.println(mDestroyed);
+            pw.print(prefix); pw.print("updateCalled: "); pw.println(mUpdateCalled);
             if (mFillView != null) {
                 pw.print(prefix); pw.print("fill window: ");
                 pw.println(mShowing ? "shown" : "hidden");
diff --git a/core/java/android/service/carrier/CarrierIdentifier.java b/core/java/android/service/carrier/CarrierIdentifier.java
index 568ca0f..3a57e3a 100644
--- a/core/java/android/service/carrier/CarrierIdentifier.java
+++ b/core/java/android/service/carrier/CarrierIdentifier.java
@@ -35,7 +35,7 @@
 public class CarrierIdentifier implements Parcelable {
 
     /** Used to create a {@link CarrierIdentifier} from a {@link Parcel}. */
-    public static final Creator<CarrierIdentifier> CREATOR = new Creator<CarrierIdentifier>() {
+    public static final @android.annotation.NonNull Creator<CarrierIdentifier> CREATOR = new Creator<CarrierIdentifier>() {
             @Override
         public CarrierIdentifier createFromParcel(Parcel parcel) {
             return new CarrierIdentifier(parcel);
diff --git a/core/java/android/service/carrier/CarrierMessagingClientService.java b/core/java/android/service/carrier/CarrierMessagingClientService.java
index 13f4fc4..767c1d1 100644
--- a/core/java/android/service/carrier/CarrierMessagingClientService.java
+++ b/core/java/android/service/carrier/CarrierMessagingClientService.java
@@ -15,6 +15,8 @@
  */
 package android.service.carrier;
 
+import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.app.Service;
 import android.content.ComponentName;
 import android.content.Intent;
@@ -71,7 +73,8 @@
     }
 
     @Override
-    public final IBinder onBind(Intent intent) {
+    @NonNull
+    public final IBinder onBind(@Nullable Intent intent) {
         return mImpl.asBinder();
     }
 
diff --git a/core/java/android/service/carrier/MessagePdu.java b/core/java/android/service/carrier/MessagePdu.java
index ca18e53..19c41b1 100644
--- a/core/java/android/service/carrier/MessagePdu.java
+++ b/core/java/android/service/carrier/MessagePdu.java
@@ -72,7 +72,7 @@
     /**
      * Constructs a {@link MessagePdu} from a {@link Parcel}.
      */
-    public static final Parcelable.Creator<MessagePdu> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<MessagePdu> CREATOR
             = new Parcelable.Creator<MessagePdu>() {
                 @Override
                 public MessagePdu createFromParcel(Parcel source) {
diff --git a/core/java/android/service/chooser/ChooserTarget.java b/core/java/android/service/chooser/ChooserTarget.java
index c2f70cc..5d2d667 100644
--- a/core/java/android/service/chooser/ChooserTarget.java
+++ b/core/java/android/service/chooser/ChooserTarget.java
@@ -202,7 +202,7 @@
         dest.writeBundle(mIntentExtras);
     }
 
-    public static final Creator<ChooserTarget> CREATOR
+    public static final @android.annotation.NonNull Creator<ChooserTarget> CREATOR
             = new Creator<ChooserTarget>() {
         @Override
         public ChooserTarget createFromParcel(Parcel source) {
diff --git a/core/java/android/service/contentcapture/SnapshotData.java b/core/java/android/service/contentcapture/SnapshotData.java
index c3af1f0..5b3930a 100644
--- a/core/java/android/service/contentcapture/SnapshotData.java
+++ b/core/java/android/service/contentcapture/SnapshotData.java
@@ -60,6 +60,7 @@
     /**
      * Returns the assist data for this snapshot.
      */
+    @NonNull
     public Bundle getAssistData() {
         return mAssistData;
     }
@@ -67,6 +68,7 @@
     /**
      * Returns the assist structure for this snapshot.
      */
+    @NonNull
     public AssistStructure getAssistStructure() {
         return mAssistStructure;
     }
@@ -74,6 +76,7 @@
     /**
      * Returns the assist context for this snapshot.
      */
+    @Nullable
     public AssistContent getAssistContent() {
         return mAssistContent;
     }
@@ -90,15 +93,17 @@
         parcel.writeParcelable(mAssistContent, flags);
     }
 
-    public static final Creator<SnapshotData> CREATOR =
+    public static final @android.annotation.NonNull Creator<SnapshotData> CREATOR =
             new Creator<SnapshotData>() {
 
         @Override
+        @NonNull
         public SnapshotData createFromParcel(@NonNull Parcel parcel) {
             return new SnapshotData(parcel);
         }
 
         @Override
+        @NonNull
         public SnapshotData[] newArray(int size) {
             return new SnapshotData[size];
         }
diff --git a/core/java/android/service/contentsuggestions/ContentSuggestionsService.java b/core/java/android/service/contentsuggestions/ContentSuggestionsService.java
index 333f4be..40333bf 100644
--- a/core/java/android/service/contentsuggestions/ContentSuggestionsService.java
+++ b/core/java/android/service/contentsuggestions/ContentSuggestionsService.java
@@ -60,11 +60,17 @@
         @Override
         public void provideContextImage(int taskId, GraphicBuffer contextImage,
                 Bundle imageContextRequestExtras) {
+
+            Bitmap wrappedBuffer = null;
+            if (contextImage != null) {
+                wrappedBuffer = Bitmap.wrapHardwareBuffer(
+                        HardwareBuffer.createFromGraphicBuffer(contextImage), null);
+            }
+
             mHandler.sendMessage(
                     obtainMessage(ContentSuggestionsService::processContextImage,
                             ContentSuggestionsService.this, taskId,
-                            Bitmap.wrapHardwareBuffer(
-                                    HardwareBuffer.createFromGraphicBuffer(contextImage), null),
+                            wrappedBuffer,
                             imageContextRequestExtras));
         }
 
diff --git a/core/java/android/service/euicc/DownloadSubscriptionResult.java b/core/java/android/service/euicc/DownloadSubscriptionResult.java
index b410e35..3b1a2c9 100644
--- a/core/java/android/service/euicc/DownloadSubscriptionResult.java
+++ b/core/java/android/service/euicc/DownloadSubscriptionResult.java
@@ -28,7 +28,7 @@
 @SystemApi
 public final class DownloadSubscriptionResult implements Parcelable {
 
-    public static final Creator<DownloadSubscriptionResult> CREATOR =
+    public static final @android.annotation.NonNull Creator<DownloadSubscriptionResult> CREATOR =
             new Creator<DownloadSubscriptionResult>() {
         @Override
         public DownloadSubscriptionResult createFromParcel(Parcel in) {
diff --git a/core/java/android/service/euicc/EuiccProfileInfo.java b/core/java/android/service/euicc/EuiccProfileInfo.java
index 4a39782..702837b 100644
--- a/core/java/android/service/euicc/EuiccProfileInfo.java
+++ b/core/java/android/service/euicc/EuiccProfileInfo.java
@@ -126,7 +126,7 @@
      */
     private final @Nullable UiccAccessRule[] mAccessRules;
 
-    public static final Creator<EuiccProfileInfo> CREATOR = new Creator<EuiccProfileInfo>() {
+    public static final @android.annotation.NonNull Creator<EuiccProfileInfo> CREATOR = new Creator<EuiccProfileInfo>() {
         @Override
         public EuiccProfileInfo createFromParcel(Parcel in) {
             return new EuiccProfileInfo(in);
diff --git a/core/java/android/service/euicc/GetDefaultDownloadableSubscriptionListResult.java b/core/java/android/service/euicc/GetDefaultDownloadableSubscriptionListResult.java
index bd91ca0..c7a9851 100644
--- a/core/java/android/service/euicc/GetDefaultDownloadableSubscriptionListResult.java
+++ b/core/java/android/service/euicc/GetDefaultDownloadableSubscriptionListResult.java
@@ -32,7 +32,7 @@
 @SystemApi
 public final class GetDefaultDownloadableSubscriptionListResult implements Parcelable {
 
-    public static final Creator<GetDefaultDownloadableSubscriptionListResult> CREATOR =
+    public static final @android.annotation.NonNull Creator<GetDefaultDownloadableSubscriptionListResult> CREATOR =
             new Creator<GetDefaultDownloadableSubscriptionListResult>() {
         @Override
         public GetDefaultDownloadableSubscriptionListResult createFromParcel(Parcel in) {
diff --git a/core/java/android/service/euicc/GetDownloadableSubscriptionMetadataResult.java b/core/java/android/service/euicc/GetDownloadableSubscriptionMetadataResult.java
index 71f1d22..abd4065 100644
--- a/core/java/android/service/euicc/GetDownloadableSubscriptionMetadataResult.java
+++ b/core/java/android/service/euicc/GetDownloadableSubscriptionMetadataResult.java
@@ -29,7 +29,7 @@
 @SystemApi
 public final class GetDownloadableSubscriptionMetadataResult implements Parcelable {
 
-    public static final Creator<GetDownloadableSubscriptionMetadataResult> CREATOR =
+    public static final @android.annotation.NonNull Creator<GetDownloadableSubscriptionMetadataResult> CREATOR =
             new Creator<GetDownloadableSubscriptionMetadataResult>() {
         @Override
         public GetDownloadableSubscriptionMetadataResult createFromParcel(Parcel in) {
diff --git a/core/java/android/service/euicc/GetEuiccProfileInfoListResult.java b/core/java/android/service/euicc/GetEuiccProfileInfoListResult.java
index 464d136..7a9d8a0 100644
--- a/core/java/android/service/euicc/GetEuiccProfileInfoListResult.java
+++ b/core/java/android/service/euicc/GetEuiccProfileInfoListResult.java
@@ -30,7 +30,7 @@
 @SystemApi
 public final class GetEuiccProfileInfoListResult implements Parcelable {
 
-    public static final Creator<GetEuiccProfileInfoListResult> CREATOR =
+    public static final @android.annotation.NonNull Creator<GetEuiccProfileInfoListResult> CREATOR =
             new Creator<GetEuiccProfileInfoListResult>() {
                 @Override
                 public GetEuiccProfileInfoListResult createFromParcel(Parcel in) {
diff --git a/core/java/android/service/euicc/IDeleteSubscriptionCallback.aidl b/core/java/android/service/euicc/IDeleteSubscriptionCallback.aidl
index 4667066..aff8f1b 100644
--- a/core/java/android/service/euicc/IDeleteSubscriptionCallback.aidl
+++ b/core/java/android/service/euicc/IDeleteSubscriptionCallback.aidl
@@ -18,5 +18,6 @@
 
 /** @hide */
 oneway interface IDeleteSubscriptionCallback {
+    @UnsupportedAppUsage
     void onComplete(int result);
 }
\ No newline at end of file
diff --git a/core/java/android/service/euicc/IEraseSubscriptionsCallback.aidl b/core/java/android/service/euicc/IEraseSubscriptionsCallback.aidl
index c975f18..34b53cc 100644
--- a/core/java/android/service/euicc/IEraseSubscriptionsCallback.aidl
+++ b/core/java/android/service/euicc/IEraseSubscriptionsCallback.aidl
@@ -18,5 +18,6 @@
 
 /** @hide */
 oneway interface IEraseSubscriptionsCallback {
+    @UnsupportedAppUsage
     void onComplete(int result);
 }
\ No newline at end of file
diff --git a/core/java/android/service/euicc/IGetDefaultDownloadableSubscriptionListCallback.aidl b/core/java/android/service/euicc/IGetDefaultDownloadableSubscriptionListCallback.aidl
index 0c5a0c6..ad69ef1 100644
--- a/core/java/android/service/euicc/IGetDefaultDownloadableSubscriptionListCallback.aidl
+++ b/core/java/android/service/euicc/IGetDefaultDownloadableSubscriptionListCallback.aidl
@@ -20,5 +20,6 @@
 
 /** @hide */
 oneway interface IGetDefaultDownloadableSubscriptionListCallback {
+    @UnsupportedAppUsage
     void onComplete(in GetDefaultDownloadableSubscriptionListResult result);
 }
\ No newline at end of file
diff --git a/core/java/android/service/euicc/IGetDownloadableSubscriptionMetadataCallback.aidl b/core/java/android/service/euicc/IGetDownloadableSubscriptionMetadataCallback.aidl
index 3353061..01f187e 100644
--- a/core/java/android/service/euicc/IGetDownloadableSubscriptionMetadataCallback.aidl
+++ b/core/java/android/service/euicc/IGetDownloadableSubscriptionMetadataCallback.aidl
@@ -20,5 +20,6 @@
 
 /** @hide */
 oneway interface IGetDownloadableSubscriptionMetadataCallback {
+    @UnsupportedAppUsage
     void onComplete(in GetDownloadableSubscriptionMetadataResult result);
 }
\ No newline at end of file
diff --git a/core/java/android/service/euicc/IGetEidCallback.aidl b/core/java/android/service/euicc/IGetEidCallback.aidl
index 35ee9c2..e405a98 100644
--- a/core/java/android/service/euicc/IGetEidCallback.aidl
+++ b/core/java/android/service/euicc/IGetEidCallback.aidl
@@ -18,5 +18,6 @@
 
 /** @hide */
 oneway interface IGetEidCallback {
+    @UnsupportedAppUsage
     void onSuccess(String eid);
 }
\ No newline at end of file
diff --git a/core/java/android/service/euicc/IGetEuiccInfoCallback.aidl b/core/java/android/service/euicc/IGetEuiccInfoCallback.aidl
index 6d28148..c061182 100644
--- a/core/java/android/service/euicc/IGetEuiccInfoCallback.aidl
+++ b/core/java/android/service/euicc/IGetEuiccInfoCallback.aidl
@@ -20,5 +20,6 @@
 
 /** @hide */
 oneway interface IGetEuiccInfoCallback {
+    @UnsupportedAppUsage
     void onSuccess(in EuiccInfo euiccInfo);
 }
\ No newline at end of file
diff --git a/core/java/android/service/euicc/IGetEuiccProfileInfoListCallback.aidl b/core/java/android/service/euicc/IGetEuiccProfileInfoListCallback.aidl
index 761ec1f..0485f7b 100644
--- a/core/java/android/service/euicc/IGetEuiccProfileInfoListCallback.aidl
+++ b/core/java/android/service/euicc/IGetEuiccProfileInfoListCallback.aidl
@@ -20,5 +20,6 @@
 
 /** @hide */
 oneway interface IGetEuiccProfileInfoListCallback {
+    @UnsupportedAppUsage
     void onComplete(in GetEuiccProfileInfoListResult result);
 }
\ No newline at end of file
diff --git a/core/java/android/service/euicc/IRetainSubscriptionsForFactoryResetCallback.aidl b/core/java/android/service/euicc/IRetainSubscriptionsForFactoryResetCallback.aidl
index 1276830..340401f 100644
--- a/core/java/android/service/euicc/IRetainSubscriptionsForFactoryResetCallback.aidl
+++ b/core/java/android/service/euicc/IRetainSubscriptionsForFactoryResetCallback.aidl
@@ -18,5 +18,6 @@
 
 /** @hide */
 oneway interface IRetainSubscriptionsForFactoryResetCallback {
+    @UnsupportedAppUsage
     void onComplete(int result);
 }
\ No newline at end of file
diff --git a/core/java/android/service/euicc/ISwitchToSubscriptionCallback.aidl b/core/java/android/service/euicc/ISwitchToSubscriptionCallback.aidl
index 0f91a6b..b8f984d 100644
--- a/core/java/android/service/euicc/ISwitchToSubscriptionCallback.aidl
+++ b/core/java/android/service/euicc/ISwitchToSubscriptionCallback.aidl
@@ -18,5 +18,6 @@
 
 /** @hide */
 oneway interface ISwitchToSubscriptionCallback {
+    @UnsupportedAppUsage
     void onComplete(int result);
 }
\ No newline at end of file
diff --git a/core/java/android/service/euicc/IUpdateSubscriptionNicknameCallback.aidl b/core/java/android/service/euicc/IUpdateSubscriptionNicknameCallback.aidl
index 6666933..0aa6697 100644
--- a/core/java/android/service/euicc/IUpdateSubscriptionNicknameCallback.aidl
+++ b/core/java/android/service/euicc/IUpdateSubscriptionNicknameCallback.aidl
@@ -18,5 +18,6 @@
 
 /** @hide */
 oneway interface IUpdateSubscriptionNicknameCallback {
+    @UnsupportedAppUsage
     void onComplete(int result);
 }
\ No newline at end of file
diff --git a/core/java/android/service/gatekeeper/GateKeeperResponse.java b/core/java/android/service/gatekeeper/GateKeeperResponse.java
index 9b52934..66fee1e 100644
--- a/core/java/android/service/gatekeeper/GateKeeperResponse.java
+++ b/core/java/android/service/gatekeeper/GateKeeperResponse.java
@@ -66,7 +66,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<GateKeeperResponse> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<GateKeeperResponse> CREATOR
             = new Parcelable.Creator<GateKeeperResponse>() {
         @Override
         public GateKeeperResponse createFromParcel(Parcel source) {
diff --git a/core/java/android/service/notification/Adjustment.java b/core/java/android/service/notification/Adjustment.java
index bddc5ef..d84124d 100644
--- a/core/java/android/service/notification/Adjustment.java
+++ b/core/java/android/service/notification/Adjustment.java
@@ -165,7 +165,7 @@
         mUser = in.readInt();
     }
 
-    public static final Creator<Adjustment> CREATOR = new Creator<Adjustment>() {
+    public static final @android.annotation.NonNull Creator<Adjustment> CREATOR = new Creator<Adjustment>() {
         @Override
         public Adjustment createFromParcel(Parcel in) {
             return new Adjustment(in);
diff --git a/core/java/android/service/notification/Condition.java b/core/java/android/service/notification/Condition.java
index 30d9804..e506509 100644
--- a/core/java/android/service/notification/Condition.java
+++ b/core/java/android/service/notification/Condition.java
@@ -227,7 +227,7 @@
         return id != null && SCHEME.equals(id.getScheme()) && pkg.equals(id.getAuthority());
     }
 
-    public static final Parcelable.Creator<Condition> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Condition> CREATOR
             = new Parcelable.Creator<Condition>() {
         @Override
         public Condition createFromParcel(Parcel source) {
diff --git a/core/java/android/service/notification/NotificationListenerService.java b/core/java/android/service/notification/NotificationListenerService.java
index d3285bb..edb10ec 100644
--- a/core/java/android/service/notification/NotificationListenerService.java
+++ b/core/java/android/service/notification/NotificationListenerService.java
@@ -2163,7 +2163,7 @@
             dest.writeParcelable(mRankingUpdate, flags);
         }
 
-        public static final Creator<RankingMap> CREATOR = new Creator<RankingMap>() {
+        public static final @android.annotation.NonNull Creator<RankingMap> CREATOR = new Creator<RankingMap>() {
             @Override
             public RankingMap createFromParcel(Parcel source) {
                 NotificationRankingUpdate rankingUpdate = source.readParcelable(null);
diff --git a/core/java/android/service/notification/NotificationRankingUpdate.java b/core/java/android/service/notification/NotificationRankingUpdate.java
index 230ae27..c5c70f8 100644
--- a/core/java/android/service/notification/NotificationRankingUpdate.java
+++ b/core/java/android/service/notification/NotificationRankingUpdate.java
@@ -119,7 +119,7 @@
         out.writeBooleanArray(mCanBubble);
     }
 
-    public static final Parcelable.Creator<NotificationRankingUpdate> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<NotificationRankingUpdate> CREATOR
             = new Parcelable.Creator<NotificationRankingUpdate>() {
         public NotificationRankingUpdate createFromParcel(Parcel parcel) {
             return new NotificationRankingUpdate(parcel);
diff --git a/core/java/android/service/notification/NotificationStats.java b/core/java/android/service/notification/NotificationStats.java
index ebfabbf..5a54a43 100644
--- a/core/java/android/service/notification/NotificationStats.java
+++ b/core/java/android/service/notification/NotificationStats.java
@@ -131,7 +131,7 @@
         return 0;
     }
 
-    public static final Creator<NotificationStats> CREATOR = new Creator<NotificationStats>() {
+    public static final @android.annotation.NonNull Creator<NotificationStats> CREATOR = new Creator<NotificationStats>() {
         @Override
         public NotificationStats createFromParcel(Parcel in) {
             return new NotificationStats(in);
diff --git a/core/java/android/service/notification/NotifyingApp.java b/core/java/android/service/notification/NotifyingApp.java
index 38f18c6..a560623 100644
--- a/core/java/android/service/notification/NotifyingApp.java
+++ b/core/java/android/service/notification/NotifyingApp.java
@@ -74,7 +74,7 @@
         return this;
     }
 
-    public static final Creator<NotifyingApp> CREATOR = new Creator<NotifyingApp>() {
+    public static final @android.annotation.NonNull Creator<NotifyingApp> CREATOR = new Creator<NotifyingApp>() {
         @Override
         public NotifyingApp createFromParcel(Parcel in) {
             return new NotifyingApp(in);
diff --git a/core/java/android/service/notification/SnoozeCriterion.java b/core/java/android/service/notification/SnoozeCriterion.java
index bd93eff..938cc10 100644
--- a/core/java/android/service/notification/SnoozeCriterion.java
+++ b/core/java/android/service/notification/SnoozeCriterion.java
@@ -78,7 +78,7 @@
         return mConfirmation;
     }
 
-    public static final Creator<SnoozeCriterion> CREATOR = new Creator<SnoozeCriterion>() {
+    public static final @android.annotation.NonNull Creator<SnoozeCriterion> CREATOR = new Creator<SnoozeCriterion>() {
         @Override
         public SnoozeCriterion createFromParcel(Parcel in) {
             return new SnoozeCriterion(in);
diff --git a/core/java/android/service/notification/StatusBarNotification.java b/core/java/android/service/notification/StatusBarNotification.java
index 954dc39..0836327 100644
--- a/core/java/android/service/notification/StatusBarNotification.java
+++ b/core/java/android/service/notification/StatusBarNotification.java
@@ -205,7 +205,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<StatusBarNotification> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<StatusBarNotification> CREATOR
             = new Parcelable.Creator<StatusBarNotification>()
     {
         public StatusBarNotification createFromParcel(Parcel parcel)
diff --git a/core/java/android/service/notification/ZenModeConfig.java b/core/java/android/service/notification/ZenModeConfig.java
index bff118e..cb7d41b 100644
--- a/core/java/android/service/notification/ZenModeConfig.java
+++ b/core/java/android/service/notification/ZenModeConfig.java
@@ -921,7 +921,7 @@
         }
     }
 
-    public static final Parcelable.Creator<ZenModeConfig> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ZenModeConfig> CREATOR
             = new Parcelable.Creator<ZenModeConfig>() {
         @Override
         public ZenModeConfig createFromParcel(Parcel source) {
@@ -1860,7 +1860,7 @@
                     || condition.state == Condition.STATE_UNKNOWN);
         }
 
-        public static final Parcelable.Creator<ZenRule> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<ZenRule> CREATOR
                 = new Parcelable.Creator<ZenRule>() {
             @Override
             public ZenRule createFromParcel(Parcel source) {
diff --git a/core/java/android/service/notification/ZenPolicy.java b/core/java/android/service/notification/ZenPolicy.java
index 6392704..74e6c6e 100644
--- a/core/java/android/service/notification/ZenPolicy.java
+++ b/core/java/android/service/notification/ZenPolicy.java
@@ -713,7 +713,7 @@
         dest.writeInt(mPriorityMessages);
     }
 
-    public static final Parcelable.Creator<ZenPolicy> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ZenPolicy> CREATOR =
             new Parcelable.Creator<ZenPolicy>() {
         @Override
         public ZenPolicy createFromParcel(Parcel source) {
diff --git a/core/java/android/service/quicksettings/Tile.java b/core/java/android/service/quicksettings/Tile.java
index 6b569cf..4191040 100644
--- a/core/java/android/service/quicksettings/Tile.java
+++ b/core/java/android/service/quicksettings/Tile.java
@@ -229,7 +229,7 @@
         mContentDescription = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
     }
 
-    public static final Creator<Tile> CREATOR = new Creator<Tile>() {
+    public static final @android.annotation.NonNull Creator<Tile> CREATOR = new Creator<Tile>() {
         @Override
         public Tile createFromParcel(Parcel source) {
             return new Tile(source);
diff --git a/core/java/android/service/resolver/ResolverTarget.java b/core/java/android/service/resolver/ResolverTarget.java
index fb3e2d7..33b3283 100644
--- a/core/java/android/service/resolver/ResolverTarget.java
+++ b/core/java/android/service/resolver/ResolverTarget.java
@@ -201,7 +201,7 @@
     }
 
     // creator definition for the class.
-    public static final Creator<ResolverTarget> CREATOR
+    public static final @android.annotation.NonNull Creator<ResolverTarget> CREATOR
             = new Creator<ResolverTarget>() {
         @Override
         public ResolverTarget createFromParcel(Parcel source) {
diff --git a/core/java/android/service/settings/suggestions/Suggestion.java b/core/java/android/service/settings/suggestions/Suggestion.java
index e97f963a..3e63efb 100644
--- a/core/java/android/service/settings/suggestions/Suggestion.java
+++ b/core/java/android/service/settings/suggestions/Suggestion.java
@@ -125,7 +125,7 @@
         mPendingIntent = in.readParcelable(PendingIntent.class.getClassLoader());
     }
 
-    public static final Creator<Suggestion> CREATOR = new Creator<Suggestion>() {
+    public static final @android.annotation.NonNull Creator<Suggestion> CREATOR = new Creator<Suggestion>() {
         @Override
         public Suggestion createFromParcel(Parcel in) {
             return new Suggestion(in);
diff --git a/core/java/android/service/vr/IVrManager.aidl b/core/java/android/service/vr/IVrManager.aidl
index b0269e3..a8293b4 100644
--- a/core/java/android/service/vr/IVrManager.aidl
+++ b/core/java/android/service/vr/IVrManager.aidl
@@ -57,6 +57,7 @@
      *
      * @return {@code true} if VR mode is enabled.
      */
+    @UnsupportedAppUsage
     boolean getVrModeState();
 
     /**
@@ -93,6 +94,7 @@
      * @return {@link android.view.Display.INVALID_DISPLAY} if there is no virtual display
      * currently, else return the display id of the virtual display
      */
+    @UnsupportedAppUsage
     int getVr2dDisplayId();
 
     /**
diff --git a/core/java/android/service/wallpaper/IWallpaperEngine.aidl b/core/java/android/service/wallpaper/IWallpaperEngine.aidl
index ebce484..00e0b7c 100644
--- a/core/java/android/service/wallpaper/IWallpaperEngine.aidl
+++ b/core/java/android/service/wallpaper/IWallpaperEngine.aidl
@@ -26,11 +26,15 @@
 oneway interface IWallpaperEngine {
     void setDesiredSize(int width, int height);
     void setDisplayPadding(in Rect padding);
+    @UnsupportedAppUsage
     void setVisibility(boolean visible);
     void setInAmbientMode(boolean inAmbientDisplay, long animationDuration);
+    @UnsupportedAppUsage
     void dispatchPointer(in MotionEvent event);
+    @UnsupportedAppUsage
     void dispatchWallpaperCommand(String action, int x, int y,
             int z, in Bundle extras);
     void requestWallpaperColors();
+    @UnsupportedAppUsage
     void destroy();
 }
diff --git a/core/java/android/speech/IRecognitionListener.aidl b/core/java/android/speech/IRecognitionListener.aidl
index 3d3c44b..e77851b 100644
--- a/core/java/android/speech/IRecognitionListener.aidl
+++ b/core/java/android/speech/IRecognitionListener.aidl
@@ -83,5 +83,6 @@
      * @param eventType the type of the occurred event
      * @param params a Bundle containing the passed parameters
      */
+    @UnsupportedAppUsage
     void onEvent(in int eventType, in Bundle params);
 }
diff --git a/core/java/android/speech/tts/Voice.java b/core/java/android/speech/tts/Voice.java
index dcf5980..fefc35e 100644
--- a/core/java/android/speech/tts/Voice.java
+++ b/core/java/android/speech/tts/Voice.java
@@ -106,7 +106,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<Voice> CREATOR = new Parcelable.Creator<Voice>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<Voice> CREATOR = new Parcelable.Creator<Voice>() {
         @Override
         public Voice createFromParcel(Parcel in) {
             return new Voice(in);
diff --git a/core/java/android/text/style/AccessibilityClickableSpan.java b/core/java/android/text/style/AccessibilityClickableSpan.java
index 7f39cc1..534ce63 100644
--- a/core/java/android/text/style/AccessibilityClickableSpan.java
+++ b/core/java/android/text/style/AccessibilityClickableSpan.java
@@ -144,7 +144,7 @@
                 R.id.accessibilityActionClickOnClickableSpan, arguments);
     }
 
-    public static final Parcelable.Creator<AccessibilityClickableSpan> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AccessibilityClickableSpan> CREATOR =
             new Parcelable.Creator<AccessibilityClickableSpan>() {
                 @Override
                 public AccessibilityClickableSpan createFromParcel(Parcel parcel) {
diff --git a/core/java/android/text/style/SuggestionSpan.java b/core/java/android/text/style/SuggestionSpan.java
index dd073e9..c000ae3 100644
--- a/core/java/android/text/style/SuggestionSpan.java
+++ b/core/java/android/text/style/SuggestionSpan.java
@@ -344,7 +344,7 @@
                 languageTag, localeStringForCompatibility});
     }
 
-    public static final Parcelable.Creator<SuggestionSpan> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<SuggestionSpan> CREATOR =
             new Parcelable.Creator<SuggestionSpan>() {
         @Override
         public SuggestionSpan createFromParcel(Parcel source) {
diff --git a/core/java/android/util/ArrayMap.java b/core/java/android/util/ArrayMap.java
index 294a179..436cb4f 100644
--- a/core/java/android/util/ArrayMap.java
+++ b/core/java/android/util/ArrayMap.java
@@ -19,6 +19,9 @@
 import libcore.util.EmptyArray;
 
 import android.annotation.UnsupportedAppUsage;
+
+import com.android.internal.util.ArrayUtils;
+
 import java.util.Collection;
 import java.util.ConcurrentModificationException;
 import java.util.Map;
@@ -816,7 +819,7 @@
             buffer.append('=');
             Object value = valueAt(i);
             if (value != this) {
-                buffer.append(value);
+                buffer.append(ArrayUtils.deepToString(value));
             } else {
                 buffer.append("(this Map)");
             }
diff --git a/core/java/android/util/FeatureFlagUtils.java b/core/java/android/util/FeatureFlagUtils.java
index 1d89628..fac699e 100644
--- a/core/java/android/util/FeatureFlagUtils.java
+++ b/core/java/android/util/FeatureFlagUtils.java
@@ -45,7 +45,6 @@
     static {
         DEFAULT_FLAGS = new HashMap<>();
         DEFAULT_FLAGS.put("settings_audio_switcher", "true");
-        DEFAULT_FLAGS.put("settings_dynamic_homepage", "true");
         DEFAULT_FLAGS.put("settings_mobile_network_v2", "true");
         DEFAULT_FLAGS.put("settings_network_and_internet_v2", "false");
         DEFAULT_FLAGS.put("settings_slice_injection", "true");
diff --git a/core/java/android/util/MemoryIntArray.java b/core/java/android/util/MemoryIntArray.java
index d5bec0f..74fea3f 100644
--- a/core/java/android/util/MemoryIntArray.java
+++ b/core/java/android/util/MemoryIntArray.java
@@ -235,7 +235,7 @@
         return MAX_SIZE;
     }
 
-    public static final Parcelable.Creator<MemoryIntArray> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<MemoryIntArray> CREATOR =
             new Parcelable.Creator<MemoryIntArray>() {
         @Override
         public MemoryIntArray createFromParcel(Parcel parcel) {
diff --git a/core/java/android/util/MergedConfiguration.java b/core/java/android/util/MergedConfiguration.java
index ae66050..2399ada 100644
--- a/core/java/android/util/MergedConfiguration.java
+++ b/core/java/android/util/MergedConfiguration.java
@@ -74,7 +74,7 @@
         return 0;
     }
 
-    public static final Creator<MergedConfiguration> CREATOR = new Creator<MergedConfiguration>() {
+    public static final @android.annotation.NonNull Creator<MergedConfiguration> CREATOR = new Creator<MergedConfiguration>() {
         @Override
         public MergedConfiguration createFromParcel(Parcel in) {
             return new MergedConfiguration(in);
diff --git a/core/java/android/util/RecurrenceRule.java b/core/java/android/util/RecurrenceRule.java
index 209a5912..9c60228 100644
--- a/core/java/android/util/RecurrenceRule.java
+++ b/core/java/android/util/RecurrenceRule.java
@@ -140,7 +140,7 @@
         return false;
     }
 
-    public static final Parcelable.Creator<RecurrenceRule> CREATOR = new Parcelable.Creator<RecurrenceRule>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<RecurrenceRule> CREATOR = new Parcelable.Creator<RecurrenceRule>() {
         @Override
         public RecurrenceRule createFromParcel(Parcel source) {
             return new RecurrenceRule(source);
diff --git a/core/java/android/view/AbsSavedState.java b/core/java/android/view/AbsSavedState.java
index 6b616c0..009898e 100644
--- a/core/java/android/view/AbsSavedState.java
+++ b/core/java/android/view/AbsSavedState.java
@@ -80,7 +80,7 @@
         dest.writeParcelable(mSuperState, flags);
     }
 
-    public static final Parcelable.Creator<AbsSavedState> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AbsSavedState> CREATOR
             = new Parcelable.ClassLoaderCreator<AbsSavedState>() {
 
         @Override
diff --git a/core/java/android/view/AppTransitionAnimationSpec.java b/core/java/android/view/AppTransitionAnimationSpec.java
index 6585e40..4c0ed52 100644
--- a/core/java/android/view/AppTransitionAnimationSpec.java
+++ b/core/java/android/view/AppTransitionAnimationSpec.java
@@ -44,7 +44,7 @@
         dest.writeParcelable(buffer, 0);
     }
 
-    public static final Parcelable.Creator<AppTransitionAnimationSpec> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AppTransitionAnimationSpec> CREATOR
             = new Parcelable.Creator<AppTransitionAnimationSpec>() {
         public AppTransitionAnimationSpec createFromParcel(Parcel in) {
             return new AppTransitionAnimationSpec(in);
diff --git a/core/java/android/view/Display.java b/core/java/android/view/Display.java
index 94a9a1c..91c85e7 100644
--- a/core/java/android/view/Display.java
+++ b/core/java/android/view/Display.java
@@ -1375,7 +1375,7 @@
         }
 
         @SuppressWarnings("hiding")
-        public static final Parcelable.Creator<Mode> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<Mode> CREATOR
                 = new Parcelable.Creator<Mode>() {
             @Override
             public Mode createFromParcel(Parcel in) {
@@ -1504,7 +1504,7 @@
             return hash;
         }
 
-        public static final Creator<HdrCapabilities> CREATOR = new Creator<HdrCapabilities>() {
+        public static final @android.annotation.NonNull Creator<HdrCapabilities> CREATOR = new Creator<HdrCapabilities>() {
             @Override
             public HdrCapabilities createFromParcel(Parcel source) {
                 return new HdrCapabilities(source);
diff --git a/core/java/android/view/DisplayAddress.java b/core/java/android/view/DisplayAddress.java
index 17ea4c4..1360815 100644
--- a/core/java/android/view/DisplayAddress.java
+++ b/core/java/android/view/DisplayAddress.java
@@ -109,7 +109,7 @@
             mPhysicalDisplayId = physicalDisplayId;
         }
 
-        public static final Parcelable.Creator<Physical> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<Physical> CREATOR =
                 new Parcelable.Creator<Physical>() {
                     @Override
                     public Physical createFromParcel(Parcel in) {
@@ -153,7 +153,7 @@
             mMacAddress = macAddress;
         }
 
-        public static final Parcelable.Creator<Network> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<Network> CREATOR =
                 new Parcelable.Creator<Network>() {
                     @Override
                     public Network createFromParcel(Parcel in) {
diff --git a/core/java/android/view/DisplayCutout.java b/core/java/android/view/DisplayCutout.java
index e9f1edf..610f7ed 100644
--- a/core/java/android/view/DisplayCutout.java
+++ b/core/java/android/view/DisplayCutout.java
@@ -233,6 +233,9 @@
     /**
      * Creates a DisplayCutout instance.
      *
+     * <p>Note that this is only useful for tests. For production code, developers should always
+     * use a {@link DisplayCutout} obtained from the system.</p>
+     *
      * @param safeInsets the insets from each edge which avoid the display cutout as returned by
      *                   {@link #getSafeInsetTop()} etc.
      * @param boundLeft the left bounding rect of the display cutout in pixels. If null is passed,
@@ -253,6 +256,9 @@
     /**
      * Creates a DisplayCutout instance.
      *
+     * <p>Note that this is only useful for tests. For production code, developers should always
+     * use a {@link DisplayCutout} obtained from the system.</p>
+     *
      * @param safeInsets the insets from each edge which avoid the display cutout as returned by
      *                   {@link #getSafeInsetTop()} etc.
      * @param boundingRects the bounding rects of the display cutouts as returned by
@@ -765,7 +771,7 @@
             mInner = readCutoutFromParcel(in);
         }
 
-        public static final Creator<ParcelableWrapper> CREATOR = new Creator<ParcelableWrapper>() {
+        public static final @android.annotation.NonNull Creator<ParcelableWrapper> CREATOR = new Creator<ParcelableWrapper>() {
             @Override
             public ParcelableWrapper createFromParcel(Parcel in) {
                 return new ParcelableWrapper(readCutoutFromParcel(in));
diff --git a/core/java/android/view/DisplayEventReceiver.java b/core/java/android/view/DisplayEventReceiver.java
index 3e8002f..60daddd 100644
--- a/core/java/android/view/DisplayEventReceiver.java
+++ b/core/java/android/view/DisplayEventReceiver.java
@@ -156,6 +156,17 @@
     }
 
     /**
+     * Called when a display config changed event is received.
+     *
+     * @param timestampNanos The timestamp of the event, in the {@link System#nanoTime()}
+     * timebase.
+     * @param physicalDisplayId Stable display ID that uniquely describes a (display, port) pair.
+     * @param configId The new config Id
+     */
+    public void onConfigChanged(long timestampNanos, long physicalDisplayId, int configId) {
+    }
+
+    /**
      * Schedules a single vertical sync pulse to be delivered when the next
      * display frame begins.
      */
@@ -182,4 +193,11 @@
     private void dispatchHotplug(long timestampNanos, long physicalDisplayId, boolean connected) {
         onHotplug(timestampNanos, physicalDisplayId, connected);
     }
+
+    // Called from native code.
+    @SuppressWarnings("unused")
+    private void dispatchConfigChanged(long timestampNanos, long physicalDisplayId, int configId) {
+        onConfigChanged(timestampNanos, physicalDisplayId, configId);
+    }
+
 }
diff --git a/core/java/android/view/DisplayInfo.java b/core/java/android/view/DisplayInfo.java
index 3aa779b..11ed357 100644
--- a/core/java/android/view/DisplayInfo.java
+++ b/core/java/android/view/DisplayInfo.java
@@ -271,7 +271,7 @@
     // TODO (b/114338689): Remove the flag and use IWindowManager#getRemoveContentMode
     public int removeMode = Display.REMOVE_MODE_MOVE_CONTENT_TO_PRIMARY;
 
-    public static final Creator<DisplayInfo> CREATOR = new Creator<DisplayInfo>() {
+    public static final @android.annotation.NonNull Creator<DisplayInfo> CREATOR = new Creator<DisplayInfo>() {
         @Override
         public DisplayInfo createFromParcel(Parcel source) {
             return new DisplayInfo(source);
diff --git a/core/java/android/view/DragAndDropPermissions.java b/core/java/android/view/DragAndDropPermissions.java
index c198e1f..e72ff38 100644
--- a/core/java/android/view/DragAndDropPermissions.java
+++ b/core/java/android/view/DragAndDropPermissions.java
@@ -117,7 +117,7 @@
         }
     }
 
-    public static final Parcelable.Creator<DragAndDropPermissions> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<DragAndDropPermissions> CREATOR =
             new Parcelable.Creator<DragAndDropPermissions> () {
         @Override
         public DragAndDropPermissions createFromParcel(Parcel source) {
diff --git a/core/java/android/view/DragEvent.java b/core/java/android/view/DragEvent.java
index bd4dda2..2a43bcc 100644
--- a/core/java/android/view/DragEvent.java
+++ b/core/java/android/view/DragEvent.java
@@ -528,7 +528,7 @@
     /**
      * A container for creating a DragEvent from a Parcel.
      */
-    public static final Parcelable.Creator<DragEvent> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<DragEvent> CREATOR =
         new Parcelable.Creator<DragEvent>() {
         public DragEvent createFromParcel(Parcel in) {
             DragEvent event = DragEvent.obtain();
diff --git a/core/java/android/view/GestureExclusionTracker.java b/core/java/android/view/GestureExclusionTracker.java
new file mode 100644
index 0000000..8eccc04
--- /dev/null
+++ b/core/java/android/view/GestureExclusionTracker.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.graphics.Rect;
+
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Used by {@link ViewRootImpl} to track system gesture exclusion rects reported by views.
+ */
+class GestureExclusionTracker {
+    private boolean mGestureExclusionViewsChanged = false;
+    private List<GestureExclusionViewInfo> mGestureExclusionViewInfos = new ArrayList<>();
+    private List<Rect> mGestureExclusionRects = Collections.emptyList();
+
+    public void updateRectsForView(@NonNull View view) {
+        boolean found = false;
+        final Iterator<GestureExclusionViewInfo> i = mGestureExclusionViewInfos.iterator();
+        while (i.hasNext()) {
+            final GestureExclusionViewInfo info = i.next();
+            final View v = info.getView();
+            if (v == null || !v.isAttachedToWindow()) {
+                mGestureExclusionViewsChanged = true;
+                i.remove();
+                continue;
+            }
+            if (v == view) {
+                found = true;
+                info.mDirty = true;
+                break;
+            }
+        }
+        if (!found && view.isAttachedToWindow()) {
+            mGestureExclusionViewInfos.add(new GestureExclusionViewInfo(view));
+            mGestureExclusionViewsChanged = true;
+        }
+    }
+
+    @Nullable
+    public List<Rect> computeChangedRects() {
+        boolean changed = false;
+        final Iterator<GestureExclusionViewInfo> i = mGestureExclusionViewInfos.iterator();
+        final List<Rect> rects = new ArrayList<>();
+        while (i.hasNext()) {
+            final GestureExclusionViewInfo info = i.next();
+            switch (info.update()) {
+                case GestureExclusionViewInfo.CHANGED:
+                    changed = true;
+                    // Deliberate fall-through
+                case GestureExclusionViewInfo.UNCHANGED:
+                    rects.addAll(info.mExclusionRects);
+                    break;
+                case GestureExclusionViewInfo.GONE:
+                    mGestureExclusionViewsChanged = true;
+                    i.remove();
+                    break;
+            }
+        }
+        if (changed || mGestureExclusionViewsChanged) {
+            mGestureExclusionViewsChanged = false;
+            if (!mGestureExclusionRects.equals(rects)) {
+                mGestureExclusionRects = rects;
+                return rects;
+            }
+        }
+        return null;
+    }
+
+    private static class GestureExclusionViewInfo {
+        public static final int CHANGED = 0;
+        public static final int UNCHANGED = 1;
+        public static final int GONE = 2;
+
+        private final WeakReference<View> mView;
+        boolean mDirty = true;
+        List<Rect> mExclusionRects = Collections.emptyList();
+
+        GestureExclusionViewInfo(View view) {
+            mView = new WeakReference<>(view);
+        }
+
+        public View getView() {
+            return mView.get();
+        }
+
+        public int update() {
+            final View excludedView = getView();
+            if (excludedView == null || !excludedView.isAttachedToWindow()) return GONE;
+            final List<Rect> localRects = excludedView.getSystemGestureExclusionRects();
+            final List<Rect> newRects = new ArrayList<>(localRects.size());
+            for (Rect src : localRects) {
+                Rect mappedRect = new Rect(src);
+                ViewParent p = excludedView.getParent();
+                if (p != null && p.getChildVisibleRect(excludedView, mappedRect, null)) {
+                    newRects.add(mappedRect);
+                }
+            }
+
+            if (mExclusionRects.equals(localRects)) return UNCHANGED;
+            mExclusionRects = newRects;
+            return CHANGED;
+        }
+    }
+}
diff --git a/core/java/android/view/IRecentsAnimationController.aidl b/core/java/android/view/IRecentsAnimationController.aidl
index 94b9bc0..b1f934a 100644
--- a/core/java/android/view/IRecentsAnimationController.aidl
+++ b/core/java/android/view/IRecentsAnimationController.aidl
@@ -33,6 +33,7 @@
      * Takes a screenshot of the task associated with the given {@param taskId}. Only valid for the
      * current set of task ids provided to the handler.
      */
+    @UnsupportedAppUsage
     ActivityManager.TaskSnapshot screenshotTask(int taskId);
 
     /**
@@ -41,6 +42,7 @@
      * the home activity should be moved to the top. Otherwise, the home activity is hidden and the
      * user is returned to the app.
      */
+    @UnsupportedAppUsage
     void finish(boolean moveHomeToTop);
 
     /**
@@ -50,6 +52,7 @@
      * may register the recents animation input consumer prior to starting the recents animation
      * and then enable it mid-animation to start receiving touch events.
      */
+    @UnsupportedAppUsage
     void setInputConsumerEnabled(boolean enabled);
 
     /**
@@ -58,6 +61,7 @@
     * they can control the SystemUI flags, otherwise the SystemUI flags from home activity will be
     * taken.
     */
+    @UnsupportedAppUsage
     void setAnimationTargetsBehindSystemBars(boolean behindSystemBars);
 
     /**
diff --git a/core/java/android/view/IRecentsAnimationRunner.aidl b/core/java/android/view/IRecentsAnimationRunner.aidl
index 4cdf664..6e382f4 100644
--- a/core/java/android/view/IRecentsAnimationRunner.aidl
+++ b/core/java/android/view/IRecentsAnimationRunner.aidl
@@ -33,6 +33,7 @@
      * wallpaper not drawing in time, or the handler not finishing the animation within a predefined
      * amount of time.
      */
+    @UnsupportedAppUsage
     void onAnimationCanceled() = 1;
 
     /**
@@ -42,6 +43,7 @@
      * @param minimizedHomeBounds Specifies the bounds of the minimized home app, will be
      *                            {@code null} if the device is not currently in split screen
      */
+    @UnsupportedAppUsage
     void onAnimationStart(in IRecentsAnimationController controller,
             in RemoteAnimationTarget[] apps, in Rect homeContentInsets,
             in Rect minimizedHomeBounds) = 2;
diff --git a/core/java/android/view/IRemoteAnimationFinishedCallback.aidl b/core/java/android/view/IRemoteAnimationFinishedCallback.aidl
index ae58b22..a99162b 100644
--- a/core/java/android/view/IRemoteAnimationFinishedCallback.aidl
+++ b/core/java/android/view/IRemoteAnimationFinishedCallback.aidl
@@ -23,5 +23,6 @@
  * {@hide}
  */
 interface IRemoteAnimationFinishedCallback {
+    @UnsupportedAppUsage
     void onAnimationFinished();
 }
diff --git a/core/java/android/view/IRemoteAnimationRunner.aidl b/core/java/android/view/IRemoteAnimationRunner.aidl
index 1350ebf..73b023c 100644
--- a/core/java/android/view/IRemoteAnimationRunner.aidl
+++ b/core/java/android/view/IRemoteAnimationRunner.aidl
@@ -33,6 +33,7 @@
      * @param apps The list of apps to animate.
      * @param finishedCallback The callback to invoke when the animation is finished.
      */
+    @UnsupportedAppUsage
     void onAnimationStart(in RemoteAnimationTarget[] apps,
             in IRemoteAnimationFinishedCallback finishedCallback);
 
@@ -40,5 +41,6 @@
      * Called when the animation was cancelled. From this point on, any updates onto the leashes
      * won't have any effect anymore.
      */
+    @UnsupportedAppUsage
     void onAnimationCancelled();
 }
diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl
index 5dc54a5..e32c4e1 100644
--- a/core/java/android/view/IWindowManager.aidl
+++ b/core/java/android/view/IWindowManager.aidl
@@ -74,10 +74,13 @@
 
     IWindowSession openSession(in IWindowSessionCallback callback);
 
+    @UnsupportedAppUsage
     void getInitialDisplaySize(int displayId, out Point size);
+    @UnsupportedAppUsage
     void getBaseDisplaySize(int displayId, out Point size);
     void setForcedDisplaySize(int displayId, int width, int height);
     void clearForcedDisplaySize(int displayId);
+    @UnsupportedAppUsage
     int getInitialDisplayDensity(int displayId);
     int getBaseDisplayDensity(int displayId);
     void setForcedDisplayDensityForUser(int displayId, int density, int userId);
@@ -97,17 +100,21 @@
      * used for recents, where generating the thumbnails of the specs takes a non-trivial amount of
      * time, so we want to move that off the critical path for starting the new activity.
      */
+    @UnsupportedAppUsage
     void overridePendingAppTransitionMultiThumbFuture(
             IAppTransitionAnimationSpecsFuture specsFuture, IRemoteCallback startedCallback,
             boolean scaleUp, int displayId);
+    @UnsupportedAppUsage
     void overridePendingAppTransitionRemote(in RemoteAnimationAdapter remoteAnimationAdapter,
             int displayId);
+    @UnsupportedAppUsage
     void executeAppTransition();
 
     /**
       * Used by system ui to report that recents has shown itself.
       * @deprecated to be removed once prebuilts are updated
       */
+    @UnsupportedAppUsage
     void endProlongedAnimations();
 
     void startFreezingScreen(int exitAnim, int enterAnim);
@@ -119,7 +126,9 @@
     /** @deprecated use Activity.setShowWhenLocked instead. */
     void reenableKeyguard(IBinder token, int userId);
     void exitKeyguardSecurely(IOnKeyguardExitResult callback);
+    @UnsupportedAppUsage
     boolean isKeyguardLocked();
+    @UnsupportedAppUsage
     boolean isKeyguardSecure();
     void dismissKeyguard(IKeyguardDismissCallback callback, CharSequence message);
 
@@ -129,9 +138,13 @@
     void closeSystemDialogs(String reason);
 
     // These can only be called with the SET_ANIMATON_SCALE permission.
+    @UnsupportedAppUsage
     float getAnimationScale(int which);
+    @UnsupportedAppUsage
     float[] getAnimationScales();
+    @UnsupportedAppUsage
     void setAnimationScale(int which, float scale);
+    @UnsupportedAppUsage
     void setAnimationScales(in float[] scales);
 
     float getCurrentAnimatorScale();
@@ -150,6 +163,7 @@
     // should be enabled.  The 'enabled' value is null or blank for
     // the system default (differs per build variant) or any valid
     // boolean string as parsed by SystemProperties.getBoolean().
+    @UnsupportedAppUsage
     void setStrictModeVisualIndicatorPreference(String enabled);
 
     /**
@@ -188,6 +202,7 @@
      * Remove a rotation watcher set using watchRotation.
      * @hide
      */
+    @UnsupportedAppUsage
     void removeRotationWatcher(IRotationWatcher watcher);
 
     /**
@@ -203,12 +218,14 @@
      * Equivalent to calling {@link #freezeDisplayRotation(int, int)} with {@link
      * android.view.Display#DEFAULT_DISPLAY} and given rotation.
      */
+    @UnsupportedAppUsage
     void freezeRotation(int rotation);
 
     /**
      * Equivalent to calling {@link #thawDisplayRotation(int)} with {@link
      * android.view.Display#DEFAULT_DISPLAY}.
      */
+    @UnsupportedAppUsage
     void thawRotation();
 
     /**
@@ -286,11 +303,13 @@
     /**
      * Called by System UI to notify of changes to the visibility and height of the shelf.
      */
+    @UnsupportedAppUsage
     void setShelfHeight(boolean visible, int shelfHeight);
 
     /**
      * Called by System UI to enable or disable haptic feedback on the navigation bar buttons.
      */
+    @UnsupportedAppUsage
     void setNavBarVirtualKeyHapticFeedbackEnabled(boolean enabled);
 
     /**
@@ -298,6 +317,7 @@
      *
      * @param displayId the id of display to check if there is a software navigation bar.
      */
+    @UnsupportedAppUsage
     boolean hasNavigationBar(int displayId);
 
     /**
@@ -308,11 +328,13 @@
     /**
      * Lock the device immediately with the specified options (can be null).
      */
+    @UnsupportedAppUsage
     void lockNow(in Bundle options);
 
     /**
      * Device is in safe mode.
      */
+    @UnsupportedAppUsage
     boolean isSafeModeEnabled();
 
     /**
@@ -340,6 +362,7 @@
      * @return the dock side the current docked stack is at; must be one of the
      *         WindowManagerGlobal.DOCKED_* values
      */
+    @UnsupportedAppUsage
     int getDockedStackSide();
 
     /**
@@ -352,6 +375,7 @@
      * Registers a listener that will be called when the dock divider changes its visibility or when
      * the docked stack gets added/removed.
      */
+    @UnsupportedAppUsage
     void registerDockedStackListener(IDockedStackListener listener);
 
     /**
@@ -378,6 +402,7 @@
     /**
      * Retrieves the current stable insets from the primary display.
      */
+    @UnsupportedAppUsage
     void getStableInsets(int displayId, out Rect outInsets);
 
     /**
@@ -400,6 +425,7 @@
     /**
      * Create an input consumer by name and display id.
      */
+    @UnsupportedAppUsage
     void createInputConsumer(IBinder token, String name, int displayId,
         out InputChannel inputChannel);
 
@@ -407,6 +433,7 @@
      * Destroy an input consumer by name and display id.
      * This method will also dispose the input channels associated with that InputConsumer.
      */
+    @UnsupportedAppUsage
     boolean destroyInputConsumer(String name, int displayId);
 
     /**
diff --git a/core/java/android/view/IWindowSession.aidl b/core/java/android/view/IWindowSession.aidl
index 240aad5..1fcd432 100644
--- a/core/java/android/view/IWindowSession.aidl
+++ b/core/java/android/view/IWindowSession.aidl
@@ -46,6 +46,7 @@
     int addToDisplayWithoutInputChannel(IWindow window, int seq, in WindowManager.LayoutParams attrs,
             in int viewVisibility, in int layerStackId, out Rect outContentInsets,
             out Rect outStableInsets, out InsetsState insetsState);
+    @UnsupportedAppUsage
     void remove(IWindow window);
 
     /**
@@ -122,6 +123,7 @@
      * completely transparent, allowing it to work with the surface flinger
      * to optimize compositing of this part of the window.
      */
+    @UnsupportedAppUsage
     void setTransparentRegion(IWindow window, in Region region);
 
     /**
@@ -143,11 +145,15 @@
      */
     void getDisplayFrame(IWindow window, out Rect outDisplayFrame);
 
+    @UnsupportedAppUsage
     void finishDrawing(IWindow window);
 
+    @UnsupportedAppUsage
     void setInTouchMode(boolean showFocus);
+    @UnsupportedAppUsage
     boolean getInTouchMode();
 
+    @UnsupportedAppUsage
     boolean performHapticFeedback(int effectId, boolean always);
 
     /**
@@ -166,6 +172,7 @@
      * @param data Data transferred by drag and drop
      * @return Token of drag operation which will be passed to cancelDragAndDrop.
      */
+    @UnsupportedAppUsage
     IBinder performDrag(IWindow window, int flags, in SurfaceControl surface, int touchSource,
             float touchX, float touchY, float thumbCenterX, float thumbCenterY, in ClipData data);
 
@@ -199,6 +206,7 @@
      */
     void setWallpaperPosition(IBinder windowToken, float x, float y, float xstep, float ystep);
 
+    @UnsupportedAppUsage
     void wallpaperOffsetsComplete(IBinder window);
 
     /**
@@ -209,6 +217,7 @@
     Bundle sendWallpaperCommand(IBinder window, String action, int x, int y,
             int z, in Bundle extras, boolean sync);
 
+    @UnsupportedAppUsage
     void wallpaperCommandComplete(IBinder window, in Bundle result);
 
     /**
diff --git a/core/java/android/view/InputChannel.java b/core/java/android/view/InputChannel.java
index 84c8e7a..af2b992 100644
--- a/core/java/android/view/InputChannel.java
+++ b/core/java/android/view/InputChannel.java
@@ -35,7 +35,7 @@
     private static final boolean DEBUG = false;
     
     @UnsupportedAppUsage
-    public static final Parcelable.Creator<InputChannel> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<InputChannel> CREATOR
             = new Parcelable.Creator<InputChannel>() {
         public InputChannel createFromParcel(Parcel source) {
             InputChannel result = new InputChannel();
diff --git a/core/java/android/view/InputDevice.java b/core/java/android/view/InputDevice.java
index 868a9de..e723f91 100644
--- a/core/java/android/view/InputDevice.java
+++ b/core/java/android/view/InputDevice.java
@@ -397,7 +397,7 @@
 
     private static final int MAX_RANGES = 1000;
 
-    public static final Parcelable.Creator<InputDevice> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<InputDevice> CREATOR =
             new Parcelable.Creator<InputDevice>() {
         public InputDevice createFromParcel(Parcel in) {
             return new InputDevice(in);
diff --git a/core/java/android/view/InputEvent.java b/core/java/android/view/InputEvent.java
index c2848d4..4b88a6a 100644
--- a/core/java/android/view/InputEvent.java
+++ b/core/java/android/view/InputEvent.java
@@ -237,7 +237,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<InputEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<InputEvent> CREATOR
             = new Parcelable.Creator<InputEvent>() {
         public InputEvent createFromParcel(Parcel in) {
             int token = in.readInt();
diff --git a/core/java/android/view/InsetsAnimationControlImpl.java b/core/java/android/view/InsetsAnimationControlImpl.java
index dd88e3c..50ef91f 100644
--- a/core/java/android/view/InsetsAnimationControlImpl.java
+++ b/core/java/android/view/InsetsAnimationControlImpl.java
@@ -20,6 +20,7 @@
 import static android.view.InsetsState.INSET_SIDE_LEFT;
 import static android.view.InsetsState.INSET_SIDE_RIGHT;
 import static android.view.InsetsState.INSET_SIDE_TOP;
+import static android.view.InsetsState.toPublicType;
 
 import android.annotation.Nullable;
 import android.graphics.Insets;
@@ -33,6 +34,7 @@
 import android.view.InsetsState.InsetSide;
 import android.view.SyncRtSurfaceTransactionApplier.SurfaceParams;
 import android.view.WindowInsets.Type.InsetType;
+import android.view.WindowInsetsAnimationListener.InsetsAnimation;
 import android.view.WindowManager.LayoutParams;
 
 import com.android.internal.annotations.VisibleForTesting;
@@ -66,8 +68,12 @@
     private final Supplier<SyncRtSurfaceTransactionApplier> mTransactionApplierSupplier;
     private final InsetsController mController;
     private final WindowInsetsAnimationListener.InsetsAnimation mAnimation;
+    private final Rect mFrame;
     private Insets mCurrentInsets;
     private Insets mPendingInsets;
+    private boolean mFinished;
+    private boolean mCancelled;
+    private int mFinishedShownTypes;
 
     @VisibleForTesting
     public InsetsAnimationControlImpl(SparseArray<InsetsSourceConsumer> consumers, Rect frame,
@@ -86,6 +92,7 @@
                 null /* typeSideMap */);
         mShownInsets = calculateInsets(mInitialInsetsState, frame, consumers, true /* shown */,
                 mTypeSideMap);
+        mFrame = new Rect(frame);
         buildTypeSourcesMap(mTypeSideMap, mSideSourceMap, mConsumers);
 
         // TODO: Check for controllability first and wait for IME if needed.
@@ -119,12 +126,26 @@
 
     @Override
     public void changeInsets(Insets insets) {
+        if (mFinished) {
+            throw new IllegalStateException(
+                    "Can't change insets on an animation that is finished.");
+        }
+        if (mCancelled) {
+            throw new IllegalStateException(
+                    "Can't change insets on an animation that is cancelled.");
+        }
         mPendingInsets = sanitize(insets);
         mController.scheduleApplyChangeInsets();
     }
 
     @VisibleForTesting
-    public void applyChangeInsets(InsetsState state) {
+    /**
+     * @return Whether the finish callback of this animation should be invoked.
+     */
+    public boolean applyChangeInsets(InsetsState state) {
+        if (mCancelled) {
+            return false;
+        }
         final Insets offset = Insets.subtract(mShownInsets, mPendingInsets);
         ArrayList<SurfaceParams> params = new ArrayList<>();
         if (offset.left != 0) {
@@ -144,13 +165,40 @@
         SyncRtSurfaceTransactionApplier applier = mTransactionApplierSupplier.get();
         applier.scheduleApply(params.toArray(new SurfaceParams[params.size()]));
         mCurrentInsets = mPendingInsets;
+        if (mFinished) {
+            mController.notifyFinished(this, mFinishedShownTypes);
+        }
+        return mFinished;
     }
 
     @Override
     public void finish(int shownTypes) {
-        // TODO
+        if (mCancelled) {
+            return;
+        }
+        InsetsState state = new InsetsState(mController.getState());
+        for (int i = mConsumers.size() - 1; i >= 0; i--) {
+            InsetsSourceConsumer consumer = mConsumers.valueAt(i);
+            boolean visible = (shownTypes & toPublicType(consumer.getType())) != 0;
+            state.getSource(consumer.getType()).setVisible(visible);
+        }
+        Insets insets = getInsetsFromState(state, mFrame, null /* typeSideMap */);
+        changeInsets(insets);
+        mFinished = true;
+        mFinishedShownTypes = shownTypes;
+    }
 
-        mController.dispatchAnimationFinished(mAnimation);
+    @VisibleForTesting
+    public void onCancelled() {
+        if (mFinished) {
+            return;
+        }
+        mCancelled = true;
+        mListener.onCancelled();
+    }
+
+    InsetsAnimation getAnimation() {
+        return mAnimation;
     }
 
     private Insets calculateInsets(InsetsState state, Rect frame,
@@ -225,4 +273,3 @@
         }
     }
 }
-
diff --git a/core/java/android/view/InsetsController.java b/core/java/android/view/InsetsController.java
index 2586000..08f2e8d 100644
--- a/core/java/android/view/InsetsController.java
+++ b/core/java/android/view/InsetsController.java
@@ -17,6 +17,8 @@
 package android.view;
 
 import static android.view.InsetsState.TYPE_IME;
+import static android.view.InsetsState.toPublicType;
+import static android.view.WindowInsets.Type.all;
 
 import android.animation.Animator;
 import android.animation.AnimatorListenerAdapter;
@@ -99,6 +101,7 @@
 
     private final SparseArray<InsetsSourceControl> mTmpControlArray = new SparseArray<>();
     private final ArrayList<InsetsAnimationControlImpl> mAnimationControls = new ArrayList<>();
+    private final ArrayList<InsetsAnimationControlImpl> mTmpFinishedControls = new ArrayList<>();
     private WindowInsets mLastInsets;
 
     private boolean mAnimCallbackScheduled;
@@ -107,7 +110,6 @@
 
     private final Rect mLastLegacyContentInsets = new Rect();
     private final Rect mLastLegacyStableInsets = new Rect();
-    private ObjectAnimator mAnimator;
     private @AnimationDirection int mAnimationDirection;
 
     private int mPendingTypesToShow;
@@ -122,19 +124,29 @@
                 return;
             }
 
+            mTmpFinishedControls.clear();
             InsetsState state = new InsetsState(mState, true /* copySources */);
             for (int i = mAnimationControls.size() - 1; i >= 0; i--) {
-                mAnimationControls.get(i).applyChangeInsets(state);
+                InsetsAnimationControlImpl control = mAnimationControls.get(i);
+                if (mAnimationControls.get(i).applyChangeInsets(state)) {
+                    mTmpFinishedControls.add(control);
+                }
             }
+
             WindowInsets insets = state.calculateInsets(mFrame, mLastInsets.isRound(),
                     mLastInsets.shouldAlwaysConsumeNavBar(), mLastInsets.getDisplayCutout(),
                     mLastLegacyContentInsets, mLastLegacyStableInsets, mLastLegacySoftInputMode,
                     null /* typeSideMap */);
             mViewRoot.mView.dispatchWindowInsetsAnimationProgress(insets);
+
+            for (int i = mTmpFinishedControls.size() - 1; i >= 0; i--) {
+                dispatchAnimationFinished(mTmpFinishedControls.get(i).getAnimation());
+            }
         };
     }
 
-    void onFrameChanged(Rect frame) {
+    @VisibleForTesting
+    public void onFrameChanged(Rect frame) {
         if (mFrame.equals(frame)) {
             return;
         }
@@ -279,7 +291,8 @@
             // nothing to animate.
             return;
         }
-        // TODO: Check whether we already have a controller.
+        cancelExistingControllers(types);
+
         final ArraySet<Integer> internalTypes = mState.toInternalType(types);
         final SparseArray<InsetsSourceConsumer> consumers = new SparseArray<>();
 
@@ -321,7 +334,7 @@
                     // Show request
                     switch(consumer.requestShow(fromIme)) {
                         case ShowResult.SHOW_IMMEDIATELY:
-                            typesReady |= InsetsState.toPublicType(TYPE_IME);
+                            typesReady |= InsetsState.toPublicType(consumer.getType());
                             break;
                         case ShowResult.SHOW_DELAYED:
                             isReady = false;
@@ -365,6 +378,36 @@
         return typesReady;
     }
 
+    private void cancelExistingControllers(@InsetType int types) {
+        for (int i = mAnimationControls.size() - 1; i >= 0; i--) {
+            InsetsAnimationControlImpl control = mAnimationControls.get(i);
+            if ((control.getTypes() & types) != 0) {
+                cancelAnimation(control);
+            }
+        }
+    }
+
+    @VisibleForTesting
+    public void notifyFinished(InsetsAnimationControlImpl controller, int shownTypes) {
+        mAnimationControls.remove(controller);
+        hideDirectly(controller.getTypes() & ~shownTypes);
+        showDirectly(controller.getTypes() & shownTypes);
+    }
+
+    void notifyControlRevoked(InsetsSourceConsumer consumer) {
+        for (int i = mAnimationControls.size() - 1; i >= 0; i--) {
+            InsetsAnimationControlImpl control = mAnimationControls.get(i);
+            if ((control.getTypes() & toPublicType(consumer.getType())) != 0) {
+                cancelAnimation(control);
+            }
+        }
+    }
+
+    private void cancelAnimation(InsetsAnimationControlImpl control) {
+        control.onCancelled();
+        mAnimationControls.remove(control);
+    }
+
     private void applyLocalVisibilityOverride() {
         for (int i = mSourceConsumers.size() - 1; i >= 0; i--) {
             final InsetsSourceConsumer controller = mSourceConsumers.valueAt(i);
@@ -455,8 +498,13 @@
         }
 
         WindowInsetsAnimationControlListener listener = new WindowInsetsAnimationControlListener() {
+
+            private WindowInsetsAnimationController mController;
+            private ObjectAnimator mAnimator;
+
             @Override
             public void onReady(WindowInsetsAnimationController controller, int types) {
+                mController = controller;
                 if (show) {
                     showDirectly(types);
                 } else {
@@ -474,10 +522,6 @@
                         : ANIMATION_DURATION_HIDE_MS);
                 mAnimator.setInterpolator(INTERPOLATOR);
                 mAnimator.addListener(new AnimatorListenerAdapter() {
-                    @Override
-                    public void onAnimationCancel(Animator animation) {
-                        onAnimationFinish();
-                    }
 
                     @Override
                     public void onAnimationEnd(Animator animation) {
@@ -488,15 +532,15 @@
             }
 
             @Override
-            public void onCancelled() {}
+            public void onCancelled() {
+                mAnimator.cancel();
+            }
 
             private void onAnimationFinish() {
                 mAnimationDirection = DIRECTION_NONE;
+                mController.finish(show ? types : 0);
             }
         };
-        // TODO: Instead of clearing this here, properly wire up
-        // InsetsAnimationControlImpl.finish() to remove this from mAnimationControls.
-        mAnimationControls.clear();
 
         // Show/hide animations always need to be relative to the display frame, in order that shown
         // and hidden state insets are correct.
@@ -522,10 +566,7 @@
      */
     @VisibleForTesting
     public void cancelExistingAnimation() {
-        mAnimationDirection = DIRECTION_NONE;
-        if (mAnimator != null) {
-            mAnimator.cancel();
-        }
+        cancelExistingControllers(all());
     }
 
     void dump(String prefix, PrintWriter pw) {
diff --git a/core/java/android/view/InsetsSource.java b/core/java/android/view/InsetsSource.java
index fbc72a0..16e00da 100644
--- a/core/java/android/view/InsetsSource.java
+++ b/core/java/android/view/InsetsSource.java
@@ -151,7 +151,7 @@
         dest.writeBoolean(mVisible);
     }
 
-    public static final Creator<InsetsSource> CREATOR = new Creator<InsetsSource>() {
+    public static final @android.annotation.NonNull Creator<InsetsSource> CREATOR = new Creator<InsetsSource>() {
 
         public InsetsSource createFromParcel(Parcel in) {
             return new InsetsSource(in);
diff --git a/core/java/android/view/InsetsSourceConsumer.java b/core/java/android/view/InsetsSourceConsumer.java
index eab83ce..1383463 100644
--- a/core/java/android/view/InsetsSourceConsumer.java
+++ b/core/java/android/view/InsetsSourceConsumer.java
@@ -77,6 +77,9 @@
         if (applyLocalVisibilityOverride()) {
             mController.notifyVisibilityChanged();
         }
+        if (mSourceControl == null) {
+            mController.notifyControlRevoked(this);
+        }
     }
 
     @VisibleForTesting
diff --git a/core/java/android/view/InsetsSourceControl.java b/core/java/android/view/InsetsSourceControl.java
index 9fb6bdb..4940981 100644
--- a/core/java/android/view/InsetsSourceControl.java
+++ b/core/java/android/view/InsetsSourceControl.java
@@ -76,7 +76,7 @@
         dest.writeParcelable(mSurfacePosition, 0 /* flags*/);
     }
 
-    public static final Creator<InsetsSourceControl> CREATOR
+    public static final @android.annotation.NonNull Creator<InsetsSourceControl> CREATOR
             = new Creator<InsetsSourceControl>() {
         public InsetsSourceControl createFromParcel(Parcel in) {
             return new InsetsSourceControl(in);
diff --git a/core/java/android/view/InsetsState.java b/core/java/android/view/InsetsState.java
index 69f86aa..1382fbc 100644
--- a/core/java/android/view/InsetsState.java
+++ b/core/java/android/view/InsetsState.java
@@ -386,7 +386,7 @@
         }
     }
 
-    public static final Creator<InsetsState> CREATOR = new Creator<InsetsState>() {
+    public static final @android.annotation.NonNull Creator<InsetsState> CREATOR = new Creator<InsetsState>() {
 
         public InsetsState createFromParcel(Parcel in) {
             return new InsetsState(in);
diff --git a/core/java/android/view/KeyCharacterMap.java b/core/java/android/view/KeyCharacterMap.java
index 989bf67..bd03348 100644
--- a/core/java/android/view/KeyCharacterMap.java
+++ b/core/java/android/view/KeyCharacterMap.java
@@ -272,7 +272,7 @@
         sDeadKeyCache.put(combination, result);
     }
 
-    public static final Parcelable.Creator<KeyCharacterMap> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<KeyCharacterMap> CREATOR =
             new Parcelable.Creator<KeyCharacterMap>() {
         public KeyCharacterMap createFromParcel(Parcel in) {
             return new KeyCharacterMap(in);
diff --git a/core/java/android/view/KeyEvent.java b/core/java/android/view/KeyEvent.java
index f9a46b1..f700d32 100644
--- a/core/java/android/view/KeyEvent.java
+++ b/core/java/android/view/KeyEvent.java
@@ -3065,7 +3065,7 @@
         return result.toString();
     }
 
-    public static final Parcelable.Creator<KeyEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<KeyEvent> CREATOR
             = new Parcelable.Creator<KeyEvent>() {
         @Override
         public KeyEvent createFromParcel(Parcel in) {
diff --git a/core/java/android/view/KeyboardShortcutGroup.java b/core/java/android/view/KeyboardShortcutGroup.java
index 52e9832..763ca26 100644
--- a/core/java/android/view/KeyboardShortcutGroup.java
+++ b/core/java/android/view/KeyboardShortcutGroup.java
@@ -125,7 +125,7 @@
         dest.writeInt(mSystemGroup ? 1 : 0);
     }
 
-    public static final Creator<KeyboardShortcutGroup> CREATOR =
+    public static final @android.annotation.NonNull Creator<KeyboardShortcutGroup> CREATOR =
             new Creator<KeyboardShortcutGroup>() {
                 public KeyboardShortcutGroup createFromParcel(Parcel source) {
                     return new KeyboardShortcutGroup(source);
diff --git a/core/java/android/view/KeyboardShortcutInfo.java b/core/java/android/view/KeyboardShortcutInfo.java
index c934a4e..2660e74 100644
--- a/core/java/android/view/KeyboardShortcutInfo.java
+++ b/core/java/android/view/KeyboardShortcutInfo.java
@@ -156,7 +156,7 @@
         dest.writeInt(mModifiers);
     }
 
-    public static final Creator<KeyboardShortcutInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<KeyboardShortcutInfo> CREATOR =
             new Creator<KeyboardShortcutInfo>() {
         public KeyboardShortcutInfo createFromParcel(Parcel source) {
             return new KeyboardShortcutInfo(source);
diff --git a/core/java/android/view/MagnificationSpec.java b/core/java/android/view/MagnificationSpec.java
index 956a211..aea337e 100644
--- a/core/java/android/view/MagnificationSpec.java
+++ b/core/java/android/view/MagnificationSpec.java
@@ -146,7 +146,7 @@
         offsetY = parcel.readFloat();
     }
 
-    public static final Creator<MagnificationSpec> CREATOR = new Creator<MagnificationSpec>() {
+    public static final @android.annotation.NonNull Creator<MagnificationSpec> CREATOR = new Creator<MagnificationSpec>() {
         @Override
         public MagnificationSpec[] newArray(int size) {
             return new MagnificationSpec[size];
diff --git a/core/java/android/view/MotionEvent.java b/core/java/android/view/MotionEvent.java
index b6c4cbb..86e94f4 100644
--- a/core/java/android/view/MotionEvent.java
+++ b/core/java/android/view/MotionEvent.java
@@ -3660,7 +3660,7 @@
         return (getButtonState() & button) == button;
     }
 
-    public static final Parcelable.Creator<MotionEvent> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<MotionEvent> CREATOR
             = new Parcelable.Creator<MotionEvent>() {
         public MotionEvent createFromParcel(Parcel in) {
             in.readInt(); // skip token, we already know this is a MotionEvent
diff --git a/core/java/android/view/PointerIcon.java b/core/java/android/view/PointerIcon.java
index c3d13bd..dfe34c8 100644
--- a/core/java/android/view/PointerIcon.java
+++ b/core/java/android/view/PointerIcon.java
@@ -361,7 +361,7 @@
         return mType;
     }
 
-    public static final Parcelable.Creator<PointerIcon> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<PointerIcon> CREATOR
             = new Parcelable.Creator<PointerIcon>() {
         public PointerIcon createFromParcel(Parcel in) {
             int type = in.readInt();
diff --git a/core/java/android/view/RemoteAnimationAdapter.java b/core/java/android/view/RemoteAnimationAdapter.java
index 6f5a85d..bc2fe54 100644
--- a/core/java/android/view/RemoteAnimationAdapter.java
+++ b/core/java/android/view/RemoteAnimationAdapter.java
@@ -129,7 +129,7 @@
         dest.writeBoolean(mChangeNeedsSnapshot);
     }
 
-    public static final Creator<RemoteAnimationAdapter> CREATOR
+    public static final @android.annotation.NonNull Creator<RemoteAnimationAdapter> CREATOR
             = new Creator<RemoteAnimationAdapter>() {
         public RemoteAnimationAdapter createFromParcel(Parcel in) {
             return new RemoteAnimationAdapter(in);
diff --git a/core/java/android/view/RemoteAnimationDefinition.java b/core/java/android/view/RemoteAnimationDefinition.java
index beb1c1d..884cae4 100644
--- a/core/java/android/view/RemoteAnimationDefinition.java
+++ b/core/java/android/view/RemoteAnimationDefinition.java
@@ -139,7 +139,7 @@
         }
     }
 
-    public static final Creator<RemoteAnimationDefinition> CREATOR =
+    public static final @android.annotation.NonNull Creator<RemoteAnimationDefinition> CREATOR =
             new Creator<RemoteAnimationDefinition>() {
         public RemoteAnimationDefinition createFromParcel(Parcel in) {
             return new RemoteAnimationDefinition(in);
@@ -181,7 +181,7 @@
             return 0;
         }
 
-        private static final Creator<RemoteAnimationAdapterEntry> CREATOR
+        private static final @android.annotation.NonNull Creator<RemoteAnimationAdapterEntry> CREATOR
                 = new Creator<RemoteAnimationAdapterEntry>() {
 
             @Override
diff --git a/core/java/android/view/RemoteAnimationTarget.java b/core/java/android/view/RemoteAnimationTarget.java
index 9b3efe1..ae3e1d0 100644
--- a/core/java/android/view/RemoteAnimationTarget.java
+++ b/core/java/android/view/RemoteAnimationTarget.java
@@ -255,7 +255,7 @@
         proto.end(token);
     }
 
-    public static final Creator<RemoteAnimationTarget> CREATOR
+    public static final @android.annotation.NonNull Creator<RemoteAnimationTarget> CREATOR
             = new Creator<RemoteAnimationTarget>() {
         public RemoteAnimationTarget createFromParcel(Parcel in) {
             return new RemoteAnimationTarget(in);
diff --git a/core/java/android/view/RenderNodeAnimator.java b/core/java/android/view/RenderNodeAnimator.java
index 23f2b8a..7ab9534 100644
--- a/core/java/android/view/RenderNodeAnimator.java
+++ b/core/java/android/view/RenderNodeAnimator.java
@@ -336,6 +336,7 @@
         return mUnscaledStartDelay;
     }
 
+    @UnsupportedAppUsage
     @Override
     public RenderNodeAnimator setDuration(long duration) {
         checkMutable();
diff --git a/core/java/android/view/ScaleGestureDetector.java b/core/java/android/view/ScaleGestureDetector.java
index c24b8b2..7c69cfd 100644
--- a/core/java/android/view/ScaleGestureDetector.java
+++ b/core/java/android/view/ScaleGestureDetector.java
@@ -201,7 +201,7 @@
         mListener = listener;
         final ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
         mSpanSlop = viewConfiguration.getScaledTouchSlop() * 2;
-        mMinSpan = viewConfiguration.getScaledMinScalingSpan();
+        mMinSpan = viewConfiguration.getScaledMinimumScalingSpan();
         mHandler = handler;
         // Quick scale is enabled by default after JB_MR2
         final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
diff --git a/core/java/android/view/Surface.java b/core/java/android/view/Surface.java
index d0194f9..6ff699e 100644
--- a/core/java/android/view/Surface.java
+++ b/core/java/android/view/Surface.java
@@ -84,7 +84,7 @@
     private static native int nativeSetSharedBufferModeEnabled(long nativeObject, boolean enabled);
     private static native int nativeSetAutoRefreshEnabled(long nativeObject, boolean enabled);
 
-    public static final Parcelable.Creator<Surface> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<Surface> CREATOR =
             new Parcelable.Creator<Surface>() {
         @Override
         public Surface createFromParcel(Parcel source) {
@@ -922,7 +922,7 @@
             if (mCanvas != null) {
                 throw new IllegalStateException("Surface was already locked!");
             }
-            mCanvas = mRenderNode.start(width, height);
+            mCanvas = mRenderNode.beginRecording(width, height);
             return mCanvas;
         }
 
@@ -931,7 +931,7 @@
                 throw new IllegalArgumentException("canvas object must be the same instance that "
                         + "was previously returned by lockCanvas");
             }
-            mRenderNode.end(mCanvas);
+            mRenderNode.endRecording();
             mCanvas = null;
             nHwuiDraw(mHwuiRenderer);
         }
diff --git a/core/java/android/view/SurfaceControl.java b/core/java/android/view/SurfaceControl.java
index aaf85af..54e70ea 100644
--- a/core/java/android/view/SurfaceControl.java
+++ b/core/java/android/view/SurfaceControl.java
@@ -88,7 +88,8 @@
     private static native void nativeDisconnect(long nativeObject);
 
     private static native GraphicBuffer nativeScreenshot(IBinder displayToken,
-            Rect sourceCrop, int width, int height, boolean useIdentityTransform, int rotation);
+            Rect sourceCrop, int width, int height, boolean useIdentityTransform, int rotation,
+            boolean captureSecureLayers);
     private static native GraphicBuffer nativeCaptureLayers(IBinder layerHandleToken,
             Rect sourceCrop, float frameScale);
 
@@ -157,6 +158,9 @@
             IBinder displayToken, long numFrames, long timestamp);
     private static native int nativeGetActiveConfig(IBinder displayToken);
     private static native boolean nativeSetActiveConfig(IBinder displayToken, int id);
+    private static native boolean nativeSetAllowedDisplayConfigs(IBinder displayToken,
+                                                                 int[] allowedConfigs);
+    private static native int[] nativeGetAllowedDisplayConfigs(IBinder displayToken);
     private static native int[] nativeGetDisplayColorModes(IBinder displayToken);
     private static native SurfaceControl.DisplayPrimaries nativeGetDisplayNativePrimaries(
             IBinder displayToken);
@@ -815,7 +819,7 @@
         proto.end(token);
     }
 
-    public static final Creator<SurfaceControl> CREATOR
+    public static final @android.annotation.NonNull Creator<SurfaceControl> CREATOR
             = new Creator<SurfaceControl>() {
         public SurfaceControl createFromParcel(Parcel in) {
             return new SurfaceControl(in);
@@ -1521,6 +1525,30 @@
     /**
      * @hide
      */
+    public static boolean setAllowedDisplayConfigs(IBinder displayToken, int[] allowedConfigs) {
+        if (displayToken == null) {
+            throw new IllegalArgumentException("displayToken must not be null");
+        }
+        if (allowedConfigs == null) {
+            throw new IllegalArgumentException("allowedConfigs must not be null");
+        }
+
+        return nativeSetAllowedDisplayConfigs(displayToken, allowedConfigs);
+    }
+
+    /**
+     * @hide
+     */
+    public static int[] getAllowedDisplayConfigs(IBinder displayToken) {
+        if (displayToken == null) {
+            throw new IllegalArgumentException("displayToken must not be null");
+        }
+        return nativeGetAllowedDisplayConfigs(displayToken);
+    }
+
+    /**
+     * @hide
+     */
     public static int[] getDisplayColorModes(IBinder displayToken) {
         if (displayToken == null) {
             throw new IllegalArgumentException("displayToken must not be null");
@@ -1853,7 +1881,29 @@
             throw new IllegalArgumentException("displayToken must not be null");
         }
 
-        return nativeScreenshot(display, sourceCrop, width, height, useIdentityTransform, rotation);
+        return nativeScreenshot(display, sourceCrop, width, height, useIdentityTransform, rotation,
+                false /* captureSecureLayers */);
+    }
+
+    /**
+     * Like screenshotToBuffer, but if the caller is AID_SYSTEM, allows
+     * for the capture of secure layers. This is used for the screen rotation
+     * animation where the system server takes screenshots but does
+     * not persist them or allow them to leave the server. However in other
+     * cases in the system server, we mostly want to omit secure layers
+     * like when we take a screenshot on behalf of the assistant.
+     *
+     * @hide
+     */
+    public static GraphicBuffer screenshotToBufferWithSecureLayersUnsafe(IBinder display,
+            Rect sourceCrop, int width, int height, boolean useIdentityTransform,
+            int rotation) {
+        if (display == null) {
+            throw new IllegalArgumentException("displayToken must not be null");
+        }
+
+        return nativeScreenshot(display, sourceCrop, width, height, useIdentityTransform, rotation,
+                true /* captureSecureLayers */);
     }
 
     private static void rotateCropForSF(Rect crop, int rot) {
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index fe9aa23..ee8d663 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -210,7 +210,7 @@
 
     public SurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
         super(context, attrs, defStyleAttr, defStyleRes);
-        mRenderNode.requestPositionUpdates(mPositionListener);
+        mRenderNode.addPositionUpdateListener(mPositionListener);
 
         setWillNotDraw(true);
     }
diff --git a/core/java/android/view/ThreadedRenderer.java b/core/java/android/view/ThreadedRenderer.java
index 2097812..3d3d5dc 100644
--- a/core/java/android/view/ThreadedRenderer.java
+++ b/core/java/android/view/ThreadedRenderer.java
@@ -590,7 +590,7 @@
         }
 
         if (mRootNodeNeedsUpdate || !mRootNode.hasDisplayList()) {
-            RecordingCanvas canvas = mRootNode.startRecording(mSurfaceWidth, mSurfaceHeight);
+            RecordingCanvas canvas = mRootNode.beginRecording(mSurfaceWidth, mSurfaceHeight);
             try {
                 final int saveCount = canvas.save();
                 canvas.translate(mInsetLeft, mInsetTop);
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 278b9ff..877b304 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -40,6 +40,7 @@
 import android.annotation.TestApi;
 import android.annotation.UiThread;
 import android.annotation.UnsupportedAppUsage;
+import android.content.AutofillOptions;
 import android.content.ClipData;
 import android.content.Context;
 import android.content.ContextWrapper;
@@ -880,12 +881,6 @@
     private static boolean sAlwaysRemeasureExactly = false;
 
     /**
-     * Relax constraints around whether setLayoutParams() must be called after
-     * modifying the layout params.
-     */
-    private static boolean sLayoutParamsAlwaysChanged = false;
-
-    /**
      * Allow setForeground/setBackground to be called (and ignored) on a textureview,
      * without throwing
      */
@@ -4602,6 +4597,16 @@
         private ArrayList<OnUnhandledKeyEventListener> mUnhandledKeyListeners;
 
         private WindowInsetsAnimationListener mWindowInsetsAnimationListener;
+
+        /**
+         * This lives here since it's only valid for interactive views.
+         */
+        private List<Rect> mSystemGestureExclusionRects;
+
+        /**
+         * Used to track {@link #mSystemGestureExclusionRects}
+         */
+        public RenderNode.PositionUpdateListener mPositionUpdateListener;
     }
 
     @UnsupportedAppUsage
@@ -5169,11 +5174,6 @@
             // modes, so we always need to run an additional EXACTLY pass.
             sAlwaysRemeasureExactly = targetSdkVersion <= Build.VERSION_CODES.M;
 
-            // Prior to N, layout params could change without requiring a
-            // subsequent call to setLayoutParams() and they would usually
-            // work. Partial layout breaks this assumption.
-            sLayoutParamsAlwaysChanged = targetSdkVersion <= Build.VERSION_CODES.M;
-
             // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
             // On N+, we throw, but that breaks compatibility with apps that use these methods.
             sTextureViewIgnoresDrawableSetters = targetSdkVersion <= Build.VERSION_CODES.M;
@@ -5971,7 +5971,7 @@
     @NonNull
     public List<Integer> getAttributeResolutionStack(@AttrRes int attribute) {
         ArrayList<Integer> stack = new ArrayList<>();
-        if (!sDebugViewAttributes) {
+        if (!sDebugViewAttributes || mAttributeResolutionStacks == null) {
             return stack;
         }
         if (mSourceLayoutId != ID_NULL) {
@@ -6003,7 +6003,7 @@
     @NonNull
     public Map<Integer, Integer> getAttributeSourceResourceMap() {
         HashMap<Integer, Integer> map = new HashMap<>();
-        if (!sDebugViewAttributes) {
+        if (!sDebugViewAttributes || mAttributeSourceResId == null) {
             return map;
         }
         for (int i = 0; i < mAttributeSourceResId.size(); i++) {
@@ -9408,20 +9408,13 @@
             }
             setNotifiedContentCaptureAppeared();
 
-            // TODO(b/123307965): instead of post, we should queue it on AttachInfo and then
-            // dispatch on RootImpl, as we're doing with the removed ones (in that case, we should
-            // merge the delayNotifyContentCaptureDisappeared() into a more generic method that
-            // takes a session and a command, where the command is either view added or removed
-
-            // The code below doesn't take much for a unique view, but it's called for all views
-            // the first time the view hiearchy is laid off, which could acccumulative delay the
-            // initial layout. Hence, we're postponing it to a later stage - it might still cost a
-            // lost frame (or more), but that jank cost would only happen after the 1st layout.
-            Choreographer.getInstance().postCallback(Choreographer.CALLBACK_COMMIT, () -> {
-                final ViewStructure structure = session.newViewStructure(this);
-                onProvideContentCaptureStructure(structure, /* flags= */ 0);
-                session.notifyViewAppeared(structure);
-            }, /* token= */ null);
+            if (ai != null) {
+                ai.delayNotifyContentCaptureEvent(session, this, appeared);
+            } else {
+                if (DEBUG_CONTENT_CAPTURE) {
+                    Log.w(CONTENT_CAPTURE_LOG_TAG, "no AttachInfo on appeared for " + this);
+                }
+            }
         } else {
             if ((mPrivateFlags4 & PFLAG4_NOTIFIED_CONTENT_CAPTURE_APPEARED) == 0
                     || (mPrivateFlags4 & PFLAG4_NOTIFIED_CONTENT_CAPTURE_DISAPPEARED) != 0) {
@@ -9440,13 +9433,11 @@
             mPrivateFlags4 &= ~PFLAG4_NOTIFIED_CONTENT_CAPTURE_APPEARED;
 
             if (ai != null) {
-                ai.delayNotifyContentCaptureDisappeared(session, getAutofillId());
+                ai.delayNotifyContentCaptureEvent(session, this, appeared);
             } else {
                 if (DEBUG_CONTENT_CAPTURE) {
-                    Log.v(CONTENT_CAPTURE_LOG_TAG, "no AttachInfo on gone for " + this);
+                    Log.v(CONTENT_CAPTURE_LOG_TAG, "no AttachInfo on disappeared for " + this);
                 }
-                Choreographer.getInstance().postCallback(Choreographer.CALLBACK_COMMIT,
-                        () -> session.notifyViewDisappeared(getAutofillId()), /* token= */ null);
             }
         }
     }
@@ -9533,8 +9524,22 @@
     }
 
     private boolean isAutofillable() {
-        return getAutofillType() != AUTOFILL_TYPE_NONE && isImportantForAutofill()
-                && getAutofillViewId() > LAST_APP_AUTOFILL_ID;
+        if (getAutofillType() == AUTOFILL_TYPE_NONE) return false;
+
+        if (!isImportantForAutofill()) {
+            // View is not important for "regular" autofill, so we must check if Augmented Autofill
+            // is enabled for the activity
+            final AutofillOptions options = mContext.getAutofillOptions();
+            if (options == null || !options.augmentedEnabled) {
+                // TODO(b/123100824): should also check if activity is whitelisted
+                return false;
+            }
+            final AutofillManager afm = getAutofillManager();
+            if (afm == null) return false;
+            afm.notifyViewEnteredForAugmentedAutofill(this);
+        }
+
+        return getAutofillViewId() > LAST_APP_AUTOFILL_ID;
     }
 
     /** @hide */
@@ -9703,13 +9708,19 @@
      *
      * @hide
      */
-    public void dispatchInitialProvideContentCaptureStructure(@NonNull ContentCaptureManager ccm) {
+    public void dispatchInitialProvideContentCaptureStructure() {
         AttachInfo ai = mAttachInfo;
         if (ai == null) {
             Log.w(CONTENT_CAPTURE_LOG_TAG,
                     "dispatchProvideContentCaptureStructure(): no AttachInfo for " + this);
             return;
         }
+        ContentCaptureManager ccm = ai.mContentCaptureManager;
+        if (ccm == null) {
+            Log.w(CONTENT_CAPTURE_LOG_TAG, "dispatchProvideContentCaptureStructure(): "
+                    + "no ContentCaptureManager for " + this);
+            return;
+        }
 
         // We must set it before checkign if the view itself is important, because it might
         // initially not be (for example, if it's empty), although that might change later (for
@@ -9735,11 +9746,11 @@
             return;
         }
 
-        session.internalNotifyViewHierarchyEvent(/* started= */ true);
+        session.internalNotifyViewTreeEvent(/* started= */ true);
         try {
             dispatchProvideContentCaptureStructure();
         } finally {
-            session.internalNotifyViewHierarchyEvent(/* started= */ false);
+            session.internalNotifyViewTreeEvent(/* started= */ false);
         }
     }
 
@@ -10956,12 +10967,101 @@
     }
 
     void dispatchWindowInsetsAnimationFinished(InsetsAnimation animation) {
-        if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
+        if (mListenerInfo != null && mListenerInfo.mWindowInsetsAnimationListener != null) {
             mListenerInfo.mWindowInsetsAnimationListener.onFinished(animation);
         }
     }
 
     /**
+     * Sets a list of areas within this view's post-layout coordinate space where the system
+     * should not intercept touch or other pointing device gestures. <em>This method should
+     * be called by {@link #onLayout(boolean, int, int, int, int)} or {@link #onDraw(Canvas)}.</em>
+     *
+     * <p>Use this to tell the system which specific sub-areas of a view need to receive gesture
+     * input in order to function correctly in the presence of global system gestures that may
+     * conflict. For example, if the system wishes to capture swipe-in-from-screen-edge gestures
+     * to provide system-level navigation functionality, a view such as a navigation drawer
+     * container can mark the left (or starting) edge of itself as requiring gesture capture
+     * priority using this API. The system may then choose to relax its own gesture recognition
+     * to allow the app to consume the user's gesture. It is not necessary for an app to register
+     * exclusion rects for broadly spanning regions such as the entirety of a
+     * <code>ScrollView</code> or for simple press and release click targets such as
+     * <code>Button</code>. Mark an exclusion rect when interacting with a view requires
+     * a precision touch gesture in a small area in either the X or Y dimension, such as
+     * an edge swipe or dragging a <code>SeekBar</code> thumb.</p>
+     *
+     * <p>Do not modify the provided list after this method is called.</p>
+     *
+     * @param rects A list of precision gesture regions that this view needs to function correctly
+     */
+    public void setSystemGestureExclusionRects(@NonNull List<Rect> rects) {
+        if (rects.isEmpty() && mListenerInfo == null) return;
+
+        final ListenerInfo info = getListenerInfo();
+        if (rects.isEmpty()) {
+            info.mSystemGestureExclusionRects = null;
+            if (info.mPositionUpdateListener != null) {
+                mRenderNode.removePositionUpdateListener(info.mPositionUpdateListener);
+            }
+        } else {
+            info.mSystemGestureExclusionRects = rects;
+            if (info.mPositionUpdateListener == null) {
+                info.mPositionUpdateListener = new RenderNode.PositionUpdateListener() {
+                    @Override
+                    public void positionChanged(long n, int l, int t, int r, int b) {
+                        postUpdateSystemGestureExclusionRects();
+                    }
+
+                    @Override
+                    public void positionLost(long frameNumber) {
+                        postUpdateSystemGestureExclusionRects();
+                    }
+                };
+                mRenderNode.addPositionUpdateListener(info.mPositionUpdateListener);
+            }
+        }
+        postUpdateSystemGestureExclusionRects();
+    }
+
+    /**
+     * WARNING: this can be called by a hwui worker thread, not just the UI thread!
+     */
+    void postUpdateSystemGestureExclusionRects() {
+        // Potentially racey from a background thread. It's ok if it's not perfect.
+        final Handler h = getHandler();
+        if (h != null) {
+            h.postAtFrontOfQueue(this::updateSystemGestureExclusionRects);
+        }
+    }
+
+    void updateSystemGestureExclusionRects() {
+        final AttachInfo ai = mAttachInfo;
+        if (ai != null) {
+            ai.mViewRootImpl.updateSystemGestureExclusionRectsForView(this);
+        }
+    }
+
+    /**
+     * Retrieve the list of areas within this view's post-layout coordinate space where the system
+     * should not intercept touch or other pointing device gestures.
+     *
+     * <p>Do not modify the returned list.</p>
+     *
+     * @return the list set by {@link #setSystemGestureExclusionRects(List)}
+     */
+    @NonNull
+    public List<Rect> getSystemGestureExclusionRects() {
+        final ListenerInfo info = mListenerInfo;
+        if (info != null) {
+            final List<Rect> list = info.mSystemGestureExclusionRects;
+            if (list != null) {
+                return list;
+            }
+        }
+        return Collections.emptyList();
+    }
+
+    /**
      * Compute the view's coordinate within the surface.
      *
      * <p>Computes the coordinates of this view in its surface. The argument
@@ -16043,7 +16143,7 @@
     @ViewDebug.ExportedProperty(category = "drawing")
     @InspectableProperty
     public float getRotation() {
-        return mRenderNode.getRotation();
+        return mRenderNode.getRotationZ();
     }
 
     /**
@@ -16064,7 +16164,7 @@
         if (rotation != getRotation()) {
             // Double-invalidation is necessary to capture view's old and new areas
             invalidateViewProperty(true, false);
-            mRenderNode.setRotation(rotation);
+            mRenderNode.setRotationZ(rotation);
             invalidateViewProperty(false, true);
 
             invalidateParentIfNeededAndWasQuickRejected();
@@ -17976,21 +18076,6 @@
     }
 
     /**
-     * Utility method to transform a given Rect by the current matrix of this view.
-     */
-    void transformRect(final Rect rect) {
-        if (!getMatrix().isIdentity()) {
-            RectF boundingRect = mAttachInfo.mTmpTransformRect;
-            boundingRect.set(rect);
-            getMatrix().mapRect(boundingRect);
-            rect.set((int) Math.floor(boundingRect.left),
-                    (int) Math.floor(boundingRect.top),
-                    (int) Math.ceil(boundingRect.right),
-                    (int) Math.ceil(boundingRect.bottom));
-        }
-    }
-
-    /**
      * Used to indicate that the parent of this view should clear its caches. This functionality
      * is used to force the parent to rebuild its display list (when hardware-accelerated),
      * which is necessary when various parent-managed properties of the view change, such as
@@ -20578,7 +20663,7 @@
             int height = mBottom - mTop;
             int layerType = getLayerType();
 
-            final RecordingCanvas canvas = renderNode.startRecording(width, height);
+            final RecordingCanvas canvas = renderNode.beginRecording(width, height);
 
             try {
                 if (layerType == LAYER_TYPE_SOFTWARE) {
@@ -21233,7 +21318,7 @@
         } else {
             mClipBounds = null;
         }
-        mRenderNode.setClipBounds(mClipBounds);
+        mRenderNode.setClipRect(mClipBounds);
         invalidateViewProperty(false, false);
     }
 
@@ -21978,7 +22063,7 @@
         final Rect bounds = drawable.getBounds();
         final int width = bounds.width();
         final int height = bounds.height();
-        final RecordingCanvas canvas = renderNode.startRecording(width, height);
+        final RecordingCanvas canvas = renderNode.beginRecording(width, height);
 
         // Reverse left/top translation done by drawable canvas, which will
         // instead be applied by rendernode's LTRB bounds below. This way, the
@@ -27904,7 +27989,7 @@
             out.writeInt(mAutofillViewId);
         }
 
-        public static final Parcelable.Creator<BaseSavedState> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<BaseSavedState> CREATOR
                 = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
             @Override
             public BaseSavedState createFromParcel(Parcel in) {
@@ -28358,11 +28443,12 @@
         boolean mReadyForContentCaptureUpdates;
 
         /**
-         * Map of ids (per session) that need to be notified after as gone the view hierchy is
-         * traversed.
+         * Map(keyed by session) of content capture events that need to be notified after the view
+         * hierarchy is traversed: value is either the view itself for appearead events, or its
+         * autofill id for disappeared.
          */
         // TODO(b/121197119): use SparseArray once session id becomes integer
-        ArrayMap<String, ArrayList<AutofillId>> mContentCaptureRemovedIds;
+        ArrayMap<String, ArrayList<Object>> mContentCaptureEvents;
 
         /**
          * Cached reference to the {@link ContentCaptureManager}.
@@ -28388,24 +28474,24 @@
             mTreeObserver = new ViewTreeObserver(context);
         }
 
-        private void delayNotifyContentCaptureDisappeared(@NonNull ContentCaptureSession session,
-                @NonNull AutofillId id) {
-            if (mContentCaptureRemovedIds == null) {
+        private void delayNotifyContentCaptureEvent(@NonNull ContentCaptureSession session,
+                @NonNull View view, boolean appeared) {
+            if (mContentCaptureEvents == null) {
                 // Most of the time there will be just one session, so intial capacity is 1
-                mContentCaptureRemovedIds = new ArrayMap<>(1);
+                mContentCaptureEvents = new ArrayMap<>(1);
             }
             String sessionId = session.getId();
             // TODO: life would be much easier if we provided a MultiMap implementation somwhere...
-            ArrayList<AutofillId> ids = mContentCaptureRemovedIds.get(sessionId);
-            if (ids == null) {
-                ids = new ArrayList<>();
-                mContentCaptureRemovedIds.put(sessionId, ids);
+            ArrayList<Object> events = mContentCaptureEvents.get(sessionId);
+            if (events == null) {
+                events = new ArrayList<>();
+                mContentCaptureEvents.put(sessionId, events);
             }
-            ids.add(id);
+            events.add(appeared ? view : view.getAutofillId());
         }
 
         @Nullable
-        private ContentCaptureManager getContentCaptureManager(@NonNull Context context) {
+        ContentCaptureManager getContentCaptureManager(@NonNull Context context) {
             if (mContentCaptureManager != null) {
                 return mContentCaptureManager;
             }
diff --git a/core/java/android/view/ViewConfiguration.java b/core/java/android/view/ViewConfiguration.java
index bb29ed6..81e9c13 100644
--- a/core/java/android/view/ViewConfiguration.java
+++ b/core/java/android/view/ViewConfiguration.java
@@ -928,8 +928,8 @@
     }
 
     /**
-     * If a MotionEvent has CLASSIFICATION_AMBIGUOUS_GESTURE set, then certain actions, such as
-     * scrolling, will be inhibited.
+     * If a MotionEvent has {@link android.view.MotionEvent#CLASSIFICATION_AMBIGUOUS_GESTURE} set,
+     * then certain actions, such as scrolling, will be inhibited.
      * However, to account for the possibility of incorrect classification,
      * the default scrolling will only be inhibited if the pointer travels less than
      * (getScaledTouchSlop() * this factor).
@@ -979,7 +979,7 @@
      * @throws IllegalStateException if this method is called on a ViewConfiguration that was
      *         instantiated using a constructor with no Context parameter.
      */
-    public int getScaledMinScalingSpan() {
+    public int getScaledMinimumScalingSpan() {
         if (!mConstructedWithContext) {
             throw new IllegalStateException("Min scaling span cannot be determined when this "
                     + "method is called on a ViewConfiguration that was instantiated using a "
diff --git a/core/java/android/view/ViewDebug.java b/core/java/android/view/ViewDebug.java
index 6f9ee4b..a390db2 100644
--- a/core/java/android/view/ViewDebug.java
+++ b/core/java/android/view/ViewDebug.java
@@ -611,11 +611,11 @@
         }
 
         if (view.isHardwareAccelerated()) {
-            RecordingCanvas canvas = node.start(dm.widthPixels, dm.heightPixels);
+            RecordingCanvas canvas = node.beginRecording(dm.widthPixels, dm.heightPixels);
             try {
                 return profileViewOperation(view, () -> view.draw(canvas));
             } finally {
-                node.end(canvas);
+                node.endRecording();
             }
         } else {
             Bitmap bitmap = Bitmap.createBitmap(
diff --git a/core/java/android/view/ViewPropertyAnimator.java b/core/java/android/view/ViewPropertyAnimator.java
index 68c0d9e..afee1e5 100644
--- a/core/java/android/view/ViewPropertyAnimator.java
+++ b/core/java/android/view/ViewPropertyAnimator.java
@@ -985,7 +985,7 @@
                 renderNode.setTranslationZ(value);
                 break;
             case ROTATION:
-                renderNode.setRotation(value);
+                renderNode.setRotationZ(value);
                 break;
             case ROTATION_X:
                 renderNode.setRotationX(value);
@@ -1031,7 +1031,7 @@
             case TRANSLATION_Z:
                 return node.getTranslationZ();
             case ROTATION:
-                return node.getRotation();
+                return node.getRotationZ();
             case ROTATION_X:
                 return node.getRotationX();
             case ROTATION_Y:
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index be6b56c..65b1abd 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -108,6 +108,7 @@
 import android.view.autofill.AutofillId;
 import android.view.autofill.AutofillManager;
 import android.view.contentcapture.ContentCaptureManager;
+import android.view.contentcapture.ContentCaptureSession;
 import android.view.contentcapture.MainContentCaptureSession;
 import android.view.inputmethod.InputMethodManager;
 import android.widget.Scroller;
@@ -223,10 +224,25 @@
      */
     static final int MAX_TRACKBALL_DELAY = 250;
 
+    /**
+     * Initial value for {@link #mContentCaptureEnabled}.
+     */
+    private static final int CONTENT_CAPTURE_ENABLED_NOT_CHECKED = 0;
+
+    /**
+     * Value for {@link #mContentCaptureEnabled} when it was checked and set to {@code true}.
+     */
+    private static final int CONTENT_CAPTURE_ENABLED_TRUE = 1;
+
+    /**
+     * Value for {@link #mContentCaptureEnabled} when it was checked and set to {@code false}.
+     */
+    private static final int CONTENT_CAPTURE_ENABLED_FALSE = 2;
+
     @UnsupportedAppUsage
     static final ThreadLocal<HandlerActionQueue> sRunQueues = new ThreadLocal<HandlerActionQueue>();
 
-    static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList();
+    static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<>();
     static boolean sFirstDrawComplete = false;
 
     /**
@@ -418,7 +434,11 @@
     boolean mApplyInsetsRequested;
     boolean mLayoutRequested;
     boolean mFirst;
+
+    @Nullable
+    int mContentCaptureEnabled = CONTENT_CAPTURE_ENABLED_NOT_CHECKED;
     boolean mPerformContentCapture;
+
     boolean mReportNextDraw;
     boolean mFullRedrawNeeded;
     boolean mNewSurfaceNeeded;
@@ -585,6 +605,8 @@
 
     private final InsetsController mInsetsController = new InsetsController(this);
 
+    private final GestureExclusionTracker mGestureExclusionTracker = new GestureExclusionTracker();
+
     static final class SystemUiVisibilityInfo {
         int seq;
         int globalVisibility;
@@ -2776,27 +2798,56 @@
             }
         }
 
-        if (mAttachInfo.mContentCaptureRemovedIds != null) {
-            MainContentCaptureSession mainSession = mAttachInfo.mContentCaptureManager
-                    .getMainContentCaptureSession();
-            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "notifyContentCaptureViewsGone");
-            try {
-                for (int i = 0; i < mAttachInfo.mContentCaptureRemovedIds.size(); i++) {
-                    String sessionId = mAttachInfo.mContentCaptureRemovedIds
-                            .keyAt(i);
-                    ArrayList<AutofillId> ids = mAttachInfo.mContentCaptureRemovedIds
-                            .valueAt(i);
-                    mainSession.notifyViewsDisappeared(sessionId, ids);
-                }
-                mAttachInfo.mContentCaptureRemovedIds = null;
-            } finally {
-                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
-            }
+        if (mAttachInfo.mContentCaptureEvents != null) {
+            notifyContentCatpureEvents();
         }
 
         mIsInTraversal = false;
     }
 
+    private void notifyContentCatpureEvents() {
+        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "notifyContentCaptureEvents");
+        try {
+            MainContentCaptureSession mainSession = mAttachInfo.mContentCaptureManager
+                    .getMainContentCaptureSession();
+            for (int i = 0; i < mAttachInfo.mContentCaptureEvents.size(); i++) {
+                String sessionId = mAttachInfo.mContentCaptureEvents
+                        .keyAt(i);
+                mainSession.notifyViewTreeEvent(sessionId, /* started= */ true);
+                ArrayList<Object> events = mAttachInfo.mContentCaptureEvents
+                        .valueAt(i);
+                for_each_event: for (int j = 0; j < events.size(); j++) {
+                    Object event = events.get(j);
+                    if (event instanceof AutofillId) {
+                        mainSession.notifyViewDisappeared(sessionId, (AutofillId) event);
+                    } else if (event instanceof View) {
+                        View view = (View) event;
+                        ContentCaptureSession session = view.getContentCaptureSession();
+                        if (session == null) {
+                            Log.w(mTag, "no content capture session on view: " + view);
+                            continue for_each_event;
+                        }
+                        String actualId = session.getId().toString();
+                        if (!actualId.equals(sessionId)) {
+                            Log.w(mTag, "content capture session mismatch for view (" + view
+                                    + "): was " + sessionId + " before, it's " + actualId + " now");
+                            continue for_each_event;
+                        }
+                        ViewStructure structure = session.newViewStructure(view);
+                        view.onProvideContentCaptureStructure(structure, /* flags= */ 0);
+                        session.notifyViewAppeared(structure);
+                    } else {
+                        Log.w(mTag, "invalid content capture event: " + event);
+                    }
+                }
+                mainSession.notifyViewTreeEvent(sessionId, /* started= */ false);
+            }
+            mAttachInfo.mContentCaptureEvents = null;
+        } finally {
+            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
+        }
+    }
+
     private void notifySurfaceDestroyed() {
         mSurfaceHolder.ungetCallbacks();
         SurfaceHolder.Callback[] callbacks = mSurfaceHolder.getCallbacks();
@@ -2927,6 +2978,13 @@
             }
         }
         mFirstInputStage.onWindowFocusChanged(hasWindowFocus);
+
+        // NOTE: there's no view visibility (appeared / disapparead) events when the windows focus
+        // is lost, so we don't need to to force a flush - there might be other events such as
+        // text changes, but these should be flushed independently.
+        if (hasWindowFocus) {
+            handleContentCaptureFlush();
+        }
     }
 
     private void fireAccessibilityFocusEventIfHasFocusedNode() {
@@ -3494,31 +3552,82 @@
             }
         }
         if (mPerformContentCapture) {
-            performContentCapture();
+            performContentCaptureInitialReport();
         }
     }
 
-    private void performContentCapture() {
+    /**
+     * Checks (and caches) if content capture is enabled for this context.
+     */
+    private boolean isContentCaptureEnabled() {
+        switch (mContentCaptureEnabled) {
+            case CONTENT_CAPTURE_ENABLED_TRUE:
+                return true;
+            case CONTENT_CAPTURE_ENABLED_FALSE:
+                return false;
+            case CONTENT_CAPTURE_ENABLED_NOT_CHECKED:
+                final boolean reallyEnabled = isContentCaptureReallyEnabled();
+                mContentCaptureEnabled = reallyEnabled ? CONTENT_CAPTURE_ENABLED_TRUE
+                        : CONTENT_CAPTURE_ENABLED_FALSE;
+                return reallyEnabled;
+            default:
+                Log.w(TAG, "isContentCaptureEnabled(): invalid state " + mContentCaptureEnabled);
+                return false;
+        }
+
+    }
+
+    /**
+     * Checks (without caching) if content capture is enabled for this context.
+     */
+    private boolean isContentCaptureReallyEnabled() {
+        // First check if context supports it, so it saves a service lookup when it doesn't
+        if (mContext.getContentCaptureOptions() == null) return false;
+
+        final ContentCaptureManager ccm = mAttachInfo.getContentCaptureManager(mContext);
+        // Then check if it's enabled in the contex itself.
+        if (ccm == null || !ccm.isContentCaptureEnabled()) return false;
+
+        return true;
+    }
+
+    private void performContentCaptureInitialReport() {
         mPerformContentCapture = false; // One-time offer!
         final View rootView = mView;
         if (DEBUG_CONTENT_CAPTURE) {
-            Log.v(mTag, "dispatchContentCapture() on " + rootView);
+            Log.v(mTag, "performContentCaptureInitialReport() on " + rootView);
         }
         if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
             Trace.traceBegin(Trace.TRACE_TAG_VIEW, "dispatchContentCapture() for "
                     + getClass().getSimpleName());
         }
         try {
-            // First check if context supports it, so it saves a service lookup when it doesn't
-            if (mContext.getContentCaptureOptions() == null) return;
-
-            // Then check if it's enabled in the contex itself.
-            final ContentCaptureManager ccm = mContext
-                    .getSystemService(ContentCaptureManager.class);
-            if (ccm == null || !ccm.isContentCaptureEnabled()) return;
+            if (!isContentCaptureEnabled()) return;
 
             // Content capture is a go!
-            rootView.dispatchInitialProvideContentCaptureStructure(ccm);
+            rootView.dispatchInitialProvideContentCaptureStructure();
+        } finally {
+            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
+        }
+    }
+
+    private void handleContentCaptureFlush() {
+        if (DEBUG_CONTENT_CAPTURE) {
+            Log.v(mTag, "handleContentCaptureFlush()");
+        }
+        if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
+            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "flushContentCapture for "
+                    + getClass().getSimpleName());
+        }
+        try {
+            if (!isContentCaptureEnabled()) return;
+
+            final ContentCaptureManager ccm = mAttachInfo.mContentCaptureManager;
+            if (ccm == null) {
+                Log.w(TAG, "No ContentCapture on AttachInfo");
+                return;
+            }
+            ccm.flush(ContentCaptureSession.FLUSH_REASON_VIEW_ROOT_ENTERED);
         } finally {
             Trace.traceEnd(Trace.TRACE_TAG_VIEW);
         }
@@ -3870,6 +3979,20 @@
         return mAttachInfo.mAccessibilityFocusDrawable;
     }
 
+    void updateSystemGestureExclusionRectsForView(View view) {
+        mGestureExclusionTracker.updateRectsForView(view);
+        mHandler.sendEmptyMessage(MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED);
+    }
+
+    void systemGestureExclusionChanged() {
+        final List<Rect> rectsForWindowManager = mGestureExclusionTracker.computeChangedRects();
+        if (rectsForWindowManager != null) {
+            // TODO Send to WM
+            mAttachInfo.mTreeObserver
+                    .dispatchOnSystemGestureExclusionRectsChanged(rectsForWindowManager);
+        }
+    }
+
     /**
      * Requests that the root render node is invalidated next time we perform a draw, such that
      * {@link WindowCallbacks#onPostDraw} gets called.
@@ -4326,35 +4449,36 @@
         }
     }
 
-    private final static int MSG_INVALIDATE = 1;
-    private final static int MSG_INVALIDATE_RECT = 2;
-    private final static int MSG_DIE = 3;
-    private final static int MSG_RESIZED = 4;
-    private final static int MSG_RESIZED_REPORT = 5;
-    private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
-    private final static int MSG_DISPATCH_INPUT_EVENT = 7;
-    private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
-    private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
-    private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
-    private final static int MSG_DISPATCH_KEY_FROM_AUTOFILL = 12;
-    private final static int MSG_CHECK_FOCUS = 13;
-    private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
-    private final static int MSG_DISPATCH_DRAG_EVENT = 15;
-    private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
-    private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
-    private final static int MSG_UPDATE_CONFIGURATION = 18;
-    private final static int MSG_PROCESS_INPUT_EVENTS = 19;
-    private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21;
-    private final static int MSG_INVALIDATE_WORLD = 22;
-    private final static int MSG_WINDOW_MOVED = 23;
-    private final static int MSG_SYNTHESIZE_INPUT_EVENT = 24;
-    private final static int MSG_DISPATCH_WINDOW_SHOWN = 25;
-    private final static int MSG_REQUEST_KEYBOARD_SHORTCUTS = 26;
-    private final static int MSG_UPDATE_POINTER_ICON = 27;
-    private final static int MSG_POINTER_CAPTURE_CHANGED = 28;
-    private final static int MSG_DRAW_FINISHED = 29;
-    private final static int MSG_INSETS_CHANGED = 30;
-    private final static int MSG_INSETS_CONTROL_CHANGED = 31;
+    private static final int MSG_INVALIDATE = 1;
+    private static final int MSG_INVALIDATE_RECT = 2;
+    private static final int MSG_DIE = 3;
+    private static final int MSG_RESIZED = 4;
+    private static final int MSG_RESIZED_REPORT = 5;
+    private static final int MSG_WINDOW_FOCUS_CHANGED = 6;
+    private static final int MSG_DISPATCH_INPUT_EVENT = 7;
+    private static final int MSG_DISPATCH_APP_VISIBILITY = 8;
+    private static final int MSG_DISPATCH_GET_NEW_SURFACE = 9;
+    private static final int MSG_DISPATCH_KEY_FROM_IME = 11;
+    private static final int MSG_DISPATCH_KEY_FROM_AUTOFILL = 12;
+    private static final int MSG_CHECK_FOCUS = 13;
+    private static final int MSG_CLOSE_SYSTEM_DIALOGS = 14;
+    private static final int MSG_DISPATCH_DRAG_EVENT = 15;
+    private static final int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
+    private static final int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
+    private static final int MSG_UPDATE_CONFIGURATION = 18;
+    private static final int MSG_PROCESS_INPUT_EVENTS = 19;
+    private static final int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21;
+    private static final int MSG_INVALIDATE_WORLD = 22;
+    private static final int MSG_WINDOW_MOVED = 23;
+    private static final int MSG_SYNTHESIZE_INPUT_EVENT = 24;
+    private static final int MSG_DISPATCH_WINDOW_SHOWN = 25;
+    private static final int MSG_REQUEST_KEYBOARD_SHORTCUTS = 26;
+    private static final int MSG_UPDATE_POINTER_ICON = 27;
+    private static final int MSG_POINTER_CAPTURE_CHANGED = 28;
+    private static final int MSG_DRAW_FINISHED = 29;
+    private static final int MSG_INSETS_CHANGED = 30;
+    private static final int MSG_INSETS_CONTROL_CHANGED = 31;
+    private static final int MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED = 32;
 
     final class ViewRootHandler extends Handler {
         @Override
@@ -4412,6 +4536,10 @@
                     return "MSG_DRAW_FINISHED";
                 case MSG_INSETS_CHANGED:
                     return "MSG_INSETS_CHANGED";
+                case MSG_INSETS_CONTROL_CHANGED:
+                    return "MSG_INSETS_CONTROL_CHANGED";
+                case MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED:
+                    return "MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED";
             }
             return super.getMessageName(message);
         }
@@ -4643,6 +4771,9 @@
                 case MSG_DRAW_FINISHED: {
                     pendingDrawFinished();
                 } break;
+                case MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED: {
+                    systemGestureExclusionChanged();
+                } break;
             }
         }
     }
@@ -5163,11 +5294,8 @@
         protected int onProcess(QueuedInputEvent q) {
             if (q.mEvent instanceof KeyEvent) {
                 return processKeyEvent(q);
-            } else {
-                final int source = q.mEvent.getSource();
-                if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
-                    return processPointerEvent(q);
-                }
+            } else if (q.mEvent instanceof MotionEvent) {
+                return processMotionEvent(q);
             }
             return FORWARD;
         }
@@ -5191,6 +5319,23 @@
             return FORWARD;
         }
 
+        private int processMotionEvent(QueuedInputEvent q) {
+            final MotionEvent event = (MotionEvent) q.mEvent;
+
+            if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
+                return processPointerEvent(q);
+            }
+
+            // If the motion event is from an absolute position device, exit touch mode
+            final int action = event.getActionMasked();
+            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
+                if (event.isFromSource(InputDevice.SOURCE_CLASS_POSITION)) {
+                    ensureTouchMode(false);
+                }
+            }
+            return FORWARD;
+        }
+
         private int processPointerEvent(QueuedInputEvent q) {
             final MotionEvent event = (MotionEvent)q.mEvent;
 
@@ -5523,6 +5668,12 @@
         private int processGenericMotionEvent(QueuedInputEvent q) {
             final MotionEvent event = (MotionEvent)q.mEvent;
 
+            if (event.isFromSource(InputDevice.SOURCE_TOUCHPAD)) {
+                if (hasPointerCapture() && mView.dispatchCapturedPointerEvent(event)) {
+                    return FINISH_HANDLED;
+                }
+            }
+
             // Deliver the event to the view.
             if (mView.dispatchGenericMotionEvent(event)) {
                 return FINISH_HANDLED;
@@ -7093,7 +7244,7 @@
         RenderNode renderNode = view.mRenderNode;
         info[0]++;
         if (renderNode != null) {
-            info[1] += renderNode.computeApproximateMemoryUsage();
+            info[1] += (int) renderNode.computeApproximateMemoryUsage();
         }
 
         if (view instanceof ViewGroup) {
diff --git a/core/java/android/view/ViewTreeObserver.java b/core/java/android/view/ViewTreeObserver.java
index 763ce4f..2896bd0 100644
--- a/core/java/android/view/ViewTreeObserver.java
+++ b/core/java/android/view/ViewTreeObserver.java
@@ -26,7 +26,9 @@
 import android.util.Log;
 
 import java.util.ArrayList;
+import java.util.List;
 import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.function.Consumer;
 
 /**
  * A view tree observer is used to register listeners that can be notified of global
@@ -57,6 +59,7 @@
     private CopyOnWriteArray<OnScrollChangedListener> mOnScrollChangedListeners;
     private CopyOnWriteArray<OnPreDrawListener> mOnPreDrawListeners;
     private CopyOnWriteArray<OnWindowShownListener> mOnWindowShownListeners;
+    private CopyOnWriteArray<Consumer<List<Rect>>> mGestureExclusionListeners;
 
     // These listeners cannot be mutated during dispatch
     private boolean mInDispatchOnDraw;
@@ -450,6 +453,14 @@
             }
         }
 
+        if (observer.mGestureExclusionListeners != null) {
+            if (mGestureExclusionListeners != null) {
+                mGestureExclusionListeners.addAll(observer.mGestureExclusionListeners);
+            } else {
+                mGestureExclusionListeners = observer.mGestureExclusionListeners;
+            }
+        }
+
         observer.kill();
     }
 
@@ -913,6 +924,35 @@
         mOnEnterAnimationCompleteListeners.remove(listener);
     }
 
+    /**
+     * Add a listener to be notified when the tree's <em>transformed</em> gesture exclusion rects
+     * change. This could be the result of an animation or other layout change, or a view calling
+     * {@link View#setSystemGestureExclusionRects(List)}.
+     *
+     * @param listener listener to add
+     * @see View#setSystemGestureExclusionRects(List)
+     */
+    public void addOnSystemGestureExclusionRectsChangedListener(Consumer<List<Rect>> listener) {
+        checkIsAlive();
+        if (mGestureExclusionListeners == null) {
+            mGestureExclusionListeners = new CopyOnWriteArray<>();
+        }
+        mGestureExclusionListeners.add(listener);
+    }
+
+    /**
+     * Unsubscribe the given listener from gesture exclusion rect changes.
+     * @see #addOnSystemGestureExclusionRectsChangedListener(Consumer)
+     * @see View#setSystemGestureExclusionRects(List)
+     */
+    public void removeOnSystemGestureExclusionRectsChangedListener(Consumer<List<Rect>> listener) {
+        checkIsAlive();
+        if (mGestureExclusionListeners == null) {
+            return;
+        }
+        mGestureExclusionListeners.remove(listener);
+    }
+
     private void checkIsAlive() {
         if (!mAlive) {
             throw new IllegalStateException("This ViewTreeObserver is not alive, call "
@@ -1178,6 +1218,21 @@
         }
     }
 
+    void dispatchOnSystemGestureExclusionRectsChanged(@NonNull List<Rect> rects) {
+        final CopyOnWriteArray<Consumer<List<Rect>>> listeners = mGestureExclusionListeners;
+        if (listeners != null && listeners.size() > 0) {
+            CopyOnWriteArray.Access<Consumer<List<Rect>>> access = listeners.start();
+            try {
+                final int count = access.size();
+                for (int i = 0; i < count; i++) {
+                    access.get(i).accept(rects);
+                }
+            } finally {
+                listeners.end();
+            }
+        }
+    }
+
     /**
      * Copy on write array. This array is not thread safe, and only one loop can
      * iterate over this array at any given time. This class avoids allocations
diff --git a/core/java/android/view/WindowAnimationFrameStats.java b/core/java/android/view/WindowAnimationFrameStats.java
index 0233c86..399dfba 100644
--- a/core/java/android/view/WindowAnimationFrameStats.java
+++ b/core/java/android/view/WindowAnimationFrameStats.java
@@ -81,7 +81,7 @@
         return builder.toString();
     }
 
-    public static final Creator<WindowAnimationFrameStats> CREATOR =
+    public static final @android.annotation.NonNull Creator<WindowAnimationFrameStats> CREATOR =
             new Creator<WindowAnimationFrameStats>() {
                 @Override
                 public WindowAnimationFrameStats createFromParcel(Parcel parcel) {
diff --git a/core/java/android/view/WindowContentFrameStats.java b/core/java/android/view/WindowContentFrameStats.java
index 96878e9..9fa5a00 100644
--- a/core/java/android/view/WindowContentFrameStats.java
+++ b/core/java/android/view/WindowContentFrameStats.java
@@ -139,7 +139,7 @@
         return builder.toString();
     }
 
-    public static final Parcelable.Creator<WindowContentFrameStats> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<WindowContentFrameStats> CREATOR =
             new Creator<WindowContentFrameStats>() {
                 @Override
                 public WindowContentFrameStats createFromParcel(Parcel parcel) {
diff --git a/core/java/android/view/WindowId.java b/core/java/android/view/WindowId.java
index 12e58f1..26d3405 100644
--- a/core/java/android/view/WindowId.java
+++ b/core/java/android/view/WindowId.java
@@ -196,7 +196,7 @@
         out.writeStrongBinder(mToken.asBinder());
     }
 
-    public static final Parcelable.Creator<WindowId> CREATOR = new Parcelable.Creator<WindowId>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<WindowId> CREATOR = new Parcelable.Creator<WindowId>() {
         @Override
         public WindowId createFromParcel(Parcel in) {
             IBinder target = in.readStrongBinder();
diff --git a/core/java/android/view/WindowInfo.java b/core/java/android/view/WindowInfo.java
index 82e9a5c..74fc15a 100644
--- a/core/java/android/view/WindowInfo.java
+++ b/core/java/android/view/WindowInfo.java
@@ -176,7 +176,7 @@
         hasFlagWatchOutsideTouch = false;
     }
 
-    public static final Parcelable.Creator<WindowInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<WindowInfo> CREATOR =
             new Creator<WindowInfo>() {
         @Override
         public WindowInfo createFromParcel(Parcel parcel) {
diff --git a/core/java/android/view/WindowInsets.java b/core/java/android/view/WindowInsets.java
index c1536ae..135a891 100644
--- a/core/java/android/view/WindowInsets.java
+++ b/core/java/android/view/WindowInsets.java
@@ -28,6 +28,7 @@
 import static android.view.WindowInsets.Type.indexOf;
 
 import android.annotation.IntDef;
+import android.annotation.IntRange;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.UnsupportedAppUsage;
@@ -700,7 +701,8 @@
      * @return the inset insets
      */
     @NonNull
-    public WindowInsets inset(int left, int top, int right, int bottom) {
+    public WindowInsets inset(@IntRange(from = 0) int left, @IntRange(from = 0) int top,
+            @IntRange(from = 0) int right, @IntRange(from = 0) int bottom) {
         Preconditions.checkArgumentNonnegative(left);
         Preconditions.checkArgumentNonnegative(top);
         Preconditions.checkArgumentNonnegative(right);
@@ -794,7 +796,7 @@
     /**
      * Builder for WindowInsets.
      */
-    public static class Builder {
+    public static final class Builder {
 
         private final Insets[] mTypeInsetsMap;
         private final Insets[] mTypeMaxInsetsMap;
@@ -821,7 +823,7 @@
          *
          * @param insets the instance to initialize from.
          */
-        public Builder(WindowInsets insets) {
+        public Builder(@NonNull WindowInsets insets) {
             mTypeInsetsMap = insets.mTypeInsetsMap.clone();
             mTypeMaxInsetsMap = insets.mTypeMaxInsetsMap.clone();
             mTypeVisibilityMap = insets.mTypeVisibilityMap.clone();
diff --git a/core/java/android/view/WindowManager.java b/core/java/android/view/WindowManager.java
index 6326c59..0275c25 100644
--- a/core/java/android/view/WindowManager.java
+++ b/core/java/android/view/WindowManager.java
@@ -2724,7 +2724,7 @@
             out.writeLong(hideTimeoutMilliseconds);
         }
 
-        public static final Parcelable.Creator<LayoutParams> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<LayoutParams> CREATOR
                     = new Parcelable.Creator<LayoutParams>() {
             public LayoutParams createFromParcel(Parcel in) {
                 return new LayoutParams(in);
diff --git a/core/java/android/view/accessibility/AccessibilityCache.java b/core/java/android/view/accessibility/AccessibilityCache.java
index 87e18b7..5d59e42 100644
--- a/core/java/android/view/accessibility/AccessibilityCache.java
+++ b/core/java/android/view/accessibility/AccessibilityCache.java
@@ -424,20 +424,28 @@
      *
      * @param nodes The nodes in the hosting window.
      * @param rootNodeId The id of the root to evict.
+     *
+     * @return {@code true} if the cache was cleared
      */
-    private void clearSubTreeRecursiveLocked(LongSparseArray<AccessibilityNodeInfo> nodes,
+    private boolean clearSubTreeRecursiveLocked(LongSparseArray<AccessibilityNodeInfo> nodes,
             long rootNodeId) {
         AccessibilityNodeInfo current = nodes.get(rootNodeId);
         if (current == null) {
-            return;
+            // The node isn't in the cache, but its descendents might be.
+            clear();
+            return true;
         }
         nodes.remove(rootNodeId);
         final int childCount = current.getChildCount();
         for (int i = 0; i < childCount; i++) {
             final long childNodeId = current.getChildId(i);
-            clearSubTreeRecursiveLocked(nodes, childNodeId);
+            if (clearSubTreeRecursiveLocked(nodes, childNodeId)) {
+                current.recycle();
+                return true;
+            }
         }
         current.recycle();
+        return false;
     }
 
     /**
diff --git a/core/java/android/view/accessibility/AccessibilityEvent.java b/core/java/android/view/accessibility/AccessibilityEvent.java
index dccf9d4..2ac44d2 100644
--- a/core/java/android/view/accessibility/AccessibilityEvent.java
+++ b/core/java/android/view/accessibility/AccessibilityEvent.java
@@ -1430,7 +1430,7 @@
     /**
      * @see Parcelable.Creator
      */
-    public static final Parcelable.Creator<AccessibilityEvent> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AccessibilityEvent> CREATOR =
             new Parcelable.Creator<AccessibilityEvent>() {
         public AccessibilityEvent createFromParcel(Parcel parcel) {
             AccessibilityEvent event = AccessibilityEvent.obtain();
diff --git a/core/java/android/view/accessibility/AccessibilityNodeInfo.java b/core/java/android/view/accessibility/AccessibilityNodeInfo.java
index 793c315..a8a787e 100644
--- a/core/java/android/view/accessibility/AccessibilityNodeInfo.java
+++ b/core/java/android/view/accessibility/AccessibilityNodeInfo.java
@@ -5144,7 +5144,7 @@
         /**
          * @see android.os.Parcelable.Creator
          */
-        public static final Parcelable.Creator<TouchDelegateInfo> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<TouchDelegateInfo> CREATOR =
                 new Parcelable.Creator<TouchDelegateInfo>() {
             @Override
             public TouchDelegateInfo createFromParcel(Parcel parcel) {
@@ -5173,7 +5173,7 @@
     /**
      * @see android.os.Parcelable.Creator
      */
-    public static final Parcelable.Creator<AccessibilityNodeInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AccessibilityNodeInfo> CREATOR =
             new Parcelable.Creator<AccessibilityNodeInfo>() {
         @Override
         public AccessibilityNodeInfo createFromParcel(Parcel parcel) {
diff --git a/core/java/android/view/accessibility/AccessibilityWindowInfo.java b/core/java/android/view/accessibility/AccessibilityWindowInfo.java
index c1c9174..4383f8a 100644
--- a/core/java/android/view/accessibility/AccessibilityWindowInfo.java
+++ b/core/java/android/view/accessibility/AccessibilityWindowInfo.java
@@ -770,7 +770,7 @@
         return changes;
     }
 
-    public static final Parcelable.Creator<AccessibilityWindowInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AccessibilityWindowInfo> CREATOR =
             new Creator<AccessibilityWindowInfo>() {
         @Override
         public AccessibilityWindowInfo createFromParcel(Parcel parcel) {
diff --git a/core/java/android/view/animation/Animation.java b/core/java/android/view/animation/Animation.java
index e095094..3b60aee 100644
--- a/core/java/android/view/animation/Animation.java
+++ b/core/java/android/view/animation/Animation.java
@@ -207,6 +207,7 @@
     private float mScaleFactor = 1f;
 
     private boolean mShowWallpaper;
+    private boolean mHasRoundedCorners;
 
     private boolean mMore = true;
     private boolean mOneMoreTime = true;
@@ -263,6 +264,8 @@
                 a.getBoolean(com.android.internal.R.styleable.Animation_detachWallpaper, false));
         setShowWallpaper(
                 a.getBoolean(com.android.internal.R.styleable.Animation_showWallpaper, false));
+        setHasRoundedCorners(
+                a.getBoolean(com.android.internal.R.styleable.Animation_hasRoundedCorners, false));
 
         final int resID = a.getResourceId(com.android.internal.R.styleable.Animation_interpolator, 0);
 
@@ -678,6 +681,19 @@
     }
 
     /**
+     * If this is a window animation, the window will have rounded corners matching the display
+     * corner radius.
+     *
+     * @param hasRoundedCorners Whether the window should have rounded corners or not.
+     * @attr ref android.R.styleable#Animation_hasRoundedCorners
+     * @see com.android.internal.policy.ScreenDecorationsUtils#getWindowCornerRadius(Resources)
+     * @hide
+     */
+    public void setHasRoundedCorners(boolean hasRoundedCorners) {
+        mHasRoundedCorners = hasRoundedCorners;
+    }
+
+    /**
      * Gets the acceleration curve type for this animation.
      *
      * @return the {@link Interpolator} associated to this animation
@@ -804,6 +820,16 @@
     }
 
     /**
+     * @return if a window animation should have rounded corners or not.
+     *
+     * @attr ref android.R.styleable#Animation_hasRoundedCorners
+     * @hide
+     */
+    public boolean hasRoundedCorners() {
+        return mHasRoundedCorners;
+    }
+
+    /**
      * <p>Indicates whether or not this animation will affect the transformation
      * matrix. For instance, a fade animation will not affect the matrix whereas
      * a scale animation will.</p>
diff --git a/core/java/android/view/autofill/AutofillId.java b/core/java/android/view/autofill/AutofillId.java
index 5608bb3..8fa29f3 100644
--- a/core/java/android/view/autofill/AutofillId.java
+++ b/core/java/android/view/autofill/AutofillId.java
@@ -206,7 +206,7 @@
         }
     }
 
-    public static final Parcelable.Creator<AutofillId> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AutofillId> CREATOR =
             new Parcelable.Creator<AutofillId>() {
         @Override
         public AutofillId createFromParcel(Parcel source) {
diff --git a/core/java/android/view/autofill/AutofillManager.java b/core/java/android/view/autofill/AutofillManager.java
index 9dcbe05..70fe230 100644
--- a/core/java/android/view/autofill/AutofillManager.java
+++ b/core/java/android/view/autofill/AutofillManager.java
@@ -16,6 +16,7 @@
 
 package android.view.autofill;
 
+import static android.service.autofill.FillRequest.FLAG_AUGMENTED_AUTOFILL_REQUEST;
 import static android.service.autofill.FillRequest.FLAG_MANUAL_REQUEST;
 import static android.view.autofill.Helper.sDebug;
 import static android.view.autofill.Helper.sVerbose;
@@ -370,6 +371,24 @@
     public static final String DEVICE_CONFIG_AUTOFILL_SMART_SUGGESTION_SUPPORTED_MODES =
             "smart_suggestion_supported_modes";
 
+    /**
+     * Sets how long (in ms) the augmented autofill service is bound while idle.
+     *
+     * <p>Use {@code 0} to keep it permanently bound.
+     *
+     * @hide
+     */
+    public static final String DEVICE_CONFIG_AUGMENTED_SERVICE_IDLE_UNBIND_TIMEOUT =
+            "augmented_service_idle_unbind_timeout";
+
+    /**
+     * Sets how long (in ms) the augmented autofill service request is killed if not replied.
+     *
+     * @hide
+     */
+    public static final String DEVICE_CONFIG_AUGMENTED_SERVICE_REQUEST_TIMEOUT =
+            "augmented_service_request_timeout";
+
     /** @hide */
     public static final int RESULT_OK = 0;
     /** @hide */
@@ -467,6 +486,13 @@
     @GuardedBy("mLock")
     @Nullable private ArraySet<AutofillId> mEnteredIds;
 
+    /**
+     * Views that were otherwised not important for autofill but triggered a session because the
+     * context is whitelisted for augmented autofill.
+     */
+    @GuardedBy("mLock")
+    @Nullable private Set<AutofillId> mEnteredForAugmentedAutofillIds;
+
     /** If set, session is commited when the field is clicked. */
     @GuardedBy("mLock")
     @Nullable private AutofillId mSaveTriggerId;
@@ -1626,6 +1652,11 @@
     @GuardedBy("mLock")
     private void startSessionLocked(@NonNull AutofillId id, @NonNull Rect bounds,
             @NonNull AutofillValue value, int flags) {
+        if (mEnteredForAugmentedAutofillIds != null
+                && mEnteredForAugmentedAutofillIds.contains(id)) {
+            if (sVerbose) Log.v(TAG, "Starting session for augmented autofill on " + id);
+            flags |= FLAG_AUGMENTED_AUTOFILL_REQUEST;
+        }
         if (sVerbose) {
             Log.v(TAG, "startSessionLocked(): id=" + id + ", bounds=" + bounds + ", value=" + value
                     + ", flags=" + flags + ", state=" + getStateAsStringLocked()
@@ -1861,6 +1892,25 @@
         return set == null ? null : new ArrayList<T>(set);
     }
 
+    /**
+     * Notifies that a non-autofillable view was entered because the activity is whitelisted for
+     * augmented autofill.
+     *
+     * <p>This method is necessary to set the right flag on start, so the server-side session
+     * doesn't trigger the standard autofill workflow, but the augmented's instead.
+     *
+     * @hide
+     */
+    public void notifyViewEnteredForAugmentedAutofill(@NonNull View view) {
+        final AutofillId id = view.getAutofillId();
+        synchronized (mLock) {
+            if (mEnteredForAugmentedAutofillIds == null) {
+                mEnteredForAugmentedAutofillIds = new ArraySet<>(1);
+            }
+            mEnteredForAugmentedAutofillIds.add(id);
+        }
+    }
+
     private void requestShowFillUi(int sessionId, AutofillId id, int width, int height,
             Rect anchorBounds, IAutofillWindowPresenter presenter) {
         final View anchor = findView(id);
@@ -2360,6 +2410,10 @@
         }
         pw.print(pfx); pw.print("fillable ids: "); pw.println(mFillableIds);
         pw.print(pfx); pw.print("entered ids: "); pw.println(mEnteredIds);
+        if (mEnteredForAugmentedAutofillIds != null) {
+            pw.print(pfx); pw.print("entered ids for augmented autofill: ");
+            pw.println(mEnteredForAugmentedAutofillIds);
+        }
         pw.print(pfx); pw.print("save trigger id: "); pw.println(mSaveTriggerId);
         pw.print(pfx); pw.print("save on finish(): "); pw.println(mSaveOnFinish);
         if (mOptions != null) {
diff --git a/core/java/android/view/autofill/AutofillValue.java b/core/java/android/view/autofill/AutofillValue.java
index 186a97d..64c8777 100644
--- a/core/java/android/view/autofill/AutofillValue.java
+++ b/core/java/android/view/autofill/AutofillValue.java
@@ -241,7 +241,7 @@
         }
     }
 
-    public static final Parcelable.Creator<AutofillValue> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AutofillValue> CREATOR =
             new Parcelable.Creator<AutofillValue>() {
         @Override
         public AutofillValue createFromParcel(Parcel source) {
diff --git a/core/java/android/view/autofill/ParcelableMap.java b/core/java/android/view/autofill/ParcelableMap.java
index f97b1a0..d8459aa 100644
--- a/core/java/android/view/autofill/ParcelableMap.java
+++ b/core/java/android/view/autofill/ParcelableMap.java
@@ -47,7 +47,7 @@
         }
     }
 
-    public static final Parcelable.Creator<ParcelableMap> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ParcelableMap> CREATOR =
             new Parcelable.Creator<ParcelableMap>() {
                 @Override
                 public ParcelableMap createFromParcel(Parcel source) {
diff --git a/core/java/android/view/contentcapture/ChildContentCaptureSession.java b/core/java/android/view/contentcapture/ChildContentCaptureSession.java
index 13e8a65..b3b0b72 100644
--- a/core/java/android/view/contentcapture/ChildContentCaptureSession.java
+++ b/core/java/android/view/contentcapture/ChildContentCaptureSession.java
@@ -84,8 +84,8 @@
     }
 
     @Override
-    public void internalNotifyViewHierarchyEvent(boolean started) {
-        getMainCaptureSession().notifyInitialViewHierarchyEvent(mId, started);
+    public void internalNotifyViewTreeEvent(boolean started) {
+        getMainCaptureSession().notifyViewTreeEvent(mId, started);
     }
 
     @Override
diff --git a/core/java/android/view/contentcapture/ContentCaptureContext.java b/core/java/android/view/contentcapture/ContentCaptureContext.java
index 8bb4d21..86f85bf 100644
--- a/core/java/android/view/contentcapture/ContentCaptureContext.java
+++ b/core/java/android/view/contentcapture/ContentCaptureContext.java
@@ -214,6 +214,7 @@
     /**
      * Helper that creates a {@link ContentCaptureContext} associated with the given {@code uri}.
      */
+    @NonNull
     public static ContentCaptureContext forLocusId(@NonNull Uri uri) {
         return new Builder(new LocusId(uri)).build();
     }
@@ -269,6 +270,7 @@
          *
          * @return the built {@code ContentCaptureContext}
          */
+        @NonNull
         public ContentCaptureContext build() {
             throwIfDestroyed();
             mDestroyed = true;
@@ -351,10 +353,11 @@
         }
     }
 
-    public static final Parcelable.Creator<ContentCaptureContext> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ContentCaptureContext> CREATOR =
             new Parcelable.Creator<ContentCaptureContext>() {
 
         @Override
+        @NonNull
         public ContentCaptureContext createFromParcel(Parcel parcel) {
             final boolean hasClientContext = parcel.readInt() == 1;
 
@@ -383,6 +386,7 @@
         }
 
         @Override
+        @NonNull
         public ContentCaptureContext[] newArray(int size) {
             return new ContentCaptureContext[size];
         }
diff --git a/core/java/android/view/contentcapture/ContentCaptureEvent.java b/core/java/android/view/contentcapture/ContentCaptureEvent.java
index 9cdbefa..67d3629 100644
--- a/core/java/android/view/contentcapture/ContentCaptureEvent.java
+++ b/core/java/android/view/contentcapture/ContentCaptureEvent.java
@@ -72,24 +72,24 @@
     public static final int TYPE_VIEW_TEXT_CHANGED = 3;
 
     /**
-     * Called before events (such as {@link #TYPE_VIEW_APPEARED}) representing the initial view
-     * hierarchy are sent.
+     * Called before events (such as {@link #TYPE_VIEW_APPEARED} and/or
+     * {@link #TYPE_VIEW_DISAPPEARED}) representing a view hierarchy are sent.
      *
      * <p><b>NOTE</b>: there is no guarantee this event will be sent. For example, it's not sent
      * if the initial view hierarchy doesn't initially have any view that's important for content
      * capture.
      */
-    public static final int TYPE_INITIAL_VIEW_TREE_APPEARING = 4;
+    public static final int TYPE_VIEW_TREE_APPEARING = 4;
 
     /**
-     * Called after events (such as {@link #TYPE_VIEW_APPEARED}) representing the initial view
-     * hierarchy are sent.
+     * Called after events (such as {@link #TYPE_VIEW_APPEARED} and/or
+     * {@link #TYPE_VIEW_DISAPPEARED}) representing a view hierarchy were sent.
      *
      * <p><b>NOTE</b>: there is no guarantee this event will be sent. For example, it's not sent
      * if the initial view hierarchy doesn't initially have any view that's important for content
      * capture.
      */
-    public static final int TYPE_INITIAL_VIEW_TREE_APPEARED = 5;
+    public static final int TYPE_VIEW_TREE_APPEARED = 5;
 
     /**
      * Called after a call to
@@ -99,14 +99,29 @@
      */
     public static final int TYPE_CONTEXT_UPDATED = 6;
 
+    /**
+     * Called after the session is ready, typically after the activity resumed and the
+     * initial views appeared
+     */
+    public static final int TYPE_SESSION_RESUMED = 7;
+
+    /**
+     * Called after the session is paused, typically after the activity paused and the
+     * views disappeared.
+     */
+    public static final int TYPE_SESSION_PAUSED = 8;
+
+
     /** @hide */
     @IntDef(prefix = { "TYPE_" }, value = {
             TYPE_VIEW_APPEARED,
             TYPE_VIEW_DISAPPEARED,
             TYPE_VIEW_TEXT_CHANGED,
-            TYPE_INITIAL_VIEW_TREE_APPEARING,
-            TYPE_INITIAL_VIEW_TREE_APPEARED,
-            TYPE_CONTEXT_UPDATED
+            TYPE_VIEW_TREE_APPEARING,
+            TYPE_VIEW_TREE_APPEARED,
+            TYPE_CONTEXT_UPDATED,
+            TYPE_SESSION_PAUSED,
+            TYPE_SESSION_RESUMED
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface EventType{}
@@ -230,8 +245,9 @@
      * Gets the type of the event.
      *
      * @return one of {@link #TYPE_VIEW_APPEARED}, {@link #TYPE_VIEW_DISAPPEARED},
-     * {@link #TYPE_VIEW_TEXT_CHANGED}, {@link #TYPE_INITIAL_VIEW_TREE_APPEARING},
-     * {@link #TYPE_INITIAL_VIEW_TREE_APPEARED}, or {@link #TYPE_CONTEXT_UPDATED}.
+     * {@link #TYPE_VIEW_TEXT_CHANGED}, {@link #TYPE_VIEW_TREE_APPEARING},
+     * {@link #TYPE_VIEW_TREE_APPEARED}, {@link #TYPE_CONTEXT_UPDATED},
+     * {@link #TYPE_SESSION_RESUMED}, or {@link #TYPE_SESSION_PAUSED}.
      */
     public @EventType int getType() {
         return mType;
@@ -367,10 +383,11 @@
         }
     }
 
-    public static final Parcelable.Creator<ContentCaptureEvent> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ContentCaptureEvent> CREATOR =
             new Parcelable.Creator<ContentCaptureEvent>() {
 
         @Override
+        @NonNull
         public ContentCaptureEvent createFromParcel(Parcel parcel) {
             final String sessionId = parcel.readString();
             final int type = parcel.readInt();
@@ -399,6 +416,7 @@
         }
 
         @Override
+        @NonNull
         public ContentCaptureEvent[] newArray(int size) {
             return new ContentCaptureEvent[size];
         }
@@ -411,16 +429,20 @@
                 return "SESSION_STARTED";
             case TYPE_SESSION_FINISHED:
                 return "SESSION_FINISHED";
+            case TYPE_SESSION_RESUMED:
+                return "SESSION_RESUMED";
+            case TYPE_SESSION_PAUSED:
+                return "SESSION_PAUSED";
             case TYPE_VIEW_APPEARED:
                 return "VIEW_APPEARED";
             case TYPE_VIEW_DISAPPEARED:
                 return "VIEW_DISAPPEARED";
             case TYPE_VIEW_TEXT_CHANGED:
                 return "VIEW_TEXT_CHANGED";
-            case TYPE_INITIAL_VIEW_TREE_APPEARING:
-                return "INITIAL_VIEW_HIERARCHY_STARTED";
-            case TYPE_INITIAL_VIEW_TREE_APPEARED:
-                return "INITIAL_VIEW_HIERARCHY_FINISHED";
+            case TYPE_VIEW_TREE_APPEARING:
+                return "VIEW_TREE_APPEARING";
+            case TYPE_VIEW_TREE_APPEARED:
+                return "VIEW_TREE_APPEARED";
             case TYPE_CONTEXT_UPDATED:
                 return "CONTEXT_UPDATED";
             default:
diff --git a/core/java/android/view/contentcapture/ContentCaptureManager.java b/core/java/android/view/contentcapture/ContentCaptureManager.java
index 336d997..885bd2a 100644
--- a/core/java/android/view/contentcapture/ContentCaptureManager.java
+++ b/core/java/android/view/contentcapture/ContentCaptureManager.java
@@ -129,6 +129,14 @@
     @TestApi
     public static final String DEVICE_CONFIG_PROPERTY_LOGGING_LEVEL = "logging_level";
 
+    /**
+     * Sets how long (in ms) the service is bound while idle.
+     *
+     * <p>Use {@code 0} to keep it permanently bound.
+     *
+     * @hide
+     */
+    public static final String DEVICE_CONFIG_PROPERTY_IDLE_UNBIND_TIMEOUT = "idle_unbind_timeout";
 
     /** @hide */
     @TestApi
@@ -224,7 +232,7 @@
 
     /** @hide */
     @UiThread
-    public void onActivityStarted(@NonNull IBinder applicationToken,
+    public void onActivityCreated(@NonNull IBinder applicationToken,
             @NonNull ComponentName activityComponent, int flags) {
         synchronized (mLock) {
             mFlags |= flags;
@@ -234,7 +242,19 @@
 
     /** @hide */
     @UiThread
-    public void onActivityStopped() {
+    public void onActivityResumed() {
+        getMainContentCaptureSession().notifySessionLifecycle(/* started= */ true);
+    }
+
+    /** @hide */
+    @UiThread
+    public void onActivityPaused() {
+        getMainContentCaptureSession().notifySessionLifecycle(/* started= */ false);
+    }
+
+    /** @hide */
+    @UiThread
+    public void onActivityDestroyed() {
         getMainContentCaptureSession().destroy();
     }
 
diff --git a/core/java/android/view/contentcapture/ContentCaptureSession.java b/core/java/android/view/contentcapture/ContentCaptureSession.java
index 1e051a4..6bf1eba 100644
--- a/core/java/android/view/contentcapture/ContentCaptureSession.java
+++ b/core/java/android/view/contentcapture/ContentCaptureSession.java
@@ -132,27 +132,24 @@
     /** @hide */
     public static final int FLUSH_REASON_FULL = 1;
     /** @hide */
-    public static final int FLUSH_REASON_ACTIVITY_PAUSED = 2;
+    public static final int FLUSH_REASON_VIEW_ROOT_ENTERED = 2;
     /** @hide */
-    public static final int FLUSH_REASON_ACTIVITY_RESUMED = 3;
+    public static final int FLUSH_REASON_SESSION_STARTED = 3;
     /** @hide */
-    public static final int FLUSH_REASON_SESSION_STARTED = 4;
+    public static final int FLUSH_REASON_SESSION_FINISHED = 4;
     /** @hide */
-    public static final int FLUSH_REASON_SESSION_FINISHED = 5;
-    /** @hide */
-    public static final int FLUSH_REASON_IDLE_TIMEOUT = 6;
+    public static final int FLUSH_REASON_IDLE_TIMEOUT = 5;
 
     /** @hide */
     @IntDef(prefix = { "FLUSH_REASON_" }, value = {
             FLUSH_REASON_FULL,
-            FLUSH_REASON_ACTIVITY_PAUSED,
-            FLUSH_REASON_ACTIVITY_RESUMED,
+            FLUSH_REASON_VIEW_ROOT_ENTERED,
             FLUSH_REASON_SESSION_STARTED,
             FLUSH_REASON_SESSION_FINISHED,
             FLUSH_REASON_IDLE_TIMEOUT
     })
     @Retention(RetentionPolicy.SOURCE)
-    @interface FlushReason{}
+    public @interface FlushReason{}
 
     private final Object mLock = new Object();
 
@@ -211,6 +208,7 @@
     /**
      * Gets the id used to identify this session.
      */
+    @NonNull
     public final ContentCaptureSessionId getContentCaptureSessionId() {
         if (mContentCaptureSessionId == null) {
             mContentCaptureSessionId = new ContentCaptureSessionId(mId);
@@ -414,7 +412,7 @@
             @Nullable CharSequence text);
 
     /** @hide */
-    public abstract void internalNotifyViewHierarchyEvent(boolean started);
+    public abstract void internalNotifyViewTreeEvent(boolean started);
 
     /**
      * Creates a {@link ViewStructure} for a "standard" view.
@@ -500,14 +498,12 @@
 
     /** @hide */
     @NonNull
-    static String getflushReasonAsString(@FlushReason int reason) {
+    public static String getFlushReasonAsString(@FlushReason int reason) {
         switch (reason) {
             case FLUSH_REASON_FULL:
                 return "FULL";
-            case FLUSH_REASON_ACTIVITY_PAUSED:
-                return "PAUSED";
-            case FLUSH_REASON_ACTIVITY_RESUMED:
-                return "RESUMED";
+            case FLUSH_REASON_VIEW_ROOT_ENTERED:
+                return "VIEW_ROOT";
             case FLUSH_REASON_SESSION_STARTED:
                 return "STARTED";
             case FLUSH_REASON_SESSION_FINISHED:
diff --git a/core/java/android/view/contentcapture/ContentCaptureSessionId.java b/core/java/android/view/contentcapture/ContentCaptureSessionId.java
index d7f9fcc..e7c350a 100644
--- a/core/java/android/view/contentcapture/ContentCaptureSessionId.java
+++ b/core/java/android/view/contentcapture/ContentCaptureSessionId.java
@@ -96,15 +96,17 @@
         parcel.writeString(mValue);
     }
 
-    public static final Parcelable.Creator<ContentCaptureSessionId> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ContentCaptureSessionId> CREATOR =
             new Parcelable.Creator<ContentCaptureSessionId>() {
 
         @Override
+        @NonNull
         public ContentCaptureSessionId createFromParcel(Parcel parcel) {
             return new ContentCaptureSessionId(parcel.readString());
         }
 
         @Override
+        @NonNull
         public ContentCaptureSessionId[] newArray(int size) {
             return new ContentCaptureSessionId[size];
         }
diff --git a/core/java/android/view/contentcapture/MainContentCaptureSession.java b/core/java/android/view/contentcapture/MainContentCaptureSession.java
index 0abf689..dce8ebe 100644
--- a/core/java/android/view/contentcapture/MainContentCaptureSession.java
+++ b/core/java/android/view/contentcapture/MainContentCaptureSession.java
@@ -16,13 +16,15 @@
 package android.view.contentcapture;
 
 import static android.view.contentcapture.ContentCaptureEvent.TYPE_CONTEXT_UPDATED;
-import static android.view.contentcapture.ContentCaptureEvent.TYPE_INITIAL_VIEW_TREE_APPEARED;
-import static android.view.contentcapture.ContentCaptureEvent.TYPE_INITIAL_VIEW_TREE_APPEARING;
 import static android.view.contentcapture.ContentCaptureEvent.TYPE_SESSION_FINISHED;
+import static android.view.contentcapture.ContentCaptureEvent.TYPE_SESSION_PAUSED;
+import static android.view.contentcapture.ContentCaptureEvent.TYPE_SESSION_RESUMED;
 import static android.view.contentcapture.ContentCaptureEvent.TYPE_SESSION_STARTED;
 import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_APPEARED;
 import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_DISAPPEARED;
 import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_TEXT_CHANGED;
+import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_TREE_APPEARED;
+import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_TREE_APPEARING;
 import static android.view.contentcapture.ContentCaptureHelper.getSanitizedString;
 import static android.view.contentcapture.ContentCaptureHelper.sDebug;
 import static android.view.contentcapture.ContentCaptureHelper.sVerbose;
@@ -126,7 +128,6 @@
     @Nullable
     private final LocalLog mFlushHistory;
 
-    /** @hide */
     protected MainContentCaptureSession(@NonNull Context context,
             @NonNull ContentCaptureManager manager, @NonNull Handler handler,
             @NonNull IContentCaptureManager systemServerInterface) {
@@ -153,8 +154,6 @@
 
     /**
      * Starts this session.
-     *
-     * @hide
      */
     @UiThread
     void start(@NonNull IBinder token, @NonNull ComponentName component,
@@ -451,7 +450,7 @@
         }
 
         final int numberEvents = mEvents.size();
-        final String reasonString = getflushReasonAsString(reason);
+        final String reasonString = getFlushReasonAsString(reason);
         if (sDebug) {
             Log.d(TAG, "Flushing " + numberEvents + " event(s) for " + getDebugState(reason));
         }
@@ -546,8 +545,8 @@
     }
 
     @Override
-    public void internalNotifyViewHierarchyEvent(boolean started) {
-        notifyInitialViewHierarchyEvent(mId, started);
+    public void internalNotifyViewTreeEvent(boolean started) {
+        notifyViewTreeEvent(mId, started);
     }
 
     @Override
@@ -581,21 +580,9 @@
                 .setViewNode(node.mNode));
     }
 
-    void notifyViewDisappeared(@NonNull String sessionId, @NonNull AutofillId id) {
-        sendEvent(
-                new ContentCaptureEvent(sessionId, TYPE_VIEW_DISAPPEARED).setAutofillId(id));
-    }
-
-    /** @hide */
-    public void notifyViewsDisappeared(@NonNull String sessionId,
-            @NonNull ArrayList<AutofillId> ids) {
-        final ContentCaptureEvent event = new ContentCaptureEvent(sessionId, TYPE_VIEW_DISAPPEARED);
-        if (ids.size() == 1) {
-            event.setAutofillId(ids.get(0));
-        } else {
-            event.setAutofillIds(ids);
-        }
-        sendEvent(event);
+    /** Public because is also used by ViewRootImpl */
+    public void notifyViewDisappeared(@NonNull String sessionId, @NonNull AutofillId id) {
+        sendEvent(new ContentCaptureEvent(sessionId, TYPE_VIEW_DISAPPEARED).setAutofillId(id));
     }
 
     void notifyViewTextChanged(@NonNull String sessionId, @NonNull AutofillId id,
@@ -604,13 +591,16 @@
                 .setText(text));
     }
 
-    void notifyInitialViewHierarchyEvent(@NonNull String sessionId, boolean started) {
-        if (started) {
-            sendEvent(new ContentCaptureEvent(sessionId, TYPE_INITIAL_VIEW_TREE_APPEARING));
-        } else {
-            sendEvent(new ContentCaptureEvent(sessionId, TYPE_INITIAL_VIEW_TREE_APPEARED),
-                    FORCE_FLUSH);
-        }
+    /** Public because is also used by ViewRootImpl */
+    public void notifyViewTreeEvent(@NonNull String sessionId, boolean started) {
+        final int type = started ? TYPE_VIEW_TREE_APPEARING : TYPE_VIEW_TREE_APPEARED;
+        sendEvent(new ContentCaptureEvent(sessionId, type), FORCE_FLUSH);
+    }
+
+    /** Public because is also used by ViewRootImpl */
+    public void notifySessionLifecycle(boolean started) {
+        final int type = started ? TYPE_SESSION_RESUMED : TYPE_SESSION_PAUSED;
+        sendEvent(new ContentCaptureEvent(mId, type), FORCE_FLUSH);
     }
 
     void notifyContextUpdated(@NonNull String sessionId,
@@ -684,6 +674,6 @@
 
     @NonNull
     private String getDebugState(@FlushReason int reason) {
-        return getDebugState() + ", reason=" + getflushReasonAsString(reason);
+        return getDebugState() + ", reason=" + getFlushReasonAsString(reason);
     }
 }
diff --git a/core/java/android/view/contentcapture/UserDataRemovalRequest.java b/core/java/android/view/contentcapture/UserDataRemovalRequest.java
index 7d66af9..b273f7c 100644
--- a/core/java/android/view/contentcapture/UserDataRemovalRequest.java
+++ b/core/java/android/view/contentcapture/UserDataRemovalRequest.java
@@ -121,6 +121,7 @@
          *
          * @return this builder
          */
+        @NonNull
         public Builder addLocusId(@NonNull LocusId locusId, boolean recursive) {
             throwIfDestroyed();
             Preconditions.checkState(!mForEverything, "Already is for everything");
@@ -174,15 +175,17 @@
         }
     }
 
-    public static final Parcelable.Creator<UserDataRemovalRequest> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<UserDataRemovalRequest> CREATOR =
             new Parcelable.Creator<UserDataRemovalRequest>() {
 
         @Override
+        @NonNull
         public UserDataRemovalRequest createFromParcel(Parcel parcel) {
             return new UserDataRemovalRequest(parcel);
         }
 
         @Override
+        @NonNull
         public UserDataRemovalRequest[] newArray(int size) {
             return new UserDataRemovalRequest[size];
         }
diff --git a/core/java/android/view/inputmethod/CompletionInfo.java b/core/java/android/view/inputmethod/CompletionInfo.java
index 70b8059..eee8a62 100644
--- a/core/java/android/view/inputmethod/CompletionInfo.java
+++ b/core/java/android/view/inputmethod/CompletionInfo.java
@@ -153,7 +153,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<CompletionInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<CompletionInfo> CREATOR
             = new Parcelable.Creator<CompletionInfo>() {
         public CompletionInfo createFromParcel(Parcel source) {
             return new CompletionInfo(source);
diff --git a/core/java/android/view/inputmethod/CorrectionInfo.java b/core/java/android/view/inputmethod/CorrectionInfo.java
index a43dfe8..6db5784 100644
--- a/core/java/android/view/inputmethod/CorrectionInfo.java
+++ b/core/java/android/view/inputmethod/CorrectionInfo.java
@@ -88,7 +88,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<CorrectionInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CorrectionInfo> CREATOR =
             new Parcelable.Creator<CorrectionInfo>() {
                 public CorrectionInfo createFromParcel(Parcel source) {
                     return new CorrectionInfo(source);
diff --git a/core/java/android/view/inputmethod/CursorAnchorInfo.java b/core/java/android/view/inputmethod/CursorAnchorInfo.java
index 24739bf..ee5b3ec 100644
--- a/core/java/android/view/inputmethod/CursorAnchorInfo.java
+++ b/core/java/android/view/inputmethod/CursorAnchorInfo.java
@@ -559,7 +559,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<CursorAnchorInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<CursorAnchorInfo> CREATOR
             = new Parcelable.Creator<CursorAnchorInfo>() {
         @Override
         public CursorAnchorInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/view/inputmethod/EditorInfo.java b/core/java/android/view/inputmethod/EditorInfo.java
index 8e7b0db..e1a9898 100644
--- a/core/java/android/view/inputmethod/EditorInfo.java
+++ b/core/java/android/view/inputmethod/EditorInfo.java
@@ -585,7 +585,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<EditorInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<EditorInfo> CREATOR =
             new Parcelable.Creator<EditorInfo>() {
                 public EditorInfo createFromParcel(Parcel source) {
                     EditorInfo res = new EditorInfo();
diff --git a/core/java/android/view/inputmethod/ExtractedText.java b/core/java/android/view/inputmethod/ExtractedText.java
index 1eb300e..159d2aa 100644
--- a/core/java/android/view/inputmethod/ExtractedText.java
+++ b/core/java/android/view/inputmethod/ExtractedText.java
@@ -115,7 +115,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<ExtractedText> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ExtractedText> CREATOR
             = new Parcelable.Creator<ExtractedText>() {
                 public ExtractedText createFromParcel(Parcel source) {
                     ExtractedText res = new ExtractedText();
diff --git a/core/java/android/view/inputmethod/ExtractedTextRequest.java b/core/java/android/view/inputmethod/ExtractedTextRequest.java
index bf0bef3..e442185 100644
--- a/core/java/android/view/inputmethod/ExtractedTextRequest.java
+++ b/core/java/android/view/inputmethod/ExtractedTextRequest.java
@@ -63,7 +63,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<ExtractedTextRequest> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<ExtractedTextRequest> CREATOR
             = new Parcelable.Creator<ExtractedTextRequest>() {
         public ExtractedTextRequest createFromParcel(Parcel source) {
             ExtractedTextRequest res = new ExtractedTextRequest();
diff --git a/core/java/android/view/inputmethod/InputBinding.java b/core/java/android/view/inputmethod/InputBinding.java
index bcd459e..2bfeb5a 100644
--- a/core/java/android/view/inputmethod/InputBinding.java
+++ b/core/java/android/view/inputmethod/InputBinding.java
@@ -135,7 +135,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<InputBinding> CREATOR = new Parcelable.Creator<InputBinding>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<InputBinding> CREATOR = new Parcelable.Creator<InputBinding>() {
         public InputBinding createFromParcel(Parcel source) {
             return new InputBinding(source);
         }
diff --git a/core/java/android/view/inputmethod/InputContentInfo.java b/core/java/android/view/inputmethod/InputContentInfo.java
index 0d0fea6..9aa410f 100644
--- a/core/java/android/view/inputmethod/InputContentInfo.java
+++ b/core/java/android/view/inputmethod/InputContentInfo.java
@@ -265,7 +265,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<InputContentInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<InputContentInfo> CREATOR
             = new Parcelable.Creator<InputContentInfo>() {
         @Override
         public InputContentInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/view/inputmethod/InputMethodInfo.java b/core/java/android/view/inputmethod/InputMethodInfo.java
index 04028ae..fe07fee 100644
--- a/core/java/android/view/inputmethod/InputMethodInfo.java
+++ b/core/java/android/view/inputmethod/InputMethodInfo.java
@@ -548,7 +548,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<InputMethodInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<InputMethodInfo> CREATOR
             = new Parcelable.Creator<InputMethodInfo>() {
         @Override
         public InputMethodInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/view/inputmethod/InputMethodSubtype.java b/core/java/android/view/inputmethod/InputMethodSubtype.java
index 14c879e..5989847 100644
--- a/core/java/android/view/inputmethod/InputMethodSubtype.java
+++ b/core/java/android/view/inputmethod/InputMethodSubtype.java
@@ -636,7 +636,7 @@
         dest.writeInt(mIsAsciiCapable ? 1 : 0);
     }
 
-    public static final Parcelable.Creator<InputMethodSubtype> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<InputMethodSubtype> CREATOR
             = new Parcelable.Creator<InputMethodSubtype>() {
         @Override
         public InputMethodSubtype createFromParcel(Parcel source) {
diff --git a/core/java/android/view/inputmethod/SparseRectFArray.java b/core/java/android/view/inputmethod/SparseRectFArray.java
index 484fe46..596ea86 100644
--- a/core/java/android/view/inputmethod/SparseRectFArray.java
+++ b/core/java/android/view/inputmethod/SparseRectFArray.java
@@ -292,7 +292,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<SparseRectFArray> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<SparseRectFArray> CREATOR =
             new Parcelable.Creator<SparseRectFArray>() {
                 @Override
                 public SparseRectFArray createFromParcel(Parcel source) {
diff --git a/core/java/android/view/textclassifier/ActionsSuggestionsHelper.java b/core/java/android/view/textclassifier/ActionsSuggestionsHelper.java
index 4d917a1..efdc968 100644
--- a/core/java/android/view/textclassifier/ActionsSuggestionsHelper.java
+++ b/core/java/android/view/textclassifier/ActionsSuggestionsHelper.java
@@ -16,6 +16,7 @@
 
 package android.view.textclassifier;
 
+import android.annotation.Nullable;
 import android.app.Person;
 import android.content.Context;
 import android.text.TextUtils;
@@ -110,6 +111,19 @@
                 SelectionSessionLogger.CLASSIFIER_ID, modelName, hash);
     }
 
+    /**
+     * Returns a {@link android.view.textclassifier.LabeledIntent.TitleChooser} for
+     * conversation actions use case.
+     */
+    @Nullable
+    public static LabeledIntent.TitleChooser createTitleChooser(String actionType) {
+        if (ConversationAction.TYPE_OPEN_URL.equals(actionType)) {
+            return (labeledIntent, resolveInfo) -> resolveInfo.handleAllWebDataURI
+                    ? labeledIntent.titleWithEntity : labeledIntent.titleWithoutEntity;
+        }
+        return null;
+    }
+
     private static final class PersonEncoder {
         private final Map<Person, Integer> mMapping = new ArrayMap<>();
         private int mNextUserId = FIRST_NON_LOCAL_USER;
diff --git a/core/java/android/view/textclassifier/ConversationAction.java b/core/java/android/view/textclassifier/ConversationAction.java
index ae6a645..2b952a3 100644
--- a/core/java/android/view/textclassifier/ConversationAction.java
+++ b/core/java/android/view/textclassifier/ConversationAction.java
@@ -95,7 +95,7 @@
     /** @hide **/
     public static final String TYPE_ADD_CONTACT = "add_contact";
 
-    public static final Creator<ConversationAction> CREATOR =
+    public static final @android.annotation.NonNull Creator<ConversationAction> CREATOR =
             new Creator<ConversationAction>() {
                 @Override
                 public ConversationAction createFromParcel(Parcel in) {
diff --git a/core/java/android/view/textclassifier/ConversationActions.java b/core/java/android/view/textclassifier/ConversationActions.java
index cf31445..9f9e666 100644
--- a/core/java/android/view/textclassifier/ConversationActions.java
+++ b/core/java/android/view/textclassifier/ConversationActions.java
@@ -44,7 +44,7 @@
  */
 public final class ConversationActions implements Parcelable {
 
-    public static final Creator<ConversationActions> CREATOR =
+    public static final @android.annotation.NonNull Creator<ConversationActions> CREATOR =
             new Creator<ConversationActions>() {
                 @Override
                 public ConversationActions createFromParcel(Parcel in) {
@@ -175,7 +175,7 @@
             return 0;
         }
 
-        public static final Creator<Message> CREATOR =
+        public static final @android.annotation.NonNull Creator<Message> CREATOR =
                 new Creator<Message>() {
                     @Override
                     public Message createFromParcel(Parcel in) {
@@ -367,7 +367,7 @@
             return 0;
         }
 
-        public static final Creator<Request> CREATOR =
+        public static final @android.annotation.NonNull Creator<Request> CREATOR =
                 new Creator<Request>() {
                     @Override
                     public Request createFromParcel(Parcel in) {
diff --git a/core/java/android/view/textclassifier/EntityConfidence.java b/core/java/android/view/textclassifier/EntityConfidence.java
index 69a59a5..3c51c38 100644
--- a/core/java/android/view/textclassifier/EntityConfidence.java
+++ b/core/java/android/view/textclassifier/EntityConfidence.java
@@ -108,7 +108,7 @@
         }
     }
 
-    public static final Parcelable.Creator<EntityConfidence> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<EntityConfidence> CREATOR =
             new Parcelable.Creator<EntityConfidence>() {
                 @Override
                 public EntityConfidence createFromParcel(Parcel in) {
diff --git a/core/java/android/view/textclassifier/IntentFactory.java b/core/java/android/view/textclassifier/IntentFactory.java
index 9f3b97f..722c812 100644
--- a/core/java/android/view/textclassifier/IntentFactory.java
+++ b/core/java/android/view/textclassifier/IntentFactory.java
@@ -32,7 +32,7 @@
     /**
      * Return a list of LabeledIntent from the classification result.
      */
-    List<TextClassifierImpl.LabeledIntent> create(
+    List<LabeledIntent> create(
             Context context,
             String text,
             boolean foreignText,
@@ -43,9 +43,10 @@
      * Inserts translate action to the list if it is a foreign text.
      */
     static void insertTranslateAction(
-            List<TextClassifierImpl.LabeledIntent> actions, Context context, String text) {
-        actions.add(new TextClassifierImpl.LabeledIntent(
+            List<LabeledIntent> actions, Context context, String text) {
+        actions.add(new LabeledIntent(
                 context.getString(com.android.internal.R.string.translate),
+                /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.translate_desc),
                 new Intent(Intent.ACTION_TRANSLATE)
                         // TODO: Probably better to introduce a "translate" scheme instead of
diff --git a/core/java/android/view/textclassifier/LabeledIntent.java b/core/java/android/view/textclassifier/LabeledIntent.java
new file mode 100644
index 0000000..7544dc1
--- /dev/null
+++ b/core/java/android/view/textclassifier/LabeledIntent.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.view.textclassifier;
+
+import android.annotation.Nullable;
+import android.app.PendingIntent;
+import android.app.RemoteAction;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.graphics.drawable.Icon;
+import android.text.TextUtils;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.Preconditions;
+
+/**
+ * Helper class to store the information from which RemoteActions are built.
+ *
+ * @hide
+ */
+@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+public final class LabeledIntent {
+    private static final String TAG = "LabeledIntent";
+    public static final int DEFAULT_REQUEST_CODE = 0;
+    private static final TitleChooser DEFAULT_TITLE_CHOOSER =
+            (labeledIntent, resolveInfo) -> {
+                if (!TextUtils.isEmpty(labeledIntent.titleWithEntity)) {
+                    return labeledIntent.titleWithEntity;
+                }
+                return labeledIntent.titleWithoutEntity;
+            };
+
+    @Nullable
+    public final String titleWithoutEntity;
+    @Nullable
+    public final String titleWithEntity;
+    public final String description;
+    // Do not update this intent.
+    public final Intent intent;
+    public final int requestCode;
+
+    /**
+     * Initializes a LabeledIntent.
+     *
+     * <p>NOTE: {@code requestCode} is required to not be {@link #DEFAULT_REQUEST_CODE}
+     * if distinguishing info (e.g. the classified text) is represented in intent extras only.
+     * In such circumstances, the request code should represent the distinguishing info
+     * (e.g. by generating a hashcode) so that the generated PendingIntent is (somewhat)
+     * unique. To be correct, the PendingIntent should be definitely unique but we try a
+     * best effort approach that avoids spamming the system with PendingIntents.
+     */
+    // TODO: Fix the issue mentioned above so the behaviour is correct.
+    public LabeledIntent(
+            @Nullable String titleWithoutEntity,
+            @Nullable String titleWithEntity,
+            String description,
+            Intent intent,
+            int requestCode) {
+        if (TextUtils.isEmpty(titleWithEntity) && TextUtils.isEmpty(titleWithoutEntity)) {
+            throw new IllegalArgumentException(
+                    "titleWithEntity and titleWithoutEntity should not be both null");
+        }
+        this.titleWithoutEntity = titleWithoutEntity;
+        this.titleWithEntity = titleWithEntity;
+        this.description = Preconditions.checkNotNull(description);
+        this.intent = Preconditions.checkNotNull(intent);
+        this.requestCode = requestCode;
+    }
+
+    /**
+     * Return the resolved result.
+     */
+    @Nullable
+    public Result resolve(
+            Context context, @Nullable TitleChooser titleChooser) {
+        final PackageManager pm = context.getPackageManager();
+        final ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
+        final String packageName = resolveInfo != null && resolveInfo.activityInfo != null
+                ? resolveInfo.activityInfo.packageName : null;
+        Icon icon = null;
+        Intent resolvedIntent = new Intent(intent);
+        boolean shouldShowIcon = false;
+        if (packageName != null && !"android".equals(packageName)) {
+            // There is a default activity handling the intent.
+            resolvedIntent.setComponent(
+                    new ComponentName(packageName, resolveInfo.activityInfo.name));
+            if (resolveInfo.activityInfo.getIconResource() != 0) {
+                icon = Icon.createWithResource(
+                        packageName, resolveInfo.activityInfo.getIconResource());
+                shouldShowIcon = true;
+            }
+        }
+        if (icon == null) {
+            // RemoteAction requires that there be an icon.
+            icon = Icon.createWithResource("android",
+                    com.android.internal.R.drawable.ic_more_items);
+        }
+        final PendingIntent pendingIntent =
+                TextClassification.createPendingIntent(context, resolvedIntent, requestCode);
+        if (pendingIntent == null) {
+            return null;
+        }
+        if (titleChooser == null) {
+            titleChooser = DEFAULT_TITLE_CHOOSER;
+        }
+        CharSequence title = titleChooser.chooseTitle(this, resolveInfo);
+        if (TextUtils.isEmpty(title)) {
+            Log.w(TAG, "Custom titleChooser return null, fallback to the default titleChooser");
+            title = DEFAULT_TITLE_CHOOSER.chooseTitle(this, resolveInfo);
+        }
+        final RemoteAction action =
+                new RemoteAction(icon, title, description, pendingIntent);
+        action.setShouldShowIcon(shouldShowIcon);
+        return new Result(resolvedIntent, action);
+    }
+
+    /**
+     * Data class that holds the result.
+     */
+    public static final class Result {
+        public final Intent resolvedIntent;
+        public final RemoteAction remoteAction;
+
+        public Result(Intent resolvedIntent, RemoteAction remoteAction) {
+            this.resolvedIntent = Preconditions.checkNotNull(resolvedIntent);
+            this.remoteAction = Preconditions.checkNotNull(remoteAction);
+        }
+    }
+
+    /**
+     * An object to choose a title from resolved info.  If {@code null} is returned,
+     * {@link #titleWithEntity} will be used if it exists, {@link #titleWithoutEntity} otherwise.
+     */
+    public interface TitleChooser {
+        /**
+         * Picks a title from a {@link LabeledIntent} by looking into resolved info.
+         */
+        @Nullable
+        CharSequence chooseTitle(LabeledIntent labeledIntent, ResolveInfo resolveInfo);
+    }
+}
diff --git a/core/java/android/view/textclassifier/LegacyIntentFactory.java b/core/java/android/view/textclassifier/LegacyIntentFactory.java
index 2d0d032..ea9229d 100644
--- a/core/java/android/view/textclassifier/LegacyIntentFactory.java
+++ b/core/java/android/view/textclassifier/LegacyIntentFactory.java
@@ -29,7 +29,6 @@
 import android.provider.Browser;
 import android.provider.CalendarContract;
 import android.provider.ContactsContract;
-import android.view.textclassifier.TextClassifierImpl.LabeledIntent;
 
 import com.google.android.textclassifier.AnnotatorModel;
 
@@ -100,8 +99,7 @@
             IntentFactory.insertTranslateAction(actions, context, text);
         }
         actions.forEach(
-                action -> action.getIntent()
-                        .putExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER, true));
+                action -> action.intent.putExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER, true));
         return actions;
     }
 
@@ -110,12 +108,14 @@
         final List<LabeledIntent> actions = new ArrayList<>();
         actions.add(new LabeledIntent(
                 context.getString(com.android.internal.R.string.email),
+                /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.email_desc),
                 new Intent(Intent.ACTION_SENDTO)
                         .setData(Uri.parse(String.format("mailto:%s", text))),
                 LabeledIntent.DEFAULT_REQUEST_CODE));
         actions.add(new LabeledIntent(
                 context.getString(com.android.internal.R.string.add_contact),
+                /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.add_contact_desc),
                 new Intent(Intent.ACTION_INSERT_OR_EDIT)
                         .setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE)
@@ -133,6 +133,7 @@
         if (!userRestrictions.getBoolean(UserManager.DISALLOW_OUTGOING_CALLS, false)) {
             actions.add(new LabeledIntent(
                     context.getString(com.android.internal.R.string.dial),
+                    /* titleWithEntity */ null,
                     context.getString(com.android.internal.R.string.dial_desc),
                     new Intent(Intent.ACTION_DIAL).setData(
                             Uri.parse(String.format("tel:%s", text))),
@@ -140,6 +141,7 @@
         }
         actions.add(new LabeledIntent(
                 context.getString(com.android.internal.R.string.add_contact),
+                /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.add_contact_desc),
                 new Intent(Intent.ACTION_INSERT_OR_EDIT)
                         .setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE)
@@ -148,6 +150,7 @@
         if (!userRestrictions.getBoolean(UserManager.DISALLOW_SMS, false)) {
             actions.add(new LabeledIntent(
                     context.getString(com.android.internal.R.string.sms),
+                    /* titleWithEntity */ null,
                     context.getString(com.android.internal.R.string.sms_desc),
                     new Intent(Intent.ACTION_SENDTO)
                             .setData(Uri.parse(String.format("smsto:%s", text))),
@@ -163,6 +166,7 @@
             final String encText = URLEncoder.encode(text, "UTF-8");
             actions.add(new LabeledIntent(
                     context.getString(com.android.internal.R.string.map),
+                    /* titleWithEntity */ null,
                     context.getString(com.android.internal.R.string.map_desc),
                     new Intent(Intent.ACTION_VIEW)
                             .setData(Uri.parse(String.format("geo:0,0?q=%s", encText))),
@@ -181,6 +185,7 @@
         final List<LabeledIntent> actions = new ArrayList<>();
         actions.add(new LabeledIntent(
                 context.getString(com.android.internal.R.string.browse),
+                /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.browse_desc),
                 new Intent(Intent.ACTION_VIEW)
                         .setDataAndNormalize(Uri.parse(text))
@@ -211,6 +216,7 @@
         final List<LabeledIntent> actions = new ArrayList<>();
         actions.add(new LabeledIntent(
                 context.getString(com.android.internal.R.string.view_flight),
+                /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.view_flight_desc),
                 new Intent(Intent.ACTION_WEB_SEARCH)
                         .putExtra(SearchManager.QUERY, text),
@@ -225,6 +231,7 @@
         ContentUris.appendId(builder, parsedTime.toEpochMilli());
         return new LabeledIntent(
                 context.getString(com.android.internal.R.string.view_calendar),
+                /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.view_calendar_desc),
                 new Intent(Intent.ACTION_VIEW).setData(builder.build()),
                 LabeledIntent.DEFAULT_REQUEST_CODE);
@@ -236,6 +243,7 @@
         final boolean isAllDay = TextClassifier.TYPE_DATE.equals(type);
         return new LabeledIntent(
                 context.getString(com.android.internal.R.string.add_calendar_event),
+                /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.add_calendar_event_desc),
                 new Intent(Intent.ACTION_INSERT)
                         .setData(CalendarContract.Events.CONTENT_URI)
@@ -252,6 +260,7 @@
         final List<LabeledIntent> actions = new ArrayList<>();
         actions.add(new LabeledIntent(
                 context.getString(com.android.internal.R.string.define),
+                /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.define_desc),
                 new Intent(Intent.ACTION_DEFINE)
                         .putExtra(Intent.EXTRA_TEXT, text),
diff --git a/core/java/android/view/textclassifier/SelectionEvent.java b/core/java/android/view/textclassifier/SelectionEvent.java
index b073596..105cbcc 100644
--- a/core/java/android/view/textclassifier/SelectionEvent.java
+++ b/core/java/android/view/textclassifier/SelectionEvent.java
@@ -643,7 +643,7 @@
                 mSessionId, mStart, mEnd, mSmartStart, mSmartEnd);
     }
 
-    public static final Creator<SelectionEvent> CREATOR = new Creator<SelectionEvent>() {
+    public static final @android.annotation.NonNull Creator<SelectionEvent> CREATOR = new Creator<SelectionEvent>() {
         @Override
         public SelectionEvent createFromParcel(Parcel in) {
             return new SelectionEvent(in);
diff --git a/core/java/android/view/textclassifier/TemplateClassificationIntentFactory.java b/core/java/android/view/textclassifier/TemplateClassificationIntentFactory.java
index 2467802..ed0259f 100644
--- a/core/java/android/view/textclassifier/TemplateClassificationIntentFactory.java
+++ b/core/java/android/view/textclassifier/TemplateClassificationIntentFactory.java
@@ -48,12 +48,12 @@
     }
 
     /**
-     * Returns a list of {@link android.view.textclassifier.TextClassifierImpl.LabeledIntent}
+     * Returns a list of {@link android.view.textclassifier.LabeledIntent}
      * that are constructed from the classification result.
      */
     @NonNull
     @Override
-    public List<TextClassifierImpl.LabeledIntent> create(
+    public List<LabeledIntent> create(
             Context context,
             String text,
             boolean foreignText,
@@ -68,7 +68,7 @@
             Log.w(TAG, "RemoteActionTemplate is missing, fallback to LegacyIntentFactory.");
             return mFallback.create(context, text, foreignText, referenceTime, classification);
         }
-        final List<TextClassifierImpl.LabeledIntent> labeledIntents =
+        final List<LabeledIntent> labeledIntents =
                 mTemplateIntentFactory.create(remoteActionTemplates);
         if (foreignText) {
             IntentFactory.insertTranslateAction(labeledIntents, context, text.trim());
diff --git a/core/java/android/view/textclassifier/TemplateIntentFactory.java b/core/java/android/view/textclassifier/TemplateIntentFactory.java
index 95f88c7..0696d98 100644
--- a/core/java/android/view/textclassifier/TemplateIntentFactory.java
+++ b/core/java/android/view/textclassifier/TemplateIntentFactory.java
@@ -42,29 +42,29 @@
     private static final String TAG = TextClassifier.DEFAULT_LOG_TAG;
 
     @NonNull
-    public List<TextClassifierImpl.LabeledIntent> create(
+    public List<LabeledIntent> create(
             @Nullable RemoteActionTemplate[] remoteActionTemplates) {
         if (ArrayUtils.isEmpty(remoteActionTemplates)) {
             return Collections.emptyList();
         }
-        final List<TextClassifierImpl.LabeledIntent> labeledIntents = new ArrayList<>();
+        final List<LabeledIntent> labeledIntents = new ArrayList<>();
         for (RemoteActionTemplate remoteActionTemplate : remoteActionTemplates) {
             if (!isValidTemplate(remoteActionTemplate)) {
                 Log.w(TAG, "Invalid RemoteActionTemplate skipped.");
                 continue;
             }
             labeledIntents.add(
-                    new TextClassifierImpl.LabeledIntent(
-                            remoteActionTemplate.title,
+                    new LabeledIntent(
+                            remoteActionTemplate.titleWithoutEntity,
+                            remoteActionTemplate.titleWithEntity,
                             remoteActionTemplate.description,
                             createIntent(remoteActionTemplate),
                             remoteActionTemplate.requestCode == null
-                                    ? TextClassifierImpl.LabeledIntent.DEFAULT_REQUEST_CODE
+                                    ? LabeledIntent.DEFAULT_REQUEST_CODE
                                     : remoteActionTemplate.requestCode));
         }
         labeledIntents.forEach(
-                action -> action.getIntent()
-                        .putExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER, true));
+                action -> action.intent.putExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER, true));
         return labeledIntents;
     }
 
@@ -73,7 +73,8 @@
             Log.w(TAG, "Invalid RemoteActionTemplate: is null");
             return false;
         }
-        if (TextUtils.isEmpty(remoteActionTemplate.title)) {
+        if (TextUtils.isEmpty(remoteActionTemplate.titleWithEntity)
+                && TextUtils.isEmpty(remoteActionTemplate.titleWithoutEntity)) {
             Log.w(TAG, "Invalid RemoteActionTemplate: title is null");
             return false;
         }
diff --git a/core/java/android/view/textclassifier/TextClassification.java b/core/java/android/view/textclassifier/TextClassification.java
index 052ee95..034da01 100644
--- a/core/java/android/view/textclassifier/TextClassification.java
+++ b/core/java/android/view/textclassifier/TextClassification.java
@@ -756,7 +756,7 @@
             return request;
         }
 
-        public static final Parcelable.Creator<Request> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<Request> CREATOR =
                 new Parcelable.Creator<Request>() {
                     @Override
                     public Request createFromParcel(Parcel in) {
@@ -785,7 +785,7 @@
         dest.writeBundle(mExtras);
     }
 
-    public static final Parcelable.Creator<TextClassification> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TextClassification> CREATOR =
             new Parcelable.Creator<TextClassification>() {
                 @Override
                 public TextClassification createFromParcel(Parcel in) {
diff --git a/core/java/android/view/textclassifier/TextClassificationContext.java b/core/java/android/view/textclassifier/TextClassificationContext.java
index a15411f..3bf8e9b 100644
--- a/core/java/android/view/textclassifier/TextClassificationContext.java
+++ b/core/java/android/view/textclassifier/TextClassificationContext.java
@@ -141,7 +141,7 @@
         mWidgetVersion = in.readString();
     }
 
-    public static final Parcelable.Creator<TextClassificationContext> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TextClassificationContext> CREATOR =
             new Parcelable.Creator<TextClassificationContext>() {
                 @Override
                 public TextClassificationContext createFromParcel(Parcel parcel) {
diff --git a/core/java/android/view/textclassifier/TextClassificationSessionId.java b/core/java/android/view/textclassifier/TextClassificationSessionId.java
index 1378bd9..5e62a11 100644
--- a/core/java/android/view/textclassifier/TextClassificationSessionId.java
+++ b/core/java/android/view/textclassifier/TextClassificationSessionId.java
@@ -115,7 +115,7 @@
         return new TextClassificationSessionId(string);
     }
 
-    public static final Parcelable.Creator<TextClassificationSessionId> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TextClassificationSessionId> CREATOR =
             new Parcelable.Creator<TextClassificationSessionId>() {
                 @Override
                 public TextClassificationSessionId createFromParcel(Parcel parcel) {
diff --git a/core/java/android/view/textclassifier/TextClassifier.java b/core/java/android/view/textclassifier/TextClassifier.java
index e010155..23ce90e 100644
--- a/core/java/android/view/textclassifier/TextClassifier.java
+++ b/core/java/android/view/textclassifier/TextClassifier.java
@@ -550,7 +550,7 @@
             return 0;
         }
 
-        public static final Parcelable.Creator<EntityConfig> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<EntityConfig> CREATOR =
                 new Parcelable.Creator<EntityConfig>() {
                     @Override
                     public EntityConfig createFromParcel(Parcel in) {
diff --git a/core/java/android/view/textclassifier/TextClassifierEvent.java b/core/java/android/view/textclassifier/TextClassifierEvent.java
index 0d4338b..236f89b 100644
--- a/core/java/android/view/textclassifier/TextClassifierEvent.java
+++ b/core/java/android/view/textclassifier/TextClassifierEvent.java
@@ -35,7 +35,7 @@
 // TODO: Comprehensive javadoc.
 public final class TextClassifierEvent implements Parcelable {
 
-    public static final Creator<TextClassifierEvent> CREATOR = new Creator<TextClassifierEvent>() {
+    public static final @android.annotation.NonNull Creator<TextClassifierEvent> CREATOR = new Creator<TextClassifierEvent>() {
         @Override
         public TextClassifierEvent createFromParcel(Parcel in) {
             return readFromParcel(in);
diff --git a/core/java/android/view/textclassifier/TextClassifierImpl.java b/core/java/android/view/textclassifier/TextClassifierImpl.java
index e628f19..632328b 100644
--- a/core/java/android/view/textclassifier/TextClassifierImpl.java
+++ b/core/java/android/view/textclassifier/TextClassifierImpl.java
@@ -19,21 +19,14 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.WorkerThread;
-import android.app.PendingIntent;
 import android.app.RemoteAction;
-import android.content.ComponentName;
 import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.graphics.drawable.Icon;
 import android.icu.util.ULocale;
 import android.os.Bundle;
 import android.os.LocaleList;
 import android.os.ParcelFileDescriptor;
 
 import com.android.internal.annotations.GuardedBy;
-import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.IndentingPrintWriter;
 import com.android.internal.util.Preconditions;
 
@@ -430,7 +423,12 @@
             // Given that we only support implicit intent here, we should expect there is just one
             // intent for each action type.
             if (!labeledIntents.isEmpty()) {
-                remoteAction = labeledIntents.get(0).asRemoteAction(mContext);
+                LabeledIntent.TitleChooser titleChooser =
+                        ActionsSuggestionsHelper.createTitleChooser(actionType);
+                LabeledIntent.Result result = labeledIntents.get(0).resolve(mContext, titleChooser);
+                if (result != null) {
+                    remoteAction = result.remoteAction;
+                }
             }
             conversationActions.add(
                     new ConversationAction.Builder(actionType)
@@ -593,23 +591,26 @@
                 foreignLanguageBundle != null,
                 referenceTime,
                 highestScoringResult);
+        LabeledIntent.TitleChooser titleChooser =
+                (labeledIntent, resolveInfo) -> labeledIntent.titleWithoutEntity;
         for (LabeledIntent labeledIntent : labeledIntents) {
-            final RemoteAction action = labeledIntent.asRemoteAction(mContext);
-            if (action == null) {
+            LabeledIntent.Result result = labeledIntent.resolve(mContext, titleChooser);
+            if (result == null) {
                 continue;
             }
+            final RemoteAction action = result.remoteAction;
             if (isPrimaryAction) {
                 // For O backwards compatibility, the first RemoteAction is also written to the
                 // legacy API fields.
                 builder.setIcon(action.getIcon().loadDrawable(mContext));
                 builder.setLabel(action.getTitle().toString());
-                builder.setIntent(labeledIntent.getIntent());
+                builder.setIntent(result.resolvedIntent);
                 builder.setOnClickListener(TextClassification.createIntentOnClickListener(
                         TextClassification.createPendingIntent(mContext,
-                                labeledIntent.getIntent(), labeledIntent.getRequestCode())));
+                                result.resolvedIntent, labeledIntent.requestCode)));
                 isPrimaryAction = false;
             }
-            builder.addAction(action, labeledIntent.getIntent());
+            builder.addAction(action, result.resolvedIntent);
         }
 
         return builder.setId(createId(text, start, end)).build();
@@ -737,89 +738,5 @@
             return LocaleList.getDefault().get(0).toLanguageTag();
         }
     }
-
-    /**
-     * Helper class to store the information from which RemoteActions are built.
-     */
-    @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
-    public static final class LabeledIntent {
-
-        static final int DEFAULT_REQUEST_CODE = 0;
-
-        private final String mTitle;
-        private final String mDescription;
-        private final Intent mIntent;
-        private final int mRequestCode;
-
-        /**
-         * Initializes a LabeledIntent.
-         *
-         * <p>NOTE: {@code reqestCode} is required to not be {@link #DEFAULT_REQUEST_CODE}
-         * if distinguishing info (e.g. the classified text) is represented in intent extras only.
-         * In such circumstances, the request code should represent the distinguishing info
-         * (e.g. by generating a hashcode) so that the generated PendingIntent is (somewhat)
-         * unique. To be correct, the PendingIntent should be definitely unique but we try a
-         * best effort approach that avoids spamming the system with PendingIntents.
-         */
-        // TODO: Fix the issue mentioned above so the behaviour is correct.
-        LabeledIntent(String title, String description, Intent intent, int requestCode) {
-            mTitle = title;
-            mDescription = description;
-            mIntent = intent;
-            mRequestCode = requestCode;
-        }
-
-        @VisibleForTesting
-        public String getTitle() {
-            return mTitle;
-        }
-
-        @VisibleForTesting
-        public String getDescription() {
-            return mDescription;
-        }
-
-        @VisibleForTesting
-        public Intent getIntent() {
-            return mIntent;
-        }
-
-        @VisibleForTesting
-        public int getRequestCode() {
-            return mRequestCode;
-        }
-
-        @Nullable
-        RemoteAction asRemoteAction(Context context) {
-            final PackageManager pm = context.getPackageManager();
-            final ResolveInfo resolveInfo = pm.resolveActivity(mIntent, 0);
-            final String packageName = resolveInfo != null && resolveInfo.activityInfo != null
-                    ? resolveInfo.activityInfo.packageName : null;
-            Icon icon = null;
-            boolean shouldShowIcon = false;
-            if (packageName != null && !"android".equals(packageName)) {
-                // There is a default activity handling the intent.
-                mIntent.setComponent(new ComponentName(packageName, resolveInfo.activityInfo.name));
-                if (resolveInfo.activityInfo.getIconResource() != 0) {
-                    icon = Icon.createWithResource(
-                            packageName, resolveInfo.activityInfo.getIconResource());
-                    shouldShowIcon = true;
-                }
-            }
-            if (icon == null) {
-                // RemoteAction requires that there be an icon.
-                icon = Icon.createWithResource("android",
-                        com.android.internal.R.drawable.ic_more_items);
-            }
-            final PendingIntent pendingIntent =
-                    TextClassification.createPendingIntent(context, mIntent, mRequestCode);
-            if (pendingIntent == null) {
-                return null;
-            }
-            final RemoteAction action = new RemoteAction(icon, mTitle, mDescription, pendingIntent);
-            action.setShouldShowIcon(shouldShowIcon);
-            return action;
-        }
-    }
 }
 
diff --git a/core/java/android/view/textclassifier/TextLanguage.java b/core/java/android/view/textclassifier/TextLanguage.java
index 735c3eb..eaf4d7f 100644
--- a/core/java/android/view/textclassifier/TextLanguage.java
+++ b/core/java/android/view/textclassifier/TextLanguage.java
@@ -43,7 +43,7 @@
  */
 public final class TextLanguage implements Parcelable {
 
-    public static final Creator<TextLanguage> CREATOR = new Creator<TextLanguage>() {
+    public static final @android.annotation.NonNull Creator<TextLanguage> CREATOR = new Creator<TextLanguage>() {
         @Override
         public TextLanguage createFromParcel(Parcel in) {
             return readFromParcel(in);
@@ -212,7 +212,7 @@
      */
     public static final class Request implements Parcelable {
 
-        public static final Creator<Request> CREATOR = new Creator<Request>() {
+        public static final @android.annotation.NonNull Creator<Request> CREATOR = new Creator<Request>() {
             @Override
             public Request createFromParcel(Parcel in) {
                 return readFromParcel(in);
diff --git a/core/java/android/view/textclassifier/TextLinks.java b/core/java/android/view/textclassifier/TextLinks.java
index ab34178..d8216ef 100644
--- a/core/java/android/view/textclassifier/TextLinks.java
+++ b/core/java/android/view/textclassifier/TextLinks.java
@@ -180,7 +180,7 @@
         dest.writeBundle(mExtras);
     }
 
-    public static final Parcelable.Creator<TextLinks> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TextLinks> CREATOR =
             new Parcelable.Creator<TextLinks>() {
                 @Override
                 public TextLinks createFromParcel(Parcel in) {
@@ -315,7 +315,7 @@
             return new TextLink(start, end, entityConfidence, extras, null /* urlSpan */);
         }
 
-        public static final Parcelable.Creator<TextLink> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<TextLink> CREATOR =
                 new Parcelable.Creator<TextLink>() {
                     @Override
                     public TextLink createFromParcel(Parcel in) {
@@ -528,7 +528,7 @@
             return request;
         }
 
-        public static final Parcelable.Creator<Request> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<Request> CREATOR =
                 new Parcelable.Creator<Request>() {
                     @Override
                     public Request createFromParcel(Parcel in) {
diff --git a/core/java/android/view/textclassifier/TextSelection.java b/core/java/android/view/textclassifier/TextSelection.java
index 4a6f3e5..52c532b 100644
--- a/core/java/android/view/textclassifier/TextSelection.java
+++ b/core/java/android/view/textclassifier/TextSelection.java
@@ -413,7 +413,7 @@
             return request;
         }
 
-        public static final Parcelable.Creator<Request> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<Request> CREATOR =
                 new Parcelable.Creator<Request>() {
                     @Override
                     public Request createFromParcel(Parcel in) {
@@ -441,7 +441,7 @@
         dest.writeBundle(mExtras);
     }
 
-    public static final Parcelable.Creator<TextSelection> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TextSelection> CREATOR =
             new Parcelable.Creator<TextSelection>() {
                 @Override
                 public TextSelection createFromParcel(Parcel in) {
diff --git a/core/java/android/view/textservice/SentenceSuggestionsInfo.java b/core/java/android/view/textservice/SentenceSuggestionsInfo.java
index afd62eb..0d37632 100644
--- a/core/java/android/view/textservice/SentenceSuggestionsInfo.java
+++ b/core/java/android/view/textservice/SentenceSuggestionsInfo.java
@@ -129,7 +129,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<SentenceSuggestionsInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<SentenceSuggestionsInfo> CREATOR
             = new Parcelable.Creator<SentenceSuggestionsInfo>() {
         @Override
         public SentenceSuggestionsInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/view/textservice/SpellCheckerInfo.java b/core/java/android/view/textservice/SpellCheckerInfo.java
index 7aa2c23..13d44da 100644
--- a/core/java/android/view/textservice/SpellCheckerInfo.java
+++ b/core/java/android/view/textservice/SpellCheckerInfo.java
@@ -192,7 +192,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<SpellCheckerInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<SpellCheckerInfo> CREATOR
             = new Parcelable.Creator<SpellCheckerInfo>() {
         @Override
         public SpellCheckerInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/view/textservice/SpellCheckerSubtype.java b/core/java/android/view/textservice/SpellCheckerSubtype.java
index d904d467..8224e0e 100644
--- a/core/java/android/view/textservice/SpellCheckerSubtype.java
+++ b/core/java/android/view/textservice/SpellCheckerSubtype.java
@@ -271,7 +271,7 @@
         dest.writeInt(mSubtypeId);
     }
 
-    public static final Parcelable.Creator<SpellCheckerSubtype> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<SpellCheckerSubtype> CREATOR
             = new Parcelable.Creator<SpellCheckerSubtype>() {
         @Override
         public SpellCheckerSubtype createFromParcel(Parcel source) {
diff --git a/core/java/android/view/textservice/SuggestionsInfo.java b/core/java/android/view/textservice/SuggestionsInfo.java
index dc2051c..e69b6e7 100644
--- a/core/java/android/view/textservice/SuggestionsInfo.java
+++ b/core/java/android/view/textservice/SuggestionsInfo.java
@@ -162,7 +162,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<SuggestionsInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<SuggestionsInfo> CREATOR
             = new Parcelable.Creator<SuggestionsInfo>() {
         @Override
         public SuggestionsInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/view/textservice/TextInfo.java b/core/java/android/view/textservice/TextInfo.java
index 5499918..571bdf3 100644
--- a/core/java/android/view/textservice/TextInfo.java
+++ b/core/java/android/view/textservice/TextInfo.java
@@ -138,7 +138,7 @@
     /**
      * Used to make this class parcelable.
      */
-    public static final Parcelable.Creator<TextInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<TextInfo> CREATOR
             = new Parcelable.Creator<TextInfo>() {
         @Override
         public TextInfo createFromParcel(Parcel source) {
diff --git a/core/java/android/webkit/IWebViewUpdateService.aidl b/core/java/android/webkit/IWebViewUpdateService.aidl
index dbca7ff..10cfea1 100644
--- a/core/java/android/webkit/IWebViewUpdateService.aidl
+++ b/core/java/android/webkit/IWebViewUpdateService.aidl
@@ -51,6 +51,7 @@
      * DevelopmentSettings uses this to get the current available WebView
      * providers (to display as choices to the user).
      */
+    @UnsupportedAppUsage
     WebViewProviderInfo[] getValidWebViewPackages();
 
     /**
@@ -61,6 +62,7 @@
     /**
      * Used by DevelopmentSetting to get the name of the WebView provider currently in use.
      */
+    @UnsupportedAppUsage
     String getCurrentWebViewPackageName();
 
     /**
@@ -72,6 +74,7 @@
      * Used by Settings to determine whether a certain package can be enabled/disabled by the user -
      * the package should not be modifiable in this way if it is a fallback package.
      */
+    @UnsupportedAppUsage
     boolean isFallbackPackage(String packageName);
 
     /**
diff --git a/core/java/android/webkit/WebViewProvider.java b/core/java/android/webkit/WebViewProvider.java
index baf5826..4c8f72a 100644
--- a/core/java/android/webkit/WebViewProvider.java
+++ b/core/java/android/webkit/WebViewProvider.java
@@ -351,7 +351,7 @@
         }
 
         default void onProvideContentCaptureStructure(
-                @SuppressWarnings("unused") android.view.ViewStructure structure,
+                @NonNull @SuppressWarnings("unused") android.view.ViewStructure structure,
                 @SuppressWarnings("unused") int flags) {
         }
 
diff --git a/core/java/android/webkit/WebViewProviderInfo.java b/core/java/android/webkit/WebViewProviderInfo.java
index 1704757..7e00cde 100644
--- a/core/java/android/webkit/WebViewProviderInfo.java
+++ b/core/java/android/webkit/WebViewProviderInfo.java
@@ -46,7 +46,7 @@
     }
 
     // aidl stuff
-    public static final Parcelable.Creator<WebViewProviderInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<WebViewProviderInfo> CREATOR =
         new Parcelable.Creator<WebViewProviderInfo>() {
             public WebViewProviderInfo createFromParcel(Parcel in) {
                 return new WebViewProviderInfo(in);
diff --git a/core/java/android/webkit/WebViewProviderResponse.java b/core/java/android/webkit/WebViewProviderResponse.java
index 0edcb6f..5622abe 100644
--- a/core/java/android/webkit/WebViewProviderResponse.java
+++ b/core/java/android/webkit/WebViewProviderResponse.java
@@ -30,7 +30,7 @@
     }
 
     // aidl stuff
-    public static final Parcelable.Creator<WebViewProviderResponse> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<WebViewProviderResponse> CREATOR =
         new Parcelable.Creator<WebViewProviderResponse>() {
             public WebViewProviderResponse createFromParcel(Parcel in) {
                 return new WebViewProviderResponse(in);
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index f01babe..7ca2304 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -1803,7 +1803,7 @@
                     + " checkState=" + checkState + "}";
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR
                 = new Parcelable.Creator<SavedState>() {
             @Override
             public SavedState createFromParcel(Parcel in) {
diff --git a/core/java/android/widget/AbsSpinner.java b/core/java/android/widget/AbsSpinner.java
index 3dcba48..daf6914 100644
--- a/core/java/android/widget/AbsSpinner.java
+++ b/core/java/android/widget/AbsSpinner.java
@@ -415,7 +415,7 @@
                     + " position=" + position + "}";
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR
                 = new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/widget/ActionMenuPresenter.java b/core/java/android/widget/ActionMenuPresenter.java
index eb20a76..cfb93ec 100644
--- a/core/java/android/widget/ActionMenuPresenter.java
+++ b/core/java/android/widget/ActionMenuPresenter.java
@@ -830,7 +830,7 @@
             dest.writeInt(openSubMenuId);
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR
                 = new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/widget/AdapterViewAnimator.java b/core/java/android/widget/AdapterViewAnimator.java
index 5174c1a..d93b635 100644
--- a/core/java/android/widget/AdapterViewAnimator.java
+++ b/core/java/android/widget/AdapterViewAnimator.java
@@ -804,7 +804,7 @@
             return "AdapterViewAnimator.SavedState{ whichChild = " + this.whichChild + " }";
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR
                 = new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/widget/CheckedTextView.java b/core/java/android/widget/CheckedTextView.java
index 99440f8..a211b46 100644
--- a/core/java/android/widget/CheckedTextView.java
+++ b/core/java/android/widget/CheckedTextView.java
@@ -493,7 +493,7 @@
                     + " checked=" + checked + "}";
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR
                 = new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/widget/CompoundButton.java b/core/java/android/widget/CompoundButton.java
index 3cfd373..80ec1c6 100644
--- a/core/java/android/widget/CompoundButton.java
+++ b/core/java/android/widget/CompoundButton.java
@@ -545,7 +545,7 @@
         }
 
         @SuppressWarnings("hiding")
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
             @Override
             public SavedState createFromParcel(Parcel in) {
diff --git a/core/java/android/widget/DatePicker.java b/core/java/android/widget/DatePicker.java
index ada4f00..ecb846b 100644
--- a/core/java/android/widget/DatePicker.java
+++ b/core/java/android/widget/DatePicker.java
@@ -791,7 +791,7 @@
 
             @SuppressWarnings("all")
             // suppress unused and hiding
-            public static final Parcelable.Creator<SavedState> CREATOR = new Creator<SavedState>() {
+            public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR = new Creator<SavedState>() {
 
                 public SavedState createFromParcel(Parcel in) {
                     return new SavedState(in);
diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java
index ded3be4e..b6ec5f9 100644
--- a/core/java/android/widget/Editor.java
+++ b/core/java/android/widget/Editor.java
@@ -1947,7 +1947,7 @@
 
             // Rebuild display list if it is invalid
             if (blockDisplayListIsInvalid) {
-                final RecordingCanvas recordingCanvas = blockDisplayList.start(
+                final RecordingCanvas recordingCanvas = blockDisplayList.beginRecording(
                         right - left, bottom - top);
                 try {
                     // drawText is always relative to TextView's origin, this translation
@@ -1958,7 +1958,7 @@
                     // No need to untranslate, previous context is popped after
                     // drawDisplayList
                 } finally {
-                    blockDisplayList.end(recordingCanvas);
+                    blockDisplayList.endRecording();
                     // Same as drawDisplayList below, handled by our TextView's parent
                     blockDisplayList.setClipToBounds(false);
                 }
diff --git a/core/java/android/widget/ExpandableListConnector.java b/core/java/android/widget/ExpandableListConnector.java
index bda64ba..f04f605 100644
--- a/core/java/android/widget/ExpandableListConnector.java
+++ b/core/java/android/widget/ExpandableListConnector.java
@@ -927,7 +927,7 @@
             dest.writeLong(gId);
         }
         
-        public static final Parcelable.Creator<GroupMetadata> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<GroupMetadata> CREATOR =
                 new Parcelable.Creator<GroupMetadata>() {
             
             public GroupMetadata createFromParcel(Parcel in) {
diff --git a/core/java/android/widget/ExpandableListView.java b/core/java/android/widget/ExpandableListView.java
index 2cc013e..cae91fc 100644
--- a/core/java/android/widget/ExpandableListView.java
+++ b/core/java/android/widget/ExpandableListView.java
@@ -1318,7 +1318,7 @@
             out.writeList(expandedGroupMetadataList);
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR
                 = new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/widget/GridView.java b/core/java/android/widget/GridView.java
index a6129b0..f44c331 100644
--- a/core/java/android/widget/GridView.java
+++ b/core/java/android/widget/GridView.java
@@ -312,7 +312,7 @@
      * @return The view that is currently selected, if it happens to be in the
      *         range that we draw.
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
     private View fillDown(int pos, int nextTop) {
         View selectedView = null;
 
@@ -412,7 +412,7 @@
      *
      * @return The view that is currently selected
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
     private View fillUp(int pos, int nextBottom) {
         View selectedView = null;
 
diff --git a/core/java/android/widget/HorizontalScrollView.java b/core/java/android/widget/HorizontalScrollView.java
index 25cfdc7..5921feb 100644
--- a/core/java/android/widget/HorizontalScrollView.java
+++ b/core/java/android/widget/HorizontalScrollView.java
@@ -1844,7 +1844,7 @@
                     + "}";
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR
                 = new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/widget/ListView.java b/core/java/android/widget/ListView.java
index 2aa019b..2f44d6e 100644
--- a/core/java/android/widget/ListView.java
+++ b/core/java/android/widget/ListView.java
@@ -782,7 +782,7 @@
      * @return The view that is currently selected, if it happens to be in the
      *         range that we draw.
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
     private View fillDown(int pos, int nextTop) {
         View selectedView = null;
 
@@ -817,7 +817,7 @@
      *
      * @return The view that is currently selected
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
     private View fillUp(int pos, int nextBottom) {
         View selectedView = null;
 
@@ -1490,7 +1490,7 @@
      * @return The selected view, or null if the selected view is outside the
      *         visible area.
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
     private View fillSpecific(int position, int top) {
         boolean tempIsSelected = position == mSelectedPosition;
         View temp = makeAndAddView(position, top, true, mListPadding.left, tempIsSelected);
diff --git a/core/java/android/widget/Magnifier.java b/core/java/android/widget/Magnifier.java
index 249f499..b7cdad2 100644
--- a/core/java/android/widget/Magnifier.java
+++ b/core/java/android/widget/Magnifier.java
@@ -859,7 +859,7 @@
             );
             setupOverlay();
 
-            final RecordingCanvas canvas = mRenderer.getRootNode().start(width, height);
+            final RecordingCanvas canvas = mRenderer.getRootNode().beginRecording(width, height);
             try {
                 canvas.insertReorderBarrier();
                 canvas.drawRenderNode(mBitmapRenderNode);
@@ -867,7 +867,7 @@
                 canvas.drawRenderNode(mOverlayRenderNode);
                 canvas.insertInorderBarrier();
             } finally {
-                mRenderer.getRootNode().end(canvas);
+                mRenderer.getRootNode().endRecording();
             }
             if (mCallback != null) {
                 mCurrentContent =
@@ -898,11 +898,12 @@
             bitmapRenderNode.setClipToOutline(true);
 
             // Create a dummy draw, which will be replaced later with real drawing.
-            final RecordingCanvas canvas = bitmapRenderNode.start(mContentWidth, mContentHeight);
+            final RecordingCanvas canvas = bitmapRenderNode.beginRecording(
+                    mContentWidth, mContentHeight);
             try {
                 canvas.drawColor(0xFF00FF00);
             } finally {
-                bitmapRenderNode.end(canvas);
+                bitmapRenderNode.endRecording();
             }
 
             return bitmapRenderNode;
@@ -954,7 +955,7 @@
             // Draw the drawable to the render node. This happens once during
             // initialization and whenever the overlay drawable is invalidated.
             final RecordingCanvas canvas =
-                    mOverlayRenderNode.startRecording(mContentWidth, mContentHeight);
+                    mOverlayRenderNode.beginRecording(mContentWidth, mContentHeight);
             try {
                 mOverlay.setBounds(0, 0, mContentWidth, mContentHeight);
                 mOverlay.draw(canvas);
@@ -1035,7 +1036,7 @@
                 }
 
                 final RecordingCanvas canvas =
-                        mBitmapRenderNode.start(mContentWidth, mContentHeight);
+                        mBitmapRenderNode.beginRecording(mContentWidth, mContentHeight);
                 try {
                     final Rect srcRect = new Rect(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
                     final Rect dstRect = new Rect(0, 0, mContentWidth, mContentHeight);
@@ -1043,7 +1044,7 @@
                     paint.setFilterBitmap(true);
                     canvas.drawBitmap(mBitmap, srcRect, dstRect, paint);
                 } finally {
-                    mBitmapRenderNode.end(canvas);
+                    mBitmapRenderNode.endRecording();
                 }
 
                 if (mPendingWindowPositionUpdate || mFirstDraw) {
@@ -1061,7 +1062,6 @@
                                 return;
                             }
                             synchronized (mLock) {
-                                mRenderer.setLightCenter(mDisplay, pendingX, pendingY);
                                 // Show or move the window at the content draw frame.
                                 SurfaceControl.openTransaction();
                                 mSurfaceControl.deferTransactionUntil(mSurface, frame);
@@ -1076,6 +1076,7 @@
                             }
                         }
                     };
+                    mRenderer.setLightCenter(mDisplay, pendingX, pendingY);
                 } else {
                     callback = null;
                 }
diff --git a/core/java/android/widget/ProgressBar.java b/core/java/android/widget/ProgressBar.java
index 8113b40..0b433b1 100644
--- a/core/java/android/widget/ProgressBar.java
+++ b/core/java/android/widget/ProgressBar.java
@@ -2061,7 +2061,7 @@
             out.writeInt(secondaryProgress);
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR
                 = new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java
index 8514b85..516c48e 100644
--- a/core/java/android/widget/RemoteViews.java
+++ b/core/java/android/widget/RemoteViews.java
@@ -3783,7 +3783,7 @@
     /**
      * Parcelable.Creator that instantiates RemoteViews objects
      */
-    public static final Parcelable.Creator<RemoteViews> CREATOR = new Parcelable.Creator<RemoteViews>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<RemoteViews> CREATOR = new Parcelable.Creator<RemoteViews>() {
         public RemoteViews createFromParcel(Parcel parcel) {
             return new RemoteViews(parcel);
         }
diff --git a/core/java/android/widget/ScrollView.java b/core/java/android/widget/ScrollView.java
index 7e72c6a..457be34 100644
--- a/core/java/android/widget/ScrollView.java
+++ b/core/java/android/widget/ScrollView.java
@@ -1978,7 +1978,7 @@
                     + " scrollPosition=" + scrollPosition + "}";
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR
                 = new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/widget/SearchView.java b/core/java/android/widget/SearchView.java
index 172f1d8..89d9e97 100644
--- a/core/java/android/widget/SearchView.java
+++ b/core/java/android/widget/SearchView.java
@@ -1433,7 +1433,7 @@
                     + " isIconified=" + isIconified + "}";
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
                     public SavedState createFromParcel(Parcel in) {
                         return new SavedState(in);
diff --git a/core/java/android/widget/Spinner.java b/core/java/android/widget/Spinner.java
index d6c657b..92fcea3 100644
--- a/core/java/android/widget/Spinner.java
+++ b/core/java/android/widget/Spinner.java
@@ -944,7 +944,7 @@
             out.writeByte((byte) (showDropdown ? 1 : 0));
         }
 
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
             public SavedState createFromParcel(Parcel in) {
                 return new SavedState(in);
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 51eaa12..73792b0 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -13062,7 +13062,7 @@
         }
 
         @SuppressWarnings("hiding")
-        public static final Parcelable.Creator<SavedState> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR =
                 new Parcelable.Creator<SavedState>() {
                     public SavedState createFromParcel(Parcel in) {
                         return new SavedState(in);
diff --git a/core/java/android/widget/TimePicker.java b/core/java/android/widget/TimePicker.java
index 97a8ade..c7a2980 100644
--- a/core/java/android/widget/TimePicker.java
+++ b/core/java/android/widget/TimePicker.java
@@ -552,7 +552,7 @@
             }
 
             @SuppressWarnings({"unused", "hiding"})
-            public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
+            public static final @android.annotation.NonNull Creator<SavedState> CREATOR = new Creator<SavedState>() {
                 public SavedState createFromParcel(Parcel in) {
                     return new SavedState(in);
                 }
diff --git a/core/java/android/widget/Toolbar.java b/core/java/android/widget/Toolbar.java
index f25109e..a21fb41 100644
--- a/core/java/android/widget/Toolbar.java
+++ b/core/java/android/widget/Toolbar.java
@@ -2384,7 +2384,7 @@
             out.writeInt(isOverflowOpen ? 1 : 0);
         }
 
-        public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
+        public static final @android.annotation.NonNull Creator<SavedState> CREATOR = new Creator<SavedState>() {
 
             @Override
             public SavedState createFromParcel(Parcel source) {
diff --git a/core/java/android/widget/ZoomControls.java b/core/java/android/widget/ZoomControls.java
index dd6a27b8f..7a5b7e8 100644
--- a/core/java/android/widget/ZoomControls.java
+++ b/core/java/android/widget/ZoomControls.java
@@ -30,7 +30,11 @@
 
 /**
  * The {@code ZoomControls} class displays a simple set of controls used for zooming and
- * provides callbacks to register for events. */
+ * provides callbacks to register for events.
+ * @deprecated This functionality and UI is better handled with custom views and layouts
+ * rather than a dedicated zoom-control widget
+ */
+@Deprecated
 @Widget
 public class ZoomControls extends LinearLayout {
 
diff --git a/core/java/com/android/internal/app/IAppOpsService.aidl b/core/java/com/android/internal/app/IAppOpsService.aidl
index 8a90cad..c096961 100644
--- a/core/java/com/android/internal/app/IAppOpsService.aidl
+++ b/core/java/com/android/internal/app/IAppOpsService.aidl
@@ -32,6 +32,7 @@
     int noteOperation(int code, int uid, String packageName);
     int startOperation(IBinder token, int code, int uid, String packageName,
             boolean startIfModeDefault);
+    @UnsupportedAppUsage
     void finishOperation(IBinder token, int code, int uid, String packageName);
     void startWatchingMode(int op, String packageName, IAppOpsCallback callback);
     void stopWatchingMode(IAppOpsCallback callback);
@@ -42,7 +43,9 @@
 
     // Remaining methods are only used in Java.
     int checkPackage(int uid, String packageName);
+    @UnsupportedAppUsage
     List<AppOpsManager.PackageOps> getPackagesForOps(in int[] ops);
+    @UnsupportedAppUsage
     List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName, in int[] ops);
     void getHistoricalOps(int uid, String packageName, in List<String> ops, long beginTimeMillis,
             long endTimeMillis, in RemoteCallback callback);
@@ -55,7 +58,9 @@
     void clearHistory();
     List<AppOpsManager.PackageOps> getUidOps(int uid, in int[] ops);
     void setUidMode(int code, int uid, int mode);
+    @UnsupportedAppUsage
     void setMode(int code, int uid, String packageName, int mode);
+    @UnsupportedAppUsage
     void resetAllModes(int reqUserId, String reqPackageName);
     int checkAudioOperation(int code, int usage, int uid, String packageName);
     void setAudioRestriction(int code, int usage, int uid, int mode, in String[] exceptionPackages);
diff --git a/core/java/com/android/internal/app/IBatteryStats.aidl b/core/java/com/android/internal/app/IBatteryStats.aidl
index d7514d1..114d31f 100644
--- a/core/java/com/android/internal/app/IBatteryStats.aidl
+++ b/core/java/com/android/internal/app/IBatteryStats.aidl
@@ -49,11 +49,13 @@
     void noteResetFlashlight();
 
     // Remaining methods are only used in Java.
+    @UnsupportedAppUsage
     byte[] getStatistics();
 
     ParcelFileDescriptor getStatisticsStream();
 
     // Return true if we see the battery as currently charging.
+    @UnsupportedAppUsage
     boolean isCharging();
 
     // Return the computed amount of time remaining on battery, in milliseconds.
@@ -62,6 +64,7 @@
 
     // Return the computed amount of time remaining to fully charge, in milliseconds.
     // Returns -1 if nothing could be computed.
+    @UnsupportedAppUsage
     long computeChargeTimeRemaining();
 
     void noteEvent(int code, String name, int uid);
@@ -131,6 +134,7 @@
     void noteDeviceIdleMode(int mode, String activeReason, int activeUid);
     void setBatteryState(int status, int health, int plugType, int level, int temp, int volt,
             int chargeUAh, int chargeFullUAh);
+    @UnsupportedAppUsage
     long getAwakeTimeBattery();
     long getAwakeTimePlugged();
 
diff --git a/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl b/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
index 9ce7ed1..420749e 100644
--- a/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
+++ b/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
@@ -51,6 +51,7 @@
      * @param keyphraseId The unique identifier for the keyphrase.
      * @param bcp47Locale The BCP47 language tag  for the keyphrase's locale.
      */
+    @UnsupportedAppUsage
     SoundTrigger.KeyphraseSoundModel getKeyphraseSoundModel(int keyphraseId, in String bcp47Locale);
     /**
      * Add/Update the given keyphrase sound model.
diff --git a/core/java/com/android/internal/appwidget/IAppWidgetService.aidl b/core/java/com/android/internal/appwidget/IAppWidgetService.aidl
index f9bf373..6d1d1ab 100644
--- a/core/java/com/android/internal/appwidget/IAppWidgetService.aidl
+++ b/core/java/com/android/internal/appwidget/IAppWidgetService.aidl
@@ -42,6 +42,7 @@
     void deleteAppWidgetId(String callingPackage, int appWidgetId);
     void deleteHost(String packageName, int hostId);
     void deleteAllHosts();
+    @UnsupportedAppUsage
     RemoteViews getAppWidgetViews(String callingPackage, int appWidgetId);
     int[] getAppWidgetIdsForHost(String callingPackage, int hostId);
     IntentSender createAppWidgetConfigIntentSender(String callingPackage, int appWidgetId,
@@ -63,11 +64,14 @@
     AppWidgetProviderInfo getAppWidgetInfo(String callingPackage, int appWidgetId);
     boolean hasBindAppWidgetPermission(in String packageName, int userId);
     void setBindAppWidgetPermission(in String packageName, int userId, in boolean permission);
+    @UnsupportedAppUsage
     boolean bindAppWidgetId(in String callingPackage, int appWidgetId,
             int providerProfileId, in ComponentName providerComponent, in Bundle options);
+    @UnsupportedAppUsage
     boolean bindRemoteViewsService(String callingPackage, int appWidgetId, in Intent intent,
             IApplicationThread caller, IBinder token, IServiceConnection connection, int flags);
 
+    @UnsupportedAppUsage
     int[] getAppWidgetIds(in ComponentName providerComponent);
     boolean isBoundWidgetPackage(String packageName, int userId);
     boolean requestPinAppWidget(String packageName, in ComponentName providerComponent,
diff --git a/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java b/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java
new file mode 100644
index 0000000..f3bf913
--- /dev/null
+++ b/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java
@@ -0,0 +1,93 @@
+/**
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.config.sysui;
+
+/**
+ * Keeps the flags related to the SystemUI namespace in {@link DeviceConfig}.
+ *
+ * @hide
+ */
+public final class SystemUiDeviceConfigFlags {
+
+    // Flags related to NotificationAssistant
+
+    /**
+     * Whether the Notification Assistant should generate replies for notifications.
+     */
+    public static final String NAS_GENERATE_REPLIES = "nas_generate_replies";
+
+    /**
+     * Whether the Notification Assistant should generate contextual actions for notifications.
+     */
+    public static final String NAS_GENERATE_ACTIONS = "nas_generate_actions";
+
+    /**
+     * The maximum number of messages the Notification Assistant should extract from a
+     * conversation when constructing responses for that conversation.
+     */
+    public static final String NAS_MAX_MESSAGES_TO_EXTRACT = "nas_max_messages_to_extract";
+
+    /**
+     * The maximum number of suggestions the Notification Assistant should provide for a
+     * messaging conversation.
+     */
+    public static final String NAS_MAX_SUGGESTIONS = "nas_max_suggestions";
+
+    // Flags related to Smart Suggestions - these are read in SmartReplyConstants.
+
+    /** (boolean) Whether to enable smart suggestions in notifications. */
+    public static final String SSIN_ENABLED = "ssin_enabled";
+
+    /**
+     * (boolean) Whether apps need to target at least P to provide their own smart replies (this
+     * doesn't apply to actions!).
+     */
+    public static final String SSIN_REQUIRES_TARGETING_P = "ssin_requires_targeting_p";
+
+    /**
+     * (int) The number of times we'll try to find a better line-break for double-line smart
+     * suggestion buttons.
+     */
+    public static final String SSIN_MAX_SQUEEZE_REMEASURE_ATTEMPTS =
+            "ssin_max_squeeze_remeasure_attempts";
+
+    /** (boolean) Whether to let the user edit smart replies before sending. */
+    public static final String SSIN_EDIT_CHOICES_BEFORE_SENDING =
+            "ssin_edit_choices_before_sending";
+
+    /** (boolean) Whether smart suggestions should be enabled in heads-up notifications. */
+    public static final String SSIN_SHOW_IN_HEADS_UP = "ssin_show_in_heads_up";
+
+    /** (int) Minimum number of system generated replies to show in a notification. */
+    public static final String SSIN_MIN_NUM_SYSTEM_GENERATED_REPLIES =
+            "ssin_min_num_system_generated_replies";
+
+    /**
+     * (int) Maximum number of actions to show in a notification, -1 if there shouldn't be a limit
+     */
+    public static final String SSIN_MAX_NUM_ACTIONS = "ssin_max_num_actions";
+
+    // Flags related to media notifications
+
+    /**
+     * (boolean) If {@code true}, enables the seekbar in compact media notifications.
+     */
+    public static final String COMPACT_MEDIA_SEEKBAR_ENABLED =
+            "compact_media_notification_seekbar_enabled";
+
+    private SystemUiDeviceConfigFlags() { }
+}
diff --git a/core/java/com/android/internal/infra/AbstractRemoteService.java b/core/java/com/android/internal/infra/AbstractRemoteService.java
index 732553b..f4c904d 100644
--- a/core/java/com/android/internal/infra/AbstractRemoteService.java
+++ b/core/java/com/android/internal/infra/AbstractRemoteService.java
@@ -67,7 +67,7 @@
     private static final int MSG_BIND = 1;
     private static final int MSG_UNBIND = 2;
 
-    protected static final long PERMANENT_BOUND_TIMEOUT_MS = 0;
+    public static final long PERMANENT_BOUND_TIMEOUT_MS = 0;
 
     protected static final int LAST_PRIVATE_MSG = MSG_UNBIND;
 
diff --git a/core/java/com/android/internal/os/BinderCallsStats.java b/core/java/com/android/internal/os/BinderCallsStats.java
index 2c78be7..bab4787 100644
--- a/core/java/com/android/internal/os/BinderCallsStats.java
+++ b/core/java/com/android/internal/os/BinderCallsStats.java
@@ -568,7 +568,7 @@
     }
 
     /**
-     * Aggregated data by uid/class/method to be sent through WestWorld.
+     * Aggregated data by uid/class/method to be sent through statsd.
      */
     public static class ExportedCallStat {
         public int callingUid;
diff --git a/core/java/com/android/internal/os/IDropBoxManagerService.aidl b/core/java/com/android/internal/os/IDropBoxManagerService.aidl
index 70844ee..5e60394 100644
--- a/core/java/com/android/internal/os/IDropBoxManagerService.aidl
+++ b/core/java/com/android/internal/os/IDropBoxManagerService.aidl
@@ -37,5 +37,6 @@
     boolean isTagEnabled(String tag);
 
     /** @see DropBoxManager#getNextEntry */
+    @UnsupportedAppUsage
     DropBoxManager.Entry getNextEntry(String tag, long millis, String packageName);
 }
diff --git a/core/java/com/android/internal/os/KernelCpuThreadReader.java b/core/java/com/android/internal/os/KernelCpuThreadReader.java
index 6bbfc2b..6a9db10 100644
--- a/core/java/com/android/internal/os/KernelCpuThreadReader.java
+++ b/core/java/com/android/internal/os/KernelCpuThreadReader.java
@@ -103,6 +103,16 @@
     private static final int ID_ERROR = -1;
 
     /**
+     * Thread ID used when reporting CPU used by other threads
+     */
+    private static final int OTHER_THREADS_ID = -1;
+
+    /**
+     * Thread name used when reporting CPU used by other threads
+     */
+    private static final String OTHER_THREADS_NAME = "__OTHER_THREADS";
+
+    /**
      * When checking whether to report data for a thread, we check the UID of the thread's owner
      * against this predicate
      */
@@ -140,9 +150,10 @@
     /**
      * Create with a path where `proc` is mounted. Used primarily for testing
      *
-     * @param procPath where `proc` is mounted (to find, see {@code mount | grep ^proc})
+     * @param procPath               where `proc` is mounted (to find, see {@code mount | grep
+     *                               ^proc})
      * @param initialTimeInStatePath where the initial {@code time_in_state} file exists to define
-     * format
+     *                               format
      */
     @VisibleForTesting
     public KernelCpuThreadReader(
@@ -250,8 +261,8 @@
      * Read all of the CPU usage statistics for each child thread of a process
      *
      * @param processPath the {@code /proc} path of the thread
-     * @param processId the ID of the process
-     * @param uid the ID of the user who owns the process
+     * @param processId   the ID of the process
+     * @param uid         the ID of the user who owns the process
      * @return process CPU usage containing usage of all child threads. Null if the process exited
      * and its {@code proc} directory was removed while collecting information
      */
@@ -263,14 +274,24 @@
                     + " and user ID " + uid);
         }
 
+        int[] filteredThreadsCpuUsage = null;
         final Path allThreadsPath = processPath.resolve("task");
         final ArrayList<ThreadCpuUsage> threadCpuUsages = new ArrayList<>();
         try (DirectoryStream<Path> threadPaths = Files.newDirectoryStream(allThreadsPath)) {
             for (Path threadDirectory : threadPaths) {
                 ThreadCpuUsage threadCpuUsage = getThreadCpuUsage(threadDirectory);
-                if (threadCpuUsage != null) {
-                    threadCpuUsages.add(threadCpuUsage);
+                if (threadCpuUsage == null) {
+                    continue;
                 }
+                if (mMinimumTotalCpuUsageMillis < totalCpuUsage(threadCpuUsage.usageTimesMillis)) {
+                    if (filteredThreadsCpuUsage == null) {
+                        filteredThreadsCpuUsage = new int[mFrequenciesKhz.length];
+                    }
+                    filteredThreadsCpuUsage =
+                            sumCpuUsage(filteredThreadsCpuUsage, threadCpuUsage.usageTimesMillis);
+                    continue;
+                }
+                threadCpuUsages.add(threadCpuUsage);
             }
         } catch (IOException e) {
             // Expected when a process finishes
@@ -282,6 +303,12 @@
             return null;
         }
 
+        // Add the filtered out thread CPU usage under an "other threads" ThreadCpuUsage
+        if (filteredThreadsCpuUsage != null) {
+            threadCpuUsages.add(new ThreadCpuUsage(
+                    OTHER_THREADS_ID, OTHER_THREADS_NAME, filteredThreadsCpuUsage));
+        }
+
         if (DEBUG) {
             Slog.d(TAG, "Read CPU usage of " + threadCpuUsages.size() + " threads");
         }
@@ -368,15 +395,6 @@
         }
         int[] cpuUsages = mFrequencyBucketCreator.getBucketedValues(cpuUsagesLong);
 
-        // Check if the total CPU usage below the threshold
-        int totalCpuUsage = 0;
-        for (int i = 0; i < cpuUsages.length; i++) {
-            totalCpuUsage += cpuUsages[i];
-        }
-        if (totalCpuUsage < mMinimumTotalCpuUsageMillis) {
-            return null;
-        }
-
         return new ThreadCpuUsage(threadId, threadName, cpuUsages);
     }
 
@@ -424,6 +442,28 @@
     }
 
     /**
+     * Get the sum of all CPU usage across all frequencies
+     */
+    private static int totalCpuUsage(int[] cpuUsage) {
+        int total = 0;
+        for (int i = 0; i < cpuUsage.length; i++) {
+            total += cpuUsage[i];
+        }
+        return total;
+    }
+
+    /**
+     * Add two CPU frequency usages together
+     */
+    private static int[] sumCpuUsage(int[] a, int[] b) {
+        int[] summed = new int[a.length];
+        for (int i = 0; i < a.length; i++) {
+            summed[i] = a[i] + b[i];
+        }
+        return summed;
+    }
+
+    /**
      * Puts frequencies and usage times into buckets
      */
     @VisibleForTesting
@@ -440,7 +480,7 @@
          * Buckets based of a list of frequencies
          *
          * @param frequencies the frequencies to base buckets off
-         * @param numBuckets how many buckets to create
+         * @param numBuckets  how many buckets to create
          */
         @VisibleForTesting
         public FrequencyBucketCreator(long[] frequencies, int numBuckets) {
diff --git a/core/java/com/android/internal/os/RoSystemProperties.java b/core/java/com/android/internal/os/RoSystemProperties.java
index f4902d4..524a5cc 100644
--- a/core/java/com/android/internal/os/RoSystemProperties.java
+++ b/core/java/com/android/internal/os/RoSystemProperties.java
@@ -61,17 +61,19 @@
             SystemProperties.getBoolean("ro.fw.system_user_split", false);
 
     // ------ ro.crypto.* -------- //
-    public static final String CRYPTO_STATE = SystemProperties.get("ro.crypto.state");
-    public static final String CRYPTO_TYPE = CryptoProperties.type().orElse("");
+    public static final CryptoProperties.state_values CRYPTO_STATE =
+            CryptoProperties.state().orElse(CryptoProperties.state_values.UNSUPPORTED);
+    public static final CryptoProperties.type_values CRYPTO_TYPE =
+            CryptoProperties.type().orElse(CryptoProperties.type_values.NONE);
     // These are pseudo-properties
     public static final boolean CRYPTO_ENCRYPTABLE =
-            !CRYPTO_STATE.isEmpty() && !"unsupported".equals(CRYPTO_STATE);
+            CRYPTO_STATE != CryptoProperties.state_values.UNSUPPORTED;
     public static final boolean CRYPTO_ENCRYPTED =
-            "encrypted".equalsIgnoreCase(CRYPTO_STATE);
+            CRYPTO_STATE == CryptoProperties.state_values.ENCRYPTED;
     public static final boolean CRYPTO_FILE_ENCRYPTED =
-            "file".equalsIgnoreCase(CRYPTO_TYPE);
+            CRYPTO_TYPE == CryptoProperties.type_values.FILE;
     public static final boolean CRYPTO_BLOCK_ENCRYPTED =
-            "block".equalsIgnoreCase(CRYPTO_TYPE);
+            CRYPTO_TYPE == CryptoProperties.type_values.BLOCK;
 
     public static final boolean CONTROL_PRIVAPP_PERMISSIONS_LOG =
             "log".equalsIgnoreCase(CONTROL_PRIVAPP_PERMISSIONS);
diff --git a/core/java/com/android/internal/os/Zygote.java b/core/java/com/android/internal/os/Zygote.java
index 0604ab2..0ccaec0 100644
--- a/core/java/com/android/internal/os/Zygote.java
+++ b/core/java/com/android/internal/os/Zygote.java
@@ -162,9 +162,9 @@
     /**
      * The duration to wait before re-checking Zygote related system properties.
      *
-     * Five minutes in milliseconds.
+     * One minute in milliseconds.
      */
-    public static final long PROPERTY_CHECK_INTERVAL = 300000;
+    public static final long PROPERTY_CHECK_INTERVAL = 60000;
 
     /**
      * @hide for internal use only
@@ -236,14 +236,14 @@
     public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
             int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
             int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
-            String packageName, String[] packagesForUID, String[] visibleVolIDs, String sandboxId) {
+            String packageName, String[] packagesForUID, String sandboxId) {
         ZygoteHooks.preFork();
         // Resets nice priority for zygote process.
         resetNicePriority();
         int pid = nativeForkAndSpecialize(
                 uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
                 fdsToIgnore, startChildZygote, instructionSet, appDataDir, packageName,
-                packagesForUID, visibleVolIDs, sandboxId);
+                packagesForUID, sandboxId);
         // Enable tracing as soon as possible for the child process.
         if (pid == 0) {
             Trace.setTracingEnabled(true, runtimeFlags);
@@ -258,7 +258,7 @@
     private static native int nativeForkAndSpecialize(int uid, int gid, int[] gids,
             int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
             int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet,
-            String appDataDir, String packageName, String[] packagesForUID, String[] visibleVolIDs,
+            String appDataDir, String packageName, String[] packagesForUID,
             String sandboxId);
 
     /**
@@ -285,11 +285,11 @@
     public static void specializeBlastula(int uid, int gid, int[] gids, int runtimeFlags,
             int[][] rlimits, int mountExternal, String seInfo, String niceName,
             boolean startChildZygote, String instructionSet, String appDataDir, String packageName,
-            String[] packagesForUID, String[] visibleVolIDs, String sandboxId) {
+            String[] packagesForUID, String sandboxId) {
 
         nativeSpecializeBlastula(uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo,
                                  niceName, startChildZygote, instructionSet, appDataDir,
-                                 packageName, packagesForUID, visibleVolIDs, sandboxId);
+                                 packageName, packagesForUID, sandboxId);
 
         // Enable tracing as soon as possible for the child process.
         Trace.setTracingEnabled(true, runtimeFlags);
@@ -309,7 +309,7 @@
     private static native void nativeSpecializeBlastula(int uid, int gid, int[] gids,
             int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
             boolean startChildZygote, String instructionSet, String appDataDir, String packageName,
-            String[] packagesForUID, String[] visibleVolIDs, String sandboxId);
+            String[] packagesForUID, String sandboxId);
 
     /**
      * Called to do any initialization before starting an application.
@@ -427,6 +427,12 @@
                 defaultValue);
     }
 
+    protected static void emptyBlastulaPool() {
+        nativeEmptyBlastulaPool();
+    }
+
+    private static native void nativeEmptyBlastulaPool();
+
     /**
      * Returns the value of a system property converted to a boolean using specific logic.
      *
@@ -520,7 +526,7 @@
         LocalSocket sessionSocket = null;
         DataOutputStream blastulaOutputStream = null;
         Credentials peerCredentials = null;
-        String[] argStrings = null;
+        ZygoteArguments args = null;
 
         while (true) {
             try {
@@ -533,25 +539,24 @@
 
                 peerCredentials = sessionSocket.getPeerCredentials();
 
-                argStrings = readArgumentList(blastulaReader);
+                String[] argStrings = readArgumentList(blastulaReader);
 
                 if (argStrings != null) {
+                    args = new ZygoteArguments(argStrings);
+
+                    // TODO (chriswailes): Should this only be run for debug builds?
+                    validateBlastulaCommand(args);
                     break;
                 } else {
                     Log.e("Blastula", "Truncated command received.");
                     IoUtils.closeQuietly(sessionSocket);
                 }
-            } catch (IOException ioEx) {
-                Log.e("Blastula", "Failed to read command: " + ioEx.getMessage());
+            } catch (Exception ex) {
+                Log.e("Blastula", ex.getMessage());
                 IoUtils.closeQuietly(sessionSocket);
             }
         }
 
-        ZygoteArguments args = new ZygoteArguments(argStrings);
-
-        // TODO (chriswailes): Should this only be run for debug builds?
-        validateBlastulaCommand(args);
-
         applyUidSecurityPolicy(args, peerCredentials);
         applyDebuggerSystemProperty(args);
 
@@ -600,7 +605,7 @@
                            args.mRuntimeFlags, rlimits, args.mMountExternal,
                            args.mSeInfo, args.mNiceName, args.mStartChildZygote,
                            args.mInstructionSet, args.mAppDataDir, args.mPackageName,
-                           args.mPackagesForUid, args.mVisibleVolIds, args.mSandboxId);
+                           args.mPackagesForUid, args.mSandboxId);
 
         if (args.mNiceName != null) {
             Process.setArgV0(args.mNiceName);
@@ -640,6 +645,9 @@
         } else if (args.mHiddenApiAccessLogSampleRate != -1) {
             throw new IllegalArgumentException(
                 BLASTULA_ERROR_PREFIX + "--hidden-api-log-sampling-rate=");
+        } else if (args.mHiddenApiAccessStatslogSampleRate != -1) {
+            throw new IllegalArgumentException(
+                BLASTULA_ERROR_PREFIX + "--hidden-api-statslog-sampling-rate=");
         } else if (args.mInvokeWith != null) {
             throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--invoke-with");
         } else if (args.mPermittedCapabilities != 0 || args.mEffectiveCapabilities != 0) {
@@ -740,8 +748,8 @@
 
         if (args.mInvokeWith != null && peerUid != 0
                 && (args.mRuntimeFlags & Zygote.DEBUG_ENABLE_JDWP) == 0) {
-            throw new ZygoteSecurityException("Peer is permitted to specify an"
-                + "explicit invoke-with wrapper command only for debuggable"
+            throw new ZygoteSecurityException("Peer is permitted to specify an "
+                + "explicit invoke-with wrapper command only for debuggable "
                 + "applications.");
         }
     }
diff --git a/core/java/com/android/internal/os/ZygoteArguments.java b/core/java/com/android/internal/os/ZygoteArguments.java
index c24a9e0..3beee78 100644
--- a/core/java/com/android/internal/os/ZygoteArguments.java
+++ b/core/java/com/android/internal/os/ZygoteArguments.java
@@ -101,6 +101,12 @@
     String mSeInfo;
 
     /**
+     *
+     */
+    boolean mBlastulaPoolEnabled;
+    boolean mBlastulaPoolStatusSpecified = false;
+
+    /**
      * from all --rlimit=r,c,m
      */
     ArrayList<int[]> mRLimits;
@@ -116,9 +122,6 @@
     /** from --packages-for-uid */
     String[] mPackagesForUid;
 
-    /** from --visible-vols */
-    String[] mVisibleVolIds;
-
     /** from --sandbox-id */
     String mSandboxId;
 
@@ -202,6 +205,12 @@
     int mHiddenApiAccessLogSampleRate = -1;
 
     /**
+     * Sampling rate for logging hidden API accesses to statslog. This is sent to the
+     * pre-forked zygote at boot time, or when it changes, via --hidden-api-statslog-sampling-rate.
+     */
+    int mHiddenApiAccessStatslogSampleRate = -1;
+
+    /**
      * Constructs instance and parses args
      *
      * @param args zygote command-line args
@@ -388,6 +397,15 @@
                         "Invalid log sampling rate: " + rateStr, nfe);
                 }
                 expectRuntimeArgs = false;
+            } else if (arg.startsWith("--hidden-api-statslog-sampling-rate=")) {
+                String rateStr = arg.substring(arg.indexOf('=') + 1);
+                try {
+                    mHiddenApiAccessStatslogSampleRate = Integer.parseInt(rateStr);
+                } catch (NumberFormatException nfe) {
+                    throw new IllegalArgumentException(
+                        "Invalid statslog sampling rate: " + rateStr, nfe);
+                }
+                expectRuntimeArgs = false;
             } else if (arg.startsWith("--package-name=")) {
                 if (mPackageName != null) {
                     throw new IllegalArgumentException("Duplicate arg specified");
@@ -395,13 +413,15 @@
                 mPackageName = arg.substring(arg.indexOf('=') + 1);
             } else if (arg.startsWith("--packages-for-uid=")) {
                 mPackagesForUid = arg.substring(arg.indexOf('=') + 1).split(",");
-            } else if (arg.startsWith("--visible-vols=")) {
-                mVisibleVolIds = arg.substring(arg.indexOf('=') + 1).split(",");
             } else if (arg.startsWith("--sandbox-id=")) {
                 if (mSandboxId != null) {
                     throw new IllegalArgumentException("Duplicate arg specified");
                 }
                 mSandboxId = arg.substring(arg.indexOf('=') + 1);
+            } else if (arg.startsWith("--blastula-pool-enabled=")) {
+                mBlastulaPoolStatusSpecified = true;
+                mBlastulaPoolEnabled = Boolean.parseBoolean(arg.substring(arg.indexOf('=') + 1));
+                expectRuntimeArgs = false;
             } else {
                 break;
             }
diff --git a/core/java/com/android/internal/os/ZygoteConnection.java b/core/java/com/android/internal/os/ZygoteConnection.java
index 8a878e2..bcdce31 100644
--- a/core/java/com/android/internal/os/ZygoteConnection.java
+++ b/core/java/com/android/internal/os/ZygoteConnection.java
@@ -37,6 +37,7 @@
 import android.system.Os;
 import android.system.StructPollfd;
 import android.util.Log;
+import android.util.StatsLog;
 
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
@@ -158,6 +159,10 @@
             return null;
         }
 
+        if (parsedArgs.mBlastulaPoolStatusSpecified) {
+            return handleBlastulaPoolStatusChange(zygoteServer, parsedArgs.mBlastulaPoolEnabled);
+        }
+
         if (parsedArgs.mPreloadDefault) {
             handlePreload();
             return null;
@@ -185,13 +190,14 @@
         }
 
         if (parsedArgs.mApiBlacklistExemptions != null) {
-            handleApiBlacklistExemptions(parsedArgs.mApiBlacklistExemptions);
-            return null;
+            return handleApiBlacklistExemptions(zygoteServer, parsedArgs.mApiBlacklistExemptions);
         }
 
-        if (parsedArgs.mHiddenApiAccessLogSampleRate != -1) {
-            handleHiddenApiAccessLogSampleRate(parsedArgs.mHiddenApiAccessLogSampleRate);
-            return null;
+        if (parsedArgs.mHiddenApiAccessLogSampleRate != -1
+                || parsedArgs.mHiddenApiAccessStatslogSampleRate != -1) {
+            return handleHiddenApiAccessLogSampleRate(zygoteServer,
+                    parsedArgs.mHiddenApiAccessLogSampleRate,
+                    parsedArgs.mHiddenApiAccessStatslogSampleRate);
         }
 
         if (parsedArgs.mPermittedCapabilities != 0 || parsedArgs.mEffectiveCapabilities != 0) {
@@ -258,7 +264,7 @@
                 parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
                 parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
                 parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mPackageName,
-                parsedArgs.mPackagesForUid, parsedArgs.mVisibleVolIds, parsedArgs.mSandboxId);
+                parsedArgs.mPackagesForUid, parsedArgs.mSandboxId);
 
         try {
             if (pid == 0) {
@@ -325,10 +331,64 @@
         }
     }
 
-    private void handleApiBlacklistExemptions(String[] exemptions) {
+    private Runnable stateChangeWithBlastulaPoolReset(ZygoteServer zygoteServer,
+            Runnable stateChangeCode) {
         try {
-            ZygoteInit.setApiBlacklistExemptions(exemptions);
+            if (zygoteServer.isBlastulaPoolEnabled()) {
+                Zygote.emptyBlastulaPool();
+            }
+
+            stateChangeCode.run();
+
+            if (zygoteServer.isBlastulaPoolEnabled()) {
+                Runnable fpResult =
+                        zygoteServer.fillBlastulaPool(
+                                new int[]{mSocket.getFileDescriptor().getInt$()});
+
+                if (fpResult != null) {
+                    zygoteServer.setForkChild();
+                    return fpResult;
+                }
+            }
+
             mSocketOutStream.writeInt(0);
+
+            return null;
+        } catch (IOException ioe) {
+            throw new IllegalStateException("Error writing to command socket", ioe);
+        }
+    }
+
+    /**
+     * Makes the necessary changes to implement a new API blacklist exemption policy, and then
+     * responds to the system server, letting it know that the task has been completed.
+     *
+     * This necessitates a change to the internal state of the Zygote.  As such, if the blastula
+     * pool is enabled all existing blastulas have an incorrect API blacklist exemption list.  To
+     * properly handle this request the pool must be emptied and refilled.  This process can return
+     * a Runnable object that must be returned to ZygoteServer.runSelectLoop to be invoked.
+     *
+     * @param zygoteServer  The server object that received the request
+     * @param exemptions  The new exemption list.
+     * @return A Runnable object representing a new app in any blastulas spawned from here; the
+     *         zygote process will always receive a null value from this function.
+     */
+    private Runnable handleApiBlacklistExemptions(ZygoteServer zygoteServer, String[] exemptions) {
+        return stateChangeWithBlastulaPoolReset(zygoteServer,
+                () -> ZygoteInit.setApiBlacklistExemptions(exemptions));
+    }
+
+    private Runnable handleBlastulaPoolStatusChange(ZygoteServer zygoteServer, boolean newStatus) {
+        try {
+            Runnable fpResult = zygoteServer.setBlastulaPoolStatus(newStatus, mSocket);
+
+            if (fpResult == null) {
+                mSocketOutStream.writeInt(0);
+            } else {
+                zygoteServer.setForkChild();
+            }
+
+            return fpResult;
         } catch (IOException ioe) {
             throw new IllegalStateException("Error writing to command socket", ioe);
         }
@@ -339,9 +399,11 @@
         private final MetricsLogger mMetricsLogger = new MetricsLogger();
         private static HiddenApiUsageLogger sInstance = new HiddenApiUsageLogger();
         private int mHiddenApiAccessLogSampleRate = 0;
+        private int mHiddenApiAccessStatslogSampleRate = 0;
 
-        public static void setHiddenApiAccessLogSampleRate(int sampleRate) {
+        public static void setHiddenApiAccessLogSampleRates(int sampleRate, int newSampleRate) {
             sInstance.mHiddenApiAccessLogSampleRate = sampleRate;
+            sInstance.mHiddenApiAccessStatslogSampleRate = newSampleRate;
         }
 
         public static HiddenApiUsageLogger getInstance() {
@@ -353,6 +415,9 @@
             if (sampledValue < mHiddenApiAccessLogSampleRate) {
                 logUsage(packageName, signature, accessMethod, accessDenied);
             }
+            if (sampledValue < mHiddenApiAccessStatslogSampleRate) {
+                newLogUsage(signature, accessMethod, accessDenied);
+            }
         }
 
         private void logUsage(String packageName, String signature, int accessMethod,
@@ -382,17 +447,52 @@
             }
             mMetricsLogger.write(logMaker);
         }
+
+        private void newLogUsage(String signature, int accessMethod, boolean accessDenied) {
+            int accessMethodProto = StatsLog.HIDDEN_API_USED__ACCESS_METHOD__NONE;
+            switch(accessMethod) {
+                case HiddenApiUsageLogger.ACCESS_METHOD_NONE:
+                    accessMethodProto = StatsLog.HIDDEN_API_USED__ACCESS_METHOD__NONE;
+                    break;
+                case HiddenApiUsageLogger.ACCESS_METHOD_REFLECTION:
+                    accessMethodProto = StatsLog.HIDDEN_API_USED__ACCESS_METHOD__REFLECTION;
+                    break;
+                case HiddenApiUsageLogger.ACCESS_METHOD_JNI:
+                    accessMethodProto = StatsLog.HIDDEN_API_USED__ACCESS_METHOD__JNI;
+                    break;
+                case HiddenApiUsageLogger.ACCESS_METHOD_LINKING:
+                    accessMethodProto = StatsLog.HIDDEN_API_USED__ACCESS_METHOD__LINKING;
+                    break;
+            }
+            int uid = Process.myUid();
+            StatsLog.write(StatsLog.HIDDEN_API_USED, uid, signature,
+                                   accessMethodProto, accessDenied);
+        }
     }
 
-    private void handleHiddenApiAccessLogSampleRate(int samplingRate) {
-        try {
-            ZygoteInit.setHiddenApiAccessLogSampleRate(samplingRate);
-            HiddenApiUsageLogger.setHiddenApiAccessLogSampleRate(samplingRate);
+    /**
+     * Changes the API access log sample rate for the Zygote and processes spawned from it.
+     *
+     * This necessitates a change to the internal state of the Zygote.  As such, if the blastula
+     * pool is enabled all existing blastulas have an incorrect API access log sample rate.  To
+     * properly handle this request the pool must be emptied and refilled.  This process can return
+     * a Runnable object that must be returned to ZygoteServer.runSelectLoop to be invoked.
+     *
+     * @param zygoteServer  The server object that received the request
+     * @param samplingRate  The new sample rate for regular logging
+     * @param statsdSamplingRate  The new sample rate for statslog logging
+     * @return A Runnable object representing a new app in any blastulas spawned from here; the
+     *         zygote process will always receive a null value from this function.
+     */
+    private Runnable handleHiddenApiAccessLogSampleRate(ZygoteServer zygoteServer,
+            int samplingRate, int statsdSamplingRate) {
+        return stateChangeWithBlastulaPoolReset(zygoteServer, () -> {
+            int maxSamplingRate = Math.max(samplingRate, statsdSamplingRate);
+            ZygoteInit.setHiddenApiAccessLogSampleRate(maxSamplingRate);
+            HiddenApiUsageLogger.setHiddenApiAccessLogSampleRates(samplingRate,
+                    statsdSamplingRate);
             ZygoteInit.setHiddenApiUsageLogger(HiddenApiUsageLogger.getInstance());
-            mSocketOutStream.writeInt(0);
-        } catch (IOException ioe) {
-            throw new IllegalStateException("Error writing to command socket", ioe);
-        }
+        });
     }
 
     protected void preload() {
diff --git a/core/java/com/android/internal/os/ZygoteServer.java b/core/java/com/android/internal/os/ZygoteServer.java
index 2c17540..c4c98ba 100644
--- a/core/java/com/android/internal/os/ZygoteServer.java
+++ b/core/java/com/android/internal/os/ZygoteServer.java
@@ -68,6 +68,15 @@
     private static final String BLASTULA_POOL_SIZE_MIN_DEFAULT = "1";
 
     /**
+     * Indicates if this Zygote server can support a blastula pool.  Currently this should only be
+     * true for the primary and secondary Zygotes, and not the App Zygotes or the WebView Zygote.
+     *
+     * TODO (chriswailes): Make this an explicit argument to the constructor
+     */
+
+    private final boolean mBlastulaPoolSupported;
+
+    /**
      * If the blastula pool should be created and used to start applications.
      *
      * Setting this value to false will disable the creation, maintenance, and use of the blastula
@@ -127,6 +136,8 @@
         mBlastulaPoolEventFD = null;
         mZygoteSocket = null;
         mBlastulaPoolSocket = null;
+
+        mBlastulaPoolSupported = false;
     }
 
     /**
@@ -151,12 +162,18 @@
         }
 
         fetchBlastulaPoolPolicyProps();
+
+        mBlastulaPoolSupported = true;
     }
 
     void setForkChild() {
         mIsForkChild = true;
     }
 
+    public boolean isBlastulaPoolEnabled() {
+        return mBlastulaPoolEnabled;
+    }
+
     /**
      * Registers a server socket for zygote command connections. This opens the server socket
      * at the specified name in the abstract socket namespace.
@@ -224,42 +241,43 @@
     }
 
     private void fetchBlastulaPoolPolicyProps() {
-        final String blastulaPoolSizeMaxPropString =
-                Zygote.getSystemProperty(
-                        DeviceConfig.RuntimeNative.BLASTULA_POOL_SIZE_MAX,
-                        BLASTULA_POOL_SIZE_MAX_DEFAULT);
+        if (mBlastulaPoolSupported) {
+            final String blastulaPoolSizeMaxPropString =
+                    Zygote.getSystemProperty(
+                            DeviceConfig.RuntimeNative.BLASTULA_POOL_SIZE_MAX,
+                            BLASTULA_POOL_SIZE_MAX_DEFAULT);
 
-        if (!blastulaPoolSizeMaxPropString.isEmpty()) {
-            mBlastulaPoolSizeMax =
-                    Integer.min(
-                            Integer.parseInt(blastulaPoolSizeMaxPropString),
-                            BLASTULA_POOL_SIZE_MAX_LIMIT);
+            if (!blastulaPoolSizeMaxPropString.isEmpty()) {
+                mBlastulaPoolSizeMax =
+                        Integer.min(
+                                Integer.parseInt(blastulaPoolSizeMaxPropString),
+                                BLASTULA_POOL_SIZE_MAX_LIMIT);
+            }
+
+            final String blastulaPoolSizeMinPropString =
+                    Zygote.getSystemProperty(
+                            DeviceConfig.RuntimeNative.BLASTULA_POOL_SIZE_MIN,
+                            BLASTULA_POOL_SIZE_MIN_DEFAULT);
+
+            if (!blastulaPoolSizeMinPropString.isEmpty()) {
+                mBlastulaPoolSizeMin =
+                        Integer.max(
+                                Integer.parseInt(blastulaPoolSizeMinPropString),
+                                BLASTULA_POOL_SIZE_MIN_LIMIT);
+            }
+
+            final String blastulaPoolRefillThresholdPropString =
+                    Zygote.getSystemProperty(
+                            DeviceConfig.RuntimeNative.BLASTULA_POOL_REFILL_THRESHOLD,
+                            Integer.toString(mBlastulaPoolSizeMax / 2));
+
+            if (!blastulaPoolRefillThresholdPropString.isEmpty()) {
+                mBlastulaPoolRefillThreshold =
+                        Integer.min(
+                                Integer.parseInt(blastulaPoolRefillThresholdPropString),
+                                mBlastulaPoolSizeMax);
+            }
         }
-
-        final String blastulaPoolSizeMinPropString =
-                Zygote.getSystemProperty(
-                        DeviceConfig.RuntimeNative.BLASTULA_POOL_SIZE_MIN,
-                        BLASTULA_POOL_SIZE_MIN_DEFAULT);
-
-        if (!blastulaPoolSizeMinPropString.isEmpty()) {
-            mBlastulaPoolSizeMin =
-                    Integer.max(
-                            Integer.parseInt(blastulaPoolSizeMinPropString),
-                            BLASTULA_POOL_SIZE_MIN_LIMIT);
-        }
-
-        final String blastulaPoolRefillThresholdPropString =
-                Zygote.getSystemProperty(
-                        DeviceConfig.RuntimeNative.BLASTULA_POOL_REFILL_THRESHOLD,
-                        Integer.toString(mBlastulaPoolSizeMax / 2));
-
-        if (!blastulaPoolRefillThresholdPropString.isEmpty()) {
-            mBlastulaPoolRefillThreshold =
-                    Integer.min(
-                        Integer.parseInt(blastulaPoolRefillThresholdPropString),
-                        mBlastulaPoolSizeMax);
-        }
-
     }
 
     private long mLastPropCheckTimestamp = 0;
@@ -282,44 +300,65 @@
      *         this function will return a Runnable object representing the new application that is
      *         passed up from blastulaMain.
      */
-    private Runnable fillBlastulaPool(int[] sessionSocketRawFDs) {
-        if (mBlastulaPoolEnabled) {
-            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Zygote:FillBlastulaPool");
 
-            int blastulaPoolCount = Zygote.getBlastulaPoolCount();
-            int numBlastulasToSpawn = mBlastulaPoolSizeMax - blastulaPoolCount;
+    Runnable fillBlastulaPool(int[] sessionSocketRawFDs) {
+        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Zygote:FillBlastulaPool");
 
-            if (blastulaPoolCount < mBlastulaPoolSizeMin
-                    || numBlastulasToSpawn >= mBlastulaPoolRefillThreshold) {
+        int blastulaPoolCount = Zygote.getBlastulaPoolCount();
+        int numBlastulasToSpawn = mBlastulaPoolSizeMax - blastulaPoolCount;
 
-                // Disable some VM functionality and reset some system values
-                // before forking.
-                ZygoteHooks.preFork();
-                Zygote.resetNicePriority();
+        if (blastulaPoolCount < mBlastulaPoolSizeMin
+                || numBlastulasToSpawn >= mBlastulaPoolRefillThreshold) {
 
-                while (blastulaPoolCount++ < mBlastulaPoolSizeMax) {
-                    Runnable caller = Zygote.forkBlastula(mBlastulaPoolSocket, sessionSocketRawFDs);
+            // Disable some VM functionality and reset some system values
+            // before forking.
+            ZygoteHooks.preFork();
+            Zygote.resetNicePriority();
 
-                    if (caller != null) {
-                        return caller;
-                    }
+            while (blastulaPoolCount++ < mBlastulaPoolSizeMax) {
+                Runnable caller = Zygote.forkBlastula(mBlastulaPoolSocket, sessionSocketRawFDs);
+
+                if (caller != null) {
+                    return caller;
                 }
-
-                // Re-enable runtime services for the Zygote.  Blastula services
-                // are re-enabled in specializeBlastula.
-                ZygoteHooks.postForkCommon();
-
-                Log.i("zygote",
-                        "Filled the blastula pool. New blastulas: " + numBlastulasToSpawn);
             }
 
-            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
+            // Re-enable runtime services for the Zygote.  Blastula services
+            // are re-enabled in specializeBlastula.
+            ZygoteHooks.postForkCommon();
+
+            Log.i("zygote",
+                    "Filled the blastula pool. New blastulas: " + numBlastulasToSpawn);
         }
 
+        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
+
         return null;
     }
 
     /**
+     * Empty or fill the blastula pool as dictated by the current and new blastula pool statuses.
+     */
+    Runnable setBlastulaPoolStatus(boolean newStatus, LocalSocket sessionSocket) {
+        if (!mBlastulaPoolSupported) {
+            Log.w(TAG,
+                    "Attempting to enable a blastula pool for a Zygote that doesn't support it.");
+            return null;
+        } else if (mBlastulaPoolEnabled == newStatus) {
+            return null;
+        }
+
+        mBlastulaPoolEnabled = newStatus;
+
+        if (newStatus) {
+            return fillBlastulaPool(new int[]{ sessionSocket.getFileDescriptor().getInt$() });
+        } else {
+            Zygote.emptyBlastulaPool();
+            return null;
+        }
+    }
+
+    /**
      * Runs the zygote process's select loop. Accepts new connections as
      * they happen, and reads commands from connections one spawn-request's
      * worth at a time.
@@ -334,12 +373,26 @@
         while (true) {
             fetchBlastulaPoolPolicyPropsWithMinInterval();
 
-            int[] blastulaPipeFDs = Zygote.getBlastulaPipeFDs();
+            int[] blastulaPipeFDs = null;
+            StructPollfd[] pollFDs = null;
 
-            // Space for all of the socket FDs, the Blastula Pool Event FD, and
-            // all of the open blastula read pipe FDs.
-            StructPollfd[] pollFDs =
-                new StructPollfd[socketFDs.size() + 1 + blastulaPipeFDs.length];
+            // Allocate enough space for the poll structs, taking into account
+            // the state of the blastula pool for this Zygote (could be a
+            // regular Zygote, a WebView Zygote, or an AppZygote).
+            if (mBlastulaPoolEnabled) {
+                blastulaPipeFDs = Zygote.getBlastulaPipeFDs();
+                pollFDs = new StructPollfd[socketFDs.size() + 1 + blastulaPipeFDs.length];
+            } else {
+                pollFDs = new StructPollfd[socketFDs.size()];
+            }
+
+            /*
+             * For reasons of correctness the blastula pool pipe and event FDs
+             * must be processed before the session and server sockets.  This
+             * is to ensure that the blastula pool accounting information is
+             * accurate when handling other requests like API blacklist
+             * exemptions.
+             */
 
             int pollIndex = 0;
             for (FileDescriptor socketFD : socketFDs) {
@@ -350,19 +403,22 @@
             }
 
             final int blastulaPoolEventFDIndex = pollIndex;
-            pollFDs[pollIndex] = new StructPollfd();
-            pollFDs[pollIndex].fd = mBlastulaPoolEventFD;
-            pollFDs[pollIndex].events = (short) POLLIN;
-            ++pollIndex;
 
-            for (int blastulaPipeFD : blastulaPipeFDs) {
-                FileDescriptor managedFd = new FileDescriptor();
-                managedFd.setInt$(blastulaPipeFD);
-
+            if (mBlastulaPoolEnabled) {
                 pollFDs[pollIndex] = new StructPollfd();
-                pollFDs[pollIndex].fd = managedFd;
+                pollFDs[pollIndex].fd = mBlastulaPoolEventFD;
                 pollFDs[pollIndex].events = (short) POLLIN;
                 ++pollIndex;
+
+                for (int blastulaPipeFD : blastulaPipeFDs) {
+                    FileDescriptor managedFd = new FileDescriptor();
+                    managedFd.setInt$(blastulaPipeFD);
+
+                    pollFDs[pollIndex] = new StructPollfd();
+                    pollFDs[pollIndex].fd = managedFd;
+                    pollFDs[pollIndex].events = (short) POLLIN;
+                    ++pollIndex;
+                }
             }
 
             try {
@@ -371,6 +427,8 @@
                 throw new RuntimeException("poll failed", ex);
             }
 
+            boolean blastulaPoolFDRead = false;
+
             while (--pollIndex >= 0) {
                 if ((pollFDs[pollIndex].revents & POLLIN) == 0) {
                     continue;
@@ -390,6 +448,7 @@
                         ZygoteConnection connection = peers.get(pollIndex);
                         final Runnable command = connection.processOneCommand(this);
 
+                        // TODO (chriswailes): Is this extra check necessary?
                         if (mIsForkChild) {
                             // We're in the child. We should always have a command to run at this
                             // stage if processOneCommand hasn't called "exec".
@@ -480,17 +539,22 @@
                         Zygote.removeBlastulaTableEntry((int) messagePayload);
                     }
 
-                    int[] sessionSocketRawFDs =
-                            socketFDs.subList(1, socketFDs.size())
+                    blastulaPoolFDRead = true;
+                }
+            }
+
+            // Check to see if the blastula pool needs to be refilled.
+            if (blastulaPoolFDRead) {
+                int[] sessionSocketRawFDs =
+                        socketFDs.subList(1, socketFDs.size())
                                 .stream()
                                 .mapToInt(fd -> fd.getInt$())
                                 .toArray();
 
-                    final Runnable command = fillBlastulaPool(sessionSocketRawFDs);
+                final Runnable command = fillBlastulaPool(sessionSocketRawFDs);
 
-                    if (command != null) {
-                        return command;
-                    }
+                if (command != null) {
+                    return command;
                 }
             }
         }
diff --git a/core/java/com/android/internal/policy/BackdropFrameRenderer.java b/core/java/com/android/internal/policy/BackdropFrameRenderer.java
index cc958f4..fa73758 100644
--- a/core/java/com/android/internal/policy/BackdropFrameRenderer.java
+++ b/core/java/com/android/internal/policy/BackdropFrameRenderer.java
@@ -339,7 +339,7 @@
         mFrameAndBackdropNode.setLeftTopRightBottom(left, top, left + width, top + height);
 
         // Draw the caption and content backdrops in to our render node.
-        RecordingCanvas canvas = mFrameAndBackdropNode.start(width, height);
+        RecordingCanvas canvas = mFrameAndBackdropNode.beginRecording(width, height);
         final Drawable drawable = mUserCaptionBackgroundDrawable != null
                 ? mUserCaptionBackgroundDrawable : mCaptionBackgroundDrawable;
 
@@ -353,7 +353,7 @@
             mResizingBackgroundDrawable.setBounds(0, mLastCaptionHeight, left + width, top + height);
             mResizingBackgroundDrawable.draw(canvas);
         }
-        mFrameAndBackdropNode.end(canvas);
+        mFrameAndBackdropNode.endRecording();
 
         drawColorViews(left, top, width, height, fullscreen, systemInsets, stableInsets);
 
@@ -368,7 +368,7 @@
         if (mSystemBarBackgroundNode == null) {
             return;
         }
-        RecordingCanvas canvas = mSystemBarBackgroundNode.start(width, height);
+        RecordingCanvas canvas = mSystemBarBackgroundNode.beginRecording(width, height);
         mSystemBarBackgroundNode.setLeftTopRightBottom(left, top, left + width, top + height);
         final int topInset = DecorView.getColorViewTopInset(mStableInsets.top, mSystemInsets.top);
         if (mStatusBarColor != null) {
@@ -384,7 +384,7 @@
             mNavigationBarColor.setBounds(mTmpRect);
             mNavigationBarColor.draw(canvas);
         }
-        mSystemBarBackgroundNode.end(canvas);
+        mSystemBarBackgroundNode.endRecording();
         mRenderer.drawRenderNode(mSystemBarBackgroundNode);
     }
 
diff --git a/core/java/com/android/internal/policy/IKeyguardService.aidl b/core/java/com/android/internal/policy/IKeyguardService.aidl
index e5d5685..54f31f9 100644
--- a/core/java/com/android/internal/policy/IKeyguardService.aidl
+++ b/core/java/com/android/internal/policy/IKeyguardService.aidl
@@ -88,8 +88,10 @@
      */
     void onScreenTurnedOff();
 
+    @UnsupportedAppUsage
     void setKeyguardEnabled(boolean enabled);
     void onSystemReady();
+    @UnsupportedAppUsage
     void doKeyguardTimeout(in Bundle options);
     void setSwitchingUser(boolean switching);
     void setCurrentUser(int userId);
diff --git a/core/java/com/android/internal/statusbar/IStatusBarService.aidl b/core/java/com/android/internal/statusbar/IStatusBarService.aidl
index bfb5084..3437614 100644
--- a/core/java/com/android/internal/statusbar/IStatusBarService.aidl
+++ b/core/java/com/android/internal/statusbar/IStatusBarService.aidl
@@ -31,16 +31,21 @@
 /** @hide */
 interface IStatusBarService
 {
+    @UnsupportedAppUsage
     void expandNotificationsPanel();
+    @UnsupportedAppUsage
     void collapsePanels();
     void togglePanel();
+    @UnsupportedAppUsage
     void disable(int what, IBinder token, String pkg);
     void disableForUser(int what, IBinder token, String pkg, int userId);
     void disable2(int what, IBinder token, String pkg);
     void disable2ForUser(int what, IBinder token, String pkg, int userId);
     int[] getDisableFlags(IBinder token, int userId);
     void setIcon(String slot, String iconPackage, int iconId, int iconLevel, String contentDescription);
+    @UnsupportedAppUsage
     void setIconVisibility(String slot, boolean visible);
+    @UnsupportedAppUsage
     void removeIcon(String slot);
     // TODO(b/117478341): support back button change when IME is showing on a external display.
     void setImeWindowStatus(in IBinder token, int vis, int backDisposition,
@@ -87,6 +92,7 @@
     void addTile(in ComponentName tile);
     void remTile(in ComponentName tile);
     void clickTile(in ComponentName tile);
+    @UnsupportedAppUsage
     void handleSystemKey(in int key);
 
     /**
diff --git a/core/java/com/android/internal/util/ArrayUtils.java b/core/java/com/android/internal/util/ArrayUtils.java
index b04ebec..ff5b996 100644
--- a/core/java/com/android/internal/util/ArrayUtils.java
+++ b/core/java/com/android/internal/util/ArrayUtils.java
@@ -712,4 +712,30 @@
         }
         return null;
     }
+
+    public static String deepToString(Object value) {
+        if (value != null && value.getClass().isArray()) {
+            if (value.getClass() == boolean[].class) {
+                return Arrays.toString((boolean[]) value);
+            } else if (value.getClass() == byte[].class) {
+                return Arrays.toString((byte[]) value);
+            } else if (value.getClass() == char[].class) {
+                return Arrays.toString((char[]) value);
+            } else if (value.getClass() == double[].class) {
+                return Arrays.toString((double[]) value);
+            } else if (value.getClass() == float[].class) {
+                return Arrays.toString((float[]) value);
+            } else if (value.getClass() == int[].class) {
+                return Arrays.toString((int[]) value);
+            } else if (value.getClass() == long[].class) {
+                return Arrays.toString((long[]) value);
+            } else if (value.getClass() == short[].class) {
+                return Arrays.toString((short[]) value);
+            } else {
+                return Arrays.deepToString((Object[]) value);
+            }
+        } else {
+            return String.valueOf(value);
+        }
+    }
 }
diff --git a/core/java/com/android/internal/widget/ILockSettings.aidl b/core/java/com/android/internal/widget/ILockSettings.aidl
index 9a77802..3be7c3e 100644
--- a/core/java/com/android/internal/widget/ILockSettings.aidl
+++ b/core/java/com/android/internal/widget/ILockSettings.aidl
@@ -30,23 +30,31 @@
 
 /** {@hide} */
 interface ILockSettings {
+    @UnsupportedAppUsage
     void setBoolean(in String key, in boolean value, in int userId);
+    @UnsupportedAppUsage
     void setLong(in String key, in long value, in int userId);
+    @UnsupportedAppUsage
     void setString(in String key, in String value, in int userId);
+    @UnsupportedAppUsage
     boolean getBoolean(in String key, in boolean defaultValue, in int userId);
+    @UnsupportedAppUsage
     long getLong(in String key, in long defaultValue, in int userId);
+    @UnsupportedAppUsage
     String getString(in String key, in String defaultValue, in int userId);
-    void setLockCredential(in String credential, int type, in String savedCredential, int requestedQuality, int userId);
+    void setLockCredential(in byte[] credential, int type, in byte[] savedCredential, int requestedQuality, int userId);
     void resetKeyStore(int userId);
-    VerifyCredentialResponse checkCredential(in String credential, int type, int userId,
+    VerifyCredentialResponse checkCredential(in byte[] credential, int type, int userId,
             in ICheckCredentialProgressCallback progressCallback);
-    VerifyCredentialResponse verifyCredential(in String credential, int type, long challenge, int userId);
-    VerifyCredentialResponse verifyTiedProfileChallenge(String credential, int type, long challenge, int userId);
+    VerifyCredentialResponse verifyCredential(in byte[] credential, int type, long challenge, int userId);
+    VerifyCredentialResponse verifyTiedProfileChallenge(in byte[] credential, int type, long challenge, int userId);
     boolean checkVoldPassword(int userId);
+    @UnsupportedAppUsage
     boolean havePattern(int userId);
+    @UnsupportedAppUsage
     boolean havePassword(int userId);
-    byte[] getHashFactor(String currentCredential, int userId);
-    void setSeparateProfileChallengeEnabled(int userId, boolean enabled, String managedUserPassword);
+    byte[] getHashFactor(in byte[] currentCredential, int userId);
+    void setSeparateProfileChallengeEnabled(int userId, boolean enabled, in byte[] managedUserPassword);
     boolean getSeparateProfileChallengeEnabled(int userId);
     void registerStrongAuthTracker(in IStrongAuthTracker tracker);
     void unregisterStrongAuthTracker(in IStrongAuthTracker tracker);
diff --git a/core/java/com/android/internal/widget/IRemoteViewsFactory.aidl b/core/java/com/android/internal/widget/IRemoteViewsFactory.aidl
index 7317ecf..d6efca5 100644
--- a/core/java/com/android/internal/widget/IRemoteViewsFactory.aidl
+++ b/core/java/com/android/internal/widget/IRemoteViewsFactory.aidl
@@ -21,15 +21,23 @@
 
 /** {@hide} */
 interface IRemoteViewsFactory {
+    @UnsupportedAppUsage
     void onDataSetChanged();
     oneway void onDataSetChangedAsync();
     oneway void onDestroy(in Intent intent);
+    @UnsupportedAppUsage
     int getCount();
+    @UnsupportedAppUsage
     RemoteViews getViewAt(int position);
+    @UnsupportedAppUsage
     RemoteViews getLoadingView();
+    @UnsupportedAppUsage
     int getViewTypeCount();
+    @UnsupportedAppUsage
     long getItemId(int position);
+    @UnsupportedAppUsage
     boolean hasStableIds();
+    @UnsupportedAppUsage
     boolean isCreated();
 }
 
diff --git a/core/java/com/android/internal/widget/LockPatternChecker.java b/core/java/com/android/internal/widget/LockPatternChecker.java
index 586ece0..bda3b57 100644
--- a/core/java/com/android/internal/widget/LockPatternChecker.java
+++ b/core/java/com/android/internal/widget/LockPatternChecker.java
@@ -150,12 +150,33 @@
      * @param challenge The challenge to verify against the pattern.
      * @param userId The user to check against the pattern.
      * @param callback The callback to be invoked with the verification result.
+     *
+     * @deprecated Pass the password as a byte array.
      */
+    @Deprecated
     public static AsyncTask<?, ?, ?> verifyPassword(final LockPatternUtils utils,
             final String password,
             final long challenge,
             final int userId,
             final OnVerifyCallback callback) {
+        byte[] passwordBytes = password != null ? password.getBytes() : null;
+        return verifyPassword(utils, passwordBytes, challenge, userId, callback);
+    }
+
+    /**
+     * Verify a password asynchronously.
+     *
+     * @param utils The LockPatternUtils instance to use.
+     * @param password The password to check.
+     * @param challenge The challenge to verify against the pattern.
+     * @param userId The user to check against the pattern.
+     * @param callback The callback to be invoked with the verification result.
+     */
+    public static AsyncTask<?, ?, ?> verifyPassword(final LockPatternUtils utils,
+            final byte[] password,
+            final long challenge,
+            final int userId,
+            final OnVerifyCallback callback) {
         AsyncTask<Void, Void, byte[]> task = new AsyncTask<Void, Void, byte[]>() {
             private int mThrottleTimeout;
 
@@ -188,7 +209,7 @@
      * @param callback The callback to be invoked with the verification result.
      */
     public static AsyncTask<?, ?, ?> verifyTiedProfileChallenge(final LockPatternUtils utils,
-            final String password,
+            final byte[] password,
             final boolean isPattern,
             final long challenge,
             final int userId,
@@ -222,18 +243,36 @@
      * @param password The password to check.
      * @param userId The user to check against the pattern.
      * @param callback The callback to be invoked with the check result.
+     * @deprecated Pass passwords as byte[]
      */
+    @Deprecated
     public static AsyncTask<?, ?, ?> checkPassword(final LockPatternUtils utils,
             final String password,
             final int userId,
             final OnCheckCallback callback) {
+        byte[] passwordBytes = password != null ? password.getBytes() : null;
+        return checkPassword(utils, passwordBytes, userId, callback);
+    }
+
+    /**
+     * Checks a password asynchronously.
+     *
+     * @param utils The LockPatternUtils instance to use.
+     * @param passwordBytes The password to check.
+     * @param userId The user to check against the pattern.
+     * @param callback The callback to be invoked with the check result.
+     */
+    public static AsyncTask<?, ?, ?> checkPassword(final LockPatternUtils utils,
+            final byte[] passwordBytes,
+            final int userId,
+            final OnCheckCallback callback) {
         AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
             private int mThrottleTimeout;
 
             @Override
             protected Boolean doInBackground(Void... args) {
                 try {
-                    return utils.checkPassword(password, userId, callback::onEarlyMatched);
+                    return utils.checkPassword(passwordBytes, userId, callback::onEarlyMatched);
                 } catch (RequestThrottledException ex) {
                     mThrottleTimeout = ex.getTimeoutMs();
                     return false;
diff --git a/core/java/com/android/internal/widget/LockPatternUtils.java b/core/java/com/android/internal/widget/LockPatternUtils.java
index 8d3c482..17ed2a0 100644
--- a/core/java/com/android/internal/widget/LockPatternUtils.java
+++ b/core/java/com/android/internal/widget/LockPatternUtils.java
@@ -67,6 +67,7 @@
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.List;
 import java.util.StringJoiner;
@@ -356,7 +357,7 @@
                 null /* componentName */, userId);
     }
 
-    private byte[] verifyCredential(String credential, int type, long challenge, int userId)
+    private byte[] verifyCredential(byte[] credential, int type, long challenge, int userId)
             throws RequestThrottledException {
         try {
             VerifyCredentialResponse response = getLockSettings().verifyCredential(credential,
@@ -373,7 +374,7 @@
         }
     }
 
-    private boolean checkCredential(String credential, int type, int userId,
+    private boolean checkCredential(byte[] credential, int type, int userId,
             @Nullable CheckCredentialProgressCallback progressCallback)
             throws RequestThrottledException {
         try {
@@ -404,7 +405,7 @@
     public byte[] verifyPattern(List<LockPatternView.Cell> pattern, long challenge, int userId)
             throws RequestThrottledException {
         throwIfCalledOnMainThread();
-        return verifyCredential(patternToString(pattern), CREDENTIAL_TYPE_PATTERN, challenge,
+        return verifyCredential(patternToByteArray(pattern), CREDENTIAL_TYPE_PATTERN, challenge,
                 userId);
     }
 
@@ -429,7 +430,7 @@
             @Nullable CheckCredentialProgressCallback progressCallback)
             throws RequestThrottledException {
         throwIfCalledOnMainThread();
-        return checkCredential(patternToString(pattern), CREDENTIAL_TYPE_PATTERN, userId,
+        return checkCredential(patternToByteArray(pattern), CREDENTIAL_TYPE_PATTERN, userId,
                 progressCallback);
     }
 
@@ -442,7 +443,7 @@
      * @param challenge The challenge to verify against the password
      * @return the attestation that the challenge was verified, or null.
      */
-    public byte[] verifyPassword(String password, long challenge, int userId)
+    public byte[] verifyPassword(byte[] password, long challenge, int userId)
             throws RequestThrottledException {
         throwIfCalledOnMainThread();
         return verifyCredential(password, CREDENTIAL_TYPE_PASSWORD, challenge, userId);
@@ -458,7 +459,7 @@
      * @param challenge The challenge to verify against the password
      * @return the attestation that the challenge was verified, or null.
      */
-    public byte[] verifyTiedProfileChallenge(String password, boolean isPattern, long challenge,
+    public byte[] verifyTiedProfileChallenge(byte[] password, boolean isPattern, long challenge,
             int userId) throws RequestThrottledException {
         throwIfCalledOnMainThread();
         try {
@@ -480,22 +481,53 @@
     }
 
     /**
+     *
      * Check to see if a password matches the saved password.  If no password exists,
      * always returns true.
      * @param password The password to check.
      * @return Whether the password matches the stored one.
      */
     public boolean checkPassword(String password, int userId) throws RequestThrottledException {
+        byte[] passwordBytes = password != null ? password.getBytes() : null;
+        return checkPassword(passwordBytes, userId, null /* progressCallback */);
+    }
+
+
+    /**
+     *
+     * Check to see if a password matches the saved password.  If no password exists,
+     * always returns true.
+     * @param password The password to check.
+     * @return Whether the password matches the stored one.
+     */
+    public boolean checkPassword(byte[] password, int userId) throws RequestThrottledException {
         return checkPassword(password, userId, null /* progressCallback */);
     }
 
+    // TODO(b/120484642): This method is necessary for vendor/qcom code and is a hidden api
+    /* *
+     * Check to see if a password matches the saved password.  If no password exists,
+     * always returns true.
+     * @param password The password to check.
+     * @return Whether the password matches the stored one.
+     */
+    public boolean checkPassword(String password, int userId,
+            @Nullable CheckCredentialProgressCallback progressCallback)
+            throws RequestThrottledException {
+        byte[] passwordBytes = password != null ? password.getBytes() : null;
+        throwIfCalledOnMainThread();
+        return checkCredential(passwordBytes, CREDENTIAL_TYPE_PASSWORD, userId, progressCallback);
+
+    }
+
     /**
      * Check to see if a password matches the saved password.  If no password exists,
      * always returns true.
      * @param password The password to check.
      * @return Whether the password matches the stored one.
      */
-    public boolean checkPassword(String password, int userId,
+
+    public boolean checkPassword(byte[] password, int userId,
             @Nullable CheckCredentialProgressCallback progressCallback)
             throws RequestThrottledException {
         throwIfCalledOnMainThread();
@@ -519,7 +551,7 @@
      * Returns the password history hash factor, needed to check new password against password
      * history with {@link #checkPasswordHistory(String, byte[], int)}
      */
-    public byte[] getPasswordHistoryHashFactor(String currentPassword, int userId) {
+    public byte[] getPasswordHistoryHashFactor(byte[] currentPassword, int userId) {
         try {
             return getLockSettings().getHashFactor(currentPassword, userId);
         } catch (RemoteException e) {
@@ -537,8 +569,8 @@
      *        {@link ILockSettings#getHashFactor}
      * @return Whether the password matches any in the history.
      */
-    public boolean checkPasswordHistory(String passwordToCheck, byte[] hashFactor, int userId) {
-        if (TextUtils.isEmpty(passwordToCheck)) {
+    public boolean checkPasswordHistory(byte[] passwordToCheck, byte[] hashFactor, int userId) {
+        if (passwordToCheck == null || passwordToCheck.length == 0) {
             Log.e(TAG, "checkPasswordHistory: empty password");
             return false;
         }
@@ -639,13 +671,13 @@
     /**
      * Clear any lock pattern or password.
      */
-    public void clearLock(String savedCredential, int userHandle) {
+    public void clearLock(byte[] savedCredential, int userHandle) {
         final int currentQuality = getKeyguardStoredPasswordQuality(userHandle);
         setKeyguardStoredPasswordQuality(PASSWORD_QUALITY_UNSPECIFIED, userHandle);
 
         try{
-            getLockSettings().setLockCredential(null, CREDENTIAL_TYPE_NONE, savedCredential,
-                    PASSWORD_QUALITY_UNSPECIFIED, userHandle);
+            getLockSettings().setLockCredential(null, CREDENTIAL_TYPE_NONE,
+                    savedCredential, PASSWORD_QUALITY_UNSPECIFIED, userHandle);
         } catch (Exception e) {
             Log.e(TAG, "Failed to clear lock", e);
             setKeyguardStoredPasswordQuality(currentQuality, userHandle);
@@ -704,10 +736,11 @@
     /**
      * Save a lock pattern.
      * @param pattern The new pattern to save.
-     * @param savedPattern The previously saved pattern, converted to String format
+     * @param savedPattern The previously saved pattern, converted to byte[] format
      * @param userId the user whose pattern is to be saved.
      */
-    public void saveLockPattern(List<LockPatternView.Cell> pattern, String savedPattern, int userId) {
+    public void saveLockPattern(List<LockPatternView.Cell> pattern, byte[] savedPattern,
+            int userId) {
         if (!hasSecureLockScreen()) {
             throw new UnsupportedOperationException(
                     "This operation requires the lock screen feature.");
@@ -717,12 +750,12 @@
                     + MIN_LOCK_PATTERN_SIZE + " dots long.");
         }
 
-        final String stringPattern = patternToString(pattern);
+        final byte[] bytePattern = patternToByteArray(pattern);
         final int currentQuality = getKeyguardStoredPasswordQuality(userId);
         setKeyguardStoredPasswordQuality(PASSWORD_QUALITY_SOMETHING, userId);
         try {
-            getLockSettings().setLockCredential(stringPattern, CREDENTIAL_TYPE_PATTERN,
-                    savedPattern, PASSWORD_QUALITY_SOMETHING, userId);
+            getLockSettings().setLockCredential(bytePattern, CREDENTIAL_TYPE_PATTERN, savedPattern,
+                    PASSWORD_QUALITY_SOMETHING, userId);
         } catch (Exception e) {
             Log.e(TAG, "Couldn't save lock pattern", e);
             setKeyguardStoredPasswordQuality(currentQuality, userId);
@@ -734,7 +767,7 @@
             if (!shouldEncryptWithCredentials(true)) {
                 clearEncryptionPassword();
             } else {
-                updateEncryptionPassword(StorageManager.CRYPT_TYPE_PATTERN, stringPattern);
+                updateEncryptionPassword(StorageManager.CRYPT_TYPE_PATTERN, bytePattern);
             }
         }
 
@@ -806,7 +839,7 @@
     }
 
     /** Update the encryption password if it is enabled **/
-    private void updateEncryptionPassword(final int type, final String password) {
+    private void updateEncryptionPassword(final int type, final byte[] password) {
         if (!hasSecureLockScreen()) {
             throw new UnsupportedOperationException(
                     "This operation requires the lock screen feature.");
@@ -825,7 +858,9 @@
             protected Void doInBackground(Void... dummy) {
                 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
                 try {
-                    storageManager.changeEncryptionPassword(type, password);
+                    // TODO(b/120484642): This is a location where we still use a String for vold
+                    String passwordString = password != null ? new String(password) : null;
+                    storageManager.changeEncryptionPassword(type, passwordString);
                 } catch (RemoteException e) {
                     Log.e(TAG, "Error changing encryption password", e);
                 }
@@ -842,14 +877,34 @@
      * @param savedPassword The previously saved lock password, or null if none
      * @param requestedQuality {@see DevicePolicyManager#getPasswordQuality(android.content.ComponentName)}
      * @param userHandle The userId of the user to change the password for
+     *
+     * @deprecated Pass password as a byte array
      */
+    @Deprecated
     public void saveLockPassword(String password, String savedPassword, int requestedQuality,
             int userHandle) {
+        byte[] passwordBytes = password != null ? password.getBytes() : null;
+        byte[] savedPasswordBytes = savedPassword != null ? savedPassword.getBytes() : null;
+        saveLockPassword(passwordBytes, savedPasswordBytes, requestedQuality, userHandle);
+    }
+
+    /**
+     * Save a lock password.  Does not ensure that the password is as good
+     * as the requested mode, but will adjust the mode to be as good as the
+     * password.
+     * @param password The password to save
+     * @param savedPassword The previously saved lock password, or null if none
+     * @param requestedQuality {@see DevicePolicyManager#getPasswordQuality(
+     *          android.content.ComponentName)}
+     * @param userHandle The userId of the user to change the password for
+     */
+    public void saveLockPassword(byte[] password, byte[] savedPassword, int requestedQuality,
+            int userHandle) {
         if (!hasSecureLockScreen()) {
             throw new UnsupportedOperationException(
                     "This operation requires the lock screen feature.");
         }
-        if (password == null || password.length() < MIN_LOCK_PASSWORD_SIZE) {
+        if (password == null || password.length < MIN_LOCK_PASSWORD_SIZE) {
             throw new IllegalArgumentException("password must not be null and at least "
                     + "of length " + MIN_LOCK_PASSWORD_SIZE);
         }
@@ -864,8 +919,8 @@
                 computePasswordQuality(CREDENTIAL_TYPE_PASSWORD, password, requestedQuality),
                 userHandle);
         try {
-            getLockSettings().setLockCredential(password, CREDENTIAL_TYPE_PASSWORD,
-                    savedPassword, requestedQuality, userHandle);
+            getLockSettings().setLockCredential(password, CREDENTIAL_TYPE_PASSWORD, savedPassword,
+                    requestedQuality, userHandle);
         } catch (Exception e) {
             Log.e(TAG, "Unable to save lock password", e);
             setKeyguardStoredPasswordQuality(currentQuality, userHandle);
@@ -882,7 +937,7 @@
      * Update device encryption password if calling user is USER_SYSTEM and device supports
      * encryption.
      */
-    private void updateEncryptionPasswordIfNeeded(String password, int quality, int userHandle) {
+    private void updateEncryptionPasswordIfNeeded(byte[] password, int quality, int userHandle) {
         // Update the device encryption password.
         if (userHandle == UserHandle.USER_SYSTEM
                 && LockPatternUtils.isDeviceEncryptionEnabled()) {
@@ -902,8 +957,8 @@
      * Store the hash of the *current* password in the password history list, if device policy
      * enforces password history requirement.
      */
-    private void updatePasswordHistory(String password, int userHandle) {
-        if (TextUtils.isEmpty(password)) {
+    private void updatePasswordHistory(byte[] password, int userHandle) {
+        if (password == null || password.length == 0) {
             Log.e(TAG, "checkPasswordHistory: empty password");
             return;
         }
@@ -982,7 +1037,7 @@
      * if DevicePolicyManager has a stronger quality requirement. This value will be written
      * to PASSWORD_TYPE_KEY.
      */
-    private int computePasswordQuality(int type, String credential, int requestedQuality) {
+    private int computePasswordQuality(int type, byte[] credential, int requestedQuality) {
         final int quality;
         if (type == CREDENTIAL_TYPE_PASSWORD) {
             int computedQuality = PasswordMetrics.computeForPassword(credential).quality;
@@ -1005,7 +1060,7 @@
      *            true
      */
     public void setSeparateProfileChallengeEnabled(int userHandle, boolean enabled,
-            String managedUserPassword) {
+            byte[] managedUserPassword) {
         if (!isManagedProfile(userHandle)) {
             return;
         }
@@ -1069,15 +1124,28 @@
      * Deserialize a pattern.
      * @param string The pattern serialized with {@link #patternToString}
      * @return The pattern.
+     * @deprecated Pass patterns as byte[] and use byteArrayToPattern
      */
+    @Deprecated
     public static List<LockPatternView.Cell> stringToPattern(String string) {
         if (string == null) {
             return null;
         }
+        return byteArrayToPattern(string.getBytes());
+    }
+
+    /**
+     * Deserialize a pattern.
+     * @param  bytes The pattern serialized with {@link #patternToByteArray}
+     * @return The pattern.
+     */
+    public static List<LockPatternView.Cell> byteArrayToPattern(byte[] bytes) {
+        if (bytes == null) {
+            return null;
+        }
 
         List<LockPatternView.Cell> result = Lists.newArrayList();
 
-        final byte[] bytes = string.getBytes();
         for (int i = 0; i < bytes.length; i++) {
             byte b = (byte) (bytes[i] - '1');
             result.add(LockPatternView.Cell.of(b / 3, b % 3));
@@ -1089,10 +1157,22 @@
      * Serialize a pattern.
      * @param pattern The pattern.
      * @return The pattern in string form.
+     * @deprecated Use patternToByteArray instead.
      */
+    @Deprecated
     public static String patternToString(List<LockPatternView.Cell> pattern) {
+        return new String(patternToByteArray(pattern));
+    }
+
+
+    /**
+     * Serialize a pattern.
+     * @param pattern The pattern.
+     * @return The pattern in byte array form.
+     */
+    public static byte[] patternToByteArray(List<LockPatternView.Cell> pattern) {
         if (pattern == null) {
-            return "";
+            return new byte[0];
         }
         final int patternSize = pattern.size();
 
@@ -1101,21 +1181,24 @@
             LockPatternView.Cell cell = pattern.get(i);
             res[i] = (byte) (cell.getRow() * 3 + cell.getColumn() + '1');
         }
-        return new String(res);
+        return res;
     }
 
-    public static String patternStringToBaseZero(String pattern) {
-        if (pattern == null) {
-            return "";
+    /**
+     * Transform a pattern byte array to base zero form.
+     * @param bytes pattern byte array.
+     * @return The pattern in base zero form.
+     */
+    public static byte[] patternByteArrayToBaseZero(byte[] bytes) {
+        if (bytes == null) {
+            return new byte[0];
         }
-        final int patternSize = pattern.length();
-
+        final int patternSize = bytes.length;
         byte[] res = new byte[patternSize];
-        final byte[] bytes = pattern.getBytes();
         for (int i = 0; i < patternSize; i++) {
             res[i] = (byte) (bytes[i] - '1');
         }
-        return new String(res);
+        return res;
     }
 
     /*
@@ -1169,13 +1252,18 @@
      *
      * @return the hash of the pattern in a byte array.
      */
-    public String legacyPasswordToHash(String password, int userId) {
-        if (password == null) {
+    public String legacyPasswordToHash(byte[] password, int userId) {
+        if (password == null || password.length == 0) {
             return null;
         }
 
         try {
-            byte[] saltedPassword = (password + getSalt(userId)).getBytes();
+            // Previously the password was passed as a String with the following code:
+            // byte[] saltedPassword = (password + getSalt(userId)).getBytes();
+            // The code below creates the identical digest preimage using byte arrays:
+            byte[] salt = getSalt(userId).getBytes();
+            byte[] saltedPassword = Arrays.copyOf(password, password.length + salt.length);
+            System.arraycopy(salt, 0, saltedPassword, password.length, salt.length);
             byte[] sha1 = MessageDigest.getInstance("SHA-1").digest(saltedPassword);
             byte[] md5 = MessageDigest.getInstance("MD5").digest(saltedPassword);
 
@@ -1184,6 +1272,7 @@
             System.arraycopy(md5, 0, combined, sha1.length, md5.length);
 
             final char[] hexEncoded = HexEncoding.encode(combined);
+            Arrays.fill(saltedPassword, (byte) 0);
             return new String(hexEncoded);
         } catch (NoSuchAlgorithmException e) {
             throw new AssertionError("Missing digest algorithm: ", e);
@@ -1193,14 +1282,19 @@
     /**
      * Hash the password for password history check purpose.
      */
-    private String passwordToHistoryHash(String passwordToHash, byte[] hashFactor, int userId) {
-        if (TextUtils.isEmpty(passwordToHash) || hashFactor == null) {
+    private String passwordToHistoryHash(byte[] passwordToHash, byte[] hashFactor, int userId) {
+        if (passwordToHash == null || passwordToHash.length == 0 || hashFactor == null) {
             return null;
         }
         try {
             MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
             sha256.update(hashFactor);
-            sha256.update((passwordToHash + getSalt(userId)).getBytes());
+            byte[] salt = getSalt(userId).getBytes();
+            byte[] saltedPassword = Arrays.copyOf(passwordToHash, passwordToHash.length
+                    + salt.length);
+            System.arraycopy(salt, 0, saltedPassword, passwordToHash.length, salt.length);
+            sha256.update(saltedPassword);
+            Arrays.fill(saltedPassword, (byte) 0);
             return new String(HexEncoding.encode(sha256.digest()));
         } catch (NoSuchAlgorithmException e) {
             throw new AssertionError("Missing digest algorithm: ", e);
@@ -1633,7 +1727,7 @@
      * @param userId The user who's lock credential to be changed
      * @return {@code true} if the operation is successful.
      */
-    public boolean setLockCredentialWithToken(String credential, int type, int requestedQuality,
+    public boolean setLockCredentialWithToken(byte[] credential, int type, int requestedQuality,
             long tokenHandle, byte[] token, int userId) {
         if (!hasSecureLockScreen()) {
             throw new UnsupportedOperationException(
@@ -1641,13 +1735,13 @@
         }
         LockSettingsInternal localService = getLockSettingsInternal();
         if (type != CREDENTIAL_TYPE_NONE) {
-            if (TextUtils.isEmpty(credential) || credential.length() < MIN_LOCK_PASSWORD_SIZE) {
+            if (credential == null || credential.length < MIN_LOCK_PASSWORD_SIZE) {
                 throw new IllegalArgumentException("password must not be null and at least "
                         + "of length " + MIN_LOCK_PASSWORD_SIZE);
             }
             final int quality = computePasswordQuality(type, credential, requestedQuality);
-            if (!localService.setLockCredentialWithToken(credential, type, tokenHandle,
-                    token, quality, userId)) {
+            if (!localService.setLockCredentialWithToken(credential, type, tokenHandle, token,
+                    quality, userId)) {
                 return false;
             }
             setKeyguardStoredPasswordQuality(quality, userId);
@@ -1656,11 +1750,11 @@
             updatePasswordHistory(credential, userId);
             onAfterChangingPassword(userId);
         } else {
-            if (!TextUtils.isEmpty(credential)) {
+            if (!(credential == null || credential.length == 0)) {
                 throw new IllegalArgumentException("password must be emtpy for NONE type");
             }
-            if (!localService.setLockCredentialWithToken(null, CREDENTIAL_TYPE_NONE,
-                    tokenHandle, token, PASSWORD_QUALITY_UNSPECIFIED, userId)) {
+            if (!localService.setLockCredentialWithToken(null, CREDENTIAL_TYPE_NONE, tokenHandle,
+                    token, PASSWORD_QUALITY_UNSPECIFIED, userId)) {
                 return false;
             }
             setKeyguardStoredPasswordQuality(PASSWORD_QUALITY_UNSPECIFIED, userId);
@@ -1891,4 +1985,22 @@
         return FRP_CREDENTIAL_ENABLED && context.getResources().getBoolean(
                 com.android.internal.R.bool.config_enableCredentialFactoryResetProtection);
     }
+
+    /**
+     * Converts a CharSequence to a byte array without requiring a toString(), which creates an
+     * additional copy.
+     *
+     * @param chars The CharSequence to convert
+     * @return A byte array representing the input
+     */
+    public static byte[] charSequenceToByteArray(CharSequence chars) {
+        if (chars == null) {
+            return null;
+        }
+        byte[] bytes = new byte[chars.length()];
+        for (int i = 0; i < chars.length(); i++) {
+            bytes[i] = (byte) chars.charAt(i);
+        }
+        return bytes;
+    }
 }
diff --git a/core/java/com/android/internal/widget/LockPatternView.java b/core/java/com/android/internal/widget/LockPatternView.java
index 25a5a07..4b26990 100644
--- a/core/java/com/android/internal/widget/LockPatternView.java
+++ b/core/java/com/android/internal/widget/LockPatternView.java
@@ -1273,8 +1273,10 @@
     @Override
     protected Parcelable onSaveInstanceState() {
         Parcelable superState = super.onSaveInstanceState();
+        byte[] patternBytes = LockPatternUtils.patternToByteArray(mPattern);
+        String patternString = patternBytes != null ? new String(patternBytes) : null;
         return new SavedState(superState,
-                LockPatternUtils.patternToString(mPattern),
+                patternString,
                 mPatternDisplayMode.ordinal(),
                 mInputEnabled, mInStealthMode, mEnableHapticFeedback);
     }
diff --git a/core/java/com/android/internal/widget/LockSettingsInternal.java b/core/java/com/android/internal/widget/LockSettingsInternal.java
index 9de9ef7..90397df 100644
--- a/core/java/com/android/internal/widget/LockSettingsInternal.java
+++ b/core/java/com/android/internal/widget/LockSettingsInternal.java
@@ -49,7 +49,11 @@
      */
     public abstract boolean isEscrowTokenActive(long handle, int userId);
 
-    public abstract boolean setLockCredentialWithToken(String credential, int type,
+    /**
+     * Set the lock credential.
+     * @return true if password is set.
+     */
+    public abstract boolean setLockCredentialWithToken(byte[] credential, int type,
             long tokenHandle, byte[] token, int requestedQuality, int userId);
 
     public abstract boolean unlockUserWithToken(long tokenHandle, byte[] token, int userId);
diff --git a/core/jni/Android.bp b/core/jni/Android.bp
index c309f27..cd34d2e 100644
--- a/core/jni/Android.bp
+++ b/core/jni/Android.bp
@@ -165,6 +165,8 @@
         "android_media_AudioTrack.cpp",
         "android_media_AudioAttributes.cpp",
         "android_media_AudioProductStrategies.cpp",
+        "android_media_AudioVolumeGroups.cpp",
+        "android_media_AudioVolumeGroupCallback.cpp",
         "android_media_DeviceCallback.cpp",
         "android_media_JetPlayer.cpp",
         "android_media_MediaMetricsJNI.cpp",
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index 0938e56..da27852 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -110,6 +110,8 @@
 extern int register_android_media_AudioTrack(JNIEnv *env);
 extern int register_android_media_AudioAttributes(JNIEnv *env);
 extern int register_android_media_AudioProductStrategies(JNIEnv *env);
+extern int register_android_media_AudioVolumeGroups(JNIEnv *env);
+extern int register_android_media_AudioVolumeGroupChangeHandler(JNIEnv *env);
 extern int register_android_media_MicrophoneInfo(JNIEnv *env);
 extern int register_android_media_JetPlayer(JNIEnv *env);
 extern int register_android_media_ToneGenerator(JNIEnv *env);
@@ -244,6 +246,11 @@
 // Copying (CC) garbage collector.
 static const char* kNoGenerationalCCRuntimeOption = "-Xgc:nogenerational_cc";
 
+// Feature flag name for running the JIT in Zygote experiment, b/119800099.
+static const char* ENABLE_APEX_IMAGE = "enable_apex_image";
+// Flag to pass to the runtime when using the apex image.
+static const char* kApexImageOption = "-Ximage:/system/framework/apex.art";
+
 static AndroidRuntime* gCurRuntime = NULL;
 
 /*
@@ -678,8 +685,17 @@
     char jdwpProviderBuf[sizeof("-XjdwpProvider:") - 1 + PROPERTY_VALUE_MAX];
     char bootImageBuf[sizeof("-Ximage:") - 1 + PROPERTY_VALUE_MAX];
 
-    if (parseRuntimeOption("dalvik.vm.boot-image", bootImageBuf, "-Ximage:")) {
-        ALOGI("Boot image: '%s'\n", bootImageBuf);
+    std::string use_apex_image =
+        server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
+                                                             ENABLE_APEX_IMAGE,
+                                                             /*default_value=*/ "");
+    if (use_apex_image == "true") {
+        addOption(kApexImageOption);
+        ALOGI("Using Apex boot image: '%s'\n", kApexImageOption);
+    } else if (parseRuntimeOption("dalvik.vm.boot-image", bootImageBuf, "-Ximage:")) {
+        ALOGI("Using dalvik.vm.boot-image: '%s'\n", bootImageBuf);
+    } else {
+        ALOGI("Using default boot image");
     }
 
     bool checkJni = false;
@@ -1510,6 +1526,8 @@
     REG_JNI(register_android_media_AudioTrack),
     REG_JNI(register_android_media_AudioAttributes),
     REG_JNI(register_android_media_AudioProductStrategies),
+    REG_JNI(register_android_media_AudioVolumeGroups),
+    REG_JNI(register_android_media_AudioVolumeGroupChangeHandler),
     REG_JNI(register_android_media_JetPlayer),
     REG_JNI(register_android_media_MicrophoneInfo),
     REG_JNI(register_android_media_RemoteDisplay),
diff --git a/core/jni/android/graphics/TEST_MAPPING b/core/jni/android/graphics/TEST_MAPPING
new file mode 100644
index 0000000..10bd0ee
--- /dev/null
+++ b/core/jni/android/graphics/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+      "name": "CtsGraphicsTestCases"
+    }
+  ]
+}
diff --git a/core/jni/android_hardware_SoundTrigger.cpp b/core/jni/android_hardware_SoundTrigger.cpp
index 8a28034..c7805ea 100644
--- a/core/jni/android_hardware_SoundTrigger.cpp
+++ b/core/jni/android_hardware_SoundTrigger.cpp
@@ -221,12 +221,23 @@
 
     jobject jAudioFormat = NULL;
     if (event->trigger_in_data || event->capture_available) {
+        jint channelMask = (jint)audio_channel_mask_get_bits(event->audio_config.channel_mask);
+        jint channelIndexMask = (jint)AUDIO_CHANNEL_NONE;
+
+        switch (audio_channel_mask_get_representation(event->audio_config.channel_mask)) {
+        case AUDIO_CHANNEL_REPRESENTATION_INDEX:
+            channelIndexMask = channelMask;
+            channelMask = (jint)AUDIO_CHANNEL_NONE;
+            break;
+        default:
+            break;
+        }
         jAudioFormat = env->NewObject(gAudioFormatClass,
                                     gAudioFormatCstor,
                                     audioFormatFromNative(event->audio_config.format),
                                     event->audio_config.sample_rate,
-                                    inChannelMaskFromNative(event->audio_config.channel_mask),
-                                    (jint)0 /* channelIndexMask */);
+                                    channelMask,
+                                    channelIndexMask);
 
     }
     if (event->type == SOUND_MODEL_TYPE_KEYPHRASE) {
diff --git a/core/jni/android_media_AudioProductStrategies.cpp b/core/jni/android_media_AudioProductStrategies.cpp
index a18e80a..822b74a 100644
--- a/core/jni/android_media_AudioProductStrategies.cpp
+++ b/core/jni/android_media_AudioProductStrategies.cpp
@@ -57,7 +57,7 @@
 static jclass gAudioAttributesGroupClass;
 static jmethodID gAudioAttributesGroupCstor;
 static struct {
-    jfieldID    mGroupId;
+    jfieldID    mVolumeGroupId;
     jfieldID    mLegacyStreamType;
     jfieldID    mAudioAttributes;
 } gAudioAttributesGroupsFields;
@@ -194,12 +194,34 @@
     return jStatus;
 }
 
+static jint
+android_media_AudioSystem_getProductStrategyFromAudioAttributes(JNIEnv *env, jobject clazz,
+                                                                jobject jAudioAttributes)
+{
+    JNIAudioAttributeHelper::UniqueAaPtr attributes = JNIAudioAttributeHelper::makeUnique();
+    jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env,
+                                                           jAudioAttributes,
+                                                           attributes.get());
+    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+        return jStatus;
+    }
+    product_strategy_t psId;
+    status_t status = AudioSystem::getProductStrategyFromAudioAttributes(
+                AudioAttributes(*attributes.get()), psId);
+    if (status != NO_ERROR) {
+        return nativeToJavaStatus(status);
+    }
+    return psId;
+}
+
 /*
  * JNI registration.
  */
 static const JNINativeMethod gMethods[] = {
     {"native_list_audio_product_strategies", "(Ljava/util/ArrayList;)I",
                         (void *)android_media_AudioSystem_listAudioProductStrategies},
+    {"native_get_product_strategies_from_audio_attributes", "(Landroid/media/AudioAttributes;)I",
+                        (void *)android_media_AudioSystem_getProductStrategyFromAudioAttributes},
 };
 
 int register_android_media_AudioProductStrategies(JNIEnv *env)
@@ -227,8 +249,8 @@
     gAudioAttributesGroupClass = MakeGlobalRefOrDie(env, audioAttributesGroupClass);
     gAudioAttributesGroupCstor = GetMethodIDOrDie(env, audioAttributesGroupClass, "<init>",
                                                   "(II[Landroid/media/AudioAttributes;)V");
-    gAudioAttributesGroupsFields.mGroupId = GetFieldIDOrDie(
-                env, audioAttributesGroupClass, "mGroupId", "I");
+    gAudioAttributesGroupsFields.mVolumeGroupId = GetFieldIDOrDie(
+                env, audioAttributesGroupClass, "mVolumeGroupId", "I");
     gAudioAttributesGroupsFields.mLegacyStreamType = GetFieldIDOrDie(
                 env, audioAttributesGroupClass, "mLegacyStreamType", "I");
     gAudioAttributesGroupsFields.mAudioAttributes = GetFieldIDOrDie(
diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp
index bd998999..1a90ebf 100644
--- a/core/jni/android_media_AudioSystem.cpp
+++ b/core/jni/android_media_AudioSystem.cpp
@@ -573,6 +573,81 @@
 }
 
 static jint
+android_media_AudioSystem_setVolumeIndexForAttributes(JNIEnv *env,
+                                                      jobject thiz,
+                                                      jobject jaa,
+                                                      jint index,
+                                                      jint device)
+{
+    // read the AudioAttributes values
+    JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
+    jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
+    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+        return jStatus;
+    }
+    return (jint) check_AudioSystem_Command(
+            AudioSystem::setVolumeIndexForAttributes(*(paa.get()), index, (audio_devices_t)device));
+}
+
+static jint
+android_media_AudioSystem_getVolumeIndexForAttributes(JNIEnv *env,
+                                                      jobject thiz,
+                                                      jobject jaa,
+                                                      jint device)
+{
+    // read the AudioAttributes values
+    JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
+    jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
+    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+        return jStatus;
+    }
+    int index;
+    if (AudioSystem::getVolumeIndexForAttributes(*(paa.get()), index, (audio_devices_t)device)
+            != NO_ERROR) {
+        index = -1;
+    }
+    return (jint) index;
+}
+
+static jint
+android_media_AudioSystem_getMinVolumeIndexForAttributes(JNIEnv *env,
+                                                         jobject thiz,
+                                                         jobject jaa)
+{
+    // read the AudioAttributes values
+    JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
+    jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
+    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+        return jStatus;
+    }
+    int index;
+    if (AudioSystem::getMinVolumeIndexForAttributes(*(paa.get()), index)
+            != NO_ERROR) {
+        index = -1;
+    }
+    return (jint) index;
+}
+
+static jint
+android_media_AudioSystem_getMaxVolumeIndexForAttributes(JNIEnv *env,
+                                                         jobject thiz,
+                                                         jobject jaa)
+{
+    // read the AudioAttributes values
+    JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
+    jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
+    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+        return jStatus;
+    }
+    int index;
+    if (AudioSystem::getMaxVolumeIndexForAttributes(*(paa.get()), index)
+            != NO_ERROR) {
+        index = -1;
+    }
+    return (jint) index;
+}
+
+static jint
 android_media_AudioSystem_setMasterVolume(JNIEnv *env, jobject thiz, jfloat value)
 {
     return (jint) check_AudioSystem_Command(AudioSystem::setMasterVolume(value));
@@ -2172,6 +2247,10 @@
     {"initStreamVolume",    "(III)I",   (void *)android_media_AudioSystem_initStreamVolume},
     {"setStreamVolumeIndex","(III)I",   (void *)android_media_AudioSystem_setStreamVolumeIndex},
     {"getStreamVolumeIndex","(II)I",    (void *)android_media_AudioSystem_getStreamVolumeIndex},
+    {"setVolumeIndexForAttributes","(Landroid/media/AudioAttributes;II)I",   (void *)android_media_AudioSystem_setVolumeIndexForAttributes},
+    {"getVolumeIndexForAttributes","(Landroid/media/AudioAttributes;I)I",    (void *)android_media_AudioSystem_getVolumeIndexForAttributes},
+    {"getMinVolumeIndexForAttributes","(Landroid/media/AudioAttributes;)I",    (void *)android_media_AudioSystem_getMinVolumeIndexForAttributes},
+    {"getMaxVolumeIndexForAttributes","(Landroid/media/AudioAttributes;)I",    (void *)android_media_AudioSystem_getMaxVolumeIndexForAttributes},
     {"setMasterVolume",     "(F)I",     (void *)android_media_AudioSystem_setMasterVolume},
     {"getMasterVolume",     "()F",      (void *)android_media_AudioSystem_getMasterVolume},
     {"setMasterMute",       "(Z)I",     (void *)android_media_AudioSystem_setMasterMute},
diff --git a/core/jni/android_media_AudioVolumeGroupCallback.cpp b/core/jni/android_media_AudioVolumeGroupCallback.cpp
new file mode 100644
index 0000000..cb4ddbd
--- /dev/null
+++ b/core/jni/android_media_AudioVolumeGroupCallback.cpp
@@ -0,0 +1,175 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+
+#define LOG_TAG "AudioVolumeGroupCallback-JNI"
+
+#include <utils/Log.h>
+#include <nativehelper/JNIHelp.h>
+#include "core_jni_helpers.h"
+
+#include "android_media_AudioVolumeGroupCallback.h"
+
+
+// ----------------------------------------------------------------------------
+using namespace android;
+
+static const char* const kAudioVolumeGroupChangeHandlerClassPathName =
+        "android/media/audiopolicy/AudioVolumeGroupChangeHandler";
+
+static struct {
+    jfieldID    mJniCallback;
+} gAudioVolumeGroupChangeHandlerFields;
+
+static struct {
+    jmethodID    postEventFromNative;
+} gAudioVolumeGroupChangeHandlerMethods;
+
+static Mutex gLock;
+
+JNIAudioVolumeGroupCallback::JNIAudioVolumeGroupCallback(JNIEnv* env,
+                                                         jobject thiz,
+                                                         jobject weak_thiz)
+{
+    jclass clazz = env->GetObjectClass(thiz);
+    if (clazz == NULL) {
+        ALOGE("Can't find class %s", kAudioVolumeGroupChangeHandlerClassPathName);
+        return;
+    }
+    mClass = (jclass)env->NewGlobalRef(clazz);
+
+    // We use a weak reference so the AudioVolumeGroupChangeHandler object can be garbage collected.
+    // The reference is only used as a proxy for callbacks.
+    mObject  = env->NewGlobalRef(weak_thiz);
+}
+
+JNIAudioVolumeGroupCallback::~JNIAudioVolumeGroupCallback()
+{
+    // remove global references
+    JNIEnv *env = AndroidRuntime::getJNIEnv();
+    if (env == NULL) {
+        return;
+    }
+    env->DeleteGlobalRef(mObject);
+    env->DeleteGlobalRef(mClass);
+}
+
+void JNIAudioVolumeGroupCallback::onAudioVolumeGroupChanged(volume_group_t group, int flags)
+{
+    JNIEnv *env = AndroidRuntime::getJNIEnv();
+    if (env == NULL) {
+        return;
+    }
+    ALOGV("%s volume group id %d", __FUNCTION__, group);
+    env->CallStaticVoidMethod(mClass,
+                              gAudioVolumeGroupChangeHandlerMethods.postEventFromNative,
+                              mObject,
+                              AUDIOVOLUMEGROUP_EVENT_VOLUME_CHANGED, group, flags, NULL);
+    if (env->ExceptionCheck()) {
+        ALOGW("An exception occurred while notifying an event.");
+        env->ExceptionClear();
+    }
+}
+
+void JNIAudioVolumeGroupCallback::onServiceDied()
+{
+    JNIEnv *env = AndroidRuntime::getJNIEnv();
+    if (env == NULL) {
+        return;
+    }
+    env->CallStaticVoidMethod(mClass,
+                              gAudioVolumeGroupChangeHandlerMethods.postEventFromNative,
+                              mObject,
+                              AUDIOVOLUMEGROUP_EVENT_SERVICE_DIED, 0, 0, NULL);
+    if (env->ExceptionCheck()) {
+        ALOGW("An exception occurred while notifying an event.");
+        env->ExceptionClear();
+    }
+}
+
+static
+sp<JNIAudioVolumeGroupCallback> setJniCallback(JNIEnv* env,
+                                               jobject thiz,
+                                               const sp<JNIAudioVolumeGroupCallback>& callback)
+{
+    Mutex::Autolock l(gLock);
+    sp<JNIAudioVolumeGroupCallback> old = (JNIAudioVolumeGroupCallback*)env->GetLongField(
+                thiz, gAudioVolumeGroupChangeHandlerFields.mJniCallback);
+    if (callback.get()) {
+        callback->incStrong((void*)setJniCallback);
+    }
+    if (old != 0) {
+        old->decStrong((void*)setJniCallback);
+    }
+    env->SetLongField(thiz, gAudioVolumeGroupChangeHandlerFields.mJniCallback,
+                      (jlong)callback.get());
+    return old;
+}
+
+static void
+android_media_AudioVolumeGroupChangeHandler_eventHandlerSetup(JNIEnv *env,
+                                                              jobject thiz,
+                                                              jobject weak_this)
+{
+    ALOGV("%s", __FUNCTION__);
+    sp<JNIAudioVolumeGroupCallback> callback =
+            new JNIAudioVolumeGroupCallback(env, thiz, weak_this);
+
+    if (AudioSystem::addAudioVolumeGroupCallback(callback) == NO_ERROR) {
+        setJniCallback(env, thiz, callback);
+    }
+}
+
+static void
+android_media_AudioVolumeGroupChangeHandler_eventHandlerFinalize(JNIEnv *env, jobject thiz)
+{
+    ALOGV("%s", __FUNCTION__);
+    sp<JNIAudioVolumeGroupCallback> callback = setJniCallback(env, thiz, 0);
+    if (callback != 0) {
+        AudioSystem::removeAudioVolumeGroupCallback(callback);
+    }
+}
+
+/*
+ * JNI registration.
+ */
+static const JNINativeMethod gMethods[] = {
+    {"native_setup", "(Ljava/lang/Object;)V",
+        (void *)android_media_AudioVolumeGroupChangeHandler_eventHandlerSetup},
+    {"native_finalize",  "()V",
+        (void *)android_media_AudioVolumeGroupChangeHandler_eventHandlerFinalize},
+};
+
+int register_android_media_AudioVolumeGroupChangeHandler(JNIEnv *env)
+{
+    jclass audioVolumeGroupChangeHandlerClass =
+            FindClassOrDie(env, kAudioVolumeGroupChangeHandlerClassPathName);
+    gAudioVolumeGroupChangeHandlerMethods.postEventFromNative =
+            GetStaticMethodIDOrDie(env, audioVolumeGroupChangeHandlerClass, "postEventFromNative",
+                                   "(Ljava/lang/Object;IIILjava/lang/Object;)V");
+
+    gAudioVolumeGroupChangeHandlerFields.mJniCallback =
+            GetFieldIDOrDie(env, audioVolumeGroupChangeHandlerClass, "mJniCallback", "J");
+
+    env->DeleteLocalRef(audioVolumeGroupChangeHandlerClass);
+
+    return RegisterMethodsOrDie(env,
+                                kAudioVolumeGroupChangeHandlerClassPathName,
+                                gMethods,
+                                NELEM(gMethods));
+}
+
diff --git a/core/jni/android_media_AudioVolumeGroupCallback.h b/core/jni/android_media_AudioVolumeGroupCallback.h
new file mode 100644
index 0000000..de06549
--- /dev/null
+++ b/core/jni/android_media_AudioVolumeGroupCallback.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <system/audio.h>
+#include <media/AudioSystem.h>
+
+namespace android {
+
+// keep in sync with AudioManager.AudioVolumeGroupChangeHandler.java
+#define AUDIOVOLUMEGROUP_EVENT_VOLUME_CHANGED      1000
+#define AUDIOVOLUMEGROUP_EVENT_SERVICE_DIED        1001
+
+class JNIAudioVolumeGroupCallback: public AudioSystem::AudioVolumeGroupCallback
+{
+public:
+    JNIAudioVolumeGroupCallback(JNIEnv* env, jobject thiz, jobject weak_thiz);
+    ~JNIAudioVolumeGroupCallback();
+
+    void onAudioVolumeGroupChanged(volume_group_t group, int flags) override;
+    void onServiceDied() override;
+
+private:
+    void sendEvent(int event);
+
+    jclass      mClass; /**< Reference to AudioVolumeGroupChangeHandler class. */
+    jobject     mObject; /**< Weak ref to AudioVolumeGroupChangeHandler object to call on. */
+};
+
+} // namespace android
diff --git a/core/jni/android_media_AudioVolumeGroups.cpp b/core/jni/android_media_AudioVolumeGroups.cpp
new file mode 100644
index 0000000..64f0c1e
--- /dev/null
+++ b/core/jni/android_media_AudioVolumeGroups.cpp
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+
+#define LOG_TAG "AudioVolumeGroups-JNI"
+
+#include <inttypes.h>
+#include <jni.h>
+#include <nativehelper/JNIHelp.h>
+#include "core_jni_helpers.h"
+
+#include <utils/Log.h>
+#include <vector>
+
+#include <media/AudioSystem.h>
+#include <media/AudioPolicy.h>
+
+#include <nativehelper/ScopedUtfChars.h>
+
+#include "android_media_AudioAttributes.h"
+#include "android_media_AudioErrors.h"
+
+// ----------------------------------------------------------------------------
+
+using namespace android;
+
+// ----------------------------------------------------------------------------
+static const char* const kClassPathName = "android/media/audiopolicy/AudioVolumeGroups";
+static const char* const kAudioVolumeGroupClassPathName =
+        "android/media/audiopolicy/AudioVolumeGroup";
+
+static jclass gAudioVolumeGroupClass;
+static jmethodID gAudioVolumeGroupCstor;
+static struct {
+    jfieldID    mName;
+    jfieldID    mId;
+} gAudioVolumeGroupFields;
+
+static jclass gArrayListClass;
+static jmethodID gArrayListCstor;
+static struct {
+    jmethodID    add;
+    jmethodID    toArray;
+} gArrayListMethods;
+
+
+static jint convertAudioVolumeGroupsFromNative(
+        JNIEnv *env, jobject *jGroup, const AudioVolumeGroup &group)
+{
+    jint jStatus = (jint)AUDIO_JAVA_SUCCESS;
+    jstring jName = NULL;
+    jint Id = NULL;
+
+    jintArray jLegacyStreamTypes = NULL;
+    jobjectArray jAudioAttributes = NULL;
+    jint numAttributes;
+    jobject jAudioAttribute = NULL;
+
+    jName = env->NewStringUTF(group.getName().c_str());
+    Id = static_cast<jint>(group.getId());
+
+    // Legacy stream types array
+    jLegacyStreamTypes = env->NewIntArray(group.getStreamTypes().size());
+    if (jLegacyStreamTypes == NULL) {
+        jStatus = (jint)AUDIO_JAVA_ERROR;
+        goto exit;
+    }
+    for (size_t streamIndex = 0; streamIndex < group.getStreamTypes().size(); streamIndex++) {
+        jint jStream = group.getStreamTypes()[streamIndex];
+        env->SetIntArrayRegion(jLegacyStreamTypes, streamIndex, 1, &jStream);
+    }
+
+    // Audio Attributes array
+    numAttributes = group.getAudioAttributes().size();
+    jStatus = JNIAudioAttributeHelper::getJavaArray(env, &jAudioAttributes, numAttributes);
+    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+        goto exit;
+    }
+
+    for (size_t j = 0; j < static_cast<size_t>(numAttributes); j++) {
+        auto attributes = group.getAudioAttributes()[j];
+
+        jStatus = JNIAudioAttributeHelper::nativeToJava(env, &jAudioAttribute, attributes);
+        if (jStatus != AUDIO_JAVA_SUCCESS) {
+            goto exit;
+        }
+        env->SetObjectArrayElement(jAudioAttributes, j, jAudioAttribute);
+    }
+
+    *jGroup = env->NewObject(gAudioVolumeGroupClass, gAudioVolumeGroupCstor,
+                             jName, Id, jAudioAttributes, jLegacyStreamTypes);
+exit:
+    if (jName != NULL) {
+        env->DeleteLocalRef(jName);
+    }
+    return jStatus;
+}
+
+static jint
+android_media_AudioSystem_listAudioVolumeGroups(JNIEnv *env, jobject clazz, jobject jVolumeGroups)
+{
+    if (env == NULL) {
+        return AUDIO_JAVA_DEAD_OBJECT;
+    }
+    if (jVolumeGroups == NULL) {
+        ALOGE("listAudioVolumeGroups NULL AudioVolumeGroups");
+        return (jint)AUDIO_JAVA_BAD_VALUE;
+    }
+    if (!env->IsInstanceOf(jVolumeGroups, gArrayListClass)) {
+        ALOGE("listAudioVolumeGroups not an arraylist");
+        return (jint)AUDIO_JAVA_BAD_VALUE;
+    }
+
+    status_t status;
+    AudioVolumeGroupVector groups;
+    jint jStatus;
+    jobject jGroup = NULL;
+
+    status = AudioSystem::listAudioVolumeGroups(groups);
+    if (status != NO_ERROR) {
+        ALOGE("AudioSystem::listAudioVolumeGroups error %d", status);
+        return nativeToJavaStatus(status);
+    }
+    for (const auto &group : groups) {
+        jStatus = convertAudioVolumeGroupsFromNative(env, &jGroup, group);
+        if (jStatus != AUDIO_JAVA_SUCCESS) {
+            goto exit;
+        }
+        env->CallBooleanMethod(jVolumeGroups, gArrayListMethods.add, jGroup);
+    }
+exit:
+    if (jGroup != NULL) {
+        env->DeleteLocalRef(jGroup);
+    }
+    return jStatus;
+}
+
+/*
+ * JNI registration.
+ */
+static const JNINativeMethod gMethods[] = {
+    {"native_list_audio_volume_groups", "(Ljava/util/ArrayList;)I",
+                        (void *)android_media_AudioSystem_listAudioVolumeGroups},
+};
+
+int register_android_media_AudioVolumeGroups(JNIEnv *env)
+{
+    jclass arrayListClass = FindClassOrDie(env, "java/util/ArrayList");
+    gArrayListClass = MakeGlobalRefOrDie(env, arrayListClass);
+    gArrayListCstor = GetMethodIDOrDie(env, arrayListClass, "<init>", "()V");
+    gArrayListMethods.add = GetMethodIDOrDie(env, arrayListClass, "add", "(Ljava/lang/Object;)Z");
+    gArrayListMethods.toArray = GetMethodIDOrDie(env, arrayListClass,
+                                                 "toArray", "()[Ljava/lang/Object;");
+
+    jclass audioVolumeGroupClass = FindClassOrDie(env, kAudioVolumeGroupClassPathName);
+    gAudioVolumeGroupClass = MakeGlobalRefOrDie(env, audioVolumeGroupClass);
+    gAudioVolumeGroupCstor = GetMethodIDOrDie(
+                env, audioVolumeGroupClass, "<init>",
+                "(Ljava/lang/String;I[Landroid/media/AudioAttributes;[I)V");
+
+    gAudioVolumeGroupFields.mName = GetFieldIDOrDie(
+                env, audioVolumeGroupClass, "mName", "Ljava/lang/String;");
+    gAudioVolumeGroupFields.mId = GetFieldIDOrDie(
+                env, audioVolumeGroupClass, "mId", "I");
+
+    env->DeleteLocalRef(audioVolumeGroupClass);
+
+    return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods));
+}
diff --git a/core/jni/android_net_LocalSocketImpl.cpp b/core/jni/android_net_LocalSocketImpl.cpp
index a1f2377..1163b86 100644
--- a/core/jni/android_net_LocalSocketImpl.cpp
+++ b/core/jni/android_net_LocalSocketImpl.cpp
@@ -33,14 +33,16 @@
 #include <unistd.h>
 #include <sys/ioctl.h>
 
+#include <android-base/cmsg.h>
+#include <android-base/macros.h>
 #include <cutils/sockets.h>
 #include <netinet/tcp.h>
 #include <nativehelper/ScopedUtfChars.h>
 
-namespace android {
+using android::base::ReceiveFileDescriptorVector;
+using android::base::SendFileDescriptorVector;
 
-template <typename T>
-void UNUSED(T t) {}
+namespace android {
 
 static jfieldID field_inboundFileDescriptors;
 static jfieldID field_outboundFileDescriptors;
@@ -118,67 +120,6 @@
 }
 
 /**
- * Processes ancillary data, handling only
- * SCM_RIGHTS. Creates appropriate objects and sets appropriate
- * fields in the LocalSocketImpl object. Returns 0 on success
- * or -1 if an exception was thrown.
- */
-static int socket_process_cmsg(JNIEnv *env, jobject thisJ, struct msghdr * pMsg)
-{
-    struct cmsghdr *cmsgptr;
-
-    for (cmsgptr = CMSG_FIRSTHDR(pMsg);
-            cmsgptr != NULL; cmsgptr = CMSG_NXTHDR(pMsg, cmsgptr)) {
-
-        if (cmsgptr->cmsg_level != SOL_SOCKET) {
-            continue;
-        }
-
-        if (cmsgptr->cmsg_type == SCM_RIGHTS) {
-            int *pDescriptors = (int *)CMSG_DATA(cmsgptr);
-            jobjectArray fdArray;
-            int count
-                = ((cmsgptr->cmsg_len - CMSG_LEN(0)) / sizeof(int));
-
-            if (count < 0) {
-                jniThrowException(env, "java/io/IOException",
-                    "invalid cmsg length");
-                return -1;
-            }
-
-            fdArray = env->NewObjectArray(count, class_FileDescriptor, NULL);
-
-            if (fdArray == NULL) {
-                return -1;
-            }
-
-            for (int i = 0; i < count; i++) {
-                jobject fdObject
-                        = jniCreateFileDescriptor(env, pDescriptors[i]);
-
-                if (env->ExceptionCheck()) {
-                    return -1;
-                }
-
-                env->SetObjectArrayElement(fdArray, i, fdObject);
-
-                if (env->ExceptionCheck()) {
-                    return -1;
-                }
-            }
-
-            env->SetObjectField(thisJ, field_inboundFileDescriptors, fdArray);
-
-            if (env->ExceptionCheck()) {
-                return -1;
-            }
-        }
-    }
-
-    return 0;
-}
-
-/**
  * Reads data from a socket into buf, processing any ancillary data
  * and adding it to thisJ.
  *
@@ -189,47 +130,48 @@
         void *buffer, size_t len)
 {
     ssize_t ret;
-    struct msghdr msg;
-    struct iovec iv;
-    unsigned char *buf = (unsigned char *)buffer;
-    // Enough buffer for a pile of fd's. We throw an exception if
-    // this buffer is too small.
-    struct cmsghdr cmsgbuf[2*sizeof(cmsghdr) + 0x100];
+    std::vector<android::base::unique_fd> received_fds;
 
-    memset(&msg, 0, sizeof(msg));
-    memset(&iv, 0, sizeof(iv));
-
-    iv.iov_base = buf;
-    iv.iov_len = len;
-
-    msg.msg_iov = &iv;
-    msg.msg_iovlen = 1;
-    msg.msg_control = cmsgbuf;
-    msg.msg_controllen = sizeof(cmsgbuf);
-
-    ret = TEMP_FAILURE_RETRY(recvmsg(fd, &msg, MSG_NOSIGNAL | MSG_CMSG_CLOEXEC));
-
-    if (ret < 0 && errno == EPIPE) {
-        // Treat this as an end of stream
-        return 0;
-    }
+    ret = ReceiveFileDescriptorVector(fd, buffer, len, 64, &received_fds);
 
     if (ret < 0) {
+        if (errno == EPIPE) {
+            // Treat this as an end of stream
+            return 0;
+        }
+
         jniThrowIOException(env, errno);
         return -1;
     }
 
-    if ((msg.msg_flags & (MSG_CTRUNC | MSG_OOB | MSG_ERRQUEUE)) != 0) {
-        // To us, any of the above flags are a fatal error
+    if (received_fds.size() > 0) {
+        jobjectArray fdArray = env->NewObjectArray(received_fds.size(), class_FileDescriptor, NULL);
 
-        jniThrowException(env, "java/io/IOException",
-                "Unexpected error or truncation during recvmsg()");
+        if (fdArray == NULL) {
+            // NewObjectArray has thrown.
+            return -1;
+        }
 
-        return -1;
-    }
+        for (size_t i = 0; i < received_fds.size(); i++) {
+            jobject fdObject = jniCreateFileDescriptor(env, received_fds[i].get());
 
-    if (ret >= 0) {
-        socket_process_cmsg(env, thisJ, &msg);
+            if (env->ExceptionCheck()) {
+                return -1;
+            }
+
+            env->SetObjectArrayElement(fdArray, i, fdObject);
+
+            if (env->ExceptionCheck()) {
+                return -1;
+            }
+        }
+
+        for (auto &fd : received_fds) {
+            // The fds are stored in java.io.FileDescriptors now.
+            static_cast<void>(fd.release());
+        }
+
+        env->SetObjectField(thisJ, field_inboundFileDescriptors, fdArray);
     }
 
     return ret;
@@ -243,7 +185,6 @@
 static int socket_write_all(JNIEnv *env, jobject object, int fd,
         void *buf, size_t len)
 {
-    ssize_t ret;
     struct msghdr msg;
     unsigned char *buffer = (unsigned char *)buf;
     memset(&msg, 0, sizeof(msg));
@@ -256,14 +197,11 @@
         return -1;
     }
 
-    struct cmsghdr *cmsg;
     int countFds = outboundFds == NULL ? 0 : env->GetArrayLength(outboundFds);
-    int fds[countFds];
-    char msgbuf[CMSG_SPACE(countFds)];
+    std::vector<int> fds;
 
     // Add any pending outbound file descriptors to the message
     if (outboundFds != NULL) {
-
         if (env->ExceptionCheck()) {
             return -1;
         }
@@ -274,47 +212,25 @@
                 return -1;
             }
 
-            fds[i] = jniGetFDFromFileDescriptor(env, fdObject);
+            fds.push_back(jniGetFDFromFileDescriptor(env, fdObject));
             if (env->ExceptionCheck()) {
                 return -1;
             }
         }
-
-        // See "man cmsg" really
-        msg.msg_control = msgbuf;
-        msg.msg_controllen = sizeof msgbuf;
-        cmsg = CMSG_FIRSTHDR(&msg);
-        cmsg->cmsg_level = SOL_SOCKET;
-        cmsg->cmsg_type = SCM_RIGHTS;
-        cmsg->cmsg_len = CMSG_LEN(sizeof fds);
-        memcpy(CMSG_DATA(cmsg), fds, sizeof fds);
     }
 
-    // We only write our msg_control during the first write
-    while (len > 0) {
-        struct iovec iv;
-        memset(&iv, 0, sizeof(iv));
+    ssize_t rc = SendFileDescriptorVector(fd, buffer, len, fds);
 
-        iv.iov_base = buffer;
-        iv.iov_len = len;
-
-        msg.msg_iov = &iv;
-        msg.msg_iovlen = 1;
-
-        do {
-            ret = sendmsg(fd, &msg, MSG_NOSIGNAL);
-        } while (ret < 0 && errno == EINTR);
-
-        if (ret < 0) {
+    while (rc != len) {
+        if (rc == -1) {
             jniThrowIOException(env, errno);
             return -1;
         }
 
-        buffer += ret;
-        len -= ret;
+        buffer += rc;
+        len -= rc;
 
-        // Wipes out any msg_control too
-        memset(&msg, 0, sizeof(msg));
+        rc = send(fd, buffer, len, MSG_NOSIGNAL);
     }
 
     return 0;
diff --git a/core/jni/android_opengl_EGL14.cpp b/core/jni/android_opengl_EGL14.cpp
index 15d1944..de5e3a5 100644
--- a/core/jni/android_opengl_EGL14.cpp
+++ b/core/jni/android_opengl_EGL14.cpp
@@ -35,8 +35,6 @@
 
 #include <ui/ANativeObjectBase.h>
 
-static int initialized = 0;
-
 static jclass egldisplayClass;
 static jclass eglcontextClass;
 static jclass eglsurfaceClass;
@@ -239,7 +237,7 @@
     }
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
-        return false;
+        return JNI_FALSE;
     }
     return (jboolean)_returnValue;
 }
@@ -337,7 +335,7 @@
     }
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
-        return false;
+        return JNI_FALSE;
     }
     return (jboolean)_returnValue;
 }
@@ -457,7 +455,7 @@
     }
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
-        return false;
+        return JNI_FALSE;
     }
     return (jboolean)_returnValue;
 }
@@ -513,7 +511,7 @@
     }
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
-        return false;
+        return JNI_FALSE;
     }
     return (jboolean)_returnValue;
 }
@@ -808,7 +806,7 @@
     }
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
-        return false;
+        return JNI_FALSE;
     }
     return (jboolean)_returnValue;
 }
@@ -1163,7 +1161,7 @@
     }
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
-        return false;
+        return JNI_FALSE;
     }
     return (jboolean)_returnValue;
 }
@@ -1209,7 +1207,7 @@
   (JNIEnv *_env, jobject _this, jobject dpy, jobject surface, jint target) {
     jniThrowException(_env, "java/lang/UnsupportedOperationException",
         "eglCopyBuffers");
-    return (EGLBoolean) 0;
+        return JNI_FALSE;
 }
 
 static const char *classPathName = "android/opengl/EGL14";
diff --git a/core/jni/android_opengl_EGL15.cpp b/core/jni/android_opengl_EGL15.cpp
index 2abd950..99bdce2 100644
--- a/core/jni/android_opengl_EGL15.cpp
+++ b/core/jni/android_opengl_EGL15.cpp
@@ -14,6 +14,8 @@
 ** limitations under the License.
 */
 
+// This source file is automatically generated
+
 #pragma GCC diagnostic ignored "-Wunused-variable"
 #pragma GCC diagnostic ignored "-Wunused-function"
 
@@ -27,8 +29,6 @@
 
 #include <ui/ANativeObjectBase.h>
 
-static int initialized = 0;
-
 // classes from EGL 1.4
 static jclass egldisplayClass;
 static jclass eglsurfaceClass;
@@ -92,7 +92,6 @@
     egldisplayGetHandleID = _env->GetMethodID(egldisplayClass, "getNativeHandle", "()J");
     eglsurfaceGetHandleID = _env->GetMethodID(eglsurfaceClass, "getNativeHandle", "()J");
 
-
     eglconfigConstructor = _env->GetMethodID(eglconfigClass, "<init>", "(J)V");
     eglcontextConstructor = _env->GetMethodID(eglcontextClass, "<init>", "(J)V");
     egldisplayConstructor = _env->GetMethodID(egldisplayClass, "<init>", "(J)V");
@@ -105,7 +104,6 @@
     jobject localeglNoSurfaceObject = _env->NewObject(eglsurfaceClass, eglsurfaceConstructor, reinterpret_cast<jlong>(EGL_NO_SURFACE));
     eglNoSurfaceObject = _env->NewGlobalRef(localeglNoSurfaceObject);
 
-
     jclass eglClass = _env->FindClass("android/opengl/EGL15");
     jfieldID noContextFieldID = _env->GetStaticFieldID(eglClass, "EGL_NO_CONTEXT", "Landroid/opengl/EGLContext;");
     _env->SetStaticObjectField(eglClass, noContextFieldID, eglNoContextObject);
@@ -171,8 +169,6 @@
         *array = NULL;
         return reinterpret_cast<void*>(pointer);
     }
-    eglimageGetHandleID = _env->GetMethodID(eglimageClass, "getNativeHandle", "()J");
-    eglsyncGetHandleID = _env->GetMethodID(eglsyncClass, "getNativeHandle", "()J");
 
     *array = (jarray) _env->CallStaticObjectMethod(nioAccessClass,
             getBaseArrayID, buffer);
@@ -191,7 +187,7 @@
 
 static void *
 fromEGLHandle(JNIEnv *_env, jmethodID mid, jobject obj) {
-    if (obj == NULL){
+    if (obj == NULL) {
         jniThrowException(_env, "java/lang/IllegalArgumentException",
                           "Object is set to null.");
         return nullptr;
@@ -202,10 +198,9 @@
 }
 
 static jobject
-toEGLHandle(JNIEnv *_env, jclass cls, jmethodID con, void * handle) {
-    if (cls == eglimageClass &&
-       (EGLImage)handle == EGL_NO_IMAGE) {
-           return eglNoImageObject;
+toEGLHandle(JNIEnv *_env, jclass cls, jmethodID con, void *handle) {
+    if (cls == eglimageClass && (EGLImage)handle == EGL_NO_IMAGE) {
+        return eglNoImageObject;
     }
 
     return _env->NewObject(cls, con, reinterpret_cast<jlong>(handle));
@@ -337,7 +332,7 @@
     }
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
-        return false;
+        return JNI_FALSE;
     }
     return (jboolean)_returnValue;
 }
@@ -461,12 +456,9 @@
 static jobject
 android_eglCreatePlatformPixmapSurface
   (JNIEnv *_env, jobject _this, jobject dpy, jobject config, jobject native_pixmap_buf, jlongArray attrib_list_ref, jint offset) {
-    if ((true)) {
-        jniThrowException(_env, "java/lang/UnsupportedOperationException",
-            "eglCreatePlatformPixmapSurface");
+    jniThrowException(_env, "java/lang/UnsupportedOperationException",
+        "eglCreatePlatformPixmapSurface");
         return nullptr;
-    }
-    return toEGLHandle(_env, eglsurfaceClass, eglsurfaceConstructor, (EGLSurface) 0);
 }
 
 /* EGLBoolean eglWaitSync ( EGLDisplay dpy, EGLSync sync, EGLint flags ) */
diff --git a/core/jni/android_opengl_EGLExt.cpp b/core/jni/android_opengl_EGLExt.cpp
index 75a25fe..fef8116 100644
--- a/core/jni/android_opengl_EGLExt.cpp
+++ b/core/jni/android_opengl_EGLExt.cpp
@@ -36,8 +36,6 @@
 
 #include <ui/ANativeObjectBase.h>
 
-static int initialized = 0;
-
 static jclass egldisplayClass;
 static jclass eglcontextClass;
 static jclass eglsurfaceClass;
@@ -104,6 +102,7 @@
     if (obj == NULL){
         jniThrowException(_env, "java/lang/IllegalArgumentException",
                           "Object is set to null.");
+        return nullptr;
     }
 
     return reinterpret_cast<void*>(_env->CallLongMethod(obj, mid));
diff --git a/core/jni/android_opengl_GLES10.cpp b/core/jni/android_opengl_GLES10.cpp
index ee5b594..a4ab5db 100644
--- a/core/jni/android_opengl_GLES10.cpp
+++ b/core/jni/android_opengl_GLES10.cpp
@@ -29,8 +29,6 @@
 #include <utils/misc.h>
 #include <assert.h>
 
-static int initialized = 0;
-
 static jclass nioAccessClass;
 static jclass bufferClass;
 static jmethodID getBasePointerID;
diff --git a/core/jni/android_opengl_GLES10Ext.cpp b/core/jni/android_opengl_GLES10Ext.cpp
index da7d0f0..a5dcbf7 100644
--- a/core/jni/android_opengl_GLES10Ext.cpp
+++ b/core/jni/android_opengl_GLES10Ext.cpp
@@ -29,8 +29,6 @@
 #include <utils/misc.h>
 #include <assert.h>
 
-static int initialized = 0;
-
 static jclass nioAccessClass;
 static jclass bufferClass;
 static jmethodID getBasePointerID;
@@ -531,6 +529,7 @@
     }
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
+        return (jint)0;
     }
     return (jint)_returnValue;
 }
@@ -600,6 +599,7 @@
     }
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
+        return (jint)0;
     }
     return (jint)_returnValue;
 }
diff --git a/core/jni/android_opengl_GLES11.cpp b/core/jni/android_opengl_GLES11.cpp
index 391ae53..be86a03 100644
--- a/core/jni/android_opengl_GLES11.cpp
+++ b/core/jni/android_opengl_GLES11.cpp
@@ -29,8 +29,6 @@
 #include <utils/misc.h>
 #include <assert.h>
 
-static int initialized = 0;
-
 static jclass nioAccessClass;
 static jclass bufferClass;
 static jmethodID getBasePointerID;
diff --git a/core/jni/android_opengl_GLES11Ext.cpp b/core/jni/android_opengl_GLES11Ext.cpp
index 09dce32..d28d9a3 100644
--- a/core/jni/android_opengl_GLES11Ext.cpp
+++ b/core/jni/android_opengl_GLES11Ext.cpp
@@ -29,8 +29,6 @@
 #include <utils/misc.h>
 #include <assert.h>
 
-static int initialized = 0;
-
 static jclass nioAccessClass;
 static jclass bufferClass;
 static jmethodID getBasePointerID;
diff --git a/core/jni/android_opengl_GLES20.cpp b/core/jni/android_opengl_GLES20.cpp
index 99922cf..0e20d47 100644
--- a/core/jni/android_opengl_GLES20.cpp
+++ b/core/jni/android_opengl_GLES20.cpp
@@ -29,8 +29,6 @@
 #include <utils/misc.h>
 #include <assert.h>
 
-static int initialized = 0;
-
 static jclass nioAccessClass;
 static jclass bufferClass;
 static jmethodID getBasePointerID;
@@ -2684,6 +2682,7 @@
 
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
+        return (jint)0;
     }
     return (jint)_returnValue;
 }
@@ -3909,6 +3908,7 @@
 
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
+        return (jint)0;
     }
     return (jint)_returnValue;
 }
diff --git a/core/jni/android_opengl_GLES30.cpp b/core/jni/android_opengl_GLES30.cpp
index adc635e..9922398 100644
--- a/core/jni/android_opengl_GLES30.cpp
+++ b/core/jni/android_opengl_GLES30.cpp
@@ -29,8 +29,6 @@
 #include <utils/misc.h>
 #include <assert.h>
 
-static int initialized = 0;
-
 static jclass nioAccessClass;
 static jclass bufferClass;
 static jmethodID getBasePointerID;
@@ -3012,6 +3010,7 @@
 
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
+        return (jint)0;
     }
     return (jint)_returnValue;
 }
@@ -3981,6 +3980,7 @@
 
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
+        return (jint)0;
     }
     return (jint)_returnValue;
 }
diff --git a/core/jni/android_opengl_GLES31.cpp b/core/jni/android_opengl_GLES31.cpp
index 512f562..27dbd39 100644
--- a/core/jni/android_opengl_GLES31.cpp
+++ b/core/jni/android_opengl_GLES31.cpp
@@ -27,8 +27,6 @@
 #include <utils/misc.h>
 #include <assert.h>
 
-static int initialized = 0;
-
 static jclass nioAccessClass;
 static jclass bufferClass;
 static jmethodID getBasePointerID;
@@ -708,6 +706,7 @@
 
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
+        return (jint)0;
     }
     return (jint)_returnValue;
 }
@@ -919,6 +918,7 @@
 
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
+        return (jint)0;
     }
     return (jint)_returnValue;
 }
diff --git a/core/jni/android_opengl_GLES31Ext.cpp b/core/jni/android_opengl_GLES31Ext.cpp
index 5543fca..5b671c8 100644
--- a/core/jni/android_opengl_GLES31Ext.cpp
+++ b/core/jni/android_opengl_GLES31Ext.cpp
@@ -28,8 +28,6 @@
 #include <utils/misc.h>
 #include <assert.h>
 
-static int initialized = 0;
-
 static jclass nioAccessClass;
 static jclass bufferClass;
 static jmethodID getBasePointerID;
diff --git a/core/jni/android_opengl_GLES32.cpp b/core/jni/android_opengl_GLES32.cpp
index 2f1e31e..d59d25c 100644
--- a/core/jni/android_opengl_GLES32.cpp
+++ b/core/jni/android_opengl_GLES32.cpp
@@ -27,8 +27,6 @@
 #include <utils/misc.h>
 #include <assert.h>
 
-static int initialized = 0;
-
 static jclass nioAccessClass;
 static jclass bufferClass;
 static jmethodID getBasePointerID;
diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp
index a212f47..af2d413 100644
--- a/core/jni/android_util_AssetManager.cpp
+++ b/core/jni/android_util_AssetManager.cpp
@@ -343,7 +343,9 @@
   assetmanager->ForEachPackage([&](const std::string& this_package_name, uint8_t package_id) {
     if (this_package_name == std_package_name) {
       map = assetmanager->GetOverlayableMapForPackage(package_id);
+      return false;
     }
+    return true;
   });
 
   if (map == nullptr) {
@@ -521,15 +523,16 @@
     return nullptr;
   }
 
-  assetmanager->ForEachPackage([&](const std::string& package_name, uint8_t package_id) {
+  assetmanager->ForEachPackage([&](const std::string& package_name, uint8_t package_id) -> bool {
     jstring jpackage_name = env->NewStringUTF(package_name.c_str());
     if (jpackage_name == nullptr) {
       // An exception is pending.
-      return;
+      return false;
     }
 
     env->CallVoidMethod(sparse_array, gSparseArrayOffsets.put, static_cast<jint>(package_id),
                         jpackage_name);
+    return true;
   });
   return sparse_array;
 }
diff --git a/core/jni/android_view_DisplayEventReceiver.cpp b/core/jni/android_view_DisplayEventReceiver.cpp
index 191472d..8d702d1 100644
--- a/core/jni/android_view_DisplayEventReceiver.cpp
+++ b/core/jni/android_view_DisplayEventReceiver.cpp
@@ -41,6 +41,7 @@
 
     jmethodID dispatchVsync;
     jmethodID dispatchHotplug;
+    jmethodID dispatchConfigChanged;
 } gDisplayEventReceiverClassInfo;
 
 
@@ -61,6 +62,8 @@
 
     void dispatchVsync(nsecs_t timestamp, PhysicalDisplayId displayId, uint32_t count) override;
     void dispatchHotplug(nsecs_t timestamp, PhysicalDisplayId displayId, bool connected) override;
+    void dispatchConfigChanged(nsecs_t timestamp, PhysicalDisplayId displayId,
+                               int32_t configId) override;
 };
 
 
@@ -114,6 +117,23 @@
     mMessageQueue->raiseAndClearException(env, "dispatchHotplug");
 }
 
+void NativeDisplayEventReceiver::dispatchConfigChanged(nsecs_t timestamp,
+                                                       PhysicalDisplayId displayId,
+                                                       int32_t configId) {
+    JNIEnv* env = AndroidRuntime::getJNIEnv();
+
+    ScopedLocalRef<jobject> receiverObj(env, jniGetReferent(env, mReceiverWeakGlobal));
+    if (receiverObj.get()) {
+        ALOGV("receiver %p ~ Invoking config changed handler.", this);
+        env->CallVoidMethod(receiverObj.get(),
+                            gDisplayEventReceiverClassInfo.dispatchConfigChanged,
+                            timestamp, displayId, configId);
+        ALOGV("receiver %p ~ Returned from config changed handler.", this);
+    }
+
+    mMessageQueue->raiseAndClearException(env, "dispatchConfigChanged");
+}
+
 
 static jlong nativeInit(JNIEnv* env, jclass clazz, jobject receiverWeak,
         jobject messageQueueObj, jint vsyncSource) {
@@ -180,6 +200,8 @@
             gDisplayEventReceiverClassInfo.clazz, "dispatchVsync", "(JJI)V");
     gDisplayEventReceiverClassInfo.dispatchHotplug = GetMethodIDOrDie(env,
             gDisplayEventReceiverClassInfo.clazz, "dispatchHotplug", "(JJZ)V");
+    gDisplayEventReceiverClassInfo.dispatchConfigChanged = GetMethodIDOrDie(env,
+           gDisplayEventReceiverClassInfo.clazz, "dispatchConfigChanged", "(JJI)V");
 
     return res;
 }
diff --git a/core/jni/android_view_InputEventReceiver.cpp b/core/jni/android_view_InputEventReceiver.cpp
index fb6dd93..7975c86 100644
--- a/core/jni/android_view_InputEventReceiver.cpp
+++ b/core/jni/android_view_InputEventReceiver.cpp
@@ -23,10 +23,9 @@
 #include <nativehelper/JNIHelp.h>
 
 #include <android_runtime/AndroidRuntime.h>
-#include <utils/Log.h>
+#include <log/log.h>
 #include <utils/Looper.h>
 #include <utils/Vector.h>
-#include <utils/threads.h>
 #include <input/InputTransport.h>
 #include "android_os_MessageQueue.h"
 #include "android_view_InputChannel.h"
diff --git a/core/jni/android_view_InputEventSender.cpp b/core/jni/android_view_InputEventSender.cpp
index aa10a2f..2542286 100644
--- a/core/jni/android_view_InputEventSender.cpp
+++ b/core/jni/android_view_InputEventSender.cpp
@@ -21,10 +21,8 @@
 #include <nativehelper/JNIHelp.h>
 
 #include <android_runtime/AndroidRuntime.h>
-#include <utils/Log.h>
+#include <log/log.h>
 #include <utils/Looper.h>
-#include <utils/threads.h>
-#include <utils/KeyedVector.h>
 #include <input/InputTransport.h>
 #include "android_os_MessageQueue.h"
 #include "android_view_InputChannel.h"
@@ -32,6 +30,7 @@
 #include "android_view_MotionEvent.h"
 
 #include <nativehelper/ScopedLocalRef.h>
+#include <unordered_map>
 
 #include "core_jni_helpers.h"
 
@@ -65,7 +64,8 @@
     jobject mSenderWeakGlobal;
     InputPublisher mInputPublisher;
     sp<MessageQueue> mMessageQueue;
-    KeyedVector<uint32_t, uint32_t> mPublishedSeqMap;
+    std::unordered_map<uint32_t, uint32_t> mPublishedSeqMap;
+
     uint32_t mNextPublishedSeq;
 
     const std::string getInputChannelName() {
@@ -122,7 +122,7 @@
                 getInputChannelName().c_str(), status);
         return status;
     }
-    mPublishedSeqMap.add(publishedSeq, seq);
+    mPublishedSeqMap.emplace(publishedSeq, seq);
     return OK;
 }
 
@@ -150,7 +150,7 @@
             return status;
         }
     }
-    mPublishedSeqMap.add(publishedSeq, seq);
+    mPublishedSeqMap.emplace(publishedSeq, seq);
     return OK;
 }
 
@@ -199,35 +199,37 @@
             return status;
         }
 
-        ssize_t index = mPublishedSeqMap.indexOfKey(publishedSeq);
-        if (index >= 0) {
-            uint32_t seq = mPublishedSeqMap.valueAt(index);
-            mPublishedSeqMap.removeItemsAt(index);
+        auto it = mPublishedSeqMap.find(publishedSeq);
+        if (it == mPublishedSeqMap.end()) {
+            continue;
+        }
 
-            if (kDebugDispatchCycle) {
-                ALOGD("channel '%s' ~ Received finished signal, seq=%u, handled=%s, "
-                        "pendingEvents=%zu.",
-                        getInputChannelName().c_str(), seq, handled ? "true" : "false",
-                        mPublishedSeqMap.size());
+        uint32_t seq = it->second;
+        mPublishedSeqMap.erase(it);
+
+        if (kDebugDispatchCycle) {
+            ALOGD("channel '%s' ~ Received finished signal, seq=%u, handled=%s, "
+                    "pendingEvents=%zu.",
+                    getInputChannelName().c_str(), seq, handled ? "true" : "false",
+                    mPublishedSeqMap.size());
+        }
+
+        if (!skipCallbacks) {
+            if (!senderObj.get()) {
+                senderObj.reset(jniGetReferent(env, mSenderWeakGlobal));
+                if (!senderObj.get()) {
+                    ALOGW("channel '%s' ~ Sender object was finalized "
+                            "without being disposed.", getInputChannelName().c_str());
+                    return DEAD_OBJECT;
+                }
             }
 
-            if (!skipCallbacks) {
-                if (!senderObj.get()) {
-                    senderObj.reset(jniGetReferent(env, mSenderWeakGlobal));
-                    if (!senderObj.get()) {
-                        ALOGW("channel '%s' ~ Sender object was finalized "
-                                "without being disposed.", getInputChannelName().c_str());
-                        return DEAD_OBJECT;
-                    }
-                }
-
-                env->CallVoidMethod(senderObj.get(),
-                        gInputEventSenderClassInfo.dispatchInputEventFinished,
-                        jint(seq), jboolean(handled));
-                if (env->ExceptionCheck()) {
-                    ALOGE("Exception dispatching finished signal.");
-                    skipCallbacks = true;
-                }
+            env->CallVoidMethod(senderObj.get(),
+                    gInputEventSenderClassInfo.dispatchInputEventFinished,
+                    jint(seq), jboolean(handled));
+            if (env->ExceptionCheck()) {
+                ALOGE("Exception dispatching finished signal.");
+                skipCallbacks = true;
             }
         }
     }
diff --git a/core/jni/android_view_Surface.cpp b/core/jni/android_view_Surface.cpp
index 464f249..a900294 100644
--- a/core/jni/android_view_Surface.cpp
+++ b/core/jni/android_view_Surface.cpp
@@ -58,8 +58,6 @@
 
 namespace android {
 
-using ui::Dataspace;
-
 static const char* const OutOfResourcesException =
     "android/view/Surface$OutOfResourcesException";
 
@@ -129,135 +127,17 @@
 }
 
 int android_view_Surface_mapPublicFormatToHalFormat(PublicFormat f) {
-
-    switch(f) {
-        case PublicFormat::JPEG:
-        case PublicFormat::DEPTH_POINT_CLOUD:
-        case PublicFormat::DEPTH_JPEG:
-        case PublicFormat::HEIC:
-            return HAL_PIXEL_FORMAT_BLOB;
-        case PublicFormat::DEPTH16:
-            return HAL_PIXEL_FORMAT_Y16;
-        case PublicFormat::RAW_SENSOR:
-        case PublicFormat::RAW_DEPTH:
-            return HAL_PIXEL_FORMAT_RAW16;
-        default:
-            // Most formats map 1:1
-            return static_cast<int>(f);
-    }
+    return mapPublicFormatToHalFormat(f);
 }
 
 android_dataspace android_view_Surface_mapPublicFormatToHalDataspace(
         PublicFormat f) {
-    Dataspace dataspace;
-    switch(f) {
-        case PublicFormat::JPEG:
-            dataspace = Dataspace::V0_JFIF;
-            break;
-        case PublicFormat::DEPTH_POINT_CLOUD:
-        case PublicFormat::DEPTH16:
-        case PublicFormat::RAW_DEPTH:
-            dataspace = Dataspace::DEPTH;
-            break;
-        case PublicFormat::RAW_SENSOR:
-        case PublicFormat::RAW_PRIVATE:
-        case PublicFormat::RAW10:
-        case PublicFormat::RAW12:
-            dataspace = Dataspace::ARBITRARY;
-            break;
-        case PublicFormat::YUV_420_888:
-        case PublicFormat::NV21:
-        case PublicFormat::YV12:
-            dataspace = Dataspace::V0_JFIF;
-            break;
-        case PublicFormat::DEPTH_JPEG:
-            dataspace = Dataspace::DYNAMIC_DEPTH;
-            break;
-        case PublicFormat::HEIC:
-            dataspace = Dataspace::HEIF;
-            break;
-        default:
-            // Most formats map to UNKNOWN
-            dataspace = Dataspace::UNKNOWN;
-            break;
-    }
-    return static_cast<android_dataspace>(dataspace);
+    return mapPublicFormatToHalDataspace(f);
 }
 
 PublicFormat android_view_Surface_mapHalFormatDataspaceToPublicFormat(
         int format, android_dataspace dataSpace) {
-    Dataspace ds = static_cast<Dataspace>(dataSpace);
-    switch(format) {
-        case HAL_PIXEL_FORMAT_RGBA_8888:
-        case HAL_PIXEL_FORMAT_RGBX_8888:
-        case HAL_PIXEL_FORMAT_RGBA_FP16:
-        case HAL_PIXEL_FORMAT_RGBA_1010102:
-        case HAL_PIXEL_FORMAT_RGB_888:
-        case HAL_PIXEL_FORMAT_RGB_565:
-        case HAL_PIXEL_FORMAT_Y8:
-        case HAL_PIXEL_FORMAT_RAW10:
-        case HAL_PIXEL_FORMAT_RAW12:
-        case HAL_PIXEL_FORMAT_YCbCr_420_888:
-        case HAL_PIXEL_FORMAT_YV12:
-            // Enums overlap in both name and value
-            return static_cast<PublicFormat>(format);
-        case HAL_PIXEL_FORMAT_RAW16:
-            switch (ds) {
-                case Dataspace::DEPTH:
-                  return PublicFormat::RAW_DEPTH;
-                default:
-                  return PublicFormat::RAW_SENSOR;
-            }
-        case HAL_PIXEL_FORMAT_RAW_OPAQUE:
-            // Name differs, though value is the same
-            return PublicFormat::RAW_PRIVATE;
-        case HAL_PIXEL_FORMAT_YCbCr_422_SP:
-            // Name differs, though the value is the same
-            return PublicFormat::NV16;
-        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
-            // Name differs, though the value is the same
-            return PublicFormat::NV21;
-        case HAL_PIXEL_FORMAT_YCbCr_422_I:
-            // Name differs, though the value is the same
-            return PublicFormat::YUY2;
-        case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
-            // Name differs, though the value is the same
-            return PublicFormat::PRIVATE;
-        case HAL_PIXEL_FORMAT_Y16:
-            // Dataspace-dependent
-            switch (ds) {
-                case Dataspace::DEPTH:
-                    return PublicFormat::DEPTH16;
-                default:
-                    // Assume non-depth Y16 is just Y16.
-                    return PublicFormat::Y16;
-            }
-            break;
-        case HAL_PIXEL_FORMAT_BLOB:
-            // Dataspace-dependent
-            switch (ds) {
-                case Dataspace::DEPTH:
-                    return PublicFormat::DEPTH_POINT_CLOUD;
-                case Dataspace::V0_JFIF:
-                    return PublicFormat::JPEG;
-                case Dataspace::HEIF:
-                    return PublicFormat::HEIC;
-                default:
-                    if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_DYNAMIC_DEPTH)) {
-                        return PublicFormat::DEPTH_JPEG;
-                    } else {
-                        // Assume otherwise-marked blobs are also JPEG
-                        return PublicFormat::JPEG;
-                    }
-            }
-            break;
-        case HAL_PIXEL_FORMAT_BGRA_8888:
-            // Not defined in public API
-            return PublicFormat::UNKNOWN;
-
-        default:
-            return PublicFormat::UNKNOWN;
-    }
+    return mapHalFormatDataspaceToPublicFormat(format, dataSpace);
 }
 // ----------------------------------------------------------------------------
 
diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp
index 003ee37..af2bf2d 100644
--- a/core/jni/android_view_SurfaceControl.cpp
+++ b/core/jni/android_view_SurfaceControl.cpp
@@ -205,7 +205,7 @@
 
 static jobject nativeScreenshot(JNIEnv* env, jclass clazz,
         jobject displayTokenObj, jobject sourceCropObj, jint width, jint height,
-        bool useIdentityTransform, int rotation) {
+        bool useIdentityTransform, int rotation, bool captureSecureLayers) {
     sp<IBinder> displayToken = ibinderForJavaObject(env, displayTokenObj);
     if (displayToken == NULL) {
         return NULL;
@@ -213,9 +213,9 @@
     Rect sourceCrop = rectFromObj(env, sourceCropObj);
     sp<GraphicBuffer> buffer;
     status_t res = ScreenshotClient::capture(displayToken, ui::Dataspace::V0_SRGB,
-                                             ui::PixelFormat::RGBA_8888,
-                                             sourceCrop, width, height,
-                                             useIdentityTransform, rotation, &buffer);
+            ui::PixelFormat::RGBA_8888,
+            sourceCrop, width, height,
+            useIdentityTransform, rotation, captureSecureLayers, &buffer);
     if (res != NO_ERROR) {
         return NULL;
     }
@@ -698,6 +698,48 @@
     return configArray;
 }
 
+static jboolean nativeSetAllowedDisplayConfigs(JNIEnv* env, jclass clazz,
+        jobject tokenObj, jintArray configArray) {
+    sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
+    if (token == nullptr) return JNI_FALSE;
+
+    std::vector<int32_t> allowedConfigs;
+    jsize configArraySize = env->GetArrayLength(configArray);
+    allowedConfigs.reserve(configArraySize);
+
+    jint* configArrayElements = env->GetIntArrayElements(configArray, 0);
+    for (int i = 0; i < configArraySize; i++) {
+        allowedConfigs.push_back(configArrayElements[i]);
+    }
+    env->ReleaseIntArrayElements(configArray, configArrayElements, 0);
+
+    size_t result = SurfaceComposerClient::setAllowedDisplayConfigs(token, allowedConfigs);
+    return result == NO_ERROR ? JNI_TRUE : JNI_FALSE;
+}
+
+static jintArray nativeGetAllowedDisplayConfigs(JNIEnv* env, jclass clazz, jobject tokenObj) {
+    sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
+    if (token == nullptr) return JNI_FALSE;
+
+    std::vector<int32_t> allowedConfigs;
+    size_t result = SurfaceComposerClient::getAllowedDisplayConfigs(token, &allowedConfigs);
+    if (result != NO_ERROR) {
+        return nullptr;
+    }
+
+    jintArray allowedConfigsArray = env->NewIntArray(allowedConfigs.size());
+    if (allowedConfigsArray == nullptr) {
+        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
+        return nullptr;
+    }
+    jint* allowedConfigsArrayValues = env->GetIntArrayElements(allowedConfigsArray, 0);
+    for (size_t i = 0; i < allowedConfigs.size(); i++) {
+        allowedConfigsArrayValues[i] = static_cast<jint>(allowedConfigs[i]);
+    }
+    env->ReleaseIntArrayElements(allowedConfigsArray, allowedConfigsArrayValues, 0);
+    return allowedConfigsArray;
+}
+
 static jint nativeGetActiveConfig(JNIEnv* env, jclass clazz, jobject tokenObj) {
     sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
     if (token == NULL) return -1;
@@ -1194,6 +1236,10 @@
             (void*)nativeGetActiveConfig },
     {"nativeSetActiveConfig", "(Landroid/os/IBinder;I)Z",
             (void*)nativeSetActiveConfig },
+    {"nativeSetAllowedDisplayConfigs", "(Landroid/os/IBinder;[I)Z",
+            (void*)nativeSetAllowedDisplayConfigs },
+    {"nativeGetAllowedDisplayConfigs", "(Landroid/os/IBinder;)[I",
+            (void*)nativeGetAllowedDisplayConfigs },
     {"nativeGetDisplayColorModes", "(Landroid/os/IBinder;)[I",
             (void*)nativeGetDisplayColorModes},
     {"nativeGetDisplayNativePrimaries", "(Landroid/os/IBinder;)Landroid/view/SurfaceControl$DisplayPrimaries;",
@@ -1232,7 +1278,7 @@
             (void*)nativeSetOverrideScalingMode },
     {"nativeGetHandle", "(J)Landroid/os/IBinder;",
             (void*)nativeGetHandle },
-    {"nativeScreenshot", "(Landroid/os/IBinder;Landroid/graphics/Rect;IIZI)Landroid/graphics/GraphicBuffer;",
+    {"nativeScreenshot", "(Landroid/os/IBinder;Landroid/graphics/Rect;IIZIZ)Landroid/graphics/GraphicBuffer;",
             (void*)nativeScreenshot },
     {"nativeCaptureLayers", "(Landroid/os/IBinder;Landroid/graphics/Rect;F)Landroid/graphics/GraphicBuffer;",
             (void*)nativeCaptureLayers },
diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index 73e6789..2ccb01a 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -155,10 +155,10 @@
 static int gBlastulaPoolEventFD = -1;
 
 /**
- * The maximum value that the gBlastulaPoolMax variable may take.  This value
- * is a mirror of Zygote.BLASTULA_POOL_MAX_LIMIT
+ * The maximum value that the gBlastulaPoolSizeMax variable may take.  This value
+ * is a mirror of ZygoteServer.BLASTULA_POOL_SIZE_MAX_LIMIT
  */
-static constexpr int BLASTULA_POOL_MAX_LIMIT = 10;
+static constexpr int BLASTULA_POOL_SIZE_MAX_LIMIT = 100;
 
 /**
  * A helper class containing accounting information for Blastulas.
@@ -216,6 +216,19 @@
     }
   }
 
+  void Clear() {
+    EntryStorage storage = mStorage.load();
+
+    if (storage != INVALID_ENTRY_VALUE) {
+      close(storage.read_pipe_fd);
+      mStorage.store(INVALID_ENTRY_VALUE);
+    }
+  }
+
+  void Invalidate() {
+    mStorage.store(INVALID_ENTRY_VALUE);
+  }
+
   /**
    * @return A copy of the data stored in this entry.
    */
@@ -257,7 +270,7 @@
  * the BlastulaTableEntry class prevent data races during these concurrent
  * operations.
  */
-static std::array<BlastulaTableEntry, BLASTULA_POOL_MAX_LIMIT> gBlastulaTable;
+static std::array<BlastulaTableEntry, BLASTULA_POOL_SIZE_MAX_LIMIT> gBlastulaTable;
 
 /**
  * The list of open zygote file descriptors.
@@ -736,10 +749,19 @@
 }
 
 static void PreparePkgSpecificDirs(const std::vector<std::string>& package_names,
-                                   const std::vector<std::string>& volume_labels,
                                    bool mount_all_obbs, const std::string& sandbox_id,
                                    userid_t user_id, uid_t uid, fail_fn_t fail_fn) {
-  for (auto& label : volume_labels) {
+  std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir("/storage"), closedir);
+  if (!dirp) {
+    fail_fn(CREATE_ERROR("Failed to opendir /storage: %s", strerror(errno)));
+  }
+  struct dirent* ent;
+  while ((ent = readdir(dirp.get()))) {
+    if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..") || !strcmp(ent->d_name, "self")) {
+      continue;
+    }
+    std::string label(ent->d_name);
+
     std::string mnt_source = StringPrintf("/mnt/runtime/write/%s", label.c_str());
     std::string mnt_target = StringPrintf("/storage/%s", label.c_str());
     if (label == "emulated") {
@@ -819,7 +841,7 @@
 static void MountEmulatedStorage(uid_t uid, jint mount_mode,
         bool force_mount_namespace, const std::string& package_name,
         const std::vector<std::string>& packages_for_uid,
-        const std::vector<std::string>& visible_vol_ids, const std::string& sandbox_id,
+        const std::string& sandbox_id,
         fail_fn_t fail_fn) {
   // See storage config details at http://source.android.com/tech/storage/
 
@@ -878,16 +900,16 @@
       userid_t user_id = multiuser_get_user_id(uid);
       CreatePkgSandboxTarget(user_id, fail_fn);
 
-      std::string pkgSandboxDir = StringPrintf("/mnt/user/%d/package", user_id);
-      if (TEMP_FAILURE_RETRY(mount(pkgSandboxDir.c_str(), "/storage",
+      std::string pkg_sandbox_dir = StringPrintf("/mnt/user/%d/package", user_id);
+      if (TEMP_FAILURE_RETRY(mount(pkg_sandbox_dir.c_str(), "/storage",
                                    nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
         fail_fn(CREATE_ERROR("Failed to mount %s to /storage: %s",
-                             pkgSandboxDir.c_str(), strerror(errno)));
+                             pkg_sandbox_dir.c_str(), strerror(errno)));
       }
 
       HandleMountModeInstaller(mount_mode, user_id, sandbox_id, fail_fn);
 
-      PreparePkgSpecificDirs(packages_for_uid, visible_vol_ids,
+      PreparePkgSpecificDirs(packages_for_uid,
           mount_mode == MOUNT_EXTERNAL_INSTALLER, sandbox_id, user_id, uid, fail_fn);
     }
   } else {
@@ -900,16 +922,16 @@
 
     // Mount user-specific symlink helper into place
     userid_t user_id = multiuser_get_user_id(uid);
-    const String8 userSource(String8::format("/mnt/user/%d", user_id));
-    if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
+    const String8 user_source(String8::format("/mnt/user/%d", user_id));
+    if (fs_prepare_dir(user_source.string(), 0751, 0, 0) == -1) {
       fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s",
-                           userSource.string()));
+                           user_source.string()));
     }
 
-    if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
+    if (TEMP_FAILURE_RETRY(mount(user_source.string(), "/storage/self",
                                  nullptr, MS_BIND, nullptr)) == -1) {
       fail_fn(CREATE_ERROR("Failed to mount %s to /storage/self: %s",
-                           userSource.string(), strerror(errno)));
+                           user_source.string(), strerror(errno)));
     }
   }
 }
@@ -1159,6 +1181,14 @@
   }
 }
 
+static void ClearBlastulaTable() {
+  for (BlastulaTableEntry& entry : gBlastulaTable) {
+    entry.Clear();
+  }
+
+  gBlastulaPoolCount = 0;
+}
+
 // Utility routine to fork a process from the zygote.
 static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
                         const std::vector<int>& fds_to_close,
@@ -1201,12 +1231,17 @@
     // Clean up any descriptors which must be closed immediately
     DetachDescriptors(env, fds_to_close, fail_fn);
 
+    // Invalidate the entries in the blastula table.
+    ClearBlastulaTable();
+
     // Re-open all remaining open file descriptors so that they aren't shared
     // with the zygote across a fork.
     gOpenFdTable->ReopenOrDetach(fail_fn);
 
     // Turn fdsan back on.
     android_fdsan_set_error_level(fdsan_error_level);
+  } else {
+    ALOGD("Forked child process %d", pid);
   }
 
   // We blocked SIGCHLD prior to a fork, we unblock it here.
@@ -1224,7 +1259,7 @@
                              bool is_child_zygote, jstring managed_instruction_set,
                              jstring managed_app_data_dir, jstring managed_package_name,
                              jobjectArray managed_pacakges_for_uid,
-                             jobjectArray managed_visible_vol_ids, jstring managed_sandbox_id) {
+                             jstring managed_sandbox_id) {
   const char* process_name = is_system_server ? "system_server" : "zygote";
   auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
   auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
@@ -1272,12 +1307,8 @@
       ExtractJStringArray(env, process_name, managed_nice_name, managed_pacakges_for_uid).
       value_or(std::vector<std::string>());
 
-  std::vector<std::string> visible_vol_ids =
-      ExtractJStringArray(env, process_name, managed_nice_name, managed_visible_vol_ids).
-      value_or(std::vector<std::string>());
-
   MountEmulatedStorage(uid, mount_external, use_native_bridge, package_name.value(),
-                       packages_for_uid, visible_vol_ids, sandbox_id.value_or(""), fail_fn);
+                       packages_for_uid, sandbox_id.value_or(""), fail_fn);
 
   // If this zygote isn't root, it won't be able to create a process group,
   // since the directory is owned by root.
@@ -1580,7 +1611,7 @@
         jint mount_external, jstring se_info, jstring nice_name,
         jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
         jstring instruction_set, jstring app_data_dir, jstring package_name,
-        jobjectArray packages_for_uid, jobjectArray visible_vol_ids, jstring sandbox_id) {
+        jobjectArray packages_for_uid, jstring sandbox_id) {
     jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
 
     if (UNLIKELY(managed_fds_to_close == nullptr)) {
@@ -1612,7 +1643,7 @@
                        capabilities, capabilities,
                        mount_external, se_info, nice_name, false,
                        is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
-                       package_name, packages_for_uid, visible_vol_ids, sandbox_id);
+                       package_name, packages_for_uid, sandbox_id);
     }
     return pid;
 }
@@ -1638,7 +1669,7 @@
       SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
                        permitted_capabilities, effective_capabilities,
                        MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
-                       false, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
+                       false, nullptr, nullptr, nullptr, nullptr, nullptr);
   } else if (pid > 0) {
       // The zygote process checks whether the child process has died or not.
       ALOGI("System server process %d has been created", pid);
@@ -1792,7 +1823,7 @@
     jint runtime_flags, jobjectArray rlimits,
     jint mount_external, jstring se_info, jstring nice_name,
     jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir,
-    jstring package_name, jobjectArray packages_for_uid, jobjectArray visible_vol_ids,
+    jstring package_name, jobjectArray packages_for_uid,
     jstring sandbox_id) {
   jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
 
@@ -1800,7 +1831,7 @@
                    capabilities, capabilities,
                    mount_external, se_info, nice_name, false,
                    is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
-                   package_name, packages_for_uid, visible_vol_ids, sandbox_id);
+                   package_name, packages_for_uid, sandbox_id);
 }
 
 /**
@@ -1887,11 +1918,32 @@
   return gBlastulaPoolCount;
 }
 
+/**
+ * Kills all processes currently in the blastula pool.
+ *
+ * @param env  Managed runtime environment
+ * @return The number of blastulas currently in the blastula pool
+ */
+static void com_android_internal_os_Zygote_nativeEmptyBlastulaPool(JNIEnv* env, jclass) {
+  for (auto& entry : gBlastulaTable) {
+    auto entry_storage = entry.GetValues();
+
+    if (entry_storage.has_value()) {
+      kill(entry_storage.value().pid, SIGKILL);
+      close(entry_storage.value().read_pipe_fd);
+
+      // Avoid a second atomic load by invalidating instead of clearing.
+      entry.Invalidate();
+      --gBlastulaPoolCount;
+    }
+  }
+}
+
 static const JNINativeMethod gMethods[] = {
     { "nativeSecurityInit", "()V",
       (void *) com_android_internal_os_Zygote_nativeSecurityInit },
     { "nativeForkAndSpecialize",
-      "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)I",
+      "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)I",
       (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
     { "nativeForkSystemServer", "(II[II[[IJJ)I",
       (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
@@ -1906,7 +1958,7 @@
     { "nativeForkBlastula", "(II[I)I",
       (void *) com_android_internal_os_Zygote_nativeForkBlastula },
     { "nativeSpecializeBlastula",
-      "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V",
+      "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V",
       (void *) com_android_internal_os_Zygote_nativeSpecializeBlastula },
     { "nativeGetSocketFDs", "(Z)V",
       (void *) com_android_internal_os_Zygote_nativeGetSocketFDs },
@@ -1917,7 +1969,9 @@
     { "nativeGetBlastulaPoolEventFD", "()I",
       (void *) com_android_internal_os_Zygote_nativeGetBlastulaPoolEventFD },
     { "nativeGetBlastulaPoolCount", "()I",
-      (void *) com_android_internal_os_Zygote_nativeGetBlastulaPoolCount }
+      (void *) com_android_internal_os_Zygote_nativeGetBlastulaPoolCount },
+    { "nativeEmptyBlastulaPool", "()V",
+      (void *) com_android_internal_os_Zygote_nativeEmptyBlastulaPool }
 };
 
 int register_com_android_internal_os_Zygote(JNIEnv* env) {
diff --git a/core/jni/com_google_android_gles_jni_GLImpl.cpp b/core/jni/com_google_android_gles_jni_GLImpl.cpp
index 40ff7e4..c806162 100644
--- a/core/jni/com_google_android_gles_jni_GLImpl.cpp
+++ b/core/jni/com_google_android_gles_jni_GLImpl.cpp
@@ -65,8 +65,6 @@
         GLsizei stride, const GLvoid *pointer, GLsizei count);
 }
 
-static int initialized = 0;
-
 static jclass nioAccessClass;
 static jclass bufferClass;
 static jclass G11ImplClass;
@@ -4239,6 +4237,7 @@
     }
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
+        return (jint)0;
     }
     return (jint)_returnValue;
 }
@@ -4308,6 +4307,7 @@
     }
     if (_exception) {
         jniThrowException(_env, _exceptionType, _exceptionMessage);
+        return (jint)0;
     }
     return (jint)_returnValue;
 }
@@ -4904,6 +4904,7 @@
   (JNIEnv *_env, jobject _this, jint target, jint pname, jintArray params_ref, jint offset) {
     jniThrowException(_env, "java/lang/UnsupportedOperationException",
         "glGetBufferParameteriv");
+    return;
 }
 
 /* void glGetBufferParameteriv ( GLenum target, GLenum pname, GLint *params ) */
@@ -4912,6 +4913,7 @@
   (JNIEnv *_env, jobject _this, jint target, jint pname, jobject params_buf) {
     jniThrowException(_env, "java/lang/UnsupportedOperationException",
         "glGetBufferParameteriv");
+    return;
 }
 
 /* void glGetClipPlanef ( GLenum pname, GLfloat *eqn ) */
diff --git a/core/jni/include/android_runtime/android_view_Surface.h b/core/jni/include/android_runtime/android_view_Surface.h
index 3f7c00c..04718cd 100644
--- a/core/jni/include/android_runtime/android_view_Surface.h
+++ b/core/jni/include/android_runtime/android_view_Surface.h
@@ -19,6 +19,7 @@
 
 #include <android/native_window.h>
 #include <system/graphics.h>
+#include <ui/PublicFormat.h>
 
 #include "jni.h"
 
@@ -27,41 +28,6 @@
 class Surface;
 class IGraphicBufferProducer;
 
-/**
- * Enum mirroring the public API definitions for image and pixel formats.
- * Some of these are hidden in the public API
- *
- * Keep up to date with android.graphics.ImageFormat and
- * android.graphics.PixelFormat
- */
-enum class PublicFormat {
-    UNKNOWN           = 0x0,
-    RGBA_8888         = 0x1,
-    RGBX_8888         = 0x2,
-    RGB_888           = 0x3,
-    RGB_565           = 0x4,
-    NV16              = 0x10,
-    NV21              = 0x11,
-    YUY2              = 0x14,
-    RGBA_FP16         = 0x16,
-    RAW_SENSOR        = 0x20,
-    PRIVATE           = 0x22,
-    YUV_420_888       = 0x23,
-    RAW_PRIVATE       = 0x24,
-    RAW10             = 0x25,
-    RAW12             = 0x26,
-    RGBA_1010102      = 0x2b,
-    JPEG              = 0x100,
-    DEPTH_POINT_CLOUD = 0x101,
-    RAW_DEPTH         = 0x1002, // @hide
-    YV12              = 0x32315659,
-    Y8                = 0x20203859,
-    Y16               = 0x20363159, // @hide
-    DEPTH16           = 0x44363159,
-    DEPTH_JPEG        = 0x69656963,
-    HEIC              = 0x48454946,
-};
-
 /* Gets the underlying ANativeWindow for a Surface. */
 extern sp<ANativeWindow> android_view_Surface_getNativeWindow(
         JNIEnv* env, jobject surfaceObj);
diff --git a/core/jni/runtime_native_boot-flags-test.sh b/core/jni/runtime_native_boot-flags-test.sh
index 01f37f0..a5d7a5a 100755
--- a/core/jni/runtime_native_boot-flags-test.sh
+++ b/core/jni/runtime_native_boot-flags-test.sh
@@ -172,14 +172,42 @@
   done
 }
 
-# test_android_runtime_flag FLAG VALUE GC_RUNTIME_OPTION
-# ------------------------------------------------------
-# Test device configuration FLAG with VALUE. Check that GC_RUNTIME_OPTION is
-# passed as GC Runtime option by the zygote.
+# check_android_runtime_message CONTEXT MESSAGE
+# ---------------------------------------------
+# Return whether AndroidRuntime generated MESSAGE in logcat. Use CONTEXT in
+# logging.
+function check_android_runtime_message {
+  local context=$1
+  local message=$2
+
+  say "[$context] Check that AndroidRuntime generated expected message in logcat..."
+  adb logcat -d -s AndroidRuntime | grep -F -q "$message" \
+    || fail "Found no message \"$message\" generated by AndroidRuntime"
+}
+
+# check_no_android_runtime_message CONTEXT MESSAGE
+# ------------------------------------------------
+# Return whether AndroidRuntime did not generate MESSAGE in logcat. Use CONTEXT
+# in logging.
+function check_no_android_runtime_message {
+  local context=$1
+  local message=$2
+
+  say "[$context] Check that AndroidRuntime did not generate unexpected message in logcat..."
+  adb logcat -d -s AndroidRuntime | grep -F -q -v "$message" \
+    || fail "Found message \"$message\" generated by AndroidRuntime"
+}
+
+# test_android_runtime_flag FLAG VALUE CHECK_EFFECT CHECK_NO_EFFECT
+# -----------------------------------------------------------------
+# Test device configuration FLAG with VALUE. CHECK_EFFECT and CHECK_NO_EFFECT
+# are functions that are passed a context as sole argument and that respectively
+# check the effect or the absence of effect of the flag.
 function test_android_runtime_flag {
   local flag=$1
   local value=$2
-  local gc_runtime_option=$3
+  local check_effect=$3
+  local check_no_effect=$4
 
   # Persistent system property (set after a reboot) associated with the device
   # configuration flag.
@@ -193,26 +221,26 @@
   sleep 3
 
   # Check that both the device configuration flag and the associated system
-  # property are set, but that the zygote hasn't had the flag passed to it as a
-  # GC runtime option (as we haven't rebooted yet).
+  # property are set, but that flag has not produced an effect on the system (as
+  # we haven't rebooted yet).
   local context="Flag set, before reboot"
   check_device_config_flag "$context" "$flag" "$value"
   check_system_property "$context" "$prop" "$value"
-  check_no_zygote_gc_runtime_option "$context" "$gc_runtime_option"
+  $check_no_effect "$context"
 
   # Reboot device for the flag value to take effect.
   reboot_and_wait_for_device
   context="Flag set, after 1st reboot"
   check_device_config_flag "$context" "$flag" "$value"
   check_system_property "$context" "$prop" "$value"
-  check_zygote_gc_runtime_option "$context" "$gc_runtime_option"
+  $check_effect "$context"
 
   # Reboot device a second time and check that the state has persisted.
   reboot_and_wait_for_device
   context="Flag set, after 2nd reboot"
   check_device_config_flag "$context" "$flag" "$value"
   check_system_property "$context" "$prop" "$value"
-  check_zygote_gc_runtime_option "$context" "$gc_runtime_option"
+  $check_effect "$context"
 
   say "Unsetting device configuration flag..."
   adb shell device_config delete "$namespace" "$flag" >/dev/null
@@ -224,9 +252,13 @@
   context="Flag unset, after 3rd reboot"
   check_no_device_config_flag "$context" "$flag"
   check_no_system_property "$context" "$prop"
-  check_no_zygote_gc_runtime_option "$context" "$gc_runtime_option"
+  $check_no_effect "$context"
 }
 
+
+# Pre-test actions.
+# =================
+
 # Enumerate Zygote processes.
 case $(adb shell getprop ro.zygote) in
   (zygote32) zygotes="zygote";;
@@ -235,8 +267,53 @@
 esac
 
 # Test "enable_generational_cc" flag values.
-test_android_runtime_flag enable_generational_cc false nogenerational_cc
-test_android_runtime_flag enable_generational_cc true generational_cc
+# ==========================================
+
+function check_nogenerational_cc {
+  check_zygote_gc_runtime_option "$1" nogenerational_cc
+}
+function check_no_nogenerational_cc {
+  check_no_zygote_gc_runtime_option "$1" nogenerational_cc
+}
+
+function check_generational_cc {
+  check_zygote_gc_runtime_option "$1" generational_cc
+}
+function check_no_generational_cc {
+  check_no_zygote_gc_runtime_option "$1" generational_cc
+}
+
+test_android_runtime_flag \
+  enable_generational_cc false check_nogenerational_cc check_no_nogenerational_cc
+test_android_runtime_flag \
+  enable_generational_cc true check_generational_cc check_no_generational_cc
+
+# Test "enable_apex_image" flag values.
+# =====================================
+
+default_boot_image_message="Using default boot image"
+function check_default_boot_image {
+  check_android_runtime_message "$1" "$default_boot_image_message"
+}
+function check_no_default_boot_image {
+  check_no_android_runtime_message "$1" "$default_boot_image_message"
+}
+
+apex_boot_image_message="Using Apex boot image: '-Ximage:/system/framework/apex.art'"
+function check_apex_boot_image {
+  check_android_runtime_message "$1" "$apex_boot_image_message"
+}
+function check_no_apex_boot_image {
+  check_no_android_runtime_message "$1" "$apex_boot_image_message"
+}
+
+test_android_runtime_flag \
+  enable_apex_image false check_default_boot_image check_no_default_boot_image
+test_android_runtime_flag \
+  enable_apex_image true check_apex_boot_image check_no_apex_boot_image
+
+# Post-test actions.
+# ==================
 
 if [[ "$exit_status" -eq 0 ]]; then
   banner "All tests passed."
diff --git a/core/proto/android/app/settings_enums.proto b/core/proto/android/app/settings_enums.proto
index f74fc21..efbe8ba 100644
--- a/core/proto/android/app/settings_enums.proto
+++ b/core/proto/android/app/settings_enums.proto
@@ -615,6 +615,40 @@
     // CATEGORY: SETTINGS
     // OS: Q
     ACTION_PANEL_INTERACTION = 1658;
+
+    // ACTION: Show Contextual homepage, log latency in loading cards
+    ACTION_CONTEXTUAL_HOME_SHOW = 1662;
+
+    // ACTION: Contextual card displays
+    ACTION_CONTEXTUAL_CARD_SHOW = 1663;
+
+    // ACTION: Contextual cards are eligible to be shown, but don't rank high
+    ACTION_CONTEXTUAL_CARD_NOT_SHOW = 1664;
+
+    // ACTION: Settings > long press a card, and click dismiss
+    // Contextual card is dismissed
+    ACTION_CONTEXTUAL_CARD_DISMISS = 1665;
+
+    // ACTION: Settings > click a card
+    // Contextual card is clicked
+    ACTION_CONTEXTUAL_CARD_CLICK = 1666;
+
+    // Mapping: go/at-mapping
+    ACTION_ATSG = 1674;
+
+    ACTION_ATPG = 1675;
+
+    ACTION_ATCLPB = 1676;
+
+    ACTION_ATCGIB = 1677;
+
+    ACTION_ATCPAB = 1678;
+
+    ACTION_ATCSAUC = 1679;
+
+    ACTION_ATCSCUC = 1680;
+
+    ACTION_ATCHNUC = 1681;
 }
 
 /**
@@ -2235,4 +2269,19 @@
 
     // Panel for Media Output
     PANEL_MEDIA_OUTPUT = 1657;
+
+    // Mapping: go/at-mapping
+    PAGE_ATSSI = 1667;
+
+    PAGE_ATSII = 1668;
+
+    PAGE_ATUS = 1669;
+
+    PAGE_ATSSP = 1670;
+
+    PAGE_ATSAP = 1671;
+
+    PAGE_ATSCP = 1672;
+
+    PAGE_ATHNP = 1673;
 }
diff --git a/core/proto/android/hardware/biometrics/enums.proto b/core/proto/android/hardware/biometrics/enums.proto
index 973e3e6..f2e0638 100644
--- a/core/proto/android/hardware/biometrics/enums.proto
+++ b/core/proto/android/hardware/biometrics/enums.proto
@@ -55,4 +55,6 @@
     // When the HAL has a template that doesn't exist in Android Framework. The framework
     // is expected to notify the HAL to remove this template to stay in sync with the framework.
     ISSUE_UNKNOWN_TEMPLATE_ENROLLED_HAL = 3;
+    // When the HAL has not sent ERROR_CANCELED within the specified timeout.
+    ISSUE_CANCEL_TIMED_OUT = 4;
 }
\ No newline at end of file
diff --git a/core/proto/android/server/activitymanagerservice.proto b/core/proto/android/server/activitymanagerservice.proto
index 6f9a564..79a5dd7 100644
--- a/core/proto/android/server/activitymanagerservice.proto
+++ b/core/proto/android/server/activitymanagerservice.proto
@@ -132,6 +132,7 @@
 
     optional bool keyguard_showing = 1;
     repeated KeyguardOccludedProto keyguard_occluded_states= 2;
+    optional bool aod_showing = 3;
 }
 
 message KeyguardOccludedProto {
diff --git a/core/proto/android/stats/style/Android.bp b/core/proto/android/stats/style/Android.bp
new file mode 100644
index 0000000..f085a52
--- /dev/null
+++ b/core/proto/android/stats/style/Android.bp
@@ -0,0 +1,27 @@
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_library {
+    name: "styleprotosnano",
+    proto: {
+        type: "nano",
+        output_params: ["store_unknown_fields=true"],
+        include_dirs: ["external/protobuf/src"],
+    },
+
+    sdk_version: "current",
+    srcs: [
+        "*.proto",
+    ],
+}
diff --git a/core/proto/android/stats/style/style_enums.proto b/core/proto/android/stats/style/style_enums.proto
new file mode 100644
index 0000000..b0e4391
--- /dev/null
+++ b/core/proto/android/stats/style/style_enums.proto
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto2";
+package android.stats.style;
+option java_multiple_files = true;
+
+enum Action {
+    DEFAULT_ACTION = 0;
+    ONRESUME = 1;
+    ONSTOP = 2;
+    PICKER_SELECT = 3;
+    PICKER_APPLIED = 4;
+    WALLPAPER_OPEN_CATEGORY = 5;
+    WALLPAPER_SELECT = 6;
+    WALLPAPER_APPLIED = 7;
+    WALLPAPER_EXPLORE = 8;
+    WALLPAPER_DOWNLOAD = 9;
+    WALLPAPER_REMOVE = 10;
+}
+
diff --git a/core/res/res/anim-ldrtl/cross_profile_apps_thumbnail_enter.xml b/core/res/res/anim-ldrtl/cross_profile_apps_thumbnail_enter.xml
index 6f3dc8c..5add19b 100644
--- a/core/res/res/anim-ldrtl/cross_profile_apps_thumbnail_enter.xml
+++ b/core/res/res/anim-ldrtl/cross_profile_apps_thumbnail_enter.xml
@@ -18,7 +18,9 @@
 -->
 <!-- This should be kept in sync with task_open_enter.xml -->
 <set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:shareInterpolator="false" android:zAdjustment="top">
+     android:hasRoundedCorners="true"
+     android:shareInterpolator="false"
+     android:zAdjustment="top">
 
     <alpha
         android:fromAlpha="1"
diff --git a/core/res/res/anim-ldrtl/task_close_enter.xml b/core/res/res/anim-ldrtl/task_close_enter.xml
index 7abada3..e00141a 100644
--- a/core/res/res/anim-ldrtl/task_close_enter.xml
+++ b/core/res/res/anim-ldrtl/task_close_enter.xml
@@ -16,6 +16,7 @@
 <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false"
     android:zAdjustment="top"
+    android:hasRoundedCorners="true"
     android:showWallpaper="true">
 
     <alpha
diff --git a/core/res/res/anim-ldrtl/task_close_exit.xml b/core/res/res/anim-ldrtl/task_close_exit.xml
index a017820..71a44ae 100644
--- a/core/res/res/anim-ldrtl/task_close_exit.xml
+++ b/core/res/res/anim-ldrtl/task_close_exit.xml
@@ -16,6 +16,7 @@
 
 <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false"
+    android:hasRoundedCorners="true"
     android:showWallpaper="true">
 
     <alpha
diff --git a/core/res/res/anim-ldrtl/task_open_enter.xml b/core/res/res/anim-ldrtl/task_open_enter.xml
index 0433664..7815f7d 100644
--- a/core/res/res/anim-ldrtl/task_open_enter.xml
+++ b/core/res/res/anim-ldrtl/task_open_enter.xml
@@ -18,6 +18,7 @@
 <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false"
     android:zAdjustment="top"
+    android:hasRoundedCorners="true"
     android:showWallpaper="true">
 
     <alpha
diff --git a/core/res/res/anim-ldrtl/task_open_enter_cross_profile_apps.xml b/core/res/res/anim-ldrtl/task_open_enter_cross_profile_apps.xml
index 45ca80e..5fccd6df 100644
--- a/core/res/res/anim-ldrtl/task_open_enter_cross_profile_apps.xml
+++ b/core/res/res/anim-ldrtl/task_open_enter_cross_profile_apps.xml
@@ -18,6 +18,7 @@
 <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false"
     android:zAdjustment="top"
+    android:hasRoundedCorners="true"
     android:showWallpaper="true">
 
     <alpha
diff --git a/core/res/res/anim-ldrtl/task_open_exit.xml b/core/res/res/anim-ldrtl/task_open_exit.xml
index f50494d..025e1bd 100644
--- a/core/res/res/anim-ldrtl/task_open_exit.xml
+++ b/core/res/res/anim-ldrtl/task_open_exit.xml
@@ -16,6 +16,7 @@
 
 <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false"
+    android:hasRoundedCorners="true"
     android:showWallpaper="true">
 
     <alpha
diff --git a/core/res/res/anim/cross_profile_apps_thumbnail_enter.xml b/core/res/res/anim/cross_profile_apps_thumbnail_enter.xml
index 4c2559f..2cfeecf 100644
--- a/core/res/res/anim/cross_profile_apps_thumbnail_enter.xml
+++ b/core/res/res/anim/cross_profile_apps_thumbnail_enter.xml
@@ -18,7 +18,9 @@
 -->
 <!-- This should be kept in sync with task_open_enter.xml -->
 <set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:shareInterpolator="false" android:zAdjustment="top">
+     android:shareInterpolator="false"
+     android:hasRoundedCorners="true"
+     android:zAdjustment="top">
 
     <alpha
         android:fromAlpha="1"
diff --git a/core/res/res/anim/task_close_enter.xml b/core/res/res/anim/task_close_enter.xml
index b059aa9..487ff5c 100644
--- a/core/res/res/anim/task_close_enter.xml
+++ b/core/res/res/anim/task_close_enter.xml
@@ -18,6 +18,7 @@
 <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false"
     android:zAdjustment="top"
+    android:hasRoundedCorners="true"
     android:showWallpaper="true">
 
     <alpha
diff --git a/core/res/res/anim/task_close_exit.xml b/core/res/res/anim/task_close_exit.xml
index c9ade22..afc3256c 100644
--- a/core/res/res/anim/task_close_exit.xml
+++ b/core/res/res/anim/task_close_exit.xml
@@ -18,6 +18,7 @@
 
 <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false"
+    android:hasRoundedCorners="true"
     android:showWallpaper="true">
 
     <alpha
diff --git a/core/res/res/anim/task_open_enter.xml b/core/res/res/anim/task_open_enter.xml
index 5c61859..0aafc1c 100644
--- a/core/res/res/anim/task_open_enter.xml
+++ b/core/res/res/anim/task_open_enter.xml
@@ -20,6 +20,7 @@
 <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false"
     android:zAdjustment="top"
+    android:hasRoundedCorners="true"
     android:showWallpaper="true">
 
     <alpha
diff --git a/core/res/res/anim/task_open_enter_cross_profile_apps.xml b/core/res/res/anim/task_open_enter_cross_profile_apps.xml
index 6441047..702f7ba 100644
--- a/core/res/res/anim/task_open_enter_cross_profile_apps.xml
+++ b/core/res/res/anim/task_open_enter_cross_profile_apps.xml
@@ -20,6 +20,7 @@
 <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false"
     android:zAdjustment="top"
+    android:hasRoundedCorners="true"
     android:showWallpaper="true">
 
     <alpha
diff --git a/core/res/res/anim/task_open_exit.xml b/core/res/res/anim/task_open_exit.xml
index 9394c57..691317d 100644
--- a/core/res/res/anim/task_open_exit.xml
+++ b/core/res/res/anim/task_open_exit.xml
@@ -18,6 +18,7 @@
 
 <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false"
+    android:hasRoundedCorners="true"
     android:showWallpaper="true">
 
     <alpha
diff --git a/core/res/res/drawable/ic_action_open.xml b/core/res/res/drawable/ic_action_open.xml
index 3d3d36e..ba0a38d 100644
--- a/core/res/res/drawable/ic_action_open.xml
+++ b/core/res/res/drawable/ic_action_open.xml
@@ -17,8 +17,10 @@
     android:width="24dp"
     android:height="24dp"
     android:viewportWidth="24.0"
-    android:viewportHeight="24.0">
+    android:viewportHeight="24.0"
+    android:tint="?attr/colorControlNormal">
+  >
   <path
-      android:fillColor="#FF737373"
+      android:fillColor="@color/white"
       android:pathData="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"/>
 </vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/ic_qs_battery_saver.xml b/core/res/res/drawable/ic_qs_battery_saver.xml
index 89b2569..93975b6 100644
--- a/core/res/res/drawable/ic_qs_battery_saver.xml
+++ b/core/res/res/drawable/ic_qs_battery_saver.xml
@@ -1,5 +1,5 @@
 <!--
-    Copyright (C) 2018 The Android Open Source Project
+    Copyright (C) 2019 The Android Open Source Project
 
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
@@ -21,8 +21,10 @@
         android:viewportHeight="24.0"
         android:tint="?android:attr/colorControlNormal">
     <path
-            android:pathData="M5,3
-            l3.5,0 l0,-1.5 l7,0 l0,1.5 l3.5,0 l0,19.5 l-14,0z
-            M10.5,8.5 l0,3 l-3,0 l0,3 l3,0 l0,3 l3,0 l0,-3 l3,0 l0,-3 l-3,0 l0,-3 z"
-            android:fillColor="#FFFFFF"/>
+        android:fillColor="#FFF"
+        android:pathData="M16.67,4H14.5V2h-5v2H7.33C6.6,4 6,4.6 6,5.33V15v5.67C6,21.4 6.6,22 7.33,22h9.33C17.4,22 18,21.4 18,20.67V15V5.33C18,4.6 17.4,4 16.67,4zM16,15v5H8v-5V6h8V15z"/>
+    <path
+        android:fillColor="#FFF"
+        android:pathData="M15,12l-2,0l0,-2l-2,0l0,2l-2,0l0,2l2,0l0,2l2,0l0,-2l2,0z"/>
+
 </vector>
diff --git a/core/res/res/values/arrays.xml b/core/res/res/values/arrays.xml
index 733878b..8f2d6c3 100644
--- a/core/res/res/values/arrays.xml
+++ b/core/res/res/values/arrays.xml
@@ -185,4 +185,20 @@
         <item>@string/app_info</item>
     </string-array>
 
+    <!-- Device-specific array of SIM slot indexes which are are embedded eUICCs.
+         e.g. If a device has two physical slots with indexes 0, 1, and slot 1 is an
+         eUICC, then the value of this array should be:
+             <integer-array name="non_removable_euicc_slots">
+                 <item>1</item>
+             </integer-array>
+         If a device has three physical slots and slot 1 and 2 are eUICCs, then the value of
+         this array should be:
+             <integer-array name="non_removable_euicc_slots">
+                <item>1</item>
+                <item>2</item>
+             </integer-array>
+         This is used to differentiate between removable eUICCs and built in eUICCs, and should
+         be set by OEMs for devices which use eUICCs. -->
+    <integer-array name="non_removable_euicc_slots"></integer-array>
+
 </resources>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 088669d..743496f 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -6488,6 +6488,9 @@
         <!-- Special option for window animations: show the wallpaper behind when running this
              animation. -->
         <attr name="showWallpaper" format="boolean" />
+        <!-- Special option for window animations: whether window should have rounded corners.
+             @see ScreenDecorationsUtils#getWindowCornerRadius(Resources) -->
+        <attr name="hasRoundedCorners" format="boolean" />
     </declare-styleable>
 
     <declare-styleable name="AnimationSet">
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index 1053184..6b8e000 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -1667,6 +1667,9 @@
              This flag is turned on by default. <em>This attribute is usable only by system apps.
              </em> -->
         <attr name="allowClearUserDataOnFailedRestore"/>
+        <!-- If {@code true} the app's non sensitive audio can be capture by other apps.
+             The default value is true. -->
+        <attr name="allowAudioPlaybackCapture" format="boolean" />
     </declare-styleable>
     <!-- The <code>permission</code> tag declares a security permission that can be
          used to control access from other packages to specific components or
diff --git a/core/res/res/values/colors_device_defaults.xml b/core/res/res/values/colors_device_defaults.xml
index 824b4b5..7209103 100644
--- a/core/res/res/values/colors_device_defaults.xml
+++ b/core/res/res/values/colors_device_defaults.xml
@@ -26,6 +26,8 @@
     <color name="primary_dark_device_default_settings">@color/primary_dark_material_settings</color>
     <color name="primary_dark_device_default_settings_light">@color/primary_dark_material_settings_light</color>
 
+    <color name="navigation_bar_divider_device_default_settings">#1f000000</color>
+
     <color name="secondary_device_default_settings">@color/secondary_material_settings</color>
     <color name="secondary_device_default_settings_light">@color/secondary_material_settings_light</color>
     <color name="tertiary_device_default_settings">@color/tertiary_material_settings</color>
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index eb69535..4e174c4 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -127,7 +127,7 @@
     <bool name="config_sendAudioBecomingNoisy">true</bool>
 
     <!-- Whether Hearing Aid profile is supported -->
-    <bool name="config_hearing_aid_profile_supported">true</bool>
+    <bool name="config_hearing_aid_profile_supported">false</bool>
 
     <!-- Flag to disable all transition animations -->
     <bool name="config_disableTransitionAnimation">false</bool>
@@ -2008,11 +2008,6 @@
          a transaction, so it interacts poorly with SECURE_DELETE. -->
     <string name="db_default_journal_mode" translatable="false">TRUNCATE</string>
 
-    <!-- Enables compatibility WAL mode.
-         In this mode, only database journal mode will be changed, connection pool
-         size will still be limited to a single connection. -->
-    <bool name="db_compatibility_wal_supported">true</bool>
-
     <!-- Maximum size of the persistent journal file in bytes.
          If the journal file grows to be larger than this amount then SQLite will
          truncate it after committing the transaction. -->
@@ -2272,6 +2267,7 @@
 
     <!-- If the sensor that wakes up the lock screen is available or not. -->
     <bool name="config_dozeWakeLockScreenSensorAvailable">false</bool>
+    <integer name="config_dozeWakeLockScreenDebounce">1500</integer>
 
     <!-- Control whether the always on display mode is available. This should only be enabled on
          devices where the display has been tuned to be power efficient in DOZE and/or DOZE_SUSPEND
@@ -3363,6 +3359,10 @@
     <!-- True if home app should be pinned via Pinner Service -->
     <bool name="config_pinnerHomeApp">false</bool>
 
+    <!-- List of files pinned by the Pinner Service with the apex boot image b/119800099 -->
+    <string-array translatable="false" name="config_apexBootImagePinnerServiceFiles">
+    </string-array>
+
     <!-- Number of days preloaded file cache should be preserved on a device before it can be
          deleted -->
     <integer name="config_keepPreloadsMinDays">7</integer>
@@ -3930,4 +3930,25 @@
          The same restrictions apply to this array. -->
     <array name="config_displayWhiteBalanceDisplayColorTemperatures">
     </array>
+
+    <!-- All of the paths defined for the batterymeter are defined on a 12x20 canvas, and must
+     be parsable by android.utill.PathParser -->
+    <string name="config_batterymeterPerimeterPath" translatable="false">
+		M3.5,2 v0 H1.33 C0.6,2 0,2.6 0,3.33 V13v5.67 C0,19.4 0.6,20 1.33,20 h9.33 C11.4,20 12,19.4 12,18.67 V13V3.33 C12,2.6 11.4,2 10.67,2 H8.5 V0 H3.5 z M2,18v-7V4h8v9v5H2L2,18z
+    </string>
+
+    <string name="config_batterymeterFillMask" translatable="false">
+        M2,18 v-14 h8 v14 z
+    </string>
+    <string name="config_batterymeterBoltPath" translatable="false">
+        M5,17.5 V12 H3 L7,4.5 V10 h2 L5,17.5 z
+    </string>
+    <string name="config_batterymeterPowersavePath" translatable="false">
+		M9,10l-2,0l0,-2l-2,0l0,2l-2,0l0,2l2,0l0,2l2,0l0,-2l2,0z
+    </string>
+
+    <!-- A dual tone battery meter draws the perimeter path twice - once to define the shape
+     and a second time clipped to the fill level to indicate charge -->
+    <bool name="config_batterymeterDualTone">false</bool>
+
 </resources>
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 5a3c536..61d53002 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -2941,6 +2941,7 @@
         <public name="forceUriPermissions" />
         <!-- @hide @SystemApi -->
         <public name="allowClearUserDataOnFailedRestore"/>
+        <public name="allowAudioPlaybackCapture"/>
     </public-group>
 
     <public-group type="drawable" first-id="0x010800b4">
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index dbdc763..4e47b1f 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -779,7 +779,7 @@
         &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to make and manage phone calls?</string>
 
     <!-- Title of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
-    <string name="permgrouplab_sensors">Body Sensors</string>
+    <string name="permgrouplab_sensors">Body sensors</string>
     <!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgroupdesc_sensors">access sensor data about your vital signs</string>
     <!-- Message shown to the user when the apps requests permission from this group. If ever possible this should stay below 80 characters (assuming the parameters takes 20 characters). Don't abbreviate until the message reaches 120 characters though. [CHAR LIMIT=120] -->
@@ -795,12 +795,12 @@
         &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to access your music?</string>
 
     <!-- Title of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
-    <string name="permgrouplab_visual">Photos &amp; Videos</string>
+    <string name="permgrouplab_visual">Photos &amp; videos</string>
     <!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgroupdesc_visual">access your photos &amp; videos</string>
     <!-- Message shown to the user when the apps requests permission from this group. If ever possible this should stay below 80 characters (assuming the parameters takes 20 characters). Don't abbreviate until the message reaches 120 characters though. [CHAR LIMIT=120] -->
     <string name="permgrouprequest_visual">Allow
-        &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to access your photos &amp; videos?</string>
+        &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to access your photos and videos, including tagged locations?</string>
 
     <!-- Title for the capability of an accessibility service to retrieve window content. -->
     <string name="capability_title_canRetrieveWindowContent">Retrieve window content</string>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 8df0e19..426d813 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -752,7 +752,6 @@
   <java-symbol type="string" name="date_time" />
   <java-symbol type="string" name="date_time_set" />
   <java-symbol type="string" name="date_time_done" />
-  <java-symbol type="bool" name="db_compatibility_wal_supported" />
   <java-symbol type="string" name="db_default_journal_mode" />
   <java-symbol type="string" name="db_default_sync_mode" />
   <java-symbol type="string" name="db_wal_sync_mode" />
@@ -2987,6 +2986,8 @@
   <java-symbol type="array" name="resolver_target_actions_pin" />
   <java-symbol type="array" name="resolver_target_actions_unpin" />
 
+  <java-symbol type="array" name="non_removable_euicc_slots" />
+
   <java-symbol type="string" name="install_carrier_app_notification_title" />
   <java-symbol type="string" name="install_carrier_app_notification_text" />
   <java-symbol type="string" name="install_carrier_app_notification_text_app_name" />
@@ -3047,6 +3048,7 @@
   <java-symbol type="array" name="config_defaultPinnerServiceFiles" />
   <java-symbol type="bool" name="config_pinnerCameraApp" />
   <java-symbol type="bool" name="config_pinnerHomeApp" />
+  <java-symbol type="array" name="config_apexBootImagePinnerServiceFiles" />
 
   <java-symbol type="string" name="config_doubleTouchGestureEnableFile" />
 
@@ -3194,6 +3196,11 @@
   <java-symbol type="raw" name="fallback_categories" />
 
   <java-symbol type="string" name="config_icon_mask" />
+  <java-symbol type="string" name="config_batterymeterPerimeterPath" />
+  <java-symbol type="string" name="config_batterymeterFillMask" />
+  <java-symbol type="string" name="config_batterymeterBoltPath" />
+  <java-symbol type="string" name="config_batterymeterPowersavePath" />
+  <java-symbol type="bool" name="config_batterymeterDualTone" />
 
   <!-- Accessibility Shortcut -->
   <java-symbol type="string" name="accessibility_shortcut_warning_dialog_title" />
@@ -3403,6 +3410,7 @@
 
   <java-symbol type="string" name="config_dozeLongPressSensorType" />
   <java-symbol type="bool" name="config_dozeWakeLockScreenSensorAvailable" />
+  <java-symbol type="integer" name="config_dozeWakeLockScreenDebounce" />
 
   <java-symbol type="array" name="config_allowedGlobalInstantAppSettings" />
   <java-symbol type="array" name="config_allowedSystemInstantAppSettings" />
diff --git a/core/res/res/values/themes_device_defaults.xml b/core/res/res/values/themes_device_defaults.xml
index 194c86c..9a95ecc 100644
--- a/core/res/res/values/themes_device_defaults.xml
+++ b/core/res/res/values/themes_device_defaults.xml
@@ -1468,7 +1468,7 @@
         <item name="colorEdgeEffect">@android:color/black</item>
 
         <!-- Add white nav bar with divider that matches material -->
-        <item name="navigationBarDividerColor">#1f000000</item>
+        <item name="navigationBarDividerColor">@color/navigation_bar_divider_device_default_settings</item>
         <item name="navigationBarColor">@android:color/white</item>
         <item name="windowLightNavigationBar">true</item>
 
diff --git a/core/tests/coretests/Android.bp b/core/tests/coretests/Android.bp
new file mode 100644
index 0000000..833c734
--- /dev/null
+++ b/core/tests/coretests/Android.bp
@@ -0,0 +1,113 @@
+android_test {
+    name: "FrameworksCoreTests",
+
+    srcs: [
+        "src/**/*.java",
+        "src/**/I*.aidl",
+        "DisabledTestApp/src/**/*.java",
+        "EnabledTestApp/src/**/*.java",
+        "BinderProxyCountingTestApp/src/**/*.java",
+        "BinderProxyCountingTestService/src/**/*.java",
+        "aidl/**/I*.aidl",
+    ],
+
+    aidl: {
+        local_include_dirs: ["aidl"],
+    },
+
+    dxflags: ["--core-library"],
+
+    aaptflags: [
+        "-0 .dat",
+        "-0 .gld",
+        "-c fa",
+    ],
+    static_libs: [
+        "frameworks-base-testutils",
+        "core-tests-support",
+        "android-common",
+        "frameworks-core-util-lib",
+        "mockwebserver",
+        "guava",
+        "androidx.test.espresso.core",
+        "androidx.test.ext.junit",
+        "androidx.test.runner",
+        "androidx.test.rules",
+        "mockito-target-minus-junit4",
+        "ub-uiautomator",
+        "platform-test-annotations",
+        "truth-prebuilt",
+        "print-test-util-lib",
+        "testng",
+    ],
+
+    libs: [
+        "android.test.runner",
+        "telephony-common",
+        "testables",
+        "org.apache.http.legacy",
+        "android.test.base",
+        "android.test.mock",
+        "framework-atb-backward-compatibility",
+    ],
+
+    platform_apis: true,
+    test_suites: ["device-tests"],
+
+    certificate: "platform",
+
+    resource_dirs: ["res"],
+    resource_zips: [":FrameworksCoreTests_apks_as_resources"],
+}
+
+// Rules to copy all the test apks to the intermediate raw resource directory
+java_genrule {
+    name: "FrameworksCoreTests_apks_as_resources",
+    srcs: [
+        ":FrameworksCoreTests_install",
+        ":FrameworksCoreTests_install_bad_dex",
+        ":FrameworksCoreTests_install_complete_package_info",
+        ":FrameworksCoreTests_install_decl_perm",
+        ":FrameworksCoreTests_install_jni_lib_open_from_apk",
+        ":FrameworksCoreTests_install_loc_auto",
+        ":FrameworksCoreTests_install_loc_internal",
+        ":FrameworksCoreTests_install_loc_sdcard",
+        ":FrameworksCoreTests_install_loc_unspecified",
+        ":FrameworksCoreTests_install_multi_package",
+        ":FrameworksCoreTests_install_split_base",
+        ":FrameworksCoreTests_install_split_feature_a",
+        ":FrameworksCoreTests_install_use_perm_good",
+        ":FrameworksCoreTests_install_uses_feature",
+        ":FrameworksCoreTests_install_verifier_bad",
+        ":FrameworksCoreTests_install_verifier_good",
+        ":FrameworksCoreTests_keyset_permdef_sa_unone",
+        ":FrameworksCoreTests_keyset_permuse_sa_ua_ub",
+        ":FrameworksCoreTests_keyset_permuse_sb_ua_ub",
+        ":FrameworksCoreTests_keyset_sab_ua",
+        ":FrameworksCoreTests_keyset_sa_ua",
+        ":FrameworksCoreTests_keyset_sa_uab",
+        ":FrameworksCoreTests_keyset_sa_ua_ub",
+        ":FrameworksCoreTests_keyset_sa_ub",
+        ":FrameworksCoreTests_keyset_sa_unone",
+        ":FrameworksCoreTests_keyset_sau_ub",
+        ":FrameworksCoreTests_keyset_sb_ua",
+        ":FrameworksCoreTests_keyset_sb_ub",
+        ":FrameworksCoreTests_keyset_splata_api",
+        ":FrameworksCoreTests_keyset_splat_api",
+        ":FrameworksCoreTests_locales",
+        ":FrameworksCoreTests_version_1",
+        ":FrameworksCoreTests_version_1_diff",
+        ":FrameworksCoreTests_version_1_nosys",
+        ":FrameworksCoreTests_version_2",
+        ":FrameworksCoreTests_version_2_diff",
+        ":FrameworksCoreTests_version_3",
+    ],
+    out: ["FrameworkCoreTests_apks_as_resources.res.zip"],
+    tools: ["soong_zip"],
+
+    cmd: "mkdir -p $(genDir)/res/raw && " +
+        "for i in $(in); do " +
+        "  x=$${i##*FrameworksCoreTests_}; echo $${x}; cp $$i $(genDir)/res/raw/$${x%.apk};" +
+        "done && " +
+        "$(location soong_zip) -o $(out) -C $(genDir)/res -D $(genDir)/res",
+}
diff --git a/core/tests/coretests/Android.mk b/core/tests/coretests/Android.mk
deleted file mode 100644
index 40ebd44..0000000
--- a/core/tests/coretests/Android.mk
+++ /dev/null
@@ -1,85 +0,0 @@
-ACTUAL_LOCAL_PATH := $(call my-dir)
-
-# this var will hold all the test apk module names later.
-FrameworkCoreTests_all_apks :=
-
-# We have to include the subdir makefiles first
-# so that FrameworkCoreTests_all_apks will be populated correctly.
-include $(call all-makefiles-under,$(ACTUAL_LOCAL_PATH))
-
-LOCAL_PATH := $(ACTUAL_LOCAL_PATH)
-
-include $(CLEAR_VARS)
-
-# We only want this apk build for tests.
-LOCAL_MODULE_TAGS := tests
-
-# Include all test java files.
-LOCAL_SRC_FILES := \
-	$(call all-java-files-under, src) \
-	$(call all-Iaidl-files-under, src) \
-	$(call all-java-files-under, DisabledTestApp/src) \
-	$(call all-java-files-under, EnabledTestApp/src) \
-	$(call all-java-files-under, BinderProxyCountingTestApp/src) \
-	$(call all-java-files-under, BinderProxyCountingTestService/src) \
-	$(call all-Iaidl-files-under, aidl)
-
-LOCAL_AIDL_INCLUDES := $(LOCAL_PATH)/aidl
-
-LOCAL_DX_FLAGS := --core-library
-LOCAL_JACK_FLAGS := --multi-dex native
-LOCAL_AAPT_FLAGS = -0 dat -0 gld -c fa
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    frameworks-base-testutils \
-    core-tests-support \
-    android-common \
-    frameworks-core-util-lib \
-    mockwebserver \
-    guava \
-    androidx.test.espresso.core \
-    androidx.test.ext.junit \
-    androidx.test.runner \
-    androidx.test.rules \
-    mockito-target-minus-junit4 \
-    ub-uiautomator \
-    platform-test-annotations \
-    truth-prebuilt \
-    print-test-util-lib \
-    testng # TODO: remove once Android migrates to JUnit 4.12, which provide assertThrows
-
-LOCAL_JAVA_LIBRARIES := \
-    android.test.runner \
-    telephony-common \
-    testables \
-    org.apache.http.legacy \
-    android.test.base \
-    android.test.mock \
-    framework-atb-backward-compatibility \
-
-LOCAL_PACKAGE_NAME := FrameworksCoreTests
-LOCAL_PRIVATE_PLATFORM_APIS := true
-LOCAL_COMPATIBILITY_SUITE := device-tests
-
-LOCAL_CERTIFICATE := platform
-
-# intermediate dir to include all the test apks as raw resource
-FrameworkCoreTests_intermediates := $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME))/test_apks/res
-LOCAL_RESOURCE_DIR := $(FrameworkCoreTests_intermediates) $(LOCAL_PATH)/res
-
-# Disable AAPT2 because the hacks below depend on the AAPT rules implementation
-LOCAL_USE_AAPT2 := false
-
-include $(BUILD_PACKAGE)
-# Rules to copy all the test apks to the intermediate raw resource directory
-FrameworkCoreTests_all_apks_res := $(addprefix $(FrameworkCoreTests_intermediates)/raw/, \
-    $(foreach a, $(FrameworkCoreTests_all_apks), $(patsubst FrameworkCoreTests_%,%,$(a))))
-
-$(FrameworkCoreTests_all_apks_res): $(FrameworkCoreTests_intermediates)/raw/%: $(call intermediates-dir-for,APPS,FrameworkCoreTests_%)/package.apk
-	$(call copy-file-to-new-target)
-
-# Use R_file_stamp as dependency because we want the test apks in place before the R.java is generated.
-$(R_file_stamp) : $(FrameworkCoreTests_all_apks_res)
-
-FrameworkCoreTests_all_apks :=
-FrameworkCoreTests_intermediates :=
-FrameworkCoreTests_all_apks_res :=
diff --git a/core/tests/coretests/BinderProxyCountingTestApp/Android.bp b/core/tests/coretests/BinderProxyCountingTestApp/Android.bp
new file mode 100644
index 0000000..6279a48
--- /dev/null
+++ b/core/tests/coretests/BinderProxyCountingTestApp/Android.bp
@@ -0,0 +1,25 @@
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+android_test_helper_app {
+    name: "BinderProxyCountingTestApp",
+
+    static_libs: ["coretests-aidl"],
+    srcs: ["**/*.java"],
+
+    sdk_version: "current",
+    certificate: "platform",
+
+    test_suites: ["device-tests"],
+}
diff --git a/core/tests/coretests/BinderProxyCountingTestApp/Android.mk b/core/tests/coretests/BinderProxyCountingTestApp/Android.mk
deleted file mode 100644
index 4642694..0000000
--- a/core/tests/coretests/BinderProxyCountingTestApp/Android.mk
+++ /dev/null
@@ -1,29 +0,0 @@
-# Copyright (C) 2017 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_STATIC_JAVA_LIBRARIES := coretests-aidl
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := BinderProxyCountingTestApp
-LOCAL_SDK_VERSION := current
-LOCAL_CERTIFICATE := platform
-
-LOCAL_COMPATIBILITY_SUITE := device-tests
-include $(BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/BinderProxyCountingTestService/Android.bp b/core/tests/coretests/BinderProxyCountingTestService/Android.bp
new file mode 100644
index 0000000..22718cb
--- /dev/null
+++ b/core/tests/coretests/BinderProxyCountingTestService/Android.bp
@@ -0,0 +1,25 @@
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+android_test_helper_app {
+    name: "BinderProxyCountingTestService",
+
+    static_libs: ["coretests-aidl"],
+    srcs: ["**/*.java"],
+
+    platform_apis: true,
+    certificate: "platform",
+
+    test_suites: ["device-tests"],
+}
diff --git a/core/tests/coretests/BinderProxyCountingTestService/Android.mk b/core/tests/coretests/BinderProxyCountingTestService/Android.mk
deleted file mode 100644
index f852c7a..0000000
--- a/core/tests/coretests/BinderProxyCountingTestService/Android.mk
+++ /dev/null
@@ -1,29 +0,0 @@
-# Copyright (C) 2017 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_STATIC_JAVA_LIBRARIES := coretests-aidl
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := BinderProxyCountingTestService
-LOCAL_PRIVATE_PLATFORM_APIS := true
-LOCAL_CERTIFICATE := platform
-
-LOCAL_COMPATIBILITY_SUITE := device-tests
-include $(BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/BstatsTestApp/Android.bp b/core/tests/coretests/BstatsTestApp/Android.bp
new file mode 100644
index 0000000..424c71a
--- /dev/null
+++ b/core/tests/coretests/BstatsTestApp/Android.bp
@@ -0,0 +1,34 @@
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+android_test_helper_app {
+    name: "BstatsTestApp",
+
+    test_suites: [
+        "device-tests",
+    ],
+
+    static_libs: ["coretests-aidl"],
+
+    srcs: ["**/*.java"],
+
+    sdk_version: "current",
+    certificate: "platform",
+    dex_preopt: {
+        enabled: false,
+    },
+    optimize: {
+        enabled: false,
+    },
+}
diff --git a/core/tests/coretests/BstatsTestApp/Android.mk b/core/tests/coretests/BstatsTestApp/Android.mk
deleted file mode 100644
index a5872a5..0000000
--- a/core/tests/coretests/BstatsTestApp/Android.mk
+++ /dev/null
@@ -1,34 +0,0 @@
-# Copyright (C) 2017 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_COMPATIBILITY_SUITE := device-tests
-
-LOCAL_STATIC_JAVA_LIBRARIES := coretests-aidl
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := BstatsTestApp
-LOCAL_SDK_VERSION := current
-LOCAL_CERTIFICATE := platform
-LOCAL_DEX_PREOPT := false
-LOCAL_PROGUARD_ENABLED := disabled
-
-LOCAL_COMPATIBILITY_SUITE := device-tests
-include $(BUILD_PACKAGE)
diff --git a/core/tests/coretests/DisabledTestApp/Android.bp b/core/tests/coretests/DisabledTestApp/Android.bp
new file mode 100644
index 0000000..419816e
--- /dev/null
+++ b/core/tests/coretests/DisabledTestApp/Android.bp
@@ -0,0 +1,8 @@
+android_test_helper_app {
+    name: "DisabledTestApp",
+
+    srcs: ["**/*.java"],
+
+    sdk_version: "current",
+    certificate: "platform",
+}
diff --git a/core/tests/coretests/DisabledTestApp/Android.mk b/core/tests/coretests/DisabledTestApp/Android.mk
deleted file mode 100644
index e4304f7..0000000
--- a/core/tests/coretests/DisabledTestApp/Android.mk
+++ /dev/null
@@ -1,13 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := DisabledTestApp
-LOCAL_SDK_VERSION := current
-LOCAL_CERTIFICATE := platform
-
-include $(BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/EnabledTestApp/Android.bp b/core/tests/coretests/EnabledTestApp/Android.bp
new file mode 100644
index 0000000..bc4f4bd
--- /dev/null
+++ b/core/tests/coretests/EnabledTestApp/Android.bp
@@ -0,0 +1,8 @@
+android_test_helper_app {
+    name: "EnabledTestApp",
+
+    srcs: ["**/*.java"],
+
+    sdk_version: "current",
+    certificate: "platform",
+}
diff --git a/core/tests/coretests/EnabledTestApp/Android.mk b/core/tests/coretests/EnabledTestApp/Android.mk
deleted file mode 100644
index cd37f08..0000000
--- a/core/tests/coretests/EnabledTestApp/Android.mk
+++ /dev/null
@@ -1,13 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := EnabledTestApp
-LOCAL_SDK_VERSION := current
-LOCAL_CERTIFICATE := platform
-
-include $(BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/aidl/Android.bp b/core/tests/coretests/aidl/Android.bp
new file mode 100644
index 0000000..6e442db
--- /dev/null
+++ b/core/tests/coretests/aidl/Android.bp
@@ -0,0 +1,19 @@
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_test {
+    name: "coretests-aidl",
+    sdk_version: "current",
+    srcs: ["**/*.aidl"],
+}
diff --git a/core/tests/coretests/aidl/Android.mk b/core/tests/coretests/aidl/Android.mk
deleted file mode 100644
index 86e36b6..0000000
--- a/core/tests/coretests/aidl/Android.mk
+++ /dev/null
@@ -1,22 +0,0 @@
-# Copyright (C) 2017 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE_TAGS := tests
-LOCAL_SDK_VERSION := current
-LOCAL_SRC_FILES := $(call all-subdir-Iaidl-files)
-LOCAL_MODULE := coretests-aidl
-include $(BUILD_STATIC_JAVA_LIBRARY)
\ No newline at end of file
diff --git a/core/tests/coretests/apks/Android.bp b/core/tests/coretests/apks/Android.bp
new file mode 100644
index 0000000..20c87b2
--- /dev/null
+++ b/core/tests/coretests/apks/Android.bp
@@ -0,0 +1,7 @@
+java_defaults {
+    name: "FrameworksCoreTests_apks_defaults",
+    sdk_version: "current",
+
+    // Every package should have a native library
+    jni_libs: ["libframeworks_coretests_jni"],
+}
diff --git a/core/tests/coretests/apks/Android.mk b/core/tests/coretests/apks/Android.mk
deleted file mode 100644
index 98c0c2a..0000000
--- a/core/tests/coretests/apks/Android.mk
+++ /dev/null
@@ -1,7 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-FrameworkCoreTests_BUILD_PACKAGE := $(LOCAL_PATH)/FrameworkCoreTests_apk.mk
-
-# build sub packages
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/core/tests/coretests/apks/FrameworkCoreTests_apk.mk b/core/tests/coretests/apks/FrameworkCoreTests_apk.mk
deleted file mode 100644
index 8a7d72a5..0000000
--- a/core/tests/coretests/apks/FrameworkCoreTests_apk.mk
+++ /dev/null
@@ -1,16 +0,0 @@
-
-LOCAL_MODULE_TAGS := tests
-
-# Disable dexpreopt.
-LOCAL_DEX_PREOPT := false
-
-# Make sure every package name gets the FrameworkCoreTests_ prefix.
-LOCAL_PACKAGE_NAME := FrameworkCoreTests_$(LOCAL_PACKAGE_NAME)
-LOCAL_SDK_VERSION := current
-
-# Every package should have a native library
-LOCAL_JNI_SHARED_LIBRARIES := libframeworks_coretests_jni
-
-FrameworkCoreTests_all_apks += $(LOCAL_PACKAGE_NAME)
-
-include $(BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install-split-base/Android.bp b/core/tests/coretests/apks/install-split-base/Android.bp
new file mode 100644
index 0000000..ddf75b2
--- /dev/null
+++ b/core/tests/coretests/apks/install-split-base/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_split_base",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install-split-base/Android.mk b/core/tests/coretests/apks/install-split-base/Android.mk
deleted file mode 100644
index 5b60e31..0000000
--- a/core/tests/coretests/apks/install-split-base/Android.mk
+++ /dev/null
@@ -1,10 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_split_base
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
\ No newline at end of file
diff --git a/core/tests/coretests/apks/install-split-feature-a/Android.bp b/core/tests/coretests/apks/install-split-feature-a/Android.bp
new file mode 100644
index 0000000..9ec9893
--- /dev/null
+++ b/core/tests/coretests/apks/install-split-feature-a/Android.bp
@@ -0,0 +1,11 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_split_feature_a",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+
+    aaptflags: [
+        "--custom-package com.google.android.dexapis.splitapp.feature_a",
+        "--package-id 0x80",
+    ],
+}
diff --git a/core/tests/coretests/apks/install-split-feature-a/Android.mk b/core/tests/coretests/apks/install-split-feature-a/Android.mk
deleted file mode 100644
index 0f37d16..0000000
--- a/core/tests/coretests/apks/install-split-feature-a/Android.mk
+++ /dev/null
@@ -1,14 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_split_feature_a
-
-LOCAL_USE_AAPT2 := true
-LOCAL_AAPT_FLAGS += --custom-package com.google.android.dexapis.splitapp.feature_a
-LOCAL_AAPT_FLAGS += --package-id 0x80
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
\ No newline at end of file
diff --git a/core/tests/coretests/apks/install/Android.bp b/core/tests/coretests/apks/install/Android.bp
new file mode 100644
index 0000000..e783fe2
--- /dev/null
+++ b/core/tests/coretests/apks/install/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install/Android.mk b/core/tests/coretests/apks/install/Android.mk
deleted file mode 100644
index b38dc20..0000000
--- a/core/tests/coretests/apks/install/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_bad_dex/Android.bp b/core/tests/coretests/apks/install_bad_dex/Android.bp
new file mode 100644
index 0000000..d156793
--- /dev/null
+++ b/core/tests/coretests/apks/install_bad_dex/Android.bp
@@ -0,0 +1,23 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_bad_dex_",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["src/**/*.java"],
+}
+
+// Inject bad classes.dex file.
+java_genrule {
+    name: "FrameworksCoreTests_install_bad_dex",
+    tools: [
+        "soong_zip",
+        "merge_zips",
+    ],
+    srcs: [
+        ":FrameworksCoreTests_install_bad_dex_",
+        "classes.dex",
+    ],
+    out: ["FrameworksCoreTests_install_bad_dex.apk"],
+    cmd: "$(location soong_zip) -o $(genDir)/classes.dex.zip -j -f $(location classes.dex) && " +
+        "$(location merge_zips) -ignore-duplicates $(out) $(genDir)/classes.dex.zip " +
+        "$(location :FrameworksCoreTests_install_bad_dex_)",
+}
diff --git a/core/tests/coretests/apks/install_bad_dex/Android.mk b/core/tests/coretests/apks/install_bad_dex/Android.mk
deleted file mode 100644
index 05983aa..0000000
--- a/core/tests/coretests/apks/install_bad_dex/Android.mk
+++ /dev/null
@@ -1,11 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_bad_dex
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-# Override target specific variable PRIVATE_DEX_FILE to inject bad classes.dex file.
-$(LOCAL_BUILT_MODULE): PRIVATE_DEX_FILE := $(LOCAL_PATH)/classes.dex
diff --git a/core/tests/coretests/apks/install_complete_package_info/Android.bp b/core/tests/coretests/apks/install_complete_package_info/Android.bp
new file mode 100644
index 0000000..123558bd
--- /dev/null
+++ b/core/tests/coretests/apks/install_complete_package_info/Android.bp
@@ -0,0 +1,7 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_complete_package_info",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
+
diff --git a/core/tests/coretests/apks/install_complete_package_info/Android.mk b/core/tests/coretests/apks/install_complete_package_info/Android.mk
deleted file mode 100644
index 19bf356..0000000
--- a/core/tests/coretests/apks/install_complete_package_info/Android.mk
+++ /dev/null
@@ -1,13 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_complete_package_info
-#LOCAL_MANIFEST_FILE := api_test/AndroidManifest.xml
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-#include $(BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/apks/install_decl_perm/Android.bp b/core/tests/coretests/apks/install_decl_perm/Android.bp
new file mode 100644
index 0000000..868e8b5
--- /dev/null
+++ b/core/tests/coretests/apks/install_decl_perm/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_decl_perm",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_decl_perm/Android.mk b/core/tests/coretests/apks/install_decl_perm/Android.mk
deleted file mode 100644
index 86370c8..0000000
--- a/core/tests/coretests/apks/install_decl_perm/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_decl_perm
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_jni_lib/Android.bp b/core/tests/coretests/apks/install_jni_lib/Android.bp
index c1a6bd0..f20f599 100644
--- a/core/tests/coretests/apks/install_jni_lib/Android.bp
+++ b/core/tests/coretests/apks/install_jni_lib/Android.bp
@@ -14,6 +14,7 @@
 
 cc_test_library {
     name: "libframeworks_coretests_jni",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
 
     srcs: ["com_android_frameworks_coretests_JNITest.cpp"],
 
diff --git a/core/tests/coretests/apks/install_jni_lib_open_from_apk/Android.bp b/core/tests/coretests/apks/install_jni_lib_open_from_apk/Android.bp
new file mode 100644
index 0000000..602b704
--- /dev/null
+++ b/core/tests/coretests/apks/install_jni_lib_open_from_apk/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_jni_lib_open_from_apk",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_jni_lib_open_from_apk/Android.mk b/core/tests/coretests/apks/install_jni_lib_open_from_apk/Android.mk
deleted file mode 100644
index 6b3b55e..0000000
--- a/core/tests/coretests/apks/install_jni_lib_open_from_apk/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_jni_lib_open_from_apk
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_loc_auto/Android.bp b/core/tests/coretests/apks/install_loc_auto/Android.bp
new file mode 100644
index 0000000..6393915
--- /dev/null
+++ b/core/tests/coretests/apks/install_loc_auto/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_loc_auto",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_loc_auto/Android.mk b/core/tests/coretests/apks/install_loc_auto/Android.mk
deleted file mode 100644
index 6435f36..0000000
--- a/core/tests/coretests/apks/install_loc_auto/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_loc_auto
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_loc_internal/Android.bp b/core/tests/coretests/apks/install_loc_internal/Android.bp
new file mode 100644
index 0000000..770aaa5
--- /dev/null
+++ b/core/tests/coretests/apks/install_loc_internal/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_loc_internal",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_loc_internal/Android.mk b/core/tests/coretests/apks/install_loc_internal/Android.mk
deleted file mode 100644
index 8cc8b8e..0000000
--- a/core/tests/coretests/apks/install_loc_internal/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_loc_internal
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_loc_sdcard/Android.bp b/core/tests/coretests/apks/install_loc_sdcard/Android.bp
new file mode 100644
index 0000000..1779401
--- /dev/null
+++ b/core/tests/coretests/apks/install_loc_sdcard/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_loc_sdcard",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_loc_sdcard/Android.mk b/core/tests/coretests/apks/install_loc_sdcard/Android.mk
deleted file mode 100644
index e1411c2..0000000
--- a/core/tests/coretests/apks/install_loc_sdcard/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_loc_sdcard
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_loc_unspecified/Android.bp b/core/tests/coretests/apks/install_loc_unspecified/Android.bp
new file mode 100644
index 0000000..21c0f82
--- /dev/null
+++ b/core/tests/coretests/apks/install_loc_unspecified/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_loc_unspecified",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_loc_unspecified/Android.mk b/core/tests/coretests/apks/install_loc_unspecified/Android.mk
deleted file mode 100644
index 0741d04..0000000
--- a/core/tests/coretests/apks/install_loc_unspecified/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_loc_unspecified
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_multi_package/Android.bp b/core/tests/coretests/apks/install_multi_package/Android.bp
new file mode 100644
index 0000000..249242e
--- /dev/null
+++ b/core/tests/coretests/apks/install_multi_package/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_multi_package",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_multi_package/Android.mk b/core/tests/coretests/apks/install_multi_package/Android.mk
deleted file mode 100644
index 3f163de..0000000
--- a/core/tests/coretests/apks/install_multi_package/Android.mk
+++ /dev/null
@@ -1,14 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_multi_package
-
-LOCAL_USE_AAPT2 := true
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-#include $(BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/apks/install_use_perm_good/Android.bp b/core/tests/coretests/apks/install_use_perm_good/Android.bp
new file mode 100644
index 0000000..bb41ebb
--- /dev/null
+++ b/core/tests/coretests/apks/install_use_perm_good/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_use_perm_good",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_use_perm_good/Android.mk b/core/tests/coretests/apks/install_use_perm_good/Android.mk
deleted file mode 100644
index e2661a1..0000000
--- a/core/tests/coretests/apks/install_use_perm_good/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_use_perm_good
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_uses_feature/Android.bp b/core/tests/coretests/apks/install_uses_feature/Android.bp
new file mode 100644
index 0000000..0ec747b
--- /dev/null
+++ b/core/tests/coretests/apks/install_uses_feature/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_uses_feature",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_uses_feature/Android.mk b/core/tests/coretests/apks/install_uses_feature/Android.mk
deleted file mode 100644
index b60d734..0000000
--- a/core/tests/coretests/apks/install_uses_feature/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_uses_feature
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_verifier_bad/Android.bp b/core/tests/coretests/apks/install_verifier_bad/Android.bp
new file mode 100644
index 0000000..1265739
--- /dev/null
+++ b/core/tests/coretests/apks/install_verifier_bad/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_verifier_bad",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_verifier_bad/Android.mk b/core/tests/coretests/apks/install_verifier_bad/Android.mk
deleted file mode 100644
index 745b4d3..0000000
--- a/core/tests/coretests/apks/install_verifier_bad/Android.mk
+++ /dev/null
@@ -1,10 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_verifier_bad
-
-LOCAL_USE_AAPT2 := true
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_verifier_good/Android.bp b/core/tests/coretests/apks/install_verifier_good/Android.bp
new file mode 100644
index 0000000..4911ffb
--- /dev/null
+++ b/core/tests/coretests/apks/install_verifier_good/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_verifier_good",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_verifier_good/Android.mk b/core/tests/coretests/apks/install_verifier_good/Android.mk
deleted file mode 100644
index 150fd8d..0000000
--- a/core/tests/coretests/apks/install_verifier_good/Android.mk
+++ /dev/null
@@ -1,10 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_verifier_good
-
-LOCAL_USE_AAPT2 := true
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/keyset/Android.bp b/core/tests/coretests/apks/keyset/Android.bp
new file mode 100644
index 0000000..e252b08
--- /dev/null
+++ b/core/tests/coretests/apks/keyset/Android.bp
@@ -0,0 +1,120 @@
+//apks signed by keyset_A
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sa_unone",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "uNone/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sa_ua",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "uA/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sa_ub",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "uB/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sa_uab",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "uAB/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sa_ua_ub",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "uAuB/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_permdef_sa_unone",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "permDef/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_permuse_sa_ua_ub",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "permUse/AndroidManifest.xml",
+}
+
+//apks signed by keyset_B
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sb_ua",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_B_cert",
+    manifest: "uA/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sb_ub",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_B_cert",
+    manifest: "uB/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_permuse_sb_ua_ub",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_B_cert",
+    manifest: "permUse/AndroidManifest.xml",
+}
+
+//apks signed by keyset_A and keyset_B
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sab_ua",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    additional_certificates: [":FrameworksCoreTests_keyset_B_cert"],
+    manifest: "uA/AndroidManifest.xml",
+}
+
+//apks signed by keyset_A and unit_test
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sau_ub",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    additional_certificates: [":FrameworksCoreTests_keyset_B_cert"],
+    manifest: "uB/AndroidManifest.xml",
+}
+
+//apks signed by platform only
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_splat_api",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: "platform",
+    manifest: "api_test/AndroidManifest.xml",
+}
+
+//apks signed by platform and keyset_A
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_splata_api",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: "platform",
+    additional_certificates: [":FrameworksCoreTests_keyset_A_cert"],
+    manifest: "api_test/AndroidManifest.xml",
+}
diff --git a/core/tests/coretests/apks/keyset/Android.mk b/core/tests/coretests/apks/keyset/Android.mk
deleted file mode 100644
index 306dc90..0000000
--- a/core/tests/coretests/apks/keyset/Android.mk
+++ /dev/null
@@ -1,108 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-#apks signed by keyset_A
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sa_unone
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := uNone/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sa_ua
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := uA/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sa_ub
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := uB/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sa_uab
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := uAB/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sa_ua_ub
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := uAuB/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_permdef_sa_unone
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := permDef/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_permuse_sa_ua_ub
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := permUse/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-#apks signed by keyset_B
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sb_ua
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_B
-LOCAL_MANIFEST_FILE := uA/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sb_ub
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_B
-LOCAL_MANIFEST_FILE := uB/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_permuse_sb_ua_ub
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_B
-LOCAL_MANIFEST_FILE := permUse/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-#apks signed by keyset_A and keyset_B
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sab_ua
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_ADDITIONAL_CERTIFICATES := $(LOCAL_PATH)/../../certs/keyset_B
-LOCAL_MANIFEST_FILE := uA/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-#apks signed by keyset_A and unit_test
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sau_ub
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_ADDITIONAL_CERTIFICATES := $(LOCAL_PATH)/../../certs/keyset_B
-LOCAL_MANIFEST_FILE := uB/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-#apks signed by platform only
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_splat_api
-LOCAL_CERTIFICATE := platform
-LOCAL_MANIFEST_FILE := api_test/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-#apks signed by platform and keyset_A
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_splata_api
-LOCAL_CERTIFICATE := platform
-LOCAL_ADDITIONAL_CERTIFICATES := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := api_test/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
\ No newline at end of file
diff --git a/core/tests/coretests/apks/locales/Android.bp b/core/tests/coretests/apks/locales/Android.bp
new file mode 100644
index 0000000..4a730ef
--- /dev/null
+++ b/core/tests/coretests/apks/locales/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_locales",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/locales/Android.mk b/core/tests/coretests/apks/locales/Android.mk
deleted file mode 100644
index 9cb13dd..0000000
--- a/core/tests/coretests/apks/locales/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := locales
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/version/Android.bp b/core/tests/coretests/apks/version/Android.bp
new file mode 100644
index 0000000..371ccfc
--- /dev/null
+++ b/core/tests/coretests/apks/version/Android.bp
@@ -0,0 +1,54 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_version_1",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    aaptflags: [
+        "--version-code 1",
+        "--version-name 1.0",
+    ],
+    certificate: ":FrameworksCoreTests_unit_test_cert",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_version_2",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    aaptflags: [
+        "--version-code 2",
+        "--version-name 2.0",
+    ],
+    certificate: ":FrameworksCoreTests_unit_test_cert",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_version_3",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    aaptflags: [
+        "--version-code 3",
+        "--version-name 3.0",
+    ],
+    certificate: ":FrameworksCoreTests_unit_test_cert",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_version_1_diff",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    aaptflags: [
+        "--version-code 1",
+        "--version-name 1.0",
+    ],
+    certificate: ":FrameworksCoreTests_unit_test_cert",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_version_2_diff",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    aaptflags: [
+        "--version-code 2",
+        "--version-name 2.0",
+    ],
+    certificate: ":FrameworksCoreTests_unit_test_cert",
+}
diff --git a/core/tests/coretests/apks/version/Android.mk b/core/tests/coretests/apks/version/Android.mk
deleted file mode 100644
index 3635a58..0000000
--- a/core/tests/coretests/apks/version/Android.mk
+++ /dev/null
@@ -1,36 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := version_1
-LOCAL_AAPT_FLAGS := --version-code 1 --version-name 1.0
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/unit_test
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := version_2
-LOCAL_AAPT_FLAGS := --version-code 2 --version-name 2.0
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/unit_test
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := version_3
-LOCAL_AAPT_FLAGS := --version-code 3 --version-name 3.0
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/unit_test
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := version_1_diff
-LOCAL_AAPT_FLAGS := --version-code 1 --version-name 1.0
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/unit_test_diff
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := version_2_diff
-LOCAL_AAPT_FLAGS := --version-code 2 --version-name 2.0
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/unit_test_diff
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/version_nosys/Android.bp b/core/tests/coretests/apks/version_nosys/Android.bp
new file mode 100644
index 0000000..5756678
--- /dev/null
+++ b/core/tests/coretests/apks/version_nosys/Android.bp
@@ -0,0 +1,10 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_version_1_nosys",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    aaptflags: [
+        "--version-code 1",
+        "--version-name 1.0",
+    ],
+    certificate: ":FrameworksCoreTests_unit_test_cert",
+}
diff --git a/core/tests/coretests/apks/version_nosys/Android.mk b/core/tests/coretests/apks/version_nosys/Android.mk
deleted file mode 100644
index bbc8e12..0000000
--- a/core/tests/coretests/apks/version_nosys/Android.mk
+++ /dev/null
@@ -1,9 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := version_1_nosys
-LOCAL_AAPT_FLAGS := --version-code 1 --version-name 1.0
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/unit_test
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/certs/Android.bp b/core/tests/coretests/certs/Android.bp
new file mode 100644
index 0000000..bd5c829
--- /dev/null
+++ b/core/tests/coretests/certs/Android.bp
@@ -0,0 +1,14 @@
+android_app_certificate {
+    name: "FrameworksCoreTests_keyset_A_cert",
+    certificate: "keyset_A",
+}
+
+android_app_certificate {
+    name: "FrameworksCoreTests_keyset_B_cert",
+    certificate: "keyset_B",
+}
+
+android_app_certificate {
+    name: "FrameworksCoreTests_unit_test_cert",
+    certificate: "unit_test",
+}
diff --git a/core/tests/coretests/src/android/app/admin/PasswordMetricsTest.java b/core/tests/coretests/src/android/app/admin/PasswordMetricsTest.java
index 5731daa..4ae9494 100644
--- a/core/tests/coretests/src/android/app/admin/PasswordMetricsTest.java
+++ b/core/tests/coretests/src/android/app/admin/PasswordMetricsTest.java
@@ -99,7 +99,8 @@
 
     @Test
     public void testComputeForPassword_metrics() {
-        final PasswordMetrics metrics = PasswordMetrics.computeForPassword("6B~0z1Z3*8A");
+        final PasswordMetrics metrics =
+                PasswordMetrics.computeForPassword("6B~0z1Z3*8A".getBytes());
         assertEquals(11, metrics.length);
         assertEquals(4, metrics.letters);
         assertEquals(3, metrics.upperCase);
@@ -112,32 +113,32 @@
     @Test
     public void testComputeForPassword_quality() {
         assertEquals(DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC,
-                PasswordMetrics.computeForPassword("a1").quality);
+                PasswordMetrics.computeForPassword("a1".getBytes()).quality);
         assertEquals(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC,
-                PasswordMetrics.computeForPassword("a").quality);
+                PasswordMetrics.computeForPassword("a".getBytes()).quality);
         assertEquals(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC,
-                PasswordMetrics.computeForPassword("*~&%$").quality);
+                PasswordMetrics.computeForPassword("*~&%$".getBytes()).quality);
         assertEquals(DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX,
-                PasswordMetrics.computeForPassword("1").quality);
+                PasswordMetrics.computeForPassword("1".getBytes()).quality);
         // contains a long sequence so isn't complex
         assertEquals(PASSWORD_QUALITY_NUMERIC,
-                PasswordMetrics.computeForPassword("1234").quality);
+                PasswordMetrics.computeForPassword("1234".getBytes()).quality);
         assertEquals(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
-                PasswordMetrics.computeForPassword("").quality);
+                PasswordMetrics.computeForPassword("".getBytes()).quality);
     }
 
     @Test
     public void testMaxLengthSequence() {
-        assertEquals(4, PasswordMetrics.maxLengthSequence("1234"));
-        assertEquals(5, PasswordMetrics.maxLengthSequence("13579"));
-        assertEquals(4, PasswordMetrics.maxLengthSequence("1234abd"));
-        assertEquals(3, PasswordMetrics.maxLengthSequence("aabc"));
-        assertEquals(1, PasswordMetrics.maxLengthSequence("qwertyuio"));
-        assertEquals(3, PasswordMetrics.maxLengthSequence("@ABC"));
+        assertEquals(4, PasswordMetrics.maxLengthSequence("1234".getBytes()));
+        assertEquals(5, PasswordMetrics.maxLengthSequence("13579".getBytes()));
+        assertEquals(4, PasswordMetrics.maxLengthSequence("1234abd".getBytes()));
+        assertEquals(3, PasswordMetrics.maxLengthSequence("aabc".getBytes()));
+        assertEquals(1, PasswordMetrics.maxLengthSequence("qwertyuio".getBytes()));
+        assertEquals(3, PasswordMetrics.maxLengthSequence("@ABC".getBytes()));
         // anything that repeats
-        assertEquals(4, PasswordMetrics.maxLengthSequence(";;;;"));
+        assertEquals(4, PasswordMetrics.maxLengthSequence(";;;;".getBytes()));
         // ordered, but not composed of alphas or digits
-        assertEquals(1, PasswordMetrics.maxLengthSequence(":;<=>"));
+        assertEquals(1, PasswordMetrics.maxLengthSequence(":;<=>".getBytes()));
     }
 
     @Test
@@ -158,8 +159,8 @@
         assertNotEquals(new PasswordMetrics(DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, 4),
                 new PasswordMetrics(PASSWORD_QUALITY_COMPLEX, 4));
 
-        metrics0 = PasswordMetrics.computeForPassword("1234abcd,./");
-        metrics1 = PasswordMetrics.computeForPassword("1234abcd,./");
+        metrics0 = PasswordMetrics.computeForPassword("1234abcd,./".getBytes());
+        metrics1 = PasswordMetrics.computeForPassword("1234abcd,./".getBytes());
         assertEquals(metrics0, metrics1);
         metrics1.letters++;
         assertNotEquals(metrics0, metrics1);
@@ -197,7 +198,7 @@
     @Test
     public void testDetermineComplexity_none() {
         assertEquals(PASSWORD_COMPLEXITY_NONE,
-                PasswordMetrics.computeForPassword("").determineComplexity());
+                PasswordMetrics.computeForPassword("".getBytes()).determineComplexity());
     }
 
     @Test
@@ -209,61 +210,61 @@
     @Test
     public void testDetermineComplexity_lowNumeric() {
         assertEquals(PASSWORD_COMPLEXITY_LOW,
-                PasswordMetrics.computeForPassword("1234").determineComplexity());
+                PasswordMetrics.computeForPassword("1234".getBytes()).determineComplexity());
     }
 
     @Test
     public void testDetermineComplexity_lowNumericComplex() {
         assertEquals(PASSWORD_COMPLEXITY_LOW,
-                PasswordMetrics.computeForPassword("124").determineComplexity());
+                PasswordMetrics.computeForPassword("124".getBytes()).determineComplexity());
     }
 
     @Test
     public void testDetermineComplexity_lowAlphabetic() {
         assertEquals(PASSWORD_COMPLEXITY_LOW,
-                PasswordMetrics.computeForPassword("a!").determineComplexity());
+                PasswordMetrics.computeForPassword("a!".getBytes()).determineComplexity());
     }
 
     @Test
     public void testDetermineComplexity_lowAlphanumeric() {
         assertEquals(PASSWORD_COMPLEXITY_LOW,
-                PasswordMetrics.computeForPassword("a!1").determineComplexity());
+                PasswordMetrics.computeForPassword("a!1".getBytes()).determineComplexity());
     }
 
     @Test
     public void testDetermineComplexity_mediumNumericComplex() {
         assertEquals(PASSWORD_COMPLEXITY_MEDIUM,
-                PasswordMetrics.computeForPassword("1238").determineComplexity());
+                PasswordMetrics.computeForPassword("1238".getBytes()).determineComplexity());
     }
 
     @Test
     public void testDetermineComplexity_mediumAlphabetic() {
         assertEquals(PASSWORD_COMPLEXITY_MEDIUM,
-                PasswordMetrics.computeForPassword("ab!c").determineComplexity());
+                PasswordMetrics.computeForPassword("ab!c".getBytes()).determineComplexity());
     }
 
     @Test
     public void testDetermineComplexity_mediumAlphanumeric() {
         assertEquals(PASSWORD_COMPLEXITY_MEDIUM,
-                PasswordMetrics.computeForPassword("ab!1").determineComplexity());
+                PasswordMetrics.computeForPassword("ab!1".getBytes()).determineComplexity());
     }
 
     @Test
     public void testDetermineComplexity_highNumericComplex() {
         assertEquals(PASSWORD_COMPLEXITY_HIGH,
-                PasswordMetrics.computeForPassword("12389647!").determineComplexity());
+                PasswordMetrics.computeForPassword("12389647!".getBytes()).determineComplexity());
     }
 
     @Test
     public void testDetermineComplexity_highAlphabetic() {
         assertEquals(PASSWORD_COMPLEXITY_HIGH,
-                PasswordMetrics.computeForPassword("alphabetic!").determineComplexity());
+                PasswordMetrics.computeForPassword("alphabetic!".getBytes()).determineComplexity());
     }
 
     @Test
     public void testDetermineComplexity_highAlphanumeric() {
-        assertEquals(PASSWORD_COMPLEXITY_HIGH,
-                PasswordMetrics.computeForPassword("alphanumeric123!").determineComplexity());
+        assertEquals(PASSWORD_COMPLEXITY_HIGH, PasswordMetrics.computeForPassword(
+                "alphanumeric123!".getBytes()).determineComplexity());
     }
 
     @Test
diff --git a/core/tests/coretests/src/android/app/timezone/RulesStateTest.java b/core/tests/coretests/src/android/app/timezone/RulesStateTest.java
index bb535b6..30cc7ff 100644
--- a/core/tests/coretests/src/android/app/timezone/RulesStateTest.java
+++ b/core/tests/coretests/src/android/app/timezone/RulesStateTest.java
@@ -46,11 +46,11 @@
                 RulesState.DISTRO_STATUS_INSTALLED, rulesVersion("2016b", 2));
         assertEqualsContract(one, two);
 
-        RulesState differentSystemRules = new RulesState(
+        RulesState differentBaseRules = new RulesState(
                 "2016b", formatVersion(1, 2), false /* operationInProgress */,
                 RulesState.STAGED_OPERATION_INSTALL, rulesVersion("2016a", 3),
                 RulesState.DISTRO_STATUS_INSTALLED, rulesVersion("2016b", 2));
-        assertFalse(one.equals(differentSystemRules));
+        assertFalse(one.equals(differentBaseRules));
 
         RulesState differentFormatVersion = new RulesState(
                 "2016a", formatVersion(1, 1), false /* operationInProgress */,
@@ -121,14 +121,14 @@
     }
 
     @Test
-    public void isSystemVersionNewerThan() {
+    public void isBaseVersionNewerThan() {
         RulesState rulesState = new RulesState(
                 "2016b", formatVersion(1, 1), false /* operationInProgress */,
                 RulesState.STAGED_OPERATION_NONE, null /* stagedDistroRulesVersion */,
                 RulesState.DISTRO_STATUS_INSTALLED, rulesVersion("2016b", 3));
-        assertTrue(rulesState.isSystemVersionNewerThan(rulesVersion("2016a", 1)));
-        assertFalse(rulesState.isSystemVersionNewerThan(rulesVersion("2016b", 1)));
-        assertFalse(rulesState.isSystemVersionNewerThan(rulesVersion("2016c", 1)));
+        assertTrue(rulesState.isBaseVersionNewerThan(rulesVersion("2016a", 1)));
+        assertFalse(rulesState.isBaseVersionNewerThan(rulesVersion("2016b", 1)));
+        assertFalse(rulesState.isBaseVersionNewerThan(rulesVersion("2016c", 1)));
     }
 
     private static void assertEqualsContract(RulesState one, RulesState two) {
diff --git a/core/tests/coretests/src/android/content/pm/AndroidTestBaseUpdaterTest.java b/core/tests/coretests/src/android/content/pm/AndroidTestBaseUpdaterTest.java
index 0ed76dc..125b9ff 100644
--- a/core/tests/coretests/src/android/content/pm/AndroidTestBaseUpdaterTest.java
+++ b/core/tests/coretests/src/android/content/pm/AndroidTestBaseUpdaterTest.java
@@ -37,37 +37,37 @@
     private static final String OTHER_LIBRARY = "other.library";
 
     @Test
-    public void targeted_at_O() {
+    public void targeted_at_P() {
         PackageBuilder before = builder()
-                .targetSdkVersion(Build.VERSION_CODES.O);
+                .targetSdkVersion(Build.VERSION_CODES.P);
 
         // Should add org.apache.http.legacy.
         PackageBuilder after = builder()
-                .targetSdkVersion(Build.VERSION_CODES.O)
+                .targetSdkVersion(Build.VERSION_CODES.P)
                 .requiredLibraries(ANDROID_TEST_BASE);
 
         checkBackwardsCompatibility(before, after);
     }
 
     @Test
-    public void targeted_at_O_not_empty_usesLibraries() {
+    public void targeted_at_P_not_empty_usesLibraries() {
         PackageBuilder before = builder()
-                .targetSdkVersion(Build.VERSION_CODES.O)
+                .targetSdkVersion(Build.VERSION_CODES.P)
                 .requiredLibraries(OTHER_LIBRARY);
 
         // The org.apache.http.legacy jar should be added at the start of the list because it
         // is not on the bootclasspath and the package targets pre-P.
         PackageBuilder after = builder()
-                .targetSdkVersion(Build.VERSION_CODES.O)
+                .targetSdkVersion(Build.VERSION_CODES.P)
                 .requiredLibraries(ANDROID_TEST_BASE, OTHER_LIBRARY);
 
         checkBackwardsCompatibility(before, after);
     }
 
     @Test
-    public void targeted_at_O_in_usesLibraries() {
+    public void targeted_at_P_in_usesLibraries() {
         PackageBuilder before = builder()
-                .targetSdkVersion(Build.VERSION_CODES.O)
+                .targetSdkVersion(Build.VERSION_CODES.P)
                 .requiredLibraries(ANDROID_TEST_BASE);
 
         // No change is required because although org.apache.http.legacy has been removed from
@@ -76,9 +76,9 @@
     }
 
     @Test
-    public void targeted_at_O_in_usesOptionalLibraries() {
+    public void targeted_at_P_in_usesOptionalLibraries() {
         PackageBuilder before = builder()
-                .targetSdkVersion(Build.VERSION_CODES.O)
+                .targetSdkVersion(Build.VERSION_CODES.P)
                 .optionalLibraries(ANDROID_TEST_BASE);
 
         // No change is required because although org.apache.http.legacy has been removed from
diff --git a/core/tests/coretests/src/android/database/sqlite/SQLiteCompatibilityWalFlagsTest.java b/core/tests/coretests/src/android/database/sqlite/SQLiteCompatibilityWalFlagsTest.java
index 5dbcb3c..82bd588 100644
--- a/core/tests/coretests/src/android/database/sqlite/SQLiteCompatibilityWalFlagsTest.java
+++ b/core/tests/coretests/src/android/database/sqlite/SQLiteCompatibilityWalFlagsTest.java
@@ -19,6 +19,7 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 
 import android.content.Context;
 import android.database.DatabaseUtils;
@@ -54,44 +55,52 @@
     @Test
     public void testParseConfig() {
         SQLiteCompatibilityWalFlags.init("");
-        assertFalse(SQLiteCompatibilityWalFlags.areFlagsSet());
-
         SQLiteCompatibilityWalFlags.init(null);
-        assertFalse(SQLiteCompatibilityWalFlags.areFlagsSet());
 
-        SQLiteCompatibilityWalFlags.init("compatibility_wal_supported=false,wal_syncmode=OFF");
-        assertTrue(SQLiteCompatibilityWalFlags.areFlagsSet());
-        assertFalse(SQLiteCompatibilityWalFlags.isCompatibilityWalSupported());
-        assertEquals("OFF", SQLiteCompatibilityWalFlags.getWALSyncMode());
+        // Ensure that legacy compatibility wal isn't turned on by the old flag.
+        SQLiteCompatibilityWalFlags.init("compatibility_wal_supported=true,wal_syncmode=OFF");
+        assertFalse(SQLiteCompatibilityWalFlags.isLegacyCompatibilityWalEnabled());
+        try {
+            SQLiteCompatibilityWalFlags.getWALSyncMode();
+            fail();
+        } catch (IllegalStateException expected) {
+        }
         assertEquals(-1, SQLiteCompatibilityWalFlags.getTruncateSize());
 
+
         SQLiteCompatibilityWalFlags.init("wal_syncmode=VALUE");
-        assertTrue(SQLiteCompatibilityWalFlags.areFlagsSet());
-        assertEquals(SQLiteGlobal.isCompatibilityWalSupported(),
-                SQLiteCompatibilityWalFlags.isCompatibilityWalSupported());
-        assertEquals("VALUE", SQLiteCompatibilityWalFlags.getWALSyncMode());
+        assertFalse(SQLiteCompatibilityWalFlags.isLegacyCompatibilityWalEnabled());
         assertEquals(-1, SQLiteCompatibilityWalFlags.getTruncateSize());
+        try {
+            SQLiteCompatibilityWalFlags.getWALSyncMode();
+            fail();
+        } catch (IllegalStateException expected) {
+        }
 
-        SQLiteCompatibilityWalFlags.init("compatibility_wal_supported=true");
-        assertTrue(SQLiteCompatibilityWalFlags.areFlagsSet());
+        SQLiteCompatibilityWalFlags.init("legacy_compatibility_wal_enabled=true");
+        assertTrue(SQLiteCompatibilityWalFlags.isLegacyCompatibilityWalEnabled());
         assertEquals(SQLiteGlobal.getWALSyncMode(),
                 SQLiteCompatibilityWalFlags.getWALSyncMode());
-        assertTrue(SQLiteCompatibilityWalFlags.isCompatibilityWalSupported());
-        assertEquals(-1, SQLiteCompatibilityWalFlags.getTruncateSize());
+
+        SQLiteCompatibilityWalFlags.init(
+                "legacy_compatibility_wal_enabled=true,wal_syncmode=VALUE");
+        assertTrue(SQLiteCompatibilityWalFlags.isLegacyCompatibilityWalEnabled());
+        assertEquals("VALUE", SQLiteCompatibilityWalFlags.getWALSyncMode());
 
         SQLiteCompatibilityWalFlags.init("truncate_size=1024");
         assertEquals(1024, SQLiteCompatibilityWalFlags.getTruncateSize());
 
         SQLiteCompatibilityWalFlags.reset();
         SQLiteCompatibilityWalFlags.init("Invalid value");
-        assertFalse(SQLiteCompatibilityWalFlags.areFlagsSet());
+        assertFalse(SQLiteCompatibilityWalFlags.isLegacyCompatibilityWalEnabled());
     }
 
     @Test
     public void testApplyFlags() {
         Context ctx = InstrumentationRegistry.getContext();
 
-        SQLiteCompatibilityWalFlags.init("compatibility_wal_supported=true,wal_syncmode=NORMAL");
+        SQLiteCompatibilityWalFlags.init(
+                "legacy_compatibility_wal_enabled=true,wal_syncmode=NORMAL");
         mDatabase = SQLiteDatabase
                 .openOrCreateDatabase(ctx.getDatabasePath("SQLiteCompatibilityWalFlagsTest"), null);
         String journalMode = DatabaseUtils.stringForQuery(mDatabase, "PRAGMA journal_mode", null);
@@ -100,5 +109,22 @@
         assertEquals("Normal mode (1) is expected", "1", syncMode);
     }
 
+    @Test
+    public void testApplyFlags_thenDisableWriteAheadLogging() {
+        Context ctx = InstrumentationRegistry.getContext();
 
+        SQLiteCompatibilityWalFlags.init(
+                "legacy_compatibility_wal_enabled=true,wal_syncmode=FULL");
+        mDatabase = SQLiteDatabase
+                .openOrCreateDatabase(ctx.getDatabasePath("SQLiteCompatibilityWalFlagsTest"), null);
+
+        mDatabase.disableWriteAheadLogging();
+        String journalMode = DatabaseUtils.stringForQuery(mDatabase, "PRAGMA journal_mode", null);
+        assertEquals(SQLiteGlobal.getDefaultJournalMode(), journalMode.toUpperCase());
+        String syncMode = DatabaseUtils.stringForQuery(mDatabase, "PRAGMA synchronous", null);
+        // TODO: This is the old behaviour and seems incorrect. The specified wal_syncmode was only
+        // intended to be used if the database is in WAL mode, and we should revert to the global
+        // default sync mode if WAL is disabled.
+        assertEquals("Normal mode (2) is expected", "2", syncMode);
+    }
 }
diff --git a/core/tests/coretests/src/android/provider/DeviceConfigTest.java b/core/tests/coretests/src/android/provider/DeviceConfigTest.java
index 17e9654..de1453a 100644
--- a/core/tests/coretests/src/android/provider/DeviceConfigTest.java
+++ b/core/tests/coretests/src/android/provider/DeviceConfigTest.java
@@ -18,15 +18,11 @@
 
 import static android.provider.DeviceConfig.OnPropertyChangedListener;
 
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertNull;
-import static junit.framework.Assert.fail;
+import static com.google.common.truth.Truth.assertThat;
 
 import android.app.ActivityThread;
 import android.content.ContentResolver;
 import android.os.Bundle;
-import android.os.SystemClock;
 import android.platform.test.annotations.Presubmit;
 
 import androidx.test.InstrumentationRegistry;
@@ -37,8 +33,8 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import java.util.concurrent.Executor;
-import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 /** Tests that ensure appropriate settings are backed up. */
 @Presubmit
@@ -51,8 +47,6 @@
     private static final String sValue = "value1";
     private static final long WAIT_FOR_PROPERTY_CHANGE_TIMEOUT_MILLIS = 2000; // 2 sec
 
-    private final Object mLock = new Object();
-
     @After
     public void cleanUp() {
         deleteViaContentProvider(sNamespace, sKey);
@@ -61,14 +55,139 @@
     @Test
     public void getProperty_empty() {
         String result = DeviceConfig.getProperty(sNamespace, sKey);
-        assertNull(result);
+        assertThat(result).isNull();
+    }
+
+    @Test
+    public void getString_empty() {
+        final String default_value = "default_value";
+        final String result = DeviceConfig.getString(sNamespace, sKey, default_value);
+        assertThat(result).isEqualTo(default_value);
+    }
+
+    @Test
+    public void getString_nonEmpty() {
+        final String value = "new_value";
+        final String default_value = "default";
+        DeviceConfig.setProperty(sNamespace, sKey, value, false);
+
+        final String result = DeviceConfig.getString(sNamespace, sKey, default_value);
+        assertThat(result).isEqualTo(value);
+    }
+
+    @Test
+    public void getBoolean_empty() {
+        final boolean default_value = true;
+        final boolean result = DeviceConfig.getBoolean(sNamespace, sKey, default_value);
+        assertThat(result).isEqualTo(default_value);
+    }
+
+    @Test
+    public void getBoolean_valid() {
+        final boolean value = true;
+        final boolean default_value = false;
+        DeviceConfig.setProperty(sNamespace, sKey, String.valueOf(value), false);
+
+        final boolean result = DeviceConfig.getBoolean(sNamespace, sKey, default_value);
+        assertThat(result).isEqualTo(value);
+    }
+
+    @Test
+    public void getBoolean_invalid() {
+        final boolean default_value = true;
+        DeviceConfig.setProperty(sNamespace, sKey, "not_a_boolean", false);
+
+        final boolean result = DeviceConfig.getBoolean(sNamespace, sKey, default_value);
+        // Anything non-null other than case insensitive "true" parses to false.
+        assertThat(result).isFalse();
+    }
+
+    @Test
+    public void getInt_empty() {
+        final int default_value = 999;
+        final int result = DeviceConfig.getInt(sNamespace, sKey, default_value);
+        assertThat(result).isEqualTo(default_value);
+    }
+
+    @Test
+    public void getInt_valid() {
+        final int value = 123;
+        final int default_value = 999;
+        DeviceConfig.setProperty(sNamespace, sKey, String.valueOf(value), false);
+
+        final int result = DeviceConfig.getInt(sNamespace, sKey, default_value);
+        assertThat(result).isEqualTo(value);
+    }
+
+    @Test
+    public void getInt_invalid() {
+        final int default_value = 999;
+        DeviceConfig.setProperty(sNamespace, sKey, "not_an_int", false);
+
+        final int result = DeviceConfig.getInt(sNamespace, sKey, default_value);
+        // Failure to parse results in using the default value
+        assertThat(result).isEqualTo(default_value);
+    }
+
+    @Test
+    public void getLong_empty() {
+        final long default_value = 123456;
+        final long result = DeviceConfig.getLong(sNamespace, sKey, default_value);
+        assertThat(result).isEqualTo(default_value);
+    }
+
+    @Test
+    public void getLong_valid() {
+        final long value = 456789;
+        final long default_value = 123456;
+        DeviceConfig.setProperty(sNamespace, sKey, String.valueOf(value), false);
+
+        final long result = DeviceConfig.getLong(sNamespace, sKey, default_value);
+        assertThat(result).isEqualTo(value);
+    }
+
+    @Test
+    public void getLong_invalid() {
+        final long default_value = 123456;
+        DeviceConfig.setProperty(sNamespace, sKey, "not_a_long", false);
+
+        final long result = DeviceConfig.getLong(sNamespace, sKey, default_value);
+        // Failure to parse results in using the default value
+        assertThat(result).isEqualTo(default_value);
+    }
+
+    @Test
+    public void getFloat_empty() {
+        final float default_value = 123.456f;
+        final float result = DeviceConfig.getFloat(sNamespace, sKey, default_value);
+        assertThat(result).isEqualTo(default_value);
+    }
+
+    @Test
+    public void getFloat_valid() {
+        final float value = 456.789f;
+        final float default_value = 123.456f;
+        DeviceConfig.setProperty(sNamespace, sKey, String.valueOf(value), false);
+
+        final float result = DeviceConfig.getFloat(sNamespace, sKey, default_value);
+        assertThat(result).isEqualTo(value);
+    }
+
+    @Test
+    public void getFloat_invalid() {
+        final float default_value = 123.456f;
+        DeviceConfig.setProperty(sNamespace, sKey, "not_a_float", false);
+
+        final float result = DeviceConfig.getFloat(sNamespace, sKey, default_value);
+        // Failure to parse results in using the default value
+        assertThat(result).isEqualTo(default_value);
     }
 
     @Test
     public void setAndGetProperty_sameNamespace() {
         DeviceConfig.setProperty(sNamespace, sKey, sValue, false);
         String result = DeviceConfig.getProperty(sNamespace, sKey);
-        assertEquals(sValue, result);
+        assertThat(result).isEqualTo(sValue);
     }
 
     @Test
@@ -76,7 +195,7 @@
         String newNamespace = "namespace2";
         DeviceConfig.setProperty(sNamespace, sKey, sValue, false);
         String result = DeviceConfig.getProperty(newNamespace, sKey);
-        assertNull(result);
+        assertThat(result).isNull();
     }
 
     @Test
@@ -86,9 +205,9 @@
         DeviceConfig.setProperty(sNamespace, sKey, sValue, false);
         DeviceConfig.setProperty(newNamespace, sKey, newValue, false);
         String result = DeviceConfig.getProperty(sNamespace, sKey);
-        assertEquals(sValue, result);
+        assertThat(result).isEqualTo(sValue);
         result = DeviceConfig.getProperty(newNamespace, sKey);
-        assertEquals(newValue, result);
+        assertThat(result).isEqualTo(newValue);
 
         // clean up
         deleteViaContentProvider(newNamespace, sKey);
@@ -100,59 +219,30 @@
         DeviceConfig.setProperty(sNamespace, sKey, sValue, false);
         DeviceConfig.setProperty(sNamespace, sKey, newValue, false);
         String result = DeviceConfig.getProperty(sNamespace, sKey);
-        assertEquals(newValue, result);
+        assertThat(result).isEqualTo(newValue);
     }
 
     @Test
-    public void testListener() {
-        setPropertyAndAssertSuccessfulChange(sNamespace, sKey, sValue);
-    }
+    public void testListener() throws InterruptedException {
+        CountDownLatch countDownLatch = new CountDownLatch(1);
 
-    private void setPropertyAndAssertSuccessfulChange(String setNamespace, String setName,
-            String setValue) {
-        final AtomicBoolean success = new AtomicBoolean();
+        OnPropertyChangedListener changeListener = (namespace, name, value) -> {
+            assertThat(namespace).isEqualTo(sNamespace);
+            assertThat(name).isEqualTo(sKey);
+            assertThat(value).isEqualTo(sValue);
+            countDownLatch.countDown();
+        };
 
-        OnPropertyChangedListener changeListener = new OnPropertyChangedListener() {
-                    @Override
-                    public void onPropertyChanged(String namespace, String name, String value) {
-                        assertEquals(setNamespace, namespace);
-                        assertEquals(setName, name);
-                        assertEquals(setValue, value);
-                        success.set(true);
-
-                        synchronized (mLock) {
-                            mLock.notifyAll();
-                        }
-                    }
-                };
-        Executor executor = ActivityThread.currentApplication().getMainExecutor();
-        DeviceConfig.addOnPropertyChangedListener(setNamespace, executor, changeListener);
         try {
-            DeviceConfig.setProperty(setNamespace, setName, setValue, false);
-
-            final long startTimeMillis = SystemClock.uptimeMillis();
-            synchronized (mLock) {
-                while (true) {
-                    if (success.get()) {
-                        return;
-                    }
-                    final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis;
-                    if (elapsedTimeMillis >= WAIT_FOR_PROPERTY_CHANGE_TIMEOUT_MILLIS) {
-                        fail("Could not change setting for "
-                                + WAIT_FOR_PROPERTY_CHANGE_TIMEOUT_MILLIS + " ms");
-                    }
-                    final long remainingTimeMillis = WAIT_FOR_PROPERTY_CHANGE_TIMEOUT_MILLIS
-                            - elapsedTimeMillis;
-                    try {
-                        mLock.wait(remainingTimeMillis);
-                    } catch (InterruptedException ie) {
-                        /* ignore */
-                    }
-                }
-            }
+            DeviceConfig.addOnPropertyChangedListener(sNamespace,
+                    ActivityThread.currentApplication().getMainExecutor(), changeListener);
+            DeviceConfig.setProperty(sNamespace, sKey, sValue, false);
+            assertThat(countDownLatch.await(
+                    WAIT_FOR_PROPERTY_CHANGE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)).isTrue();
         } finally {
             DeviceConfig.removeOnPropertyChangedListener(changeListener);
         }
+
     }
 
     private static boolean deleteViaContentProvider(String namespace, String key) {
@@ -160,7 +250,7 @@
         String compositeName = namespace + "/" + key;
         Bundle result = resolver.call(
                 DeviceConfig.CONTENT_URI, Settings.CALL_METHOD_DELETE_CONFIG, compositeName, null);
-        assertNotNull(result);
+        assertThat(result).isNotNull();
         return compositeName.equals(result.getString(Settings.NameValueTable.VALUE));
     }
 
diff --git a/core/tests/coretests/src/android/provider/SettingsBackupTest.java b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
index 23cd963..69632c1 100644
--- a/core/tests/coretests/src/android/provider/SettingsBackupTest.java
+++ b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
@@ -287,6 +287,7 @@
                     Settings.Global.HDMI_SYSTEM_AUDIO_CONTROL_ENABLED,
                     Settings.Global.HEADS_UP_NOTIFICATIONS_ENABLED,
                     Settings.Global.HIDDEN_API_ACCESS_LOG_SAMPLING_RATE,
+                    Settings.Global.HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE,
                     Settings.Global.HIDDEN_API_POLICY,
                     Settings.Global.HIDE_ERROR_DIALOGS,
                     Settings.Global.HTTP_PROXY,
diff --git a/core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java b/core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java
index 71ce02d..23ab05e 100644
--- a/core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java
+++ b/core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java
@@ -129,6 +129,29 @@
         assertPosition(navParams.matrix, new Rect(400, 0, 500, 500), new Rect(460, 0, 560, 500));
     }
 
+    @Test
+    public void testFinishing() {
+        when(mMockController.getState()).thenReturn(mInsetsState);
+        mController.finish(sideBars());
+        mController.applyChangeInsets(mInsetsState);
+        assertFalse(mInsetsState.getSource(TYPE_TOP_BAR).isVisible());
+        assertTrue(mInsetsState.getSource(TYPE_NAVIGATION_BAR).isVisible());
+        assertEquals(Insets.of(0, 0, 100, 0), mController.getCurrentInsets());
+        verify(mMockController).notifyFinished(eq(mController), eq(sideBars()));
+    }
+
+    @Test
+    public void testCancelled() {
+        mController.onCancelled();
+        try {
+            mController.changeInsets(Insets.NONE);
+            fail("Expected exception to be thrown");
+        } catch (IllegalStateException ignored) {
+        }
+        verify(mMockListener).onCancelled();
+        mController.finish(sideBars());
+    }
+
     private void assertPosition(Matrix m, Rect original, Rect transformed) {
         RectF rect = new RectF(original);
         rect.offsetTo(0, 0);
diff --git a/core/tests/coretests/src/android/view/InsetsControllerTest.java b/core/tests/coretests/src/android/view/InsetsControllerTest.java
index 731d564..d71bde83 100644
--- a/core/tests/coretests/src/android/view/InsetsControllerTest.java
+++ b/core/tests/coretests/src/android/view/InsetsControllerTest.java
@@ -20,6 +20,7 @@
 import static android.view.InsetsState.TYPE_NAVIGATION_BAR;
 import static android.view.InsetsState.TYPE_TOP_BAR;
 
+import static android.view.WindowInsets.Type.topBar;
 import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
 import static junit.framework.Assert.assertEquals;
 import static junit.framework.Assert.assertFalse;
@@ -48,6 +49,9 @@
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+
+import java.util.concurrent.CountDownLatch;
 
 @Presubmit
 @FlakyTest(detail = "Promote once confirmed non-flaky")
@@ -80,6 +84,8 @@
                     new DisplayCutout(
                             Insets.of(10, 10, 10, 10), rect, rect, rect, rect),
                     rect, rect, SOFT_INPUT_ADJUST_RESIZE);
+            mController.onFrameChanged(new Rect(0, 0, 100, 100));
+            mController.getState().setDisplayFrame(new Rect(0, 0, 100, 100));
         });
         InstrumentationRegistry.getInstrumentation().waitForIdleSync();
     }
@@ -101,6 +107,19 @@
     }
 
     @Test
+    public void testControlsRevoked_duringAnim() {
+        InsetsSourceControl control = new InsetsSourceControl(TYPE_TOP_BAR, mLeash, new Point());
+        mController.onControlsChanged(new InsetsSourceControl[] { control });
+
+        WindowInsetsAnimationControlListener mockListener =
+                mock(WindowInsetsAnimationControlListener.class);
+        mController.controlWindowInsetsAnimation(topBar(), mockListener);
+        verify(mockListener).onReady(any(), anyInt());
+        mController.onControlsChanged(new InsetsSourceControl[0]);
+        verify(mockListener).onCancelled();
+    }
+
+    @Test
     public void testFrameDoesntMatchDisplay() {
         mController.onFrameChanged(new Rect(0, 0, 100, 100));
         mController.getState().setDisplayFrame(new Rect(0, 0, 200, 200));
@@ -119,24 +138,21 @@
         InsetsSourceControl ime = controls[2];
 
         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
+            // since there is no focused view, forcefully make IME visible.
+            mController.applyImeVisibility(true /* setVisible */);
             mController.show(Type.all());
             // quickly jump to final state by cancelling it.
             mController.cancelExistingAnimation();
             assertTrue(mController.getSourceConsumer(navBar.getType()).isVisible());
             assertTrue(mController.getSourceConsumer(topBar.getType()).isVisible());
-            // no focused view, no IME.
-            assertFalse(mController.getSourceConsumer(ime.getType()).isVisible());
+            assertTrue(mController.getSourceConsumer(ime.getType()).isVisible());
 
+            mController.applyImeVisibility(false /* setVisible */);
             mController.hide(Type.all());
             mController.cancelExistingAnimation();
             assertFalse(mController.getSourceConsumer(navBar.getType()).isVisible());
             assertFalse(mController.getSourceConsumer(topBar.getType()).isVisible());
             assertFalse(mController.getSourceConsumer(ime.getType()).isVisible());
-
-            mController.show(Type.ime());
-            mController.cancelExistingAnimation();
-            // no focused view, no IME.
-            assertFalse(mController.getSourceConsumer(ime.getType()).isVisible());
         });
         InstrumentationRegistry.getInstrumentation().waitForIdleSync();
     }
@@ -292,6 +308,35 @@
         InstrumentationRegistry.getInstrumentation().waitForIdleSync();
     }
 
+    @Test
+    public void testAnimationEndState_controller() throws Exception {
+        InsetsSourceControl control = new InsetsSourceControl(TYPE_TOP_BAR, mLeash, new Point());
+        mController.onControlsChanged(new InsetsSourceControl[] { control });
+
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
+            WindowInsetsAnimationControlListener mockListener =
+                    mock(WindowInsetsAnimationControlListener.class);
+            mController.controlWindowInsetsAnimation(topBar(), mockListener);
+
+            ArgumentCaptor<WindowInsetsAnimationController> controllerCaptor =
+                    ArgumentCaptor.forClass(WindowInsetsAnimationController.class);
+            verify(mockListener).onReady(controllerCaptor.capture(), anyInt());
+            controllerCaptor.getValue().finish(0 /* shownTypes */);
+        });
+        waitUntilNextFrame();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
+            assertFalse(mController.getSourceConsumer(TYPE_TOP_BAR).isVisible());
+        });
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
+    }
+
+    private void waitUntilNextFrame() throws Exception {
+        final CountDownLatch latch = new CountDownLatch(1);
+        Choreographer.getMainThreadInstance().postCallback(Choreographer.CALLBACK_COMMIT,
+                latch::countDown, null /* token */);
+        latch.await();
+    }
+
     private InsetsSourceControl[] prepareControls() {
         final InsetsSourceControl navBar = new InsetsSourceControl(TYPE_NAVIGATION_BAR, mLeash,
                 new Point());
diff --git a/core/tests/coretests/src/android/view/accessibility/AccessibilityCacheTest.java b/core/tests/coretests/src/android/view/accessibility/AccessibilityCacheTest.java
index e3852e1..a88968b 100644
--- a/core/tests/coretests/src/android/view/accessibility/AccessibilityCacheTest.java
+++ b/core/tests/coretests/src/android/view/accessibility/AccessibilityCacheTest.java
@@ -301,6 +301,26 @@
     }
 
     @Test
+    public void subTreeChangeEventFromUncachedNode_clearsNodeInCache() {
+        AccessibilityNodeInfo nodeInfo = getNodeWithA11yAndWindowId(CHILD_VIEW_ID, WINDOW_ID_1);
+        long id = nodeInfo.getSourceNodeId();
+        mAccessibilityCache.add(nodeInfo);
+        nodeInfo.recycle();
+
+        AccessibilityEvent event = AccessibilityEvent
+                .obtain(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
+        event.setContentChangeTypes(AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
+        event.setSource(getMockViewWithA11yAndWindowIds(PARENT_VIEW_ID, WINDOW_ID_1));
+
+        mAccessibilityCache.onAccessibilityEvent(event);
+        AccessibilityNodeInfo shouldBeNull = mAccessibilityCache.getNode(WINDOW_ID_1, id);
+        if (shouldBeNull != null) {
+            shouldBeNull.recycle();
+        }
+        assertNull(shouldBeNull);
+    }
+
+    @Test
     public void scrollEvent_clearsNodeAndChild() {
         AccessibilityEvent event = AccessibilityEvent
                 .obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
diff --git a/core/tests/coretests/src/android/view/contentcapture/ContentCaptureSessionTest.java b/core/tests/coretests/src/android/view/contentcapture/ContentCaptureSessionTest.java
index b6717e1..013408e 100644
--- a/core/tests/coretests/src/android/view/contentcapture/ContentCaptureSessionTest.java
+++ b/core/tests/coretests/src/android/view/contentcapture/ContentCaptureSessionTest.java
@@ -157,7 +157,7 @@
         }
 
         @Override
-        public void internalNotifyViewHierarchyEvent(boolean started) {
+        public void internalNotifyViewTreeEvent(boolean started) {
             throw new UnsupportedOperationException("should not have been called");
         }
 
diff --git a/core/tests/coretests/src/android/view/textclassifier/LabeledIntentTest.java b/core/tests/coretests/src/android/view/textclassifier/LabeledIntentTest.java
new file mode 100644
index 0000000..e4e9cde
--- /dev/null
+++ b/core/tests/coretests/src/android/view/textclassifier/LabeledIntentTest.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view.textclassifier;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.assertThrows;
+
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public final class LabeledIntentTest {
+    private static final String TITLE_WITHOUT_ENTITY = "Map";
+    private static final String TITLE_WITH_ENTITY = "Map NW14D1";
+    private static final String DESCRIPTION = "Check the map";
+    private static final Intent INTENT =
+            new Intent(Intent.ACTION_VIEW).setDataAndNormalize(Uri.parse("http://www.android.com"));
+    private static final int REQUEST_CODE = 42;
+    private Context mContext;
+
+    @Before
+    public void setup() {
+        mContext = InstrumentationRegistry.getTargetContext();
+    }
+
+    @Test
+    public void resolve_preferTitleWithEntity() {
+        LabeledIntent labeledIntent = new LabeledIntent(
+                TITLE_WITHOUT_ENTITY,
+                TITLE_WITH_ENTITY,
+                DESCRIPTION,
+                INTENT,
+                REQUEST_CODE
+        );
+
+        LabeledIntent.Result result =
+                labeledIntent.resolve(mContext, /*titleChooser*/ null);
+
+        assertThat(result).isNotNull();
+        assertThat(result.remoteAction.getTitle()).isEqualTo(TITLE_WITH_ENTITY);
+        assertThat(result.remoteAction.getContentDescription()).isEqualTo(DESCRIPTION);
+        Intent intent = result.resolvedIntent;
+        assertThat(intent.getAction()).isEqualTo(intent.getAction());
+        assertThat(intent.getComponent()).isNotNull();
+    }
+
+    @Test
+    public void resolve_useAvailableTitle() {
+        LabeledIntent labeledIntent = new LabeledIntent(
+                TITLE_WITHOUT_ENTITY,
+                null,
+                DESCRIPTION,
+                INTENT,
+                REQUEST_CODE
+        );
+
+        LabeledIntent.Result result =
+                labeledIntent.resolve(mContext, /*titleChooser*/ null);
+
+        assertThat(result).isNotNull();
+        assertThat(result.remoteAction.getTitle()).isEqualTo(TITLE_WITHOUT_ENTITY);
+        assertThat(result.remoteAction.getContentDescription()).isEqualTo(DESCRIPTION);
+        Intent intent = result.resolvedIntent;
+        assertThat(intent.getAction()).isEqualTo(intent.getAction());
+        assertThat(intent.getComponent()).isNotNull();
+    }
+
+    @Test
+    public void resolve_titleChooser() {
+        LabeledIntent labeledIntent = new LabeledIntent(
+                TITLE_WITHOUT_ENTITY,
+                null,
+                DESCRIPTION,
+                INTENT,
+                REQUEST_CODE
+        );
+
+        LabeledIntent.Result result =
+                labeledIntent.resolve(mContext, (labeledIntent1, resolveInfo) -> "chooser");
+
+        assertThat(result).isNotNull();
+        assertThat(result.remoteAction.getTitle()).isEqualTo("chooser");
+        assertThat(result.remoteAction.getContentDescription()).isEqualTo(DESCRIPTION);
+        Intent intent = result.resolvedIntent;
+        assertThat(intent.getAction()).isEqualTo(intent.getAction());
+        assertThat(intent.getComponent()).isNotNull();
+    }
+
+    @Test
+    public void resolve_titleChooserReturnsNull() {
+        LabeledIntent labeledIntent = new LabeledIntent(
+                TITLE_WITHOUT_ENTITY,
+                null,
+                DESCRIPTION,
+                INTENT,
+                REQUEST_CODE
+        );
+
+        LabeledIntent.Result result =
+                labeledIntent.resolve(mContext, (labeledIntent1, resolveInfo) -> null);
+
+        assertThat(result).isNotNull();
+        assertThat(result.remoteAction.getTitle()).isEqualTo(TITLE_WITHOUT_ENTITY);
+        assertThat(result.remoteAction.getContentDescription()).isEqualTo(DESCRIPTION);
+        Intent intent = result.resolvedIntent;
+        assertThat(intent.getAction()).isEqualTo(intent.getAction());
+        assertThat(intent.getComponent()).isNotNull();
+    }
+
+
+    @Test
+    public void resolve_missingTitle() {
+        assertThrows(
+                IllegalArgumentException.class,
+                () ->
+                        new LabeledIntent(
+                                null,
+                                null,
+                                DESCRIPTION,
+                                INTENT,
+                                REQUEST_CODE
+                        ));
+    }
+}
diff --git a/core/tests/coretests/src/android/view/textclassifier/LegacyIntentFactoryTest.java b/core/tests/coretests/src/android/view/textclassifier/LegacyIntentFactoryTest.java
index 73d3eec..743818c 100644
--- a/core/tests/coretests/src/android/view/textclassifier/LegacyIntentFactoryTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/LegacyIntentFactoryTest.java
@@ -58,9 +58,12 @@
                         null,
                         null,
                         null,
+                        null,
+                        null,
+                        null,
                         null);
 
-        List<TextClassifierImpl.LabeledIntent> intents = mLegacyIntentFactory.create(
+        List<LabeledIntent> intents = mLegacyIntentFactory.create(
                 InstrumentationRegistry.getContext(),
                 TEXT,
                 /* foreignText */ false,
@@ -68,8 +71,8 @@
                 classificationResult);
 
         assertThat(intents).hasSize(1);
-        TextClassifierImpl.LabeledIntent labeledIntent = intents.get(0);
-        Intent intent = labeledIntent.getIntent();
+        LabeledIntent labeledIntent = intents.get(0);
+        Intent intent = labeledIntent.intent;
         assertThat(intent.getAction()).isEqualTo(Intent.ACTION_DEFINE);
         assertThat(intent.getStringExtra(Intent.EXTRA_TEXT)).isEqualTo(TEXT);
         assertThat(
@@ -89,9 +92,12 @@
                         null,
                         null,
                         null,
+                        null,
+                        null,
+                        null,
                         null);
 
-        List<TextClassifierImpl.LabeledIntent> intents = mLegacyIntentFactory.create(
+        List<LabeledIntent> intents = mLegacyIntentFactory.create(
                 InstrumentationRegistry.getContext(),
                 TEXT,
                 /* foreignText */ true,
@@ -99,7 +105,7 @@
                 classificationResult);
 
         assertThat(intents).hasSize(2);
-        assertThat(intents.get(0).getIntent().getAction()).isEqualTo(Intent.ACTION_DEFINE);
-        assertThat(intents.get(1).getIntent().getAction()).isEqualTo(Intent.ACTION_TRANSLATE);
+        assertThat(intents.get(0).intent.getAction()).isEqualTo(Intent.ACTION_DEFINE);
+        assertThat(intents.get(1).intent.getAction()).isEqualTo(Intent.ACTION_TRANSLATE);
     }
 }
diff --git a/core/tests/coretests/src/android/view/textclassifier/TemplateClassificationIntentFactoryTest.java b/core/tests/coretests/src/android/view/textclassifier/TemplateClassificationIntentFactoryTest.java
index d9dac31..9fd9e8e 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TemplateClassificationIntentFactoryTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TemplateClassificationIntentFactoryTest.java
@@ -40,7 +40,7 @@
 public class TemplateClassificationIntentFactoryTest {
 
     private static final String TEXT = "text";
-    private static final String TITLE = "Map";
+    private static final String TITLE_WITHOUT_ENTITY = "Map";
     private static final String DESCRIPTION = "Opens in Maps";
     private static final String ACTION = Intent.ACTION_VIEW;
 
@@ -69,9 +69,12 @@
                         null,
                         null,
                         null,
+                        null,
+                        null,
+                        null,
                         createRemoteActionTemplates());
 
-        List<TextClassifierImpl.LabeledIntent> intents =
+        List<LabeledIntent> intents =
                 mTemplateClassificationIntentFactory.create(
                         InstrumentationRegistry.getContext(),
                         TEXT,
@@ -80,14 +83,14 @@
                         classificationResult);
 
         assertThat(intents).hasSize(2);
-        TextClassifierImpl.LabeledIntent labeledIntent = intents.get(0);
-        assertThat(labeledIntent.getTitle()).isEqualTo(TITLE);
-        Intent intent = labeledIntent.getIntent();
+        LabeledIntent labeledIntent = intents.get(0);
+        assertThat(labeledIntent.titleWithoutEntity).isEqualTo(TITLE_WITHOUT_ENTITY);
+        Intent intent = labeledIntent.intent;
         assertThat(intent.getAction()).isEqualTo(ACTION);
         assertThat(intent.hasExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER)).isTrue();
 
         labeledIntent = intents.get(1);
-        intent = labeledIntent.getIntent();
+        intent = labeledIntent.intent;
         assertThat(intent.getAction()).isEqualTo(Intent.ACTION_TRANSLATE);
         assertThat(intent.hasExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER)).isTrue();
     }
@@ -105,9 +108,12 @@
                         null,
                         null,
                         null,
+                        null,
+                        null,
+                        null,
                         createRemoteActionTemplates());
 
-        List<TextClassifierImpl.LabeledIntent> intents =
+        List<LabeledIntent> intents =
                 mTemplateClassificationIntentFactory.create(
                         InstrumentationRegistry.getContext(),
                         TEXT,
@@ -116,9 +122,9 @@
                         classificationResult);
 
         assertThat(intents).hasSize(1);
-        TextClassifierImpl.LabeledIntent labeledIntent = intents.get(0);
-        assertThat(labeledIntent.getTitle()).isEqualTo(TITLE);
-        Intent intent = labeledIntent.getIntent();
+        LabeledIntent labeledIntent = intents.get(0);
+        assertThat(labeledIntent.titleWithoutEntity).isEqualTo(TITLE_WITHOUT_ENTITY);
+        Intent intent = labeledIntent.intent;
         assertThat(intent.getAction()).isEqualTo(ACTION);
         assertThat(intent.hasExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER)).isTrue();
     }
@@ -126,7 +132,8 @@
     private static RemoteActionTemplate[] createRemoteActionTemplates() {
         return new RemoteActionTemplate[]{
                 new RemoteActionTemplate(
-                        TITLE,
+                        TITLE_WITHOUT_ENTITY,
+                        null,
                         DESCRIPTION,
                         ACTION,
                         null,
diff --git a/core/tests/coretests/src/android/view/textclassifier/TemplateIntentFactoryTest.java b/core/tests/coretests/src/android/view/textclassifier/TemplateIntentFactoryTest.java
index a1158a7..1860734 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TemplateIntentFactoryTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TemplateIntentFactoryTest.java
@@ -38,7 +38,8 @@
 public class TemplateIntentFactoryTest {
 
     private static final String TEXT = "text";
-    private static final String TITLE = "Map";
+    private static final String TITLE_WITHOUT_ENTITY = "Map";
+    private static final String TITLE_WITH_ENTITY = "Map NW14D1";
     private static final String DESCRIPTION = "Check the map";
     private static final String ACTION = Intent.ACTION_VIEW;
     private static final String DATA = Uri.parse("http://www.android.com").toString();
@@ -69,7 +70,8 @@
     @Test
     public void create_full() {
         RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
-                TITLE,
+                TITLE_WITHOUT_ENTITY,
+                TITLE_WITH_ENTITY,
                 DESCRIPTION,
                 ACTION,
                 DATA,
@@ -81,15 +83,16 @@
                 REQUEST_CODE
         );
 
-        List<TextClassifierImpl.LabeledIntent> intents =
+        List<LabeledIntent> intents =
                 mTemplateIntentFactory.create(new RemoteActionTemplate[]{remoteActionTemplate});
 
         assertThat(intents).hasSize(1);
-        TextClassifierImpl.LabeledIntent labeledIntent = intents.get(0);
-        assertThat(labeledIntent.getTitle()).isEqualTo(TITLE);
-        assertThat(labeledIntent.getDescription()).isEqualTo(DESCRIPTION);
-        assertThat(labeledIntent.getRequestCode()).isEqualTo(REQUEST_CODE);
-        Intent intent = labeledIntent.getIntent();
+        LabeledIntent labeledIntent = intents.get(0);
+        assertThat(labeledIntent.titleWithoutEntity).isEqualTo(TITLE_WITHOUT_ENTITY);
+        assertThat(labeledIntent.titleWithEntity).isEqualTo(TITLE_WITH_ENTITY);
+        assertThat(labeledIntent.description).isEqualTo(DESCRIPTION);
+        assertThat(labeledIntent.requestCode).isEqualTo(REQUEST_CODE);
+        Intent intent = labeledIntent.intent;
         assertThat(intent.getAction()).isEqualTo(ACTION);
         assertThat(intent.getData().toString()).isEqualTo(DATA);
         assertThat(intent.getType()).isEqualTo(TYPE);
@@ -104,7 +107,8 @@
     @Test
     public void normalizesScheme() {
         RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
-                TITLE,
+                TITLE_WITHOUT_ENTITY,
+                TITLE_WITH_ENTITY,
                 DESCRIPTION,
                 ACTION,
                 "HTTp://www.android.com",
@@ -116,17 +120,18 @@
                 REQUEST_CODE
         );
 
-        List<TextClassifierImpl.LabeledIntent> intents =
+        List<LabeledIntent> intents =
                 mTemplateIntentFactory.create(new RemoteActionTemplate[] {remoteActionTemplate});
 
-        String data = intents.get(0).getIntent().getData().toString();
+        String data = intents.get(0).intent.getData().toString();
         assertThat(data).isEqualTo("http://www.android.com");
     }
 
     @Test
     public void create_minimal() {
         RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
-                TITLE,
+                TITLE_WITHOUT_ENTITY,
+                null,
                 DESCRIPTION,
                 ACTION,
                 null,
@@ -138,16 +143,17 @@
                 null
         );
 
-        List<TextClassifierImpl.LabeledIntent> intents =
+        List<LabeledIntent> intents =
                 mTemplateIntentFactory.create(new RemoteActionTemplate[]{remoteActionTemplate});
 
         assertThat(intents).hasSize(1);
-        TextClassifierImpl.LabeledIntent labeledIntent = intents.get(0);
-        assertThat(labeledIntent.getTitle()).isEqualTo(TITLE);
-        assertThat(labeledIntent.getDescription()).isEqualTo(DESCRIPTION);
-        assertThat(labeledIntent.getRequestCode()).isEqualTo(
-                TextClassifierImpl.LabeledIntent.DEFAULT_REQUEST_CODE);
-        Intent intent = labeledIntent.getIntent();
+        LabeledIntent labeledIntent = intents.get(0);
+        assertThat(labeledIntent.titleWithoutEntity).isEqualTo(TITLE_WITHOUT_ENTITY);
+        assertThat(labeledIntent.titleWithEntity).isNull();
+        assertThat(labeledIntent.description).isEqualTo(DESCRIPTION);
+        assertThat(labeledIntent.requestCode).isEqualTo(
+                LabeledIntent.DEFAULT_REQUEST_CODE);
+        Intent intent = labeledIntent.intent;
         assertThat(intent.getAction()).isEqualTo(ACTION);
         assertThat(intent.getData()).isNull();
         assertThat(intent.getType()).isNull();
@@ -161,7 +167,7 @@
     public void invalidTemplate_nullTemplate() {
         RemoteActionTemplate remoteActionTemplate = null;
 
-        List<TextClassifierImpl.LabeledIntent> intents =
+        List<LabeledIntent> intents =
                 mTemplateIntentFactory.create(new RemoteActionTemplate[] {remoteActionTemplate});
 
         assertThat(intents).isEmpty();
@@ -170,7 +176,8 @@
     @Test
     public void invalidTemplate_nonEmptyPackageName() {
         RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
-                TITLE,
+                TITLE_WITHOUT_ENTITY,
+                TITLE_WITH_ENTITY,
                 DESCRIPTION,
                 ACTION,
                 DATA,
@@ -182,7 +189,7 @@
                 REQUEST_CODE
         );
 
-        List<TextClassifierImpl.LabeledIntent> intents =
+        List<LabeledIntent> intents =
                 mTemplateIntentFactory.create(new RemoteActionTemplate[] {remoteActionTemplate});
 
         assertThat(intents).isEmpty();
@@ -192,6 +199,7 @@
     public void invalidTemplate_emptyTitle() {
         RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
                 null,
+                null,
                 DESCRIPTION,
                 ACTION,
                 null,
@@ -203,7 +211,7 @@
                 null
         );
 
-        List<TextClassifierImpl.LabeledIntent> intents =
+        List<LabeledIntent> intents =
                 mTemplateIntentFactory.create(new RemoteActionTemplate[] {remoteActionTemplate});
 
         assertThat(intents).isEmpty();
@@ -212,7 +220,8 @@
     @Test
     public void invalidTemplate_emptyDescription() {
         RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
-                TITLE,
+                TITLE_WITHOUT_ENTITY,
+                TITLE_WITH_ENTITY,
                 null,
                 ACTION,
                 null,
@@ -224,7 +233,7 @@
                 null
         );
 
-        List<TextClassifierImpl.LabeledIntent> intents =
+        List<LabeledIntent> intents =
                 mTemplateIntentFactory.create(new RemoteActionTemplate[] {remoteActionTemplate});
 
         assertThat(intents).isEmpty();
@@ -233,7 +242,8 @@
     @Test
     public void invalidTemplate_emptyIntentAction() {
         RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
-                TITLE,
+                TITLE_WITHOUT_ENTITY,
+                TITLE_WITH_ENTITY,
                 DESCRIPTION,
                 null,
                 null,
@@ -245,7 +255,7 @@
                 null
         );
 
-        List<TextClassifierImpl.LabeledIntent> intents =
+        List<LabeledIntent> intents =
                 mTemplateIntentFactory.create(new RemoteActionTemplate[] {remoteActionTemplate});
 
         assertThat(intents).isEmpty();
diff --git a/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java b/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java
index 442ece5..5dddd1a 100644
--- a/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java
@@ -218,6 +218,51 @@
 
     }
 
+    @Test
+    public void testReader_otherThreads() throws IOException {
+        final Path processPath = mProcDirectory.toPath().resolve("self");
+        setupDirectory(
+                processPath,
+                new int[]{1, 2, 3},
+                "process",
+                new String[]{"thread1", "thread2", "thread3"},
+                new int[]{1000, 2000},
+                new int[][]{{0, 100}, {10, 0}, {0, 300}});
+        final KernelCpuThreadReader kernelCpuThreadReader = new KernelCpuThreadReader(
+                8,
+                i -> true,
+                2000,
+                mProcDirectory.toPath(),
+                processPath.resolve("task/1/time_in_state"),
+                new KernelCpuThreadReader.Injector() {
+                    @Override
+                    public int myPid() {
+                        return 1000;
+                    }
+
+                    @Override
+                    public int myUid() {
+                        return 0;
+                    }
+
+                    @Override
+                    public int getUidForPid(int pid) {
+                        return 0;
+                    }
+                });
+        checkResults(
+                kernelCpuThreadReader.getCurrentProcessCpuUsage(),
+                kernelCpuThreadReader.getCpuFrequenciesKhz(),
+                0,
+                1000,
+                new int[]{-1, 3},
+                "process",
+                new String[]{"__OTHER_THREADS", "thread3"},
+                new int[]{1000, 2000},
+                new int[][]{{100, 1000}, {0, 3000}}
+        );
+    }
+
     private void setupDirectory(Path processPath, int[] threadIds, String processName,
             String[] threadNames, int[] cpuFrequencies, int[][] cpuTimes) throws IOException {
         // Make /proc/$PID
@@ -259,6 +304,7 @@
         assertEquals(processId, processCpuUsage.processId);
         assertEquals(uid, processCpuUsage.uid);
         assertEquals(processName, processCpuUsage.processName);
+        assertEquals(threadIds.length, processCpuUsage.threadCpuUsages.size());
 
         // Sort the thread CPU usages to compare with test case
         final ArrayList<KernelCpuThreadReader.ThreadCpuUsage> threadCpuUsages =
diff --git a/core/tests/utillib/Android.bp b/core/tests/utillib/Android.bp
new file mode 100644
index 0000000..1f742c2
--- /dev/null
+++ b/core/tests/utillib/Android.bp
@@ -0,0 +1,22 @@
+// Copyright (C) 2010 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_library {
+    name: "frameworks-core-util-lib",
+
+    srcs: ["**/*.java"],
+
+    static_libs: ["junit"],
+    libs: ["android.test.base"],
+}
diff --git a/core/tests/utillib/Android.mk b/core/tests/utillib/Android.mk
deleted file mode 100644
index be1ab1f..0000000
--- a/core/tests/utillib/Android.mk
+++ /dev/null
@@ -1,29 +0,0 @@
-# Copyright (C) 2010 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_MODULE := frameworks-core-util-lib
-LOCAL_STATIC_JAVA_LIBRARIES := junit
-LOCAL_JAVA_LIBRARIES := android.test.base
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-# Build the test APKs using their own makefiles
-include $(call all-makefiles-under,$(LOCAL_PATH))
-
diff --git a/graphics/TEST_MAPPING b/graphics/TEST_MAPPING
new file mode 100644
index 0000000..10bd0ee
--- /dev/null
+++ b/graphics/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+      "name": "CtsGraphicsTestCases"
+    }
+  ]
+}
diff --git a/graphics/java/android/graphics/BaseCanvas.java b/graphics/java/android/graphics/BaseCanvas.java
index aaf40b4..83c8b01 100644
--- a/graphics/java/android/graphics/BaseCanvas.java
+++ b/graphics/java/android/graphics/BaseCanvas.java
@@ -599,9 +599,6 @@
             int colorOffset, @Nullable short[] indices, int indexOffset, int indexCount,
             @NonNull Paint paint) {
         checkRange(verts.length, vertOffset, vertexCount);
-        if (isHardwareAccelerated()) {
-            return;
-        }
         if (texs != null) {
             checkRange(texs.length, texOffset, vertexCount);
         }
diff --git a/graphics/java/android/graphics/Bitmap.java b/graphics/java/android/graphics/Bitmap.java
index 8d3bac8..18eafa6 100644
--- a/graphics/java/android/graphics/Bitmap.java
+++ b/graphics/java/android/graphics/Bitmap.java
@@ -836,7 +836,7 @@
      * @return A bitmap that represents the specified subset of source
      * @throws IllegalArgumentException if the x, y, width, height values are
      *         outside of the dimensions of the source bitmap, or width is <= 0,
-     *         or height is <= 0
+     *         or height is <= 0, or if the source bitmap has already been recycled
      */
     public static Bitmap createBitmap(@NonNull Bitmap source, int x, int y, int width, int height,
             @Nullable Matrix m, boolean filter) {
@@ -849,6 +849,9 @@
         if (y + height > source.getHeight()) {
             throw new IllegalArgumentException("y + height must be <= bitmap.height()");
         }
+        if (source.isRecycled()) {
+            throw new IllegalArgumentException("cannot use a recycled source in createBitmap");
+        }
 
         // check if we can just return our argument unchanged
         if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() &&
@@ -1270,7 +1273,7 @@
             node.setLeftTopRightBottom(0, 0, width, height);
             node.setClipToBounds(false);
             node.setForceDarkAllowed(false);
-            final RecordingCanvas canvas = node.startRecording(width, height);
+            final RecordingCanvas canvas = node.beginRecording(width, height);
             if (source.getWidth() != width || source.getHeight() != height) {
                 canvas.scale(width / (float) source.getWidth(),
                         height / (float) source.getHeight());
@@ -1842,6 +1845,7 @@
      * @throws IllegalStateException if the bitmap's config is {@link Config#HARDWARE}
      *
      */
+    @NonNull
     public Color getColor(int x, int y) {
         checkRecycled("Can't call getColor() on a recycled bitmap");
         checkHardware("unable to getColor(), "
@@ -2021,7 +2025,7 @@
                         x, y, width, height);
     }
 
-    public static final Parcelable.Creator<Bitmap> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Bitmap> CREATOR
             = new Parcelable.Creator<Bitmap>() {
         /**
          * Rebuilds a bitmap previously stored with writeToParcel().
diff --git a/graphics/java/android/graphics/GraphicBuffer.java b/graphics/java/android/graphics/GraphicBuffer.java
index 7408683..3b1fc70 100644
--- a/graphics/java/android/graphics/GraphicBuffer.java
+++ b/graphics/java/android/graphics/GraphicBuffer.java
@@ -279,7 +279,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Parcelable.Creator<GraphicBuffer> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<GraphicBuffer> CREATOR =
             new Parcelable.Creator<GraphicBuffer>() {
         public GraphicBuffer createFromParcel(Parcel in) {
             int width = in.readInt();
diff --git a/graphics/java/android/graphics/HardwareRenderer.java b/graphics/java/android/graphics/HardwareRenderer.java
index b020556..e623354 100644
--- a/graphics/java/android/graphics/HardwareRenderer.java
+++ b/graphics/java/android/graphics/HardwareRenderer.java
@@ -258,7 +258,7 @@
      *                and the renderer will draw nothing.
      */
     public void setContentRoot(@Nullable RenderNode content) {
-        RecordingCanvas canvas = mRootNode.startRecording();
+        RecordingCanvas canvas = mRootNode.beginRecording();
         if (content != null) {
             canvas.drawRenderNode(content);
         }
diff --git a/graphics/java/android/graphics/Insets.java b/graphics/java/android/graphics/Insets.java
index c64c789..c6dc239 100644
--- a/graphics/java/android/graphics/Insets.java
+++ b/graphics/java/android/graphics/Insets.java
@@ -184,7 +184,7 @@
         out.writeInt(bottom);
     }
 
-    public static final Parcelable.Creator<Insets> CREATOR = new Parcelable.Creator<Insets>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<Insets> CREATOR = new Parcelable.Creator<Insets>() {
         @Override
         public Insets createFromParcel(Parcel in) {
             return new Insets(in.readInt(), in.readInt(), in.readInt(), in.readInt());
diff --git a/graphics/java/android/graphics/Point.java b/graphics/java/android/graphics/Point.java
index ea93501..3614f3b 100644
--- a/graphics/java/android/graphics/Point.java
+++ b/graphics/java/android/graphics/Point.java
@@ -139,7 +139,7 @@
         protoOutputStream.end(token);
     }
 
-    public static final Parcelable.Creator<Point> CREATOR = new Parcelable.Creator<Point>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<Point> CREATOR = new Parcelable.Creator<Point>() {
         /**
          * Return a new point from the data in the specified parcel.
          */
diff --git a/graphics/java/android/graphics/PointF.java b/graphics/java/android/graphics/PointF.java
index a3b4194..f1f48ad 100644
--- a/graphics/java/android/graphics/PointF.java
+++ b/graphics/java/android/graphics/PointF.java
@@ -130,7 +130,7 @@
         out.writeFloat(y);
     }
 
-    public static final Parcelable.Creator<PointF> CREATOR = new Parcelable.Creator<PointF>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<PointF> CREATOR = new Parcelable.Creator<PointF>() {
         /**
          * Return a new point from the data in the specified parcel.
          */
diff --git a/graphics/java/android/graphics/RecordingCanvas.java b/graphics/java/android/graphics/RecordingCanvas.java
index 515532f..30466e1 100644
--- a/graphics/java/android/graphics/RecordingCanvas.java
+++ b/graphics/java/android/graphics/RecordingCanvas.java
@@ -31,7 +31,7 @@
  * Bitmap objects that it draws, preventing the backing memory of Bitmaps from being released while
  * the RecordingCanvas is still holding a native reference to the memory.
  *
- * This is obtained by calling {@link RenderNode#startRecording()} and is valid until the matching
+ * This is obtained by calling {@link RenderNode#beginRecording()} and is valid until the matching
  * {@link RenderNode#endRecording()} is called. It must not be retained beyond that as it is
  * internally reused.
  */
diff --git a/graphics/java/android/graphics/Rect.java b/graphics/java/android/graphics/Rect.java
index 40a32f3..d47f682 100644
--- a/graphics/java/android/graphics/Rect.java
+++ b/graphics/java/android/graphics/Rect.java
@@ -722,7 +722,7 @@
         out.writeInt(bottom);
     }
 
-    public static final Parcelable.Creator<Rect> CREATOR = new Parcelable.Creator<Rect>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<Rect> CREATOR = new Parcelable.Creator<Rect>() {
         /**
          * Return a new rectangle from the data in the specified parcel.
          */
diff --git a/graphics/java/android/graphics/RectF.java b/graphics/java/android/graphics/RectF.java
index d6447ac..3361fa2 100644
--- a/graphics/java/android/graphics/RectF.java
+++ b/graphics/java/android/graphics/RectF.java
@@ -561,7 +561,7 @@
         out.writeFloat(bottom);
     }
     
-    public static final Parcelable.Creator<RectF> CREATOR = new Parcelable.Creator<RectF>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<RectF> CREATOR = new Parcelable.Creator<RectF>() {
         /**
          * Return a new rectangle from the data in the specified parcel.
          */
diff --git a/graphics/java/android/graphics/Region.java b/graphics/java/android/graphics/Region.java
index 29d9367..ec7f7a0 100644
--- a/graphics/java/android/graphics/Region.java
+++ b/graphics/java/android/graphics/Region.java
@@ -345,7 +345,7 @@
 
     //////////////////////////////////////////////////////////////////////////
     
-    public static final Parcelable.Creator<Region> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Region> CREATOR
         = new Parcelable.Creator<Region>() {
             /**
             * Rebuild a Region previously stored with writeToParcel().
diff --git a/graphics/java/android/graphics/RenderNode.java b/graphics/java/android/graphics/RenderNode.java
index 09b18b7..42b6acd 100644
--- a/graphics/java/android/graphics/RenderNode.java
+++ b/graphics/java/android/graphics/RenderNode.java
@@ -16,6 +16,9 @@
 
 package android.graphics;
 
+import android.annotation.BytesLong;
+import android.annotation.ColorInt;
+import android.annotation.FloatRange;
 import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -24,6 +27,8 @@
 import android.view.Surface;
 import android.view.View;
 
+import com.android.internal.util.ArrayUtils;
+
 import dalvik.annotation.optimization.CriticalNative;
 import dalvik.annotation.optimization.FastNative;
 
@@ -59,7 +64,7 @@
  * <pre class="prettyprint">
  *     RenderNode renderNode = RenderNode.create("myRenderNode");
  *     renderNode.setLeftTopRightBottom(0, 0, 50, 50); // Set the size to 50x50
- *     RecordingCanvas canvas = renderNode.startRecording();
+ *     RecordingCanvas canvas = renderNode.beginRecording();
  *     try {
  *         // Draw with the canvas
  *         canvas.drawRect(...);
@@ -71,14 +76,13 @@
  * <h3>Drawing a RenderNode in a View</h3>
  * <pre class="prettyprint">
  *     protected void onDraw(Canvas canvas) {
- *         if (canvas instanceof RecordingCanvas) {
- *             RecordingCanvas recordingCanvas = (RecordingCanvas) canvas;
+ *         if (canvas.isHardwareAccelerated()) {
  *             // Check that the RenderNode has a display list, re-recording it if it does not.
  *             if (!myRenderNode.hasDisplayList()) {
  *                 updateDisplayList(myRenderNode);
  *             }
  *             // Draw the RenderNode into this canvas.
- *             recordingCanvas.drawRenderNode(myRenderNode);
+ *             canvas.drawRenderNode(myRenderNode);
  *         }
  *     }
  * </pre>
@@ -95,7 +99,7 @@
  *
  * <h3>Properties</h3>
  * <p>In addition, a RenderNode offers several properties, such as
- * {@link #setScaleX(float)} or {@link #setLeft(int)}, that can be used to affect all
+ * {@link #setScaleX(float)} or {@link #setTranslationX(float)}, that can be used to affect all
  * the drawing commands recorded within. For instance, these properties can be used
  * to move around a large number of images without re-issuing all the individual
  * <code>canvas.drawBitmap()</code> calls.</p>
@@ -104,7 +108,7 @@
  *     private void createDisplayList() {
  *         mRenderNode = RenderNode.create("MyRenderNode");
  *         mRenderNode.setLeftTopRightBottom(0, 0, width, height);
- *         RecordingCanvas canvas = mRenderNode.startRecording();
+ *         RecordingCanvas canvas = mRenderNode.beginRecording();
  *         try {
  *             for (Bitmap b : mBitmaps) {
  *                 canvas.drawBitmap(b, 0.0f, 0.0f, null);
@@ -116,9 +120,8 @@
  *     }
  *
  *     protected void onDraw(Canvas canvas) {
- *         if (canvas instanceof RecordingCanvas) {
- *             RecordingCanvas recordingCanvas = (RecordingCanvas) canvas;
- *             recordingCanvas.drawRenderNode(mRenderNode);
+ *         if (canvas.isHardwareAccelerated())
+ *             canvas.drawRenderNode(mRenderNode);
  *         }
  *     }
  *
@@ -178,6 +181,10 @@
     private final AnimationHost mAnimationHost;
     private RecordingCanvas mCurrentRecordingCanvas;
 
+    // Will be null if not currently registered
+    @Nullable
+    private CompositePositionUpdateListener mCompositePositionUpdateListener;
+
     /**
      * Creates a new RenderNode that can be used to record batches of
      * drawing operations, and store / apply render properties when drawn.
@@ -247,15 +254,70 @@
 
     }
 
+    private static final class CompositePositionUpdateListener implements PositionUpdateListener {
+        private final PositionUpdateListener[] mListeners;
+
+        CompositePositionUpdateListener(PositionUpdateListener... listeners) {
+            mListeners = listeners;
+        }
+
+        public CompositePositionUpdateListener with(PositionUpdateListener listener) {
+            return new CompositePositionUpdateListener(
+                    ArrayUtils.appendElement(PositionUpdateListener.class, mListeners, listener));
+        }
+
+        public CompositePositionUpdateListener without(PositionUpdateListener listener) {
+            return new CompositePositionUpdateListener(
+                    ArrayUtils.removeElement(PositionUpdateListener.class, mListeners, listener));
+        }
+
+        @Override
+        public void positionChanged(long frameNumber, int left, int top, int right, int bottom) {
+            for (PositionUpdateListener pul : mListeners) {
+                pul.positionChanged(frameNumber, left, top, right, bottom);
+            }
+        }
+
+        @Override
+        public void positionLost(long frameNumber) {
+            for (PositionUpdateListener pul : mListeners) {
+                pul.positionLost(frameNumber);
+            }
+        }
+    }
+
     /**
-     * Enable callbacks for position changes.
+     * Enable callbacks for position changes. Call only from the UI thread or with
+     * external synchronization.
      *
      * @hide
      */
-    public void requestPositionUpdates(PositionUpdateListener listener) {
-        nRequestPositionUpdates(mNativeRenderNode, listener);
+    public void addPositionUpdateListener(@NonNull PositionUpdateListener listener) {
+        CompositePositionUpdateListener comp = mCompositePositionUpdateListener;
+        if (comp == null) {
+            comp = new CompositePositionUpdateListener(listener);
+        } else {
+            comp = comp.with(listener);
+        }
+        mCompositePositionUpdateListener = comp;
+        nRequestPositionUpdates(mNativeRenderNode, comp);
     }
 
+    /**
+     * Disable a callback for position changes. Call only from the UI thread or with
+     * external synchronization.
+     *
+     * @param listener Callback to remove
+     * @hide
+     */
+    public void removePositionUpdateListener(@NonNull PositionUpdateListener listener) {
+        CompositePositionUpdateListener comp = mCompositePositionUpdateListener;
+        if (comp != null) {
+            comp = comp.without(listener);
+            mCompositePositionUpdateListener = comp;
+            nRequestPositionUpdates(mNativeRenderNode, comp);
+        }
+    }
 
     /**
      * Starts recording a display list for the render node. All
@@ -263,19 +325,20 @@
      * stored in this display list.
      *
      * {@link #endRecording()} must be called when the recording is finished in order to apply
-     * the updated display list.
+     * the updated display list. Failing to call {@link #endRecording()} will result in an
+     * {@link IllegalStateException} if {@link #beginRecording(int, int)} is called again.
      *
      * @param width  The width of the recording viewport. This will not alter the width of the
-     *               RenderNode itself, that must be set with {@link #setLeft(int)} and
-     *               {@link #setRight(int)}
+     *               RenderNode itself, that must be set with {@link #setPosition(Rect)}.
      * @param height The height of the recording viewport. This will not alter the height of the
-     *               RenderNode itself, that must be set with {@link #setTop(int)} and
-     *               {@link #setBottom(int)}.
+     *               RenderNode itself, that must be set with {@link #setPosition(Rect)}.
      * @return A canvas to record drawing operations.
+     * @throws IllegalStateException If a recording is already in progress. That is, the previous
+     * call to {@link #beginRecording(int, int)} did not call {@link #endRecording()}.
      * @see #endRecording()
      * @see #hasDisplayList()
      */
-    public RecordingCanvas startRecording(int width, int height) {
+    public RecordingCanvas beginRecording(int width, int height) {
         if (mCurrentRecordingCanvas != null) {
             throw new IllegalStateException(
                     "Recording currently in progress - missing #endRecording() call?");
@@ -285,21 +348,18 @@
     }
 
     /**
-     * Same as {@link #startRecording(int, int)} with the width & height set
+     * Same as {@link #beginRecording(int, int)} with the width & height set
      * to the RenderNode's own width & height. The RenderNode's width & height may be set
-     * with {@link #setLeftTopRightBottom(int, int, int, int)}.
+     * with {@link #setPosition(int, int, int, int)}.
+     *
+     * @return A canvas to record drawing operations.
+     * @throws IllegalStateException If a recording is already in progress. That is, the previous
+     * call to {@link #beginRecording(int, int)} did not call {@link #endRecording()}.
+     * @see #endRecording()
+     * @see #hasDisplayList()
      */
-    public RecordingCanvas startRecording() {
-        return startRecording(nGetWidth(mNativeRenderNode), nGetHeight(mNativeRenderNode));
-    }
-
-    /**
-     * @hide
-     * @deprecated use {@link #startRecording(int, int)} instead
-     */
-    @Deprecated
-    public RecordingCanvas start(int width, int height) {
-        return startRecording(width, height);
+    public RecordingCanvas beginRecording() {
+        return beginRecording(nGetWidth(mNativeRenderNode), nGetHeight(mNativeRenderNode));
     }
 
     /**
@@ -307,13 +367,13 @@
      * Ends the recording for this display list. Calling this method marks
      * the display list valid and {@link #hasDisplayList()} will return true.
      *
-     * @see #startRecording(int, int)
+     * @see #beginRecording(int, int)
      * @see #hasDisplayList()
      */
     public void endRecording() {
         if (mCurrentRecordingCanvas == null) {
             throw new IllegalStateException(
-                    "No recording in progress, forgot to call #startRecording()?");
+                    "No recording in progress, forgot to call #beginRecording()?");
         }
         RecordingCanvas canvas = mCurrentRecordingCanvas;
         mCurrentRecordingCanvas = null;
@@ -324,13 +384,21 @@
 
     /**
      * @hide
+     * @deprecated use {@link #beginRecording(int, int)} instead
+     */
+    @Deprecated
+    public RecordingCanvas start(int width, int height) {
+        return beginRecording(width, height);
+    }
+
+    /**
+     * @hide
      * @deprecated use {@link #endRecording()} instead
      */
     @Deprecated
     public void end(RecordingCanvas canvas) {
-        if (mCurrentRecordingCanvas != canvas) {
-            throw new IllegalArgumentException(
-                    "Canvas given isn't the one that was returned from #startRecording");
+        if (canvas != mCurrentRecordingCanvas) {
+            throw new IllegalArgumentException("Wrong canvas");
         }
         endRecording();
     }
@@ -346,7 +414,7 @@
 
     /**
      * Returns whether the RenderNode has a display list. If this returns false, the RenderNode
-     * should be re-recorded with {@link #startRecording()} and {@link #endRecording()}.
+     * should be re-recorded with {@link #beginRecording()} and {@link #endRecording()}.
      *
      * A RenderNode without a display list may still be drawn, however it will have no impact
      * on the rendering content until its display list is updated.
@@ -425,18 +493,21 @@
      * for performance or required for the current combination of {@link #setAlpha(float)} and
      * {@link #setHasOverlappingRendering(boolean)}.
      *
-     * The usage of this is instead to allow for either overriding of the internal behavior
+     * <p>The usage of this is instead to allow for either overriding of the internal behavior
      * if it's measured to be necessary for the particular rendering content in question or, more
      * usefully, to add a composition effect to the RenderNode via the optional paint parameter.
      *
-     * Note: When a RenderNode is using a compositing layer it will also result in
+     * <p>Note: When a RenderNode is using a compositing layer it will also result in
      * clipToBounds=true behavior.
      *
      * @param forceToLayer if true this forces the RenderNode to use an intermediate buffer.
      *                     Default & generally recommended value is false.
      * @param paint        The blend mode, alpha, and ColorFilter to apply to the compositing layer.
-     *                     Only applies if forceToLayer is true.
-     * @return true if anything changed, false otherwise
+     *                     Only applies if forceToLayer is true. The paint's alpha is multiplied
+     *                     with {@link #getAlpha()} to resolve the final alpha of the RenderNode.
+     *                     If null then no additional composition effects are applied on top of the
+     *                     composition layer.
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setUseCompositingLayer(boolean forceToLayer, @Nullable Paint paint) {
         boolean didChange = nSetLayerType(mNativeRenderNode, forceToLayer ? 2 : 0);
@@ -457,15 +528,22 @@
     }
 
     /**
-     * Sets the clip bounds of the RenderNode. If null, the clip bounds is removed from the
-     * RenderNode. If non-null, the RenderNode will be clipped to this rect. If
+     * Sets an additional clip on the RenderNode. If null, the extra clip is removed from the
+     * RenderNode. If non-null, the RenderNode will be clipped to this rect. In addition  if
      * {@link #setClipToBounds(boolean)} is true, then the RenderNode will be clipped to the
-     * intersection of this rectangle and the bounds of the render node.
+     * intersection of this rectangle and the bounds of the render node, which is set with
+     * {@link #setPosition(Rect)}.
      *
-     * @param rect the bounds to clip to. If null, the clip bounds are reset
-     * @return True if the clip bounds changed, false otherwise
+     * <p>This is equivalent to do a {@link Canvas#clipRect(Rect)} at the start of this
+     * RenderNode's display list. However, as this is a property of the RenderNode instead
+     * of part of the display list it can be more easily animated for transient additional
+     * clipping. An example usage of this would be the {@link android.transition.ChangeBounds}
+     * transition animation with the resizeClip=true option.
+     *
+     * @param rect the bounds to clip to. If null, the additional clip is removed.
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
-    public boolean setClipBounds(@Nullable Rect rect) {
+    public boolean setClipRect(@Nullable Rect rect) {
         if (rect == null) {
             return nSetClipBoundsEmpty(mNativeRenderNode);
         } else {
@@ -477,11 +555,12 @@
      * Set whether the Render node should clip itself to its bounds. This defaults to true,
      * and is useful to the renderer in enable quick-rejection of chunks of the tree as well as
      * better partial invalidation support. Clipping can be further restricted or controlled
-     * through the combination of this property as well as {@link #setClipBounds(Rect)}, which
+     * through the combination of this property as well as {@link #setClipRect(Rect)}, which
      * allows for a different clipping rectangle to be used in addition to or instead of the
-     * {@link #setLeftTopRightBottom(int, int, int, int)} or the RenderNode.
+     * {@link #setPosition(int, int, int, int)} or the RenderNode.
      *
      * @param clipToBounds true if the display list should clip to its bounds, false otherwise.
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setClipToBounds(boolean clipToBounds) {
         return nSetClipToBounds(mNativeRenderNode, clipToBounds);
@@ -489,7 +568,7 @@
 
     /**
      * Returns whether or not the RenderNode is clipping to its bounds. See
-     * {@link #setClipToBounds(boolean)} and {@link #setLeftTopRightBottom(int, int, int, int)}
+     * {@link #setClipToBounds(boolean)} and {@link #setPosition(int, int, int, int)}
      *
      * @return true if the render node clips to its bounds, false otherwise.
      */
@@ -498,20 +577,58 @@
     }
 
     /**
-     * Sets whether the RenderNode should be drawn immediately after the
+     * <p>Sets whether the RenderNode should be drawn immediately after the
      * closest ancestor RenderNode containing a projection receiver.
      *
+     * <p>The default is false, and the rendering of this node happens in the typical draw order.
+     *
+     * <p>If true, then at rendering time this rendernode will not be drawn in order with the
+     * {@link Canvas#drawRenderNode(RenderNode)} command that drew this RenderNode, but instead
+     * it will be re-positioned in the RenderNode tree to be drawn on the closet ancestor with a
+     * child rendernode that has {@link #setProjectionReceiver(boolean)} as true.
+     *
+     * <p>The typical usage of this is to allow a child RenderNode to draw on a parent's background,
+     * such as the platform's usage with {@link android.graphics.drawable.RippleDrawable}. Consider
+     * the following structure, built out of which RenderNode called drawRenderNode on a different
+     * RenderNode:
+     *
+     * <pre>
+     *        +-------------+
+     *        |RenderNode: P|
+     *        +-+----------++
+     *          |          |
+     *          v          v
+     *  +-------+-----+  +-+--------------+
+     *  |RenderNode: C|  |RenderNode: P'BG|
+     *  +-------+-----+  +----------------+
+     *          |
+     *          |
+     * +--------+-------+
+     * |RenderNode: C'BG|
+     * +----------------+
+     * </pre>
+     *
+     * If P'BG is a projection receiver, and C'BG is set to project backwards then C'BG will
+     * behave as if it was drawn directly by P'BG instead of by C. This includes inheriting P'BG's
+     * clip instead of C's clip.
+     *
      * @param shouldProject true if the display list should be projected onto a
-     *                      containing volume.
+     *                      containing volume. Default is false.
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setProjectBackwards(boolean shouldProject) {
         return nSetProjectBackwards(mNativeRenderNode, shouldProject);
     }
 
     /**
-     * Sets whether the RenderNode is a projection receiver - that its parent
-     * RenderNode should draw any descendent RenderNodes with
-     * ProjectBackwards=true directly on top of it. Default value is false.
+     * Sets whether the RenderNode is a projection receiver. If true then this RenderNode's parent
+     * should draw any descendant RenderNodes with ProjectBackwards=true directly on top of it.
+     * Default value is false. See
+     * {@link #setProjectBackwards(boolean)} for a description of what this entails.
+     *
+     * @param shouldRecieve True if this RenderNode is a projection receiver, false otherwise.
+     *                      Default is false.
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setProjectionReceiver(boolean shouldRecieve) {
         return nSetProjectionReceiver(mNativeRenderNode, shouldRecieve);
@@ -526,6 +643,7 @@
      * outline for those changes to be applied.
      *
      * @param outline The outline to use for this RenderNode.
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setOutline(@Nullable Outline outline) {
         if (outline == null) {
@@ -572,8 +690,9 @@
      * {@link android.R.attr#spotShadowAlpha} theme attribute
      *
      * @param color The color this RenderNode will cast for its elevation spot shadow.
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
-    public boolean setSpotShadowColor(int color) {
+    public boolean setSpotShadowColor(@ColorInt int color) {
         return nSetSpotShadowColor(mNativeRenderNode, color);
     }
 
@@ -581,7 +700,7 @@
      * @return The shadow color set by {@link #setSpotShadowColor(int)}, or black if nothing
      * was set
      */
-    public int getSpotShadowColor() {
+    public @ColorInt int getSpotShadowColor() {
         return nGetSpotShadowColor(mNativeRenderNode);
     }
 
@@ -597,8 +716,9 @@
      * {@link android.R.attr#ambientShadowAlpha} theme attribute.
      *
      * @param color The color this RenderNode will cast for its elevation shadow.
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
-    public boolean setAmbientShadowColor(int color) {
+    public boolean setAmbientShadowColor(@ColorInt int color) {
         return nSetAmbientShadowColor(mNativeRenderNode, color);
     }
 
@@ -606,7 +726,7 @@
      * @return The shadow color set by {@link #setAmbientShadowColor(int)}, or black if
      * nothing was set
      */
-    public int getAmbientShadowColor() {
+    public @ColorInt int getAmbientShadowColor() {
         return nGetAmbientShadowColor(mNativeRenderNode);
     }
 
@@ -614,6 +734,8 @@
      * Enables or disables clipping to the outline.
      *
      * @param clipToOutline true if clipping to the outline.
+     * @return True if the clipToOutline value changed, false if previous value matched the new
+     *         value.
      */
     public boolean setClipToOutline(boolean clipToOutline) {
         return nSetClipToOutline(mNativeRenderNode, clipToOutline);
@@ -640,7 +762,7 @@
 
     /**
      * Set the static matrix on the display list. The specified matrix is combined with other
-     * transforms (such as {@link #setScaleX(float)}, {@link #setRotation(float)}, etc.)
+     * transforms (such as {@link #setScaleX(float)}, {@link #setRotationZ(float)}, etc.)
      *
      * @param matrix A transform matrix to apply to this display list
      * @hide TODO Do we want this?
@@ -669,6 +791,7 @@
      * @param alpha The translucency of the display list, must be a value between 0.0f and 1.0f
      * @see View#setAlpha(float)
      * @see #getAlpha()
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setAlpha(float alpha) {
         return nSetAlpha(mNativeRenderNode, alpha);
@@ -742,7 +865,7 @@
      * Sets the base elevation of this RenderNode in pixels
      *
      * @param lift the elevation in pixels
-     * @return true if the elevation changed, false if it was the same
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setElevation(float lift) {
         return nSetElevation(mNativeRenderNode, lift);
@@ -763,6 +886,7 @@
      * @param translationX The X axis translation value of the display list, in pixels
      * @see View#setTranslationX(float)
      * @see #getTranslationX()
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setTranslationX(float translationX) {
         return nSetTranslationX(mNativeRenderNode, translationX);
@@ -783,6 +907,7 @@
      * @param translationY The Y axis translation value of the display list, in pixels
      * @see View#setTranslationY(float)
      * @see #getTranslationY()
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setTranslationY(float translationY) {
         return nSetTranslationY(mNativeRenderNode, translationY);
@@ -802,6 +927,7 @@
      *
      * @see View#setTranslationZ(float)
      * @see #getTranslationZ()
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setTranslationZ(float translationZ) {
         return nSetTranslationZ(mNativeRenderNode, translationZ);
@@ -820,19 +946,20 @@
      * Sets the rotation value for the display list around the Z axis.
      *
      * @param rotation The rotation value of the display list, in degrees
-     * @see View#setRotation(float)
-     * @see #getRotation()
+     * @see View#setRotationZ(float)
+     * @see #getRotationZ()
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
-    public boolean setRotation(float rotation) {
+    public boolean setRotationZ(float rotation) {
         return nSetRotation(mNativeRenderNode, rotation);
     }
 
     /**
      * Returns the rotation value for this display list around the Z axis, in degrees.
      *
-     * @see #setRotation(float)
+     * @see #setRotationZ(float)
      */
-    public float getRotation() {
+    public float getRotationZ() {
         return nGetRotation(mNativeRenderNode);
     }
 
@@ -842,6 +969,7 @@
      * @param rotationX The rotation value of the display list, in degrees
      * @see View#setRotationX(float)
      * @see #getRotationX()
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setRotationX(float rotationX) {
         return nSetRotationX(mNativeRenderNode, rotationX);
@@ -862,6 +990,7 @@
      * @param rotationY The rotation value of the display list, in degrees
      * @see View#setRotationY(float)
      * @see #getRotationY()
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setRotationY(float rotationY) {
         return nSetRotationY(mNativeRenderNode, rotationY);
@@ -882,6 +1011,7 @@
      * @param scaleX The scale value of the display list
      * @see View#setScaleX(float)
      * @see #getScaleX()
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setScaleX(float scaleX) {
         return nSetScaleX(mNativeRenderNode, scaleX);
@@ -902,6 +1032,7 @@
      * @param scaleY The scale value of the display list
      * @see View#setScaleY(float)
      * @see #getScaleY()
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setScaleY(float scaleY) {
         return nSetScaleY(mNativeRenderNode, scaleY);
@@ -922,6 +1053,7 @@
      * @param pivotX The pivot value of the display list on the X axis, in pixels
      * @see View#setPivotX(float)
      * @see #getPivotX()
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setPivotX(float pivotX) {
         return nSetPivotX(mNativeRenderNode, pivotX);
@@ -942,6 +1074,7 @@
      * @param pivotY The pivot value of the display list on the Y axis, in pixels
      * @see View#setPivotY(float)
      * @see #getPivotY()
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setPivotY(float pivotY) {
         return nSetPivotY(mNativeRenderNode, pivotY);
@@ -969,6 +1102,8 @@
      * Clears any pivot previously set by a call to  {@link #setPivotX(float)} or
      * {@link #setPivotY(float)}. After calling this {@link #isPivotExplicitlySet()} will be false
      * and the pivot used for rotation will return to default of being centered on the view.
+     *
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean resetPivot() {
         return nResetPivot(mNativeRenderNode);
@@ -997,8 +1132,10 @@
      * @param distance The distance in pixels, must always be positive
      * @see #setRotationX(float)
      * @see #setRotationY(float)
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
-    public boolean setCameraDistance(float distance) {
+    public boolean setCameraDistance(
+            @FloatRange(from = 0.0f, to = Float.MAX_VALUE) float distance) {
         if (!Float.isFinite(distance) || distance < 0.0f) {
             throw new IllegalArgumentException("distance must be finite & positive, given="
                     + distance);
@@ -1013,7 +1150,7 @@
      * @return the distance along the Z axis in pixels.
      * @see #setCameraDistance(float)
      */
-    public float getCameraDistance() {
+    public @FloatRange(from = 0.0f, to = Float.MAX_VALUE) float getCameraDistance() {
         return -nGetCameraDistance(mNativeRenderNode);
     }
 
@@ -1022,6 +1159,7 @@
      *
      * @param left The left position, in pixels, of the RenderNode
      * @return true if the value changed, false otherwise
+     * @hide
      */
     public boolean setLeft(int left) {
         return nSetLeft(mNativeRenderNode, left);
@@ -1032,6 +1170,7 @@
      *
      * @param top The top position, in pixels, of the RenderNode
      * @return true if the value changed, false otherwise.
+     * @hide
      */
     public boolean setTop(int top) {
         return nSetTop(mNativeRenderNode, top);
@@ -1042,6 +1181,7 @@
      *
      * @param right The right position, in pixels, of the RenderNode
      * @return true if the value changed, false otherwise.
+     * @hide
      */
     public boolean setRight(int right) {
         return nSetRight(mNativeRenderNode, right);
@@ -1052,6 +1192,7 @@
      *
      * @param bottom The bottom position, in pixels, of the RenderNode
      * @return true if the value changed, false otherwise.
+     * @hide
      */
     public boolean setBottom(int bottom) {
         return nSetBottom(mNativeRenderNode, bottom);
@@ -1060,8 +1201,6 @@
     /**
      * Gets the left position for the RenderNode.
      *
-     * See {@link #setLeft(int)}
-     *
      * @return the left position in pixels
      */
     public int getLeft() {
@@ -1071,8 +1210,6 @@
     /**
      * Gets the top position for the RenderNode.
      *
-     * See {@link #setTop(int)}
-     *
      * @return the top position in pixels
      */
     public int getTop() {
@@ -1082,8 +1219,6 @@
     /**
      * Gets the right position for the RenderNode.
      *
-     * See {@link #setRight(int)}
-     *
      * @return the right position in pixels
      */
     public int getRight() {
@@ -1093,8 +1228,6 @@
     /**
      * Gets the bottom position for the RenderNode.
      *
-     * See {@link #setBottom(int)}
-     *
      * @return the bottom position in pixels
      */
     public int getBottom() {
@@ -1127,20 +1260,41 @@
      * @param right  The right position of the RenderNode, in pixels
      * @param bottom The bottom position of the RenderNode, in pixels
      * @return true if any values changed, false otherwise.
-     * @see #setLeft(int)
-     * @see #setTop(int)
-     * @see #setRight(int)
-     * @see #setBottom(int)
+     * @hide
      */
     public boolean setLeftTopRightBottom(int left, int top, int right, int bottom) {
         return nSetLeftTopRightBottom(mNativeRenderNode, left, top, right, bottom);
     }
 
     /**
+     * Sets the position of the RenderNode.
+     *
+     * @param left   The left position of the RenderNode, in pixels
+     * @param top    The top position of the RenderNode, in pixels
+     * @param right  The right position of the RenderNode, in pixels
+     * @param bottom The bottom position of the RenderNode, in pixels
+     * @return True if the value changed, false if the new value was the same as the previous value.
+     */
+    public boolean setPosition(int left, int top, int right, int bottom) {
+        return nSetLeftTopRightBottom(mNativeRenderNode, left, top, right, bottom);
+    }
+
+    /**
+     * Sets the position of the RenderNode.
+     *
+     * @param position The position rectangle in pixels
+     * @return True if the value changed, false if the new value was the same as the previous value.
+     */
+    public boolean setPosition(Rect position) {
+        return nSetLeftTopRightBottom(mNativeRenderNode,
+                position.left, position.top, position.right, position.bottom);
+    }
+
+    /**
      * Offsets the left and right positions for the RenderNode
      *
      * @param offset The amount that the left and right positions are offset in pixels
-     * @return true if any values changed, false otherwise.
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean offsetLeftAndRight(int offset) {
         return nOffsetLeftAndRight(mNativeRenderNode, offset);
@@ -1150,7 +1304,7 @@
      * Offsets the top and bottom values for the RenderNode
      *
      * @param offset The amount that the left and right positions are offset in pixels
-     * @return true if any values changed, false otherwise.
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean offsetTopAndBottom(int offset) {
         return nOffsetTopAndBottom(mNativeRenderNode, offset);
@@ -1170,8 +1324,10 @@
      * Gets the approximate memory usage of the RenderNode for debug purposes. Does not include
      * the memory usage of any child RenderNodes nor any bitmaps, only the memory usage of
      * this RenderNode and any data it owns.
+     *
+     * @return Approximate memory usage in bytes.
      */
-    public int computeApproximateMemoryUsage() {
+    public @BytesLong long computeApproximateMemoryUsage() {
         return nGetDebugSize(mNativeRenderNode);
     }
 
@@ -1186,7 +1342,7 @@
      * it prevent any 'false' in any of its children.
      *
      * @param allow Whether or not to allow force dark.
-     * @return true If the value has changed, false otherwise.
+     * @return True if the value changed, false if the new value was the same as the previous value.
      */
     public boolean setForceDarkAllowed(boolean allow) {
         return nSetAllowForceDark(mNativeRenderNode, allow);
diff --git a/graphics/java/android/graphics/drawable/Icon.java b/graphics/java/android/graphics/drawable/Icon.java
index f41cc7e..71dd7a2 100644
--- a/graphics/java/android/graphics/drawable/Icon.java
+++ b/graphics/java/android/graphics/drawable/Icon.java
@@ -840,7 +840,7 @@
         dest.writeInt(PorterDuff.modeToInt(mTintMode));
     }
 
-    public static final Parcelable.Creator<Icon> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<Icon> CREATOR
             = new Parcelable.Creator<Icon>() {
         public Icon createFromParcel(Parcel in) {
             return new Icon(in);
diff --git a/keystore/java/android/security/Credentials.java b/keystore/java/android/security/Credentials.java
index 2ae28f5..08f4176 100644
--- a/keystore/java/android/security/Credentials.java
+++ b/keystore/java/android/security/Credentials.java
@@ -20,6 +20,7 @@
 import com.android.org.bouncycastle.util.io.pem.PemReader;
 import com.android.org.bouncycastle.util.io.pem.PemWriter;
 
+import android.annotation.UnsupportedAppUsage;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
@@ -122,6 +123,7 @@
      * Convert objects to a PEM format which is used for
      * CA_CERTIFICATE and USER_CERTIFICATE entries.
      */
+    @UnsupportedAppUsage
     public static byte[] convertToPem(Certificate... objects)
             throws IOException, CertificateEncodingException {
         ByteArrayOutputStream bao = new ByteArrayOutputStream();
diff --git a/keystore/java/android/security/IKeyChainService.aidl b/keystore/java/android/security/IKeyChainService.aidl
index 0d32075..b3cdff7 100644
--- a/keystore/java/android/security/IKeyChainService.aidl
+++ b/keystore/java/android/security/IKeyChainService.aidl
@@ -27,6 +27,7 @@
  */
 interface IKeyChainService {
     // APIs used by KeyChain
+    @UnsupportedAppUsage
     String requestPrivateKey(String alias);
     byte[] getCertificate(String alias);
     byte[] getCaCertificates(String alias);
diff --git a/keystore/java/android/security/keystore/KeystoreResponse.java b/keystore/java/android/security/keystore/KeystoreResponse.java
index 3a229cb..529351e 100644
--- a/keystore/java/android/security/keystore/KeystoreResponse.java
+++ b/keystore/java/android/security/keystore/KeystoreResponse.java
@@ -30,7 +30,7 @@
     public final int error_code_;
     public final String error_msg_;
 
-    public static final Parcelable.Creator<KeystoreResponse> CREATOR = new
+    public static final @android.annotation.NonNull Parcelable.Creator<KeystoreResponse> CREATOR = new
             Parcelable.Creator<KeystoreResponse>() {
                 @Override
                 public KeystoreResponse createFromParcel(Parcel in) {
diff --git a/keystore/java/android/security/keystore/ParcelableKeyGenParameterSpec.java b/keystore/java/android/security/keystore/ParcelableKeyGenParameterSpec.java
index 8231dc9..d8030fb 100644
--- a/keystore/java/android/security/keystore/ParcelableKeyGenParameterSpec.java
+++ b/keystore/java/android/security/keystore/ParcelableKeyGenParameterSpec.java
@@ -193,7 +193,7 @@
                 unlockedDeviceRequired);
     }
 
-    public static final Creator<ParcelableKeyGenParameterSpec> CREATOR = new Creator<ParcelableKeyGenParameterSpec>() {
+    public static final @android.annotation.NonNull Creator<ParcelableKeyGenParameterSpec> CREATOR = new Creator<ParcelableKeyGenParameterSpec>() {
         @Override
         public ParcelableKeyGenParameterSpec createFromParcel(Parcel in) {
             return new ParcelableKeyGenParameterSpec(in);
diff --git a/libs/androidfw/AssetManager2.cpp b/libs/androidfw/AssetManager2.cpp
index 66d8542..117d05e 100644
--- a/libs/androidfw/AssetManager2.cpp
+++ b/libs/androidfw/AssetManager2.cpp
@@ -35,6 +35,12 @@
 #endif
 #endif
 
+#ifdef __ANDROID__
+#define ANDROID_LOG(x) LOG(x)
+#else
+#define ANDROID_LOG(x) std::stringstream()
+#endif
+
 #include "androidfw/ResourceUtils.h"
 
 namespace android {
@@ -356,6 +362,7 @@
 
 ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
                                          bool /*stop_at_first_match*/,
+                                         bool ignore_configuration,
                                          FindEntryResult* out_entry) const {
   // Might use this if density_override != 0.
   ResTable_config density_override_config;
@@ -379,7 +386,8 @@
 
   const uint8_t package_idx = package_ids_[package_id];
   if (package_idx == 0xff) {
-    LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.", package_id, resid);
+    ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
+                                             package_id, resid);
     return kInvalidCookie;
   }
 
@@ -399,7 +407,7 @@
 
   // If desired_config is the same as the set configuration, then we can use our filtered list
   // and we don't need to match the configurations, since they already matched.
-  const bool use_fast_path = desired_config == &configuration_;
+  const bool use_fast_path = !ignore_configuration && desired_config == &configuration_;
 
   for (size_t pi = 0; pi < package_count; pi++) {
     const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
@@ -475,21 +483,23 @@
       // ResTable_config, we must copy it.
       const auto iter_end = type_spec->types + type_spec->type_count;
       for (auto iter = type_spec->types; iter != iter_end; ++iter) {
-        ResTable_config this_config;
-        this_config.copyFromDtoH((*iter)->config);
+        ResTable_config this_config{};
 
-        if (!this_config.match(*desired_config)) {
-          continue;
-        }
+        if (!ignore_configuration) {
+          this_config.copyFromDtoH((*iter)->config);
+          if (!this_config.match(*desired_config)) {
+            continue;
+          }
 
-        if (best_config == nullptr) {
-          resolution_type = Resolution::Step::Type::INITIAL;
-        } else if (this_config.isBetterThan(*best_config, desired_config)) {
-          resolution_type = Resolution::Step::Type::BETTER_MATCH;
-        } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
-          resolution_type = Resolution::Step::Type::OVERLAID;
-        } else {
-          continue;
+          if (best_config == nullptr) {
+            resolution_type = Resolution::Step::Type::INITIAL;
+          } else if (this_config.isBetterThan(*best_config, desired_config)) {
+            resolution_type = Resolution::Step::Type::BETTER_MATCH;
+          } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
+            resolution_type = Resolution::Step::Type::OVERLAID;
+          } else {
+            continue;
+          }
         }
 
         // The configuration matches and is better than the previous selection.
@@ -506,6 +516,11 @@
         best_config = &best_config_copy;
         best_offset = offset;
 
+        if (ignore_configuration) {
+          // Any configuration will suffice, so break.
+          break;
+        }
+
         if (resource_resolution_logging_enabled_) {
           resolution_steps.push_back(Resolution::Step{resolution_type,
                                                       this_config.toString(),
@@ -622,8 +637,9 @@
 
 bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
   FindEntryResult entry;
-  ApkAssetsCookie cookie =
-      FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */, &entry);
+  ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
+                                     true /* stop_at_first_match */,
+                                     true /* ignore_configuration */, &entry);
   if (cookie == kInvalidCookie) {
     return false;
   }
@@ -652,13 +668,14 @@
 
 bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
   FindEntryResult entry;
-  ApkAssetsCookie cookie =
-      FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
+  ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
+                                     false /* stop_at_first_match */,
+                                     true /* ignore_configuration */, &entry);
   if (cookie != kInvalidCookie) {
     *out_flags = entry.type_flags;
-    return cookie;
+    return true;
   }
-  return kInvalidCookie;
+  return false;
 }
 
 ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
@@ -666,8 +683,8 @@
                                            ResTable_config* out_selected_config,
                                            uint32_t* out_flags) const {
   FindEntryResult entry;
-  ApkAssetsCookie cookie =
-      FindEntry(resid, density_override, false /* stop_at_first_match */, &entry);
+  ApkAssetsCookie cookie = FindEntry(resid, density_override, false /* stop_at_first_match */,
+                                     false /* ignore_configuration */, &entry);
   if (cookie == kInvalidCookie) {
     return kInvalidCookie;
   }
@@ -759,8 +776,10 @@
   }
 
   FindEntryResult entry;
-  ApkAssetsCookie cookie =
-      FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
+  ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
+                                     false /* stop_at_first_match */,
+                                     false /* ignore_configuration */,
+                                     &entry);
   if (cookie == kInvalidCookie) {
     return nullptr;
   }
@@ -1387,7 +1406,9 @@
             // Find the cookie of the attribute resource id
             FindEntryResult attribute_entry_result;
             ApkAssetsCookie attribute_cookie =
-                o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ , false,
+                o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
+                                            true /* stop_at_first_match */,
+                                            true /* ignore_configuration */,
                                             &attribute_entry_result);
 
             // Determine the package id of the attribute in the destination AssetManager
diff --git a/libs/androidfw/DisplayEventDispatcher.cpp b/libs/androidfw/DisplayEventDispatcher.cpp
index 3b9a348..6606148 100644
--- a/libs/androidfw/DisplayEventDispatcher.cpp
+++ b/libs/androidfw/DisplayEventDispatcher.cpp
@@ -135,6 +135,9 @@
             case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
                 dispatchHotplug(ev.header.timestamp, ev.header.displayId, ev.hotplug.connected);
                 break;
+            case DisplayEventReceiver::DISPLAY_EVENT_CONFIG_CHANGED:
+                dispatchConfigChanged(ev.header.timestamp, ev.header.displayId, ev.config.configId);
+                break;
             default:
                 ALOGW("dispatcher %p ~ ignoring unknown event type %#x", this, ev.header.type);
                 break;
diff --git a/libs/androidfw/include/androidfw/AssetManager2.h b/libs/androidfw/include/androidfw/AssetManager2.h
index fc5aa9c7..1e2b36c 100644
--- a/libs/androidfw/include/androidfw/AssetManager2.h
+++ b/libs/androidfw/include/androidfw/AssetManager2.h
@@ -257,11 +257,12 @@
   // Creates a new Theme from this AssetManager.
   std::unique_ptr<Theme> NewTheme();
 
-  template <typename Func>
-  void ForEachPackage(Func func) const {
+  void ForEachPackage(const std::function<bool(const std::string&, uint8_t)> func) const {
     for (const PackageGroup& package_group : package_groups_) {
-      func(package_group.packages_.front().loaded_package_->GetPackageName(),
-           package_group.dynamic_ref_table.mAssignedPackageId);
+      if (!func(package_group.packages_.front().loaded_package_->GetPackageName(),
+           package_group.dynamic_ref_table.mAssignedPackageId)) {
+        return;
+      }
     }
   }
 
@@ -282,10 +283,13 @@
   // care about the value. In this case, the value of `FindEntryResult::type_flags` is incomplete
   // and should not be used.
   //
+  // When `ignore_configuration` is true, FindEntry will return always select the first entry in
+  // for the type seen regardless of its configuration.
+  //
   // NOTE: FindEntry takes care of ensuring that structs within FindEntryResult have been properly
   // bounds-checked. Callers of FindEntry are free to trust the data if this method succeeds.
   ApkAssetsCookie FindEntry(uint32_t resid, uint16_t density_override, bool stop_at_first_match,
-                            FindEntryResult* out_entry) const;
+                            bool ignore_configuration, FindEntryResult* out_entry) const;
 
   // Assigns package IDs to all shared library ApkAssets.
   // Should be called whenever the ApkAssets are changed.
diff --git a/libs/androidfw/include/androidfw/DisplayEventDispatcher.h b/libs/androidfw/include/androidfw/DisplayEventDispatcher.h
index d2addba..5381c01 100644
--- a/libs/androidfw/include/androidfw/DisplayEventDispatcher.h
+++ b/libs/androidfw/include/androidfw/DisplayEventDispatcher.h
@@ -40,6 +40,8 @@
     virtual void dispatchVsync(nsecs_t timestamp, PhysicalDisplayId displayId, uint32_t count) = 0;
     virtual void dispatchHotplug(nsecs_t timestamp, PhysicalDisplayId displayId,
                                  bool connected) = 0;
+    virtual void dispatchConfigChanged(nsecs_t timestamp, PhysicalDisplayId displayId,
+                                       int32_t configId) = 0;
 
     virtual int handleEvent(int receiveFd, int events, void* data);
     bool processPendingEvents(nsecs_t* outTimestamp, PhysicalDisplayId* outDisplayId,
diff --git a/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp b/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp
index df1537e..1bd30eb 100644
--- a/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp
+++ b/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp
@@ -161,7 +161,7 @@
             SkAutoCanvasRestore acr2(canvas, shouldClip);
             canvas->setMatrix(mProjectedDisplayList->mParentMatrix);
             if (shouldClip) {
-                clipOutline(*mProjectedDisplayList->mProjectedOutline, canvas, nullptr);
+                canvas->clipPath(*mProjectedDisplayList->mProjectedOutline->getPath());
             }
             drawBackwardsProjectedNodes(canvas, *mProjectedDisplayList);
         }
diff --git a/libs/hwui/renderthread/CacheManager.cpp b/libs/hwui/renderthread/CacheManager.cpp
index 6da8062..6c04232 100644
--- a/libs/hwui/renderthread/CacheManager.cpp
+++ b/libs/hwui/renderthread/CacheManager.cpp
@@ -117,6 +117,7 @@
     auto& cache = skiapipeline::ShaderCache::get();
     cache.initShaderDiskCache(identity, size);
     contextOptions->fPersistentCache = &cache;
+    contextOptions->fGpuPathRenderers &= ~GpuPathRenderers::kCoverageCounting;
 }
 
 void CacheManager::trimMemory(TrimMemoryMode mode) {
diff --git a/libs/hwui/renderthread/VulkanManager.cpp b/libs/hwui/renderthread/VulkanManager.cpp
index 3b43f12..5af660c 100644
--- a/libs/hwui/renderthread/VulkanManager.cpp
+++ b/libs/hwui/renderthread/VulkanManager.cpp
@@ -254,10 +254,36 @@
 
     float queuePriorities[1] = { 0.0 };
 
+    void* queueNextPtr = nullptr;
+
+    VkDeviceQueueGlobalPriorityCreateInfoEXT queuePriorityCreateInfo;
+
+    if (Properties::contextPriority != 0
+            && grExtensions.hasExtension(VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME, 2)) {
+        memset(&queuePriorityCreateInfo, 0, sizeof(VkDeviceQueueGlobalPriorityCreateInfoEXT));
+        queuePriorityCreateInfo.sType =
+            VK_STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT;
+        queuePriorityCreateInfo.pNext = nullptr;
+        switch (Properties::contextPriority) {
+            case EGL_CONTEXT_PRIORITY_LOW_IMG:
+                queuePriorityCreateInfo.globalPriority = VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT;
+                break;
+            case EGL_CONTEXT_PRIORITY_MEDIUM_IMG:
+                queuePriorityCreateInfo.globalPriority = VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT;
+                break;
+            case EGL_CONTEXT_PRIORITY_HIGH_IMG:
+                queuePriorityCreateInfo.globalPriority = VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT;
+                break;
+            default:
+                LOG_ALWAYS_FATAL("Unsupported context priority");
+         }
+         queueNextPtr = &queuePriorityCreateInfo;
+    }
+
     const VkDeviceQueueCreateInfo queueInfo[2] = {
         {
             VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, // sType
-            nullptr,                                    // pNext
+            queueNextPtr,                               // pNext
             0,                                          // VkDeviceQueueCreateFlags
             mGraphicsQueueIndex,                        // queueFamilyIndex
             1,                                          // queueCount
@@ -265,7 +291,7 @@
         },
         {
             VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, // sType
-            nullptr,                                    // pNext
+            queueNextPtr,                               // pNext
             0,                                          // VkDeviceQueueCreateFlags
             mPresentQueueIndex,                         // queueFamilyIndex
             1,                                          // queueCount
diff --git a/libs/input/PointerController.cpp b/libs/input/PointerController.cpp
index 733b866..abf0837 100644
--- a/libs/input/PointerController.cpp
+++ b/libs/input/PointerController.cpp
@@ -759,11 +759,11 @@
 
 void PointerController::loadResourcesLocked() REQUIRES(mLock) {
     mPolicy->loadPointerResources(&mResources, mLocked.viewport.displayId);
+    mPolicy->loadPointerIcon(&mLocked.pointerIcon, mLocked.viewport.displayId);
 
+    mLocked.additionalMouseResources.clear();
+    mLocked.animationResources.clear();
     if (mLocked.presentation == PRESENTATION_POINTER) {
-        mLocked.additionalMouseResources.clear();
-        mLocked.animationResources.clear();
-        mPolicy->loadPointerIcon(&mLocked.pointerIcon, mLocked.viewport.displayId);
         mPolicy->loadAdditionalMouseResources(&mLocked.additionalMouseResources,
                 &mLocked.animationResources, mLocked.viewport.displayId);
     }
diff --git a/location/java/android/location/Address.java b/location/java/android/location/Address.java
index 83f05c2..bb97c78 100644
--- a/location/java/android/location/Address.java
+++ b/location/java/android/location/Address.java
@@ -472,7 +472,7 @@
         return sb.toString();
     }
 
-    public static final Parcelable.Creator<Address> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<Address> CREATOR =
         new Parcelable.Creator<Address>() {
         public Address createFromParcel(Parcel in) {
             String language = in.readString();
diff --git a/location/java/android/location/Country.java b/location/java/android/location/Country.java
index 6f82b78..f3c2a16 100644
--- a/location/java/android/location/Country.java
+++ b/location/java/android/location/Country.java
@@ -137,7 +137,7 @@
         return mTimestamp;
     }
 
-    public static final Parcelable.Creator<Country> CREATOR = new Parcelable.Creator<Country>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<Country> CREATOR = new Parcelable.Creator<Country>() {
         public Country createFromParcel(Parcel in) {
             return new Country(in.readString(), in.readInt(), in.readLong());
         }
diff --git a/location/java/android/location/Criteria.java b/location/java/android/location/Criteria.java
index 74eb445..1370b10 100644
--- a/location/java/android/location/Criteria.java
+++ b/location/java/android/location/Criteria.java
@@ -324,7 +324,7 @@
         return mBearingRequired;
     }
 
-    public static final Parcelable.Creator<Criteria> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<Criteria> CREATOR =
         new Parcelable.Creator<Criteria>() {
         @Override
         public Criteria createFromParcel(Parcel in) {
diff --git a/location/java/android/location/FusedBatchOptions.java b/location/java/android/location/FusedBatchOptions.java
index aa4a860..4a022c3 100644
--- a/location/java/android/location/FusedBatchOptions.java
+++ b/location/java/android/location/FusedBatchOptions.java
@@ -113,7 +113,7 @@
     /*
      * Method definitions to support Parcelable operations.
      */
-    public static final Parcelable.Creator<FusedBatchOptions> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<FusedBatchOptions> CREATOR =
             new Parcelable.Creator<FusedBatchOptions>() {
         @Override
         public FusedBatchOptions createFromParcel(Parcel parcel) {
diff --git a/location/java/android/location/GeocoderParams.java b/location/java/android/location/GeocoderParams.java
index d90e4b5..45d92ee 100644
--- a/location/java/android/location/GeocoderParams.java
+++ b/location/java/android/location/GeocoderParams.java
@@ -67,7 +67,7 @@
         return mPackageName;
     }
 
-    public static final Parcelable.Creator<GeocoderParams> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<GeocoderParams> CREATOR =
         new Parcelable.Creator<GeocoderParams>() {
         public GeocoderParams createFromParcel(Parcel in) {
             GeocoderParams gp = new GeocoderParams();
diff --git a/location/java/android/location/Geofence.java b/location/java/android/location/Geofence.java
index ed2aa64..9570b26 100644
--- a/location/java/android/location/Geofence.java
+++ b/location/java/android/location/Geofence.java
@@ -100,7 +100,7 @@
     }
 
     @UnsupportedAppUsage
-    public static final Parcelable.Creator<Geofence> CREATOR = new Parcelable.Creator<Geofence>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<Geofence> CREATOR = new Parcelable.Creator<Geofence>() {
         @Override
         public Geofence createFromParcel(Parcel in) {
             int type = in.readInt();
diff --git a/location/java/android/location/GnssClock.java b/location/java/android/location/GnssClock.java
index 671c57c..8507c83 100644
--- a/location/java/android/location/GnssClock.java
+++ b/location/java/android/location/GnssClock.java
@@ -431,7 +431,7 @@
         mHardwareClockDiscontinuityCount = value;
     }
 
-    public static final Creator<GnssClock> CREATOR = new Creator<GnssClock>() {
+    public static final @android.annotation.NonNull Creator<GnssClock> CREATOR = new Creator<GnssClock>() {
         @Override
         public GnssClock createFromParcel(Parcel parcel) {
             GnssClock gpsClock = new GnssClock();
diff --git a/location/java/android/location/GnssMeasurement.java b/location/java/android/location/GnssMeasurement.java
index a545f2e..446ea85 100644
--- a/location/java/android/location/GnssMeasurement.java
+++ b/location/java/android/location/GnssMeasurement.java
@@ -1509,7 +1509,7 @@
         }
     }
 
-    public static final Creator<GnssMeasurement> CREATOR = new Creator<GnssMeasurement>() {
+    public static final @android.annotation.NonNull Creator<GnssMeasurement> CREATOR = new Creator<GnssMeasurement>() {
         @Override
         public GnssMeasurement createFromParcel(Parcel parcel) {
             GnssMeasurement gnssMeasurement = new GnssMeasurement();
diff --git a/location/java/android/location/GnssMeasurementCorrections.java b/location/java/android/location/GnssMeasurementCorrections.java
index 9d3211d..fdbc3dd 100644
--- a/location/java/android/location/GnssMeasurementCorrections.java
+++ b/location/java/android/location/GnssMeasurementCorrections.java
@@ -133,7 +133,7 @@
         return 0;
     }
 
-    public static final Creator<GnssMeasurementCorrections> CREATOR =
+    public static final @android.annotation.NonNull Creator<GnssMeasurementCorrections> CREATOR =
             new Creator<GnssMeasurementCorrections>() {
                 @Override
                 public GnssMeasurementCorrections createFromParcel(Parcel parcel) {
diff --git a/location/java/android/location/GnssMeasurementsEvent.java b/location/java/android/location/GnssMeasurementsEvent.java
index 34c7354..98ef2d4 100644
--- a/location/java/android/location/GnssMeasurementsEvent.java
+++ b/location/java/android/location/GnssMeasurementsEvent.java
@@ -130,7 +130,7 @@
         return mReadOnlyMeasurements;
     }
 
-    public static final Creator<GnssMeasurementsEvent> CREATOR =
+    public static final @android.annotation.NonNull Creator<GnssMeasurementsEvent> CREATOR =
             new Creator<GnssMeasurementsEvent>() {
         @Override
         public GnssMeasurementsEvent createFromParcel(Parcel in) {
diff --git a/location/java/android/location/GnssNavigationMessage.java b/location/java/android/location/GnssNavigationMessage.java
index c7188aa..a83db3f 100644
--- a/location/java/android/location/GnssNavigationMessage.java
+++ b/location/java/android/location/GnssNavigationMessage.java
@@ -365,7 +365,7 @@
         }
     }
 
-    public static final Creator<GnssNavigationMessage> CREATOR =
+    public static final @android.annotation.NonNull Creator<GnssNavigationMessage> CREATOR =
             new Creator<GnssNavigationMessage>() {
         @Override
         public GnssNavigationMessage createFromParcel(Parcel parcel) {
diff --git a/location/java/android/location/GnssReflectingPlane.java b/location/java/android/location/GnssReflectingPlane.java
index 9a106a7..c5095d7 100644
--- a/location/java/android/location/GnssReflectingPlane.java
+++ b/location/java/android/location/GnssReflectingPlane.java
@@ -76,7 +76,7 @@
         return 0;
     }
 
-    public static final Creator<GnssReflectingPlane> CREATOR =
+    public static final @android.annotation.NonNull Creator<GnssReflectingPlane> CREATOR =
             new Creator<GnssReflectingPlane>() {
                 @Override
                 public GnssReflectingPlane createFromParcel(Parcel parcel) {
diff --git a/location/java/android/location/GnssSingleSatCorrection.java b/location/java/android/location/GnssSingleSatCorrection.java
index f719e1a..dbf3fd9 100644
--- a/location/java/android/location/GnssSingleSatCorrection.java
+++ b/location/java/android/location/GnssSingleSatCorrection.java
@@ -215,7 +215,7 @@
         return 0;
     }
 
-    public static final Creator<GnssSingleSatCorrection> CREATOR =
+    public static final @android.annotation.NonNull Creator<GnssSingleSatCorrection> CREATOR =
             new Creator<GnssSingleSatCorrection>() {
                 @Override
                 public GnssSingleSatCorrection createFromParcel(Parcel parcel) {
diff --git a/location/java/android/location/GpsClock.java b/location/java/android/location/GpsClock.java
index 4135a1c..52ba60e 100644
--- a/location/java/android/location/GpsClock.java
+++ b/location/java/android/location/GpsClock.java
@@ -394,7 +394,7 @@
         mDriftUncertaintyInNsPerSec = Double.NaN;
     }
 
-    public static final Creator<GpsClock> CREATOR = new Creator<GpsClock>() {
+    public static final @android.annotation.NonNull Creator<GpsClock> CREATOR = new Creator<GpsClock>() {
         @Override
         public GpsClock createFromParcel(Parcel parcel) {
             GpsClock gpsClock = new GpsClock();
diff --git a/location/java/android/location/GpsMeasurement.java b/location/java/android/location/GpsMeasurement.java
index f13a440..51718b8 100644
--- a/location/java/android/location/GpsMeasurement.java
+++ b/location/java/android/location/GpsMeasurement.java
@@ -1157,7 +1157,7 @@
         mUsedInFix = value;
     }
 
-    public static final Creator<GpsMeasurement> CREATOR = new Creator<GpsMeasurement>() {
+    public static final @android.annotation.NonNull Creator<GpsMeasurement> CREATOR = new Creator<GpsMeasurement>() {
         @Override
         public GpsMeasurement createFromParcel(Parcel parcel) {
             GpsMeasurement gpsMeasurement = new GpsMeasurement();
diff --git a/location/java/android/location/GpsMeasurementsEvent.java b/location/java/android/location/GpsMeasurementsEvent.java
index 1366873..1cd1fb4 100644
--- a/location/java/android/location/GpsMeasurementsEvent.java
+++ b/location/java/android/location/GpsMeasurementsEvent.java
@@ -103,7 +103,7 @@
         return mReadOnlyMeasurements;
     }
 
-    public static final Creator<GpsMeasurementsEvent> CREATOR =
+    public static final @android.annotation.NonNull Creator<GpsMeasurementsEvent> CREATOR =
             new Creator<GpsMeasurementsEvent>() {
         @Override
         public GpsMeasurementsEvent createFromParcel(Parcel in) {
diff --git a/location/java/android/location/GpsNavigationMessage.java b/location/java/android/location/GpsNavigationMessage.java
index 5c3c710..77f0113 100644
--- a/location/java/android/location/GpsNavigationMessage.java
+++ b/location/java/android/location/GpsNavigationMessage.java
@@ -243,7 +243,7 @@
         }
     }
 
-    public static final Creator<GpsNavigationMessage> CREATOR =
+    public static final @android.annotation.NonNull Creator<GpsNavigationMessage> CREATOR =
             new Creator<GpsNavigationMessage>() {
         @Override
         public GpsNavigationMessage createFromParcel(Parcel parcel) {
diff --git a/location/java/android/location/GpsNavigationMessageEvent.java b/location/java/android/location/GpsNavigationMessageEvent.java
index bd6921c..2aa685c 100644
--- a/location/java/android/location/GpsNavigationMessageEvent.java
+++ b/location/java/android/location/GpsNavigationMessageEvent.java
@@ -84,7 +84,7 @@
         return mNavigationMessage;
     }
 
-    public static final Creator<GpsNavigationMessageEvent> CREATOR =
+    public static final @android.annotation.NonNull Creator<GpsNavigationMessageEvent> CREATOR =
             new Creator<GpsNavigationMessageEvent>() {
                 @Override
                 public GpsNavigationMessageEvent createFromParcel(Parcel in) {
diff --git a/location/java/android/location/IGeocodeProvider.aidl b/location/java/android/location/IGeocodeProvider.aidl
index aaa70c7..7eaf7b8 100644
--- a/location/java/android/location/IGeocodeProvider.aidl
+++ b/location/java/android/location/IGeocodeProvider.aidl
@@ -26,9 +26,11 @@
  */
 interface IGeocodeProvider {
 
+    @UnsupportedAppUsage
     String getFromLocation(double latitude, double longitude, int maxResults,
         in GeocoderParams params, out List<Address> addrs);
 
+    @UnsupportedAppUsage
     String getFromLocationName(String locationName,
         double lowerLeftLatitude, double lowerLeftLongitude,
         double upperRightLatitude, double upperRightLongitude, int maxResults,
diff --git a/location/java/android/location/IGeofenceProvider.aidl b/location/java/android/location/IGeofenceProvider.aidl
index d4ff0dd..426ebef 100644
--- a/location/java/android/location/IGeofenceProvider.aidl
+++ b/location/java/android/location/IGeofenceProvider.aidl
@@ -24,5 +24,6 @@
  * {@hide}
  */
 oneway interface IGeofenceProvider {
+    @UnsupportedAppUsage
     void setGeofenceHardware(in IGeofenceHardware proxy);
 }
diff --git a/location/java/android/location/ILocationListener.aidl b/location/java/android/location/ILocationListener.aidl
index 180183e..ec11345 100644
--- a/location/java/android/location/ILocationListener.aidl
+++ b/location/java/android/location/ILocationListener.aidl
@@ -25,10 +25,14 @@
  */
 oneway interface ILocationListener
 {
+    @UnsupportedAppUsage
     void onLocationChanged(in Location location);
+    @UnsupportedAppUsage
     void onProviderEnabled(String provider);
+    @UnsupportedAppUsage
     void onProviderDisabled(String provider);
 
     // --- deprecated ---
+    @UnsupportedAppUsage
     void onStatusChanged(String provider, int status, in Bundle extras);
 }
diff --git a/location/java/android/location/ILocationManager.aidl b/location/java/android/location/ILocationManager.aidl
index 57a0a72..bb75c77 100644
--- a/location/java/android/location/ILocationManager.aidl
+++ b/location/java/android/location/ILocationManager.aidl
@@ -85,6 +85,7 @@
     boolean stopGnssBatch();
     boolean injectLocation(in Location location);
 
+    @UnsupportedAppUsage
     List<String> getAllProviders();
     List<String> getProviders(in Criteria criteria, boolean enabledOnly);
     String getBestProvider(in Criteria criteria, boolean enabledOnly);
diff --git a/location/java/android/location/INetInitiatedListener.aidl b/location/java/android/location/INetInitiatedListener.aidl
index fc64dd6..a9e9136 100644
--- a/location/java/android/location/INetInitiatedListener.aidl
+++ b/location/java/android/location/INetInitiatedListener.aidl
@@ -22,5 +22,6 @@
  */
 interface INetInitiatedListener
 {
+    @UnsupportedAppUsage
     boolean sendNiResponse(int notifId, int userResponse);
 }
diff --git a/location/java/android/location/Location.java b/location/java/android/location/Location.java
index fbebbb1..17e2509 100644
--- a/location/java/android/location/Location.java
+++ b/location/java/android/location/Location.java
@@ -1084,7 +1084,7 @@
         pw.println(prefix + toString());
     }
 
-    public static final Parcelable.Creator<Location> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<Location> CREATOR =
         new Parcelable.Creator<Location>() {
         @Override
         public Location createFromParcel(Parcel in) {
diff --git a/location/java/android/location/LocationRequest.java b/location/java/android/location/LocationRequest.java
index b3953fd..99b2dee 100644
--- a/location/java/android/location/LocationRequest.java
+++ b/location/java/android/location/LocationRequest.java
@@ -669,7 +669,7 @@
         }
     }
 
-    public static final Parcelable.Creator<LocationRequest> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<LocationRequest> CREATOR =
             new Parcelable.Creator<LocationRequest>() {
                 @Override
                 public LocationRequest createFromParcel(Parcel in) {
diff --git a/location/java/com/android/internal/location/ILocationProvider.aidl b/location/java/com/android/internal/location/ILocationProvider.aidl
index 71b54fb..a571630 100644
--- a/location/java/com/android/internal/location/ILocationProvider.aidl
+++ b/location/java/com/android/internal/location/ILocationProvider.aidl
@@ -36,6 +36,8 @@
     oneway void sendExtraCommand(String command, in Bundle extras);
 
     // --- deprecated and will be removed the future ---
+    @UnsupportedAppUsage
     int getStatus(out Bundle extras);
+    @UnsupportedAppUsage
     long getStatusUpdateTime();
 }
diff --git a/location/java/com/android/internal/location/ILocationProviderManager.aidl b/location/java/com/android/internal/location/ILocationProviderManager.aidl
index 79166ae..85e18ba 100644
--- a/location/java/com/android/internal/location/ILocationProviderManager.aidl
+++ b/location/java/com/android/internal/location/ILocationProviderManager.aidl
@@ -28,9 +28,12 @@
 
     void onSetAdditionalProviderPackages(in List<String> packageNames);
 
+    @UnsupportedAppUsage
     void onSetEnabled(boolean enabled);
 
+    @UnsupportedAppUsage
     void onSetProperties(in ProviderProperties properties);
 
+    @UnsupportedAppUsage
     void onReportLocation(in Location location);
 }
diff --git a/location/lib/api/current.txt b/location/lib/api/current.txt
index dbb581f..d1b39b3 100644
--- a/location/lib/api/current.txt
+++ b/location/lib/api/current.txt
@@ -11,7 +11,7 @@
     method public android.os.IBinder getBinder();
     method public boolean isEnabled();
     method @Deprecated protected void onDisable();
-    method protected void onDump(java.io.FileDescriptor, java.io.PrintWriter, String[]);
+    method @Deprecated protected void onDump(java.io.FileDescriptor, java.io.PrintWriter, String[]);
     method @Deprecated protected void onEnable();
     method @Deprecated protected int onGetStatus(android.os.Bundle);
     method @Deprecated protected long onGetStatusUpdateTime();
diff --git a/location/lib/java/com/android/location/provider/LocationProviderBase.java b/location/lib/java/com/android/location/provider/LocationProviderBase.java
index 7cd7207..fa113a8 100644
--- a/location/lib/java/com/android/location/provider/LocationProviderBase.java
+++ b/location/lib/java/com/android/location/provider/LocationProviderBase.java
@@ -240,8 +240,10 @@
     protected abstract void onSetRequest(ProviderRequestUnbundled request, WorkSource source);
 
     /**
-     * Dump debug information.
+     * @deprecated This callback will never be invoked on Android Q and above. This method may be
+     * removed in the future. Prefer to dump provider state via the containing service instead.
      */
+    @Deprecated
     protected void onDump(FileDescriptor fd, PrintWriter pw, String[] args) {}
 
     /**
@@ -336,10 +338,5 @@
         public void sendExtraCommand(String command, Bundle extras) {
             onSendExtraCommand(command, extras);
         }
-
-        @Override
-        public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
-            onDump(fd, pw, args);
-        }
     }
 }
diff --git a/lowpan/java/android/net/lowpan/LowpanBeaconInfo.java b/lowpan/java/android/net/lowpan/LowpanBeaconInfo.java
index 345a4c5..5d4a3a0 100644
--- a/lowpan/java/android/net/lowpan/LowpanBeaconInfo.java
+++ b/lowpan/java/android/net/lowpan/LowpanBeaconInfo.java
@@ -208,7 +208,7 @@
     }
 
     /** Implement the Parcelable interface. */
-    public static final Creator<LowpanBeaconInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<LowpanBeaconInfo> CREATOR =
             new Creator<LowpanBeaconInfo>() {
                 public LowpanBeaconInfo createFromParcel(Parcel in) {
                     Builder builder = new Builder();
diff --git a/lowpan/java/android/net/lowpan/LowpanChannelInfo.java b/lowpan/java/android/net/lowpan/LowpanChannelInfo.java
index 52b1c6d..12c98b6 100644
--- a/lowpan/java/android/net/lowpan/LowpanChannelInfo.java
+++ b/lowpan/java/android/net/lowpan/LowpanChannelInfo.java
@@ -193,7 +193,7 @@
     }
 
     /** Implement the Parcelable interface. */
-    public static final Creator<LowpanChannelInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<LowpanChannelInfo> CREATOR =
             new Creator<LowpanChannelInfo>() {
 
                 public LowpanChannelInfo createFromParcel(Parcel in) {
diff --git a/lowpan/java/android/net/lowpan/LowpanCredential.java b/lowpan/java/android/net/lowpan/LowpanCredential.java
index e9126f9..dcbb831 100644
--- a/lowpan/java/android/net/lowpan/LowpanCredential.java
+++ b/lowpan/java/android/net/lowpan/LowpanCredential.java
@@ -153,7 +153,7 @@
     }
 
     /** Implement the Parcelable interface. */
-    public static final Creator<LowpanCredential> CREATOR =
+    public static final @android.annotation.NonNull Creator<LowpanCredential> CREATOR =
             new Creator<LowpanCredential>() {
 
                 public LowpanCredential createFromParcel(Parcel in) {
diff --git a/lowpan/java/android/net/lowpan/LowpanIdentity.java b/lowpan/java/android/net/lowpan/LowpanIdentity.java
index 6cb1f98..1997bc4 100644
--- a/lowpan/java/android/net/lowpan/LowpanIdentity.java
+++ b/lowpan/java/android/net/lowpan/LowpanIdentity.java
@@ -233,7 +233,7 @@
     }
 
     /** Implement the Parcelable interface. */
-    public static final Creator<LowpanIdentity> CREATOR =
+    public static final @android.annotation.NonNull Creator<LowpanIdentity> CREATOR =
             new Creator<LowpanIdentity>() {
 
                 public LowpanIdentity createFromParcel(Parcel in) {
diff --git a/lowpan/java/android/net/lowpan/LowpanProvision.java b/lowpan/java/android/net/lowpan/LowpanProvision.java
index f126003..68c8709 100644
--- a/lowpan/java/android/net/lowpan/LowpanProvision.java
+++ b/lowpan/java/android/net/lowpan/LowpanProvision.java
@@ -128,7 +128,7 @@
     }
 
     /** Implement the Parcelable interface. */
-    public static final Creator<LowpanProvision> CREATOR =
+    public static final @android.annotation.NonNull Creator<LowpanProvision> CREATOR =
             new Creator<LowpanProvision>() {
                 public LowpanProvision createFromParcel(Parcel in) {
                     Builder builder = new Builder();
diff --git a/media/apex/java/android/media/BufferingParams.java b/media/apex/java/android/media/BufferingParams.java
index aaae5e7b..83594d4 100644
--- a/media/apex/java/android/media/BufferingParams.java
+++ b/media/apex/java/android/media/BufferingParams.java
@@ -167,7 +167,7 @@
         mResumePlaybackMarkMs = in.readInt();
     }
 
-    public static final Parcelable.Creator<BufferingParams> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<BufferingParams> CREATOR =
             new Parcelable.Creator<BufferingParams>() {
                 @Override
                 public BufferingParams createFromParcel(Parcel in) {
diff --git a/media/apex/java/android/media/Controller2Link.java b/media/apex/java/android/media/Controller2Link.java
index d11f776..04185e7 100644
--- a/media/apex/java/android/media/Controller2Link.java
+++ b/media/apex/java/android/media/Controller2Link.java
@@ -34,7 +34,7 @@
     private static final String TAG = "Controller2Link";
     private static final boolean DEBUG = MediaController2.DEBUG;
 
-    public static final Parcelable.Creator<Controller2Link> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<Controller2Link> CREATOR =
             new Parcelable.Creator<Controller2Link>() {
                 @Override
                 public Controller2Link createFromParcel(Parcel in) {
diff --git a/media/apex/java/android/media/MediaConstants.java b/media/apex/java/android/media/MediaConstants.java
index 65b6f55..776c1ba 100644
--- a/media/apex/java/android/media/MediaConstants.java
+++ b/media/apex/java/android/media/MediaConstants.java
@@ -27,6 +27,7 @@
     static final String KEY_SESSION2LINK = "android.media.key.SESSION2LINK";
     static final String KEY_ALLOWED_COMMANDS = "android.media.key.ALLOWED_COMMANDS";
     static final String KEY_PLAYBACK_ACTIVE = "android.media.key.PLAYBACK_ACTIVE";
+    static final String KEY_TOKEN_EXTRAS = "android.media.key.TOKEN_EXTRAS";
 
     private MediaConstants() {
     }
diff --git a/media/apex/java/android/media/MediaController2.java b/media/apex/java/android/media/MediaController2.java
index 4ea384a..2709df0 100644
--- a/media/apex/java/android/media/MediaController2.java
+++ b/media/apex/java/android/media/MediaController2.java
@@ -21,6 +21,7 @@
 import static android.media.MediaConstants.KEY_PID;
 import static android.media.MediaConstants.KEY_PLAYBACK_ACTIVE;
 import static android.media.MediaConstants.KEY_SESSION2LINK;
+import static android.media.MediaConstants.KEY_TOKEN_EXTRAS;
 import static android.media.Session2Command.RESULT_ERROR_UNKNOWN_ERROR;
 import static android.media.Session2Command.RESULT_INFO_SKIPPED;
 import static android.media.Session2Token.TYPE_SESSION;
@@ -264,6 +265,7 @@
         Session2CommandGroup allowedCommands =
                 connectionResult.getParcelable(KEY_ALLOWED_COMMANDS);
         boolean playbackActive = connectionResult.getBoolean(KEY_PLAYBACK_ACTIVE);
+        Bundle tokenExtras = connectionResult.getBundle(KEY_TOKEN_EXTRAS);
         if (DEBUG) {
             Log.d(TAG, "notifyConnected sessionBinder=" + sessionBinder
                     + ", allowedCommands=" + allowedCommands);
@@ -282,7 +284,7 @@
             // so can be used without worrying about deadlock.
             sessionBinder.linkToDeath(mDeathRecipient, 0);
             mConnectedToken = new Session2Token(mSessionToken.getUid(), TYPE_SESSION,
-                    mSessionToken.getPackageName(), sessionBinder);
+                    mSessionToken.getPackageName(), sessionBinder, tokenExtras);
         }
         mCallbackExecutor.execute(() -> {
             mCallback.onConnected(MediaController2.this, allowedCommands);
diff --git a/media/apex/java/android/media/MediaItem2.java b/media/apex/java/android/media/MediaItem2.java
index c496cf7..fc0f08e 100644
--- a/media/apex/java/android/media/MediaItem2.java
+++ b/media/apex/java/android/media/MediaItem2.java
@@ -55,7 +55,7 @@
      */
     public static final long POSITION_UNKNOWN = LONG_MAX;
 
-    public static final Parcelable.Creator<MediaItem2> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<MediaItem2> CREATOR =
             new Parcelable.Creator<MediaItem2>() {
                 @Override
                 public MediaItem2 createFromParcel(Parcel in) {
diff --git a/media/apex/java/android/media/MediaPlayer2.java b/media/apex/java/android/media/MediaPlayer2.java
index 89a9540..ef30172 100644
--- a/media/apex/java/android/media/MediaPlayer2.java
+++ b/media/apex/java/android/media/MediaPlayer2.java
@@ -962,7 +962,7 @@
                 return;
             }
         } catch (NullPointerException | SecurityException | IOException ex) {
-            Log.w(TAG, "Couldn't open " + uri + ": " + ex);
+            Log.w(TAG, "Couldn't open " + uri == null ? "null uri" : uri.toSafeString(), ex);
             // Fallback to media server
         }
         handleDataSource(isCurrent, srcId, uri.toString(), headers, cookies, startPos, endPos);
diff --git a/media/apex/java/android/media/MediaSession2.java b/media/apex/java/android/media/MediaSession2.java
index 4c6945a..148e16c 100644
--- a/media/apex/java/android/media/MediaSession2.java
+++ b/media/apex/java/android/media/MediaSession2.java
@@ -21,6 +21,7 @@
 import static android.media.MediaConstants.KEY_PID;
 import static android.media.MediaConstants.KEY_PLAYBACK_ACTIVE;
 import static android.media.MediaConstants.KEY_SESSION2LINK;
+import static android.media.MediaConstants.KEY_TOKEN_EXTRAS;
 import static android.media.Session2Command.RESULT_ERROR_UNKNOWN_ERROR;
 import static android.media.Session2Command.RESULT_INFO_SKIPPED;
 import static android.media.Session2Token.TYPE_SESSION;
@@ -94,7 +95,8 @@
     private ForegroundServiceEventCallback mForegroundServiceEventCallback;
 
     MediaSession2(@NonNull Context context, @NonNull String id, PendingIntent sessionActivity,
-            @NonNull Executor callbackExecutor, @NonNull SessionCallback callback) {
+            @NonNull Executor callbackExecutor, @NonNull SessionCallback callback,
+            Bundle tokenExtras) {
         synchronized (MediaSession2.class) {
             if (SESSION_ID_LIST.contains(id)) {
                 throw new IllegalStateException("Session ID must be unique. ID=" + id);
@@ -109,7 +111,7 @@
         mCallback = callback;
         mSessionStub = new Session2Link(this);
         mSessionToken = new Session2Token(Process.myUid(), TYPE_SESSION, context.getPackageName(),
-                mSessionStub);
+                mSessionStub, tokenExtras);
         mSessionManager = (MediaSessionManager) mContext.getSystemService(
                 Context.MEDIA_SESSION_SERVICE);
         // NOTE: mResultHandler uses main looper, so this MUST NOT be blocked.
@@ -339,6 +341,7 @@
                 connectionResult.putParcelable(KEY_ALLOWED_COMMANDS,
                         controllerInfo.mAllowedCommands);
                 connectionResult.putBoolean(KEY_PLAYBACK_ACTIVE, isPlaybackActive());
+                connectionResult.putBundle(KEY_TOKEN_EXTRAS, mSessionToken.getExtras());
 
                 // Double check if session is still there, because close() can be called in
                 // another thread.
@@ -444,6 +447,7 @@
         private PendingIntent mSessionActivity;
         private Executor mCallbackExecutor;
         private SessionCallback mCallback;
+        private Bundle mExtras;
 
         /**
          * Creates a builder for {@link MediaSession2}.
@@ -507,6 +511,18 @@
         }
 
         /**
+         * Set extras for the session token.
+         *
+         * @return The Builder to allow chaining
+         * @see Session2Token#getExtras()
+         */
+        @NonNull
+        public Builder setExtras(@Nullable Bundle extras) {
+            mExtras = extras;
+            return this;
+        }
+
+        /**
          * Build {@link MediaSession2}.
          *
          * @return a new session
@@ -525,7 +541,7 @@
                 mId = "";
             }
             MediaSession2 session2 = new MediaSession2(mContext, mId, mSessionActivity,
-                    mCallbackExecutor, mCallback);
+                    mCallbackExecutor, mCallback, mExtras);
 
             // Notify framework about the newly create session after the constructor is finished.
             // Otherwise, framework may access the session before the initialization is finished.
diff --git a/media/apex/java/android/media/Session2Command.java b/media/apex/java/android/media/Session2Command.java
index 8b285f2..20d6391 100644
--- a/media/apex/java/android/media/Session2Command.java
+++ b/media/apex/java/android/media/Session2Command.java
@@ -60,7 +60,7 @@
      */
     public static final int RESULT_ERROR_UNKNOWN_ERROR = -1;
 
-    public static final Parcelable.Creator<Session2Command> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<Session2Command> CREATOR =
             new Parcelable.Creator<Session2Command>() {
                 @Override
                 public Session2Command createFromParcel(Parcel in) {
diff --git a/media/apex/java/android/media/Session2CommandGroup.java b/media/apex/java/android/media/Session2CommandGroup.java
index 2dab697..73a59d0 100644
--- a/media/apex/java/android/media/Session2CommandGroup.java
+++ b/media/apex/java/android/media/Session2CommandGroup.java
@@ -39,7 +39,7 @@
 public final class Session2CommandGroup implements Parcelable {
     private static final String TAG = "Session2CommandGroup";
 
-    public static final Parcelable.Creator<Session2CommandGroup> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<Session2CommandGroup> CREATOR =
             new Parcelable.Creator<Session2CommandGroup>() {
                 @Override
                 public Session2CommandGroup createFromParcel(Parcel in) {
diff --git a/media/apex/java/android/media/Session2Link.java b/media/apex/java/android/media/Session2Link.java
index 08664aa..6e550e8 100644
--- a/media/apex/java/android/media/Session2Link.java
+++ b/media/apex/java/android/media/Session2Link.java
@@ -37,7 +37,7 @@
     private static final String TAG = "Session2Link";
     private static final boolean DEBUG = MediaSession2.DEBUG;
 
-    public static final Parcelable.Creator<Session2Link> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<Session2Link> CREATOR =
             new Parcelable.Creator<Session2Link>() {
                 @Override
                 public Session2Link createFromParcel(Parcel in) {
diff --git a/media/apex/java/android/media/Session2Token.java b/media/apex/java/android/media/Session2Token.java
index 238cc2b..dc970ae 100644
--- a/media/apex/java/android/media/Session2Token.java
+++ b/media/apex/java/android/media/Session2Token.java
@@ -24,6 +24,7 @@
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
+import android.os.Bundle;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.text.TextUtils;
@@ -51,7 +52,7 @@
 public final class Session2Token implements Parcelable {
     private static final String TAG = "Session2Token";
 
-    public static final Creator<Session2Token> CREATOR = new Creator<Session2Token>() {
+    public static final @android.annotation.NonNull Creator<Session2Token> CREATOR = new Creator<Session2Token>() {
         @Override
         public Session2Token createFromParcel(Parcel p) {
             return new Session2Token(p);
@@ -88,6 +89,7 @@
     private final String mServiceName;
     private final Session2Link mSessionLink;
     private final ComponentName mComponentName;
+    private final Bundle mExtras;
 
     /**
      * Constructor for the token with type {@link #TYPE_SESSION_SERVICE}.
@@ -116,15 +118,18 @@
         mUid = uid;
         mType = TYPE_SESSION_SERVICE;
         mSessionLink = null;
+        mExtras = null;
     }
 
-    Session2Token(int uid, int type, String packageName, Session2Link sessionLink) {
+    Session2Token(int uid, int type, String packageName, Session2Link sessionLink,
+            Bundle tokenExtras) {
         mUid = uid;
         mType = type;
         mPackageName = packageName;
         mServiceName = null;
         mComponentName = null;
         mSessionLink = sessionLink;
+        mExtras = tokenExtras;
     }
 
     Session2Token(Parcel in) {
@@ -134,6 +139,7 @@
         mServiceName = in.readString();
         mSessionLink = in.readParcelable(null);
         mComponentName = ComponentName.unflattenFromString(in.readString());
+        mExtras = in.readBundle();
     }
 
     @Override
@@ -144,6 +150,7 @@
         dest.writeString(mServiceName);
         dest.writeParcelable(mSessionLink, flags);
         dest.writeString(mComponentName == null ? "" : mComponentName.flattenToString());
+        dest.writeBundle(mExtras);
     }
 
     @Override
@@ -207,6 +214,14 @@
         return mType;
     }
 
+    /**
+     * @return extras of the token
+     */
+    @Nullable
+    public Bundle getExtras() {
+        return mExtras;
+    }
+
     Session2Link getSessionLink() {
         return mSessionLink;
     }
diff --git a/media/java/android/media/AudioAttributes.java b/media/java/android/media/AudioAttributes.java
index ea396c6..46d4204 100644
--- a/media/java/android/media/AudioAttributes.java
+++ b/media/java/android/media/AudioAttributes.java
@@ -877,7 +877,7 @@
         }
     }
 
-    public static final Parcelable.Creator<AudioAttributes> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AudioAttributes> CREATOR
             = new Parcelable.Creator<AudioAttributes>() {
         /**
          * Rebuilds an AudioAttributes previously stored with writeToParcel().
diff --git a/media/java/android/media/AudioFocusInfo.java b/media/java/android/media/AudioFocusInfo.java
index 3594ee7..3aaa7df 100644
--- a/media/java/android/media/AudioFocusInfo.java
+++ b/media/java/android/media/AudioFocusInfo.java
@@ -190,7 +190,7 @@
         return true;
     }
 
-    public static final Parcelable.Creator<AudioFocusInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AudioFocusInfo> CREATOR
             = new Parcelable.Creator<AudioFocusInfo>() {
 
         public AudioFocusInfo createFromParcel(Parcel in) {
diff --git a/media/java/android/media/AudioFormat.java b/media/java/android/media/AudioFormat.java
index 5516086..f0787e9 100644
--- a/media/java/android/media/AudioFormat.java
+++ b/media/java/android/media/AudioFormat.java
@@ -1096,7 +1096,7 @@
             );
     }
 
-    public static final Parcelable.Creator<AudioFormat> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AudioFormat> CREATOR =
             new Parcelable.Creator<AudioFormat>() {
         public AudioFormat createFromParcel(Parcel p) {
             return new AudioFormat(p);
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index bd828ee..15f9b47 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -36,6 +36,9 @@
 import android.content.Intent;
 import android.media.audiopolicy.AudioPolicy;
 import android.media.audiopolicy.AudioPolicy.AudioPolicyFocusListener;
+import android.media.audiopolicy.AudioProductStrategies;
+import android.media.audiopolicy.AudioVolumeGroupChangeHandler;
+import android.media.audiopolicy.AudioVolumeGroups;
 import android.media.projection.MediaProjection;
 import android.media.session.MediaController;
 import android.media.session.MediaSession;
@@ -60,6 +63,7 @@
 import android.view.KeyEvent;
 
 import com.android.internal.annotations.GuardedBy;
+import com.android.internal.util.Preconditions;
 
 import java.io.IOException;
 import java.lang.annotation.Retention;
@@ -89,6 +93,8 @@
     private static final String TAG = "AudioManager";
     private static final boolean DEBUG = false;
     private static final AudioPortEventHandler sAudioPortEventHandler = new AudioPortEventHandler();
+    private static final AudioVolumeGroupChangeHandler sAudioAudioVolumeGroupChangedHandler =
+            new AudioVolumeGroupChangeHandler();
 
     /**
      * Broadcast intent, a hint for applications that audio is about to become
@@ -1163,6 +1169,93 @@
     }
 
     /**
+     * Sets the volume index for a particular {@link AudioAttributes}.
+     * @param attr The {@link AudioAttributes} whose volume index should be set.
+     * @param index The volume index to set. See
+     *          {@link #getMaxVolumeIndexForAttributes(AudioAttributes)} for the largest valid value
+     *          {@link #getMinVolumeIndexForAttributes(AudioAttributes)} for the lowest valid value.
+     * @param flags One or more flags.
+     * @see #getMaxVolumeIndexForAttributes(AudioAttributes)
+     * @see #getMinVolumeIndexForAttributes(AudioAttributes)
+     * @see #isVolumeFixed()
+     * @hide
+     */
+    @SystemApi
+    @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
+    public void setVolumeIndexForAttributes(@NonNull AudioAttributes attr, int index, int flags) {
+        Preconditions.checkNotNull(attr, "attr must not be null");
+        final IAudioService service = getService();
+        try {
+            service.setVolumeIndexForAttributes(attr, index, flags,
+                                                getContext().getOpPackageName());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Returns the current volume index for a particular {@link AudioAttributes}.
+     *
+     * @param attr The {@link AudioAttributes} whose volume index is returned.
+     * @return The current volume index for the stream.
+     * @see #getMaxVolumeIndexForAttributes(AudioAttributes)
+     * @see #getMinVolumeIndexForAttributes(AudioAttributes)
+     * @see #setVolumeForAttributes(AudioAttributes, int, int)
+     * @hide
+     */
+    @SystemApi
+    @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
+    public int getVolumeIndexForAttributes(@NonNull AudioAttributes attr) {
+        Preconditions.checkNotNull(attr, "attr must not be null");
+        final IAudioService service = getService();
+        try {
+            return service.getVolumeIndexForAttributes(attr);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Returns the maximum volume index for a particular {@link AudioAttributes}.
+     *
+     * @param attr The {@link AudioAttributes} whose maximum volume index is returned.
+     * @return The maximum valid volume index for the {@link AudioAttributes}.
+     * @see #getVolumeIndexForAttributes(AudioAttributes)
+     * @hide
+     */
+    @SystemApi
+    @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
+    public int getMaxVolumeIndexForAttributes(@NonNull AudioAttributes attr) {
+        Preconditions.checkNotNull(attr, "attr must not be null");
+        final IAudioService service = getService();
+        try {
+            return service.getMaxVolumeIndexForAttributes(attr);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Returns the minimum volume index for a particular {@link AudioAttributes}.
+     *
+     * @param attr The {@link AudioAttributes} whose minimum volume index is returned.
+     * @return The minimum valid volume index for the {@link AudioAttributes}.
+     * @see #getVolumeIndexForAttributes(AudioAttributes)
+     * @hide
+     */
+    @SystemApi
+    @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
+    public int getMinVolumeIndexForAttributes(@NonNull AudioAttributes attr) {
+        Preconditions.checkNotNull(attr, "attr must not be null");
+        final IAudioService service = getService();
+        try {
+            return service.getMinVolumeIndexForAttributes(attr);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Solo or unsolo a particular stream.
      * <p>
      * Do not use. This method has been deprecated and is now a no-op.
@@ -5221,6 +5314,89 @@
         return AudioSystem.isHapticPlaybackSupported();
     }
 
+    /**
+     * @hide
+     * Introspection API to retrieve audio product strategies.
+     * When implementing {Car|Oem}AudioManager, use this method  to retrieve the collection of
+     * audio product strategies, which is indexed by a weakly typed index in order to be extended
+     * by OEM without any needs of AOSP patches.
+     * The {Car|Oem}AudioManager can expose API to build {@link AudioAttributes} for a given product
+     * strategy refered either by its index or human readable string. It will allow clients
+     * application to start streaming data using these {@link AudioAttributes} on the selected
+     * device by Audio Policy Engine.
+     * @return a (possibly zero-length) array of
+     *         {@see android.media.audiopolicy.AudioProductStrategy} objects.
+     */
+    @SystemApi
+    @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
+    public @NonNull AudioProductStrategies getAudioProductStrategies() {
+        final IAudioService service = getService();
+        try {
+            return service.getAudioProductStrategies();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * @hide
+     * Introspection API to retrieve audio volume groups.
+     * When implementing {Car|Oem}AudioManager, use this method  to retrieve the collection of
+     * audio volume groups.
+     * @return a (possibly zero-length) array of
+     *         {@see android.media.audiopolicy.AudioVolumeGroups} objects.
+     */
+    @SystemApi
+    @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
+    public @NonNull AudioVolumeGroups getAudioVolumeGroups() {
+        final IAudioService service = getService();
+        try {
+            return service.listAudioVolumeGroups();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * @hide
+     * Callback registered by client to be notified upon volume group change.
+     */
+    @SystemApi
+    public abstract static class VolumeGroupCallback {
+        /**
+         * Callback method called upon audio volume group change.
+         * @param group the group for which the volume has changed
+         */
+        public void onAudioVolumeGroupChanged(int group, int flags) {}
+    }
+
+   /**
+    * @hide
+    * Register an audio volume group change listener.
+    * @param callback the {@link VolumeGroupCallback} to register
+    */
+    @SystemApi
+    public void registerVolumeGroupCallback(
+            @NonNull Executor executor,
+            @NonNull VolumeGroupCallback callback) {
+        Preconditions.checkNotNull(executor, "executor must not be null");
+        Preconditions.checkNotNull(callback, "volume group change cb must not be null");
+        sAudioAudioVolumeGroupChangedHandler.init();
+        // TODO: make use of executor
+        sAudioAudioVolumeGroupChangedHandler.registerListener(callback);
+    }
+
+   /**
+    * @hide
+    * Unregister an audio volume group change listener.
+    * @param callback the {@link VolumeGroupCallback} to unregister
+    */
+    @SystemApi
+    public void unregisterVolumeGroupCallback(
+            @NonNull VolumeGroupCallback callback) {
+        Preconditions.checkNotNull(callback, "volume group change cb must not be null");
+        sAudioAudioVolumeGroupChangedHandler.unregisterListener(callback);
+    }
 
     //---------------------------------------------------------
     // Inner classes
diff --git a/media/java/android/media/AudioPlaybackCaptureConfiguration.java b/media/java/android/media/AudioPlaybackCaptureConfiguration.java
index d714dc7..9a16aea 100644
--- a/media/java/android/media/AudioPlaybackCaptureConfiguration.java
+++ b/media/java/android/media/AudioPlaybackCaptureConfiguration.java
@@ -33,7 +33,7 @@
  *  - played by apps that MUST be in the same user profile as the capturing app
  *    (eg work profile can not capture user profile apps and vice-versa).
  *  - played by apps that MUST NOT have in their manifest.xml the application
- *    attribute android:allowPlaybackCapture="false"
+ *    attribute android:allowAudioPlaybackCapture="false"
  *  - played by apps that MUST have a targetSdkVersion higher or equal to 29 (Q).
  *
  * <p>An example for creating a capture configuration for capturing all media playback:
diff --git a/media/java/android/media/AudioPlaybackConfiguration.java b/media/java/android/media/AudioPlaybackConfiguration.java
index 7dfdb20..5d12c3c 100644
--- a/media/java/android/media/AudioPlaybackConfiguration.java
+++ b/media/java/android/media/AudioPlaybackConfiguration.java
@@ -430,7 +430,7 @@
                 + " -- attr:" + apc.mPlayerAttr);
     }
 
-    public static final Parcelable.Creator<AudioPlaybackConfiguration> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AudioPlaybackConfiguration> CREATOR
             = new Parcelable.Creator<AudioPlaybackConfiguration>() {
         /**
          * Rebuilds an AudioPlaybackConfiguration previously stored with writeToParcel().
diff --git a/media/java/android/media/AudioPresentation.java b/media/java/android/media/AudioPresentation.java
index fca7074..894fbba 100644
--- a/media/java/android/media/AudioPresentation.java
+++ b/media/java/android/media/AudioPresentation.java
@@ -45,6 +45,9 @@
  * accessibility, end point mastering and dialogue enhancement. An audio presentation may also have
  * a set of description labels in different languages to help the user to make an informed
  * selection.
+ *
+ * Applications that parse media streams and extract presentation information on their own
+ * can create instances of AudioPresentation by using {@link AudioPresentation.Builder} class.
  */
 public final class AudioPresentation {
     private final int mPresentationId;
@@ -66,7 +69,7 @@
     private final boolean mAudioDescriptionAvailable;
     private final boolean mSpokenSubtitlesAvailable;
     private final boolean mDialogueEnhancementAvailable;
-    private final Map<ULocale, String> mLabels;
+    private final Map<ULocale, CharSequence> mLabels;
 
     /**
      * No preferred reproduction channel layout.
@@ -131,7 +134,7 @@
                              boolean audioDescriptionAvailable,
                              boolean spokenSubtitlesAvailable,
                              boolean dialogueEnhancementAvailable,
-                             @NonNull Map<ULocale, String> labels) {
+                             @NonNull Map<ULocale, CharSequence> labels) {
         mPresentationId = presentationId;
         mProgramId = programId;
         mLanguage = language;
@@ -139,7 +142,7 @@
         mAudioDescriptionAvailable = audioDescriptionAvailable;
         mSpokenSubtitlesAvailable = spokenSubtitlesAvailable;
         mDialogueEnhancementAvailable = dialogueEnhancementAvailable;
-        mLabels = new HashMap<ULocale, String>(labels);
+        mLabels = new HashMap<ULocale, CharSequence>(labels);
     }
 
     /**
@@ -164,14 +167,14 @@
      * or ISO 639-2/T could be used.
      */
     public Map<Locale, String> getLabels() {
-        Map<Locale, String> localeLabels = new HashMap<Locale, String>();
-        for (Map.Entry<ULocale, String> entry : mLabels.entrySet()) {
-            localeLabels.put(entry.getKey().toLocale(), entry.getValue());
+        Map<Locale, String> localeLabels = new HashMap<Locale, String>(mLabels.size());
+        for (Map.Entry<ULocale, CharSequence> entry : mLabels.entrySet()) {
+            localeLabels.put(entry.getKey().toLocale(), entry.getValue().toString());
         }
         return localeLabels;
     }
 
-    private Map<ULocale, String> getULabels() {
+    private Map<ULocale, CharSequence> getULabels() {
         return mLabels;
     }
 
@@ -273,7 +276,7 @@
     /**
      * A builder class for creating {@link AudioPresentation} objects.
      */
-    public static class Builder {
+    public static final class Builder {
         private final int mPresentationId;
         private int mProgramId = UNKNOWN_ID;
         private ULocale mLanguage = new ULocale("");
@@ -281,13 +284,13 @@
         private boolean mAudioDescriptionAvailable = false;
         private boolean mSpokenSubtitlesAvailable = false;
         private boolean mDialogueEnhancementAvailable = false;
-        private Map<ULocale, String> mLabels = new HashMap<ULocale, String>();
+        private Map<ULocale, CharSequence> mLabels = new HashMap<ULocale, CharSequence>();
 
         /**
          * Create a {@link Builder}. Any field that should be included in the
          * {@link AudioPresentation} must be added.
          *
-         * @param presentationId the presentation ID of this audio presentation
+         * @param presentationId The presentation ID of this audio presentation.
          */
         public Builder(int presentationId) {
             mPresentationId = presentationId;
@@ -295,7 +298,7 @@
         /**
          * Sets the ProgramId to which this audio presentation refers.
          *
-         * @param programId
+         * @param programId The program ID to be decoded.
          */
         public @NonNull Builder setProgramId(int programId) {
             mProgramId = programId;
@@ -304,9 +307,9 @@
         /**
          * Sets the language information of the audio presentation.
          *
-         * @param language code
+         * @param language Locale corresponding to ISO 639-1/639-2 language code.
          */
-        public @NonNull Builder setLocale(ULocale language) {
+        public @NonNull Builder setLocale(@NonNull ULocale language) {
             mLanguage = language;
             return this;
         }
@@ -339,17 +342,17 @@
         /**
          * Sets locale / text label pairs describing the presentation.
          *
-         * @param labels
+         * @param labels Text label indexed by its locale corresponding to the language code.
          */
-        public @NonNull Builder setLabels(@NonNull Map<ULocale, String> labels) {
-            mLabels = new HashMap<ULocale, String>(labels);
+        public @NonNull Builder setLabels(@NonNull Map<ULocale, CharSequence> labels) {
+            mLabels = new HashMap<ULocale, CharSequence>(labels);
             return this;
         }
 
         /**
          * Indicate whether the presentation contains audio description for the visually impaired.
          *
-         * @param audioDescriptionAvailable
+         * @param audioDescriptionAvailable Audio description for the visually impaired.
          */
         public @NonNull Builder setHasAudioDescription(boolean audioDescriptionAvailable) {
             mAudioDescriptionAvailable = audioDescriptionAvailable;
@@ -359,7 +362,7 @@
         /**
          * Indicate whether the presentation contains spoken subtitles for the visually impaired.
          *
-         * @param spokenSubtitlesAvailable
+         * @param spokenSubtitlesAvailable Spoken subtitles for the visually impaired.
          */
         public @NonNull Builder setHasSpokenSubtitles(boolean spokenSubtitlesAvailable) {
             mSpokenSubtitlesAvailable = spokenSubtitlesAvailable;
@@ -369,7 +372,7 @@
         /**
          * Indicate whether the presentation supports dialogue enhancement.
          *
-         * @param dialogueEnhancementAvailable
+         * @param dialogueEnhancementAvailable Dialogue enhancement.
          */
         public @NonNull Builder setHasDialogueEnhancement(boolean dialogueEnhancementAvailable) {
             mDialogueEnhancementAvailable = dialogueEnhancementAvailable;
diff --git a/media/java/android/media/AudioRecord.java b/media/java/android/media/AudioRecord.java
index ec1a854..3d5120f 100644
--- a/media/java/android/media/AudioRecord.java
+++ b/media/java/android/media/AudioRecord.java
@@ -653,7 +653,16 @@
             AudioPolicy audioPolicy = new AudioPolicy.Builder(/*context=*/ null)
                     .setMediaProjection(projection)
                     .addMix(audioMix).build();
+
+            int error = AudioManager.registerAudioPolicyStatic(audioPolicy);
+            if (error != 0) {
+                throw new UnsupportedOperationException("Error: could not register audio policy");
+            }
+
             AudioRecord record = audioPolicy.createAudioRecordSink(audioMix);
+            if (record == null) {
+                throw new UnsupportedOperationException("Cannot create AudioRecord");
+            }
             record.unregisterAudioPolicyOnRelease(audioPolicy);
             return record;
         }
diff --git a/media/java/android/media/AudioRecordingConfiguration.java b/media/java/android/media/AudioRecordingConfiguration.java
index 0af47e8..82bcbc1 100644
--- a/media/java/android/media/AudioRecordingConfiguration.java
+++ b/media/java/android/media/AudioRecordingConfiguration.java
@@ -317,7 +317,7 @@
         return new ArrayList<AudioEffect.Descriptor>(Arrays.asList(mDeviceEffects));
     }
 
-    public static final Parcelable.Creator<AudioRecordingConfiguration> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AudioRecordingConfiguration> CREATOR
             = new Parcelable.Creator<AudioRecordingConfiguration>() {
         /**
          * Rebuilds an AudioRecordingConfiguration previously stored with writeToParcel().
diff --git a/media/java/android/media/AudioRoutesInfo.java b/media/java/android/media/AudioRoutesInfo.java
index 83cd797..46df388 100644
--- a/media/java/android/media/AudioRoutesInfo.java
+++ b/media/java/android/media/AudioRoutesInfo.java
@@ -76,7 +76,7 @@
         dest.writeInt(mainType);
     }
 
-    public static final Parcelable.Creator<AudioRoutesInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AudioRoutesInfo> CREATOR
             = new Parcelable.Creator<AudioRoutesInfo>() {
         public AudioRoutesInfo createFromParcel(Parcel in) {
             return new AudioRoutesInfo(in);
diff --git a/media/java/android/media/AudioSystem.java b/media/java/android/media/AudioSystem.java
index 9218e92..a976d70 100644
--- a/media/java/android/media/AudioSystem.java
+++ b/media/java/android/media/AudioSystem.java
@@ -40,7 +40,7 @@
  */
 public class AudioSystem
 {
-    private static final boolean DEBUG_VOLUME = true;
+    private static final boolean DEBUG_VOLUME = false;
 
     private static final String TAG = "AudioSystem";
     /* These values must be kept in sync with system/audio.h */
@@ -920,6 +920,41 @@
     @UnsupportedAppUsage
     private static native int setStreamVolumeIndex(int stream, int index, int device);
     public static native int getStreamVolumeIndex(int stream, int device);
+    /**
+     * @hide
+     * set a volume for the given {@link AudioAttributes} and for all other stream that belong to
+     * the same volume group.
+     * @param attributes the {@link AudioAttributes} to be considered
+     * @param index to be applied
+     * @param device the volume device to be considered
+     * @return command completion status.
+     */
+    public static native int setVolumeIndexForAttributes(@NonNull AudioAttributes attributes,
+                                                         int index, int device);
+   /**
+    * @hide
+    * get the volume index for the given {@link AudioAttributes}.
+    * @param attributes the {@link AudioAttributes} to be considered
+    * @param device the volume device to be considered
+    * @return volume index for the given {@link AudioAttributes} and volume device.
+    */
+    public static native int getVolumeIndexForAttributes(@NonNull AudioAttributes attributes,
+                                                         int device);
+    /**
+     * @hide
+     * get the minimum volume index for the given {@link AudioAttributes}.
+     * @param attributes the {@link AudioAttributes} to be considered
+     * @return minimum volume index for the given {@link AudioAttributes}.
+     */
+    public static native int getMinVolumeIndexForAttributes(@NonNull AudioAttributes attributes);
+    /**
+     * @hide
+     * get the maximum volume index for the given {@link AudioAttributes}.
+     * @param attributes the {@link AudioAttributes} to be considered
+     * @return maximum volume index for the given {@link AudioAttributes}.
+     */
+    public static native int getMaxVolumeIndexForAttributes(@NonNull AudioAttributes attributes);
+
     public static native int setMasterVolume(float value);
     public static native float getMasterVolume();
     @UnsupportedAppUsage
diff --git a/media/java/android/media/IAudioFocusDispatcher.aidl b/media/java/android/media/IAudioFocusDispatcher.aidl
index 3b33c5b..e3512fa 100644
--- a/media/java/android/media/IAudioFocusDispatcher.aidl
+++ b/media/java/android/media/IAudioFocusDispatcher.aidl
@@ -23,6 +23,7 @@
  */
 oneway interface IAudioFocusDispatcher {
 
+    @UnsupportedAppUsage
     void dispatchAudioFocusChange(int focusChange, String clientId);
 
     void dispatchFocusResultFromExtPolicy(int requestResult, String clientId);
diff --git a/media/java/android/media/IAudioService.aidl b/media/java/android/media/IAudioService.aidl
index 571e67e..1b82fcc 100644
--- a/media/java/android/media/IAudioService.aidl
+++ b/media/java/android/media/IAudioService.aidl
@@ -33,6 +33,8 @@
 import android.media.PlayerBase;
 import android.media.VolumePolicy;
 import android.media.audiopolicy.AudioPolicyConfig;
+import android.media.audiopolicy.AudioProductStrategies;
+import android.media.audiopolicy.AudioVolumeGroups;
 import android.media.audiopolicy.IAudioPolicyCallback;
 import android.media.projection.IMediaProjection;
 
@@ -64,6 +66,7 @@
 
     void adjustStreamVolume(int streamType, int direction, int flags, String callingPackage);
 
+    @UnsupportedAppUsage
     void setStreamVolume(int streamType, int index, int flags, String callingPackage);
 
     boolean isStreamMute(int streamType);
@@ -74,14 +77,28 @@
 
     void setMasterMute(boolean mute, int flags, String callingPackage, int userId);
 
+    @UnsupportedAppUsage
     int getStreamVolume(int streamType);
 
     int getStreamMinVolume(int streamType);
 
+    @UnsupportedAppUsage
     int getStreamMaxVolume(int streamType);
 
+    AudioVolumeGroups listAudioVolumeGroups();
+
+    void setVolumeIndexForAttributes(in AudioAttributes aa, int index, int flags, String callingPackage);
+
+    int getVolumeIndexForAttributes(in AudioAttributes aa);
+
+    int getMaxVolumeIndexForAttributes(in AudioAttributes aa);
+
+    int getMinVolumeIndexForAttributes(in AudioAttributes aa);
+
     int getLastAudibleStreamVolume(int streamType);
 
+    AudioProductStrategies getAudioProductStrategies();
+
     void setMicrophoneMute(boolean on, String callingPackage, int userId);
 
     void setRingerModeExternal(int ringerMode, String caller);
@@ -157,6 +174,7 @@
     int handleBluetoothA2dpActiveDeviceChange(in BluetoothDevice device,
             int state, int profile, boolean suppressNoisyIntent, int a2dpVolume);
 
+    @UnsupportedAppUsage
     AudioRoutesInfo startWatchingRoutes(in IAudioRoutesObserver observer);
 
     boolean isCameraSoundForced();
diff --git a/media/java/android/media/IMediaScannerService.aidl b/media/java/android/media/IMediaScannerService.aidl
index c531646..24b5595 100644
--- a/media/java/android/media/IMediaScannerService.aidl
+++ b/media/java/android/media/IMediaScannerService.aidl
@@ -31,6 +31,7 @@
      * @param listener an optional IMediaScannerListener. 
      * If specified, the caller will be notified when scanning is complete via the listener.
      */
+    @UnsupportedAppUsage
     void requestScanFile(String path, String mimeType, in IMediaScannerListener listener);
 
     /**
@@ -40,5 +41,6 @@
      * @param mimeType  an optional mimeType for the file.
      * If mimeType is null, then the mimeType will be inferred from the file extension.
      */
+    @UnsupportedAppUsage
     void scanFile(String path, String mimeType);
 }
diff --git a/media/java/android/media/IRemoteDisplayCallback.aidl b/media/java/android/media/IRemoteDisplayCallback.aidl
index 19cf070..584417d 100644
--- a/media/java/android/media/IRemoteDisplayCallback.aidl
+++ b/media/java/android/media/IRemoteDisplayCallback.aidl
@@ -22,5 +22,6 @@
  * {@hide}
  */
 oneway interface IRemoteDisplayCallback {
+    @UnsupportedAppUsage
     void onStateChanged(in RemoteDisplayState state);
 }
diff --git a/media/java/android/media/MediaDescription.java b/media/java/android/media/MediaDescription.java
index 39eeb3e..458562a 100644
--- a/media/java/android/media/MediaDescription.java
+++ b/media/java/android/media/MediaDescription.java
@@ -268,7 +268,7 @@
         return mTitle + ", " + mSubtitle + ", " + mDescription;
     }
 
-    public static final Parcelable.Creator<MediaDescription> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<MediaDescription> CREATOR =
             new Parcelable.Creator<MediaDescription>() {
                 @Override
                 public MediaDescription createFromParcel(Parcel in) {
diff --git a/media/java/android/media/MediaHTTPConnection.java b/media/java/android/media/MediaHTTPConnection.java
index 5f324f7..d724762 100644
--- a/media/java/android/media/MediaHTTPConnection.java
+++ b/media/java/android/media/MediaHTTPConnection.java
@@ -37,7 +37,6 @@
 import java.net.UnknownServiceException;
 import java.util.HashMap;
 import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
 
 /** @hide */
 public class MediaHTTPConnection extends IMediaHTTPConnection.Stub {
@@ -67,7 +66,6 @@
     // from com.squareup.okhttp.internal.http
     private final static int HTTP_TEMP_REDIRECT = 307;
     private final static int MAX_REDIRECTS = 20;
-    private AtomicBoolean mIsConnected = new AtomicBoolean(false);
 
     @UnsupportedAppUsage
     public MediaHTTPConnection() {
@@ -91,7 +89,6 @@
             mAllowCrossDomainRedirect = true;
             mURL = new URL(uri);
             mHeaders = convertHeaderStringToMap(headers);
-            mIsConnected.set(true);
         } catch (MalformedURLException e) {
             return null;
         }
@@ -142,14 +139,7 @@
     @Override
     @UnsupportedAppUsage
     public void disconnect() {
-        if (mIsConnected.getAndSet(false)) {
-            (new Thread() {
-                @Override
-                public void run() {
-                    teardownConnection();
-                }
-            }).start();
-        }
+        teardownConnection();
         mHeaders = null;
         mURL = null;
     }
@@ -334,14 +324,7 @@
     @Override
     @UnsupportedAppUsage
     public int readAt(long offset, int size) {
-        if (!mIsConnected.get()) {
-            return -1;
-        }
-        int result = native_readAt(offset, size);
-        if (!mIsConnected.get()) {
-            return -1;
-        }
-        return result;
+        return native_readAt(offset, size);
     }
 
     private int readAt(long offset, byte[] data, int size) {
diff --git a/media/java/android/media/MediaMetadata.java b/media/java/android/media/MediaMetadata.java
index dea98d5..8512dbe 100644
--- a/media/java/android/media/MediaMetadata.java
+++ b/media/java/android/media/MediaMetadata.java
@@ -632,7 +632,7 @@
         return EDITOR_KEY_MAPPING.get(editorKey, null);
     }
 
-    public static final Parcelable.Creator<MediaMetadata> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<MediaMetadata> CREATOR =
             new Parcelable.Creator<MediaMetadata>() {
                 @Override
                 public MediaMetadata createFromParcel(Parcel in) {
diff --git a/media/java/android/media/MediaParceledListSlice.java b/media/java/android/media/MediaParceledListSlice.java
index 16a37d9..e90d9a4 100644
--- a/media/java/android/media/MediaParceledListSlice.java
+++ b/media/java/android/media/MediaParceledListSlice.java
@@ -185,7 +185,7 @@
         return contents;
     }
 
-    public static final Parcelable.Creator<MediaParceledListSlice> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<MediaParceledListSlice> CREATOR =
             new Parcelable.Creator<MediaParceledListSlice>() {
         @Override
         public MediaParceledListSlice createFromParcel(Parcel in) {
diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java
index e4d356b..abbfa88 100644
--- a/media/java/android/media/MediaPlayer.java
+++ b/media/java/android/media/MediaPlayer.java
@@ -1103,7 +1103,7 @@
             setDataSource(afd);
             return true;
         } catch (NullPointerException | SecurityException | IOException ex) {
-            Log.w(TAG, "Couldn't open " + uri + ": " + ex);
+            Log.w(TAG, "Couldn't open " + uri == null ? "null uri" : uri.toSafeString(), ex);
             return false;
         }
     }
@@ -2519,7 +2519,7 @@
          * Used to read a TrackInfo from a Parcel.
          */
         @UnsupportedAppUsage
-        static final Parcelable.Creator<TrackInfo> CREATOR
+        static final @android.annotation.NonNull Parcelable.Creator<TrackInfo> CREATOR
                 = new Parcelable.Creator<TrackInfo>() {
                     @Override
                     public TrackInfo createFromParcel(Parcel in) {
@@ -2645,6 +2645,7 @@
      */
     private synchronized void setSubtitleAnchor() {
         if ((mSubtitleController == null) && (ActivityThread.currentApplication() != null)) {
+            getMediaTimeProvider();
             final HandlerThread thread = new HandlerThread("SetSubtitleAnchorThread");
             thread.start();
             Handler handler = new Handler(thread.getLooper());
@@ -2660,7 +2661,7 @@
 
                         @Override
                         public Looper getSubtitleLooper() {
-                            return Looper.getMainLooper();
+                            return mTimeProvider.mEventHandler.getLooper();
                         }
                     });
                     thread.getLooper().quitSafely();
diff --git a/media/java/android/media/MediaRouterClientState.java b/media/java/android/media/MediaRouterClientState.java
index 7643924..1fe4eef 100644
--- a/media/java/android/media/MediaRouterClientState.java
+++ b/media/java/android/media/MediaRouterClientState.java
@@ -68,7 +68,7 @@
         return "MediaRouterClientState{ routes=" + routes.toString() + " }";
     }
 
-    public static final Parcelable.Creator<MediaRouterClientState> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<MediaRouterClientState> CREATOR =
             new Parcelable.Creator<MediaRouterClientState>() {
         @Override
         public MediaRouterClientState createFromParcel(Parcel in) {
@@ -180,7 +180,7 @@
         }
 
         @SuppressWarnings("hiding")
-        public static final Parcelable.Creator<RouteInfo> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<RouteInfo> CREATOR =
                 new Parcelable.Creator<RouteInfo>() {
             @Override
             public RouteInfo createFromParcel(Parcel in) {
diff --git a/media/java/android/media/PlaybackParams.java b/media/java/android/media/PlaybackParams.java
index 3fe1a32..b4325b6 100644
--- a/media/java/android/media/PlaybackParams.java
+++ b/media/java/android/media/PlaybackParams.java
@@ -234,7 +234,7 @@
         return mSpeed;
     }
 
-    public static final Parcelable.Creator<PlaybackParams> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PlaybackParams> CREATOR =
             new Parcelable.Creator<PlaybackParams>() {
                 @Override
                 public PlaybackParams createFromParcel(Parcel in) {
diff --git a/media/java/android/media/PlayerBase.java b/media/java/android/media/PlayerBase.java
index 7c6367e..34d56ed 100644
--- a/media/java/android/media/PlayerBase.java
+++ b/media/java/android/media/PlayerBase.java
@@ -535,7 +535,7 @@
             dest.writeStrongBinder(mIPlayer == null ? null : mIPlayer.asBinder());
         }
 
-        public static final Parcelable.Creator<PlayerIdCard> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<PlayerIdCard> CREATOR
         = new Parcelable.Creator<PlayerIdCard>() {
             /**
              * Rebuilds an PlayerIdCard previously stored with writeToParcel().
diff --git a/media/java/android/media/Rating.java b/media/java/android/media/Rating.java
index ffe7e48..be75258 100644
--- a/media/java/android/media/Rating.java
+++ b/media/java/android/media/Rating.java
@@ -116,7 +116,7 @@
         dest.writeFloat(mRatingValue);
     }
 
-    public static final Parcelable.Creator<Rating> CREATOR = new Parcelable.Creator<Rating>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<Rating> CREATOR = new Parcelable.Creator<Rating>() {
         /**
          * Rebuilds a Rating previously stored with writeToParcel().
          * @param p    Parcel object to read the Rating from
diff --git a/media/java/android/media/RemoteDisplayState.java b/media/java/android/media/RemoteDisplayState.java
index f8a4605..2f4ace0 100644
--- a/media/java/android/media/RemoteDisplayState.java
+++ b/media/java/android/media/RemoteDisplayState.java
@@ -76,7 +76,7 @@
         dest.writeTypedList(displays);
     }
 
-    public static final Parcelable.Creator<RemoteDisplayState> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<RemoteDisplayState> CREATOR =
             new Parcelable.Creator<RemoteDisplayState>() {
         @Override
         public RemoteDisplayState createFromParcel(Parcel in) {
@@ -176,7 +176,7 @@
         }
 
         @SuppressWarnings("hiding")
-        public static final Parcelable.Creator<RemoteDisplayInfo> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<RemoteDisplayInfo> CREATOR =
                 new Parcelable.Creator<RemoteDisplayInfo>() {
             @Override
             public RemoteDisplayInfo createFromParcel(Parcel in) {
diff --git a/media/java/android/media/VolumePolicy.java b/media/java/android/media/VolumePolicy.java
index bd6667f..b193b70 100644
--- a/media/java/android/media/VolumePolicy.java
+++ b/media/java/android/media/VolumePolicy.java
@@ -95,7 +95,7 @@
         dest.writeInt(vibrateToSilentDebounce);
     }
 
-    public static final Parcelable.Creator<VolumePolicy> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<VolumePolicy> CREATOR
             = new Parcelable.Creator<VolumePolicy>() {
         @Override
         public VolumePolicy createFromParcel(Parcel p) {
diff --git a/media/java/android/media/VolumeShaper.java b/media/java/android/media/VolumeShaper.java
index 2f33e75..663d564 100644
--- a/media/java/android/media/VolumeShaper.java
+++ b/media/java/android/media/VolumeShaper.java
@@ -501,7 +501,7 @@
             }
         }
 
-        public static final Parcelable.Creator<VolumeShaper.Configuration> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<VolumeShaper.Configuration> CREATOR
                 = new Parcelable.Creator<VolumeShaper.Configuration>() {
             @Override
             public VolumeShaper.Configuration createFromParcel(Parcel p) {
@@ -1178,7 +1178,7 @@
             dest.writeFloat(mXOffset);
         }
 
-        public static final Parcelable.Creator<VolumeShaper.Operation> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<VolumeShaper.Operation> CREATOR
                 = new Parcelable.Creator<VolumeShaper.Operation>() {
             @Override
             public VolumeShaper.Operation createFromParcel(Parcel p) {
@@ -1397,7 +1397,7 @@
             dest.writeFloat(mXOffset);
         }
 
-        public static final Parcelable.Creator<VolumeShaper.State> CREATOR
+        public static final @android.annotation.NonNull Parcelable.Creator<VolumeShaper.State> CREATOR
                 = new Parcelable.Creator<VolumeShaper.State>() {
             @Override
             public VolumeShaper.State createFromParcel(Parcel p) {
diff --git a/media/java/android/media/audiopolicy/AudioPolicy.java b/media/java/android/media/audiopolicy/AudioPolicy.java
index 445edd1..5f65d58 100644
--- a/media/java/android/media/audiopolicy/AudioPolicy.java
+++ b/media/java/android/media/audiopolicy/AudioPolicy.java
@@ -364,11 +364,10 @@
      * played.
      * @param uid UID of the application to affect.
      * @param devices list of devices to which the audio stream of the application may be routed.
-     * @return {@link AudioManager#SUCCESS} if the change was successful, {@link AudioManager#ERROR}
-     *          otherwise.
+     * @return true if the change was successful, false otherwise.
      */
     @SystemApi
-    public int setUidDeviceAffinity(int uid, @NonNull List<AudioDeviceInfo> devices) {
+    public boolean setUidDeviceAffinity(int uid, @NonNull List<AudioDeviceInfo> devices) {
         if (devices == null) {
             throw new IllegalArgumentException("Illegal null list of audio devices");
         }
@@ -393,10 +392,10 @@
             try {
                 final int status = service.setUidDeviceAffinity(this.cb(),
                         uid, deviceTypes, deviceAdresses);
-                return status;
+                return (status == AudioManager.SUCCESS);
             } catch (RemoteException e) {
                 Log.e(TAG, "Dead object in setUidDeviceAffinity", e);
-                return AudioManager.ERROR;
+                return false;
             }
         }
     }
@@ -406,11 +405,10 @@
      * Removes audio device affinity previously set by
      * {@link #setUidDeviceAffinity(int, java.util.List)}.
      * @param uid UID of the application affected.
-     * @return {@link AudioManager#SUCCESS} if the change was successful, {@link AudioManager#ERROR}
-     *          otherwise.
+     * @return true if the change was successful, false otherwise.
      */
     @SystemApi
-    public int removeUidDeviceAffinity(int uid) {
+    public boolean removeUidDeviceAffinity(int uid) {
         synchronized (mLock) {
             if (mStatus != POLICY_STATUS_REGISTERED) {
                 throw new IllegalStateException("Cannot use unregistered AudioPolicy");
@@ -418,10 +416,10 @@
             final IAudioService service = getService();
             try {
                 final int status = service.removeUidDeviceAffinity(this.cb(), uid);
-                return status;
+                return (status == AudioManager.SUCCESS);
             } catch (RemoteException e) {
                 Log.e(TAG, "Dead object in removeUidDeviceAffinity", e);
-                return AudioManager.ERROR;
+                return false;
             }
         }
     }
@@ -682,7 +680,6 @@
      *
      */
     public static abstract class AudioPolicyVolumeCallback {
-        /** @hide */
         public AudioPolicyVolumeCallback() {}
         /**
          * Called when volume key-related changes are triggered, on the key down event.
diff --git a/media/java/android/media/audiopolicy/AudioPolicyConfig.java b/media/java/android/media/audiopolicy/AudioPolicyConfig.java
index a56fd31..a6e63c7 100644
--- a/media/java/android/media/audiopolicy/AudioPolicyConfig.java
+++ b/media/java/android/media/audiopolicy/AudioPolicyConfig.java
@@ -136,7 +136,7 @@
         }
     }
 
-    public static final Parcelable.Creator<AudioPolicyConfig> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<AudioPolicyConfig> CREATOR
             = new Parcelable.Creator<AudioPolicyConfig>() {
         /**
          * Rebuilds an AudioPolicyConfig previously stored with writeToParcel().
diff --git a/media/java/android/media/audiopolicy/AudioProductStrategies.java b/media/java/android/media/audiopolicy/AudioProductStrategies.java
index b836409..98b6d97 100644
--- a/media/java/android/media/audiopolicy/AudioProductStrategies.java
+++ b/media/java/android/media/audiopolicy/AudioProductStrategies.java
@@ -144,8 +144,10 @@
      * @hide
      * @param aa the {@link AudioAttributes} for which stream type is requested
      * @return the legacy stream type relevant for the given {@link AudioAttributes}.
-     *         If the product strategy is not associated to any stream, it returns STREAM_MUSIC.
-     *         If no product strategy supports the stream type, it returns STREAM_MUSIC.
+     *         If the product strategy is not associated to any stream, it returns
+     *         {@link AudioSystem#STREAM_MUSIC}.
+     *         If no product strategy supports the stream type, it returns
+     *         {@link AudioSystem#STREAM_MUSIC}.
      */
     @SystemApi
     public int getLegacyStreamTypeForAudioAttributes(@NonNull AudioAttributes aa) {
@@ -165,6 +167,62 @@
         return AudioSystem.STREAM_MUSIC;
     }
 
+    /**
+     * @hide
+     * @param aa the {@link AudioAttributes} to be considered
+     * @return {@link AudioProductStrategy} supporting the given {@link AudioAttributes}.
+     *         null is returned if no match with given attributes.
+     */
+    @SystemApi
+    @Nullable
+    public AudioProductStrategy getProductStrategyForAudioAttributes(@NonNull AudioAttributes aa) {
+        Preconditions.checkNotNull(aa, "attributes must not be null");
+        int productStrategyId =  native_get_product_strategies_from_audio_attributes(aa);
+        if (productStrategyId < 0) {
+            Log.w(TAG, "no strategy found for Attributes " + aa.toString());
+            return null;
+        }
+        return getById(productStrategyId);
+    }
+
+   /**
+    * @hide
+    * @param attributes the {@link AudioAttributes} to be considered
+    * @return volume group associated to the given {@link AudioAttributes}.
+    *         If no group supports the given {@link AudioAttributes}, it returns the volume group
+    *         for the default attributes.
+    *         If no group supports the default attributes, it returns {@link #DEFAULT_VOLUME_GROUP}
+    */
+    @SystemApi
+    public int getVolumeGroupIdForAttributes(@NonNull AudioAttributes attributes) {
+        Preconditions.checkNotNull(attributes, "attributes must not be null");
+        int volumeGroupId = getVolumeGroupIdForAttributesInt(attributes);
+        if (volumeGroupId != AudioVolumeGroups.DEFAULT_VOLUME_GROUP) {
+            return volumeGroupId;
+        }
+        // The default volume group is the one hosted by default product strategy, i.e.
+        // supporting Default Attributes
+        return getVolumeGroupIdForAttributesInt(AudioProductStrategy.sDefaultAttributes);
+    }
+
+   /**
+    * @hide
+    * @param streamType to be considered
+    * @return volume group associated to the given stream type.
+    */
+    @SystemApi
+    public int getVolumeGroupIdForLegacyStreamType(int streamType) {
+        for (final AudioProductStrategy productStrategy : this) {
+            int volumeGroupId = productStrategy.getVolumeGroupIdForLegacyStreamType(streamType);
+            if (volumeGroupId != AudioVolumeGroups.DEFAULT_VOLUME_GROUP) {
+                return volumeGroupId;
+            }
+        }
+        // The default volume group is the one hosted by default product strategy, i.e.
+        // supporting Default Attributes
+        return getVolumeGroupIdForAttributesInt(AudioProductStrategy.sDefaultAttributes);
+    }
+
     @Override
     public int describeContents() {
         return 0;
@@ -178,7 +236,22 @@
         }
     }
 
-    public static final Parcelable.Creator<AudioProductStrategies> CREATOR =
+    /**
+     * @param attributes to be considered
+     * @return volume group associated to the given {@link AudioAttributes}.
+     */
+    private int getVolumeGroupIdForAttributesInt(@NonNull AudioAttributes attributes) {
+        Preconditions.checkNotNull(attributes, "attributes must not be null");
+        for (final AudioProductStrategy productStrategy : this) {
+            int volumeGroupId = productStrategy.getVolumeGroupIdForAudioAttributes(attributes);
+            if (volumeGroupId != AudioVolumeGroups.DEFAULT_VOLUME_GROUP) {
+                return volumeGroupId;
+            }
+        }
+        return AudioVolumeGroups.DEFAULT_VOLUME_GROUP;
+    }
+
+    public static final @android.annotation.NonNull Parcelable.Creator<AudioProductStrategies> CREATOR =
             new Parcelable.Creator<AudioProductStrategies>() {
                 @Override
                 public AudioProductStrategies createFromParcel(@NonNull Parcel in) {
@@ -198,4 +271,7 @@
 
     private static native int native_list_audio_product_strategies(
             ArrayList<AudioProductStrategy> strategies);
+
+    private static native int native_get_product_strategies_from_audio_attributes(
+            AudioAttributes attributes);
 }
diff --git a/media/java/android/media/audiopolicy/AudioProductStrategy.java b/media/java/android/media/audiopolicy/AudioProductStrategy.java
index af6e8bf..48500e01 100644
--- a/media/java/android/media/audiopolicy/AudioProductStrategy.java
+++ b/media/java/android/media/audiopolicy/AudioProductStrategy.java
@@ -157,32 +157,32 @@
     /**
      * @hide
      * @param streamType legacy stream type used for volume operation only
-     * @return the {@link AudioAttributes} relevant for the given streamType.
-     *         If none is found, it builds the default attributes.
+     * @return the volume group id relevant for the given streamType.
+     *         If none is found, {@link AudioVolumeGroups#DEFAULT_VOLUME_GROUP} is returned.
      */
-    public int getGroupIdForLegacyStreamType(int streamType) {
+    public int getVolumeGroupIdForLegacyStreamType(int streamType) {
         for (final AudioAttributesGroup aag : mAudioAttributesGroups) {
             if (aag.supportsStreamType(streamType)) {
-                return aag.getGroupId();
+                return aag.getVolumeGroupId();
             }
         }
-        return DEFAULT_GROUP;
+        return AudioVolumeGroups.DEFAULT_VOLUME_GROUP;
     }
 
     /**
      * @hide
      * @param aa the {@link AudioAttributes} to be considered
-     * @return the group id associated with the given audio attributes if found,
-     *         default value otherwise.
+     * @return the volume group id associated with the given audio attributes if found,
+     *         {@link AudioVolumeGroups#DEFAULT_VOLUME_GROUP} otherwise.
      */
-    public int getGroupIdForAudioAttributes(@NonNull AudioAttributes aa) {
+    public int getVolumeGroupIdForAudioAttributes(@NonNull AudioAttributes aa) {
         Preconditions.checkNotNull(aa, "AudioAttributes must not be null");
         for (final AudioAttributesGroup aag : mAudioAttributesGroups) {
             if (aag.supportsAttributes(aa)) {
-                return aag.getGroupId();
+                return aag.getVolumeGroupId();
             }
         }
-        return DEFAULT_GROUP;
+        return AudioVolumeGroups.DEFAULT_VOLUME_GROUP;
     }
 
     @Override
@@ -200,7 +200,7 @@
         }
     }
 
-    public static final Parcelable.Creator<AudioProductStrategy> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AudioProductStrategy> CREATOR =
             new Parcelable.Creator<AudioProductStrategy>() {
                 @Override
                 public AudioProductStrategy createFromParcel(@NonNull Parcel in) {
@@ -266,15 +266,14 @@
             && ((refFormattedTags.length() == 0) || refFormattedTags.equals(cliFormattedTags));
     }
 
-
     private static final class AudioAttributesGroup implements Parcelable {
-        private int mGroupId;
+        private int mVolumeGroupId;
         private int mLegacyStreamType;
         private final AudioAttributes[] mAudioAttributes;
 
-        AudioAttributesGroup(int groupId, int streamType,
+        AudioAttributesGroup(int volumeGroupId, int streamType,
                 @NonNull AudioAttributes[] audioAttributes) {
-            mGroupId = groupId;
+            mVolumeGroupId = volumeGroupId;
             mLegacyStreamType = streamType;
             mAudioAttributes = audioAttributes;
         }
@@ -286,7 +285,7 @@
 
             AudioAttributesGroup thatAag = (AudioAttributesGroup) o;
 
-            return mGroupId == thatAag.mGroupId
+            return mVolumeGroupId == thatAag.mVolumeGroupId
                     && mLegacyStreamType == thatAag.mLegacyStreamType
                     && mAudioAttributes.equals(thatAag.mAudioAttributes);
         }
@@ -295,8 +294,8 @@
             return mLegacyStreamType;
         }
 
-        public int getGroupId() {
-            return mGroupId;
+        public int getVolumeGroupId() {
+            return mVolumeGroupId;
         }
 
         public @NonNull AudioAttributes getAudioAttributes() {
@@ -331,7 +330,7 @@
 
         @Override
         public void writeToParcel(@NonNull Parcel dest, int flags) {
-            dest.writeInt(mGroupId);
+            dest.writeInt(mVolumeGroupId);
             dest.writeInt(mLegacyStreamType);
             dest.writeInt(mAudioAttributes.length);
             for (AudioAttributes attributes : mAudioAttributes) {
@@ -339,18 +338,18 @@
             }
         }
 
-        public static final Parcelable.Creator<AudioAttributesGroup> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<AudioAttributesGroup> CREATOR =
                 new Parcelable.Creator<AudioAttributesGroup>() {
                     @Override
                     public AudioAttributesGroup createFromParcel(@NonNull Parcel in) {
-                        int groupId = in.readInt();
+                        int volumeGroupId = in.readInt();
                         int streamType = in.readInt();
                         int nbAttributes = in.readInt();
                         AudioAttributes[] aa = new AudioAttributes[nbAttributes];
                         for (int index = 0; index < nbAttributes; index++) {
                             aa[index] = AudioAttributes.CREATOR.createFromParcel(in);
                         }
-                        return new AudioAttributesGroup(groupId, streamType, aa);
+                        return new AudioAttributesGroup(volumeGroupId, streamType, aa);
                     }
 
                     @Override
@@ -365,8 +364,8 @@
             StringBuilder s = new StringBuilder();
             s.append("\n    Legacy Stream Type: ");
             s.append(Integer.toString(mLegacyStreamType));
-            s.append(" Group Id: ");
-            s.append(Integer.toString(mGroupId));
+            s.append(" Volume Group Id: ");
+            s.append(Integer.toString(mVolumeGroupId));
 
             for (AudioAttributes attribute : mAudioAttributes) {
                 s.append("\n    -");
diff --git a/media/java/android/media/audiopolicy/AudioVolumeGroup.aidl b/media/java/android/media/audiopolicy/AudioVolumeGroup.aidl
new file mode 100644
index 0000000..caf1e0d
--- /dev/null
+++ b/media/java/android/media/audiopolicy/AudioVolumeGroup.aidl
@@ -0,0 +1,18 @@
+/* Copyright 2018, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+package android.media.audiopolicy;
+
+parcelable AudioVolumeGroup;
diff --git a/media/java/android/media/audiopolicy/AudioVolumeGroup.java b/media/java/android/media/audiopolicy/AudioVolumeGroup.java
new file mode 100644
index 0000000..0b4ba93
--- /dev/null
+++ b/media/java/android/media/audiopolicy/AudioVolumeGroup.java
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.audiopolicy;
+
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+import android.media.AudioAttributes;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import com.android.internal.util.Preconditions;
+
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * A class to create the association between different playback attributes
+ * (e.g. media, mapping direction) to a single volume control.
+ * @hide
+ */
+@SystemApi
+public final class AudioVolumeGroup implements Parcelable {
+    /**
+     * Unique identifier of a volume group.
+     */
+    private int mId;
+    /**
+     * human-readable name of this volume group.
+     */
+    private final String mName;
+
+    private final AudioAttributes[] mAudioAttributes;
+    private int[] mLegacyStreamTypes;
+
+    /**
+     * @param name of the volume group
+     * @param id of the volume group
+     * @param followers {@link AudioProductStrategies} strategy following this volume group
+     */
+    AudioVolumeGroup(@NonNull String name, int id,
+                     @NonNull AudioAttributes[] audioAttributes,
+                     @NonNull int[] legacyStreamTypes) {
+        Preconditions.checkNotNull(name, "name must not be null");
+        Preconditions.checkNotNull(audioAttributes, "audioAttributes must not be null");
+        Preconditions.checkNotNull(legacyStreamTypes, "legacyStreamTypes must not be null");
+        mName = name;
+        mId = id;
+        mAudioAttributes = audioAttributes;
+        mLegacyStreamTypes = legacyStreamTypes;
+    }
+
+    @Override
+    public boolean equals(@NonNull Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        AudioVolumeGroup thatAvg = (AudioVolumeGroup) o;
+
+        return mName == thatAvg.mName && mId == thatAvg.mId
+                && mAudioAttributes.equals(thatAvg.mAudioAttributes);
+    }
+
+    /**
+     * @return List of {@link AudioAttributes} involved in this {@link AudioVolumeGroup}.
+     */
+    public List<AudioAttributes> getAudioAttributes() {
+        return Arrays.asList(mAudioAttributes);
+    }
+
+    /**
+     * @return the stream types involved in this {@link AudioVolumeGroup}.
+     */
+    public @NonNull int[] getLegacyStreamTypes() {
+        return mLegacyStreamTypes;
+    }
+
+    /**
+     * @return human-readable name of this volume group.
+     */
+    public @NonNull String name() {
+        return mName;
+    }
+
+    /**
+     * @return the volume group unique identifier id.
+     */
+    public int getId() {
+        return mId;
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(@NonNull Parcel dest, int flags) {
+        dest.writeString(mName);
+        dest.writeInt(mId);
+        dest.writeInt(mAudioAttributes.length);
+        for (AudioAttributes attributes : mAudioAttributes) {
+            attributes.writeToParcel(dest, flags | AudioAttributes.FLATTEN_TAGS/*flags*/);
+        }
+        dest.writeInt(mLegacyStreamTypes.length);
+        for (int streamType : mLegacyStreamTypes) {
+            dest.writeInt(streamType);
+        }
+    }
+
+    public static final Parcelable.Creator<AudioVolumeGroup> CREATOR =
+            new Parcelable.Creator<AudioVolumeGroup>() {
+                @Override
+                public @NonNull AudioVolumeGroup createFromParcel(@NonNull Parcel in) {
+                    Preconditions.checkNotNull(in, "in Parcel must not be null");
+                    String name = in.readString();
+                    int id = in.readInt();
+                    int nbAttributes = in.readInt();
+                    AudioAttributes[] audioAttributes = new AudioAttributes[nbAttributes];
+                    for (int index = 0; index < nbAttributes; index++) {
+                        audioAttributes[index] = AudioAttributes.CREATOR.createFromParcel(in);
+                    }
+                    int nbStreamTypes = in.readInt();
+                    int[] streamTypes = new int[nbStreamTypes];
+                    for (int index = 0; index < nbStreamTypes; index++) {
+                        streamTypes[index] = in.readInt();
+                    }
+                    return new AudioVolumeGroup(name, id, audioAttributes, streamTypes);
+                }
+
+                @Override
+                public @NonNull AudioVolumeGroup[] newArray(int size) {
+                    return new AudioVolumeGroup[size];
+                }
+            };
+
+    @Override
+    public @NonNull String toString() {
+        StringBuilder s = new StringBuilder();
+        s.append("\n Name: ");
+        s.append(mName);
+        s.append(" Id: ");
+        s.append(Integer.toString(mId));
+
+        s.append("\n     Supported Audio Attributes:");
+        for (AudioAttributes attribute : mAudioAttributes) {
+            s.append("\n       -");
+            s.append(attribute.toString());
+        }
+        s.append("\n     Supported Legacy Stream Types: { ");
+        for (int legacyStreamType : mLegacyStreamTypes) {
+            s.append(Integer.toString(legacyStreamType));
+            s.append(" ");
+        }
+        s.append("}");
+        return s.toString();
+    }
+}
diff --git a/media/java/android/media/audiopolicy/AudioVolumeGroupChangeHandler.java b/media/java/android/media/audiopolicy/AudioVolumeGroupChangeHandler.java
new file mode 100644
index 0000000..074188e
--- /dev/null
+++ b/media/java/android/media/audiopolicy/AudioVolumeGroupChangeHandler.java
@@ -0,0 +1,167 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.audiopolicy;
+
+import android.annotation.NonNull;
+import android.media.AudioManager;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Message;
+
+import com.android.internal.util.Preconditions;
+
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+
+/**
+ * The AudioVolumeGroupChangeHandler handles AudioManager.OnAudioVolumeGroupChangedListener
+ * callbacks posted from JNI
+ *
+ * TODO: Make use of Executor of callbacks.
+ * @hide
+ */
+public class AudioVolumeGroupChangeHandler {
+    private Handler mHandler;
+    private HandlerThread mHandlerThread;
+    private final ArrayList<AudioManager.VolumeGroupCallback> mListeners =
+            new ArrayList<AudioManager.VolumeGroupCallback>();
+
+    private static final String TAG = "AudioVolumeGroupChangeHandler";
+
+    private static final int AUDIOVOLUMEGROUP_EVENT_VOLUME_CHANGED = 1000;
+    private static final int AUDIOVOLUMEGROUP_EVENT_NEW_LISTENER = 4;
+
+    /**
+     * Accessed by native methods: JNI Callback context.
+     */
+    @SuppressWarnings("unused")
+    private long mJniCallback;
+
+    /**
+     * Initialization
+     */
+    public void init() {
+        synchronized (this) {
+            if (mHandler != null) {
+                return;
+            }
+            // create a new thread for our new event handler
+            mHandlerThread = new HandlerThread(TAG);
+            mHandlerThread.start();
+
+            if (mHandlerThread.getLooper() == null) {
+                mHandler = null;
+                return;
+            }
+            mHandler = new Handler(mHandlerThread.getLooper()) {
+                @Override
+                public void handleMessage(Message msg) {
+                    ArrayList<AudioManager.VolumeGroupCallback> listeners;
+                    synchronized (this) {
+                        if (msg.what == AUDIOVOLUMEGROUP_EVENT_NEW_LISTENER) {
+                            listeners =
+                                    new ArrayList<AudioManager.VolumeGroupCallback>();
+                            if (mListeners.contains(msg.obj)) {
+                                listeners.add(
+                                        (AudioManager.VolumeGroupCallback) msg.obj);
+                            }
+                        } else {
+                            listeners = mListeners;
+                        }
+                    }
+                    if (listeners.isEmpty()) {
+                        return;
+                    }
+
+                    switch (msg.what) {
+                        case AUDIOVOLUMEGROUP_EVENT_VOLUME_CHANGED:
+                            for (int i = 0; i < listeners.size(); i++) {
+                                listeners.get(i).onAudioVolumeGroupChanged((int) msg.arg1,
+                                                                           (int) msg.arg2);
+                            }
+                            break;
+
+                        default:
+                            break;
+                    }
+                }
+            };
+            native_setup(new WeakReference<AudioVolumeGroupChangeHandler>(this));
+        }
+    }
+
+    private native void native_setup(Object moduleThis);
+
+    @Override
+    protected void finalize() {
+        native_finalize();
+        if (mHandlerThread.isAlive()) {
+            mHandlerThread.quit();
+        }
+    }
+    private native void native_finalize();
+
+   /**
+    * @param cb the {@link AudioManager.VolumeGroupCallback} to register
+    */
+    public void registerListener(@NonNull AudioManager.VolumeGroupCallback cb) {
+        Preconditions.checkNotNull(cb, "volume group callback shall not be null");
+        synchronized (this) {
+            mListeners.add(cb);
+        }
+        if (mHandler != null) {
+            Message m = mHandler.obtainMessage(
+                    AUDIOVOLUMEGROUP_EVENT_NEW_LISTENER, 0, 0, cb);
+            mHandler.sendMessage(m);
+        }
+    }
+
+   /**
+    * @param cb the {@link AudioManager.VolumeGroupCallback} to unregister
+    */
+    public void unregisterListener(@NonNull AudioManager.VolumeGroupCallback cb) {
+        Preconditions.checkNotNull(cb, "volume group callback shall not be null");
+        synchronized (this) {
+            mListeners.remove(cb);
+        }
+    }
+
+    Handler handler() {
+        return mHandler;
+    }
+
+    @SuppressWarnings("unused")
+    private static void postEventFromNative(Object moduleRef,
+                                            int what, int arg1, int arg2, Object obj) {
+        AudioVolumeGroupChangeHandler eventHandler =
+                (AudioVolumeGroupChangeHandler) ((WeakReference) moduleRef).get();
+        if (eventHandler == null) {
+            return;
+        }
+
+        if (eventHandler != null) {
+            Handler handler = eventHandler.handler();
+            if (handler != null) {
+                Message m = handler.obtainMessage(what, arg1, arg2, obj);
+                if (what != AUDIOVOLUMEGROUP_EVENT_NEW_LISTENER) {
+                    handler.removeMessages(what);
+                }
+                handler.sendMessage(m);
+            }
+        }
+    }
+}
diff --git a/media/java/android/media/audiopolicy/AudioVolumeGroups.aidl b/media/java/android/media/audiopolicy/AudioVolumeGroups.aidl
new file mode 100644
index 0000000..918cac3
--- /dev/null
+++ b/media/java/android/media/audiopolicy/AudioVolumeGroups.aidl
@@ -0,0 +1,18 @@
+/* Copyright 2018, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+package android.media.audiopolicy;
+
+parcelable AudioVolumeGroups;
diff --git a/media/java/android/media/audiopolicy/AudioVolumeGroups.java b/media/java/android/media/audiopolicy/AudioVolumeGroups.java
new file mode 100644
index 0000000..301bec7
--- /dev/null
+++ b/media/java/android/media/audiopolicy/AudioVolumeGroups.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.audiopolicy;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
+import android.media.AudioSystem;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.Log;
+
+import com.android.internal.util.Preconditions;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+/**
+ * @hide
+ * A class to encapsulate a collection of {@link AudioVolumeGroup}.
+ */
+@SystemApi
+public final class AudioVolumeGroups implements Iterable<AudioVolumeGroup>, Parcelable {
+
+    private final ArrayList<AudioVolumeGroup> mAudioVolumeGroupList;
+
+    private static final String TAG = "AudioVolumeGroups";
+
+    /**
+     * Volume group value to use when introspection API fails.
+     */
+    public static final int DEFAULT_VOLUME_GROUP = -1;
+
+    public AudioVolumeGroups() {
+        ArrayList<AudioVolumeGroup> avgList = new ArrayList<AudioVolumeGroup>();
+        int status = native_list_audio_volume_groups(avgList);
+        if (status != AudioSystem.SUCCESS) {
+            Log.w(TAG, ": listAudioVolumeGroups failed");
+        }
+        mAudioVolumeGroupList = avgList;
+    }
+
+    private AudioVolumeGroups(@NonNull ArrayList<AudioVolumeGroup> audioVolumeGroupList) {
+        Preconditions.checkNotNull(audioVolumeGroupList, "audioVolumeGroupList must not be null");
+        mAudioVolumeGroupList = audioVolumeGroupList;
+    }
+
+    /**
+     * @return number of {@link AudioProductStrategy} objects
+     */
+    public int size() {
+        return mAudioVolumeGroupList.size();
+    }
+
+    /**
+     * Returns an {@link Iterator}
+     */
+    @Override
+    public Iterator<AudioVolumeGroup> iterator() {
+        return mAudioVolumeGroupList.iterator();
+    }
+
+    @Override
+    public boolean equals(@NonNull Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        AudioVolumeGroups that = (AudioVolumeGroups) o;
+
+        return mAudioVolumeGroupList.equals(that.mAudioVolumeGroupList);
+    }
+
+    /**
+     * @return the matching {@link AudioVolumeGroup} objects with the given id,
+     *         null object if not found.
+     */
+    public @Nullable AudioVolumeGroup getById(int volumeGroupId) {
+        for (final AudioVolumeGroup avg : this) {
+            if (avg.getId() == volumeGroupId) {
+                return avg;
+            }
+        }
+        Log.e(TAG, ": invalid volume group id: " + volumeGroupId + " requested");
+        return null;
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(@NonNull Parcel dest, int flags) {
+        dest.writeInt(size());
+        for (final AudioVolumeGroup volumeGroup : this) {
+            volumeGroup.writeToParcel(dest, flags);
+        }
+    }
+
+    private static native int native_list_audio_volume_groups(
+            ArrayList<AudioVolumeGroup> groups);
+
+    public static final Parcelable.Creator<AudioVolumeGroups> CREATOR =
+            new Parcelable.Creator<AudioVolumeGroups>() {
+                @Override
+                public @NonNull AudioVolumeGroups createFromParcel(@NonNull Parcel in) {
+                    Preconditions.checkNotNull(in, "in Parcel must not be null");
+                    ArrayList<AudioVolumeGroup> avgList = new ArrayList<AudioVolumeGroup>();
+                    int size = in.readInt();
+                    for (int index = 0; index < size; index++) {
+                        avgList.add(AudioVolumeGroup.CREATOR.createFromParcel(in));
+                    }
+                    return new AudioVolumeGroups(avgList);
+                }
+
+                @Override
+                public @NonNull AudioVolumeGroups[] newArray(int size) {
+                    return new AudioVolumeGroups[size];
+                }
+            };
+}
diff --git a/media/java/android/media/browse/MediaBrowser.java b/media/java/android/media/browse/MediaBrowser.java
index 2dffef9..65255a1 100644
--- a/media/java/android/media/browse/MediaBrowser.java
+++ b/media/java/android/media/browse/MediaBrowser.java
@@ -808,7 +808,7 @@
             return sb.toString();
         }
 
-        public static final Parcelable.Creator<MediaItem> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<MediaItem> CREATOR =
                 new Parcelable.Creator<MediaItem>() {
                     @Override
                     public MediaItem createFromParcel(Parcel in) {
diff --git a/media/java/android/media/midi/MidiDeviceInfo.java b/media/java/android/media/midi/MidiDeviceInfo.java
index ab8af2a..c222985 100644
--- a/media/java/android/media/midi/MidiDeviceInfo.java
+++ b/media/java/android/media/midi/MidiDeviceInfo.java
@@ -325,7 +325,7 @@
                 ",mIsPrivate=" + mIsPrivate);
     }
 
-    public static final Parcelable.Creator<MidiDeviceInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<MidiDeviceInfo> CREATOR =
         new Parcelable.Creator<MidiDeviceInfo>() {
         public MidiDeviceInfo createFromParcel(Parcel in) {
             // Needs to be kept in sync with code in MidiDeviceInfo.cpp
diff --git a/media/java/android/media/midi/MidiDeviceStatus.java b/media/java/android/media/midi/MidiDeviceStatus.java
index acb54de..b118279 100644
--- a/media/java/android/media/midi/MidiDeviceStatus.java
+++ b/media/java/android/media/midi/MidiDeviceStatus.java
@@ -111,7 +111,7 @@
         return builder.toString();
     }
 
-    public static final Parcelable.Creator<MidiDeviceStatus> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<MidiDeviceStatus> CREATOR =
         new Parcelable.Creator<MidiDeviceStatus>() {
         public MidiDeviceStatus createFromParcel(Parcel in) {
             ClassLoader classLoader = MidiDeviceInfo.class.getClassLoader();
diff --git a/media/java/android/media/projection/IMediaProjectionManager.aidl b/media/java/android/media/projection/IMediaProjectionManager.aidl
index 7e10c51..d190fce 100644
--- a/media/java/android/media/projection/IMediaProjectionManager.aidl
+++ b/media/java/android/media/projection/IMediaProjectionManager.aidl
@@ -24,6 +24,7 @@
 
 /** {@hide} */
 interface IMediaProjectionManager {
+    @UnsupportedAppUsage
     boolean hasProjectionPermission(int uid, String packageName);
     IMediaProjection createProjection(int uid, String packageName, int type,
             boolean permanentGrant);
diff --git a/media/java/android/media/projection/MediaProjection.java b/media/java/android/media/projection/MediaProjection.java
index f9c5b8d..632cfb0 100644
--- a/media/java/android/media/projection/MediaProjection.java
+++ b/media/java/android/media/projection/MediaProjection.java
@@ -21,7 +21,6 @@
 import android.content.Context;
 import android.hardware.display.DisplayManager;
 import android.hardware.display.VirtualDisplay;
-import android.media.AudioRecord;
 import android.media.projection.IMediaProjection;
 import android.media.projection.IMediaProjectionCallback;
 import android.os.Handler;
@@ -140,16 +139,6 @@
     }
 
     /**
-     * Creates an AudioRecord to capture audio played back by the system.
-     * @hide
-     */
-    public AudioRecord createAudioRecord(
-            int sampleRateInHz, int channelConfig,
-            int audioFormat, int bufferSizeInBytes) {
-        return null;
-    }
-
-    /**
      * Stops projection.
      */
     public void stop() {
diff --git a/media/java/android/media/projection/MediaProjectionInfo.java b/media/java/android/media/projection/MediaProjectionInfo.java
index 5a65e65..ff60856 100644
--- a/media/java/android/media/projection/MediaProjectionInfo.java
+++ b/media/java/android/media/projection/MediaProjectionInfo.java
@@ -78,7 +78,7 @@
         UserHandle.writeToParcel(mUserHandle, out);
     }
 
-    public static final Parcelable.Creator<MediaProjectionInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<MediaProjectionInfo> CREATOR =
             new Parcelable.Creator<MediaProjectionInfo>() {
         @Override
         public MediaProjectionInfo createFromParcel(Parcel in) {
diff --git a/media/java/android/media/session/ControllerCallbackLink.java b/media/java/android/media/session/ControllerCallbackLink.java
index 428be0d..67d849a 100644
--- a/media/java/android/media/session/ControllerCallbackLink.java
+++ b/media/java/android/media/session/ControllerCallbackLink.java
@@ -191,7 +191,7 @@
         dest.writeStrongBinder(mIControllerCallback.asBinder());
     }
 
-    public static final Parcelable.Creator<ControllerCallbackLink> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ControllerCallbackLink> CREATOR =
             new Parcelable.Creator<ControllerCallbackLink>() {
         @Override
         public ControllerCallbackLink createFromParcel(Parcel in) {
diff --git a/media/java/android/media/session/ControllerLink.java b/media/java/android/media/session/ControllerLink.java
index 5828fbd..d4ea2a3 100644
--- a/media/java/android/media/session/ControllerLink.java
+++ b/media/java/android/media/session/ControllerLink.java
@@ -40,7 +40,7 @@
  * @hide
  */
 public final class ControllerLink implements Parcelable {
-    public static final Parcelable.Creator<ControllerLink> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ControllerLink> CREATOR =
             new Parcelable.Creator<ControllerLink>() {
                 @Override
                 public ControllerLink createFromParcel(Parcel in) {
diff --git a/media/java/android/media/session/MediaController.java b/media/java/android/media/session/MediaController.java
index fb21f69..5ee52ce 100644
--- a/media/java/android/media/session/MediaController.java
+++ b/media/java/android/media/session/MediaController.java
@@ -1050,7 +1050,7 @@
             dest.writeParcelable(mAudioAttrs, flags);
         }
 
-        public static final Parcelable.Creator<PlaybackInfo> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<PlaybackInfo> CREATOR =
                 new Parcelable.Creator<PlaybackInfo>() {
             @Override
             public PlaybackInfo createFromParcel(Parcel in) {
diff --git a/media/java/android/media/session/MediaSession.java b/media/java/android/media/session/MediaSession.java
index 9fdefa6..e0cb86e 100644
--- a/media/java/android/media/session/MediaSession.java
+++ b/media/java/android/media/session/MediaSession.java
@@ -511,7 +511,7 @@
             return mControllerLink;
         }
 
-        public static final Parcelable.Creator<Token> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<Token> CREATOR =
                 new Parcelable.Creator<Token>() {
             @Override
             public Token createFromParcel(Parcel in) {
@@ -789,7 +789,7 @@
             return 0;
         }
 
-        public static final Creator<MediaSession.QueueItem> CREATOR =
+        public static final @android.annotation.NonNull Creator<MediaSession.QueueItem> CREATOR =
                 new Creator<MediaSession.QueueItem>() {
 
             @Override
diff --git a/media/java/android/media/session/PlaybackState.java b/media/java/android/media/session/PlaybackState.java
index 6b28c97..8dd6127 100644
--- a/media/java/android/media/session/PlaybackState.java
+++ b/media/java/android/media/session/PlaybackState.java
@@ -480,7 +480,7 @@
         return mExtras;
     }
 
-    public static final Parcelable.Creator<PlaybackState> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PlaybackState> CREATOR =
             new Parcelable.Creator<PlaybackState>() {
         @Override
         public PlaybackState createFromParcel(Parcel in) {
@@ -534,7 +534,7 @@
             return 0;
         }
 
-        public static final Parcelable.Creator<PlaybackState.CustomAction> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<PlaybackState.CustomAction> CREATOR =
                 new Parcelable.Creator<PlaybackState.CustomAction>() {
 
                     @Override
diff --git a/media/java/android/media/session/SessionCallbackLink.java b/media/java/android/media/session/SessionCallbackLink.java
index f9fa45a..6ffdc2b 100644
--- a/media/java/android/media/session/SessionCallbackLink.java
+++ b/media/java/android/media/session/SessionCallbackLink.java
@@ -554,7 +554,7 @@
         dest.writeStrongBinder(mISessionCallback.asBinder());
     }
 
-    public static final Parcelable.Creator<SessionCallbackLink> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<SessionCallbackLink> CREATOR =
             new Parcelable.Creator<SessionCallbackLink>() {
                 @Override
                 public SessionCallbackLink createFromParcel(Parcel in) {
diff --git a/media/java/android/media/session/SessionLink.java b/media/java/android/media/session/SessionLink.java
index 2331a4a..2b42a2d 100644
--- a/media/java/android/media/session/SessionLink.java
+++ b/media/java/android/media/session/SessionLink.java
@@ -36,7 +36,7 @@
  * @hide
  */
 public final class SessionLink implements Parcelable {
-    public static final Parcelable.Creator<SessionLink> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<SessionLink> CREATOR =
             new Parcelable.Creator<SessionLink>() {
                 @Override
                 public SessionLink createFromParcel(Parcel in) {
diff --git a/media/java/android/media/tv/DvbDeviceInfo.java b/media/java/android/media/tv/DvbDeviceInfo.java
index e07f3a6..a574fe1 100644
--- a/media/java/android/media/tv/DvbDeviceInfo.java
+++ b/media/java/android/media/tv/DvbDeviceInfo.java
@@ -29,7 +29,7 @@
 public final class DvbDeviceInfo implements Parcelable {
     static final String TAG = "DvbDeviceInfo";
 
-    public static final Parcelable.Creator<DvbDeviceInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<DvbDeviceInfo> CREATOR =
             new Parcelable.Creator<DvbDeviceInfo>() {
                 @Override
                 public DvbDeviceInfo createFromParcel(Parcel source) {
diff --git a/media/java/android/media/tv/ITvRemoteServiceInput.aidl b/media/java/android/media/tv/ITvRemoteServiceInput.aidl
index df39299..a0b6c9b 100644
--- a/media/java/android/media/tv/ITvRemoteServiceInput.aidl
+++ b/media/java/android/media/tv/ITvRemoteServiceInput.aidl
@@ -21,13 +21,22 @@
  */
 oneway interface ITvRemoteServiceInput {
     // InputBridge related
+    @UnsupportedAppUsage
     void openInputBridge(IBinder token, String name, int width, int height, int maxPointers);
+    @UnsupportedAppUsage
     void closeInputBridge(IBinder token);
+    @UnsupportedAppUsage
     void clearInputBridge(IBinder token);
+    @UnsupportedAppUsage
     void sendTimestamp(IBinder token, long timestamp);
+    @UnsupportedAppUsage
     void sendKeyDown(IBinder token, int keyCode);
+    @UnsupportedAppUsage
     void sendKeyUp(IBinder token, int keyCode);
+    @UnsupportedAppUsage
     void sendPointerDown(IBinder token, int pointerId, int x, int y);
+    @UnsupportedAppUsage
     void sendPointerUp(IBinder token, int pointerId);
+    @UnsupportedAppUsage
     void sendPointerSync(IBinder token);
 }
\ No newline at end of file
diff --git a/media/java/android/media/tv/TvContentRatingSystemInfo.java b/media/java/android/media/tv/TvContentRatingSystemInfo.java
index f2e5b08..f44ded3 100644
--- a/media/java/android/media/tv/TvContentRatingSystemInfo.java
+++ b/media/java/android/media/tv/TvContentRatingSystemInfo.java
@@ -80,7 +80,7 @@
      * Used to make this class parcelable.
      * @hide
      */
-    public static final Parcelable.Creator<TvContentRatingSystemInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TvContentRatingSystemInfo> CREATOR =
             new Parcelable.Creator<TvContentRatingSystemInfo>() {
         @Override
         public TvContentRatingSystemInfo createFromParcel(Parcel in) {
diff --git a/media/java/android/media/tv/TvInputHardwareInfo.java b/media/java/android/media/tv/TvInputHardwareInfo.java
index 762f0c0..5b316be 100644
--- a/media/java/android/media/tv/TvInputHardwareInfo.java
+++ b/media/java/android/media/tv/TvInputHardwareInfo.java
@@ -74,7 +74,7 @@
     public static final int CABLE_CONNECTION_STATUS_DISCONNECTED =
             Constants.CABLE_CONNECTION_STATUS_DISCONNECTED;
 
-    public static final Parcelable.Creator<TvInputHardwareInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TvInputHardwareInfo> CREATOR =
             new Parcelable.Creator<TvInputHardwareInfo>() {
         @Override
         public TvInputHardwareInfo createFromParcel(Parcel source) {
diff --git a/media/java/android/media/tv/TvInputInfo.java b/media/java/android/media/tv/TvInputInfo.java
index 30907a5..1b9cac0 100644
--- a/media/java/android/media/tv/TvInputInfo.java
+++ b/media/java/android/media/tv/TvInputInfo.java
@@ -621,7 +621,7 @@
         return mService.serviceInfo.loadIcon(context.getPackageManager());
     }
 
-    public static final Parcelable.Creator<TvInputInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TvInputInfo> CREATOR =
             new Parcelable.Creator<TvInputInfo>() {
         @Override
         public TvInputInfo createFromParcel(Parcel in) {
diff --git a/media/java/android/media/tv/TvStreamConfig.java b/media/java/android/media/tv/TvStreamConfig.java
index 0c2f3fe..f012b46 100644
--- a/media/java/android/media/tv/TvStreamConfig.java
+++ b/media/java/android/media/tv/TvStreamConfig.java
@@ -42,7 +42,7 @@
      */
     private int mGeneration;
 
-    public static final Parcelable.Creator<TvStreamConfig> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TvStreamConfig> CREATOR =
             new Parcelable.Creator<TvStreamConfig>() {
         @Override
         public TvStreamConfig createFromParcel(Parcel source) {
diff --git a/media/java/android/media/tv/TvTrackInfo.java b/media/java/android/media/tv/TvTrackInfo.java
index c9c881c..8142979 100644
--- a/media/java/android/media/tv/TvTrackInfo.java
+++ b/media/java/android/media/tv/TvTrackInfo.java
@@ -289,7 +289,7 @@
         return Objects.hashCode(mId);
     }
 
-    public static final Parcelable.Creator<TvTrackInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TvTrackInfo> CREATOR =
             new Parcelable.Creator<TvTrackInfo>() {
                 @Override
                 public TvTrackInfo createFromParcel(Parcel in) {
diff --git a/media/jni/Android.bp b/media/jni/Android.bp
index 8ed265d..65b58ab 100644
--- a/media/jni/Android.bp
+++ b/media/jni/Android.bp
@@ -20,8 +20,8 @@
         "android_media_MediaScanner.cpp",
         "android_media_MediaSync.cpp",
         "android_media_ResampleInputStream.cpp",
+        "android_media_Streams.cpp",
         "android_media_SyncParams.cpp",
-        "android_media_Utils.cpp",
         "android_mtp_MtpDatabase.cpp",
         "android_mtp_MtpDevice.cpp",
         "android_mtp_MtpServer.cpp",
@@ -34,6 +34,7 @@
         "libutils",
         "libbinder",
         "libmedia",
+        "libmedia_jni_utils",
         "libmedia_omx",
         "libmediametrics",
         "libmediadrm",
@@ -85,6 +86,36 @@
 }
 
 cc_library_shared {
+    name: "libmedia_jni_utils",
+    srcs: [
+        "android_media_Utils.cpp",
+    ],
+
+    shared_libs: [
+        "liblog",
+        "libmedia_omx",
+        "libnativewindow",
+        "libui",
+        "libutils",
+        "android.hidl.token@1.0-utils",
+    ],
+
+    include_dirs: [
+        "system/media/camera/include",
+    ],
+
+    export_include_dirs: ["."],
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wno-error=deprecated-declarations",
+        "-Wunused",
+        "-Wunreachable-code",
+    ],
+}
+
+cc_library_shared {
     name: "libmedia2_jni",
 
     srcs: [
@@ -125,7 +156,6 @@
         "libcrypto",
         "libcutils",
         "libjsoncpp",
-        "libmedia_helper",
         "libmedia_player2_util",
         "libmediaplayer2",
         "libmediaplayer2-protos",
@@ -133,7 +163,6 @@
         "libmediautils",
         "libprocessgroup",
         "libprotobuf-cpp-lite",
-        "libstagefright",
         "libstagefright_esds",
         "libstagefright_foundation_without_imemory",
         "libstagefright_httplive",
diff --git a/media/jni/android_media_ImageWriter.cpp b/media/jni/android_media_ImageWriter.cpp
index 031e373..cfcba76 100644
--- a/media/jni/android_media_ImageWriter.cpp
+++ b/media/jni/android_media_ImageWriter.cpp
@@ -18,8 +18,11 @@
 #define LOG_TAG "ImageWriter_JNI"
 #include "android_media_Utils.h"
 
+#include <utils/Condition.h>
 #include <utils/Log.h>
+#include <utils/Mutex.h>
 #include <utils/String8.h>
+#include <utils/Thread.h>
 
 #include <gui/IProducerListener.h>
 #include <gui/Surface.h>
@@ -34,6 +37,8 @@
 #include <inttypes.h>
 #include <android/hardware_buffer_jni.h>
 
+#include <deque>
+
 #define IMAGE_BUFFER_JNI_ID           "mNativeBuffer"
 #define IMAGE_FORMAT_UNKNOWN          0 // This is the same value as ImageFormat#UNKNOWN.
 // ----------------------------------------------------------------------------
@@ -90,14 +95,124 @@
     int mFormat;
     int mWidth;
     int mHeight;
+
+    // Class for a shared thread used to detach buffers from buffer queues
+    // to discard buffers after consumers are done using them.
+    // This is needed because detaching buffers in onBufferReleased callback
+    // can lead to deadlock when consumer/producer are on the same process.
+    class BufferDetacher {
+    public:
+        // Called by JNIImageWriterContext ctor. Will start the thread for first ref.
+        void addRef();
+        // Called by JNIImageWriterContext dtor. Will stop the thread after ref goes to 0.
+        void removeRef();
+        // Called by onBufferReleased to signal this thread to detach a buffer
+        void detach(wp<Surface>);
+
+    private:
+
+        class DetachThread : public Thread {
+        public:
+            DetachThread() : Thread(/*canCallJava*/false) {};
+
+            void detach(wp<Surface>);
+
+            virtual void requestExit() override;
+
+        private:
+            virtual bool threadLoop() override;
+
+            Mutex     mLock;
+            Condition mCondition;
+            std::deque<wp<Surface>> mQueue;
+
+            static const nsecs_t kWaitDuration = 20000000; // 20 ms
+        };
+        sp<DetachThread> mThread;
+
+        Mutex     mLock;
+        int       mRefCount = 0;
+    };
+
+    static BufferDetacher sBufferDetacher;
 };
 
+JNIImageWriterContext::BufferDetacher JNIImageWriterContext::sBufferDetacher;
+
+void JNIImageWriterContext::BufferDetacher::addRef() {
+    Mutex::Autolock l(mLock);
+    mRefCount++;
+    if (mRefCount == 1) {
+        mThread = new DetachThread();
+        mThread->run("BufDtchThrd");
+    }
+}
+
+void JNIImageWriterContext::BufferDetacher::removeRef() {
+    Mutex::Autolock l(mLock);
+    mRefCount--;
+    if (mRefCount == 0) {
+        mThread->requestExit();
+        mThread->join();
+        mThread.clear();
+    }
+}
+
+void JNIImageWriterContext::BufferDetacher::detach(wp<Surface> bq) {
+    Mutex::Autolock l(mLock);
+    if (mThread == nullptr) {
+        ALOGE("%s: buffer detach thread is gone!", __FUNCTION__);
+        return;
+    }
+    mThread->detach(bq);
+}
+
+void JNIImageWriterContext::BufferDetacher::DetachThread::detach(wp<Surface> bq) {
+    Mutex::Autolock l(mLock);
+    mQueue.push_back(bq);
+    mCondition.signal();
+}
+
+void JNIImageWriterContext::BufferDetacher::DetachThread::requestExit() {
+    Thread::requestExit();
+    {
+        Mutex::Autolock l(mLock);
+        mQueue.clear();
+    }
+    mCondition.signal();
+}
+
+bool JNIImageWriterContext::BufferDetacher::DetachThread::threadLoop() {
+    Mutex::Autolock l(mLock);
+    mCondition.waitRelative(mLock, kWaitDuration);
+
+    while (!mQueue.empty()) {
+        if (exitPending()) {
+            return false;
+        }
+
+        wp<Surface> wbq = mQueue.front();
+        mQueue.pop_front();
+        sp<Surface> bq = wbq.promote();
+        if (bq != nullptr) {
+            sp<Fence> fence;
+            sp<GraphicBuffer> buffer;
+            ALOGV("%s: One buffer is detached", __FUNCTION__);
+            mLock.unlock();
+            bq->detachNextBuffer(&buffer, &fence);
+            mLock.lock();
+        }
+    }
+    return !exitPending();
+}
+
 JNIImageWriterContext::JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz) :
-    mWeakThiz(env->NewGlobalRef(weakThiz)),
-    mClazz((jclass)env->NewGlobalRef(clazz)),
-    mFormat(0),
-    mWidth(-1),
-    mHeight(-1) {
+        mWeakThiz(env->NewGlobalRef(weakThiz)),
+        mClazz((jclass)env->NewGlobalRef(clazz)),
+        mFormat(0),
+        mWidth(-1),
+        mHeight(-1) {
+    sBufferDetacher.addRef();
 }
 
 JNIImageWriterContext::~JNIImageWriterContext() {
@@ -115,6 +230,7 @@
     }
 
     mProducer.clear();
+    sBufferDetacher.removeRef();
 }
 
 JNIEnv* JNIImageWriterContext::getJNIEnv(bool* needsDetach) {
@@ -153,10 +269,7 @@
         // need let this callback give a BufferItem, then only detach if it was attached to this
         // Writer. Do the detach unconditionally for opaque format now. see b/19977520
         if (mFormat == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
-            sp<Fence> fence;
-            sp<GraphicBuffer> buffer;
-            ALOGV("%s: One buffer is detached", __FUNCTION__);
-            mProducer->detachNextBuffer(&buffer, &fence);
+            sBufferDetacher.detach(mProducer);
         }
 
         env->CallStaticVoidMethod(mClazz, gImageWriterClassInfo.postEventFromNative, mWeakThiz);
diff --git a/media/jni/android_media_MediaCodec.cpp b/media/jni/android_media_MediaCodec.cpp
index f07f1e8..150b6f9 100644
--- a/media/jni/android_media_MediaCodec.cpp
+++ b/media/jni/android_media_MediaCodec.cpp
@@ -23,7 +23,7 @@
 #include "android_media_MediaCrypto.h"
 #include "android_media_MediaDescrambler.h"
 #include "android_media_MediaMetricsJNI.h"
-#include "android_media_Utils.h"
+#include "android_media_Streams.h"
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/android_view_Surface.h"
 #include "android_util_Binder.h"
diff --git a/media/jni/android_media_MediaCodecList.cpp b/media/jni/android_media_MediaCodecList.cpp
index 6b8f745..923d1d2 100644
--- a/media/jni/android_media_MediaCodecList.cpp
+++ b/media/jni/android_media_MediaCodecList.cpp
@@ -31,7 +31,7 @@
 #include "android_runtime/AndroidRuntime.h"
 #include "jni.h"
 #include <nativehelper/JNIHelp.h>
-#include "android_media_Utils.h"
+#include "android_media_Streams.h"
 
 using namespace android;
 
diff --git a/media/jni/android_media_MediaExtractor.cpp b/media/jni/android_media_MediaExtractor.cpp
index c6b171b..f5ae9d0 100644
--- a/media/jni/android_media_MediaExtractor.cpp
+++ b/media/jni/android_media_MediaExtractor.cpp
@@ -22,7 +22,7 @@
 #include "android_media_MediaDataSource.h"
 #include "android_media_MediaExtractor.h"
 #include "android_media_MediaMetricsJNI.h"
-#include "android_media_Utils.h"
+#include "android_media_Streams.h"
 #include "android_os_HwRemoteBinder.h"
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/Log.h"
diff --git a/media/jni/android_media_MediaMetadataRetriever.cpp b/media/jni/android_media_MediaMetadataRetriever.cpp
index c1226fa..a480784 100644
--- a/media/jni/android_media_MediaMetadataRetriever.cpp
+++ b/media/jni/android_media_MediaMetadataRetriever.cpp
@@ -18,6 +18,7 @@
 //#define LOG_NDEBUG 0
 #define LOG_TAG "MediaMetadataRetrieverJNI"
 
+#include <cmath>
 #include <assert.h>
 #include <utils/Log.h>
 #include <utils/threads.h>
@@ -32,7 +33,7 @@
 #include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_media_MediaDataSource.h"
-#include "android_media_Utils.h"
+#include "android_media_Streams.h"
 #include "android_util_Binder.h"
 
 #include "android/graphics/GraphicsJNI.h"
diff --git a/media/jni/android_media_MediaMuxer.cpp b/media/jni/android_media_MediaMuxer.cpp
index f11452a..f0aa4c3 100644
--- a/media/jni/android_media_MediaMuxer.cpp
+++ b/media/jni/android_media_MediaMuxer.cpp
@@ -18,7 +18,7 @@
 #define LOG_TAG "MediaMuxer-JNI"
 #include <utils/Log.h>
 
-#include "android_media_Utils.h"
+#include "android_media_Streams.h"
 #include "android_runtime/AndroidRuntime.h"
 #include "jni.h"
 #include <nativehelper/JNIHelp.h>
diff --git a/media/jni/android_media_MediaPlayer.cpp b/media/jni/android_media_MediaPlayer.cpp
index 35b1081..d24edc7 100644
--- a/media/jni/android_media_MediaPlayer.cpp
+++ b/media/jni/android_media_MediaPlayer.cpp
@@ -44,7 +44,7 @@
 #include "android_media_PlaybackParams.h"
 #include "android_media_SyncParams.h"
 #include "android_media_VolumeShaper.h"
-#include "android_media_Utils.h"
+#include "android_media_Streams.h"
 
 #include "android_os_Parcel.h"
 #include "android_util_Binder.h"
diff --git a/media/jni/android_media_Streams.cpp b/media/jni/android_media_Streams.cpp
new file mode 100644
index 0000000..b7cbd97
--- /dev/null
+++ b/media/jni/android_media_Streams.cpp
@@ -0,0 +1,559 @@
+/*
+ * Copyright 2019, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// #define LOG_NDEBUG 0
+#define LOG_TAG "AndroidMediaStreams"
+
+#include <utils/Log.h>
+#include "android_media_Streams.h"
+
+#include <media/stagefright/foundation/ADebug.h>
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/AMessage.h>
+
+#include <nativehelper/ScopedLocalRef.h>
+
+namespace android {
+
+AssetStream::AssetStream(SkStream* stream)
+    : mStream(stream), mPosition(0) {
+}
+
+AssetStream::~AssetStream() {
+}
+
+piex::Error AssetStream::GetData(
+        const size_t offset, const size_t length, std::uint8_t* data) {
+    // Seek first.
+    if (mPosition != offset) {
+        if (!mStream->seek(offset)) {
+            return piex::Error::kFail;
+        }
+    }
+
+    // Read bytes.
+    size_t size = mStream->read((void*)data, length);
+    mPosition = offset + size;
+
+    return size == length ? piex::Error::kOk : piex::Error::kFail;
+}
+
+BufferedStream::BufferedStream(SkStream* stream)
+    : mStream(stream) {
+}
+
+BufferedStream::~BufferedStream() {
+}
+
+piex::Error BufferedStream::GetData(
+        const size_t offset, const size_t length, std::uint8_t* data) {
+    // Seek first.
+    if (offset + length > mStreamBuffer.bytesWritten()) {
+        size_t sizeToRead = offset + length - mStreamBuffer.bytesWritten();
+        if (sizeToRead <= kMinSizeToRead) {
+            sizeToRead = kMinSizeToRead;
+        }
+
+        void* tempBuffer = malloc(sizeToRead);
+        if (tempBuffer == NULL) {
+          return piex::Error::kFail;
+        }
+
+        size_t bytesRead = mStream->read(tempBuffer, sizeToRead);
+        if (bytesRead != sizeToRead) {
+            free(tempBuffer);
+            return piex::Error::kFail;
+        }
+        mStreamBuffer.write(tempBuffer, bytesRead);
+        free(tempBuffer);
+    }
+
+    // Read bytes.
+    if (mStreamBuffer.read((void*)data, offset, length)) {
+        return piex::Error::kOk;
+    } else {
+        return piex::Error::kFail;
+    }
+}
+
+FileStream::FileStream(const int fd)
+    : mPosition(0) {
+    mFile = fdopen(fd, "r");
+    if (mFile == NULL) {
+        return;
+    }
+}
+
+FileStream::FileStream(const String8 filename)
+    : mPosition(0) {
+    mFile = fopen(filename.string(), "r");
+    if (mFile == NULL) {
+        return;
+    }
+}
+
+FileStream::~FileStream() {
+    if (mFile != NULL) {
+        fclose(mFile);
+        mFile = NULL;
+    }
+}
+
+piex::Error FileStream::GetData(
+        const size_t offset, const size_t length, std::uint8_t* data) {
+    if (mFile == NULL) {
+        return piex::Error::kFail;
+    }
+
+    // Seek first.
+    if (mPosition != offset) {
+        fseek(mFile, offset, SEEK_SET);
+    }
+
+    // Read bytes.
+    size_t size = fread((void*)data, sizeof(std::uint8_t), length, mFile);
+    mPosition += size;
+
+    // Handle errors and verify the size.
+    if (ferror(mFile) || size != length) {
+        ALOGV("GetData read failed: (offset: %zu, length: %zu)", offset, length);
+        return piex::Error::kFail;
+    }
+    return piex::Error::kOk;
+}
+
+bool FileStream::exists() const {
+    return mFile != NULL;
+}
+
+bool GetExifFromRawImage(
+        piex::StreamInterface* stream, const String8& filename,
+        piex::PreviewImageData& image_data) {
+    // Reset the PreviewImageData to its default.
+    image_data = piex::PreviewImageData();
+
+    if (!piex::IsRaw(stream)) {
+        // Format not supported.
+        ALOGV("Format not supported: %s", filename.string());
+        return false;
+    }
+
+    piex::Error err = piex::GetPreviewImageData(stream, &image_data);
+
+    if (err != piex::Error::kOk) {
+        // The input data seems to be broken.
+        ALOGV("Raw image not detected: %s (piex error code: %d)", filename.string(), (int32_t)err);
+        return false;
+    }
+
+    return true;
+}
+
+bool ConvertKeyValueArraysToKeyedVector(
+        JNIEnv *env, jobjectArray keys, jobjectArray values,
+        KeyedVector<String8, String8>* keyedVector) {
+
+    int nKeyValuePairs = 0;
+    bool failed = false;
+    if (keys != NULL && values != NULL) {
+        nKeyValuePairs = env->GetArrayLength(keys);
+        failed = (nKeyValuePairs != env->GetArrayLength(values));
+    }
+
+    if (!failed) {
+        failed = ((keys != NULL && values == NULL) ||
+                  (keys == NULL && values != NULL));
+    }
+
+    if (failed) {
+        ALOGE("keys and values arrays have different length");
+        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
+        return false;
+    }
+
+    for (int i = 0; i < nKeyValuePairs; ++i) {
+        // No need to check on the ArrayIndexOutOfBoundsException, since
+        // it won't happen here.
+        jstring key = (jstring) env->GetObjectArrayElement(keys, i);
+        jstring value = (jstring) env->GetObjectArrayElement(values, i);
+
+        const char* keyStr = env->GetStringUTFChars(key, NULL);
+        if (!keyStr) {  // OutOfMemoryError
+            return false;
+        }
+
+        const char* valueStr = env->GetStringUTFChars(value, NULL);
+        if (!valueStr) {  // OutOfMemoryError
+            env->ReleaseStringUTFChars(key, keyStr);
+            return false;
+        }
+
+        keyedVector->add(String8(keyStr), String8(valueStr));
+
+        env->ReleaseStringUTFChars(key, keyStr);
+        env->ReleaseStringUTFChars(value, valueStr);
+        env->DeleteLocalRef(key);
+        env->DeleteLocalRef(value);
+    }
+    return true;
+}
+
+static jobject makeIntegerObject(JNIEnv *env, int32_t value) {
+    ScopedLocalRef<jclass> clazz(env, env->FindClass("java/lang/Integer"));
+    CHECK(clazz.get() != NULL);
+
+    jmethodID integerConstructID =
+        env->GetMethodID(clazz.get(), "<init>", "(I)V");
+    CHECK(integerConstructID != NULL);
+
+    return env->NewObject(clazz.get(), integerConstructID, value);
+}
+
+static jobject makeLongObject(JNIEnv *env, int64_t value) {
+    ScopedLocalRef<jclass> clazz(env, env->FindClass("java/lang/Long"));
+    CHECK(clazz.get() != NULL);
+
+    jmethodID longConstructID = env->GetMethodID(clazz.get(), "<init>", "(J)V");
+    CHECK(longConstructID != NULL);
+
+    return env->NewObject(clazz.get(), longConstructID, value);
+}
+
+static jobject makeFloatObject(JNIEnv *env, float value) {
+    ScopedLocalRef<jclass> clazz(env, env->FindClass("java/lang/Float"));
+    CHECK(clazz.get() != NULL);
+
+    jmethodID floatConstructID =
+        env->GetMethodID(clazz.get(), "<init>", "(F)V");
+    CHECK(floatConstructID != NULL);
+
+    return env->NewObject(clazz.get(), floatConstructID, value);
+}
+
+static jobject makeByteBufferObject(
+        JNIEnv *env, const void *data, size_t size) {
+    jbyteArray byteArrayObj = env->NewByteArray(size);
+    env->SetByteArrayRegion(byteArrayObj, 0, size, (const jbyte *)data);
+
+    ScopedLocalRef<jclass> clazz(env, env->FindClass("java/nio/ByteBuffer"));
+    CHECK(clazz.get() != NULL);
+
+    jmethodID byteBufWrapID =
+        env->GetStaticMethodID(
+                clazz.get(), "wrap", "([B)Ljava/nio/ByteBuffer;");
+    CHECK(byteBufWrapID != NULL);
+
+    jobject byteBufObj = env->CallStaticObjectMethod(
+            clazz.get(), byteBufWrapID, byteArrayObj);
+
+    env->DeleteLocalRef(byteArrayObj); byteArrayObj = NULL;
+
+    return byteBufObj;
+}
+
+static void SetMapInt32(
+        JNIEnv *env, jobject hashMapObj, jmethodID hashMapPutID,
+        const char *key, int32_t value) {
+    jstring keyObj = env->NewStringUTF(key);
+    jobject valueObj = makeIntegerObject(env, value);
+
+    env->CallObjectMethod(hashMapObj, hashMapPutID, keyObj, valueObj);
+
+    env->DeleteLocalRef(valueObj); valueObj = NULL;
+    env->DeleteLocalRef(keyObj); keyObj = NULL;
+}
+
+status_t ConvertMessageToMap(
+        JNIEnv *env, const sp<AMessage> &msg, jobject *map) {
+    ScopedLocalRef<jclass> hashMapClazz(
+            env, env->FindClass("java/util/HashMap"));
+
+    if (hashMapClazz.get() == NULL) {
+        return -EINVAL;
+    }
+
+    jmethodID hashMapConstructID =
+        env->GetMethodID(hashMapClazz.get(), "<init>", "()V");
+
+    if (hashMapConstructID == NULL) {
+        return -EINVAL;
+    }
+
+    jmethodID hashMapPutID =
+        env->GetMethodID(
+                hashMapClazz.get(),
+                "put",
+                "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
+
+    if (hashMapPutID == NULL) {
+        return -EINVAL;
+    }
+
+    jobject hashMap = env->NewObject(hashMapClazz.get(), hashMapConstructID);
+
+    for (size_t i = 0; i < msg->countEntries(); ++i) {
+        AMessage::Type valueType;
+        const char *key = msg->getEntryNameAt(i, &valueType);
+
+        if (!strncmp(key, "android._", 9)) {
+            // don't expose private keys (starting with android._)
+            continue;
+        }
+
+        jobject valueObj = NULL;
+
+        switch (valueType) {
+            case AMessage::kTypeInt32:
+            {
+                int32_t val;
+                CHECK(msg->findInt32(key, &val));
+
+                valueObj = makeIntegerObject(env, val);
+                break;
+            }
+
+            case AMessage::kTypeInt64:
+            {
+                int64_t val;
+                CHECK(msg->findInt64(key, &val));
+
+                valueObj = makeLongObject(env, val);
+                break;
+            }
+
+            case AMessage::kTypeFloat:
+            {
+                float val;
+                CHECK(msg->findFloat(key, &val));
+
+                valueObj = makeFloatObject(env, val);
+                break;
+            }
+
+            case AMessage::kTypeString:
+            {
+                AString val;
+                CHECK(msg->findString(key, &val));
+
+                valueObj = env->NewStringUTF(val.c_str());
+                break;
+            }
+
+            case AMessage::kTypeBuffer:
+            {
+                sp<ABuffer> buffer;
+                CHECK(msg->findBuffer(key, &buffer));
+
+                valueObj = makeByteBufferObject(
+                        env, buffer->data(), buffer->size());
+                break;
+            }
+
+            case AMessage::kTypeRect:
+            {
+                int32_t left, top, right, bottom;
+                CHECK(msg->findRect(key, &left, &top, &right, &bottom));
+
+                SetMapInt32(
+                        env,
+                        hashMap,
+                        hashMapPutID,
+                        AStringPrintf("%s-left", key).c_str(),
+                        left);
+
+                SetMapInt32(
+                        env,
+                        hashMap,
+                        hashMapPutID,
+                        AStringPrintf("%s-top", key).c_str(),
+                        top);
+
+                SetMapInt32(
+                        env,
+                        hashMap,
+                        hashMapPutID,
+                        AStringPrintf("%s-right", key).c_str(),
+                        right);
+
+                SetMapInt32(
+                        env,
+                        hashMap,
+                        hashMapPutID,
+                        AStringPrintf("%s-bottom", key).c_str(),
+                        bottom);
+                break;
+            }
+
+            default:
+                break;
+        }
+
+        if (valueObj != NULL) {
+            jstring keyObj = env->NewStringUTF(key);
+
+            env->CallObjectMethod(hashMap, hashMapPutID, keyObj, valueObj);
+
+            env->DeleteLocalRef(keyObj); keyObj = NULL;
+            env->DeleteLocalRef(valueObj); valueObj = NULL;
+        }
+    }
+
+    *map = hashMap;
+
+    return OK;
+}
+
+status_t ConvertKeyValueArraysToMessage(
+        JNIEnv *env, jobjectArray keys, jobjectArray values,
+        sp<AMessage> *out) {
+    ScopedLocalRef<jclass> stringClass(env, env->FindClass("java/lang/String"));
+    CHECK(stringClass.get() != NULL);
+    ScopedLocalRef<jclass> integerClass(env, env->FindClass("java/lang/Integer"));
+    CHECK(integerClass.get() != NULL);
+    ScopedLocalRef<jclass> longClass(env, env->FindClass("java/lang/Long"));
+    CHECK(longClass.get() != NULL);
+    ScopedLocalRef<jclass> floatClass(env, env->FindClass("java/lang/Float"));
+    CHECK(floatClass.get() != NULL);
+    ScopedLocalRef<jclass> byteBufClass(env, env->FindClass("java/nio/ByteBuffer"));
+    CHECK(byteBufClass.get() != NULL);
+
+    sp<AMessage> msg = new AMessage;
+
+    jsize numEntries = 0;
+
+    if (keys != NULL) {
+        if (values == NULL) {
+            return -EINVAL;
+        }
+
+        numEntries = env->GetArrayLength(keys);
+
+        if (numEntries != env->GetArrayLength(values)) {
+            return -EINVAL;
+        }
+    } else if (values != NULL) {
+        return -EINVAL;
+    }
+
+    for (jsize i = 0; i < numEntries; ++i) {
+        jobject keyObj = env->GetObjectArrayElement(keys, i);
+
+        if (!env->IsInstanceOf(keyObj, stringClass.get())) {
+            return -EINVAL;
+        }
+
+        const char *tmp = env->GetStringUTFChars((jstring)keyObj, NULL);
+
+        if (tmp == NULL) {
+            return -ENOMEM;
+        }
+
+        AString key = tmp;
+
+        env->ReleaseStringUTFChars((jstring)keyObj, tmp);
+        tmp = NULL;
+
+        if (key.startsWith("android._")) {
+            // don't propagate private keys (starting with android._)
+            continue;
+        }
+
+        jobject valueObj = env->GetObjectArrayElement(values, i);
+
+        if (env->IsInstanceOf(valueObj, stringClass.get())) {
+            const char *value = env->GetStringUTFChars((jstring)valueObj, NULL);
+
+            if (value == NULL) {
+                return -ENOMEM;
+            }
+
+            msg->setString(key.c_str(), value);
+
+            env->ReleaseStringUTFChars((jstring)valueObj, value);
+            value = NULL;
+        } else if (env->IsInstanceOf(valueObj, integerClass.get())) {
+            jmethodID intValueID =
+                env->GetMethodID(integerClass.get(), "intValue", "()I");
+            CHECK(intValueID != NULL);
+
+            jint value = env->CallIntMethod(valueObj, intValueID);
+
+            msg->setInt32(key.c_str(), value);
+        } else if (env->IsInstanceOf(valueObj, longClass.get())) {
+            jmethodID longValueID =
+                env->GetMethodID(longClass.get(), "longValue", "()J");
+            CHECK(longValueID != NULL);
+
+            jlong value = env->CallLongMethod(valueObj, longValueID);
+
+            msg->setInt64(key.c_str(), value);
+        } else if (env->IsInstanceOf(valueObj, floatClass.get())) {
+            jmethodID floatValueID =
+                env->GetMethodID(floatClass.get(), "floatValue", "()F");
+            CHECK(floatValueID != NULL);
+
+            jfloat value = env->CallFloatMethod(valueObj, floatValueID);
+
+            msg->setFloat(key.c_str(), value);
+        } else if (env->IsInstanceOf(valueObj, byteBufClass.get())) {
+            jmethodID positionID =
+                env->GetMethodID(byteBufClass.get(), "position", "()I");
+            CHECK(positionID != NULL);
+
+            jmethodID limitID =
+                env->GetMethodID(byteBufClass.get(), "limit", "()I");
+            CHECK(limitID != NULL);
+
+            jint position = env->CallIntMethod(valueObj, positionID);
+            jint limit = env->CallIntMethod(valueObj, limitID);
+
+            sp<ABuffer> buffer = new ABuffer(limit - position);
+
+            void *data = env->GetDirectBufferAddress(valueObj);
+
+            if (data != NULL) {
+                memcpy(buffer->data(),
+                       (const uint8_t *)data + position,
+                       buffer->size());
+            } else {
+                jmethodID arrayID =
+                    env->GetMethodID(byteBufClass.get(), "array", "()[B");
+                CHECK(arrayID != NULL);
+
+                jbyteArray byteArray =
+                    (jbyteArray)env->CallObjectMethod(valueObj, arrayID);
+                CHECK(byteArray != NULL);
+
+                env->GetByteArrayRegion(
+                        byteArray,
+                        position,
+                        buffer->size(),
+                        (jbyte *)buffer->data());
+
+                env->DeleteLocalRef(byteArray); byteArray = NULL;
+            }
+
+            msg->setBuffer(key.c_str(), buffer);
+        }
+    }
+
+    *out = msg;
+
+    return OK;
+}
+
+}  // namespace android
+
diff --git a/media/jni/android_media_Streams.h b/media/jni/android_media_Streams.h
new file mode 100644
index 0000000..d174f9a
--- /dev/null
+++ b/media/jni/android_media_Streams.h
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2019, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _ANDROID_MEDIA_STREAMS_H_
+#define _ANDROID_MEDIA_STREAMS_H_
+
+#include "src/piex_types.h"
+#include "src/piex.h"
+
+#include <jni.h>
+#include <nativehelper/JNIHelp.h>
+#include <utils/KeyedVector.h>
+#include <utils/String8.h>
+#include <utils/StrongPointer.h>
+#include <SkStream.h>
+
+
+namespace android {
+
+class AssetStream : public piex::StreamInterface {
+private:
+    SkStream *mStream;
+    size_t mPosition;
+
+public:
+    explicit AssetStream(SkStream* stream);
+    ~AssetStream();
+
+    // Reads 'length' amount of bytes from 'offset' to 'data'. The 'data' buffer
+    // provided by the caller, guaranteed to be at least "length" bytes long.
+    // On 'kOk' the 'data' pointer contains 'length' valid bytes beginning at
+    // 'offset' bytes from the start of the stream.
+    // Returns 'kFail' if 'offset' + 'length' exceeds the stream and does not
+    // change the contents of 'data'.
+    piex::Error GetData(
+            const size_t offset, const size_t length, std::uint8_t* data) override;
+};
+
+class BufferedStream : public piex::StreamInterface {
+private:
+    SkStream *mStream;
+    // Growable memory stream
+    SkDynamicMemoryWStream mStreamBuffer;
+
+    // Minimum size to read on filling the buffer.
+    const size_t kMinSizeToRead = 8192;
+
+public:
+    explicit BufferedStream(SkStream* stream);
+    ~BufferedStream();
+
+    // Reads 'length' amount of bytes from 'offset' to 'data'. The 'data' buffer
+    // provided by the caller, guaranteed to be at least "length" bytes long.
+    // On 'kOk' the 'data' pointer contains 'length' valid bytes beginning at
+    // 'offset' bytes from the start of the stream.
+    // Returns 'kFail' if 'offset' + 'length' exceeds the stream and does not
+    // change the contents of 'data'.
+    piex::Error GetData(
+            const size_t offset, const size_t length, std::uint8_t* data) override;
+};
+
+class FileStream : public piex::StreamInterface {
+private:
+    FILE *mFile;
+    size_t mPosition;
+
+public:
+    explicit FileStream(const int fd);
+    explicit FileStream(const String8 filename);
+    ~FileStream();
+
+    // Reads 'length' amount of bytes from 'offset' to 'data'. The 'data' buffer
+    // provided by the caller, guaranteed to be at least "length" bytes long.
+    // On 'kOk' the 'data' pointer contains 'length' valid bytes beginning at
+    // 'offset' bytes from the start of the stream.
+    // Returns 'kFail' if 'offset' + 'length' exceeds the stream and does not
+    // change the contents of 'data'.
+    piex::Error GetData(
+            const size_t offset, const size_t length, std::uint8_t* data) override;
+    bool exists() const;
+};
+
+// Reads EXIF metadata from a given raw image via piex.
+// And returns true if the operation is successful; otherwise, false.
+bool GetExifFromRawImage(
+        piex::StreamInterface* stream, const String8& filename, piex::PreviewImageData& image_data);
+
+// Returns true if the conversion is successful; otherwise, false.
+bool ConvertKeyValueArraysToKeyedVector(
+        JNIEnv *env, jobjectArray keys, jobjectArray values,
+        KeyedVector<String8, String8>* vector);
+
+struct AMessage;
+status_t ConvertMessageToMap(
+        JNIEnv *env, const sp<AMessage> &msg, jobject *map);
+
+status_t ConvertKeyValueArraysToMessage(
+        JNIEnv *env, jobjectArray keys, jobjectArray values,
+        sp<AMessage> *msg);
+
+};  // namespace android
+
+#endif //  _ANDROID_MEDIA_STREAMS_H_
diff --git a/media/jni/android_media_Utils.cpp b/media/jni/android_media_Utils.cpp
index 01baadb..2ef7b9e 100644
--- a/media/jni/android_media_Utils.cpp
+++ b/media/jni/android_media_Utils.cpp
@@ -21,12 +21,6 @@
 #include <utils/Log.h>
 #include "android_media_Utils.h"
 
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/ABuffer.h>
-#include <media/stagefright/foundation/AMessage.h>
-
-#include <nativehelper/ScopedLocalRef.h>
-
 #define ALIGN(x, mask) ( ((x) + (mask) - 1) & ~((mask) - 1) )
 
 // Must be in sync with the value in HeicCompositeStream.cpp
@@ -34,533 +28,6 @@
 
 namespace android {
 
-AssetStream::AssetStream(SkStream* stream)
-    : mStream(stream), mPosition(0) {
-}
-
-AssetStream::~AssetStream() {
-}
-
-piex::Error AssetStream::GetData(
-        const size_t offset, const size_t length, std::uint8_t* data) {
-    // Seek first.
-    if (mPosition != offset) {
-        if (!mStream->seek(offset)) {
-            return piex::Error::kFail;
-        }
-    }
-
-    // Read bytes.
-    size_t size = mStream->read((void*)data, length);
-    mPosition = offset + size;
-
-    return size == length ? piex::Error::kOk : piex::Error::kFail;
-}
-
-BufferedStream::BufferedStream(SkStream* stream)
-    : mStream(stream) {
-}
-
-BufferedStream::~BufferedStream() {
-}
-
-piex::Error BufferedStream::GetData(
-        const size_t offset, const size_t length, std::uint8_t* data) {
-    // Seek first.
-    if (offset + length > mStreamBuffer.bytesWritten()) {
-        size_t sizeToRead = offset + length - mStreamBuffer.bytesWritten();
-        if (sizeToRead <= kMinSizeToRead) {
-            sizeToRead = kMinSizeToRead;
-        }
-
-        void* tempBuffer = malloc(sizeToRead);
-        if (tempBuffer == NULL) {
-          return piex::Error::kFail;
-        }
-
-        size_t bytesRead = mStream->read(tempBuffer, sizeToRead);
-        if (bytesRead != sizeToRead) {
-            free(tempBuffer);
-            return piex::Error::kFail;
-        }
-        mStreamBuffer.write(tempBuffer, bytesRead);
-        free(tempBuffer);
-    }
-
-    // Read bytes.
-    if (mStreamBuffer.read((void*)data, offset, length)) {
-        return piex::Error::kOk;
-    } else {
-        return piex::Error::kFail;
-    }
-}
-
-FileStream::FileStream(const int fd)
-    : mPosition(0) {
-    mFile = fdopen(fd, "r");
-    if (mFile == NULL) {
-        return;
-    }
-}
-
-FileStream::FileStream(const String8 filename)
-    : mPosition(0) {
-    mFile = fopen(filename.string(), "r");
-    if (mFile == NULL) {
-        return;
-    }
-}
-
-FileStream::~FileStream() {
-    if (mFile != NULL) {
-        fclose(mFile);
-        mFile = NULL;
-    }
-}
-
-piex::Error FileStream::GetData(
-        const size_t offset, const size_t length, std::uint8_t* data) {
-    if (mFile == NULL) {
-        return piex::Error::kFail;
-    }
-
-    // Seek first.
-    if (mPosition != offset) {
-        fseek(mFile, offset, SEEK_SET);
-    }
-
-    // Read bytes.
-    size_t size = fread((void*)data, sizeof(std::uint8_t), length, mFile);
-    mPosition += size;
-
-    // Handle errors and verify the size.
-    if (ferror(mFile) || size != length) {
-        ALOGV("GetData read failed: (offset: %zu, length: %zu)", offset, length);
-        return piex::Error::kFail;
-    }
-    return piex::Error::kOk;
-}
-
-bool FileStream::exists() const {
-    return mFile != NULL;
-}
-
-bool GetExifFromRawImage(
-        piex::StreamInterface* stream, const String8& filename,
-        piex::PreviewImageData& image_data) {
-    // Reset the PreviewImageData to its default.
-    image_data = piex::PreviewImageData();
-
-    if (!piex::IsRaw(stream)) {
-        // Format not supported.
-        ALOGV("Format not supported: %s", filename.string());
-        return false;
-    }
-
-    piex::Error err = piex::GetPreviewImageData(stream, &image_data);
-
-    if (err != piex::Error::kOk) {
-        // The input data seems to be broken.
-        ALOGV("Raw image not detected: %s (piex error code: %d)", filename.string(), (int32_t)err);
-        return false;
-    }
-
-    return true;
-}
-
-bool ConvertKeyValueArraysToKeyedVector(
-        JNIEnv *env, jobjectArray keys, jobjectArray values,
-        KeyedVector<String8, String8>* keyedVector) {
-
-    int nKeyValuePairs = 0;
-    bool failed = false;
-    if (keys != NULL && values != NULL) {
-        nKeyValuePairs = env->GetArrayLength(keys);
-        failed = (nKeyValuePairs != env->GetArrayLength(values));
-    }
-
-    if (!failed) {
-        failed = ((keys != NULL && values == NULL) ||
-                  (keys == NULL && values != NULL));
-    }
-
-    if (failed) {
-        ALOGE("keys and values arrays have different length");
-        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
-        return false;
-    }
-
-    for (int i = 0; i < nKeyValuePairs; ++i) {
-        // No need to check on the ArrayIndexOutOfBoundsException, since
-        // it won't happen here.
-        jstring key = (jstring) env->GetObjectArrayElement(keys, i);
-        jstring value = (jstring) env->GetObjectArrayElement(values, i);
-
-        const char* keyStr = env->GetStringUTFChars(key, NULL);
-        if (!keyStr) {  // OutOfMemoryError
-            return false;
-        }
-
-        const char* valueStr = env->GetStringUTFChars(value, NULL);
-        if (!valueStr) {  // OutOfMemoryError
-            env->ReleaseStringUTFChars(key, keyStr);
-            return false;
-        }
-
-        keyedVector->add(String8(keyStr), String8(valueStr));
-
-        env->ReleaseStringUTFChars(key, keyStr);
-        env->ReleaseStringUTFChars(value, valueStr);
-        env->DeleteLocalRef(key);
-        env->DeleteLocalRef(value);
-    }
-    return true;
-}
-
-static jobject makeIntegerObject(JNIEnv *env, int32_t value) {
-    ScopedLocalRef<jclass> clazz(env, env->FindClass("java/lang/Integer"));
-    CHECK(clazz.get() != NULL);
-
-    jmethodID integerConstructID =
-        env->GetMethodID(clazz.get(), "<init>", "(I)V");
-    CHECK(integerConstructID != NULL);
-
-    return env->NewObject(clazz.get(), integerConstructID, value);
-}
-
-static jobject makeLongObject(JNIEnv *env, int64_t value) {
-    ScopedLocalRef<jclass> clazz(env, env->FindClass("java/lang/Long"));
-    CHECK(clazz.get() != NULL);
-
-    jmethodID longConstructID = env->GetMethodID(clazz.get(), "<init>", "(J)V");
-    CHECK(longConstructID != NULL);
-
-    return env->NewObject(clazz.get(), longConstructID, value);
-}
-
-static jobject makeFloatObject(JNIEnv *env, float value) {
-    ScopedLocalRef<jclass> clazz(env, env->FindClass("java/lang/Float"));
-    CHECK(clazz.get() != NULL);
-
-    jmethodID floatConstructID =
-        env->GetMethodID(clazz.get(), "<init>", "(F)V");
-    CHECK(floatConstructID != NULL);
-
-    return env->NewObject(clazz.get(), floatConstructID, value);
-}
-
-static jobject makeByteBufferObject(
-        JNIEnv *env, const void *data, size_t size) {
-    jbyteArray byteArrayObj = env->NewByteArray(size);
-    env->SetByteArrayRegion(byteArrayObj, 0, size, (const jbyte *)data);
-
-    ScopedLocalRef<jclass> clazz(env, env->FindClass("java/nio/ByteBuffer"));
-    CHECK(clazz.get() != NULL);
-
-    jmethodID byteBufWrapID =
-        env->GetStaticMethodID(
-                clazz.get(), "wrap", "([B)Ljava/nio/ByteBuffer;");
-    CHECK(byteBufWrapID != NULL);
-
-    jobject byteBufObj = env->CallStaticObjectMethod(
-            clazz.get(), byteBufWrapID, byteArrayObj);
-
-    env->DeleteLocalRef(byteArrayObj); byteArrayObj = NULL;
-
-    return byteBufObj;
-}
-
-static void SetMapInt32(
-        JNIEnv *env, jobject hashMapObj, jmethodID hashMapPutID,
-        const char *key, int32_t value) {
-    jstring keyObj = env->NewStringUTF(key);
-    jobject valueObj = makeIntegerObject(env, value);
-
-    env->CallObjectMethod(hashMapObj, hashMapPutID, keyObj, valueObj);
-
-    env->DeleteLocalRef(valueObj); valueObj = NULL;
-    env->DeleteLocalRef(keyObj); keyObj = NULL;
-}
-
-status_t ConvertMessageToMap(
-        JNIEnv *env, const sp<AMessage> &msg, jobject *map) {
-    ScopedLocalRef<jclass> hashMapClazz(
-            env, env->FindClass("java/util/HashMap"));
-
-    if (hashMapClazz.get() == NULL) {
-        return -EINVAL;
-    }
-
-    jmethodID hashMapConstructID =
-        env->GetMethodID(hashMapClazz.get(), "<init>", "()V");
-
-    if (hashMapConstructID == NULL) {
-        return -EINVAL;
-    }
-
-    jmethodID hashMapPutID =
-        env->GetMethodID(
-                hashMapClazz.get(),
-                "put",
-                "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
-
-    if (hashMapPutID == NULL) {
-        return -EINVAL;
-    }
-
-    jobject hashMap = env->NewObject(hashMapClazz.get(), hashMapConstructID);
-
-    for (size_t i = 0; i < msg->countEntries(); ++i) {
-        AMessage::Type valueType;
-        const char *key = msg->getEntryNameAt(i, &valueType);
-
-        if (!strncmp(key, "android._", 9)) {
-            // don't expose private keys (starting with android._)
-            continue;
-        }
-
-        jobject valueObj = NULL;
-
-        switch (valueType) {
-            case AMessage::kTypeInt32:
-            {
-                int32_t val;
-                CHECK(msg->findInt32(key, &val));
-
-                valueObj = makeIntegerObject(env, val);
-                break;
-            }
-
-            case AMessage::kTypeInt64:
-            {
-                int64_t val;
-                CHECK(msg->findInt64(key, &val));
-
-                valueObj = makeLongObject(env, val);
-                break;
-            }
-
-            case AMessage::kTypeFloat:
-            {
-                float val;
-                CHECK(msg->findFloat(key, &val));
-
-                valueObj = makeFloatObject(env, val);
-                break;
-            }
-
-            case AMessage::kTypeString:
-            {
-                AString val;
-                CHECK(msg->findString(key, &val));
-
-                valueObj = env->NewStringUTF(val.c_str());
-                break;
-            }
-
-            case AMessage::kTypeBuffer:
-            {
-                sp<ABuffer> buffer;
-                CHECK(msg->findBuffer(key, &buffer));
-
-                valueObj = makeByteBufferObject(
-                        env, buffer->data(), buffer->size());
-                break;
-            }
-
-            case AMessage::kTypeRect:
-            {
-                int32_t left, top, right, bottom;
-                CHECK(msg->findRect(key, &left, &top, &right, &bottom));
-
-                SetMapInt32(
-                        env,
-                        hashMap,
-                        hashMapPutID,
-                        AStringPrintf("%s-left", key).c_str(),
-                        left);
-
-                SetMapInt32(
-                        env,
-                        hashMap,
-                        hashMapPutID,
-                        AStringPrintf("%s-top", key).c_str(),
-                        top);
-
-                SetMapInt32(
-                        env,
-                        hashMap,
-                        hashMapPutID,
-                        AStringPrintf("%s-right", key).c_str(),
-                        right);
-
-                SetMapInt32(
-                        env,
-                        hashMap,
-                        hashMapPutID,
-                        AStringPrintf("%s-bottom", key).c_str(),
-                        bottom);
-                break;
-            }
-
-            default:
-                break;
-        }
-
-        if (valueObj != NULL) {
-            jstring keyObj = env->NewStringUTF(key);
-
-            env->CallObjectMethod(hashMap, hashMapPutID, keyObj, valueObj);
-
-            env->DeleteLocalRef(keyObj); keyObj = NULL;
-            env->DeleteLocalRef(valueObj); valueObj = NULL;
-        }
-    }
-
-    *map = hashMap;
-
-    return OK;
-}
-
-status_t ConvertKeyValueArraysToMessage(
-        JNIEnv *env, jobjectArray keys, jobjectArray values,
-        sp<AMessage> *out) {
-    ScopedLocalRef<jclass> stringClass(env, env->FindClass("java/lang/String"));
-    CHECK(stringClass.get() != NULL);
-    ScopedLocalRef<jclass> integerClass(env, env->FindClass("java/lang/Integer"));
-    CHECK(integerClass.get() != NULL);
-    ScopedLocalRef<jclass> longClass(env, env->FindClass("java/lang/Long"));
-    CHECK(longClass.get() != NULL);
-    ScopedLocalRef<jclass> floatClass(env, env->FindClass("java/lang/Float"));
-    CHECK(floatClass.get() != NULL);
-    ScopedLocalRef<jclass> byteBufClass(env, env->FindClass("java/nio/ByteBuffer"));
-    CHECK(byteBufClass.get() != NULL);
-
-    sp<AMessage> msg = new AMessage;
-
-    jsize numEntries = 0;
-
-    if (keys != NULL) {
-        if (values == NULL) {
-            return -EINVAL;
-        }
-
-        numEntries = env->GetArrayLength(keys);
-
-        if (numEntries != env->GetArrayLength(values)) {
-            return -EINVAL;
-        }
-    } else if (values != NULL) {
-        return -EINVAL;
-    }
-
-    for (jsize i = 0; i < numEntries; ++i) {
-        jobject keyObj = env->GetObjectArrayElement(keys, i);
-
-        if (!env->IsInstanceOf(keyObj, stringClass.get())) {
-            return -EINVAL;
-        }
-
-        const char *tmp = env->GetStringUTFChars((jstring)keyObj, NULL);
-
-        if (tmp == NULL) {
-            return -ENOMEM;
-        }
-
-        AString key = tmp;
-
-        env->ReleaseStringUTFChars((jstring)keyObj, tmp);
-        tmp = NULL;
-
-        if (key.startsWith("android._")) {
-            // don't propagate private keys (starting with android._)
-            continue;
-        }
-
-        jobject valueObj = env->GetObjectArrayElement(values, i);
-
-        if (env->IsInstanceOf(valueObj, stringClass.get())) {
-            const char *value = env->GetStringUTFChars((jstring)valueObj, NULL);
-
-            if (value == NULL) {
-                return -ENOMEM;
-            }
-
-            msg->setString(key.c_str(), value);
-
-            env->ReleaseStringUTFChars((jstring)valueObj, value);
-            value = NULL;
-        } else if (env->IsInstanceOf(valueObj, integerClass.get())) {
-            jmethodID intValueID =
-                env->GetMethodID(integerClass.get(), "intValue", "()I");
-            CHECK(intValueID != NULL);
-
-            jint value = env->CallIntMethod(valueObj, intValueID);
-
-            msg->setInt32(key.c_str(), value);
-        } else if (env->IsInstanceOf(valueObj, longClass.get())) {
-            jmethodID longValueID =
-                env->GetMethodID(longClass.get(), "longValue", "()J");
-            CHECK(longValueID != NULL);
-
-            jlong value = env->CallLongMethod(valueObj, longValueID);
-
-            msg->setInt64(key.c_str(), value);
-        } else if (env->IsInstanceOf(valueObj, floatClass.get())) {
-            jmethodID floatValueID =
-                env->GetMethodID(floatClass.get(), "floatValue", "()F");
-            CHECK(floatValueID != NULL);
-
-            jfloat value = env->CallFloatMethod(valueObj, floatValueID);
-
-            msg->setFloat(key.c_str(), value);
-        } else if (env->IsInstanceOf(valueObj, byteBufClass.get())) {
-            jmethodID positionID =
-                env->GetMethodID(byteBufClass.get(), "position", "()I");
-            CHECK(positionID != NULL);
-
-            jmethodID limitID =
-                env->GetMethodID(byteBufClass.get(), "limit", "()I");
-            CHECK(limitID != NULL);
-
-            jint position = env->CallIntMethod(valueObj, positionID);
-            jint limit = env->CallIntMethod(valueObj, limitID);
-
-            sp<ABuffer> buffer = new ABuffer(limit - position);
-
-            void *data = env->GetDirectBufferAddress(valueObj);
-
-            if (data != NULL) {
-                memcpy(buffer->data(),
-                       (const uint8_t *)data + position,
-                       buffer->size());
-            } else {
-                jmethodID arrayID =
-                    env->GetMethodID(byteBufClass.get(), "array", "()[B");
-                CHECK(arrayID != NULL);
-
-                jbyteArray byteArray =
-                    (jbyteArray)env->CallObjectMethod(valueObj, arrayID);
-                CHECK(byteArray != NULL);
-
-                env->GetByteArrayRegion(
-                        byteArray,
-                        position,
-                        buffer->size(),
-                        (jbyte *)buffer->data());
-
-                env->DeleteLocalRef(byteArray); byteArray = NULL;
-            }
-
-            msg->setBuffer(key.c_str(), buffer);
-        }
-    }
-
-    *out = msg;
-
-    return OK;
-}
-
 // -----------Utility functions used by ImageReader/Writer JNI-----------------
 
 enum {
diff --git a/media/jni/android_media_Utils.h b/media/jni/android_media_Utils.h
index 19c1b88..12841c0 100644
--- a/media/jni/android_media_Utils.h
+++ b/media/jni/android_media_Utils.h
@@ -17,100 +17,10 @@
 #ifndef _ANDROID_MEDIA_UTILS_H_
 #define _ANDROID_MEDIA_UTILS_H_
 
-#include "src/piex_types.h"
-#include "src/piex.h"
-
-#include <android_runtime/AndroidRuntime.h>
 #include <gui/CpuConsumer.h>
-#include <jni.h>
-#include <nativehelper/JNIHelp.h>
-#include <utils/KeyedVector.h>
-#include <utils/String8.h>
-#include <SkStream.h>
 
 namespace android {
 
-class AssetStream : public piex::StreamInterface {
-private:
-    SkStream *mStream;
-    size_t mPosition;
-
-public:
-    explicit AssetStream(SkStream* stream);
-    ~AssetStream();
-
-    // Reads 'length' amount of bytes from 'offset' to 'data'. The 'data' buffer
-    // provided by the caller, guaranteed to be at least "length" bytes long.
-    // On 'kOk' the 'data' pointer contains 'length' valid bytes beginning at
-    // 'offset' bytes from the start of the stream.
-    // Returns 'kFail' if 'offset' + 'length' exceeds the stream and does not
-    // change the contents of 'data'.
-    piex::Error GetData(
-            const size_t offset, const size_t length, std::uint8_t* data) override;
-};
-
-class BufferedStream : public piex::StreamInterface {
-private:
-    SkStream *mStream;
-    // Growable memory stream
-    SkDynamicMemoryWStream mStreamBuffer;
-
-    // Minimum size to read on filling the buffer.
-    const size_t kMinSizeToRead = 8192;
-
-public:
-    explicit BufferedStream(SkStream* stream);
-    ~BufferedStream();
-
-    // Reads 'length' amount of bytes from 'offset' to 'data'. The 'data' buffer
-    // provided by the caller, guaranteed to be at least "length" bytes long.
-    // On 'kOk' the 'data' pointer contains 'length' valid bytes beginning at
-    // 'offset' bytes from the start of the stream.
-    // Returns 'kFail' if 'offset' + 'length' exceeds the stream and does not
-    // change the contents of 'data'.
-    piex::Error GetData(
-            const size_t offset, const size_t length, std::uint8_t* data) override;
-};
-
-class FileStream : public piex::StreamInterface {
-private:
-    FILE *mFile;
-    size_t mPosition;
-
-public:
-    explicit FileStream(const int fd);
-    explicit FileStream(const String8 filename);
-    ~FileStream();
-
-    // Reads 'length' amount of bytes from 'offset' to 'data'. The 'data' buffer
-    // provided by the caller, guaranteed to be at least "length" bytes long.
-    // On 'kOk' the 'data' pointer contains 'length' valid bytes beginning at
-    // 'offset' bytes from the start of the stream.
-    // Returns 'kFail' if 'offset' + 'length' exceeds the stream and does not
-    // change the contents of 'data'.
-    piex::Error GetData(
-            const size_t offset, const size_t length, std::uint8_t* data) override;
-    bool exists() const;
-};
-
-// Reads EXIF metadata from a given raw image via piex.
-// And returns true if the operation is successful; otherwise, false.
-bool GetExifFromRawImage(
-        piex::StreamInterface* stream, const String8& filename, piex::PreviewImageData& image_data);
-
-// Returns true if the conversion is successful; otherwise, false.
-bool ConvertKeyValueArraysToKeyedVector(
-        JNIEnv *env, jobjectArray keys, jobjectArray values,
-        KeyedVector<String8, String8>* vector);
-
-struct AMessage;
-status_t ConvertMessageToMap(
-        JNIEnv *env, const sp<AMessage> &msg, jobject *map);
-
-status_t ConvertKeyValueArraysToMessage(
-        JNIEnv *env, jobjectArray keys, jobjectArray values,
-        sp<AMessage> *msg);
-
 // -----------Utility functions used by ImageReader/Writer JNI-----------------
 
 typedef CpuConsumer::LockedBuffer LockedImage;
diff --git a/media/jni/android_mtp_MtpDatabase.cpp b/media/jni/android_mtp_MtpDatabase.cpp
index 06a7182..1f89d86 100644
--- a/media/jni/android_mtp_MtpDatabase.cpp
+++ b/media/jni/android_mtp_MtpDatabase.cpp
@@ -18,7 +18,7 @@
 #include "utils/Log.h"
 #include "utils/String8.h"
 
-#include "android_media_Utils.h"
+#include "android_media_Streams.h"
 #include "mtp.h"
 #include "IMtpDatabase.h"
 #include "MtpDataPacket.h"
diff --git a/native/android/choreographer.cpp b/native/android/choreographer.cpp
index 2db575b..3fecd53 100644
--- a/native/android/choreographer.cpp
+++ b/native/android/choreographer.cpp
@@ -70,6 +70,8 @@
 
     void dispatchVsync(nsecs_t timestamp, PhysicalDisplayId displayId, uint32_t count) override;
     void dispatchHotplug(nsecs_t timestamp, PhysicalDisplayId displayId, bool connected) override;
+    void dispatchConfigChanged(nsecs_t timestamp, PhysicalDisplayId displayId,
+                               int32_t configId) override;
 
     void scheduleCallbacks();
 
@@ -164,6 +166,13 @@
             this, displayId, toString(connected));
 }
 
+void Choreographer::dispatchConfigChanged(nsecs_t, PhysicalDisplayId displayId,
+                                          int32_t configId) {
+    ALOGV("choreographer %p ~ received config changed event (displayId=%"
+            ANDROID_PHYSICAL_DISPLAY_ID_FORMAT ", configId=%s), ignoring.",
+            this, displayId, toString(configId));
+}
+
 void Choreographer::handleMessage(const Message& message) {
     switch (message.what) {
     case MSG_SCHEDULE_CALLBACKS:
diff --git a/packages/CaptivePortalLogin/AndroidManifest.xml b/packages/CaptivePortalLogin/AndroidManifest.xml
index 0894ee5..a5f3b88fe 100644
--- a/packages/CaptivePortalLogin/AndroidManifest.xml
+++ b/packages/CaptivePortalLogin/AndroidManifest.xml
@@ -17,8 +17,11 @@
  */
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.captiveportallogin" >
+    package="com.android.captiveportallogin"
+    android:versionCode="10"
+    android:versionName="Q-initial">
 
+    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="28" />
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
diff --git a/packages/CarSystemUI/res/drawable/car_ic_selection_bg.xml b/packages/CarSystemUI/res/drawable/car_ic_selection_bg.xml
index 781beaf..12993f5 100644
--- a/packages/CarSystemUI/res/drawable/car_ic_selection_bg.xml
+++ b/packages/CarSystemUI/res/drawable/car_ic_selection_bg.xml
@@ -20,7 +20,7 @@
     android:viewportHeight="70.0"
     android:viewportWidth="70.0">
     <path
-        android:fillColor="@color/car_accent"
+        android:fillColor="?android:attr/colorAccent"
         android:fillType="evenOdd"
         android:pathData="M4,0L66,0A4,4 0,0 1,70 4L70,66A4,4 0,0 1,66 70L4,70A4,4 0,0 1,0 66L0,4A4,4 0,0 1,4 0z"
         android:strokeColor="#00000000"
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
index 369bb9f..bd0e0b8 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
@@ -92,6 +92,10 @@
 
     @Override
     public void start() {
+        // get the provisioned state before calling the parent class since it's that flow that
+        // builds the nav bar
+        mDeviceProvisionedController = Dependency.get(DeviceProvisionedController.class);
+        mDeviceIsProvisioned = mDeviceProvisionedController.isDeviceProvisioned();
         super.start();
         mTaskStackListener = new TaskStackListenerImpl();
         mActivityManagerWrapper = ActivityManagerWrapper.getInstance();
@@ -105,8 +109,6 @@
         mHvacController.connectToCarService();
 
         CarSystemUIFactory factory = SystemUIFactory.getInstance();
-        mDeviceProvisionedController = Dependency.get(DeviceProvisionedController.class);
-        mDeviceIsProvisioned = mDeviceProvisionedController.isDeviceProvisioned();
         if (!mDeviceIsProvisioned) {
             mDeviceProvisionedController.addCallback(
                     new DeviceProvisionedController.DeviceProvisionedListener() {
diff --git a/packages/ExtServices/src/android/ext/services/notification/AssistantSettings.java b/packages/ExtServices/src/android/ext/services/notification/AssistantSettings.java
index 6cf72a4..ba361c4 100644
--- a/packages/ExtServices/src/android/ext/services/notification/AssistantSettings.java
+++ b/packages/ExtServices/src/android/ext/services/notification/AssistantSettings.java
@@ -26,6 +26,7 @@
 import android.util.Log;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
 
 /**
  * Observes the settings for {@link Assistant}.
@@ -103,7 +104,7 @@
 
     private void registerDeviceConfigs() {
         DeviceConfig.addOnPropertyChangedListener(
-                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
                 this::postToHandler,
                 this::onDeviceConfigPropertyChanged);
 
@@ -117,7 +118,7 @@
 
     @VisibleForTesting
     void onDeviceConfigPropertyChanged(String namespace, String name, String value) {
-        if (!DeviceConfig.NotificationAssistant.NAMESPACE.equals(namespace)) {
+        if (!DeviceConfig.NAMESPACE_SYSTEMUI.equals(namespace)) {
             Log.e(LOG_TAG, "Received update from DeviceConfig for unrelated namespace: "
                     + namespace + " " + name + "=" + value);
             return;
@@ -128,17 +129,17 @@
 
     private void updateFromDeviceConfigFlags() {
         mGenerateReplies = DeviceConfigHelper.getBoolean(
-                DeviceConfig.NotificationAssistant.GENERATE_REPLIES, DEFAULT_GENERATE_REPLIES);
+                SystemUiDeviceConfigFlags.NAS_GENERATE_REPLIES, DEFAULT_GENERATE_REPLIES);
 
         mGenerateActions = DeviceConfigHelper.getBoolean(
-                DeviceConfig.NotificationAssistant.GENERATE_ACTIONS, DEFAULT_GENERATE_ACTIONS);
+                SystemUiDeviceConfigFlags.NAS_GENERATE_ACTIONS, DEFAULT_GENERATE_ACTIONS);
 
         mMaxMessagesToExtract = DeviceConfigHelper.getInteger(
-                DeviceConfig.NotificationAssistant.MAX_MESSAGES_TO_EXTRACT,
+                SystemUiDeviceConfigFlags.NAS_MAX_MESSAGES_TO_EXTRACT,
                 DEFAULT_MAX_MESSAGES_TO_EXTRACT);
 
         mMaxSuggestions = DeviceConfigHelper.getInteger(
-                DeviceConfig.NotificationAssistant.MAX_SUGGESTIONS, DEFAULT_MAX_SUGGESTIONS);
+                SystemUiDeviceConfigFlags.NAS_MAX_SUGGESTIONS, DEFAULT_MAX_SUGGESTIONS);
 
         mOnUpdateRunnable.run();
     }
@@ -193,8 +194,7 @@
 
         private static String getValue(String key) {
             return DeviceConfig.getProperty(
-                    DeviceConfig.NotificationAssistant.NAMESPACE,
-                    key);
+                    DeviceConfig.NAMESPACE_SYSTEMUI, key);
         }
     }
 
@@ -202,4 +202,4 @@
         AssistantSettings createAndRegister(Handler handler, ContentResolver resolver, int userId,
                 Runnable onUpdateRunnable);
     }
-}
\ No newline at end of file
+}
diff --git a/packages/ExtServices/tests/Android.bp b/packages/ExtServices/tests/Android.bp
index 930b783..ae60d4e 100644
--- a/packages/ExtServices/tests/Android.bp
+++ b/packages/ExtServices/tests/Android.bp
@@ -14,14 +14,14 @@
 
     static_libs: [
         "ExtServices-core",
-        "android-support-test",
-        "compatibility-device-util",
+        "androidx.test.rules",
+        "compatibility-device-util-axt",
         "mockito-target-minus-junit4",
-        "espresso-core",
+        "androidx.test.espresso.core",
         "truth-prebuilt",
         "testables",
         "testng",
     ],
 
     platform_apis: true,
-}
\ No newline at end of file
+}
diff --git a/packages/ExtServices/tests/AndroidManifest.xml b/packages/ExtServices/tests/AndroidManifest.xml
index 3cf1527..a08a10e 100644
--- a/packages/ExtServices/tests/AndroidManifest.xml
+++ b/packages/ExtServices/tests/AndroidManifest.xml
@@ -23,7 +23,7 @@
         <uses-library android:name="android.test.runner" />
     </application>
 
-    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
                      android:targetPackage="android.ext.services.tests.unit"
                      android:label="ExtServices Test Cases">
     </instrumentation>
diff --git a/packages/ExtServices/tests/AndroidTest.xml b/packages/ExtServices/tests/AndroidTest.xml
index c3d32de..cd26ebc 100644
--- a/packages/ExtServices/tests/AndroidTest.xml
+++ b/packages/ExtServices/tests/AndroidTest.xml
@@ -23,7 +23,7 @@
     <option name="test-tag" value="ExtServicesUnitTests" />
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.ext.services.tests.unit" />
-        <option name="runner" value="android.support.test.runner.AndroidJUnitRunner" />
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
         <option name="hidden-api-checks" value="false"/>
     </test>
 </configuration>
\ No newline at end of file
diff --git a/packages/ExtServices/tests/src/android/ext/services/notification/AgingHelperTest.java b/packages/ExtServices/tests/src/android/ext/services/notification/AgingHelperTest.java
index 90018e5f..3db275a 100644
--- a/packages/ExtServices/tests/src/android/ext/services/notification/AgingHelperTest.java
+++ b/packages/ExtServices/tests/src/android/ext/services/notification/AgingHelperTest.java
@@ -39,10 +39,11 @@
 import android.os.Process;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.runner.AndroidJUnit4;
 import android.testing.TestableContext;
 
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
diff --git a/packages/ExtServices/tests/src/android/ext/services/notification/AssistantSettingsTest.java b/packages/ExtServices/tests/src/android/ext/services/notification/AssistantSettingsTest.java
index d890c1a..eeabb86 100644
--- a/packages/ExtServices/tests/src/android/ext/services/notification/AssistantSettingsTest.java
+++ b/packages/ExtServices/tests/src/android/ext/services/notification/AssistantSettingsTest.java
@@ -17,7 +17,6 @@
 package android.ext.services.notification;
 
 import static android.ext.services.notification.AssistantSettings.DEFAULT_MAX_SUGGESTIONS;
-import static android.provider.DeviceConfig.NotificationAssistant;
 import static android.provider.DeviceConfig.setProperty;
 
 import static junit.framework.Assert.assertFalse;
@@ -30,12 +29,16 @@
 import android.content.ContentResolver;
 import android.os.Handler;
 import android.os.Looper;
+import android.provider.DeviceConfig;
 import android.provider.Settings;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.runner.AndroidJUnit4;
 import android.support.test.uiautomator.UiDevice;
 import android.testing.TestableContext;
 
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
@@ -49,7 +52,7 @@
 @RunWith(AndroidJUnit4.class)
 public class AssistantSettingsTest {
     private static final String CLEAR_DEVICE_CONFIG_KEY_CMD =
-            "device_config delete " + NotificationAssistant.NAMESPACE;
+            "device_config delete " + DeviceConfig.NAMESPACE_SYSTEMUI;
 
     private static final int USER_ID = 5;
 
@@ -87,13 +90,13 @@
     @Test
     public void testGenerateRepliesDisabled() {
         setProperty(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_REPLIES,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_REPLIES,
                 "false",
                 false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_REPLIES,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_REPLIES,
                 "false");
 
         assertFalse(mAssistantSettings.mGenerateReplies);
@@ -102,13 +105,13 @@
     @Test
     public void testGenerateRepliesEnabled() {
         setProperty(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_REPLIES,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_REPLIES,
                 "true",
                 false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_REPLIES,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_REPLIES,
                 "true");
 
         assertTrue(mAssistantSettings.mGenerateReplies);
@@ -117,25 +120,25 @@
     @Test
     public void testGenerateRepliesEmptyFlag() {
         setProperty(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_REPLIES,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_REPLIES,
                 "false",
                 false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_REPLIES,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_REPLIES,
                 "false");
 
         assertFalse(mAssistantSettings.mGenerateReplies);
 
         setProperty(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_REPLIES,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_REPLIES,
                 "",
                 false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_REPLIES,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_REPLIES,
                 "");
 
         // Go back to the default value.
@@ -145,13 +148,13 @@
     @Test
     public void testGenerateActionsDisabled() {
         setProperty(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_ACTIONS,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_ACTIONS,
                 "false",
                 false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_ACTIONS,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_ACTIONS,
                 "false");
 
         assertFalse(mAssistantSettings.mGenerateActions);
@@ -160,13 +163,13 @@
     @Test
     public void testGenerateActionsEnabled() {
         setProperty(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_ACTIONS,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_ACTIONS,
                 "true",
                 false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_ACTIONS,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_ACTIONS,
                 "true");
 
         assertTrue(mAssistantSettings.mGenerateActions);
@@ -175,25 +178,25 @@
     @Test
     public void testGenerateActionsEmptyFlag() {
         setProperty(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_ACTIONS,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_ACTIONS,
                 "false",
                 false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_ACTIONS,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_ACTIONS,
                 "false");
 
         assertFalse(mAssistantSettings.mGenerateActions);
 
         setProperty(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_ACTIONS,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_ACTIONS,
                 "",
                 false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.GENERATE_ACTIONS,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_GENERATE_ACTIONS,
                 "");
 
         // Go back to the default value.
@@ -203,13 +206,13 @@
     @Test
     public void testMaxMessagesToExtract() {
         setProperty(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.MAX_MESSAGES_TO_EXTRACT,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_MAX_MESSAGES_TO_EXTRACT,
                 "10",
                 false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.MAX_MESSAGES_TO_EXTRACT,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_MAX_MESSAGES_TO_EXTRACT,
                 "10");
 
         assertEquals(10, mAssistantSettings.mMaxMessagesToExtract);
@@ -218,13 +221,13 @@
     @Test
     public void testMaxSuggestions() {
         setProperty(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.MAX_SUGGESTIONS,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_MAX_SUGGESTIONS,
                 "5",
                 false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.MAX_SUGGESTIONS,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_MAX_SUGGESTIONS,
                 "5");
 
         assertEquals(5, mAssistantSettings.mMaxSuggestions);
@@ -233,8 +236,8 @@
     @Test
     public void testMaxSuggestionsEmpty() {
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                NotificationAssistant.NAMESPACE,
-                NotificationAssistant.MAX_SUGGESTIONS,
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.NAS_MAX_SUGGESTIONS,
                 "");
 
         assertEquals(DEFAULT_MAX_SUGGESTIONS, mAssistantSettings.mMaxSuggestions);
@@ -278,13 +281,14 @@
     private static void clearDeviceConfig() throws IOException {
         UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
         uiDevice.executeShellCommand(
-                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + NotificationAssistant.GENERATE_ACTIONS);
+                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + SystemUiDeviceConfigFlags.NAS_GENERATE_ACTIONS);
         uiDevice.executeShellCommand(
-                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + NotificationAssistant.GENERATE_REPLIES);
+                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + SystemUiDeviceConfigFlags.NAS_GENERATE_REPLIES);
         uiDevice.executeShellCommand(
-                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + NotificationAssistant.MAX_MESSAGES_TO_EXTRACT);
+                CLEAR_DEVICE_CONFIG_KEY_CMD + " "
+                + SystemUiDeviceConfigFlags.NAS_MAX_MESSAGES_TO_EXTRACT);
         uiDevice.executeShellCommand(
-                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + NotificationAssistant.MAX_SUGGESTIONS);
+                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + SystemUiDeviceConfigFlags.NAS_MAX_SUGGESTIONS);
     }
 
 }
diff --git a/packages/ExtServices/tests/src/android/ext/services/notification/AssistantTest.java b/packages/ExtServices/tests/src/android/ext/services/notification/AssistantTest.java
index f632814..459cd40 100644
--- a/packages/ExtServices/tests/src/android/ext/services/notification/AssistantTest.java
+++ b/packages/ExtServices/tests/src/android/ext/services/notification/AssistantTest.java
@@ -44,11 +44,12 @@
 import android.service.notification.NotificationListenerService.RankingMap;
 import android.service.notification.NotificationStats;
 import android.service.notification.StatusBarNotification;
-import android.support.test.InstrumentationRegistry;
 import android.test.ServiceTestCase;
 import android.testing.TestableContext;
 import android.util.AtomicFile;
 
+import androidx.test.InstrumentationRegistry;
+
 import com.android.internal.util.FastXmlSerializer;
 
 import org.junit.Before;
diff --git a/packages/ExtServices/tests/src/android/ext/services/notification/EntityTypeCounterTest.java b/packages/ExtServices/tests/src/android/ext/services/notification/EntityTypeCounterTest.java
index 2d29c7b..ada61d0 100644
--- a/packages/ExtServices/tests/src/android/ext/services/notification/EntityTypeCounterTest.java
+++ b/packages/ExtServices/tests/src/android/ext/services/notification/EntityTypeCounterTest.java
@@ -17,9 +17,10 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import android.support.test.runner.AndroidJUnit4;
 import android.view.textclassifier.TextClassifier;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
diff --git a/packages/ExtServices/tests/src/android/ext/services/notification/NotificationCategorizerTest.java b/packages/ExtServices/tests/src/android/ext/services/notification/NotificationCategorizerTest.java
index 05af6e7..ea77d31 100644
--- a/packages/ExtServices/tests/src/android/ext/services/notification/NotificationCategorizerTest.java
+++ b/packages/ExtServices/tests/src/android/ext/services/notification/NotificationCategorizerTest.java
@@ -32,10 +32,11 @@
 import android.app.NotificationChannel;
 import android.os.Process;
 import android.service.notification.StatusBarNotification;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.runner.AndroidJUnit4;
 import android.testing.TestableContext;
 
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
diff --git a/packages/ExtServices/tests/src/android/ext/services/notification/NotificationEntryTest.java b/packages/ExtServices/tests/src/android/ext/services/notification/NotificationEntryTest.java
index 2d44e79..f51e911 100644
--- a/packages/ExtServices/tests/src/android/ext/services/notification/NotificationEntryTest.java
+++ b/packages/ExtServices/tests/src/android/ext/services/notification/NotificationEntryTest.java
@@ -39,10 +39,11 @@
 import android.os.Process;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.runner.AndroidJUnit4;
 import android.testing.TestableContext;
 
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
diff --git a/packages/ExtServices/tests/src/android/ext/services/notification/SmartActionsHelperTest.java b/packages/ExtServices/tests/src/android/ext/services/notification/SmartActionsHelperTest.java
index d0b6d00..a1fbc7b 100644
--- a/packages/ExtServices/tests/src/android/ext/services/notification/SmartActionsHelperTest.java
+++ b/packages/ExtServices/tests/src/android/ext/services/notification/SmartActionsHelperTest.java
@@ -39,14 +39,15 @@
 import android.os.Process;
 import android.service.notification.NotificationAssistantService;
 import android.service.notification.StatusBarNotification;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.runner.AndroidJUnit4;
 import android.view.textclassifier.ConversationAction;
 import android.view.textclassifier.ConversationActions;
 import android.view.textclassifier.TextClassificationManager;
 import android.view.textclassifier.TextClassifier;
 import android.view.textclassifier.TextClassifierEvent;
 
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.google.common.truth.FailureStrategy;
 import com.google.common.truth.Subject;
 import com.google.common.truth.SubjectFactory;
diff --git a/packages/NetworkStack/Android.bp b/packages/NetworkStack/Android.bp
index b700bf3..5f1f26d 100644
--- a/packages/NetworkStack/Android.bp
+++ b/packages/NetworkStack/Android.bp
@@ -28,6 +28,7 @@
     static_libs: [
         "netd_aidl_interface-java",
         "networkstack-aidl-interfaces-java",
+        "datastallprotosnano",
     ]
 }
 
@@ -43,4 +44,4 @@
     jarjar_rules: "jarjar-rules-shared.txt",
     manifest: "AndroidManifest.xml",
     required: ["NetworkStackPermissionStub"],
-}
\ No newline at end of file
+}
diff --git a/packages/NetworkStack/AndroidManifest.xml b/packages/NetworkStack/AndroidManifest.xml
index 52c209e..740c573 100644
--- a/packages/NetworkStack/AndroidManifest.xml
+++ b/packages/NetworkStack/AndroidManifest.xml
@@ -18,7 +18,10 @@
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="com.android.networkstack"
-          android:sharedUserId="android.uid.networkstack">
+          android:sharedUserId="android.uid.networkstack"
+          android:versionCode="10"
+          android:versionName="Q-initial">
+    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="28" />
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
diff --git a/packages/NetworkStack/src/android/net/metrics/DataStallDetectionStats.java b/packages/NetworkStack/src/android/net/metrics/DataStallDetectionStats.java
new file mode 100644
index 0000000..225dc0f
--- /dev/null
+++ b/packages/NetworkStack/src/android/net/metrics/DataStallDetectionStats.java
@@ -0,0 +1,228 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.metrics;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.net.util.NetworkStackUtils;
+import android.net.wifi.WifiInfo;
+
+import com.android.internal.util.HexDump;
+import com.android.server.connectivity.nano.CellularData;
+import com.android.server.connectivity.nano.DataStallEventProto;
+import com.android.server.connectivity.nano.DnsEvent;
+import com.android.server.connectivity.nano.WifiData;
+
+import com.google.protobuf.nano.MessageNano;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Class to record the stats of detection level information for data stall.
+ *
+ * @hide
+ */
+public final class DataStallDetectionStats {
+    private static final int UNKNOWN_SIGNAL_STRENGTH = -1;
+    @NonNull
+    final byte[] mCellularInfo;
+    @NonNull
+    final byte[] mWifiInfo;
+    @NonNull
+    final byte[] mDns;
+    final int mEvaluationType;
+    final int mNetworkType;
+
+    public DataStallDetectionStats(@Nullable byte[] cell, @Nullable byte[] wifi,
+                @NonNull int[] returnCode, @NonNull long[] dnsTime, int evalType, int netType) {
+        mCellularInfo = emptyCellDataIfNull(cell);
+        mWifiInfo = emptyWifiInfoIfNull(wifi);
+
+        DnsEvent dns = new DnsEvent();
+        dns.dnsReturnCode = returnCode;
+        dns.dnsTime = dnsTime;
+        mDns = MessageNano.toByteArray(dns);
+        mEvaluationType = evalType;
+        mNetworkType = netType;
+    }
+
+    private byte[] emptyCellDataIfNull(@Nullable byte[] cell) {
+        if (cell != null) return cell;
+
+        CellularData data  = new CellularData();
+        data.ratType = DataStallEventProto.RADIO_TECHNOLOGY_UNKNOWN;
+        data.networkMccmnc = "";
+        data.simMccmnc = "";
+        data.signalStrength = UNKNOWN_SIGNAL_STRENGTH;
+        return MessageNano.toByteArray(data);
+    }
+
+    private byte[] emptyWifiInfoIfNull(@Nullable byte[] wifi) {
+        if (wifi != null) return wifi;
+
+        WifiData data = new WifiData();
+        data.wifiBand = DataStallEventProto.AP_BAND_UNKNOWN;
+        data.signalStrength = UNKNOWN_SIGNAL_STRENGTH;
+        return MessageNano.toByteArray(data);
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+        sb.append("type: ").append(mNetworkType)
+          .append(", evaluation type: ")
+          .append(mEvaluationType)
+          .append(", wifi info: ")
+          .append(HexDump.toHexString(mWifiInfo))
+          .append(", cell info: ")
+          .append(HexDump.toHexString(mCellularInfo))
+          .append(", dns: ")
+          .append(HexDump.toHexString(mDns));
+        return sb.toString();
+    }
+
+    @Override
+    public boolean equals(@Nullable final Object o) {
+        if (!(o instanceof DataStallDetectionStats)) return false;
+        final DataStallDetectionStats other = (DataStallDetectionStats) o;
+        return (mNetworkType == other.mNetworkType)
+            && (mEvaluationType == other.mEvaluationType)
+            && Arrays.equals(mWifiInfo, other.mWifiInfo)
+            && Arrays.equals(mCellularInfo, other.mCellularInfo)
+            && Arrays.equals(mDns, other.mDns);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(mNetworkType, mEvaluationType, mWifiInfo, mCellularInfo, mDns);
+    }
+
+    /**
+     * Utility to create an instance of {@Link DataStallDetectionStats}
+     *
+     * @hide
+     */
+    public static class Builder {
+        @Nullable
+        private byte[] mCellularInfo;
+        @Nullable
+        private byte[] mWifiInfo;
+        @NonNull
+        private final List<Integer> mDnsReturnCode = new ArrayList<Integer>();
+        @NonNull
+        private final List<Long> mDnsTimeStamp = new ArrayList<Long>();
+        private int mEvaluationType;
+        private int mNetworkType;
+
+        /**
+         * Add a dns event into Builder.
+         *
+         * @param code the return code of the dns event.
+         * @param timeMs the elapsedRealtime in ms that the the dns event was received from netd.
+         * @return {@code this} {@link Builder} instance.
+         */
+        public Builder addDnsEvent(int code, long timeMs) {
+            mDnsReturnCode.add(code);
+            mDnsTimeStamp.add(timeMs);
+            return this;
+        }
+
+        /**
+         * Set the dns evaluation type into Builder.
+         *
+         * @param type the return code of the dns event.
+         * @return {@code this} {@link Builder} instance.
+         */
+        public Builder setEvaluationType(int type) {
+            mEvaluationType = type;
+            return this;
+        }
+
+        /**
+         * Set the network type into Builder.
+         *
+         * @param type the network type of the logged network.
+         * @return {@code this} {@link Builder} instance.
+         */
+        public Builder setNetworkType(int type) {
+            mNetworkType = type;
+            return this;
+        }
+
+        /**
+         * Set the wifi data into Builder.
+         *
+         * @param info a {@link WifiInfo} of the connected wifi network.
+         * @return {@code this} {@link Builder} instance.
+         */
+        public Builder setWiFiData(@Nullable final WifiInfo info) {
+            WifiData data = new WifiData();
+            data.wifiBand = getWifiBand(info);
+            data.signalStrength = (info != null) ? info.getRssi() : UNKNOWN_SIGNAL_STRENGTH;
+            mWifiInfo = MessageNano.toByteArray(data);
+            return this;
+        }
+
+        private static int getWifiBand(@Nullable final WifiInfo info) {
+            if (info == null) return DataStallEventProto.AP_BAND_UNKNOWN;
+
+            int freq = info.getFrequency();
+            // Refer to ScanResult.is5GHz() and ScanResult.is24GHz().
+            if (freq > 4900 && freq < 5900) {
+                return DataStallEventProto.AP_BAND_5GHZ;
+            } else if (freq > 2400 && freq < 2500) {
+                return DataStallEventProto.AP_BAND_2GHZ;
+            } else {
+                return DataStallEventProto.AP_BAND_UNKNOWN;
+            }
+        }
+
+        /**
+         * Set the cellular data into Builder.
+         *
+         * @param radioType the radio technology of the logged cellular network.
+         * @param roaming a boolean indicates if logged cellular network is roaming or not.
+         * @param networkMccmnc the mccmnc of the camped network.
+         * @param simMccmnc the mccmnc of the sim.
+         * @return {@code this} {@link Builder} instance.
+         */
+        public Builder setCellData(int radioType, boolean roaming,
+                @NonNull String networkMccmnc, @NonNull String simMccmnc, int ss) {
+            CellularData data  = new CellularData();
+            data.ratType = radioType;
+            data.isRoaming = roaming;
+            data.networkMccmnc = networkMccmnc;
+            data.simMccmnc = simMccmnc;
+            data.signalStrength = ss;
+            mCellularInfo = MessageNano.toByteArray(data);
+            return this;
+        }
+
+        /**
+         * Create a new {@Link DataStallDetectionStats}.
+         */
+        public DataStallDetectionStats build() {
+            return new DataStallDetectionStats(mCellularInfo, mWifiInfo,
+                    NetworkStackUtils.convertToIntArray(mDnsReturnCode),
+                    NetworkStackUtils.convertToLongArray(mDnsTimeStamp),
+                    mEvaluationType, mNetworkType);
+        }
+    }
+}
diff --git a/packages/NetworkStack/src/android/net/metrics/DataStallStatsUtils.java b/packages/NetworkStack/src/android/net/metrics/DataStallStatsUtils.java
new file mode 100644
index 0000000..17a36ad
--- /dev/null
+++ b/packages/NetworkStack/src/android/net/metrics/DataStallStatsUtils.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.metrics;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.net.captiveportal.CaptivePortalProbeResult;
+import android.util.Log;
+
+import com.android.internal.util.HexDump;
+import com.android.server.connectivity.nano.DataStallEventProto;
+
+/**
+ * Collection of utilities for data stall metrics.
+ *
+ * To see if the logs are properly sent to statsd, execute following command.
+ *
+ * $ adb shell cmd stats print-logs
+ * $ adb logcat | grep statsd  OR $ adb logcat -b stats
+ *
+ * @hide
+ */
+public class DataStallStatsUtils {
+    private static final String TAG = DataStallStatsUtils.class.getSimpleName();
+    private static final boolean DBG = false;
+
+    private static int probeResultToEnum(@Nullable final CaptivePortalProbeResult result) {
+        if (result == null) return DataStallEventProto.INVALID;
+
+        // TODO: Add partial connectivity support.
+        if (result.isSuccessful()) {
+            return DataStallEventProto.VALID;
+        } else if (result.isPortal()) {
+            return DataStallEventProto.PORTAL;
+        } else {
+            return DataStallEventProto.INVALID;
+        }
+    }
+
+    /**
+     * Write the metric to {@link StatsLog}.
+     */
+    public static void write(@NonNull final DataStallDetectionStats stats,
+            @NonNull final CaptivePortalProbeResult result) {
+        int validationResult = probeResultToEnum(result);
+        if (DBG) {
+            Log.d(TAG, "write: " + stats + " with result: " + validationResult
+                    + ", dns: " + HexDump.toHexString(stats.mDns));
+        }
+        // TODO(b/124613085): Send to Statsd once the public StatsLog API is ready.
+    }
+}
diff --git a/packages/NetworkStack/src/android/net/util/NetworkStackUtils.java b/packages/NetworkStack/src/android/net/util/NetworkStackUtils.java
index 98123a5..481dbda 100644
--- a/packages/NetworkStack/src/android/net/util/NetworkStackUtils.java
+++ b/packages/NetworkStack/src/android/net/util/NetworkStackUtils.java
@@ -16,8 +16,11 @@
 
 package android.net.util;
 
+import android.annotation.NonNull;
+
 import java.io.FileDescriptor;
 import java.io.IOException;
+import java.util.List;
 
 /**
  * Collection of utilities for the network stack.
@@ -40,4 +43,26 @@
         } catch (IOException ignored) {
         }
     }
+
+    /**
+     * Returns an int array from the given Integer list.
+     */
+    public static int[] convertToIntArray(@NonNull List<Integer> list) {
+        int[] array = new int[list.size()];
+        for (int i = 0; i < list.size(); i++) {
+            array[i] = list.get(i);
+        }
+        return array;
+    }
+
+    /**
+     * Returns a long array from the given long list.
+     */
+    public static long[] convertToLongArray(@NonNull List<Long> list) {
+        long[] array = new long[list.size()];
+        for (int i = 0; i < list.size(); i++) {
+            array[i] = list.get(i);
+        }
+        return array;
+    }
 }
diff --git a/packages/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java b/packages/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
index 4b846b0..e82a5d7 100644
--- a/packages/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
+++ b/packages/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
@@ -33,6 +33,7 @@
 import static android.net.metrics.ValidationProbeEvent.PROBE_PRIVDNS;
 import static android.net.util.NetworkStackUtils.isEmpty;
 
+import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.app.PendingIntent;
 import android.content.BroadcastReceiver;
@@ -50,6 +51,8 @@
 import android.net.Uri;
 import android.net.captiveportal.CaptivePortalProbeResult;
 import android.net.captiveportal.CaptivePortalProbeSpec;
+import android.net.metrics.DataStallDetectionStats;
+import android.net.metrics.DataStallStatsUtils;
 import android.net.metrics.IpConnectivityLog;
 import android.net.metrics.NetworkEvent;
 import android.net.metrics.ValidationProbeEvent;
@@ -66,8 +69,10 @@
 import android.os.UserHandle;
 import android.provider.Settings;
 import android.telephony.AccessNetworkConstants;
+import android.telephony.CellSignalStrength;
 import android.telephony.NetworkRegistrationState;
 import android.telephony.ServiceState;
+import android.telephony.SignalStrength;
 import android.telephony.TelephonyManager;
 import android.text.TextUtils;
 import android.util.Log;
@@ -126,6 +131,9 @@
     private static final int DATA_STALL_EVALUATION_TYPE_DNS = 1;
     private static final int DEFAULT_DATA_STALL_EVALUATION_TYPES =
             (1 << DATA_STALL_EVALUATION_TYPE_DNS);
+    // Reevaluate it as intending to increase the number. Larger log size may cause statsd
+    // log buffer bust and have stats log lost.
+    private static final int DEFAULT_DNS_LOG_SIZE = 20;
 
     enum EvaluationResult {
         VALIDATED(true),
@@ -244,6 +252,7 @@
     private final ConnectivityManager mCm;
     private final IpConnectivityLog mMetricsLog;
     private final Dependencies mDependencies;
+    private final DataStallStatsUtils mDetectionStatsUtils;
 
     // Configuration values for captive portal detection probes.
     private final String mCaptivePortalUserAgent;
@@ -302,17 +311,19 @@
     private final int mDataStallEvaluationType;
     private final DnsStallDetector mDnsStallDetector;
     private long mLastProbeTime;
+    // Set to true if data stall is suspected and reset to false after metrics are sent to statsd.
+    private boolean mCollectDataStallMetrics = false;
 
     public NetworkMonitor(Context context, INetworkMonitorCallbacks cb, Network network,
             SharedLog validationLog) {
         this(context, cb, network, new IpConnectivityLog(), validationLog,
-                Dependencies.DEFAULT);
+                Dependencies.DEFAULT, new DataStallStatsUtils());
     }
 
     @VisibleForTesting
     protected NetworkMonitor(Context context, INetworkMonitorCallbacks cb, Network network,
             IpConnectivityLog logger, SharedLog validationLogs,
-            Dependencies deps) {
+            Dependencies deps, DataStallStatsUtils detectionStatsUtils) {
         // Add suffix indicating which NetworkMonitor we're talking about.
         super(TAG + "/" + network.toString());
 
@@ -325,6 +336,7 @@
         mValidationLogs = validationLogs;
         mCallback = cb;
         mDependencies = deps;
+        mDetectionStatsUtils = detectionStatsUtils;
         mNonPrivateDnsBypassNetwork = network;
         mNetwork = deps.getPrivateDnsBypassNetwork(network);
         mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
@@ -656,6 +668,7 @@
                 case EVENT_DNS_NOTIFICATION:
                     mDnsStallDetector.accumulateConsecutiveDnsTimeoutCount(message.arg1);
                     if (isDataStall()) {
+                        mCollectDataStallMetrics = true;
                         validationLog("Suspecting data stall, reevaluate");
                         transitionTo(mEvaluatingState);
                     }
@@ -667,6 +680,66 @@
         }
     }
 
+    private void writeDataStallStats(@NonNull final CaptivePortalProbeResult result) {
+        /*
+         * Collect data stall detection level information for each transport type. Collect type
+         * specific information for cellular and wifi only currently. Generate
+         * DataStallDetectionStats for each transport type. E.g., if a network supports both
+         * TRANSPORT_WIFI and TRANSPORT_VPN, two DataStallDetectionStats will be generated.
+         */
+        final int[] transports = mNetworkCapabilities.getTransportTypes();
+
+        for (int i = 0; i < transports.length; i++) {
+            DataStallStatsUtils.write(buildDataStallDetectionStats(transports[i]), result);
+        }
+        mCollectDataStallMetrics = false;
+    }
+
+    @VisibleForTesting
+    protected DataStallDetectionStats buildDataStallDetectionStats(int transport) {
+        final DataStallDetectionStats.Builder stats = new DataStallDetectionStats.Builder();
+        if (VDBG_STALL) log("collectDataStallMetrics: type=" + transport);
+        stats.setEvaluationType(DATA_STALL_EVALUATION_TYPE_DNS);
+        stats.setNetworkType(transport);
+        switch (transport) {
+            case NetworkCapabilities.TRANSPORT_WIFI:
+                // TODO: Update it if status query in dual wifi is supported.
+                final WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
+                stats.setWiFiData(wifiInfo);
+                break;
+            case NetworkCapabilities.TRANSPORT_CELLULAR:
+                final boolean isRoaming = !mNetworkCapabilities.hasCapability(
+                        NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
+                final SignalStrength ss = mTelephonyManager.getSignalStrength();
+                // TODO(b/120452078): Support multi-sim.
+                stats.setCellData(
+                        mTelephonyManager.getDataNetworkType(),
+                        isRoaming,
+                        mTelephonyManager.getNetworkOperator(),
+                        mTelephonyManager.getSimOperator(),
+                        (ss != null)
+                        ? ss.getLevel() : CellSignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN);
+                break;
+            default:
+                // No transport type specific information for the other types.
+                break;
+        }
+        addDnsEvents(stats);
+
+        return stats.build();
+    }
+
+    @VisibleForTesting
+    protected void addDnsEvents(@NonNull final DataStallDetectionStats.Builder stats) {
+        final int size = mDnsStallDetector.mResultIndices.size();
+        for (int i = 1; i <= DEFAULT_DNS_LOG_SIZE && i <= size; i++) {
+            final int index = mDnsStallDetector.mResultIndices.indexOf(size - i);
+            stats.addDnsEvent(mDnsStallDetector.mDnsEvents[index].mReturnCode,
+                    mDnsStallDetector.mDnsEvents[index].mTimeStamp);
+        }
+    }
+
+
     // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
     // is required.  This State takes care to clear the notification upon exit from the State.
     private class MaybeNotifyState extends State {
@@ -972,6 +1045,11 @@
                     final CaptivePortalProbeResult probeResult =
                             (CaptivePortalProbeResult) message.obj;
                     mLastProbeTime = SystemClock.elapsedRealtime();
+
+                    if (mCollectDataStallMetrics) {
+                        writeDataStallStats(probeResult);
+                    }
+
                     if (probeResult.isSuccessful()) {
                         // Transit EvaluatingPrivateDnsState to get to Validated
                         // state (even if no Private DNS validation required).
@@ -1617,7 +1695,6 @@
      */
     @VisibleForTesting
     protected class DnsStallDetector {
-        private static final int DEFAULT_DNS_LOG_SIZE = 50;
         private int mConsecutiveTimeoutCount = 0;
         private int mSize;
         final DnsResult[] mDnsEvents;
diff --git a/packages/NetworkStack/tests/Android.bp b/packages/NetworkStack/tests/Android.bp
index 5c7b514..f22b647 100644
--- a/packages/NetworkStack/tests/Android.bp
+++ b/packages/NetworkStack/tests/Android.bp
@@ -21,7 +21,7 @@
     test_suites: ["device-tests"],
     resource_dirs: ["res"],
     static_libs: [
-        "android-support-test",
+        "androidx.test.rules",
         "frameworks-base-testutils",
         "mockito-target-extended-minus-junit4",
         "NetworkStackLib",
diff --git a/packages/NetworkStack/tests/AndroidManifest.xml b/packages/NetworkStack/tests/AndroidManifest.xml
index 9cb2c21..5dcf6ff 100644
--- a/packages/NetworkStack/tests/AndroidManifest.xml
+++ b/packages/NetworkStack/tests/AndroidManifest.xml
@@ -47,7 +47,7 @@
     <application android:debuggable="true">
         <uses-library android:name="android.test.runner" />
     </application>
-    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
         android:targetPackage="com.android.server.networkstack.tests"
         android:label="Networking service tests">
     </instrumentation>
diff --git a/packages/NetworkStack/tests/AndroidTest.xml b/packages/NetworkStack/tests/AndroidTest.xml
index 6b08b57..047bc2e 100644
--- a/packages/NetworkStack/tests/AndroidTest.xml
+++ b/packages/NetworkStack/tests/AndroidTest.xml
@@ -23,7 +23,7 @@
     <option name="test-tag" value="NetworkStackTests" />
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="com.android.server.networkstack.tests" />
-        <option name="runner" value="android.support.test.runner.AndroidJUnitRunner" />
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
         <option name="hidden-api-checks" value="false"/>
     </test>
 </configuration>
\ No newline at end of file
diff --git a/packages/NetworkStack/tests/src/android/net/apf/ApfTest.java b/packages/NetworkStack/tests/src/android/net/apf/ApfTest.java
index 3414397..88a05d5 100644
--- a/packages/NetworkStack/tests/src/android/net/apf/ApfTest.java
+++ b/packages/NetworkStack/tests/src/android/net/apf/ApfTest.java
@@ -53,14 +53,15 @@
 import android.os.ConditionVariable;
 import android.os.Parcelable;
 import android.os.SystemClock;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.system.ErrnoException;
 import android.system.Os;
 import android.text.format.DateUtils;
 import android.util.Log;
 
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.internal.util.HexDump;
 import com.android.server.networkstack.tests.R;
 import com.android.server.util.NetworkStackConstants;
diff --git a/packages/NetworkStack/tests/src/android/net/dhcp/DhcpLeaseRepositoryTest.java b/packages/NetworkStack/tests/src/android/net/dhcp/DhcpLeaseRepositoryTest.java
index 4abd77e..27d7255 100644
--- a/packages/NetworkStack/tests/src/android/net/dhcp/DhcpLeaseRepositoryTest.java
+++ b/packages/NetworkStack/tests/src/android/net/dhcp/DhcpLeaseRepositoryTest.java
@@ -31,16 +31,15 @@
 import static org.junit.Assert.fail;
 import static org.mockito.Mockito.when;
 
-import static java.lang.String.format;
-
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.net.IpPrefix;
 import android.net.MacAddress;
 import android.net.dhcp.DhcpServer.Clock;
 import android.net.util.SharedLog;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -48,6 +47,8 @@
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
+import static java.lang.String.format;
+
 import java.net.Inet4Address;
 import java.util.Arrays;
 import java.util.Collections;
diff --git a/packages/NetworkStack/tests/src/android/net/dhcp/DhcpPacketTest.java b/packages/NetworkStack/tests/src/android/net/dhcp/DhcpPacketTest.java
index 7544e72..4d98403 100644
--- a/packages/NetworkStack/tests/src/android/net/dhcp/DhcpPacketTest.java
+++ b/packages/NetworkStack/tests/src/android/net/dhcp/DhcpPacketTest.java
@@ -48,8 +48,9 @@
 import android.net.LinkAddress;
 import android.net.NetworkUtils;
 import android.net.metrics.DhcpErrorEvent;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.util.HexDump;
 
@@ -324,7 +325,7 @@
     @Test
     public void testOffer1() throws Exception {
         // TODO: Turn all of these into golden files. This will probably require using
-        // android.support.test.InstrumentationRegistry for obtaining a Context object
+        // androidx.test.InstrumentationRegistry for obtaining a Context object
         // to read such golden files, along with an appropriate Android.mk.
         final ByteBuffer packet = ByteBuffer.wrap(HexDump.hexStringToByteArray(
             // IP header.
diff --git a/packages/NetworkStack/tests/src/android/net/dhcp/DhcpServerTest.java b/packages/NetworkStack/tests/src/android/net/dhcp/DhcpServerTest.java
index d4c1e2e..7d5e9e3 100644
--- a/packages/NetworkStack/tests/src/android/net/dhcp/DhcpServerTest.java
+++ b/packages/NetworkStack/tests/src/android/net/dhcp/DhcpServerTest.java
@@ -51,11 +51,12 @@
 import android.net.dhcp.DhcpServer.Dependencies;
 import android.net.util.SharedLog;
 import android.os.HandlerThread;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
diff --git a/packages/NetworkStack/tests/src/android/net/dhcp/DhcpServingParamsTest.java b/packages/NetworkStack/tests/src/android/net/dhcp/DhcpServingParamsTest.java
index 1004382..57a87a4 100644
--- a/packages/NetworkStack/tests/src/android/net/dhcp/DhcpServingParamsTest.java
+++ b/packages/NetworkStack/tests/src/android/net/dhcp/DhcpServingParamsTest.java
@@ -29,8 +29,9 @@
 import android.net.LinkAddress;
 import android.net.dhcp.DhcpServingParams.InvalidParameterException;
 import android.net.shared.Inet4AddressUtils;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
diff --git a/packages/NetworkStack/tests/src/android/net/ip/IpClientTest.java b/packages/NetworkStack/tests/src/android/net/ip/IpClientTest.java
index aaaff02..1990229 100644
--- a/packages/NetworkStack/tests/src/android/net/ip/IpClientTest.java
+++ b/packages/NetworkStack/tests/src/android/net/ip/IpClientTest.java
@@ -47,10 +47,11 @@
 import android.net.shared.ProvisioningConfiguration;
 import android.net.util.InterfaceParams;
 import android.provider.Settings;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.mock.MockContentResolver;
 
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.internal.R;
 import com.android.internal.util.test.FakeSettingsProvider;
 import com.android.server.NetworkObserver;
diff --git a/packages/NetworkStack/tests/src/android/net/ip/IpReachabilityMonitorTest.java b/packages/NetworkStack/tests/src/android/net/ip/IpReachabilityMonitorTest.java
index e3b5ddf..64b168a 100644
--- a/packages/NetworkStack/tests/src/android/net/ip/IpReachabilityMonitorTest.java
+++ b/packages/NetworkStack/tests/src/android/net/ip/IpReachabilityMonitorTest.java
@@ -24,8 +24,9 @@
 import android.net.util.SharedLog;
 import android.os.Handler;
 import android.os.Looper;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -33,7 +34,6 @@
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
-
 /**
  * Tests for IpReachabilityMonitor.
  */
diff --git a/packages/NetworkStack/tests/src/android/net/util/ConnectivityPacketSummaryTest.java b/packages/NetworkStack/tests/src/android/net/util/ConnectivityPacketSummaryTest.java
index dfaf52a..71be8b3 100644
--- a/packages/NetworkStack/tests/src/android/net/util/ConnectivityPacketSummaryTest.java
+++ b/packages/NetworkStack/tests/src/android/net/util/ConnectivityPacketSummaryTest.java
@@ -20,8 +20,9 @@
 import static org.junit.Assert.assertTrue;
 
 import android.net.MacAddress;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import libcore.util.HexEncoding;
 
diff --git a/packages/NetworkStack/tests/src/android/net/util/PacketReaderTest.java b/packages/NetworkStack/tests/src/android/net/util/PacketReaderTest.java
index 6e11c40..289dcad 100644
--- a/packages/NetworkStack/tests/src/android/net/util/PacketReaderTest.java
+++ b/packages/NetworkStack/tests/src/android/net/util/PacketReaderTest.java
@@ -31,12 +31,13 @@
 
 import android.os.Handler;
 import android.os.HandlerThread;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.system.ErrnoException;
 import android.system.Os;
 import android.system.StructTimeval;
 
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
diff --git a/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java b/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java
index 9a16bb7..04b906b 100644
--- a/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java
+++ b/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java
@@ -39,6 +39,7 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import android.annotation.NonNull;
 import android.content.Context;
 import android.net.ConnectivityManager;
 import android.net.INetworkMonitorCallbacks;
@@ -48,19 +49,24 @@
 import android.net.NetworkCapabilities;
 import android.net.NetworkInfo;
 import android.net.captiveportal.CaptivePortalProbeResult;
+import android.net.metrics.DataStallDetectionStats;
+import android.net.metrics.DataStallStatsUtils;
 import android.net.metrics.IpConnectivityLog;
 import android.net.util.SharedLog;
+import android.net.wifi.WifiInfo;
 import android.net.wifi.WifiManager;
 import android.os.Bundle;
 import android.os.ConditionVariable;
 import android.os.Handler;
 import android.os.SystemClock;
 import android.provider.Settings;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+import android.telephony.CellSignalStrength;
 import android.telephony.TelephonyManager;
 import android.util.ArrayMap;
 
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -77,7 +83,6 @@
 
 import javax.net.ssl.SSLHandshakeException;
 
-
 @RunWith(AndroidJUnit4.class)
 @SmallTest
 public class NetworkMonitorTest {
@@ -98,6 +103,8 @@
     private @Mock NetworkMonitor.Dependencies mDependencies;
     private @Mock INetworkMonitorCallbacks mCallbacks;
     private @Spy Network mNetwork = new Network(TEST_NETID);
+    private @Mock DataStallStatsUtils mDataStallStatsUtils;
+    private @Mock WifiInfo mWifiInfo;
 
     private static final int TEST_NETID = 4242;
 
@@ -105,10 +112,12 @@
     private static final String TEST_HTTPS_URL = "https://www.google.com/gen_204";
     private static final String TEST_FALLBACK_URL = "http://fallback.google.com/gen_204";
     private static final String TEST_OTHER_FALLBACK_URL = "http://otherfallback.google.com/gen_204";
+    private static final String TEST_MCCMNC = "123456";
 
     private static final int DATA_STALL_EVALUATION_TYPE_DNS = 1;
     private static final int RETURN_CODE_DNS_SUCCESS = 0;
     private static final int RETURN_CODE_DNS_TIMEOUT = 255;
+    private static final int DEFAULT_DNS_TIMEOUT_THRESHOLD = 5;
 
     private static final int HANDLER_TIMEOUT_MS = 1000;
 
@@ -186,9 +195,9 @@
         private long mProbeTime = 0;
 
         WrappedNetworkMonitor(Context context, Network network, IpConnectivityLog logger,
-                Dependencies deps) {
+                Dependencies deps, DataStallStatsUtils statsUtils) {
                 super(context, mCallbacks, network, logger,
-                        new SharedLog("test_nm"), deps);
+                        new SharedLog("test_nm"), deps, statsUtils);
         }
 
         @Override
@@ -199,11 +208,16 @@
         protected void setLastProbeTime(long time) {
             mProbeTime = time;
         }
+
+        @Override
+        protected void addDnsEvents(@NonNull final DataStallDetectionStats.Builder stats) {
+            generateTimeoutDnsEvent(stats, DEFAULT_DNS_TIMEOUT_THRESHOLD);
+        }
     }
 
     private WrappedNetworkMonitor makeMeteredWrappedNetworkMonitor() {
         final WrappedNetworkMonitor nm = new WrappedNetworkMonitor(
-                mContext, mNetwork, mLogger, mDependencies);
+                mContext, mNetwork, mLogger, mDependencies, mDataStallStatsUtils);
         when(mCm.getNetworkCapabilities(any())).thenReturn(METERED_CAPABILITIES);
         nm.start();
         waitForIdle(nm.getHandler());
@@ -212,7 +226,7 @@
 
     private WrappedNetworkMonitor makeNotMeteredWrappedNetworkMonitor() {
         final WrappedNetworkMonitor nm = new WrappedNetworkMonitor(
-                mContext, mNetwork, mLogger, mDependencies);
+                mContext, mNetwork, mLogger, mDependencies, mDataStallStatsUtils);
         when(mCm.getNetworkCapabilities(any())).thenReturn(NOT_METERED_CAPABILITIES);
         nm.start();
         waitForIdle(nm.getHandler());
@@ -222,7 +236,7 @@
     private NetworkMonitor makeMonitor() {
         final NetworkMonitor nm = new NetworkMonitor(
                 mContext, mCallbacks, mNetwork, mLogger, mValidationLogger,
-                mDependencies);
+                mDependencies, mDataStallStatsUtils);
         nm.start();
         waitForIdle(nm.getHandler());
         return nm;
@@ -384,7 +398,7 @@
     public void testIsDataStall_EvaluationDnsOnNotMeteredNetwork() {
         WrappedNetworkMonitor wrappedMonitor = makeNotMeteredWrappedNetworkMonitor();
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 100);
-        makeDnsTimeoutEvent(wrappedMonitor, 5);
+        makeDnsTimeoutEvent(wrappedMonitor, DEFAULT_DNS_TIMEOUT_THRESHOLD);
         assertTrue(wrappedMonitor.isDataStall());
     }
 
@@ -395,7 +409,7 @@
         assertFalse(wrappedMonitor.isDataStall());
 
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000);
-        makeDnsTimeoutEvent(wrappedMonitor, 5);
+        makeDnsTimeoutEvent(wrappedMonitor, DEFAULT_DNS_TIMEOUT_THRESHOLD);
         assertTrue(wrappedMonitor.isDataStall());
     }
 
@@ -429,7 +443,7 @@
         // Test dns events happened in valid dns time threshold.
         WrappedNetworkMonitor wrappedMonitor = makeMeteredWrappedNetworkMonitor();
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 100);
-        makeDnsTimeoutEvent(wrappedMonitor, 5);
+        makeDnsTimeoutEvent(wrappedMonitor, DEFAULT_DNS_TIMEOUT_THRESHOLD);
         assertFalse(wrappedMonitor.isDataStall());
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000);
         assertTrue(wrappedMonitor.isDataStall());
@@ -438,7 +452,7 @@
         setValidDataStallDnsTimeThreshold(0);
         wrappedMonitor = makeMeteredWrappedNetworkMonitor();
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 100);
-        makeDnsTimeoutEvent(wrappedMonitor, 5);
+        makeDnsTimeoutEvent(wrappedMonitor, DEFAULT_DNS_TIMEOUT_THRESHOLD);
         assertFalse(wrappedMonitor.isDataStall());
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000);
         assertFalse(wrappedMonitor.isDataStall());
@@ -505,6 +519,59 @@
                 .notifyNetworkTested(NETWORK_TEST_RESULT_VALID, null);
     }
 
+    @Test
+    public void testDataStall_StallSuspectedAndSendMetrics() throws IOException {
+        WrappedNetworkMonitor wrappedMonitor = makeNotMeteredWrappedNetworkMonitor();
+        wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000);
+        makeDnsTimeoutEvent(wrappedMonitor, 5);
+        assertTrue(wrappedMonitor.isDataStall());
+        verify(mDataStallStatsUtils, times(1)).write(any(), any());
+    }
+
+    @Test
+    public void testDataStall_NoStallSuspectedAndSendMetrics() throws IOException {
+        WrappedNetworkMonitor wrappedMonitor = makeNotMeteredWrappedNetworkMonitor();
+        wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000);
+        makeDnsTimeoutEvent(wrappedMonitor, 3);
+        assertFalse(wrappedMonitor.isDataStall());
+        verify(mDataStallStatsUtils, never()).write(any(), any());
+    }
+
+    @Test
+    public void testCollectDataStallMetrics() {
+        WrappedNetworkMonitor wrappedMonitor = makeNotMeteredWrappedNetworkMonitor();
+
+        when(mTelephony.getDataNetworkType()).thenReturn(TelephonyManager.NETWORK_TYPE_LTE);
+        when(mTelephony.getNetworkOperator()).thenReturn(TEST_MCCMNC);
+        when(mTelephony.getSimOperator()).thenReturn(TEST_MCCMNC);
+
+        DataStallDetectionStats.Builder stats =
+                new DataStallDetectionStats.Builder()
+                .setEvaluationType(DATA_STALL_EVALUATION_TYPE_DNS)
+                .setNetworkType(NetworkCapabilities.TRANSPORT_CELLULAR)
+                .setCellData(TelephonyManager.NETWORK_TYPE_LTE /* radioType */,
+                        true /* roaming */,
+                        TEST_MCCMNC /* networkMccmnc */,
+                        TEST_MCCMNC /* simMccmnc */,
+                        CellSignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN /* signalStrength */);
+        generateTimeoutDnsEvent(stats, DEFAULT_DNS_TIMEOUT_THRESHOLD);
+
+        assertEquals(wrappedMonitor.buildDataStallDetectionStats(
+                 NetworkCapabilities.TRANSPORT_CELLULAR), stats.build());
+
+        when(mWifi.getConnectionInfo()).thenReturn(mWifiInfo);
+
+        stats = new DataStallDetectionStats.Builder()
+                .setEvaluationType(DATA_STALL_EVALUATION_TYPE_DNS)
+                .setNetworkType(NetworkCapabilities.TRANSPORT_WIFI)
+                .setWiFiData(mWifiInfo);
+        generateTimeoutDnsEvent(stats, DEFAULT_DNS_TIMEOUT_THRESHOLD);
+
+        assertEquals(
+                wrappedMonitor.buildDataStallDetectionStats(NetworkCapabilities.TRANSPORT_WIFI),
+                stats.build());
+    }
+
     private void makeDnsTimeoutEvent(WrappedNetworkMonitor wrappedMonitor, int count) {
         for (int i = 0; i < count; i++) {
             wrappedMonitor.getDnsStallDetector().accumulateConsecutiveDnsTimeoutCount(
@@ -594,5 +661,11 @@
     private void setStatus(HttpURLConnection connection, int status) throws IOException {
         doReturn(status).when(connection).getResponseCode();
     }
+
+    private void generateTimeoutDnsEvent(DataStallDetectionStats.Builder stats, int num) {
+        for (int i = 0; i < num; i++) {
+            stats.addDnsEvent(RETURN_CODE_DNS_TIMEOUT, 123456789 /* timeMs */);
+        }
+    }
 }
 
diff --git a/packages/NetworkStack/tests/src/com/android/server/util/SharedLogTest.java b/packages/NetworkStack/tests/src/com/android/server/util/SharedLogTest.java
index 07ad3123..b1db051 100644
--- a/packages/NetworkStack/tests/src/com/android/server/util/SharedLogTest.java
+++ b/packages/NetworkStack/tests/src/com/android/server/util/SharedLogTest.java
@@ -20,8 +20,9 @@
 import static org.junit.Assert.assertTrue;
 
 import android.net.util.SharedLog;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
diff --git a/packages/NetworkStackPermissionStub/AndroidManifest.xml b/packages/NetworkStackPermissionStub/AndroidManifest.xml
index a8742d7..62bf3de 100644
--- a/packages/NetworkStackPermissionStub/AndroidManifest.xml
+++ b/packages/NetworkStackPermissionStub/AndroidManifest.xml
@@ -18,7 +18,10 @@
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.android.networkstack.permissionstub"
-    android:sharedUserId="android.uid.networkstack">
+    android:sharedUserId="android.uid.networkstack"
+    android:versionCode="10"
+    android:versionName="Q-initial">
+    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="28" />
     <!--
     This package only exists to define the below permissions, and enforce that they are only
     granted to apps sharing the same signature.
@@ -34,4 +37,4 @@
                 android:protectionLevel="signature"/>
 
     <application android:name="com.android.server.NetworkStackPermissionStub"/>
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/packages/SettingsLib/Android.bp b/packages/SettingsLib/Android.bp
index caa928f..730e9e1 100644
--- a/packages/SettingsLib/Android.bp
+++ b/packages/SettingsLib/Android.bp
@@ -29,7 +29,7 @@
 
     resource_dirs: ["res"],
 
-    srcs: ["src/**/*.java"],
+    srcs: ["src/**/*.java", "src/**/*.kt"],
 
     min_sdk_version: "21",
 
diff --git a/packages/SettingsLib/BarChartPreference/res/layout/settings_bar_view.xml b/packages/SettingsLib/BarChartPreference/res/layout/settings_bar_view.xml
index b053317..4bc68b3 100644
--- a/packages/SettingsLib/BarChartPreference/res/layout/settings_bar_view.xml
+++ b/packages/SettingsLib/BarChartPreference/res/layout/settings_bar_view.xml
@@ -25,8 +25,7 @@
     <View
         android:id="@+id/bar_view"
         android:layout_width="8dp"
-        android:layout_height="wrap_content"
-        android:background="?android:attr/colorAccent"/>
+        android:layout_height="wrap_content"/>
 
     <ImageView
         android:id="@+id/icon_view"
diff --git a/packages/SettingsLib/BarChartPreference/res/values/styles.xml b/packages/SettingsLib/BarChartPreference/res/values/styles.xml
index 647d080..4876cb6 100644
--- a/packages/SettingsLib/BarChartPreference/res/values/styles.xml
+++ b/packages/SettingsLib/BarChartPreference/res/values/styles.xml
@@ -18,7 +18,7 @@
 <resources>
     <style name="BarViewStyle">
         <item name="android:layout_width">0dp</item>
-        <item name="android:layout_height">wrap_content</item>
+        <item name="android:layout_height">226dp</item>
         <item name="android:layout_weight">1</item>
         <item name="android:layout_marginStart">8dp</item>
         <item name="android:layout_marginEnd">8dp</item>
diff --git a/packages/SettingsLib/BarChartPreference/src/com/android/settingslib/widget/BarChartPreference.java b/packages/SettingsLib/BarChartPreference/src/com/android/settingslib/widget/BarChartPreference.java
index 3b87fca..1003c97 100644
--- a/packages/SettingsLib/BarChartPreference/src/com/android/settingslib/widget/BarChartPreference.java
+++ b/packages/SettingsLib/BarChartPreference/src/com/android/settingslib/widget/BarChartPreference.java
@@ -160,8 +160,11 @@
 
         // If the state is loading, we just show a blank view.
         if (mIsLoading) {
+            holder.itemView.setVisibility(View.INVISIBLE);
             return;
         }
+        holder.itemView.setVisibility(View.VISIBLE);
+
         // We must show title of bar chart.
         bindChartTitleView(holder);
 
diff --git a/packages/SettingsLib/BarChartPreference/src/com/android/settingslib/widget/BarView.java b/packages/SettingsLib/BarChartPreference/src/com/android/settingslib/widget/BarView.java
index 6bf61ae..3ef0235 100644
--- a/packages/SettingsLib/BarChartPreference/src/com/android/settingslib/widget/BarView.java
+++ b/packages/SettingsLib/BarChartPreference/src/com/android/settingslib/widget/BarView.java
@@ -89,7 +89,7 @@
     private void init() {
         LayoutInflater.from(getContext()).inflate(R.layout.settings_bar_view, this);
         setOrientation(LinearLayout.VERTICAL);
-        setGravity(Gravity.CENTER);
+        setGravity(Gravity.CENTER | Gravity.BOTTOM);
 
         mBarView = findViewById(R.id.bar_view);
         mIcon = findViewById(R.id.icon_view);
diff --git a/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt b/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt
new file mode 100644
index 0000000..911cfcd
--- /dev/null
+++ b/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt
@@ -0,0 +1,412 @@
+/*
+ * 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.settingslib.graph
+
+import android.content.Context
+import android.graphics.BlendMode
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.ColorFilter
+import android.graphics.Matrix
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.PixelFormat
+import android.graphics.Rect
+import android.graphics.RectF
+import android.graphics.drawable.Drawable
+import android.util.PathParser
+import android.util.TypedValue
+
+import com.android.settingslib.R
+import com.android.settingslib.Utils
+
+/**
+ * A battery meter drawable that respects paths configured in
+ * frameworks/base/core/res/res/values/config.xml to allow for an easily overrideable battery icon
+ */
+open class ThemedBatteryDrawable(private val context: Context, frameColor: Int) : Drawable() {
+
+    // Need to load:
+    // 1. perimeter shape
+    // 2. fill mask (if smaller than perimeter, this would create a fill that
+    //    doesn't touch the walls
+    private val perimeterPath = Path()
+    private val scaledPerimeter = Path()
+    // Fill will cover the whole bounding rect of the fillMask, and be masked by the path
+    private val fillMask = Path()
+    private val scaledFill = Path()
+    // Based off of the mask, the fill will interpolate across this space
+    private val fillRect = RectF()
+    // Top of this rect changes based on level, 100% == fillRect
+    private val levelRect = RectF()
+    private val levelPath = Path()
+    // Updates the transform of the paths when our bounds change
+    private val scaleMatrix = Matrix()
+    private val padding = Rect()
+    // The net result of fill + perimeter paths
+    private val unifiedPath = Path()
+
+    // Bolt path (used while charging)
+    private val boltPath = Path()
+    private val scaledBolt = Path()
+
+    // Plus sign (used for power save mode)
+    private val plusPath = Path()
+    private val scaledPlus = Path()
+
+    private var intrinsicHeight: Int
+    private var intrinsicWidth: Int
+
+    // To implement hysteresis, keep track of the need to invert the interior icon of the battery
+    private var invertFillIcon = false
+
+    // Colors can be configured based on battery level (see res/values/arrays.xml)
+    private var colorLevels: IntArray
+
+    private var fillColor: Int = Color.MAGENTA
+    private var backgroundColor: Int = Color.MAGENTA
+    // updated whenever level changes
+    private var levelColor: Int = Color.MAGENTA
+
+    // Dual tone implies that battery level is a clipped overlay over top of the whole shape
+    private var dualTone = false
+
+    private val invalidateRunnable: () -> Unit = {
+        invalidateSelf()
+    }
+
+    open var criticalLevel: Int = context.resources.getInteger(
+            com.android.internal.R.integer.config_criticalBatteryWarningLevel)
+
+    var charging = false
+        set(value) {
+            field = value
+            postInvalidate()
+        }
+
+    var powerSaveEnabled = false
+        set(value) {
+            field = value
+            postInvalidate()
+        }
+
+    private val fillColorStrokePaint = Paint(Paint.ANTI_ALIAS_FLAG).also { p ->
+        p.color = frameColor
+        p.isDither = true
+        p.strokeWidth = 5f
+        p.style = Paint.Style.STROKE
+        p.blendMode = BlendMode.SRC
+        p.strokeMiter = 5f
+        p.strokeJoin = Paint.Join.ROUND
+    }
+
+    private val fillColorStrokeProtection = Paint(Paint.ANTI_ALIAS_FLAG).also { p ->
+        p.isDither = true
+        p.strokeWidth = 5f
+        p.style = Paint.Style.STROKE
+        p.blendMode = BlendMode.CLEAR
+        p.strokeMiter = 5f
+        p.strokeJoin = Paint.Join.ROUND
+    }
+
+    private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).also { p ->
+        p.color = frameColor
+        p.alpha = 255
+        p.isDither = true
+        p.strokeWidth = 0f
+        p.style = Paint.Style.FILL_AND_STROKE
+    }
+
+    // Only used if dualTone is set to true
+    private val dualToneBackgroundFill = Paint(Paint.ANTI_ALIAS_FLAG).also { p ->
+        p.color = frameColor
+        p.alpha = 255
+        p.isDither = true
+        p.strokeWidth = 0f
+        p.style = Paint.Style.FILL_AND_STROKE
+    }
+
+    init {
+        val density = context.resources.displayMetrics.density
+        intrinsicHeight = (Companion.HEIGHT * density).toInt()
+        intrinsicWidth = (Companion.WIDTH * density).toInt()
+
+        val res = context.resources
+        val levels = res.obtainTypedArray(R.array.batterymeter_color_levels)
+        val colors = res.obtainTypedArray(R.array.batterymeter_color_values)
+        val N = levels.length()
+        colorLevels = IntArray(2 * N)
+        for (i in 0 until N) {
+            colorLevels[2 * i] = levels.getInt(i, 0)
+            if (colors.getType(i) == TypedValue.TYPE_ATTRIBUTE) {
+                colorLevels[2 * i + 1] = Utils.getColorAttrDefaultColor(context,
+                        colors.getThemeAttributeId(i, 0))
+            } else {
+                colorLevels[2 * i + 1] = colors.getColor(i, 0)
+            }
+        }
+        levels.recycle()
+        colors.recycle()
+
+        loadPaths()
+    }
+
+    override fun draw(c: Canvas) {
+        unifiedPath.reset()
+        levelPath.reset()
+        levelRect.set(fillRect)
+        val fillFraction = level / 100f
+        val fillTop =
+                if (level >= 95)
+                    fillRect.top
+                else
+                    fillRect.top + (fillRect.height() * (1 - fillFraction))
+
+        levelRect.top = Math.floor(fillTop.toDouble()).toFloat()
+        levelPath.addRect(levelRect, Path.Direction.CCW)
+
+        // The perimeter should never change
+        unifiedPath.addPath(scaledPerimeter)
+        // IF drawing dual tone, the level is used only to clip the whole drawable path
+        if (!dualTone) {
+            unifiedPath.op(levelPath, Path.Op.UNION)
+        }
+
+        fillPaint.color = levelColor
+
+        // Deal with unifiedPath clipping before it draws
+        if (charging) {
+            // Clip out the bolt shape
+            unifiedPath.op(scaledBolt, Path.Op.DIFFERENCE)
+            if (!invertFillIcon) {
+                c.drawPath(scaledBolt, fillPaint)
+            }
+        } else if (powerSaveEnabled) {
+            // Clip out the plus shape
+            unifiedPath.op(scaledPlus, Path.Op.DIFFERENCE)
+            if (!invertFillIcon) {
+                c.drawPath(scaledPlus, fillPaint)
+            }
+        }
+
+        if (dualTone) {
+            // Dual tone means we draw the shape again, clipped to the charge level
+            c.drawPath(unifiedPath, dualToneBackgroundFill)
+            c.save()
+            c.clipRect(0f,
+                    bounds.bottom - bounds.height() * fillFraction,
+                    bounds.right.toFloat(),
+                    bounds.bottom.toFloat())
+            c.drawPath(unifiedPath, fillPaint)
+            c.restore()
+        } else {
+            // Non dual-tone means we draw the perimeter (with the level fill), and potentially
+            // draw the fill again with a critical color
+            fillPaint.color = fillColor
+            c.drawPath(unifiedPath, fillPaint)
+            fillPaint.color = levelColor
+
+            // Show colorError below this level
+            if (level <= Companion.CRITICAL_LEVEL && !charging) {
+                c.save()
+                c.clipPath(scaledFill)
+                c.drawPath(levelPath, fillPaint)
+                c.restore()
+            }
+        }
+
+        if (charging) {
+            c.clipOutPath(scaledBolt)
+            if (invertFillIcon) {
+                c.drawPath(scaledBolt, fillColorStrokePaint)
+            } else {
+                c.drawPath(scaledBolt, fillColorStrokeProtection)
+            }
+        } else if (powerSaveEnabled) {
+            c.clipOutPath(scaledPlus)
+            if (invertFillIcon) {
+                c.drawPath(scaledPlus, fillColorStrokePaint)
+            } else {
+                c.drawPath(scaledPlus, fillColorStrokeProtection)
+            }
+        }
+    }
+
+    private fun batteryColorForLevel(level: Int): Int {
+        return when {
+            charging || powerSaveEnabled -> fillColor
+            else -> getColorForLevel(level)
+        }
+    }
+
+    private fun getColorForLevel(level: Int): Int {
+        var thresh: Int
+        var color = 0
+        var i = 0
+        while (i < colorLevels.size) {
+            thresh = colorLevels[i]
+            color = colorLevels[i + 1]
+            if (level <= thresh) {
+
+                // Respect tinting for "normal" level
+                return if (i == colorLevels.size - 2) {
+                    fillColor
+                } else {
+                    color
+                }
+            }
+            i += 2
+        }
+        return color
+    }
+
+    /**
+     * Alpha is unused internally, and should be defined in the colors passed to {@link setColors}.
+     * Further, setting an alpha for a dual tone battery meter doesn't make sense without bounds
+     * defining the minimum background fill alpha. This is because fill + background must be equal
+     * to the net alpha passed in here.
+     */
+    override fun setAlpha(alpha: Int) {
+    }
+
+    override fun setColorFilter(colorFilter: ColorFilter?) {
+        fillPaint.colorFilter = colorFilter
+        fillColorStrokePaint.colorFilter = colorFilter
+        dualToneBackgroundFill.colorFilter = colorFilter
+    }
+
+    /**
+     * Deprecated, but required by Drawable
+     */
+    override fun getOpacity(): Int {
+        return PixelFormat.OPAQUE
+    }
+
+    override fun getIntrinsicHeight(): Int {
+        return intrinsicHeight
+    }
+
+    override fun getIntrinsicWidth(): Int {
+        return intrinsicWidth
+    }
+
+    /**
+     * Set the fill level
+     */
+    public open fun setBatteryLevel(l: Int) {
+        invertFillIcon = if (l >= 67) true else if (l <= 33) false else invertFillIcon
+        level = l
+        levelColor = batteryColorForLevel(level)
+        invalidateSelf()
+    }
+
+    public fun getBatteryLevel(): Int {
+        return level
+    }
+
+    override fun onBoundsChange(bounds: Rect?) {
+        super.onBoundsChange(bounds)
+        updateSize()
+    }
+
+    fun setPadding(left: Int, top: Int, right: Int, bottom: Int) {
+        padding.left = left
+        padding.top = top
+        padding.right = right
+        padding.bottom = bottom
+
+        updateSize()
+    }
+
+    fun setColors(fgColor: Int, bgColor: Int, singleToneColor: Int) {
+        fillColor = if (dualTone) fgColor else singleToneColor
+
+        fillPaint.color = fillColor
+        fillColorStrokePaint.color = fillColor
+
+        backgroundColor = bgColor
+        dualToneBackgroundFill.color = bgColor
+
+        // Also update the level color, since fillColor may have changed
+        levelColor = batteryColorForLevel(level)
+
+        invalidateSelf()
+    }
+
+    private fun postInvalidate() {
+        unscheduleSelf(invalidateRunnable)
+        scheduleSelf(invalidateRunnable, 0)
+    }
+
+    private fun updateSize() {
+        val b = bounds
+        if (b.isEmpty) {
+            scaleMatrix.setScale(1f, 1f)
+        } else {
+            scaleMatrix.setScale((b.right / WIDTH), (b.bottom / HEIGHT))
+        }
+
+        perimeterPath.transform(scaleMatrix, scaledPerimeter)
+        fillMask.transform(scaleMatrix, scaledFill)
+        scaledFill.computeBounds(fillRect, true)
+        boltPath.transform(scaleMatrix, scaledBolt)
+        plusPath.transform(scaleMatrix, scaledPlus)
+
+        // It is expected that this view only ever scale by the same factor in each dimension, so
+        // just pick one to scale the strokeWidths
+        val scaledStrokeWidth =
+                Math.max(b.right / WIDTH * PROTECTION_STROKE_WIDTH, PROTECTION_MIN_STROKE_WIDTH)
+
+        fillColorStrokePaint.strokeWidth = scaledStrokeWidth
+        fillColorStrokeProtection.strokeWidth = scaledStrokeWidth
+    }
+
+    private fun loadPaths() {
+        val pathString = context.resources.getString(
+                com.android.internal.R.string.config_batterymeterPerimeterPath)
+        perimeterPath.set(PathParser.createPathFromPathData(pathString))
+        val b = RectF()
+        perimeterPath.computeBounds(b, true)
+
+        val fillMaskString = context.resources.getString(
+                com.android.internal.R.string.config_batterymeterFillMask)
+        fillMask.set(PathParser.createPathFromPathData(fillMaskString))
+        // Set the fill rect so we can calculate the fill properly
+        fillMask.computeBounds(fillRect, true)
+
+        val boltPathString = context.resources.getString(
+                com.android.internal.R.string.config_batterymeterBoltPath)
+        boltPath.set(PathParser.createPathFromPathData(boltPathString))
+
+        val plusPathString = context.resources.getString(
+                com.android.internal.R.string.config_batterymeterPowersavePath)
+        plusPath.set(PathParser.createPathFromPathData(plusPathString))
+
+        dualTone = context.resources.getBoolean(
+                com.android.internal.R.bool.config_batterymeterDualTone)
+    }
+
+    companion object {
+        private const val TAG = "ThemedBatteryDrawable"
+        private const val WIDTH = 12f
+        private const val HEIGHT = 20f
+        private const val CRITICAL_LEVEL = 15
+        // On a 12x20 grid, how wide to make the fill protection stroke.
+        // Scales when our size changes
+        private const val PROTECTION_STROKE_WIDTH = 1.4f
+        // Arbitrarily chosen for visibility at small sizes
+        private const val PROTECTION_MIN_STROKE_WIDTH = 5f
+    }
+}
diff --git a/packages/SettingsLib/src/com/android/settingslib/widget/FooterPreference.java b/packages/SettingsLib/src/com/android/settingslib/widget/FooterPreference.java
index 2a12810..a31b71e 100644
--- a/packages/SettingsLib/src/com/android/settingslib/widget/FooterPreference.java
+++ b/packages/SettingsLib/src/com/android/settingslib/widget/FooterPreference.java
@@ -59,6 +59,5 @@
         setIcon(R.drawable.ic_info_outline_24);
         setKey(KEY_FOOTER);
         setOrder(ORDER_FOOTER);
-        setSelectable(false);
     }
 }
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BarChartPreferenceTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BarChartPreferenceTest.java
index 1080cf4..3acca2a 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BarChartPreferenceTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BarChartPreferenceTest.java
@@ -305,7 +305,7 @@
     }
 
     @Test
-    public void onBindViewHolder_loadingStateIsTrue_shouldNotInitAnyView() {
+    public void onBindViewHolder_loadingStateIsTrue_shouldHideAllViews() {
         final BarViewInfo viewInfo = new BarViewInfo(mIcon, 30 /* barNumber */, R.string.debug_app);
         viewInfo.setClickListener(v -> {
         });
@@ -317,8 +317,7 @@
 
         mPreference.onBindViewHolder(mHolder);
 
-        assertThat(TextUtils.isEmpty(mTitleView.getText())).isTrue();
-        assertThat(TextUtils.isEmpty(mDetailsView.getText())).isTrue();
+        assertThat(mHolder.itemView.getVisibility()).isEqualTo(View.INVISIBLE);
     }
 
     @Test
@@ -334,6 +333,7 @@
 
         mPreference.onBindViewHolder(mHolder);
 
+        assertThat(mHolder.itemView.getVisibility()).isEqualTo(View.VISIBLE);
         assertThat(TextUtils.isEmpty(mTitleView.getText())).isFalse();
         assertThat(TextUtils.isEmpty(mDetailsView.getText())).isFalse();
     }
diff --git a/packages/SettingsProvider/res/values/defaults.xml b/packages/SettingsProvider/res/values/defaults.xml
index 26ea6ab..65e0c0f 100644
--- a/packages/SettingsProvider/res/values/defaults.xml
+++ b/packages/SettingsProvider/res/values/defaults.xml
@@ -40,8 +40,8 @@
     <bool name="def_wifi_display_on">false</bool>
     <bool name="def_install_non_market_apps">false</bool>
     <bool name="def_package_verifier_enable">true</bool>
-    <!-- Comma-separated list of location providers -->
-    <string name="def_location_providers_allowed" translatable="false">gps,network</string>
+    <!-- 0 == off, 3 == on -->
+    <integer name="def_location_mode">3</integer>
     <bool name="assisted_gps_enabled">true</bool>
     <bool name="def_netstats_enabled">true</bool>
     <bool name="def_usb_mass_storage_enabled">true</bool>
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
index 0ee16a9..5e2b7c8 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
@@ -2340,9 +2340,6 @@
             stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
                     + " VALUES(?,?);");
 
-            loadStringSetting(stmt, Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
-                    R.string.def_location_providers_allowed);
-
             // Don't do this.  The SystemServer will initialize ADB_ENABLED from a
             // persistent system property instead.
             //loadSetting(stmt, Settings.Secure.ADB_ENABLED, 0);
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index a7ad223..d6c33a3 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -969,6 +969,11 @@
                 try {
                     synchronized (mLock) {
                         Setting setting = getSecureSetting(
+                                Settings.Secure.LOCATION_MODE, userId);
+                        updateSecureSetting(Settings.Secure.LOCATION_MODE,
+                                setting != null ? setting.getValue() : null, null,
+                                true, userId, true);
+                        setting = getSecureSetting(
                                 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
                         updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
                                 setting != null ? setting.getValue() : null, null,
@@ -1379,8 +1384,8 @@
             }
         }
         if (enableOverride) {
-            if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
-                final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
+            if (Secure.LOCATION_MODE.equals(name)) {
+                final Setting overridden = getLocationModeSetting(owningUserId);
                 if (overridden != null) {
                     return overridden;
                 }
@@ -1475,7 +1480,7 @@
         return null;
     }
 
-    private Setting getLocationProvidersAllowedSetting(int owningUserId) {
+    private Setting getLocationModeSetting(int owningUserId) {
         synchronized (mLock) {
             final Setting setting = getGlobalSetting(
                     Global.LOCATION_GLOBAL_KILL_SWITCH);
@@ -1486,7 +1491,7 @@
             final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
                     SETTINGS_TYPE_SECURE, owningUserId);
             return settingsState.new Setting(
-                    Secure.LOCATION_PROVIDERS_ALLOWED,
+                    Secure.LOCATION_MODE,
                     "", // value
                     "", // tag
                     "", // default value
@@ -1497,7 +1502,7 @@
                 @Override
                 public boolean update(String value, boolean setDefault, String packageName,
                         String tag, boolean forceNonSystemPackage) {
-                    Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
+                    Slog.wtf(LOG_TAG, "update shouldn't be called on this instance.");
                     return false;
                 }
             };
@@ -3115,7 +3120,7 @@
                 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
                 mGenerationRegistry.incrementGeneration(key);
 
-                final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
+                final Uri uri = getNotificationUriFor(key, Secure.LOCATION_MODE);
                 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
                         userId, 0, uri).sendToTarget();
             }
@@ -4229,23 +4234,18 @@
                         final Setting locationProvidersAllowed = secureSettings.getSettingLocked(
                                 Secure.LOCATION_PROVIDERS_ALLOWED);
 
-                        String defLocationMode = Integer.toString(
-                                !TextUtils.isEmpty(locationProvidersAllowed.getValue())
-                                        ? Secure.LOCATION_MODE_ON
-                                        : Secure.LOCATION_MODE_OFF);
+                        final int defLocationMode;
+                        if (locationProvidersAllowed.isNull()) {
+                            defLocationMode = getContext().getResources().getInteger(
+                                    R.integer.def_location_mode);
+                        } else {
+                            defLocationMode =
+                                    !TextUtils.isEmpty(locationProvidersAllowed.getValue())
+                                            ? Secure.LOCATION_MODE_ON
+                                            : Secure.LOCATION_MODE_OFF;
+                        }
                         secureSettings.insertSettingLocked(
-                                Secure.LOCATION_MODE, defLocationMode,
-                                null, true, SettingsState.SYSTEM_PACKAGE_NAME);
-
-                        // also reset LOCATION_PROVIDERS_ALLOWED back to the default value - this
-                        // setting is now only for debug/test purposes, and will likely be removed
-                        // in a later release. LocationManagerService is responsible for adjusting
-                        // these settings to the proper state.
-
-                        String defLocationProvidersAllowed = getContext().getResources().getString(
-                                R.string.def_location_providers_allowed);
-                        secureSettings.insertSettingLocked(
-                                Secure.LOCATION_PROVIDERS_ALLOWED, defLocationProvidersAllowed,
+                                Secure.LOCATION_MODE, Integer.toString(defLocationMode),
                                 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
                     }
 
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index 0da3b10..fc6ef2b 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -146,6 +146,7 @@
     <uses-permission android:name="android.permission.SET_TIME_ZONE" />
     <uses-permission android:name="android.permission.DISABLE_HIDDEN_API_CHECKS" />
     <uses-permission android:name="android.permission.MANAGE_ROLE_HOLDERS" />
+    <uses-permission android:name="android.permission.OBSERVE_ROLE_HOLDERS" />
     <uses-permission android:name="android.permission.STATUS_BAR_SERVICE" />
     <!-- Permission needed to rename bugreport notifications (so they're not shown as Shell) -->
     <uses-permission android:name="android.permission.SUBSTITUTE_NOTIFICATION_APP_NAME" />
diff --git a/packages/SystemUI/Android.bp b/packages/SystemUI/Android.bp
index 29ae1b2..c2495b5 100644
--- a/packages/SystemUI/Android.bp
+++ b/packages/SystemUI/Android.bp
@@ -113,7 +113,7 @@
         "SystemUI-tags",
         "SystemUI-proto",
         "metrics-helper-lib",
-        "android-support-test",
+        "androidx.test.rules", "hamcrest-library",
         "mockito-target-inline-minus-junit4",
         "testables",
         "truth-prebuilt",
diff --git a/packages/SystemUI/plugin/src/com/android/systemui/plugins/ClockPlugin.java b/packages/SystemUI/plugin/src/com/android/systemui/plugins/ClockPlugin.java
index 38bf77d..7b7657a 100644
--- a/packages/SystemUI/plugin/src/com/android/systemui/plugins/ClockPlugin.java
+++ b/packages/SystemUI/plugin/src/com/android/systemui/plugins/ClockPlugin.java
@@ -13,6 +13,7 @@
  */
 package com.android.systemui.plugins;
 
+import android.graphics.Bitmap;
 import android.graphics.Paint.Style;
 import android.view.View;
 
@@ -21,13 +22,30 @@
 import java.util.TimeZone;
 
 /**
- * This plugin is used to replace main clock in keyguard.
+ * Plugin used to replace main clock in keyguard.
  */
 @ProvidesInterface(action = ClockPlugin.ACTION, version = ClockPlugin.VERSION)
 public interface ClockPlugin extends Plugin {
 
     String ACTION = "com.android.systemui.action.PLUGIN_CLOCK";
-    int VERSION = 1;
+    int VERSION = 2;
+
+    /**
+     * Get the name of the clock face.
+     *
+     * This name should not be translated.
+     */
+    String getName();
+
+    /**
+     * Get the title of the clock face to be shown in the picker app.
+     */
+    String getTitle();
+
+    /**
+     * Get thumbnail of clock face to be shown in the picker app.
+     */
+    Bitmap getThumbnail();
 
     /**
      * Get clock view.
@@ -62,18 +80,22 @@
     default void setColorPalette(boolean supportsDarkText, int[] colors) {}
 
     /**
-     * Notifies that time tick alarm from doze service fired.
-     */
-    default void dozeTimeTick() {}
-
-    /**
      * Set the amount (ratio) that the device has transitioned to doze.
      * @param darkAmount Amount of transition to doze: 1f for doze and 0f for awake.
      */
     default void setDarkAmount(float darkAmount) {}
 
     /**
+     * Notifies that time tick alarm from doze service fired.
+     *
+     * Implement this method instead of registering a broadcast listener for TIME_TICK.
+     */
+    default void onTimeTick() {}
+
+    /**
      * Notifies that the time zone has changed.
+     *
+     * Implement this method instead of registering a broadcast listener for TIME_ZONE_CHANGED.
      */
     default void onTimeZoneChanged(TimeZone timeZone) {}
 
diff --git a/packages/SystemUI/res-keyguard/drawable/bubble_hour_hand.xml b/packages/SystemUI/res-keyguard/drawable/bubble_hour_hand.xml
index d3c3a51..a2404b0 100644
--- a/packages/SystemUI/res-keyguard/drawable/bubble_hour_hand.xml
+++ b/packages/SystemUI/res-keyguard/drawable/bubble_hour_hand.xml
@@ -1,9 +1,9 @@
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
-    android:height="200dp"
-    android:width="200dp"
-    android:viewportHeight="100"
-    android:viewportWidth="100">
+    android:height="350dp"
+    android:width="350dp"
+    android:viewportHeight="254.66145"
+    android:viewportWidth="254.66145">
     <path
         android:fillColor="#000000"
-        android:pathData="M50.082,14.199m-13.985,0a13.985,13.985 0,1 1,27.97 0a13.985,13.985 0,1 1,-27.97 0"/>
+        android:pathData="M127.331,40.481m-10.914,0a10.914,10.914 0,1 1,21.828 0a10.914,10.914 0,1 1,-21.828 0"/>
 </vector>
diff --git a/packages/SystemUI/res-keyguard/drawable/bubble_minute_hand.xml b/packages/SystemUI/res-keyguard/drawable/bubble_minute_hand.xml
index a4417fb..be10b5d 100644
--- a/packages/SystemUI/res-keyguard/drawable/bubble_minute_hand.xml
+++ b/packages/SystemUI/res-keyguard/drawable/bubble_minute_hand.xml
@@ -1,9 +1,11 @@
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
-    android:height="200dp"
-    android:width="200dp"
-    android:viewportHeight="100"
-    android:viewportWidth="100" >
+    android:height="350dp"
+    android:width="350dp"
+    android:viewportHeight="254.66145"
+    android:viewportWidth="254.66145" >
     <path
-        android:fillColor="#000000"
-        android:pathData="M50.082,0.025L50.082,0.025A13.985,15.63 0,0 1,64.067 15.656L64.067,49.029A13.985,15.63 0,0 1,50.082 64.659L50.082,64.659A13.985,15.63 0,0 1,36.097 49.029L36.097,15.656A13.985,15.63 0,0 1,50.082 0.025z"/>
+        android:strokeColor="#000000"
+        android:strokeWidth="5"
+        android:pathData="M125.923,29.692L128.739,29.692A27.108,30.579 0,0 1,155.847 60.271L155.847,125.268A27.108,30.579 0,0 1,128.739 155.847L125.923,155.847A27.108,30.579 0,0 1,98.815 125.268L98.815,60.271A27.108,30.579 0,0 1,125.923 29.692z"/>
 </vector>
+
diff --git a/packages/SystemUI/res-keyguard/layout/bubble_clock.xml b/packages/SystemUI/res-keyguard/layout/bubble_clock.xml
index c8dc8e4..0bc1319 100644
--- a/packages/SystemUI/res-keyguard/layout/bubble_clock.xml
+++ b/packages/SystemUI/res-keyguard/layout/bubble_clock.xml
@@ -42,15 +42,15 @@
   >
     <ImageView
         android:id="@+id/minute_hand"
-        android:layout_width="300dp"
-        android:layout_height="300dp"
+        android:layout_width="350dp"
+        android:layout_height="350dp"
         android:src="@drawable/bubble_minute_hand"
         android:tint="@color/bubbleMinuteHandColor"
     />
     <ImageView
         android:id="@+id/hour_hand"
-        android:layout_width="300dp"
-        android:layout_height="300dp"
+        android:layout_width="350dp"
+        android:layout_height="350dp"
         android:src="@drawable/bubble_hour_hand"
         android:tint="@color/bubbleHourHandColor"
     />
diff --git a/packages/SystemUI/res-keyguard/layout/default_clock_preview.xml b/packages/SystemUI/res-keyguard/layout/default_clock_preview.xml
new file mode 100644
index 0000000..3e6dd13
--- /dev/null
+++ b/packages/SystemUI/res-keyguard/layout/default_clock_preview.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    >
+    <TextClock
+        android:id="@+id/time"
+        style="@style/widget_big"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_above="@id/date"
+        android:letterSpacing="0.03"
+        android:gravity="center_horizontal"
+        android:format12Hour="@string/keyguard_widget_12_hours_format"
+        android:format24Hour="@string/keyguard_widget_24_hours_format"
+        />
+
+    <TextClock
+        android:id="@+id/date"
+        style="@stype/widget_big"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_centerInParent="true"
+        android:letterSpacing="0.03"
+        android:gravity="center_horizontal"
+        android:format12Hour="EEE, MMM d"
+        android:format24Hour="EEE, MMM d"
+        />
+</RelativeLayout>
diff --git a/packages/SystemUI/res/drawable/bubble_expanded_header_bg.xml b/packages/SystemUI/res/drawable/bubble_expanded_header_bg.xml
deleted file mode 100644
index a76b7b1..0000000
--- a/packages/SystemUI/res/drawable/bubble_expanded_header_bg.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2018 The Android Open Source Project
-  ~
-  ~ Licensed under the Apache License, Version 2.0 (the "License");
-  ~ you may not use this file except in compliance with the License.
-  ~ You may obtain a copy of the License at
-  ~
-  ~      http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing, software
-  ~ distributed under the License is distributed on an "AS IS" BASIS,
-  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  ~ See the License for the specific language governing permissions and
-  ~ limitations under the License
-  -->
-<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
-    <item>
-        <shape android:shape="rectangle">
-            <solid android:color="?android:attr/colorBackgroundFloating"/>
-            <corners
-                    android:topLeftRadius="@dimen/corner_size"
-                    android:topRightRadius="@dimen/corner_size"/>
-        </shape>
-    </item>
-</layer-list>
\ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/ic_tune_black_16dp.xml b/packages/SystemUI/res/drawable/ic_tune_black_16dp.xml
new file mode 100644
index 0000000..339cb70
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_tune_black_16dp.xml
@@ -0,0 +1,25 @@
+<!--
+    Copyright (C) 2019 The Android Open Source Project
+
+    Licensed under the Apache License, Version 2.0 (the "License");
+    you may not use this file except in compliance with the License.
+    You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+-->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="16dp"
+        android:height="16dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0">
+    <path
+        android:fillColor="#FF000000"
+        android:pathData="M3,17v2h6v-2L3,17zM3,5v2h10L13,5L3,5zM13,21v-2h8v-2h-8v-2h-2v6h2zM7,9v2L3,11v2h4v2h2L9,9L7,9zM21,13v-2L11,11v2h10zM15,9h2L17,7h4L21,5h-4L17,3h-2v6z"/>
+</vector>
\ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/qs_customize_tile_decoration.xml b/packages/SystemUI/res/drawable/qs_customize_tile_decoration.xml
new file mode 100644
index 0000000..f086cec
--- /dev/null
+++ b/packages/SystemUI/res/drawable/qs_customize_tile_decoration.xml
@@ -0,0 +1,17 @@
+<!--
+     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.
+-->
+<color xmlns:android="http://schemas.android.com/apk/res/android"
+       android:color="@color/qs_customize_decoration"/>
\ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/qs_customizer_background_primary.xml b/packages/SystemUI/res/drawable/qs_customizer_background_primary.xml
index abe1429..215dee4 100644
--- a/packages/SystemUI/res/drawable/qs_customizer_background_primary.xml
+++ b/packages/SystemUI/res/drawable/qs_customizer_background_primary.xml
@@ -15,7 +15,7 @@
 -->
 <inset xmlns:android="http://schemas.android.com/apk/res/android">
     <shape>
-        <solid android:color="?android:attr/colorPrimary"/>
+        <solid android:color="@color/qs_customize_background"/>
         <corners android:radius="?android:attr/dialogCornerRadius" />
     </shape>
 </inset>
diff --git a/packages/SystemUI/res/drawable/qs_customizer_toolbar.xml b/packages/SystemUI/res/drawable/qs_customizer_toolbar.xml
index 557cae1..648d45b 100644
--- a/packages/SystemUI/res/drawable/qs_customizer_toolbar.xml
+++ b/packages/SystemUI/res/drawable/qs_customizer_toolbar.xml
@@ -15,7 +15,7 @@
 -->
 <inset xmlns:android="http://schemas.android.com/apk/res/android">
     <shape>
-        <solid android:color="?android:attr/colorSecondary"/>
+        <solid android:color="@color/qs_customize_background"/>
         <corners
             android:topLeftRadius="?android:attr/dialogCornerRadius"
             android:topRightRadius="?android:attr/dialogCornerRadius" />
diff --git a/packages/SystemUI/res/layout/bubble_expanded_view.xml b/packages/SystemUI/res/layout/bubble_expanded_view.xml
index a8b1b2e..56a3cd5 100644
--- a/packages/SystemUI/res/layout/bubble_expanded_view.xml
+++ b/packages/SystemUI/res/layout/bubble_expanded_view.xml
@@ -29,10 +29,9 @@
 
     <FrameLayout
         android:id="@+id/header_permission_wrapper"
-        android:layout_width="wrap_content"
+        android:layout_width="match_parent"
         android:layout_height="wrap_content"
-        android:animateLayoutChanges="true"
-        android:background="@drawable/bubble_expanded_header_bg">
+        android:animateLayoutChanges="true">
 
         <LinearLayout
             android:id="@+id/header_layout"
diff --git a/packages/SystemUI/res/layout/keyguard_status_bar.xml b/packages/SystemUI/res/layout/keyguard_status_bar.xml
index 5b9816d..66c0c5c 100644
--- a/packages/SystemUI/res/layout/keyguard_status_bar.xml
+++ b/packages/SystemUI/res/layout/keyguard_status_bar.xml
@@ -71,7 +71,7 @@
         android:gravity="center_vertical"
         android:ellipsize="marquee"
         android:textDirection="locale"
-        android:textAppearance="?android:attr/textAppearanceSmall"
+        android:textAppearance="@style/TextAppearance.StatusBar.Clock"
         android:textColor="?attr/wallpaperTextColorSecondary"
         android:singleLine="true"
         systemui:showMissingSim="true"
diff --git a/packages/SystemUI/res/layout/notification_info.xml b/packages/SystemUI/res/layout/notification_info.xml
index 91353d7..863c1cc 100644
--- a/packages/SystemUI/res/layout/notification_info.xml
+++ b/packages/SystemUI/res/layout/notification_info.xml
@@ -178,6 +178,7 @@
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_centerVertical="true"
+                android:maxWidth="100dp"
                 style="@style/TextAppearance.NotificationInfo.Button"/>
 
             <LinearLayout
@@ -186,6 +187,7 @@
                 android:layout_height="wrap_content"
                 android:layout_centerVertical="true"
                 android:layout_alignParentEnd="true"
+                android:maxWidth="200dp"
                 android:orientation="horizontal">
                 <TextView
                     android:id="@+id/deliver_silently"
@@ -195,6 +197,7 @@
                     android:layout_centerVertical="true"
                     android:layout_marginStart="@dimen/notification_guts_button_horizontal_spacing"
                     android:paddingRight="24dp"
+                    android:maxWidth="125dp"
                     style="@style/TextAppearance.NotificationInfo.Button"/>
                 <TextView
                     android:id="@+id/block"
@@ -203,6 +206,7 @@
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:layout_centerVertical="true"
+                    android:maxWidth="75dp"
                     android:layout_marginStart="@dimen/notification_guts_button_horizontal_spacing"
                     style="@style/TextAppearance.NotificationInfo.Button"/>
                 <TextView
@@ -212,6 +216,7 @@
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:layout_centerVertical="true"
+                    android:maxWidth="75dp"
                     android:layout_marginStart="@dimen/notification_guts_button_horizontal_spacing"
                     style="@style/TextAppearance.NotificationInfo.Button"/>
             </LinearLayout>
diff --git a/packages/SystemUI/res/layout/ongoing_privacy_dialog_content.xml b/packages/SystemUI/res/layout/ongoing_privacy_dialog_content.xml
index bc15f2c4..665fc3f 100644
--- a/packages/SystemUI/res/layout/ongoing_privacy_dialog_content.xml
+++ b/packages/SystemUI/res/layout/ongoing_privacy_dialog_content.xml
@@ -54,9 +54,6 @@
                 android:orientation="vertical"
                 android:gravity="start"
             />
-
-            <include android:id="@+id/overflow" layout="@layout/ongoing_privacy_dialog_item"
-                     android:visibility="gone" />
         </LinearLayout>
 
     </LinearLayout>
diff --git a/packages/SystemUI/res/layout/qs_customize_divider.xml b/packages/SystemUI/res/layout/qs_customize_divider.xml
index 6fcfa8d..d6664fe 100644
--- a/packages/SystemUI/res/layout/qs_customize_divider.xml
+++ b/packages/SystemUI/res/layout/qs_customize_divider.xml
@@ -24,5 +24,4 @@
     android:paddingTop="20dp"
     android:paddingBottom="13dp"
     android:textAppearance="@style/TextAppearance.QSEdit.Headers"
-    android:textColor="?android:attr/colorAccent"
     android:text="@string/drag_to_add_tiles" />
diff --git a/packages/SystemUI/res/layout/qs_customize_header.xml b/packages/SystemUI/res/layout/qs_customize_header.xml
index d54dfee..58066a3 100644
--- a/packages/SystemUI/res/layout/qs_customize_header.xml
+++ b/packages/SystemUI/res/layout/qs_customize_header.xml
@@ -24,5 +24,4 @@
     android:gravity="center"
     android:minHeight="@dimen/qs_customize_header_min_height"
     android:textAppearance="@style/TextAppearance.QSEdit.Headers"
-    android:textColor="?android:attr/colorAccent"
     android:text="@string/drag_to_rearrange_tiles" />
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/qs_customize_panel_content.xml b/packages/SystemUI/res/layout/qs_customize_panel_content.xml
index 87b4551..09f512f 100644
--- a/packages/SystemUI/res/layout/qs_customize_panel_content.xml
+++ b/packages/SystemUI/res/layout/qs_customize_panel_content.xml
@@ -37,7 +37,8 @@
             android:layout_height="wrap_content"
             android:background="@drawable/qs_customizer_toolbar"
             android:navigationContentDescription="@*android:string/action_bar_up_description"
-            style="?android:attr/toolbarStyle" />
+            style="@style/QSCustomizeToolbar"
+            />
 
         <androidx.recyclerview.widget.RecyclerView
             android:id="@android:id/list"
diff --git a/packages/SystemUI/res/layout/volume_dialog.xml b/packages/SystemUI/res/layout/volume_dialog.xml
index e67bb60..ca34c23 100644
--- a/packages/SystemUI/res/layout/volume_dialog.xml
+++ b/packages/SystemUI/res/layout/volume_dialog.xml
@@ -87,7 +87,7 @@
                 android:background="@drawable/rounded_bg_bottom_background">
                 <com.android.keyguard.AlphaOptimizedImageButton
                     android:id="@+id/settings"
-                    android:src="@drawable/ic_settings_16dp"
+                    android:src="@drawable/ic_tune_black_16dp"
                     android:layout_width="@dimen/volume_dialog_tap_target_size"
                     android:layout_height="@dimen/volume_dialog_tap_target_size"
                     android:layout_gravity="center"
diff --git a/packages/SystemUI/res/values-night/colors.xml b/packages/SystemUI/res/values-night/colors.xml
index 2c5120d..5803bf1 100644
--- a/packages/SystemUI/res/values-night/colors.xml
+++ b/packages/SystemUI/res/values-night/colors.xml
@@ -41,4 +41,10 @@
 
     <!-- The color of the text inside a notification -->
     <color name="notification_primary_text_color">@*android:color/notification_primary_text_color_dark</color>
+
+    <!-- The color of the background in the top part of QSCustomizer -->
+    <color name="qs_customize_background">@color/GM2_grey_900</color>
+
+    <!-- The color of the background in the bottom part of QSCustomizer -->
+    <color name="qs_customize_decoration">@color/GM2_grey_800</color>
 </resources>
\ No newline at end of file
diff --git a/packages/SystemUI/res/values-sw320dp/dimens.xml b/packages/SystemUI/res/values-sw320dp/dimens.xml
index 0c2b1cc..8f27f45 100644
--- a/packages/SystemUI/res/values-sw320dp/dimens.xml
+++ b/packages/SystemUI/res/values-sw320dp/dimens.xml
@@ -15,9 +15,8 @@
   ~ limitations under the License
   -->
 <resources>
-
     <!-- Global actions grid -->
-    <dimen name="global_actions_grid_container_bottom_margin">16dp</dimen>
+    <dimen name="global_actions_grid_container_bottom_margin">4dp</dimen>
 
     <dimen name="global_actions_grid_vertical_padding">0dp</dimen>
     <dimen name="global_actions_grid_horizontal_padding">3dp</dimen>
@@ -29,7 +28,7 @@
 
     <dimen name="global_actions_grid_item_icon_width">18dp</dimen>
     <dimen name="global_actions_grid_item_icon_height">18dp</dimen>
-    <dimen name="global_actions_grid_item_icon_top_margin">12dp</dimen>
+    <dimen name="global_actions_grid_item_icon_top_margin">10dp</dimen>
     <dimen name="global_actions_grid_item_icon_side_margin">22dp</dimen>
     <dimen name="global_actions_grid_item_icon_bottom_margin">4dp</dimen>
 
diff --git a/packages/SystemUI/res/values-sw410dp/dimens.xml b/packages/SystemUI/res/values-sw410dp/dimens.xml
index 4197eb2..73d1857 100644
--- a/packages/SystemUI/res/values-sw410dp/dimens.xml
+++ b/packages/SystemUI/res/values-sw410dp/dimens.xml
@@ -23,7 +23,7 @@
     <dimen name="qs_detail_items_padding_top">16dp</dimen>
 
     <!-- Global actions grid -->
-    <dimen name="global_actions_grid_container_bottom_margin">16dp</dimen>
+    <dimen name="global_actions_grid_container_bottom_margin">4dp</dimen>
 
     <dimen name="global_actions_grid_vertical_padding">8dp</dimen>
     <dimen name="global_actions_grid_horizontal_padding">4dp</dimen>
@@ -35,7 +35,7 @@
 
     <dimen name="global_actions_grid_item_icon_width">24dp</dimen>
     <dimen name="global_actions_grid_item_icon_height">24dp</dimen>
-    <dimen name="global_actions_grid_item_icon_top_margin">16dp</dimen>
+    <dimen name="global_actions_grid_item_icon_top_margin">14dp</dimen>
     <dimen name="global_actions_grid_item_icon_side_margin">24dp</dimen>
     <dimen name="global_actions_grid_item_icon_bottom_margin">4dp</dimen>
 
diff --git a/packages/SystemUI/res/values/colors.xml b/packages/SystemUI/res/values/colors.xml
index d5f29ba..0e4ffee 100644
--- a/packages/SystemUI/res/values/colors.xml
+++ b/packages/SystemUI/res/values/colors.xml
@@ -35,6 +35,8 @@
     <color name="status_bar_clock_color">#FFFFFFFF</color>
     <color name="qs_user_detail_icon_muted">#FFFFFFFF</color> <!-- not so muted after all -->
     <color name="qs_tile_disabled_color">#9E9E9E</color> <!-- 38% black -->
+    <color name="qs_customize_background">@color/GM2_grey_50</color>
+    <color name="qs_customize_decoration">@color/GM2_grey_100</color>
 
     <!-- Tint color for the content on the notification overflow card. -->
     <color name="keyguard_overflow_content_color">#ff686868</color>
@@ -72,7 +74,7 @@
     <color name="notification_primary_text_color">@*android:color/notification_primary_text_color_light</color>
 
     <!-- The "inside" of a notification, reached via longpress -->
-    <color name="notification_guts_bg_color">#f8f9fa</color>
+    <color name="notification_guts_bg_color">@color/GM2_grey_50</color>
 
     <color name="assist_orb_color">#ffffff</color>
 
@@ -123,7 +125,7 @@
 
     <color name="zen_introduction">#ffffffff</color>
 
-    <color name="smart_reply_button_text">#5F6368</color>
+    <color name="smart_reply_button_text">@color/GM2_grey_700</color>
     <color name="smart_reply_button_text_dark_bg">@*android:color/notification_primary_text_color_dark</color>
     <color name="smart_reply_button_background">#ffffffff</color>
     <color name="smart_reply_button_stroke">#ffdadce0</color>
@@ -134,4 +136,17 @@
 
     <!-- Logout button -->
     <color name="logout_button_bg_color">#ccffffff</color>
+
+    <!-- GM2 colors -->
+    <color name="GM2_grey_50">#F8F9FA</color>
+    <color name="GM2_grey_100">#F1F3F4</color>
+    <color name="GM2_grey_200">#E8EAED</color>
+    <color name="GM2_grey_300">#DADCE0</color>
+    <color name="GM2_grey_400">#BDC1C6</color>
+    <color name="GM2_grey_500">#9AA0A6</color>
+    <color name="GM2_grey_600">#80868B</color>
+    <color name="GM2_grey_650">#70757A</color>
+    <color name="GM2_grey_700">#5F6368</color>
+    <color name="GM2_grey_800">#3C4043</color>
+    <color name="GM2_grey_900">#202124</color>
 </resources>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 536bc4e..50cf37b 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -44,8 +44,9 @@
     <!-- Height of the battery icon in the status bar. -->
     <dimen name="status_bar_battery_icon_height">13.0dp</dimen>
 
-    <!-- Width of the battery icon in the status bar. -->
-    <dimen name="status_bar_battery_icon_width">8.5dp</dimen>
+    <!-- Width of the battery icon in the status bar. The battery drawable assumes a 12x20 canvas,
+    so the width of the icon should be 13.0dp * (12.0 / 20.0) -->
+    <dimen name="status_bar_battery_icon_width">7.8dp</dimen>
 
     <!-- The font size for the clock in the status bar. -->
     <dimen name="status_bar_clock_size">14sp</dimen>
@@ -1049,4 +1050,7 @@
     <dimen name="bubble_pointer_margin">8dp</dimen>
     <!-- Height of the permission prompt shown with bubbles -->
     <dimen name="bubble_permission_height">120dp</dimen>
+
+    <!-- Size of the RAT type for CellularTile -->
+    <dimen name="celltile_rat_type_size">10sp</dimen>
 </resources>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index 4905e57..5338bb4 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -776,7 +776,7 @@
     <!-- QuickSettings: Wifi secondary label shown when the wifi is being enabled [CHAR LIMIT=NONE] -->
     <string name="quick_settings_wifi_secondary_label_transient">Turning on&#8230;</string>
     <!-- QuickSettings: Cast title [CHAR LIMIT=NONE] -->
-    <string name="quick_settings_cast_title">Cast</string>
+    <string name="quick_settings_cast_title">Screen Cast</string>
     <!-- QuickSettings: Cast detail panel, status text when casting [CHAR LIMIT=NONE] -->
     <string name="quick_settings_casting">Casting</string>
     <!-- QuickSettings: Cast detail panel, default device name [CHAR LIMIT=NONE] -->
@@ -1579,7 +1579,7 @@
     <string name="inline_blocking_helper">You usually dismiss these notifications.
     \nKeep showing them?</string>
 
-    <!-- Notification Inline controls: button to dismiss the blocking helper [CHAR_LIMIT=25] -->
+    <!-- Notification Inline controls: button to dismiss the blocking helper [CHAR_LIMIT=20] -->
     <string name="inline_done_button">Done</string>
 
     <!-- Notification Inline controls: continue receiving notifications prompt, channel level -->
@@ -1588,7 +1588,7 @@
     <!-- Notification inline controls: block notifications button [CHAR_LIMIT=25] -->
     <string name="inline_stop_button">Stop notifications</string>
 
-    <!-- Notification inline controls: button to deliver notifications silently from this channel [CHAR_LIMIT=35] -->
+    <!-- Notification inline controls: button to deliver notifications silently from this channel [CHAR_LIMIT=30] -->
     <string name="inline_deliver_silently_button">Deliver Silently</string>
 
     <!-- Notification inline controls: button to block notifications from this channel [CHAR_LIMIT=20] -->
diff --git a/packages/SystemUI/res/values/styles.xml b/packages/SystemUI/res/values/styles.xml
index 96cdbd3..30dbc8b 100644
--- a/packages/SystemUI/res/values/styles.xml
+++ b/packages/SystemUI/res/values/styles.xml
@@ -216,6 +216,12 @@
         <item name="android:fontFamily">@*android:string/config_bodyFontFamily</item>
     </style>
 
+    <!-- This is hard coded to be sans-serif-condensed to match the icons -->
+    <style name="TextAppearance.RATBadge" parent="@style/TextAppearance.QS.TileLabel.Secondary">
+        <item name="android:fontFamily">sans-serif-condensed</item>
+        <item name="android:textSize">@dimen/celltile_rat_type_size</item>
+    </style>
+
     <style name="TextAppearance.QS.CarrierInfo">
         <item name="android:fontFamily">@*android:string/config_headlineFontFamily</item>
         <item name="android:textSize">@dimen/qs_carrier_info_text_size</item>
@@ -458,8 +464,15 @@
     </style>
 
     <style name="TextAppearance.QSEdit.Headers"
-        parent="@*android:style/TextAppearance.Material.Body2">
-        <item name="android:fontFamily">@*android:string/config_headlineFontFamily</item>
+        parent="@*android:style/TextAppearance.DeviceDefault.Body2">
+        <item name="android:textSize">11sp</item>
+        <item name="android:textColor">?android:attr/textColorSecondary</item>
+        <item name="android:textAllCaps">true</item>
+    </style>
+
+    <style name="QSCustomizeToolbar" parent="@*android:style/Widget.DeviceDefault.Toolbar">
+        <item name="android:textColor">?android:attr/textColorPrimary</item>
+        <item name="android:elevation">10dp</item>
     </style>
 
     <style name="edit_theme" parent="qs_theme">
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/InputConsumerController.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/InputConsumerController.java
index 0cde9da..e554dcd 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/InputConsumerController.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/InputConsumerController.java
@@ -27,26 +27,26 @@
 import android.util.Log;
 import android.view.BatchedInputEventReceiver;
 import android.view.Choreographer;
+import android.view.IWindowManager;
 import android.view.InputChannel;
 import android.view.InputEvent;
-import android.view.IWindowManager;
-import android.view.MotionEvent;
 import android.view.WindowManagerGlobal;
 
 import java.io.PrintWriter;
 
 /**
- * Manages the input consumer that allows the SystemUI to directly receive touch input.
+ * Manages the input consumer that allows the SystemUI to directly receive input.
  */
 public class InputConsumerController {
 
     private static final String TAG = InputConsumerController.class.getSimpleName();
 
     /**
-     * Listener interface for callers to subscribe to touch events.
+     * Listener interface for callers to subscribe to input events.
      */
-    public interface TouchListener {
-        boolean onTouchEvent(MotionEvent ev);
+    public interface InputListener {
+        /** Handles any input event. */
+        boolean onInputEvent(InputEvent ev);
     }
 
     /**
@@ -71,9 +71,8 @@
         public void onInputEvent(InputEvent event) {
             boolean handled = true;
             try {
-                if (mListener != null && event instanceof MotionEvent) {
-                    MotionEvent ev = (MotionEvent) event;
-                    handled = mListener.onTouchEvent(ev);
+                if (mListener != null) {
+                    handled = mListener.onInputEvent(event);
                 }
             } finally {
                 finishInputEvent(event, handled);
@@ -86,7 +85,7 @@
     private final String mName;
 
     private InputEventReceiver mInputEventReceiver;
-    private TouchListener mListener;
+    private InputListener mListener;
     private RegistrationListener mRegistrationListener;
 
     /**
@@ -115,9 +114,9 @@
     }
 
     /**
-     * Sets the touch listener.
+     * Sets the input listener.
      */
-    public void setTouchListener(TouchListener listener) {
+    public void setInputListener(InputListener listener) {
         mListener = listener;
     }
 
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/StatsLogCompat.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/StatsLogCompat.java
index 5bc1f25..d17725f 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/StatsLogCompat.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/StatsLogCompat.java
@@ -32,4 +32,17 @@
         StatsLog.write(19, action, srcState, dstState, extension,
                 swipeUpEnabled);
     }
+
+    /**
+     *  StatsLog.write(StatsLog.STYLE_EVENT, action, colorPackageHash,
+     *           fontPackageHash, shapePackageHash, clockPackageHash,
+     *           launcherGrid, wallpaperCategoryHash, wallpaperIdHash);
+     */
+    public static void write(int action, int colorPackageHash,
+            int fontPackageHash, int shapePackageHash, int clockPackageHash,
+            int launcherGrid, int wallpaperCategoryHash, int wallpaperIdHash) {
+        StatsLog.write(179, action, colorPackageHash,
+                fontPackageHash, shapePackageHash, clockPackageHash,
+                launcherGrid, wallpaperCategoryHash, wallpaperIdHash);
+    }
 }
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListener.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListener.java
index 3d2f61e..c54a469 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListener.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListener.java
@@ -48,6 +48,21 @@
         onActivityLaunchOnSecondaryDisplayFailed();
     }
 
+    /**
+     * @see #onActivityLaunchOnSecondaryDisplayRerouted(RunningTaskInfo taskInfo)
+     */
+    public void onActivityLaunchOnSecondaryDisplayRerouted() { }
+
+    /**
+     * Called when an activity was requested to be launched on a secondary display but was rerouted
+     * to default display.
+     *
+     * @param taskInfo info about the Activity's task
+     */
+    public void onActivityLaunchOnSecondaryDisplayRerouted(RunningTaskInfo taskInfo) {
+        onActivityLaunchOnSecondaryDisplayRerouted();
+    }
+
     public void onTaskProfileLocked(int taskId, int userId) { }
     public void onTaskCreated(int taskId, ComponentName componentName) { }
     public void onTaskRemoved(int taskId) { }
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java
index a9ac42f..7e4ab85 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java
@@ -141,6 +141,13 @@
     }
 
     @Override
+    public void onActivityLaunchOnSecondaryDisplayRerouted(RunningTaskInfo taskInfo,
+            int requestedDisplayId) throws RemoteException {
+        mHandler.obtainMessage(H.ON_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_REROUTED,
+                 requestedDisplayId, 0 /* unused */, taskInfo).sendToTarget();
+    }
+
+    @Override
     public void onTaskProfileLocked(int taskId, int userId) throws RemoteException {
         mHandler.obtainMessage(H.ON_TASK_PROFILE_LOCKED, taskId, userId).sendToTarget();
     }
@@ -189,6 +196,7 @@
         private static final int ON_TASK_REMOVED = 13;
         private static final int ON_TASK_MOVED_TO_FRONT = 14;
         private static final int ON_ACTIVITY_REQUESTED_ORIENTATION_CHANGE = 15;
+        private static final int ON_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_REROUTED = 16;
 
 
         public H(Looper looper) {
@@ -270,6 +278,14 @@
                         }
                         break;
                     }
+                    case ON_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_REROUTED: {
+                        final RunningTaskInfo info = (RunningTaskInfo) msg.obj;
+                        for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) {
+                            mTaskStackListeners.get(i)
+                                .onActivityLaunchOnSecondaryDisplayRerouted(info);
+                        }
+                        break;
+                    }
                     case ON_TASK_PROFILE_LOCKED: {
                         for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) {
                             mTaskStackListeners.get(i).onTaskProfileLocked(msg.arg1, msg.arg2);
diff --git a/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java b/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java
index 1539582..64517ba 100644
--- a/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java
+++ b/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java
@@ -52,9 +52,11 @@
     private boolean mTelephonyCapable;
     private boolean mShowMissingSim;
     private boolean mShowAirplaneMode;
-    private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
+    @VisibleForTesting
+    protected KeyguardUpdateMonitor mKeyguardUpdateMonitor;
     private WifiManager mWifiManager;
-    private boolean[] mSimErrorState = new boolean[TelephonyManager.getDefault().getPhoneCount()];
+    private boolean[] mSimErrorState;
+    private final int mSimSlotsNumber;
     private CarrierTextCallback mCarrierTextCallback;
     private Context mContext;
     private CharSequence mSeparator;
@@ -72,7 +74,8 @@
                 }
             };
 
-    private final KeyguardUpdateMonitorCallback mCallback = new KeyguardUpdateMonitorCallback() {
+    @VisibleForTesting
+    protected final KeyguardUpdateMonitorCallback mCallback = new KeyguardUpdateMonitorCallback() {
         @Override
         public void onRefreshCarrierInfo() {
             if (DEBUG) {
@@ -93,7 +96,7 @@
         }
 
         public void onSimStateChanged(int subId, int slotId, IccCardConstants.State simState) {
-            if (slotId < 0) {
+            if (slotId < 0 || slotId >= mSimSlotsNumber) {
                 Log.d(TAG, "onSimStateChanged() - slotId invalid: " + slotId
                         + " mTelephonyCapable: " + Boolean.toString(mTelephonyCapable));
                 return;
@@ -144,36 +147,48 @@
         mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
         mSeparator = separator;
         mWakefulnessLifecycle = Dependency.get(WakefulnessLifecycle.class);
+        mSimSlotsNumber = ((TelephonyManager) context.getSystemService(
+                Context.TELEPHONY_SERVICE)).getPhoneCount();
+        mSimErrorState = new boolean[mSimSlotsNumber];
     }
 
     /**
      * Checks if there are faulty cards. Adds the text depending on the slot of the card
      *
      * @param text:   current carrier text based on the sim state
+     * @param carrierNames names order by subscription order
+     * @param subOrderBySlot array containing the sub index for each slot ID
      * @param noSims: whether a valid sim card is inserted
      * @return text
      */
-    private CharSequence updateCarrierTextWithSimIoError(CharSequence text, boolean noSims) {
+    private CharSequence updateCarrierTextWithSimIoError(CharSequence text,
+            CharSequence[] carrierNames, int[] subOrderBySlot, boolean noSims) {
         final CharSequence carrier = "";
         CharSequence carrierTextForSimIOError = getCarrierTextForSimState(
                 IccCardConstants.State.CARD_IO_ERROR, carrier);
+        // mSimErrorState has the state of each sim indexed by slotID.
         for (int index = 0; index < mSimErrorState.length; index++) {
-            if (mSimErrorState[index]) {
-                // In the case when no sim cards are detected but a faulty card is inserted
-                // overwrite the text and only show "Invalid card"
-                if (noSims) {
-                    return concatenate(carrierTextForSimIOError,
-                            getContext().getText(
-                                    com.android.internal.R.string.emergency_calls_only),
-                            mSeparator);
-                } else if (index == 0) {
-                    // prepend "Invalid card" when faulty card is inserted in slot 0
-                    text = concatenate(carrierTextForSimIOError, text, mSeparator);
-                } else {
-                    // concatenate "Invalid card" when faulty card is inserted in slot 1
-                    text = concatenate(text, carrierTextForSimIOError, mSeparator);
-                }
+            if (!mSimErrorState[index]) {
+                continue;
             }
+            // In the case when no sim cards are detected but a faulty card is inserted
+            // overwrite the text and only show "Invalid card"
+            if (noSims) {
+                return concatenate(carrierTextForSimIOError,
+                        getContext().getText(
+                                com.android.internal.R.string.emergency_calls_only),
+                        mSeparator);
+            } else if (subOrderBySlot[index] != -1) {
+                int subIndex = subOrderBySlot[index];
+                // prepend "Invalid card" when faulty card is inserted in slot 0 or 1
+                carrierNames[subIndex] = concatenate(carrierTextForSimIOError,
+                        carrierNames[subIndex],
+                        mSeparator);
+            } else {
+                // concatenate "Invalid card" when faulty card is inserted in other slot
+                text = concatenate(text, carrierTextForSimIOError, mSeparator);
+            }
+
         }
         return text;
     }
@@ -209,16 +224,25 @@
     protected void updateCarrierText() {
         boolean allSimsMissing = true;
         boolean anySimReadyAndInService = false;
-        boolean missingSimsWithSubs = false;
         CharSequence displayText = null;
 
         List<SubscriptionInfo> subs = mKeyguardUpdateMonitor.getSubscriptionInfo(false);
         final int numSubs = subs.size();
         final int[] subsIds = new int[numSubs];
+        // This array will contain in position i, the index of subscription in slot ID i.
+        // -1 if no subscription in that slot
+        final int[] subOrderBySlot = new int[mSimSlotsNumber];
+        for (int i = 0; i < mSimSlotsNumber; i++) {
+            subOrderBySlot[i] = -1;
+        }
+        final CharSequence[] carrierNames = new CharSequence[numSubs];
         if (DEBUG) Log.d(TAG, "updateCarrierText(): " + numSubs);
+
         for (int i = 0; i < numSubs; i++) {
             int subId = subs.get(i).getSubscriptionId();
+            carrierNames[i] = "";
             subsIds[i] = subId;
+            subOrderBySlot[subs.get(i).getSimSlotIndex()] = i;
             IccCardConstants.State simState = mKeyguardUpdateMonitor.getSimState(subId);
             CharSequence carrierName = subs.get(i).getCarrierName();
             CharSequence carrierTextForSimState = getCarrierTextForSimState(simState, carrierName);
@@ -227,7 +251,7 @@
             }
             if (carrierTextForSimState != null) {
                 allSimsMissing = false;
-                displayText = concatenate(displayText, carrierTextForSimState, mSeparator);
+                carrierNames[i] = carrierTextForSimState;
             }
             if (simState == IccCardConstants.State.READY) {
                 ServiceState ss = mKeyguardUpdateMonitor.mServiceStates.get(subId);
@@ -256,7 +280,6 @@
                 // described above.
                 displayText = makeCarrierStringOnEmergencyCapable(
                         getMissingSimMessage(), subs.get(0).getCarrierName());
-                missingSimsWithSubs = true;
             } else {
                 // We don't have a SubscriptionInfo to get the emergency calls only from.
                 // Grab it from the old sticky broadcast if possible instead. We can use it
@@ -286,24 +309,32 @@
             }
         }
 
-        displayText = updateCarrierTextWithSimIoError(displayText, allSimsMissing);
+        displayText = updateCarrierTextWithSimIoError(displayText, carrierNames, subOrderBySlot,
+                allSimsMissing);
         // APM (airplane mode) != no carrier state. There are carrier services
         // (e.g. WFC = Wi-Fi calling) which may operate in APM.
         if (!anySimReadyAndInService && WirelessUtils.isAirplaneModeOn(mContext)) {
             displayText = getAirplaneModeMessage();
         }
 
-        Handler handler = Dependency.get(Dependency.MAIN_HANDLER);
+        if (TextUtils.isEmpty(displayText)) {
+            displayText = TextUtils.join(mSeparator, carrierNames);
+        }
         final CarrierTextCallbackInfo info = new CarrierTextCallbackInfo(
                 displayText,
-                displayText.toString().split(mSeparator.toString()),
-                anySimReadyAndInService && !missingSimsWithSubs,
+                carrierNames,
+                !allSimsMissing,
                 subsIds);
+        postToCallback(info);
+    }
+
+    @VisibleForTesting
+    protected void postToCallback(CarrierTextCallbackInfo info) {
+        Handler handler = Dependency.get(Dependency.MAIN_HANDLER);
         final CarrierTextCallback callback = mCarrierTextCallback;
         if (callback != null) {
             handler.post(() -> callback.updateCarrierInfo(info));
         }
-
     }
 
     private Context getContext() {
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputView.java
index a055950..4cb8d90 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputView.java
@@ -34,6 +34,8 @@
 import com.android.internal.widget.LockPatternChecker;
 import com.android.internal.widget.LockPatternUtils;
 
+import java.util.Arrays;
+
 /**
  * Base class for PIN and password unlock screens.
  */
@@ -124,18 +126,19 @@
     protected void verifyPasswordAndUnlock() {
         if (mDismissing) return; // already verified but haven't been dismissed; don't do it again.
 
-        final String entry = getPasswordText();
+        final byte[] entry = getPasswordText();
         setPasswordEntryInputEnabled(false);
         if (mPendingLockCheck != null) {
             mPendingLockCheck.cancel(false);
         }
 
         final int userId = KeyguardUpdateMonitor.getCurrentUser();
-        if (entry.length() <= MINIMUM_PASSWORD_LENGTH_BEFORE_REPORT) {
+        if (entry.length <= MINIMUM_PASSWORD_LENGTH_BEFORE_REPORT) {
             // to avoid accidental lockout, only count attempts that are long enough to be a
             // real password. This may require some tweaking.
             setPasswordEntryInputEnabled(true);
             onPasswordChecked(userId, false /* matched */, 0, false /* not valid - too short */);
+            Arrays.fill(entry, (byte) 0);
             return;
         }
 
@@ -157,6 +160,7 @@
                         }
                         onPasswordChecked(userId, true /* matched */, 0 /* timeoutMs */,
                                 true /* isValidPassword */);
+                        Arrays.fill(entry, (byte) 0);
                     }
 
                     @Override
@@ -171,6 +175,7 @@
                             onPasswordChecked(userId, false /* matched */, timeoutMs,
                                     true /* isValidPassword */);
                         }
+                        Arrays.fill(entry, (byte) 0);
                     }
 
                     @Override
@@ -181,6 +186,7 @@
                             LatencyTracker.getInstance(mContext).onActionEnd(
                                     ACTION_CHECK_CREDENTIAL_UNLOCKED);
                         }
+                        Arrays.fill(entry, (byte) 0);
                     }
                 });
     }
@@ -211,7 +217,7 @@
     }
 
     protected abstract void resetPasswordText(boolean animate, boolean announce);
-    protected abstract String getPasswordText();
+    protected abstract byte[] getPasswordText();
     protected abstract void setPasswordEntryEnabled(boolean enabled);
     protected abstract void setPasswordEntryInputEnabled(boolean enabled);
 
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
index 8de84bf..563b007 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
@@ -279,7 +279,7 @@
      */
     public void dozeTimeTick() {
         if (mClockPlugin != null) {
-            mClockPlugin.dozeTimeTick();
+            mClockPlugin.onTimeTick();
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java b/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java
index 583dac7..9dd9717 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java
@@ -17,7 +17,6 @@
 
 import static android.view.Display.DEFAULT_DISPLAY;
 
-import android.annotation.Nullable;
 import android.app.Presentation;
 import android.content.Context;
 import android.graphics.Point;
@@ -32,15 +31,11 @@
 import android.view.View;
 import android.view.WindowManager;
 
-import java.util.function.BooleanSupplier;
-
 // TODO(multi-display): Support multiple external displays
 public class KeyguardDisplayManager {
     protected static final String TAG = "KeyguardDisplayManager";
     private static boolean DEBUG = KeyguardConstants.DEBUG;
 
-    private final ViewMediatorCallback mCallback;
-
     private final MediaRouter mMediaRouter;
     private final DisplayManager mDisplayService;
     private final Context mContext;
@@ -57,7 +52,7 @@
         public void onDisplayAdded(int displayId) {
             final Display display = mDisplayService.getDisplay(displayId);
             if (mShowing) {
-                notifyIfChanged(() -> showPresentation(display));
+                showPresentation(display);
             }
         }
 
@@ -76,13 +71,12 @@
 
         @Override
         public void onDisplayRemoved(int displayId) {
-            notifyIfChanged(() -> hidePresentation(displayId));
+            hidePresentation(displayId);
         }
     };
 
-    public KeyguardDisplayManager(Context context, ViewMediatorCallback callback) {
+    public KeyguardDisplayManager(Context context) {
         mContext = context;
-        mCallback = callback;
         mMediaRouter = mContext.getSystemService(MediaRouter.class);
         mDisplayService = mContext.getSystemService(DisplayManager.class);
         mDisplayService.registerDisplayListener(mDisplayListener, null /* handler */);
@@ -138,42 +132,13 @@
 
     /**
      * @param displayId The id of the display to hide the presentation off.
-     * @return {@code true} if the a presentation was removed.
-     *         {@code false} if the presentation was not added before.
      */
-    private boolean hidePresentation(int displayId) {
+    private void hidePresentation(int displayId) {
         final Presentation presentation = mPresentations.get(displayId);
         if (presentation != null) {
             presentation.dismiss();
             mPresentations.remove(displayId);
-            return true;
         }
-        return false;
-    }
-
-    private void notifyIfChanged(BooleanSupplier updateMethod) {
-        if (updateMethod.getAsBoolean()) {
-            final int[] displayList = getPresentationDisplayIds();
-            mCallback.onSecondaryDisplayShowingChanged(displayList);
-        }
-    }
-
-    /**
-     * @return An array of displayId's on which a {@link KeyguardPresentation} is showing on.
-     */
-    @Nullable
-    private int[] getPresentationDisplayIds() {
-        final int size = mPresentations.size();
-        if (size == 0) return null;
-
-        final int[] displayIds = new int[size];
-        for (int i = mPresentations.size() - 1; i >= 0; i--) {
-            final Presentation presentation = mPresentations.valueAt(i);
-            if (presentation != null) {
-                displayIds[i] = presentation.getDisplay().getDisplayId();
-            }
-        }
-        return displayIds;
     }
 
     public void show() {
@@ -181,7 +146,7 @@
             if (DEBUG) Log.v(TAG, "show");
             mMediaRouter.addCallback(MediaRouter.ROUTE_TYPE_REMOTE_DISPLAY,
                     mMediaRouterCallback, MediaRouter.CALLBACK_FLAG_PASSIVE_DISCOVERY);
-            notifyIfChanged(() -> updateDisplays(true /* showing */));
+            updateDisplays(true /* showing */);
         }
         mShowing = true;
     }
@@ -190,7 +155,7 @@
         if (mShowing) {
             if (DEBUG) Log.v(TAG, "hide");
             mMediaRouter.removeCallback(mMediaRouterCallback);
-            notifyIfChanged(() -> updateDisplays(false /* showing */));
+            updateDisplays(false /* showing */);
         }
         mShowing = false;
     }
@@ -200,19 +165,19 @@
         @Override
         public void onRouteSelected(MediaRouter router, int type, RouteInfo info) {
             if (DEBUG) Log.d(TAG, "onRouteSelected: type=" + type + ", info=" + info);
-            notifyIfChanged(() -> updateDisplays(mShowing));
+            updateDisplays(mShowing);
         }
 
         @Override
         public void onRouteUnselected(MediaRouter router, int type, RouteInfo info) {
             if (DEBUG) Log.d(TAG, "onRouteUnselected: type=" + type + ", info=" + info);
-            notifyIfChanged(() -> updateDisplays(mShowing));
+            updateDisplays(mShowing);
         }
 
         @Override
         public void onRoutePresentationDisplayChanged(MediaRouter router, RouteInfo info) {
             if (DEBUG) Log.d(TAG, "onRoutePresentationDisplayChanged: info=" + info);
-            notifyIfChanged(() -> updateDisplays(mShowing));
+            updateDisplays(mShowing);
         }
     };
 
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java
index 261f391..185edbf 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java
@@ -241,8 +241,8 @@
     }
 
     @Override
-    protected String getPasswordText() {
-        return mPasswordEntry.getText().toString();
+    protected byte[] getPasswordText() {
+        return charSequenceToByteArray(mPasswordEntry.getText());
     }
 
     @Override
@@ -377,4 +377,18 @@
         return getContext().getString(
                 com.android.internal.R.string.keyguard_accessibility_password_unlock);
     }
+
+    /*
+     * This method avoids creating a new string when getting a byte array from EditView#getText().
+     */
+    private static byte[] charSequenceToByteArray(CharSequence chars) {
+        if (chars == null) {
+            return null;
+        }
+        byte[] bytes = new byte[chars.length()];
+        for (int i = 0; i < chars.length(); i++) {
+            bytes[i] = (byte) chars.charAt(i);
+        }
+        return bytes;
+    }
 }
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardPinBasedInputView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardPinBasedInputView.java
index 3cc18dd..ecafc34 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardPinBasedInputView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardPinBasedInputView.java
@@ -165,8 +165,8 @@
     }
 
     @Override
-    protected String getPasswordText() {
-        return mPasswordEntry.getText();
+    protected byte[] getPasswordText() {
+        return charSequenceToByteArray(mPasswordEntry.getText());
     }
 
     @Override
@@ -264,4 +264,18 @@
         return getContext().getString(
                 com.android.internal.R.string.keyguard_accessibility_pin_unlock);
     }
+
+    /*
+     * This method avoids creating a new string when getting a byte array from EditView#getText().
+     */
+    private static byte[] charSequenceToByteArray(CharSequence chars) {
+        if (chars == null) {
+            return null;
+        }
+        byte[] bytes = new byte[chars.length()];
+        for (int i = 0; i < chars.length(); i++) {
+            bytes[i] = (byte) chars.charAt(i);
+        }
+        return bytes;
+    }
 }
diff --git a/packages/SystemUI/src/com/android/keyguard/ViewMediatorCallback.java b/packages/SystemUI/src/com/android/keyguard/ViewMediatorCallback.java
index a07c5cb..6e06130 100644
--- a/packages/SystemUI/src/com/android/keyguard/ViewMediatorCallback.java
+++ b/packages/SystemUI/src/com/android/keyguard/ViewMediatorCallback.java
@@ -96,11 +96,6 @@
     int getBouncerPromptReason();
 
     /**
-     * Invoked when the secondary displays showing a keyguard window changes.
-     */
-    void onSecondaryDisplayShowingChanged(int[] displayId);
-
-    /**
      * Consumes a message that was enqueued to be displayed on the next time the bouncer shows up.
      * @return Message that should be displayed above the challenge.
      */
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/BubbleClockController.java b/packages/SystemUI/src/com/android/keyguard/clock/BubbleClockController.java
index 3114708..870ac87 100644
--- a/packages/SystemUI/src/com/android/keyguard/clock/BubbleClockController.java
+++ b/packages/SystemUI/src/com/android/keyguard/clock/BubbleClockController.java
@@ -15,6 +15,9 @@
  */
 package com.android.keyguard.clock;
 
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
 import android.graphics.Paint.Style;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -31,6 +34,16 @@
 public class BubbleClockController implements ClockPlugin {
 
     /**
+     * Resources used to get title and thumbnail.
+     */
+    private final Resources mResources;
+
+    /**
+     * LayoutInflater used to inflate custom clock views.
+     */
+    private final LayoutInflater mLayoutInflater;
+
+    /**
      * Custom clock shown on AOD screen and behind stack scroller on lock.
      */
     private View mView;
@@ -48,25 +61,22 @@
      */
     private CrossFadeDarkController mDarkController;
 
-    private BubbleClockController() { }
-
     /**
      * Create a BubbleClockController instance.
      *
      * @param layoutInflater Inflater used to inflate custom clock views.
      */
-    public static BubbleClockController build(LayoutInflater layoutInflater) {
-        BubbleClockController controller = new BubbleClockController();
-        controller.createViews(layoutInflater);
-        return controller;
+    public BubbleClockController(Resources res, LayoutInflater inflater) {
+        mResources = res;
+        mLayoutInflater = inflater;
     }
 
-    private void createViews(LayoutInflater layoutInflater) {
-        mView = layoutInflater.inflate(R.layout.bubble_clock, null);
+    private void createViews() {
+        mView = mLayoutInflater.inflate(R.layout.bubble_clock, null);
         mDigitalClock = (TextClock) mView.findViewById(R.id.digital_clock);
         mAnalogClock = (ImageClock) mView.findViewById(R.id.analog_clock);
 
-        mLockClockContainer = layoutInflater.inflate(R.layout.digital_clock, null);
+        mLockClockContainer = mLayoutInflater.inflate(R.layout.digital_clock, null);
         mLockClock = (TextClock) mLockClockContainer.findViewById(R.id.lock_screen_clock);
         mLockClock.setVisibility(View.GONE);
 
@@ -74,12 +84,33 @@
     }
 
     @Override
+    public String getName() {
+        return "bubble";
+    }
+
+    @Override
+    public String getTitle() {
+        return mResources.getString(R.string.clock_title_bubble);
+    }
+
+    @Override
+    public Bitmap getThumbnail() {
+        return BitmapFactory.decodeResource(mResources, R.drawable.bubble_thumbnail);
+    }
+
+    @Override
     public View getView() {
+        if (mLockClockContainer == null) {
+            createViews();
+        }
         return mLockClockContainer;
     }
 
     @Override
     public View getBigClockView() {
+        if (mView == null) {
+            createViews();
+        }
         return mView;
     }
 
@@ -103,13 +134,13 @@
     }
 
     @Override
-    public void dozeTimeTick() {
-        mAnalogClock.onTimeChanged();
+    public void setDarkAmount(float darkAmount) {
+        mDarkController.setDarkAmount(darkAmount);
     }
 
     @Override
-    public void setDarkAmount(float darkAmount) {
-        mDarkController.setDarkAmount(darkAmount);
+    public void onTimeTick() {
+        mAnalogClock.onTimeChanged();
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java b/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java
index 3827e44..294c725 100644
--- a/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java
+++ b/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java
@@ -23,7 +23,6 @@
 import android.database.ContentObserver;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.Config;
-import android.graphics.BitmapFactory;
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.os.Handler;
@@ -31,6 +30,7 @@
 import android.provider.Settings;
 import android.util.ArrayMap;
 import android.util.DisplayMetrics;
+import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.View.MeasureSpec;
@@ -39,17 +39,19 @@
 import androidx.annotation.VisibleForTesting;
 
 import com.android.internal.colorextraction.ColorExtractor;
-import com.android.keyguard.R;
 import com.android.systemui.colorextraction.SysuiColorExtractor;
 import com.android.systemui.dock.DockManager;
 import com.android.systemui.dock.DockManager.DockEventListener;
 import com.android.systemui.plugins.ClockPlugin;
+import com.android.systemui.plugins.PluginListener;
+import com.android.systemui.shared.plugins.PluginManager;
 import com.android.systemui.util.InjectionInflationController;
 
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
-import java.util.function.Supplier;
+import java.util.concurrent.Callable;
+import java.util.concurrent.FutureTask;
 
 import javax.inject.Inject;
 import javax.inject.Singleton;
@@ -60,26 +62,49 @@
 @Singleton
 public final class ClockManager {
 
+    private static final String TAG = "ClockOptsProvider";
+    private static final String DEFAULT_CLOCK_ID = "default";
+
     private final List<ClockInfo> mClockInfos = new ArrayList<>();
     /**
      * Map from expected value stored in settings to supplier of custom clock face.
      */
-    private final Map<String, Supplier<ClockPlugin>> mClocks = new ArrayMap<>();
+    private final Map<String, ClockPlugin> mClocks = new ArrayMap<>();
     @Nullable private ClockPlugin mCurrentClock;
 
     private final ContentResolver mContentResolver;
     private final SettingsWrapper mSettingsWrapper;
+    private final Handler mMainHandler = new Handler(Looper.getMainLooper());
+
     /**
      * Observe settings changes to know when to switch the clock face.
      */
     private final ContentObserver mContentObserver =
-            new ContentObserver(new Handler(Looper.getMainLooper())) {
+            new ContentObserver(mMainHandler) {
                 @Override
                 public void onChange(boolean selfChange) {
                     super.onChange(selfChange);
                     reload();
                 }
             };
+
+    private final PluginListener<ClockPlugin> mClockPluginListener =
+            new PluginListener<ClockPlugin>() {
+                @Override
+                public void onPluginConnected(ClockPlugin plugin, Context pluginContext) {
+                    addClockPlugin(plugin);
+                    reload();
+                }
+
+                @Override
+                public void onPluginDisconnected(ClockPlugin plugin) {
+                    removeClockPlugin(plugin);
+                    reload();
+                }
+            };
+
+    private final PluginManager mPluginManager;
+
     /**
      * Observe changes to dock state to know when to switch the clock face.
      */
@@ -107,56 +132,29 @@
 
     @Inject
     public ClockManager(Context context, InjectionInflationController injectionInflater,
-            @Nullable DockManager dockManager, SysuiColorExtractor colorExtractor) {
-        this(context, injectionInflater, dockManager, colorExtractor, context.getContentResolver(),
-                new SettingsWrapper(context.getContentResolver()));
+            PluginManager pluginManager, @Nullable DockManager dockManager,
+            SysuiColorExtractor colorExtractor) {
+        this(context, injectionInflater, pluginManager, dockManager, colorExtractor,
+                context.getContentResolver(), new SettingsWrapper(context.getContentResolver()));
     }
 
     ClockManager(Context context, InjectionInflationController injectionInflater,
-            @Nullable DockManager dockManager, SysuiColorExtractor colorExtractor,
-            ContentResolver contentResolver, SettingsWrapper settingsWrapper) {
+            PluginManager pluginManager, @Nullable DockManager dockManager,
+            SysuiColorExtractor colorExtractor, ContentResolver contentResolver,
+            SettingsWrapper settingsWrapper) {
+        mPluginManager = pluginManager;
         mDockManager = dockManager;
         mColorExtractor = colorExtractor;
         mContentResolver = contentResolver;
         mSettingsWrapper = settingsWrapper;
 
         Resources res = context.getResources();
-        mClockInfos.add(ClockInfo.builder()
-                .setName("default")
-                .setTitle(res.getString(R.string.clock_title_default))
-                .setId("default")
-                .setThumbnail(() -> BitmapFactory.decodeResource(res, R.drawable.default_thumbnail))
-                .setPreview(() -> BitmapFactory.decodeResource(res, R.drawable.default_preview))
-                .build());
-        mClockInfos.add(ClockInfo.builder()
-                .setName("bubble")
-                .setTitle(res.getString(R.string.clock_title_bubble))
-                .setId(BubbleClockController.class.getName())
-                .setThumbnail(() -> BitmapFactory.decodeResource(res, R.drawable.bubble_thumbnail))
-                .setPreview(() -> getClockPreview(BubbleClockController.class.getName()))
-                .build());
-        mClockInfos.add(ClockInfo.builder()
-                .setName("stretch")
-                .setTitle(res.getString(R.string.clock_title_stretch))
-                .setId(StretchAnalogClockController.class.getName())
-                .setThumbnail(() -> BitmapFactory.decodeResource(res, R.drawable.stretch_thumbnail))
-                .setPreview(() -> getClockPreview(StretchAnalogClockController.class.getName()))
-                .build());
-        mClockInfos.add(ClockInfo.builder()
-                .setName("type")
-                .setTitle(res.getString(R.string.clock_title_type))
-                .setId(TypeClockController.class.getName())
-                .setThumbnail(() -> BitmapFactory.decodeResource(res, R.drawable.type_thumbnail))
-                .setPreview(() -> getClockPreview(TypeClockController.class.getName()))
-                .build());
-
         LayoutInflater layoutInflater = injectionInflater.injectable(LayoutInflater.from(context));
-        mClocks.put(BubbleClockController.class.getName(),
-                () -> BubbleClockController.build(layoutInflater));
-        mClocks.put(StretchAnalogClockController.class.getName(),
-                () -> StretchAnalogClockController.build(layoutInflater));
-        mClocks.put(TypeClockController.class.getName(),
-                () -> TypeClockController.build(layoutInflater));
+
+        addClockPlugin(new DefaultClockController(res, layoutInflater));
+        addClockPlugin(new BubbleClockController(res, layoutInflater));
+        addClockPlugin(new StretchAnalogClockController(res, layoutInflater));
+        addClockPlugin(new TypeClockController(res, layoutInflater));
 
         // Store the size of the display for generation of clock preview.
         DisplayMetrics dm = res.getDisplayMetrics();
@@ -211,6 +209,29 @@
         return mContentObserver;
     }
 
+    private void addClockPlugin(ClockPlugin plugin) {
+        final String id = plugin.getClass().getName();
+        mClocks.put(plugin.getClass().getName(), plugin);
+        mClockInfos.add(ClockInfo.builder()
+                .setName(plugin.getName())
+                .setTitle(plugin.getTitle())
+                .setId(id)
+                .setThumbnail(() -> plugin.getThumbnail())
+                .setPreview(() -> getClockPreview(id))
+                .build());
+    }
+
+    private void removeClockPlugin(ClockPlugin plugin) {
+        final String id = plugin.getClass().getName();
+        mClocks.remove(id);
+        for (int i = 0; i < mClockInfos.size(); i++) {
+            if (id.equals(mClockInfos.get(i).getId())) {
+                mClockInfos.remove(i);
+                break;
+            }
+        }
+    }
+
     /**
      * Generate a realistic preview of a clock face.
      * @param clockId ID of clock to use for preview, should be obtained from {@link getClockInfos}.
@@ -218,38 +239,54 @@
      */
     @Nullable
     private Bitmap getClockPreview(String clockId) {
-        Supplier<ClockPlugin> supplier = mClocks.get(clockId);
-        if (supplier == null) {
-            return null;
-        }
-        ClockPlugin plugin = supplier.get();
+        FutureTask<Bitmap> task = new FutureTask<>(new Callable<Bitmap>() {
+            @Override
+            public Bitmap call() {
+                Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, Config.ARGB_8888);
+                ClockPlugin plugin = mClocks.get(clockId);
+                if (plugin == null) {
+                    return null;
+                }
 
-        // Use the big clock view for the preview
-        View clockView = plugin.getBigClockView();
-        if (clockView == null) {
-            return null;
+                // Use the big clock view for the preview
+                View clockView = plugin.getBigClockView();
+                if (clockView == null) {
+                    return null;
+                }
+
+                // Initialize state of plugin before generating preview.
+                plugin.setDarkAmount(1f);
+                plugin.setTextColor(Color.WHITE);
+
+                ColorExtractor.GradientColors colors = mColorExtractor.getColors(
+                        WallpaperManager.FLAG_LOCK, true);
+                plugin.setColorPalette(colors.supportsDarkText(), colors.getColorPalette());
+                plugin.onTimeTick();
+
+                // Draw clock view hierarchy to canvas.
+                Canvas canvas = new Canvas(bitmap);
+                canvas.drawColor(Color.BLACK);
+                dispatchVisibilityAggregated(clockView, true);
+                clockView.measure(MeasureSpec.makeMeasureSpec(mWidth, MeasureSpec.EXACTLY),
+                        MeasureSpec.makeMeasureSpec(mHeight, MeasureSpec.EXACTLY));
+                clockView.layout(0, 0, mWidth, mHeight);
+                clockView.draw(canvas);
+                return bitmap;
+            }
+        });
+
+        if (Looper.myLooper() == Looper.getMainLooper()) {
+            task.run();
+        } else {
+            mMainHandler.post(task);
         }
 
-        // Initialize state of plugin before generating preview.
-        plugin.setDarkAmount(1f);
-        plugin.setTextColor(Color.WHITE);
-
-        ColorExtractor.GradientColors colors = mColorExtractor.getColors(WallpaperManager.FLAG_LOCK,
-                true);
-        plugin.setColorPalette(colors.supportsDarkText(), colors.getColorPalette());
-        plugin.dozeTimeTick();
-
-        // Draw clock view hierarchy to canvas.
-        Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, Config.ARGB_8888);
-        Canvas canvas = new Canvas(bitmap);
-        dispatchVisibilityAggregated(clockView, true);
-        clockView.measure(MeasureSpec.makeMeasureSpec(mWidth, MeasureSpec.EXACTLY),
-                MeasureSpec.makeMeasureSpec(mHeight, MeasureSpec.EXACTLY));
-        clockView.layout(0, 0, mWidth, mHeight);
-        canvas.drawColor(Color.BLACK);
-        clockView.draw(canvas);
-
-        return bitmap;
+        try {
+            return task.get();
+        } catch (Exception e) {
+            Log.e(TAG, "Error completing task", e);
+            return null;
+        }
     }
 
     private void dispatchVisibilityAggregated(View view, boolean isVisible) {
@@ -279,6 +316,7 @@
     }
 
     private void register() {
+        mPluginManager.addPluginListener(mClockPluginListener, ClockPlugin.class, true);
         mContentResolver.registerContentObserver(
                 Settings.Secure.getUriFor(Settings.Secure.LOCK_SCREEN_CUSTOM_CLOCK_FACE),
                 false, mContentObserver);
@@ -291,6 +329,7 @@
     }
 
     private void unregister() {
+        mPluginManager.removePluginListener(mClockPluginListener);
         mContentResolver.unregisterContentObserver(mContentObserver);
         if (mDockManager != null) {
             mDockManager.removeListener(mDockEventListener);
@@ -299,7 +338,11 @@
 
     private void reload() {
         mCurrentClock = getClockPlugin();
-        notifyClockChanged(mCurrentClock);
+        if (mCurrentClock instanceof DefaultClockController) {
+            notifyClockChanged(null);
+        } else {
+            notifyClockChanged(mCurrentClock);
+        }
     }
 
     private ClockPlugin getClockPlugin() {
@@ -307,21 +350,15 @@
         if (mIsDocked) {
             final String name = mSettingsWrapper.getDockedClockFace();
             if (name != null) {
-                Supplier<ClockPlugin> supplier = mClocks.get(name);
-                if (supplier != null) {
-                    plugin = supplier.get();
-                    if (plugin != null) {
-                        return plugin;
-                    }
+                plugin = mClocks.get(name);
+                if (plugin != null) {
+                    return plugin;
                 }
             }
         }
         final String name = mSettingsWrapper.getLockScreenCustomClockFace();
         if (name != null) {
-            Supplier<ClockPlugin> supplier = mClocks.get(name);
-            if (supplier != null) {
-                plugin = supplier.get();
-            }
+            plugin = mClocks.get(name);
         }
         return plugin;
     }
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/DefaultClockController.java b/packages/SystemUI/src/com/android/keyguard/clock/DefaultClockController.java
new file mode 100644
index 0000000..8a6a4cd
--- /dev/null
+++ b/packages/SystemUI/src/com/android/keyguard/clock/DefaultClockController.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.keyguard.clock;
+
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Paint.Style;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.TextView;
+
+import com.android.keyguard.R;
+import com.android.systemui.plugins.ClockPlugin;
+
+import java.util.TimeZone;
+
+/**
+ * Plugin for the default clock face used only to provide a preview.
+ */
+public class DefaultClockController implements ClockPlugin {
+
+    /**
+     * Resources used to get title and thumbnail.
+     */
+    private final Resources mResources;
+
+    /**
+     * LayoutInflater used to inflate custom clock views.
+     */
+    private final LayoutInflater mLayoutInflater;
+
+    /**
+     * Root view of preview.
+     */
+    private View mView;
+
+    /**
+     * Text clock in preview view hierarchy.
+     */
+    private TextView mTextTime;
+
+    /**
+     * Date showing below time in preview view hierarchy.
+     */
+    private TextView mTextDate;
+
+    /**
+     * Create a DefaultClockController instance.
+     *
+     * @param inflater Inflater used to inflate custom clock views.
+     */
+    public DefaultClockController(Resources res, LayoutInflater inflater) {
+        mResources = res;
+        mLayoutInflater = inflater;
+    }
+
+    private void createViews() {
+        mView = mLayoutInflater.inflate(R.layout.default_clock_preview, null);
+        mTextTime = mView.findViewById(R.id.time);
+        mTextDate = mView.findViewById(R.id.date);
+    }
+
+    @Override
+    public String getName() {
+        return "default";
+    }
+
+    @Override
+    public String getTitle() {
+        return mResources.getString(R.string.clock_title_default);
+    }
+
+    @Override
+    public Bitmap getThumbnail() {
+        return BitmapFactory.decodeResource(mResources, R.drawable.default_thumbnail);
+    }
+
+    @Override
+    public View getView() {
+        return null;
+    }
+
+    @Override
+    public View getBigClockView() {
+        if (mView == null) {
+            createViews();
+        }
+        return mView;
+    }
+
+    @Override
+    public void setStyle(Style style) {}
+
+    @Override
+    public void setTextColor(int color) {
+        mTextTime.setTextColor(color);
+        mTextDate.setTextColor(color);
+    }
+
+    @Override
+    public void setColorPalette(boolean supportsDarkText, int[] colorPalette) {}
+
+    @Override
+    public void onTimeTick() {
+    }
+
+    @Override
+    public void setDarkAmount(float darkAmount) {}
+
+    @Override
+    public void onTimeZoneChanged(TimeZone timeZone) {}
+
+    @Override
+    public boolean shouldShowStatusArea() {
+        return true;
+    }
+}
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/StretchAnalogClockController.java b/packages/SystemUI/src/com/android/keyguard/clock/StretchAnalogClockController.java
index c465114..7401819 100644
--- a/packages/SystemUI/src/com/android/keyguard/clock/StretchAnalogClockController.java
+++ b/packages/SystemUI/src/com/android/keyguard/clock/StretchAnalogClockController.java
@@ -15,6 +15,9 @@
  */
 package com.android.keyguard.clock;
 
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
 import android.graphics.Paint.Style;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -31,6 +34,16 @@
 public class StretchAnalogClockController implements ClockPlugin {
 
     /**
+     * Resources used to get title and thumbnail.
+     */
+    private final Resources mResources;
+
+    /**
+     * LayoutInflater used to inflate custom clock views.
+     */
+    private final LayoutInflater mLayoutInflater;
+
+    /**
      * Custom clock shown on AOD screen and behind stack scroller on lock.
      */
     private View mBigClockView;
@@ -48,25 +61,22 @@
      */
     private CrossFadeDarkController mDarkController;
 
-    private StretchAnalogClockController() { }
-
     /**
      * Create a BubbleClockController instance.
      *
      * @param layoutInflater Inflater used to inflate custom clock views.
      */
-    public static StretchAnalogClockController build(LayoutInflater layoutInflater) {
-        StretchAnalogClockController controller = new StretchAnalogClockController();
-        controller.createViews(layoutInflater);
-        return controller;
+    public StretchAnalogClockController(Resources res, LayoutInflater inflater) {
+        mResources = res;
+        mLayoutInflater = inflater;
     }
 
-    private void createViews(LayoutInflater layoutInflater) {
-        mBigClockView = layoutInflater.inflate(R.layout.stretchanalog_clock, null);
+    private void createViews() {
+        mBigClockView = mLayoutInflater.inflate(R.layout.stretchanalog_clock, null);
         mAnalogClock = mBigClockView.findViewById(R.id.analog_clock);
         mDigitalClock = mBigClockView.findViewById(R.id.digital_clock);
 
-        mView = layoutInflater.inflate(R.layout.digital_clock, null);
+        mView = mLayoutInflater.inflate(R.layout.digital_clock, null);
         mLockClock = mView.findViewById(R.id.lock_screen_clock);
         mLockClock.setVisibility(View.GONE);
 
@@ -74,12 +84,33 @@
     }
 
     @Override
+    public String getName() {
+        return "stretch";
+    }
+
+    @Override
+    public String getTitle() {
+        return mResources.getString(R.string.clock_title_stretch);
+    }
+
+    @Override
+    public Bitmap getThumbnail() {
+        return BitmapFactory.decodeResource(mResources, R.drawable.stretch_thumbnail);
+    }
+
+    @Override
     public View getView() {
+        if (mView == null) {
+            createViews();
+        }
         return mView;
     }
 
     @Override
     public View getBigClockView() {
+        if (mBigClockView == null) {
+            createViews();
+        }
         return mBigClockView;
     }
 
@@ -103,7 +134,7 @@
     }
 
     @Override
-    public void dozeTimeTick() {
+    public void onTimeTick() {
         mAnalogClock.onTimeChanged();
     }
 
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/TypeClockController.java b/packages/SystemUI/src/com/android/keyguard/clock/TypeClockController.java
index 2ea39c4..69f86c7 100644
--- a/packages/SystemUI/src/com/android/keyguard/clock/TypeClockController.java
+++ b/packages/SystemUI/src/com/android/keyguard/clock/TypeClockController.java
@@ -15,6 +15,9 @@
  */
 package com.android.keyguard.clock;
 
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
 import android.graphics.Paint.Style;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -30,6 +33,16 @@
 public class TypeClockController implements ClockPlugin {
 
     /**
+     * Resources used to get title and thumbnail.
+     */
+    private final Resources mResources;
+
+    /**
+     * LayoutInflater used to inflate custom clock views.
+     */
+    private final LayoutInflater mLayoutInflater;
+
+    /**
      * Custom clock shown on AOD screen and behind stack scroller on lock.
      */
     private View mView;
@@ -45,36 +58,54 @@
      */
     private CrossFadeDarkController mDarkController;
 
-    private TypeClockController() {}
-
     /**
      * Create a TypeClockController instance.
      *
      * @param inflater Inflater used to inflate custom clock views.
      */
-    public static TypeClockController build(LayoutInflater inflater) {
-        TypeClockController controller = new TypeClockController();
-        controller.createViews(inflater);
-        return controller;
+    TypeClockController(Resources res, LayoutInflater inflater) {
+        mResources = res;
+        mLayoutInflater = inflater;
     }
 
-    private void createViews(LayoutInflater inflater) {
-        mView = inflater.inflate(R.layout.type_clock, null);
+    private void createViews() {
+        mView = mLayoutInflater.inflate(R.layout.type_clock, null);
         mTypeClock = mView.findViewById(R.id.type_clock);
 
         // For now, this view is used to hide the default digital clock.
         // Need better transition to lock screen.
-        mLockClockContainer = inflater.inflate(R.layout.digital_clock, null);
+        mLockClockContainer = mLayoutInflater.inflate(R.layout.digital_clock, null);
         mLockClockContainer.setVisibility(View.GONE);
     }
 
     @Override
+    public String getName() {
+        return "type";
+    }
+
+    @Override
+    public String getTitle() {
+        return mResources.getString(R.string.clock_title_type);
+    }
+
+    @Override
+    public Bitmap getThumbnail() {
+        return BitmapFactory.decodeResource(mResources, R.drawable.type_thumbnail);
+    }
+
+    @Override
     public View getView() {
+        if (mLockClockContainer == null) {
+            createViews();
+        }
         return mLockClockContainer;
     }
 
     @Override
     public View getBigClockView() {
+        if (mView == null) {
+            createViews();
+        }
         return mView;
     }
 
@@ -96,7 +127,7 @@
     }
 
     @Override
-    public void dozeTimeTick() {
+    public void onTimeTick() {
         mTypeClock.onTimeChanged();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java b/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
index 2006794..592b603 100644
--- a/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
+++ b/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
@@ -46,7 +46,7 @@
 import android.widget.TextView;
 
 import com.android.settingslib.Utils;
-import com.android.settingslib.graph.BatteryMeterDrawableBase;
+import com.android.settingslib.graph.ThemedBatteryDrawable;
 import com.android.systemui.plugins.DarkIconDispatcher;
 import com.android.systemui.plugins.DarkIconDispatcher.DarkReceiver;
 import com.android.systemui.settings.CurrentUserTracker;
@@ -76,7 +76,7 @@
     public static final int MODE_OFF = 2;
     public static final int MODE_ESTIMATE = 3;
 
-    private final BatteryMeterDrawableBase mDrawable;
+    private final ThemedBatteryDrawable mDrawable;
     private final String mSlotBattery;
     private final ImageView mBatteryIconView;
     private final CurrentUserTracker mUserTracker;
@@ -94,9 +94,11 @@
     private boolean mIsSubscribedForTunerUpdates;
     private boolean mCharging;
 
+    private int mDarkModeSingleToneColor;
     private int mDarkModeBackgroundColor;
     private int mDarkModeFillColor;
 
+    private int mLightModeSingleToneColor;
     private int mLightModeBackgroundColor;
     private int mLightModeFillColor;
     private int mUser;
@@ -106,6 +108,7 @@
      */
     private boolean mUseWallpaperTextColors;
 
+    private int mNonAdaptedSingleToneColor;
     private int mNonAdaptedForegroundColor;
     private int mNonAdaptedBackgroundColor;
 
@@ -127,7 +130,7 @@
                 defStyle, 0);
         final int frameColor = atts.getColor(R.styleable.BatteryMeterView_frameColor,
                 context.getColor(R.color.meter_background_color));
-        mDrawable = new BatteryMeterDrawableBase(context, frameColor);
+        mDrawable = new ThemedBatteryDrawable(context, frameColor);
         atts.recycle();
 
         mSettingObserver = new SettingObserver(new Handler(context.getMainLooper()));
@@ -169,6 +172,10 @@
         setClipChildren(false);
         setClipToPadding(false);
         Dependency.get(ConfigurationController.class).observe(viewAttachLifecycle(this), this);
+
+        // Needed for PorderDuff.Mode.CLEAR operations to work properly, but redraws don't happen
+        // enough to justify a hardware layer.
+        setLayerType(LAYER_TYPE_SOFTWARE, null);
     }
 
     public void setForceShowPercent(boolean show) {
@@ -243,9 +250,11 @@
         if (mUseWallpaperTextColors) {
             updateColors(
                     Utils.getColorAttrDefaultColor(mContext, R.attr.wallpaperTextColor),
-                    Utils.getColorAttrDefaultColor(mContext, R.attr.wallpaperTextColorSecondary));
+                    Utils.getColorAttrDefaultColor(mContext, R.attr.wallpaperTextColorSecondary),
+                    Utils.getColorAttrDefaultColor(mContext, R.attr.wallpaperTextColor));
         } else {
-            updateColors(mNonAdaptedForegroundColor, mNonAdaptedBackgroundColor);
+            updateColors(mNonAdaptedForegroundColor, mNonAdaptedBackgroundColor,
+                    mNonAdaptedSingleToneColor);
         }
     }
 
@@ -258,10 +267,14 @@
                 Utils.getThemeAttr(context, R.attr.darkIconTheme));
         Context dualToneLightTheme = new ContextThemeWrapper(context,
                 Utils.getThemeAttr(context, R.attr.lightIconTheme));
+        mDarkModeSingleToneColor = Utils.getColorAttrDefaultColor(dualToneDarkTheme,
+                R.attr.singleToneColor);
         mDarkModeBackgroundColor = Utils.getColorAttrDefaultColor(dualToneDarkTheme,
                 R.attr.backgroundColor);
         mDarkModeFillColor = Utils.getColorAttrDefaultColor(dualToneDarkTheme,
                 R.attr.fillColor);
+        mLightModeSingleToneColor = Utils.getColorAttrDefaultColor(dualToneLightTheme,
+                R.attr.singleToneColor);
         mLightModeBackgroundColor = Utils.getColorAttrDefaultColor(dualToneLightTheme,
                 R.attr.backgroundColor);
         mLightModeFillColor = Utils.getColorAttrDefaultColor(dualToneLightTheme, R.attr.fillColor);
@@ -303,8 +316,8 @@
 
     @Override
     public void onBatteryLevelChanged(int level, boolean pluggedIn, boolean charging) {
-        mDrawable.setBatteryLevel(level);
         mDrawable.setCharging(pluggedIn);
+        mDrawable.setBatteryLevel(level);
         mCharging = pluggedIn;
         mLevel = level;
         updatePercentText();
@@ -315,7 +328,7 @@
 
     @Override
     public void onPowerSaveChanged(boolean isPowerSave) {
-        mDrawable.setPowerSave(isPowerSave);
+        mDrawable.setPowerSaveEnabled(isPowerSave);
     }
 
     private TextView loadPercentView() {
@@ -406,21 +419,24 @@
     @Override
     public void onDarkChanged(Rect area, float darkIntensity, int tint) {
         float intensity = DarkIconDispatcher.isInArea(area, this) ? darkIntensity : 0;
+        mNonAdaptedSingleToneColor = getColorForDarkIntensity(
+                intensity, mLightModeSingleToneColor, mDarkModeSingleToneColor);
         mNonAdaptedForegroundColor = getColorForDarkIntensity(
                 intensity, mLightModeFillColor, mDarkModeFillColor);
         mNonAdaptedBackgroundColor = getColorForDarkIntensity(
                 intensity, mLightModeBackgroundColor,mDarkModeBackgroundColor);
 
         if (!mUseWallpaperTextColors) {
-            updateColors(mNonAdaptedForegroundColor, mNonAdaptedBackgroundColor);
+            updateColors(mNonAdaptedForegroundColor, mNonAdaptedBackgroundColor,
+                    mNonAdaptedSingleToneColor);
         }
     }
 
-    private void updateColors(int foregroundColor, int backgroundColor) {
-        mDrawable.setColors(foregroundColor, backgroundColor);
-        mTextColor = foregroundColor;
+    private void updateColors(int foregroundColor, int backgroundColor, int singleToneColor) {
+        mDrawable.setColors(foregroundColor, backgroundColor, singleToneColor);
+        mTextColor = singleToneColor;
         if (mBatteryPercentView != null) {
-            mBatteryPercentView.setTextColor(foregroundColor);
+            mBatteryPercentView.setTextColor(singleToneColor);
         }
     }
 
@@ -429,7 +445,7 @@
     }
 
     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
-        String powerSave = mDrawable == null ? null : mDrawable.getPowerSave() + "";
+        String powerSave = mDrawable == null ? null : mDrawable.getPowerSaveEnabled() + "";
         CharSequence percent = mBatteryPercentView == null ? null : mBatteryPercentView.getText();
         pw.println("  BatteryMeterView:");
         pw.println("    mDrawable.getPowerSave: " + powerSave);
diff --git a/packages/SystemUI/src/com/android/systemui/Dependency.java b/packages/SystemUI/src/com/android/systemui/Dependency.java
index 5672073..87f004f 100644
--- a/packages/SystemUI/src/com/android/systemui/Dependency.java
+++ b/packages/SystemUI/src/com/android/systemui/Dependency.java
@@ -61,7 +61,6 @@
 import com.android.systemui.statusbar.notification.NotificationEntryManager;
 import com.android.systemui.statusbar.notification.NotificationFilter;
 import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
-import com.android.systemui.statusbar.notification.NotificationRowBinder;
 import com.android.systemui.statusbar.notification.VisualStabilityManager;
 import com.android.systemui.statusbar.notification.collection.NotificationData.KeyguardEnvironment;
 import com.android.systemui.statusbar.notification.logging.NotificationLogger;
@@ -266,7 +265,6 @@
     @Inject Lazy<NotificationListener> mNotificationListener;
     @Inject Lazy<NotificationLogger> mNotificationLogger;
     @Inject Lazy<NotificationViewHierarchyManager> mNotificationViewHierarchyManager;
-    @Inject Lazy<NotificationRowBinder> mNotificationRowBinder;
     @Inject Lazy<NotificationFilter> mNotificationFilter;
     @Inject Lazy<NotificationInterruptionStateProvider> mNotificationInterruptionStateProvider;
     @Inject Lazy<KeyguardDismissUtil> mKeyguardDismissUtil;
@@ -440,7 +438,6 @@
         mProviders.put(NotificationLogger.class, mNotificationLogger::get);
         mProviders.put(NotificationViewHierarchyManager.class,
                 mNotificationViewHierarchyManager::get);
-        mProviders.put(NotificationRowBinder.class, mNotificationRowBinder::get);
         mProviders.put(NotificationFilter.class, mNotificationFilter::get);
         mProviders.put(NotificationInterruptionStateProvider.class,
                 mNotificationInterruptionStateProvider::get);
diff --git a/packages/SystemUI/src/com/android/systemui/HardwareUiLayout.java b/packages/SystemUI/src/com/android/systemui/HardwareUiLayout.java
index 2a1d066..f5451e9 100644
--- a/packages/SystemUI/src/com/android/systemui/HardwareUiLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/HardwareUiLayout.java
@@ -63,6 +63,9 @@
 
     public HardwareUiLayout(Context context, AttributeSet attrs) {
         super(context, attrs);
+        // Manually re-initialize mRotation to portrait-mode, since this view must always
+        // be constructed in portrait mode and rotated into the correct initial position.
+        mRotation = ROTATION_NONE;
         updateSettings();
     }
 
@@ -172,6 +175,10 @@
                 mSeparatedView.setBackground(mSeparatedViewBackground);
                 updateEdgeMargin(mEdgeBleed ? 0 : getEdgePadding());
                 mOldHeight = mList.getMeasuredHeight();
+
+                // Must be called to initialize view rotation correctly.
+                // Requires LayoutParams, hence why this isn't called during the constructor.
+                updateRotation();
             } else {
                 return;
             }
@@ -189,7 +196,18 @@
         mSwapOrientation = swapOrientation;
     }
 
-    @Override
+    private void updateRotation() {
+        int rotation = RotationUtils.getRotation(getContext());
+        if (rotation != mRotation) {
+            rotate(mRotation, rotation);
+            mRotation = rotation;
+        }
+    }
+
+    /**
+     *  Requires LayoutParams to be set to work correctly, and therefore must be run after after
+     *  the HardwareUILayout has been added to the view hierarchy.
+     */
     protected void rotate(int from, int to) {
         super.rotate(from, to);
         if (from != ROTATION_NONE && to != ROTATION_NONE) {
@@ -522,4 +540,4 @@
         inoutInfo.contentInsets.set(mList.getLeft(), mList.getTop(),
                 0, getBottom() - mList.getBottom());
     };
-}
+}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java
index b635033..603b3b9 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java
@@ -39,6 +39,7 @@
 import android.graphics.Insets;
 import android.graphics.Point;
 import android.graphics.drawable.Drawable;
+import android.graphics.drawable.GradientDrawable;
 import android.graphics.drawable.ShapeDrawable;
 import android.os.RemoteException;
 import android.os.ServiceManager;
@@ -48,7 +49,6 @@
 import android.util.Log;
 import android.util.StatsLog;
 import android.view.View;
-import android.view.ViewGroup;
 import android.view.WindowInsets;
 import android.widget.FrameLayout;
 import android.widget.ImageButton;
@@ -189,6 +189,8 @@
         mPointerView.setBackground(triangleDrawable);
 
         FrameLayout viewWrapper = findViewById(R.id.header_permission_wrapper);
+        viewWrapper.setBackground(createHeaderPermissionBackground(bgColor));
+
         LayoutTransition transition = new LayoutTransition();
         transition.setDuration(200);
 
@@ -204,6 +206,7 @@
         viewWrapper.setLayoutTransition(transition);
         viewWrapper.getLayoutTransition().enableTransitionType(LayoutTransition.CHANGING);
 
+
         mHeaderHeight = getContext().getResources().getDimensionPixelSize(
                 R.dimen.bubble_expanded_header_height);
         mPermissionHeight = getContext().getResources().getDimensionPixelSize(
@@ -243,7 +246,10 @@
         if (!mShowOnTop) {
             removeView(mPointerView);
             if (mUseFooter) {
+                View divider = findViewById(R.id.divider);
+                viewWrapper.removeView(divider);
                 removeView(viewWrapper);
+                addView(divider);
                 addView(viewWrapper);
             }
             addView(mPointerView);
@@ -251,6 +257,25 @@
     }
 
     /**
+     * Creates a background with corners rounded based on how the view is configured to display
+     */
+    private Drawable createHeaderPermissionBackground(int bgColor) {
+        TypedArray ta2 = getContext().obtainStyledAttributes(
+                new int[] {android.R.attr.dialogCornerRadius});
+        final float cr = ta2.getDimension(0, 0f);
+        ta2.recycle();
+
+        float[] radii = mUseFooter
+                ? new float[] {0, 0, 0, 0, cr, cr, cr, cr}
+                : new float[] {cr, cr, cr, cr, 0, 0, 0, 0};
+        GradientDrawable chromeBackground = new GradientDrawable();
+        chromeBackground.setShape(GradientDrawable.RECTANGLE);
+        chromeBackground.setCornerRadii(radii);
+        chromeBackground.setColor(bgColor);
+        return chromeBackground;
+    }
+
+    /**
      * Sets the listener to notify when a bubble has been blocked.
      */
     public void setOnBlockedListener(OnBubbleBlockedListener listener) {
@@ -491,23 +516,14 @@
     /**
      * Removes and releases an ActivityView if one was previously created for this bubble.
      */
-    public void destroyActivityView(ViewGroup tmpParent) {
+    public void destroyActivityView() {
         if (mActivityView == null) {
             return;
         }
-        if (!mActivityViewReady) {
-            // release not needed, never initialized?
-            mActivityView = null;
-            return;
+        if (mActivityViewReady) {
+            mActivityView.release();
         }
-        // HACK: release() will crash if the view is not attached.
-        if (!isAttachedToWindow()) {
-            mActivityView.setVisibility(View.GONE);
-            tmpParent.addView(this);
-        }
-
-        mActivityView.release();
-        ((ViewGroup) getParent()).removeView(this);
+        removeView(mActivityView);
         mActivityView = null;
         mActivityViewReady = false;
     }
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
index 167bf47..8235d8d 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
@@ -348,7 +348,7 @@
 
         // Remove it from the views
         int removedIndex = mBubbleContainer.indexOfChild(b.iconView);
-        b.expandedView.destroyActivityView(this /* tmpParent */);
+        b.expandedView.destroyActivityView();
         mBubbleContainer.removeView(b.iconView);
 
         int bubbleCount = mBubbleContainer.getChildCount();
@@ -377,7 +377,7 @@
     public void stackDismissed() {
         for (Bubble bubble : mBubbleData.getBubbles()) {
             bubble.entry.setBubbleDismissed(true);
-            bubble.expandedView.destroyActivityView(this /* tmpParent */);
+            bubble.expandedView.destroyActivityView();
         }
         mBubbleData.clear();
         collapseStack();
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java
index 165eb1d..c8eebac 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java
@@ -81,8 +81,7 @@
         // anything, collapse the stack.
         if (action == MotionEvent.ACTION_OUTSIDE || mTouchedView == null) {
             mStack.collapseStack();
-            cleanUpDismissTarget();
-            mTouchedView = null;
+            resetForNextGesture();
             return false;
         }
 
@@ -135,8 +134,7 @@
                 break;
 
             case MotionEvent.ACTION_CANCEL:
-                mTouchedView = null;
-                cleanUpDismissTarget();
+                resetForNextGesture();
                 break;
 
             case MotionEvent.ACTION_UP:
@@ -144,7 +142,7 @@
                 if (mInDismissTarget && isStack) {
                     mController.dismissStack();
                 } else if (mMovedEnough) {
-                    mVelocityTracker.computeCurrentVelocity(1000);
+                    mVelocityTracker.computeCurrentVelocity(/* maxVelocity */ 1000);
                     final float velX = mVelocityTracker.getXVelocity();
                     final float velY = mVelocityTracker.getYVelocity();
                     if (isStack) {
@@ -157,7 +155,7 @@
                             mController.removeBubble(((BubbleView) mTouchedView).getKey());
                         }
                     }
-                } else if (mTouchedView.equals(mStack.getExpandedBubbleView())) {
+                } else if (mTouchedView == mStack.getExpandedBubbleView()) {
                     mStack.collapseStack();
                 } else if (isStack) {
                     if (mStack.isExpanded()) {
@@ -169,17 +167,25 @@
                     mStack.setExpandedBubble(((BubbleView) mTouchedView).getKey());
                 }
 
-                cleanUpDismissTarget();
-                mVelocityTracker.recycle();
-                mVelocityTracker = null;
-                mTouchedView = null;
-                mMovedEnough = false;
+                resetForNextGesture();
                 break;
         }
 
         return true;
     }
 
+    /** Clears all touch-related state. */
+    private void resetForNextGesture() {
+        cleanUpDismissTarget();
+        if (mVelocityTracker != null) {
+            mVelocityTracker.recycle();
+            mVelocityTracker = null;
+        }
+        mTouchedView = null;
+        mMovedEnough = false;
+        mInDismissTarget = false;
+    }
+
     /**
      * Removes the dismiss target and cancels any pending callbacks to show it.
      */
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeDockHandler.java b/packages/SystemUI/src/com/android/systemui/doze/DozeDockHandler.java
index 5353ee6..06dbdbf 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeDockHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeDockHandler.java
@@ -17,11 +17,11 @@
 package com.android.systemui.doze;
 
 import android.content.Context;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.os.Handler;
 import android.os.UserHandle;
 import android.util.Log;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.systemui.dock.DockManager;
 import com.android.systemui.doze.DozeMachine.State;
 
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeFactory.java b/packages/SystemUI/src/com/android/systemui/doze/DozeFactory.java
index 3250182..36e28dc 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeFactory.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeFactory.java
@@ -21,9 +21,9 @@
 import android.content.Context;
 import android.hardware.Sensor;
 import android.hardware.SensorManager;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.os.Handler;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java b/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java
index 4d89a39..6c4be06 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java
@@ -17,12 +17,12 @@
 package com.android.systemui.doze;
 
 import android.annotation.MainThread;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.os.Trace;
 import android.os.UserHandle;
 import android.util.Log;
 import android.view.Display;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.internal.util.Preconditions;
 import com.android.systemui.statusbar.phone.DozeParameters;
 import com.android.systemui.util.Assert;
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java b/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
index 2d1dba6..77180f8 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
@@ -30,6 +30,7 @@
 import android.hardware.SensorManager;
 import android.hardware.TriggerEvent;
 import android.hardware.TriggerEventListener;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.net.Uri;
 import android.os.Handler;
 import android.os.SystemClock;
@@ -38,7 +39,8 @@
 import android.text.TextUtils;
 import android.util.Log;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
+import androidx.annotation.VisibleForTesting;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto;
 import com.android.systemui.plugins.SensorManagerPlugin;
@@ -60,7 +62,6 @@
     private final Context mContext;
     private final AlarmManager mAlarmManager;
     private final SensorManager mSensorManager;
-    private final TriggerSensor[] mSensors;
     private final ContentResolver mResolver;
     private final TriggerSensor mPickupSensor;
     private final DozeParameters mDozeParameters;
@@ -68,10 +69,12 @@
     private final WakeLock mWakeLock;
     private final Consumer<Boolean> mProxCallback;
     private final Callback mCallback;
+    @VisibleForTesting
+    protected final TriggerSensor[] mSensors;
 
     private final Handler mHandler = new Handler();
     private final ProxSensor mProxSensor;
-
+    private long mDebounceFrom;
 
     public DozeSensors(Context context, AlarmManager alarmManager, SensorManager sensorManager,
             DozeParameters dozeParameters, AmbientDisplayConfiguration config, WakeLock wakeLock,
@@ -134,13 +137,21 @@
                         mConfig.wakeScreenGestureAvailable() && alwaysOn,
                         DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN,
                         false /* reports touch coordinates */,
-                        false /* touchscreen */),
+                        false /* touchscreen */, mConfig.getWakeLockScreenDebounce()),
         };
 
         mProxSensor = new ProxSensor(policy);
         mCallback = callback;
     }
 
+    /**
+     * Temporarily disable some sensors to avoid turning on the device while the user is
+     * turning it off.
+     */
+    public void requestTemporaryDisable() {
+        mDebounceFrom = SystemClock.uptimeMillis();
+    }
+
     private Sensor findSensorWithType(String type) {
         return findSensorWithType(mSensorManager, type);
     }
@@ -179,15 +190,6 @@
         }
     }
 
-    public void reregisterAllSensors() {
-        for (TriggerSensor s : mSensors) {
-            s.setListening(false);
-        }
-        for (TriggerSensor s : mSensors) {
-            s.setListening(true);
-        }
-    }
-
     public void onUserSwitched() {
         for (TriggerSensor s : mSensors) {
             s.updateListener();
@@ -320,7 +322,8 @@
         }
     }
 
-    private class TriggerSensor extends TriggerEventListener {
+    @VisibleForTesting
+    class TriggerSensor extends TriggerEventListener {
         final Sensor mSensor;
         final boolean mConfigured;
         final int mPulseReason;
@@ -467,23 +470,25 @@
     /**
      * A Sensor that is injected via plugin.
      */
-    private class PluginSensor extends TriggerSensor {
+    @VisibleForTesting
+    class PluginSensor extends TriggerSensor implements SensorManagerPlugin.SensorEventListener {
 
-        private final SensorManagerPlugin.Sensor mPluginSensor;
-        private final SensorManagerPlugin.SensorEventListener mTriggerEventListener = (event) -> {
-            DozeLog.traceSensor(mContext, mPulseReason);
-            mHandler.post(mWakeLock.wrap(() -> {
-                if (DEBUG) Log.d(TAG, "onSensorEvent: " + triggerEventToString(event));
-                mCallback.onSensorPulse(mPulseReason, true /* sensorPerformsProxCheck */, -1, -1,
-                        event.getValues());
-            }));
-        };
+        final SensorManagerPlugin.Sensor mPluginSensor;
+        private long mDebounce;
 
         PluginSensor(SensorManagerPlugin.Sensor sensor, String setting, boolean configured,
                 int pulseReason, boolean reportsTouchCoordinates, boolean requiresTouchscreen) {
+            this(sensor, setting, configured, pulseReason, reportsTouchCoordinates,
+                    requiresTouchscreen, 0L /* debounce */);
+        }
+
+        PluginSensor(SensorManagerPlugin.Sensor sensor, String setting, boolean configured,
+                int pulseReason, boolean reportsTouchCoordinates, boolean requiresTouchscreen,
+                long debounce) {
             super(null, setting, configured, pulseReason, reportsTouchCoordinates,
                     requiresTouchscreen);
             mPluginSensor = sensor;
+            mDebounce = debounce;
         }
 
         @Override
@@ -492,11 +497,11 @@
             AsyncSensorManager asyncSensorManager = (AsyncSensorManager) mSensorManager;
             if (mRequested && !mDisabled && (enabledBySetting() || mIgnoresSetting)
                     && !mRegistered) {
-                asyncSensorManager.registerPluginListener(mPluginSensor, mTriggerEventListener);
+                asyncSensorManager.registerPluginListener(mPluginSensor, this);
                 mRegistered = true;
                 if (DEBUG) Log.d(TAG, "registerPluginListener");
             } else if (mRegistered) {
-                asyncSensorManager.unregisterPluginListener(mPluginSensor, mTriggerEventListener);
+                asyncSensorManager.unregisterPluginListener(mPluginSensor, this);
                 mRegistered = false;
                 if (DEBUG) Log.d(TAG, "unregisterPluginListener");
             }
@@ -524,6 +529,21 @@
             }
             return sb.append(']').toString();
         }
+
+        @Override
+        public void onSensorChanged(SensorManagerPlugin.SensorEvent event) {
+            DozeLog.traceSensor(mContext, mPulseReason);
+            mHandler.post(mWakeLock.wrap(() -> {
+                final long now = SystemClock.uptimeMillis();
+                if (now < mDebounceFrom + mDebounce) {
+                    if (DEBUG) Log.d(TAG, "onSensorEvent dropped: " + triggerEventToString(event));
+                    return;
+                }
+                if (DEBUG) Log.d(TAG, "onSensorEvent: " + triggerEventToString(event));
+                mCallback.onSensorPulse(mPulseReason, true /* sensorPerformsProxCheck */, -1, -1,
+                        event.getValues());
+            }));
+        }
     }
 
     public interface Callback {
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
index 70bf903..b2f707f 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
@@ -27,6 +27,7 @@
 import android.hardware.SensorEvent;
 import android.hardware.SensorEventListener;
 import android.hardware.SensorManager;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.os.Handler;
 import android.os.SystemClock;
 import android.os.UserHandle;
@@ -34,7 +35,6 @@
 import android.util.Log;
 
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.internal.util.Preconditions;
 import com.android.systemui.dock.DockManager;
 import com.android.systemui.statusbar.phone.DozeParameters;
@@ -143,8 +143,12 @@
 
         if (isWakeDisplay) {
             onWakeScreen(wakeEvent, mMachine.getState());
-        } else if (isLongPress || isWakeLockScreen) {
+        } else if (isLongPress) {
             requestPulse(pulseReason, sensorPerformedProxCheck);
+        } else if (isWakeLockScreen) {
+            if (wakeEvent) {
+                requestPulse(pulseReason, sensorPerformedProxCheck);
+            }
         } else {
             proximityCheckThenCall((result) -> {
                 if (result == ProximityCheck.RESULT_NEAR) {
@@ -228,14 +232,12 @@
                 if (mDockManager != null) {
                     mDockManager.addListener(mDockEventListener);
                 }
+                mDozeSensors.requestTemporaryDisable();
                 checkTriggersAtInit();
                 break;
             case DOZE:
             case DOZE_AOD:
                 mDozeSensors.setProxListening(newState != DozeMachine.State.DOZE);
-                if (oldState != DozeMachine.State.INITIALIZED) {
-                    mDozeSensors.reregisterAllSensors();
-                }
                 mDozeSensors.setListening(true);
                 if (newState == DozeMachine.State.DOZE_AOD && !sWakeDisplaySensorState) {
                     onWakeScreen(false, newState);
@@ -250,6 +252,9 @@
                 mDozeSensors.setTouchscreenSensorsListening(false);
                 mDozeSensors.setProxListening(true);
                 break;
+            case DOZE_PULSE_DONE:
+                mDozeSensors.requestTemporaryDisable();
+                break;
             case FINISH:
                 mBroadcastReceiver.unregister(mContext);
                 mDozeHost.removeCallback(mHostCallback);
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index 66cfadf..172746e 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -21,7 +21,6 @@
 import static com.android.internal.telephony.IccCardConstants.State.ABSENT;
 import static com.android.internal.telephony.IccCardConstants.State.PIN_REQUIRED;
 import static com.android.internal.telephony.IccCardConstants.State.PUK_REQUIRED;
-import static com.android.internal.telephony.IccCardConstants.State.READY;
 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_USER_REQUEST;
 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT;
@@ -95,7 +94,6 @@
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 import java.util.ArrayList;
-import java.util.Arrays;
 
 /**
  * Mediates requests related to the keyguard.  This includes queries about the
@@ -247,9 +245,6 @@
     // AOD is enabled and status bar is in AOD state.
     private boolean mAodShowing;
 
-    // display ids of the external display on which we have put a keyguard window
-    private int[] mSecondaryDisplaysShowing;
-
     /** Cached value of #isInputRestricted */
     private boolean mInputRestricted;
 
@@ -687,13 +682,6 @@
             mCustomMessage = null;
             return message;
         }
-
-        @Override
-        public void onSecondaryDisplayShowingChanged(int[] displayIds) {
-            synchronized (KeyguardViewMediator.this) {
-                setShowingLocked(mShowing, mAodShowing, displayIds, false);
-            }
-        }
     };
 
     public void userActivity() {
@@ -722,7 +710,7 @@
         mContext.registerReceiver(mDelayedLockBroadcastReceiver, delayedActionFilter,
                 SYSTEMUI_PERMISSION, null /* scheduler */);
 
-        mKeyguardDisplayManager = new KeyguardDisplayManager(mContext, mViewMediatorCallback);
+        mKeyguardDisplayManager = new KeyguardDisplayManager(mContext);
 
         mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
 
@@ -738,10 +726,10 @@
             setShowingLocked(!shouldWaitForProvisioning()
                     && !mLockPatternUtils.isLockScreenDisabled(
                             KeyguardUpdateMonitor.getCurrentUser()),
-                    mAodShowing, mSecondaryDisplaysShowing, true /* forceCallbacks */);
+                    mAodShowing, true /* forceCallbacks */);
         } else {
             // The system's keyguard is disabled or missing.
-            setShowingLocked(false, mAodShowing, mSecondaryDisplaysShowing, true);
+            setShowingLocked(false, mAodShowing, true);
         }
 
         mStatusBarKeyguardViewManager =
@@ -1764,12 +1752,10 @@
         playSound(mTrustedSoundId);
     }
 
-    private void updateActivityLockScreenState(boolean showing, boolean aodShowing,
-            int[] secondaryDisplaysShowing) {
+    private void updateActivityLockScreenState(boolean showing, boolean aodShowing) {
         mUiOffloadThread.submit(() -> {
             try {
-                ActivityTaskManager.getService().setLockScreenShown(showing, aodShowing,
-                        secondaryDisplaysShowing);
+                ActivityTaskManager.getService().setLockScreenShown(showing, aodShowing);
             } catch (RemoteException e) {
             }
         });
@@ -1892,8 +1878,7 @@
 
             if (!mHiding) {
                 // Tell ActivityManager that we canceled the keyguardExitAnimation.
-                setShowingLocked(mShowing, mAodShowing, mSecondaryDisplaysShowing,
-                        true /* force */);
+                setShowingLocked(mShowing, mAodShowing, true /* force */);
                 return;
             }
             mHiding = false;
@@ -2163,23 +2148,19 @@
     }
 
     private void setShowingLocked(boolean showing, boolean aodShowing) {
-        setShowingLocked(showing, aodShowing, mSecondaryDisplaysShowing,
-                false /* forceCallbacks */);
+        setShowingLocked(showing, aodShowing, false /* forceCallbacks */);
     }
 
-    private void setShowingLocked(boolean showing, boolean aodShowing,
-            int[] secondaryDisplaysShowing, boolean forceCallbacks) {
+    private void setShowingLocked(boolean showing, boolean aodShowing, boolean forceCallbacks) {
         final boolean notifyDefaultDisplayCallbacks = showing != mShowing
                 || aodShowing != mAodShowing || forceCallbacks;
-        if (notifyDefaultDisplayCallbacks
-                || !Arrays.equals(secondaryDisplaysShowing, mSecondaryDisplaysShowing)) {
+        if (notifyDefaultDisplayCallbacks) {
             mShowing = showing;
             mAodShowing = aodShowing;
-            mSecondaryDisplaysShowing = secondaryDisplaysShowing;
             if (notifyDefaultDisplayCallbacks) {
                 notifyDefaultDisplayCallbacks(showing);
             }
-            updateActivityLockScreenState(showing, aodShowing, secondaryDisplaysShowing);
+            updateActivityLockScreenState(showing, aodShowing);
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
index cef1b6b..3140e6d 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
@@ -37,6 +37,7 @@
 import android.util.Log;
 import android.util.Size;
 import android.view.IPinnedStackController;
+import android.view.InputEvent;
 import android.view.MotionEvent;
 import android.view.ViewConfiguration;
 import android.view.accessibility.AccessibilityEvent;
@@ -206,7 +207,7 @@
         mEnableDimissDragToEdge = res.getBoolean(R.bool.config_pipEnableDismissDragToEdge);
 
         // Register the listener for input consumer touch events
-        inputConsumerController.setTouchListener(this::handleTouchEvent);
+        inputConsumerController.setInputListener(this::handleTouchEvent);
         inputConsumerController.setRegistrationListener(this::onRegistrationChanged);
         onRegistrationChanged(inputConsumerController.isRegistered());
     }
@@ -370,11 +371,16 @@
                 mMovementBounds, true /* allowMenuTimeout */, willResizeMenu());
     }
 
-    private boolean handleTouchEvent(MotionEvent ev) {
+    private boolean handleTouchEvent(InputEvent inputEvent) {
+        // Skip any non motion events
+        if (!(inputEvent instanceof MotionEvent)) {
+            return true;
+        }
         // Skip touch handling until we are bound to the controller
         if (mPinnedStackController == null) {
             return true;
         }
+        MotionEvent ev = (MotionEvent) inputEvent;
 
         // Update the touch state
         mTouchState.onTouchEvent(ev);
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt b/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt
index 75b8a05..84a3446 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt
@@ -42,14 +42,10 @@
 
     private val iconSize = context.resources.getDimensionPixelSize(
             R.dimen.ongoing_appops_dialog_icon_size)
-    private val plusSize = context.resources.getDimensionPixelSize(
-            R.dimen.ongoing_appops_dialog_app_plus_size)
     private val iconColor = context.resources.getColor(
             com.android.internal.R.color.text_color_primary, context.theme)
-    private val plusColor: Int
     private val iconMargin = context.resources.getDimensionPixelSize(
             R.dimen.ongoing_appops_dialog_icon_margin)
-    private val MAX_ITEMS = context.resources.getInteger(R.integer.ongoing_appops_dialog_max_apps)
     private val iconFactory = IconDrawableFactory.newInstance(context, true)
     private var dismissDialog: (() -> Unit)? = null
     private val appsAndTypes = dialogBuilder.appsAndTypes
@@ -57,13 +53,6 @@
             { it.second.min() },
             { it.first }))
 
-    init {
-        val a = context.theme.obtainStyledAttributes(
-                intArrayOf(com.android.internal.R.attr.colorAccent))
-        plusColor = a.getColor(0, 0)
-        a.recycle()
-    }
-
     fun createDialog(): Dialog {
         val builder = AlertDialog.Builder(context).apply {
             setPositiveButton(R.string.ongoing_privacy_dialog_ok, null)
@@ -96,33 +85,9 @@
 
         val numItems = appsAndTypes.size
         for (i in 0..(numItems - 1)) {
-            if (i >= MAX_ITEMS) break
             val item = appsAndTypes[i]
             addAppItem(appsList, item.first, item.second, dialogBuilder.types.size > 1)
         }
-
-        if (numItems > MAX_ITEMS) {
-            val overflow = contentView.findViewById(R.id.overflow) as LinearLayout
-            overflow.visibility = View.VISIBLE
-            val overflowText = overflow.findViewById(R.id.app_name) as TextView
-            overflowText.text = context.resources.getQuantityString(
-                    R.plurals.ongoing_privacy_dialog_overflow_text,
-                    numItems - MAX_ITEMS,
-                    numItems - MAX_ITEMS
-            )
-            val overflowPlus = overflow.findViewById(R.id.app_icon) as ImageView
-            val lp = overflowPlus.layoutParams.apply {
-                height = plusSize
-                width = plusSize
-            }
-            overflowPlus.layoutParams = lp
-            overflowPlus.apply {
-                val plus = context.getDrawable(R.drawable.plus)
-                imageTintList = ColorStateList.valueOf(plusColor)
-                setImageDrawable(plus)
-            }
-        }
-
         return contentView
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItem.kt b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItem.kt
index a6e48f8..3f581c4d 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItem.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItem.kt
@@ -18,6 +18,8 @@
 import android.content.pm.ApplicationInfo
 import android.content.pm.PackageManager
 import android.graphics.drawable.Drawable
+import android.os.UserHandle
+import android.util.IconDrawableFactory
 import com.android.systemui.R
 
 typealias Privacy = PrivacyType
@@ -46,14 +48,21 @@
 
     private val applicationInfo: ApplicationInfo? by lazy {
         try {
-            context.packageManager.getApplicationInfo(packageName, 0)
+            val userHandle = UserHandle.getUserHandleForUid(uid)
+            context.createPackageContextAsUser(packageName, 0, userHandle).getPackageManager()
+                    .getApplicationInfo(packageName, 0)
         } catch (_: PackageManager.NameNotFoundException) {
             null
         }
     }
     val icon: Drawable by lazy {
         applicationInfo?.let {
-            context.packageManager.getApplicationIcon(it)
+            try {
+                val iconFactory = IconDrawableFactory.newInstance(context, true)
+                iconFactory.getBadgedIcon(it, UserHandle.getUserId(uid))
+            } catch (_: Exception) {
+                null
+            }
         } ?: context.getDrawable(android.R.drawable.sym_def_app_icon)
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java b/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
index f91c9d9..bbd8de3 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
@@ -521,16 +521,7 @@
                     }
                 }
             } else {
-                // If there are sims ready but there are not the same number of carrier names as
-                // subscription ids, just show the full text in the first slot
-                mInfos[0].visible = true;
-                mCarrierTexts[0].setText(info.carrierText);
-                mCarrierGroups[0].setVisibility(View.VISIBLE);
-                for (int i = 1; i < SIM_SLOTS; i++) {
-                    mInfos[i].visible = false;
-                    mCarrierTexts[i].setText("");
-                    mCarrierGroups[i].setVisibility(View.GONE);
-                }
+                Log.e(TAG, "Carrier information arrays not of same length");
             }
         } else {
             mInfos[0].visible = false;
@@ -612,8 +603,10 @@
             // Only show marquee when visible
             if (visibility == VISIBLE) {
                 setEllipsize(TextUtils.TruncateAt.MARQUEE);
+                setSelected(true);
             } else {
                 setEllipsize(TextUtils.TruncateAt.END);
+                setSelected(false);
             }
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java b/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
index 64ad95c..c209b31 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
@@ -38,7 +38,6 @@
 
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto;
-import com.android.settingslib.Utils;
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
 import com.android.systemui.plugins.qs.QS;
@@ -103,10 +102,6 @@
         mToolbar.getMenu().add(Menu.NONE, MENU_RESET, 0,
                 mContext.getString(com.android.internal.R.string.reset));
         mToolbar.setTitle(R.string.qs_edit);
-        int accentColor = Utils.getColorAttrDefaultColor(context, android.R.attr.colorAccent);
-        mToolbar.setTitleTextColor(accentColor);
-        mToolbar.getNavigationIcon().setTint(accentColor);
-        mToolbar.getOverflowIcon().setTint(accentColor);
         mRecyclerView = findViewById(android.R.id.list);
         mTransparentView = findViewById(R.id.customizer_transparent_view);
         mTileAdapter = new TileAdapter(getContext());
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java b/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
index a29e93a..608f646 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
@@ -19,9 +19,8 @@
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.DialogInterface;
-import android.content.res.TypedArray;
 import android.graphics.Canvas;
-import android.graphics.drawable.ColorDrawable;
+import android.graphics.drawable.Drawable;
 import android.os.Handler;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -505,13 +504,10 @@
     };
 
     private class TileItemDecoration extends ItemDecoration {
-        private final ColorDrawable mDrawable;
+        private final Drawable mDrawable;
 
         private TileItemDecoration(Context context) {
-            TypedArray ta =
-                    context.obtainStyledAttributes(new int[]{android.R.attr.colorSecondary});
-            mDrawable = new ColorDrawable(ta.getColor(0, 0));
-            ta.recycle();
+            mDrawable = context.getDrawable(R.drawable.qs_customize_tile_decoration);
         }
 
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/BatterySaverTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/BatterySaverTile.java
index 7f76900..c664a20 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/BatterySaverTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/BatterySaverTile.java
@@ -15,14 +15,11 @@
  */
 package com.android.systemui.qs.tiles;
 
-import android.content.Context;
 import android.content.Intent;
-import android.graphics.drawable.Drawable;
 import android.service.quicksettings.Tile;
 import android.widget.Switch;
 
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.settingslib.graph.BatteryMeterDrawableBase;
 import com.android.systemui.R;
 import com.android.systemui.plugins.qs.QSTile.BooleanState;
 import com.android.systemui.qs.QSHost;
@@ -41,6 +38,8 @@
     private boolean mCharging;
     private boolean mPluggedIn;
 
+    private Icon mIcon = ResourceIcon.get(com.android.internal.R.drawable.ic_qs_battery_saver);
+
     @Inject
     public BatterySaverTile(QSHost host, BatteryController batteryController) {
         super(host);
@@ -84,9 +83,7 @@
     protected void handleUpdateState(BooleanState state, Object arg) {
         state.state = mPluggedIn ? Tile.STATE_UNAVAILABLE
                 : mPowerSave ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE;
-        BatterySaverIcon bsi = new BatterySaverIcon();
-        bsi.mState = state.state;
-        state.icon = bsi;
+        state.icon = mIcon;
         state.label = mContext.getString(R.string.battery_detail_switch_title);
         state.contentDescription = state.label;
         state.value = mPowerSave;
@@ -106,48 +103,4 @@
         mPowerSave = isPowerSave;
         refreshState(null);
     }
-
-    public static class BatterySaverIcon extends Icon {
-        private int mState;
-
-        @Override
-        public Drawable getDrawable(Context context) {
-            BatterySaverDrawable b =
-                    new BatterySaverDrawable(context, QSTileImpl.getColorForState(context, mState));
-            b.mState = mState;
-            final int pad = context.getResources()
-                    .getDimensionPixelSize(R.dimen.qs_tile_divider_height);
-            b.setPadding(pad, pad, pad, pad);
-            return b;
-        }
-    }
-
-    private static class BatterySaverDrawable extends BatteryMeterDrawableBase {
-        private int mState;
-        private static final int MAX_BATTERY = 100;
-
-        BatterySaverDrawable(Context context, int frameColor) {
-            super(context, frameColor);
-            // Show as full so it's always uniform color
-            super.setBatteryLevel(MAX_BATTERY);
-            setPowerSave(true);
-            setCharging(false);
-            setPowerSaveAsColorError(false);
-            mPowerSaveAsColorError = true;
-            mFramePaint.setColor(0);
-            mPowersavePaint.setColor(frameColor);
-            mFramePaint.setStrokeWidth(mPowersavePaint.getStrokeWidth());
-            mPlusPaint.setColor(frameColor);
-        }
-
-        @Override
-        protected int batteryColorForLevel(int level) {
-            return 0;
-        }
-
-        @Override
-        public void setBatteryLevel(int val) {
-            // Don't change the actual level, otherwise this won't draw correctly
-        }
-    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java
index f05ac4c..0b1e9c3 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java
@@ -21,6 +21,7 @@
 import android.app.Dialog;
 import android.content.Context;
 import android.content.Intent;
+import android.media.projection.MediaProjectionInfo;
 import android.provider.Settings;
 import android.service.quicksettings.Tile;
 import android.util.Log;
@@ -125,7 +126,30 @@
             });
             return;
         }
-        showDetail(true);
+
+        CastDevice activeProjection = getActiveDeviceMediaProjection();
+        if (activeProjection == null) {
+            showDetail(true);
+        } else {
+            mController.stopCasting(activeProjection);
+        }
+    }
+
+    private CastDevice getActiveDeviceMediaProjection() {
+        CastDevice activeDevice = null;
+        for (CastDevice device : mController.getCastDevices()) {
+            if (device.state == CastDevice.STATE_CONNECTED
+                    || device.state == CastDevice.STATE_CONNECTING) {
+                activeDevice = device;
+                break;
+            }
+        }
+
+        if (activeDevice != null && activeDevice.tag instanceof MediaProjectionInfo) {
+            return activeDevice;
+        }
+
+        return null;
     }
 
     @Override
@@ -161,21 +185,23 @@
         for (CastDevice device : devices) {
             if (device.state == CastDevice.STATE_CONNECTED) {
                 state.value = true;
-                state.label = getDeviceName(device);
+                state.secondaryLabel = getDeviceName(device);
                 state.contentDescription = state.contentDescription + "," +
                         mContext.getString(R.string.accessibility_cast_name, state.label);
             } else if (device.state == CastDevice.STATE_CONNECTING) {
                 connecting = true;
             }
         }
-        if (!state.value && connecting) {
-            state.label = mContext.getString(R.string.quick_settings_connecting);
+        if (connecting && !state.value) {
+            state.secondaryLabel = mContext.getString(R.string.quick_settings_connecting);
         }
         state.icon = ResourceIcon.get(state.value ? R.drawable.ic_qs_cast_on
                 : R.drawable.ic_qs_cast_off);
-        if (mWifiConnected) {
+        if (mWifiConnected || state.value) {
             state.state = state.value ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE;
-            state.secondaryLabel = "";
+            if (!state.value) {
+                state.secondaryLabel = "";
+            }
             state.contentDescription = state.contentDescription + ","
                     + mContext.getString(R.string.accessibility_quick_settings_open_details);
             state.expandedAccessibilityClassName = Button.class.getName();
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java
index e1becdb..c587a39 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java
@@ -25,7 +25,11 @@
 import android.content.res.Resources;
 import android.provider.Settings;
 import android.service.quicksettings.Tile;
+import android.text.SpannableString;
+import android.text.SpannableStringBuilder;
+import android.text.Spanned;
 import android.text.TextUtils;
+import android.text.style.TextAppearanceSpan;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
@@ -188,7 +192,8 @@
             state.secondaryLabel = r.getString(R.string.status_bar_airplane);
         } else if (mobileDataEnabled) {
             state.state = Tile.STATE_ACTIVE;
-            state.secondaryLabel = getMobileDataSubscriptionName(cb);
+            state.secondaryLabel = appendMobileDataType(getMobileDataSubscriptionName(cb),
+                    cb.dataContentDescription);
         } else {
             state.state = Tile.STATE_INACTIVE;
             state.secondaryLabel = r.getString(R.string.cell_data_off);
@@ -207,6 +212,18 @@
         state.contentDescription = state.label + ", " + contentDescriptionSuffix;
     }
 
+    private CharSequence appendMobileDataType(CharSequence current, CharSequence dataType) {
+        if (TextUtils.isEmpty(dataType)) {
+            return current;
+        }
+        SpannableString type = new SpannableString(dataType);
+        SpannableStringBuilder builder = new SpannableStringBuilder(current);
+        builder.append(" ");
+        builder.append(type, new TextAppearanceSpan(mContext, R.style.TextAppearance_RATBadge),
+                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+        return builder;
+    }
+
     private CharSequence getMobileDataSubscriptionName(CallbackInfo cb) {
         if (cb.roaming && !TextUtils.isEmpty(cb.dataSubscriptionName)) {
             String roaming = mContext.getString(R.string.data_connection_roaming);
@@ -232,6 +249,7 @@
     private static final class CallbackInfo {
         boolean airplaneModeEnabled;
         CharSequence dataSubscriptionName;
+        CharSequence dataContentDescription;
         boolean activityIn;
         boolean activityOut;
         boolean noSim;
@@ -250,6 +268,7 @@
                 return;
             }
             mInfo.dataSubscriptionName = mController.getMobileDataNetworkName();
+            mInfo.dataContentDescription = (description != null) ? typeContentDescription : null;
             mInfo.activityIn = activityIn;
             mInfo.activityOut = activityOut;
             mInfo.roaming = roaming;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/WifiTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/WifiTile.java
index 52a8814..3e40cfc 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/WifiTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/WifiTile.java
@@ -22,6 +22,7 @@
 import android.content.res.Resources;
 import android.provider.Settings;
 import android.service.quicksettings.Tile;
+import android.text.TextUtils;
 import android.util.Log;
 import android.view.View;
 import android.view.ViewGroup;
@@ -208,6 +209,9 @@
             if (wifiConnected) {
                 minimalContentDescription.append(cb.wifiSignalContentDescription).append(",");
                 minimalContentDescription.append(removeDoubleQuotes(cb.ssid));
+                if (!TextUtils.isEmpty(state.secondaryLabel)) {
+                    minimalContentDescription.append(",").append(state.secondaryLabel);
+                }
             }
         }
         state.contentDescription = minimalContentDescription.toString();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationMediaManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationMediaManager.java
index 490317b..fa22367 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationMediaManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationMediaManager.java
@@ -38,10 +38,12 @@
 import android.os.Handler;
 import android.os.Trace;
 import android.os.UserHandle;
+import android.provider.DeviceConfig;
 import android.util.Log;
 import android.view.View;
 import android.widget.ImageView;
 
+import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
 import com.android.internal.statusbar.NotificationVisibility;
 import com.android.systemui.Dependency;
 import com.android.systemui.Dumpable;
@@ -115,6 +117,20 @@
     private ImageView mBackdropFront;
     private ImageView mBackdropBack;
 
+    private boolean mShowCompactMediaSeekbar;
+    private final DeviceConfig.OnPropertyChangedListener mPropertyChangedListener =
+            new DeviceConfig.OnPropertyChangedListener() {
+        @Override
+        public void onPropertyChanged(String namespace, String name, String value) {
+            if (SystemUiDeviceConfigFlags.COMPACT_MEDIA_SEEKBAR_ENABLED.equals(name)) {
+                if (DEBUG_MEDIA) {
+                    Log.v(TAG, "DEBUG_MEDIA: compact media seekbar flag updated: " + value);
+                }
+                mShowCompactMediaSeekbar = "true".equals(value);
+            }
+        }
+    };
+
     private final MediaController.Callback mMediaListener = new MediaController.Callback() {
         @Override
         public void onPlaybackStateChanged(PlaybackState state) {
@@ -168,6 +184,14 @@
                 onNotificationRemoved(entry.key);
             }
         });
+
+        mShowCompactMediaSeekbar = "true".equals(
+                DeviceConfig.getProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
+                    SystemUiDeviceConfigFlags.COMPACT_MEDIA_SEEKBAR_ENABLED));
+
+        DeviceConfig.addOnPropertyChangedListener(DeviceConfig.NAMESPACE_SYSTEMUI,
+                mContext.getMainExecutor(),
+                mPropertyChangedListener);
     }
 
     public void setUpWithPresenter(NotificationPresenter presenter) {
@@ -189,6 +213,10 @@
         return mMediaMetadata;
     }
 
+    public boolean getShowCompactMediaSeekbar() {
+        return mShowCompactMediaSeekbar;
+    }
+
     public Icon getMediaIcon() {
         if (mMediaNotificationKey == null) {
             return null;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationPresenter.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationPresenter.java
index c945afd..f34b912 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationPresenter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationPresenter.java
@@ -15,7 +15,6 @@
  */
 package com.android.systemui.statusbar;
 
-import com.android.systemui.statusbar.notification.NotificationRowBinder;
 import com.android.systemui.statusbar.notification.row.ActivatableNotificationView;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 
@@ -27,8 +26,7 @@
  * want to perform some action before doing so).
  */
 public interface NotificationPresenter extends ExpandableNotificationRow.OnExpandClickListener,
-        ActivatableNotificationView.OnActivatedListener,
-        NotificationRowBinder.BindRowCallback {
+        ActivatableNotificationView.OnActivatedListener {
     /**
      * Returns true if the presenter is not visible. For example, it may not be necessary to do
      * animations if this returns true.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
index 3fbc641..4ed9ae4 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
@@ -35,6 +35,7 @@
 import com.android.systemui.statusbar.notification.collection.NotificationData;
 import com.android.systemui.statusbar.notification.collection.NotificationData.KeyguardEnvironment;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationRowBinder;
 import com.android.systemui.statusbar.notification.logging.NotificationLogger;
 import com.android.systemui.statusbar.notification.row.NotificationContentInflater;
 import com.android.systemui.statusbar.notification.row.NotificationContentInflater.InflationFlag;
@@ -124,16 +125,7 @@
         return mRemoteInputManager;
     }
 
-    private NotificationRowBinder getRowBinder() {
-        if (mNotificationRowBinder == null) {
-            mNotificationRowBinder = Dependency.get(NotificationRowBinder.class);
-        }
-        return mNotificationRowBinder;
-    }
-
-    // TODO: Remove this once we can always use a mocked row binder in our tests
-    @VisibleForTesting
-    void setRowBinder(NotificationRowBinder notificationRowBinder) {
+    public void setRowBinder(NotificationRowBinder notificationRowBinder) {
         mNotificationRowBinder = notificationRowBinder;
     }
 
@@ -345,7 +337,7 @@
 
         Dependency.get(LeakDetector.class).trackInstance(entry);
         // Construct the expanded view.
-        getRowBinder().inflateViews(entry, () -> performRemoveNotification(notification));
+        requireBinder().inflateViews(entry, () -> performRemoveNotification(notification));
 
         abortExistingInflation(key);
 
@@ -386,7 +378,7 @@
             listener.onPreEntryUpdated(entry);
         }
 
-        getRowBinder().inflateViews(entry, () -> performRemoveNotification(notification));
+        requireBinder().inflateViews(entry, () -> performRemoveNotification(notification));
         updateNotifications();
 
         if (DEBUG) {
@@ -440,7 +432,7 @@
 
         // By comparing the old and new UI adjustments, reinflate the view accordingly.
         for (NotificationEntry entry : entries) {
-            getRowBinder().onNotificationRankingUpdated(
+            requireBinder().onNotificationRankingUpdated(
                     entry,
                     oldImportances.get(entry.key),
                     oldAdjustments.get(entry.key),
@@ -486,4 +478,12 @@
             activeExtender.setShouldManageLifetime(entry, false);
         }
     }
+
+    private NotificationRowBinder requireBinder() {
+        if (mNotificationRowBinder == null) {
+            throw new RuntimeException("You must initialize NotificationEntryManager by calling"
+                    + "setRowBinder() before using.");
+        }
+        return mNotificationRowBinder;
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinder.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinder.java
new file mode 100644
index 0000000..7504e86
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinder.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.notification.collection;
+
+import android.annotation.Nullable;
+
+import com.android.systemui.statusbar.NotificationUiAdjustment;
+import com.android.systemui.statusbar.notification.InflationException;
+import com.android.systemui.statusbar.notification.NotificationEntryManager;
+
+/**
+ * Used by the {@link NotificationEntryManager}. When notifications are added or updated, the binder
+ * is asked to (re)inflate and prepare their views. This inflation must occur off the main thread.
+ */
+public interface NotificationRowBinder {
+    /**
+     * Called when a notification has been added or updated. The binder must asynchronously inflate
+     * and bind the views associated with the notification.
+     *
+     * TODO: The caller is notified when the inflation completes, but this is currently a very
+     * roundabout business. Add an explicit completion/failure callback to this method.
+     */
+    void inflateViews(
+            NotificationEntry entry,
+            Runnable onDismissRunnable)
+            throws InflationException;
+
+    /**
+     * Called when the ranking has been updated (but not add or remove has been done). The binder
+     * should inspect the old and new adjustments and re-inflate the entry's views if necessary
+     * (e.g. if something important changed).
+     */
+    void onNotificationRankingUpdated(
+            NotificationEntry entry,
+            @Nullable Integer oldImportance,
+            NotificationUiAdjustment oldAdjustment,
+            NotificationUiAdjustment newAdjustment);
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationRowBinder.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinderImpl.java
similarity index 94%
rename from packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationRowBinder.java
rename to packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinderImpl.java
index 6f5baf9..b91cdaf 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationRowBinder.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinderImpl.java
@@ -14,10 +14,9 @@
  * limitations under the License.
  */
 
-package com.android.systemui.statusbar.notification;
+package com.android.systemui.statusbar.notification.collection;
 
 import static com.android.internal.util.Preconditions.checkNotNull;
-import static com.android.systemui.Dependency.ALLOW_NOTIFICATION_LONG_PRESS_NAME;
 import static com.android.systemui.statusbar.NotificationRemoteInputManager.ENABLE_REMOTE_INPUT;
 import static com.android.systemui.statusbar.notification.row.NotificationContentInflater.FLAG_CONTENT_VIEW_AMBIENT;
 import static com.android.systemui.statusbar.notification.row.NotificationContentInflater.FLAG_CONTENT_VIEW_HEADS_UP;
@@ -39,7 +38,9 @@
 import com.android.systemui.statusbar.NotificationPresenter;
 import com.android.systemui.statusbar.NotificationRemoteInputManager;
 import com.android.systemui.statusbar.NotificationUiAdjustment;
-import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.InflationException;
+import com.android.systemui.statusbar.notification.NotificationClicker;
+import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
 import com.android.systemui.statusbar.notification.logging.NotificationLogger;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.row.NotificationContentInflater;
@@ -50,13 +51,8 @@
 import com.android.systemui.statusbar.phone.StatusBar;
 import com.android.systemui.statusbar.policy.HeadsUpManager;
 
-import javax.inject.Inject;
-import javax.inject.Named;
-import javax.inject.Singleton;
-
 /** Handles inflating and updating views for notifications. */
-@Singleton
-public class NotificationRowBinder {
+public class NotificationRowBinderImpl implements NotificationRowBinder {
 
     private static final String TAG = "NotificationViewManager";
 
@@ -84,9 +80,7 @@
     private NotificationClicker mNotificationClicker;
     private final NotificationLogger mNotificationLogger = Dependency.get(NotificationLogger.class);
 
-    @Inject
-    public NotificationRowBinder(Context context,
-            @Named(ALLOW_NOTIFICATION_LONG_PRESS_NAME) boolean allowLongPress) {
+    public NotificationRowBinderImpl(Context context, boolean allowLongPress) {
         mContext = context;
         mMessagingUtil = new NotificationMessagingUtil(context);
         mAllowLongPress = allowLongPress;
@@ -122,6 +116,7 @@
     /**
      * Inflates the views for the given entry (possibly asynchronously).
      */
+    @Override
     public void inflateViews(
             NotificationEntry entry,
             Runnable onDismissRunnable)
@@ -192,6 +187,7 @@
      * Updates the views bound to an entry when the entry's ranking changes, either in-place or by
      * reinflating them.
      */
+    @Override
     public void onNotificationRankingUpdated(
             NotificationEntry entry,
             @Nullable Integer oldImportance,
@@ -264,7 +260,7 @@
     }
 
     private void logNotificationExpansion(String key, boolean userAction, boolean expanded) {
-         mNotificationLogger.onExpansionChanged(key, userAction, expanded);
+        mNotificationLogger.onExpansionChanged(key, userAction, expanded);
     }
 
     /** Callback for when a row is bound to an entry. */
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
index 2b643d0..0fbc55b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
@@ -81,6 +81,7 @@
 import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
 import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin.MenuItem;
 import com.android.systemui.shared.plugins.PluginManager;
+import com.android.systemui.statusbar.NotificationMediaManager;
 import com.android.systemui.statusbar.RemoteInputController;
 import com.android.systemui.statusbar.StatusBarIconView;
 import com.android.systemui.statusbar.notification.AboveShelfChangedListener;
@@ -90,7 +91,6 @@
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.logging.NotificationCounters;
 import com.android.systemui.statusbar.notification.row.NotificationContentInflater.InflationFlag;
-import com.android.systemui.statusbar.notification.row.wrapper.NotificationMediaTemplateViewWrapper;
 import com.android.systemui.statusbar.notification.row.wrapper.NotificationViewWrapper;
 import com.android.systemui.statusbar.notification.stack.AmbientState;
 import com.android.systemui.statusbar.notification.stack.AnimationProperties;
@@ -331,6 +331,7 @@
     private boolean mWasChildInGroupWhenRemoved;
     private int mNotificationColorAmbient;
     private NotificationInlineImageResolver mImageResolver;
+    private NotificationMediaManager mMediaManager;
 
     private SystemNotificationAsyncTask mSystemNotificationAsyncTask =
             new SystemNotificationAsyncTask();
@@ -658,10 +659,11 @@
         View expandedView = layout.getExpandedChild();
         boolean isMediaLayout = expandedView != null
                 && expandedView.findViewById(com.android.internal.R.id.media_actions) != null;
+        boolean showCompactMediaSeekbar = mMediaManager.getShowCompactMediaSeekbar();
 
         if (customView && beforeP && !mIsSummaryWithChildren) {
             minHeight = beforeN ? mNotificationMinHeightBeforeN : mNotificationMinHeightBeforeP;
-        } else if (isMediaLayout && !NotificationMediaTemplateViewWrapper.HIDE_COMPACT_SCRUBBER) {
+        } else if (isMediaLayout && showCompactMediaSeekbar) {
             minHeight = mNotificationMinHeightMedia;
         } else if (mUseIncreasedCollapsedHeight && layout == mPrivateLayout) {
             minHeight = mNotificationMinHeightLarge;
@@ -1635,6 +1637,7 @@
         mMenuRow = new NotificationMenuRow(mContext);
         mImageResolver = new NotificationInlineImageResolver(context,
                 new NotificationInlineImageCache());
+        mMediaManager = Dependency.get(NotificationMediaManager.class);
         initDimens();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentInflater.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentInflater.java
index b65c4a5..b4dd114 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentInflater.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentInflater.java
@@ -34,12 +34,17 @@
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.widget.ImageMessageConsumer;
+import com.android.systemui.Dependency;
 import com.android.systemui.statusbar.InflationTask;
+import com.android.systemui.statusbar.SmartReplyController;
 import com.android.systemui.statusbar.notification.InflationException;
 import com.android.systemui.statusbar.notification.MediaNotificationProcessor;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.row.wrapper.NotificationViewWrapper;
 import com.android.systemui.statusbar.phone.StatusBar;
+import com.android.systemui.statusbar.policy.HeadsUpManager;
+import com.android.systemui.statusbar.policy.InflatedSmartReplies;
+import com.android.systemui.statusbar.policy.SmartReplyConstants;
 import com.android.systemui.util.Assert;
 
 import java.lang.annotation.Retention;
@@ -278,6 +283,8 @@
         InflationProgress result = createRemoteViews(reInflateFlags, builder, mIsLowPriority,
                 mIsChildInGroup, mUsesIncreasedHeight, mUsesIncreasedHeadsUpHeight,
                 mRedactAmbient, packageContext);
+        result = inflateSmartReplyViews(result, reInflateFlags, mRow.getEntry(),
+                mRow.getContext(), mRow.getHeadsUpManager());
         apply(
                 inflateSynchronously,
                 result,
@@ -306,6 +313,7 @@
                 if (mRow.getPrivateLayout().isContentViewInactive(VISIBLE_TYPE_HEADSUP)) {
                     mRow.getPrivateLayout().setHeadsUpChild(null);
                     mCachedContentViews.remove(FLAG_CONTENT_VIEW_HEADS_UP);
+                    mRow.getPrivateLayout().setHeadsUpInflatedSmartReplies(null);
                 }
                 break;
             case FLAG_CONTENT_VIEW_AMBIENT:
@@ -336,12 +344,33 @@
         }
     }
 
+    private static InflationProgress inflateSmartReplyViews(InflationProgress result,
+            @InflationFlag int reInflateFlags, NotificationEntry entry, Context context,
+            HeadsUpManager headsUpManager) {
+        SmartReplyConstants smartReplyConstants = Dependency.get(SmartReplyConstants.class);
+        SmartReplyController smartReplyController = Dependency.get(SmartReplyController.class);
+        if ((reInflateFlags & FLAG_CONTENT_VIEW_EXPANDED) != 0 && result.newExpandedView != null) {
+            result.expandedInflatedSmartReplies =
+                    InflatedSmartReplies.inflate(
+                            context, entry, smartReplyConstants, smartReplyController,
+                            headsUpManager);
+        }
+        if ((reInflateFlags & FLAG_CONTENT_VIEW_HEADS_UP) != 0 && result.newHeadsUpView != null) {
+            result.headsUpInflatedSmartReplies =
+                    InflatedSmartReplies.inflate(
+                            context, entry, smartReplyConstants, smartReplyController,
+                            headsUpManager);
+        }
+        return result;
+    }
+
     private static InflationProgress createRemoteViews(@InflationFlag int reInflateFlags,
             Notification.Builder builder, boolean isLowPriority, boolean isChildInGroup,
             boolean usesIncreasedHeight, boolean usesIncreasedHeadsUpHeight, boolean redactAmbient,
             Context packageContext) {
         InflationProgress result = new InflationProgress();
         isLowPriority = isLowPriority && !isChildInGroup;
+
         if ((reInflateFlags & FLAG_CONTENT_VIEW_CONTRACTED) != 0) {
             result.newContentView = createContentView(builder, isLowPriority, usesIncreasedHeight);
         }
@@ -661,6 +690,12 @@
                 } else if (result.newExpandedView == null) {
                     privateLayout.setExpandedChild(null);
                 }
+                if (result.newExpandedView != null) {
+                    privateLayout.setExpandedInflatedSmartReplies(
+                            result.expandedInflatedSmartReplies);
+                } else {
+                    privateLayout.setExpandedInflatedSmartReplies(null);
+                }
                 cachedContentViews.put(FLAG_CONTENT_VIEW_EXPANDED, result.newExpandedView);
                 row.setExpandable(result.newExpandedView != null);
             }
@@ -671,6 +706,12 @@
                 } else if (result.newHeadsUpView == null) {
                     privateLayout.setHeadsUpChild(null);
                 }
+                if (result.newHeadsUpView != null) {
+                    privateLayout.setHeadsUpInflatedSmartReplies(
+                            result.headsUpInflatedSmartReplies);
+                } else {
+                    privateLayout.setHeadsUpInflatedSmartReplies(null);
+                }
                 cachedContentViews.put(FLAG_CONTENT_VIEW_HEADS_UP, result.newHeadsUpView);
             }
 
@@ -846,9 +887,12 @@
                             packageContext);
                     processor.processNotification(notification, recoveredBuilder);
                 }
-                return createRemoteViews(mReInflateFlags, recoveredBuilder, mIsLowPriority,
+                InflationProgress inflationProgress = createRemoteViews(mReInflateFlags,
+                        recoveredBuilder, mIsLowPriority,
                         mIsChildInGroup, mUsesIncreasedHeight, mUsesIncreasedHeadsUpHeight,
                         mRedactAmbient, packageContext);
+                return inflateSmartReplyViews(inflationProgress, mReInflateFlags, mRow.getEntry(),
+                        mRow.getContext(), mRow.getHeadsUpManager());
             } catch (Exception e) {
                 mError = e;
                 return null;
@@ -927,6 +971,9 @@
         private View inflatedPublicView;
         private CharSequence headsUpStatusBarText;
         private CharSequence headsUpStatusBarTextPublic;
+
+        private InflatedSmartReplies expandedInflatedSmartReplies;
+        private InflatedSmartReplies headsUpInflatedSmartReplies;
     }
 
     @VisibleForTesting
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
index 1dc48d4..646617c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
@@ -19,7 +19,6 @@
 import android.annotation.Nullable;
 import android.app.Notification;
 import android.app.PendingIntent;
-import android.app.RemoteInput;
 import android.content.Context;
 import android.graphics.Rect;
 import android.os.Build;
@@ -28,7 +27,6 @@
 import android.util.ArraySet;
 import android.util.AttributeSet;
 import android.util.Log;
-import android.util.Pair;
 import android.view.MotionEvent;
 import android.view.NotificationHeaderView;
 import android.view.View;
@@ -39,7 +37,6 @@
 import android.widget.LinearLayout;
 
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.ContrastColorUtil;
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
@@ -52,13 +49,14 @@
 import com.android.systemui.statusbar.notification.row.wrapper.NotificationCustomViewWrapper;
 import com.android.systemui.statusbar.notification.row.wrapper.NotificationViewWrapper;
 import com.android.systemui.statusbar.phone.NotificationGroupManager;
+import com.android.systemui.statusbar.policy.InflatedSmartReplies;
+import com.android.systemui.statusbar.policy.InflatedSmartReplies.SmartRepliesAndActions;
 import com.android.systemui.statusbar.policy.RemoteInputView;
 import com.android.systemui.statusbar.policy.SmartReplyConstants;
 import com.android.systemui.statusbar.policy.SmartReplyView;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
-import java.util.List;
 
 /**
  * A frame layout containing the actual payload of the notification, including the contracted,
@@ -95,6 +93,8 @@
     private SmartReplyView mExpandedSmartReplyView;
     private SmartReplyView mHeadsUpSmartReplyView;
     private SmartReplyController mSmartReplyController;
+    private InflatedSmartReplies mExpandedInflatedSmartReplies;
+    private InflatedSmartReplies mHeadsUpInflatedSmartReplies;
 
     private NotificationViewWrapper mContractedWrapper;
     private NotificationViewWrapper mExpandedWrapper;
@@ -1318,8 +1318,22 @@
             return;
         }
 
-        SmartRepliesAndActions smartRepliesAndActions =
-                chooseSmartRepliesAndActions(mSmartReplyConstants, entry);
+        applyRemoteInput(entry, InflatedSmartReplies.hasFreeformRemoteInput(entry));
+
+        if (mExpandedInflatedSmartReplies == null && mHeadsUpInflatedSmartReplies == null) {
+            if (DEBUG) {
+                Log.d(TAG, "Both expanded, and heads-up InflatedSmartReplies are null, "
+                        + "don't add smart replies.");
+            }
+            return;
+        }
+        // The inflated smart-reply objects for the expanded view and the heads-up view both contain
+        // the same SmartRepliesAndActions to avoid discrepancies between the two views. We here
+        // reuse that object for our local SmartRepliesAndActions to avoid discrepancies between
+        // this class and the InflatedSmartReplies classes.
+        SmartRepliesAndActions smartRepliesAndActions = mExpandedInflatedSmartReplies != null
+                ? mExpandedInflatedSmartReplies.getSmartRepliesAndActions()
+                : mHeadsUpInflatedSmartReplies.getSmartRepliesAndActions();
         if (DEBUG) {
             Log.d(TAG, String.format("Adding suggestions for %s, %d actions, and %d replies.",
                     entry.notification.getKey(),
@@ -1328,86 +1342,9 @@
                     smartRepliesAndActions.smartReplies == null ? 0 :
                             smartRepliesAndActions.smartReplies.choices.length));
         }
-
-        applyRemoteInput(entry, smartRepliesAndActions.hasFreeformRemoteInput);
         applySmartReplyView(smartRepliesAndActions, entry);
     }
 
-    /**
-     * Chose what smart replies and smart actions to display. App generated suggestions take
-     * precedence. So if the app provides any smart replies, we don't show any
-     * replies or actions generated by the NotificationAssistantService (NAS), and if the app
-     * provides any smart actions we also don't show any NAS-generated replies or actions.
-     */
-    @VisibleForTesting
-    static SmartRepliesAndActions chooseSmartRepliesAndActions(
-            SmartReplyConstants smartReplyConstants,
-            final NotificationEntry entry) {
-        Notification notification = entry.notification.getNotification();
-        Pair<RemoteInput, Notification.Action> remoteInputActionPair =
-                notification.findRemoteInputActionPair(false /* freeform */);
-        Pair<RemoteInput, Notification.Action> freeformRemoteInputActionPair =
-                notification.findRemoteInputActionPair(true /* freeform */);
-
-        if (!smartReplyConstants.isEnabled()) {
-            if (DEBUG) {
-                Log.d(TAG, "Smart suggestions not enabled, not adding suggestions for "
-                        + entry.notification.getKey());
-            }
-            return new SmartRepliesAndActions(null, null, freeformRemoteInputActionPair != null);
-        }
-        // Only use smart replies from the app if they target P or above. We have this check because
-        // the smart reply API has been used for other things (Wearables) in the past. The API to
-        // add smart actions is new in Q so it doesn't require a target-sdk check.
-        boolean enableAppGeneratedSmartReplies = (!smartReplyConstants.requiresTargetingP()
-                || entry.targetSdk >= Build.VERSION_CODES.P);
-
-        boolean appGeneratedSmartRepliesExist =
-                enableAppGeneratedSmartReplies
-                        && remoteInputActionPair != null
-                        && !ArrayUtils.isEmpty(remoteInputActionPair.first.getChoices())
-                        && remoteInputActionPair.second.actionIntent != null;
-
-        List<Notification.Action> appGeneratedSmartActions = notification.getContextualActions();
-        boolean appGeneratedSmartActionsExist = !appGeneratedSmartActions.isEmpty();
-
-        SmartReplyView.SmartReplies smartReplies = null;
-        SmartReplyView.SmartActions smartActions = null;
-        if (appGeneratedSmartRepliesExist) {
-            smartReplies = new SmartReplyView.SmartReplies(
-                    remoteInputActionPair.first.getChoices(),
-                    remoteInputActionPair.first,
-                    remoteInputActionPair.second.actionIntent,
-                    false /* fromAssistant */);
-        }
-        if (appGeneratedSmartActionsExist) {
-            smartActions = new SmartReplyView.SmartActions(appGeneratedSmartActions,
-                    false /* fromAssistant */);
-        }
-        // Apps didn't provide any smart replies / actions, use those from NAS (if any).
-        if (!appGeneratedSmartRepliesExist && !appGeneratedSmartActionsExist) {
-            boolean useGeneratedReplies = !ArrayUtils.isEmpty(entry.systemGeneratedSmartReplies)
-                    && freeformRemoteInputActionPair != null
-                    && freeformRemoteInputActionPair.second.getAllowGeneratedReplies()
-                    && freeformRemoteInputActionPair.second.actionIntent != null;
-            if (useGeneratedReplies) {
-                smartReplies = new SmartReplyView.SmartReplies(
-                        entry.systemGeneratedSmartReplies,
-                        freeformRemoteInputActionPair.first,
-                        freeformRemoteInputActionPair.second.actionIntent,
-                        true /* fromAssistant */);
-            }
-            boolean useSmartActions = !ArrayUtils.isEmpty(entry.systemGeneratedSmartActions)
-                    && notification.getAllowSystemGeneratedContextualActions();
-            if (useSmartActions) {
-                smartActions = new SmartReplyView.SmartActions(
-                        entry.systemGeneratedSmartActions, true /* fromAssistant */);
-            }
-        }
-        return new SmartRepliesAndActions(
-                smartReplies, smartActions, freeformRemoteInputActionPair != null);
-    }
-
     private void applyRemoteInput(NotificationEntry entry, boolean hasFreeformRemoteInput) {
         View bigContentView = mExpandedChild;
         if (bigContentView != null) {
@@ -1507,11 +1444,12 @@
         return null;
     }
 
-    private void applySmartReplyView(SmartRepliesAndActions smartRepliesAndActions,
+    private void applySmartReplyView(
+            SmartRepliesAndActions smartRepliesAndActions,
             NotificationEntry entry) {
         if (mExpandedChild != null) {
-            mExpandedSmartReplyView =
-                    applySmartReplyView(mExpandedChild, smartRepliesAndActions, entry);
+            mExpandedSmartReplyView = applySmartReplyView(mExpandedChild, smartRepliesAndActions,
+                    entry, mExpandedInflatedSmartReplies);
             if (mExpandedSmartReplyView != null) {
                 if (smartRepliesAndActions.smartReplies != null
                         || smartRepliesAndActions.smartActions != null) {
@@ -1533,65 +1471,79 @@
             }
         }
         if (mHeadsUpChild != null && mSmartReplyConstants.getShowInHeadsUp()) {
-            mHeadsUpSmartReplyView =
-                    applySmartReplyView(mHeadsUpChild, smartRepliesAndActions, entry);
+            mHeadsUpSmartReplyView = applySmartReplyView(mHeadsUpChild, smartRepliesAndActions,
+                    entry, mHeadsUpInflatedSmartReplies);
         }
     }
 
+    @Nullable
     private SmartReplyView applySmartReplyView(View view,
-            SmartRepliesAndActions smartRepliesAndActions, NotificationEntry entry) {
+            SmartRepliesAndActions smartRepliesAndActions,
+            NotificationEntry entry, InflatedSmartReplies inflatedSmartReplyView) {
         View smartReplyContainerCandidate = view.findViewById(
                 com.android.internal.R.id.smart_reply_container);
         if (!(smartReplyContainerCandidate instanceof LinearLayout)) {
             return null;
         }
+
         LinearLayout smartReplyContainer = (LinearLayout) smartReplyContainerCandidate;
-        // If there are no smart replies and no smart actions - early out.
-        if (smartRepliesAndActions.smartReplies == null
-                && smartRepliesAndActions.smartActions == null) {
+        if (!InflatedSmartReplies.shouldShowSmartReplyView(entry, smartRepliesAndActions)) {
             smartReplyContainer.setVisibility(View.GONE);
             return null;
         }
-        // If we are showing the spinner we don't want to add the buttons.
-        boolean showingSpinner = entry.notification.getNotification()
-                .extras.getBoolean(Notification.EXTRA_SHOW_REMOTE_INPUT_SPINNER, false);
-        if (showingSpinner) {
-            smartReplyContainer.setVisibility(View.GONE);
-            return null;
-        }
-        // If we are keeping the notification around while sending we don't want to add the buttons.
-        boolean hideSmartReplies = entry.notification.getNotification()
-                .extras.getBoolean(Notification.EXTRA_HIDE_SMART_REPLIES, false);
-        if (hideSmartReplies) {
-            smartReplyContainer.setVisibility(View.GONE);
-            return null;
-        }
+
         SmartReplyView smartReplyView = null;
-        if (smartReplyContainer.getChildCount() == 0) {
-            smartReplyView = SmartReplyView.inflate(mContext, smartReplyContainer);
+        if (smartReplyContainer.getChildCount() == 1
+                && smartReplyContainer.getChildAt(0) instanceof SmartReplyView) {
+            // If we already have a SmartReplyView - replace it with the newly inflated one. The
+            // newly inflated one is connected to the new inflated smart reply/action buttons.
+            smartReplyContainer.removeAllViews();
+        }
+        if (smartReplyContainer.getChildCount() == 0
+                && inflatedSmartReplyView != null
+                && inflatedSmartReplyView.getSmartReplyView() != null) {
+            smartReplyView = inflatedSmartReplyView.getSmartReplyView();
             smartReplyContainer.addView(smartReplyView);
-        } else if (smartReplyContainer.getChildCount() == 1) {
-            View child = smartReplyContainer.getChildAt(0);
-            if (child instanceof SmartReplyView) {
-                smartReplyView = (SmartReplyView) child;
-            }
         }
         if (smartReplyView != null) {
             smartReplyView.resetSmartSuggestions(smartReplyContainer);
-            if (smartRepliesAndActions.smartReplies != null) {
-                smartReplyView.addRepliesFromRemoteInput(
-                        smartRepliesAndActions.smartReplies, mSmartReplyController, entry);
-            }
-            if (smartRepliesAndActions.smartActions != null) {
-                smartReplyView.addSmartActions(
-                        smartRepliesAndActions.smartActions, mSmartReplyController, entry,
-                        mContainingNotification.getHeadsUpManager());
-            }
+            smartReplyView.addPreInflatedButtons(
+                    inflatedSmartReplyView.getSmartSuggestionButtons());
             smartReplyContainer.setVisibility(View.VISIBLE);
         }
         return smartReplyView;
     }
 
+    /**
+     * Set pre-inflated views necessary to display smart replies and actions in the expanded
+     * notification state.
+     *
+     * @param inflatedSmartReplies the pre-inflated state to add to this view. If null the existing
+     * {@link SmartReplyView} related to the expanded notification state is cleared.
+     */
+    public void setExpandedInflatedSmartReplies(
+            @Nullable InflatedSmartReplies inflatedSmartReplies) {
+        mExpandedInflatedSmartReplies = inflatedSmartReplies;
+        if (inflatedSmartReplies == null) {
+            mExpandedSmartReplyView = null;
+        }
+    }
+
+    /**
+     * Set pre-inflated views necessary to display smart replies and actions in the heads-up
+     * notification state.
+     *
+     * @param inflatedSmartReplies the pre-inflated state to add to this view. If null the existing
+     * {@link SmartReplyView} related to the heads-up notification state is cleared.
+     */
+    public void setHeadsUpInflatedSmartReplies(
+            @Nullable InflatedSmartReplies inflatedSmartReplies) {
+        mHeadsUpInflatedSmartReplies = inflatedSmartReplies;
+        if (inflatedSmartReplies == null) {
+            mHeadsUpSmartReplyView = null;
+        }
+    }
+
     public void closeRemoteInput() {
         if (mHeadsUpRemoteInput != null) {
             mHeadsUpRemoteInput.close();
@@ -2005,22 +1957,4 @@
         }
         pw.println();
     }
-
-    @VisibleForTesting
-    static class SmartRepliesAndActions {
-        @Nullable
-        public final SmartReplyView.SmartReplies smartReplies;
-        @Nullable
-        public final SmartReplyView.SmartActions smartActions;
-        public final boolean hasFreeformRemoteInput;
-
-        SmartRepliesAndActions(
-                @Nullable SmartReplyView.SmartReplies smartReplies,
-                @Nullable SmartReplyView.SmartActions smartActions,
-                boolean hasFreeformRemoteInput) {
-            this.smartReplies = smartReplies;
-            this.smartActions = smartActions;
-            this.hasFreeformRemoteInput = hasFreeformRemoteInput;
-        }
-    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationMediaTemplateViewWrapper.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationMediaTemplateViewWrapper.java
index ddda3e5..99f5874 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationMediaTemplateViewWrapper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationMediaTemplateViewWrapper.java
@@ -36,6 +36,7 @@
 
 import com.android.internal.R;
 import com.android.systemui.Dependency;
+import com.android.systemui.statusbar.NotificationMediaManager;
 import com.android.systemui.statusbar.TransformableView;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 
@@ -58,12 +59,10 @@
     private TextView mSeekBarTotalTime;
     private long mDuration = 0;
     private MediaController mMediaController;
+    private NotificationMediaManager mMediaManager;
     private View mSeekBarView;
     private Context mContext;
 
-    // TODO: implement as phenotype flag
-    public static final boolean HIDE_COMPACT_SCRUBBER = true;
-
     private SeekBar.OnSeekBarChangeListener mSeekListener = new SeekBar.OnSeekBarChangeListener() {
         @Override
         public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
@@ -102,6 +101,7 @@
             ExpandableNotificationRow row) {
         super(ctx, view, row);
         mContext = ctx;
+        mMediaManager = Dependency.get(NotificationMediaManager.class);
     }
 
     private void resolveViews() {
@@ -110,7 +110,8 @@
         final MediaSession.Token token = mRow.getEntry().notification.getNotification().extras
                 .getParcelable(Notification.EXTRA_MEDIA_SESSION);
 
-        if (token == null || (COMPACT_MEDIA_TAG.equals(mView.getTag()) && HIDE_COMPACT_SCRUBBER)) {
+        boolean showCompactSeekbar = mMediaManager.getShowCompactMediaSeekbar();
+        if (token == null || (COMPACT_MEDIA_TAG.equals(mView.getTag()) && !showCompactSeekbar)) {
             if (mSeekBarView != null) {
                 mSeekBarView.setVisibility(View.GONE);
             }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/AutoTileManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/AutoTileManager.java
index c9be2c8..007c50c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/AutoTileManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/AutoTileManager.java
@@ -25,6 +25,8 @@
 import com.android.systemui.qs.AutoAddTracker;
 import com.android.systemui.qs.QSTileHost;
 import com.android.systemui.qs.SecureSetting;
+import com.android.systemui.statusbar.policy.CastController;
+import com.android.systemui.statusbar.policy.CastController.CastDevice;
 import com.android.systemui.statusbar.policy.DataSaverController;
 import com.android.systemui.statusbar.policy.DataSaverController.Listener;
 import com.android.systemui.statusbar.policy.HotspotController;
@@ -42,6 +44,7 @@
     public static final String INVERSION = "inversion";
     public static final String WORK = "work";
     public static final String NIGHT = "night";
+    public static final String CAST = "cast";
 
     private final Context mContext;
     private final QSTileHost mHost;
@@ -51,6 +54,7 @@
     private final DataSaverController mDataSaverController;
     private final ManagedProfileController mManagedProfileController;
     private final NightDisplayListener mNightDisplayListener;
+    private final CastController mCastController;
 
     @Inject
     public AutoTileManager(Context context, AutoAddTracker autoAddTracker, QSTileHost host,
@@ -58,7 +62,8 @@
             HotspotController hotspotController,
             DataSaverController dataSaverController,
             ManagedProfileController managedProfileController,
-            NightDisplayListener nightDisplayListener) {
+            NightDisplayListener nightDisplayListener,
+            CastController castController) {
         mAutoTracker = autoAddTracker;
         mContext = context;
         mHost = host;
@@ -67,6 +72,7 @@
         mDataSaverController = dataSaverController;
         mManagedProfileController = managedProfileController;
         mNightDisplayListener = nightDisplayListener;
+        mCastController = castController;
         if (!mAutoTracker.isAdded(HOTSPOT)) {
             hotspotController.addCallback(mHotspotCallback);
         }
@@ -95,6 +101,9 @@
                 && ColorDisplayManager.isNightDisplayAvailable(mContext)) {
             nightDisplayListener.setCallback(mNightDisplayCallback);
         }
+        if (!mAutoTracker.isAdded(CAST)) {
+            castController.addCallback(mCastCallback);
+        }
     }
 
     public void destroy() {
@@ -108,6 +117,7 @@
         if (ColorDisplayManager.isNightDisplayAvailable(mContext)) {
             mNightDisplayListener.setCallback(null);
         }
+        mCastController.removeCallback(mCastCallback);
     }
 
     public void unmarkTileAsAutoAdded(String tabSpec) {
@@ -181,4 +191,27 @@
             mHandler.post(() -> mNightDisplayListener.setCallback(null));
         }
     };
+
+    @VisibleForTesting
+    final CastController.Callback mCastCallback = new CastController.Callback() {
+        @Override
+        public void onCastDevicesChanged() {
+            if (mAutoTracker.isAdded(CAST)) return;
+
+            boolean isCasting = false;
+            for (CastDevice device : mCastController.getCastDevices()) {
+                if (device.state == CastDevice.STATE_CONNECTED
+                        || device.state == CastDevice.STATE_CONNECTING) {
+                    isCasting = true;
+                    break;
+                }
+            }
+
+            if (isCasting) {
+                mHost.addTile(CAST);
+                mAutoTracker.setTileAdded(CAST);
+                mHandler.post(() -> mCastController.removeCallback(mCastCallback));
+            }
+        }
+    };
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeParameters.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeParameters.java
index 1049773..a17e042 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeParameters.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeParameters.java
@@ -17,6 +17,7 @@
 package com.android.systemui.statusbar.phone;
 
 import android.content.Context;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.os.PowerManager;
 import android.os.SystemProperties;
 import android.os.UserHandle;
@@ -26,7 +27,6 @@
 import android.util.SparseBooleanArray;
 
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
 import com.android.systemui.doze.AlwaysOnDisplayPolicy;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
index 13d4489..41580f6 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
@@ -195,9 +195,9 @@
 import com.android.systemui.statusbar.notification.NotificationEntryManager;
 import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
 import com.android.systemui.statusbar.notification.NotificationListController;
-import com.android.systemui.statusbar.notification.NotificationRowBinder;
 import com.android.systemui.statusbar.notification.VisualStabilityManager;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationRowBinderImpl;
 import com.android.systemui.statusbar.notification.logging.NotificationLogger;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
@@ -390,7 +390,6 @@
     protected NotificationEntryManager mEntryManager;
     private NotificationListController mNotificationListController;
     private NotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
-    private NotificationRowBinder mNotificationRowBinder;
     protected NotificationViewHierarchyManager mViewHierarchyManager;
     protected ForegroundServiceController mForegroundServiceController;
     protected AppOpsController mAppOpsController;
@@ -620,7 +619,6 @@
         mEntryManager = Dependency.get(NotificationEntryManager.class);
         mNotificationInterruptionStateProvider =
                 Dependency.get(NotificationInterruptionStateProvider.class);
-        mNotificationRowBinder = Dependency.get(NotificationRowBinder.class);
         mViewHierarchyManager = Dependency.get(NotificationViewHierarchyManager.class);
         mForegroundServiceController = Dependency.get(ForegroundServiceController.class);
         mAppOpsController = Dependency.get(AppOpsController.class);
@@ -1032,10 +1030,15 @@
                 mStatusBarWindow, this, mNotificationPanel,
                 (NotificationListContainer) mStackScroller);
 
+        final NotificationRowBinderImpl rowBinder =
+                new NotificationRowBinderImpl(
+                        mContext,
+                        SystemUIFactory.getInstance().provideAllowNotificationLongPress());
+
         mPresenter = new StatusBarNotificationPresenter(mContext, mNotificationPanel,
                 mHeadsUpManager, mStatusBarWindow, mStackScroller, mDozeScrimController,
                 mScrimController, mActivityLaunchAnimator, mStatusBarKeyguardViewManager,
-                mNotificationAlertingManager);
+                mNotificationAlertingManager, rowBinder);
 
         mNotificationListController =
                 new NotificationListController(
@@ -1051,7 +1054,9 @@
         mNotificationActivityStarter = new StatusBarNotificationActivityStarter(
                 mContext, mNotificationPanel, mPresenter, mHeadsUpManager, mActivityLaunchAnimator);
         mGutsManager.setNotificationActivityStarter(mNotificationActivityStarter);
-        mNotificationRowBinder.setNotificationClicker(new NotificationClicker(
+
+        mEntryManager.setRowBinder(rowBinder);
+        rowBinder.setNotificationClicker(new NotificationClicker(
                 this, Dependency.get(BubbleController.class), mNotificationActivityStarter));
 
         mGroupAlertTransferHelper.bind(mEntryManager, mGroupManager);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconControllerImpl.java
index f846036..e0b1846 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconControllerImpl.java
@@ -42,6 +42,7 @@
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 
 import javax.inject.Inject;
@@ -122,7 +123,7 @@
         // Remove all the icons.
         for (int i = currentSlots.size() - 1; i >= 0; i--) {
             Slot s = currentSlots.get(i);
-            slotsToReAdd.put(s, s.getHolderListInViewOrder());
+            slotsToReAdd.put(s, s.getHolderList());
             removeAllIconsForSlot(s.getName());
         }
 
@@ -200,6 +201,10 @@
         Slot mobileSlot = getSlot(slot);
         int slotIndex = getSlotIndex(slot);
 
+        // Reverse the sort order to show icons with left to right([Slot1][Slot2]..).
+        // StatusBarIconList has UI design that first items go to the right of second items.
+        Collections.reverse(iconStates);
+
         for (MobileIconState state : iconStates) {
             StatusBarIconHolder holder = mobileSlot.getHolderForTag(state.subId);
             if (holder == null) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconList.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconList.java
index 2e41617..c876c32 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconList.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconList.java
@@ -250,6 +250,25 @@
             return holders;
         }
 
+        /**
+         * Build a list of the {@link StatusBarIconHolder}s in the same order.
+         * This provides a safe list that can be iterated and inserted into its group.
+         *
+         * @return all holders contained here
+         */
+        public List<StatusBarIconHolder> getHolderList() {
+            ArrayList<StatusBarIconHolder> holders = new ArrayList<>();
+            if (mHolder != null) {
+                holders.add(mHolder);
+            }
+
+            if (mSubSlots != null) {
+                holders.addAll(mSubSlots);
+            }
+
+            return holders;
+        }
+
         @Override
         public String toString() {
             return String.format("(%s) %s", mName, subSlotsString());
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
index 3ce66c5..6fe8964 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
@@ -64,9 +64,9 @@
 import com.android.systemui.statusbar.notification.NotificationEntryListener;
 import com.android.systemui.statusbar.notification.NotificationEntryManager;
 import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
-import com.android.systemui.statusbar.notification.NotificationRowBinder;
 import com.android.systemui.statusbar.notification.VisualStabilityManager;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationRowBinderImpl;
 import com.android.systemui.statusbar.notification.row.ActivatableNotificationView;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
@@ -79,7 +79,8 @@
 import java.util.ArrayList;
 
 public class StatusBarNotificationPresenter implements NotificationPresenter,
-        ConfigurationController.ConfigurationListener {
+        ConfigurationController.ConfigurationListener,
+        NotificationRowBinderImpl.BindRowCallback {
 
     private final LockscreenGestureLogger mLockscreenGestureLogger =
             Dependency.get(LockscreenGestureLogger.class);
@@ -97,8 +98,6 @@
             (SysuiStatusBarStateController) Dependency.get(StatusBarStateController.class);
     private final NotificationEntryManager mEntryManager =
             Dependency.get(NotificationEntryManager.class);
-    private final NotificationRowBinder mNotificationRowBinder =
-            Dependency.get(NotificationRowBinder.class);
     private final NotificationInterruptionStateProvider mNotificationInterruptionStateProvider =
             Dependency.get(NotificationInterruptionStateProvider.class);
     private final NotificationMediaManager mMediaManager =
@@ -140,7 +139,8 @@
             ScrimController scrimController,
             ActivityLaunchAnimator activityLaunchAnimator,
             StatusBarKeyguardViewManager statusBarKeyguardViewManager,
-            NotificationAlertingManager notificationAlertingManager) {
+            NotificationAlertingManager notificationAlertingManager,
+            NotificationRowBinderImpl notificationRowBinder) {
         mContext = context;
         mNotificationPanel = panel;
         mHeadsUpManager = headsUp;
@@ -217,7 +217,7 @@
             mEntryManager.addNotificationLifetimeExtender(mGutsManager);
             mEntryManager.addNotificationLifetimeExtenders(
                     remoteInputManager.getLifetimeExtenders());
-            mNotificationRowBinder.setUpWithPresenter(this, notifListContainer, mHeadsUpManager,
+            notificationRowBinder.setUpWithPresenter(this, notifListContainer, mHeadsUpManager,
                     mEntryManager, this);
             mNotificationInterruptionStateProvider.setUpWithPresenter(
                     this, mHeadsUpManager, this::canHeadsUp);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java
index e1a77b0..ce69a48 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java
@@ -246,7 +246,7 @@
     private boolean isExpanded(State state) {
         return !state.forceCollapsed && (state.isKeyguardShowingAndNotOccluded()
                 || state.panelVisible || state.keyguardFadingAway || state.bouncerShowing
-                || state.headsUpShowing || state.bubblesShowing
+                || state.headsUpShowing || state.bubblesShowing || state.assistShowing
                 || state.scrimsVisibility != ScrimController.VISIBILITY_FULLY_TRANSPARENT);
     }
 
@@ -490,6 +490,21 @@
     }
 
     /**
+     * Sets whether assist UI is showing on the screen.
+     */
+    public void setAssistShowing(boolean assistShowing) {
+        mCurrentState.assistShowing = assistShowing;
+        apply(mCurrentState);
+    }
+
+    /**
+     * The assist UI showing state for the status bar.
+     */
+    public boolean getAssistShowing() {
+        return mCurrentState.assistShowing;
+    }
+
+    /**
      * Sets if there is a bubble being expanded on the screen.
      */
     public void setBubbleExpanded(boolean bubbleExpanded) {
@@ -558,6 +573,7 @@
         boolean notTouchable;
         boolean bubblesShowing;
         boolean bubbleExpanded;
+        boolean assistShowing;
 
         /**
          * The {@link StatusBar} state from the status bar.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowView.java
index ad4ba75..50c4fac 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowView.java
@@ -29,14 +29,18 @@
 import android.graphics.PorterDuffXfermode;
 import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.media.AudioManager;
 import android.media.session.MediaSessionLegacyHelper;
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.SystemClock;
+import android.os.UserHandle;
+import android.provider.Settings;
 import android.util.AttributeSet;
 import android.view.ActionMode;
 import android.view.DisplayCutout;
+import android.view.GestureDetector;
 import android.view.InputDevice;
 import android.view.InputQueue;
 import android.view.KeyEvent;
@@ -63,16 +67,23 @@
 import com.android.systemui.statusbar.DragDownHelper;
 import com.android.systemui.statusbar.StatusBarState;
 import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
+import com.android.systemui.tuner.TunerService;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 
+/**
+ * Combined status bar and notification panel view. Also holding backdrop and scrims.
+ */
 public class StatusBarWindowView extends FrameLayout {
     public static final String TAG = "StatusBarWindowView";
     public static final boolean DEBUG = StatusBar.DEBUG;
 
+    private final GestureDetector mGestureDetector;
+    private final StatusBarStateController mStatusBarStateController;
+    private boolean mDoubleTapEnabled;
+    private boolean mSingleTapEnabled;
     private DragDownHelper mDragDownHelper;
-    private DoubleTapHelper mDoubleTapHelper;
     private NotificationStackScrollLayout mStackScrollLayout;
     private NotificationPanelView mNotificationPanel;
     private View mBrightnessMirror;
@@ -95,8 +106,37 @@
     private boolean mTouchActive;
     private boolean mExpandAnimationRunning;
     private boolean mExpandAnimationPending;
-    private final StatusBarStateController
-            mStatusBarStateController = Dependency.get(StatusBarStateController.class);
+
+    private final GestureDetector.SimpleOnGestureListener mGestureListener =
+            new GestureDetector.SimpleOnGestureListener() {
+        @Override
+        public boolean onSingleTapConfirmed(MotionEvent e) {
+            if (mSingleTapEnabled) {
+                mService.wakeUpIfDozing(SystemClock.uptimeMillis(), StatusBarWindowView.this,
+                        "SINGLE_TAP");
+            }
+            return mSingleTapEnabled;
+        }
+
+        @Override
+        public boolean onDoubleTap(MotionEvent e) {
+            if (mDoubleTapEnabled) {
+                mService.wakeUpIfDozing(SystemClock.uptimeMillis(), StatusBarWindowView.this,
+                        "DOUBLE_TAP");
+            }
+            return mDoubleTapEnabled;
+        }
+    };
+    private final TunerService.Tunable mTunable = (key, newValue) -> {
+        AmbientDisplayConfiguration configuration = new AmbientDisplayConfiguration(mContext);
+        switch (key) {
+            case Settings.Secure.DOZE_DOUBLE_TAP_GESTURE:
+                mDoubleTapEnabled = configuration.doubleTapGestureEnabled(UserHandle.USER_CURRENT);
+                break;
+            case Settings.Secure.DOZE_TAP_SCREEN_GESTURE:
+                mSingleTapEnabled = configuration.tapGestureEnabled(UserHandle.USER_CURRENT);
+        }
+    };
 
     /**
      * If set to true, the current gesture started below the notch and we need to dispatch touch
@@ -110,10 +150,11 @@
         mTransparentSrcPaint.setColor(0);
         mTransparentSrcPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
         mFalsingManager = FalsingManager.getInstance(context);
-        mDoubleTapHelper = new DoubleTapHelper(this, active -> {}, () -> {
-            mService.wakeUpIfDozing(SystemClock.uptimeMillis(), this, "DOUBLE_TAP");
-            return true;
-        }, null, null);
+        mGestureDetector = new GestureDetector(context, mGestureListener);
+        mStatusBarStateController = Dependency.get(StatusBarStateController.class);
+        Dependency.get(TunerService.class).addTunable(mTunable,
+                Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
+                Settings.Secure.DOZE_TAP_SCREEN_GESTURE);
     }
 
     @Override
@@ -306,6 +347,7 @@
             return false;
         }
         mFalsingManager.onTouchEvent(ev, getWidth(), getHeight());
+        mGestureDetector.onTouchEvent(ev);
         if (mBrightnessMirror != null && mBrightnessMirror.getVisibility() == VISIBLE) {
             // Disallow new pointers while the brightness mirror is visible. This is so that you
             // can't touch anything other than the brightness slider while the mirror is showing
@@ -366,7 +408,6 @@
     public boolean onTouchEvent(MotionEvent ev) {
         boolean handled = false;
         if (mService.isDozing()) {
-            mDoubleTapHelper.onTouchEvent(ev);
             handled = !mService.isPulsing();
         }
         if ((mStatusBarStateController.getState() == StatusBarState.KEYGUARD && !handled)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/InflatedSmartReplies.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/InflatedSmartReplies.java
new file mode 100644
index 0000000..d8ea1f6
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/InflatedSmartReplies.java
@@ -0,0 +1,225 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.policy;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.app.Notification;
+import android.app.RemoteInput;
+import android.content.Context;
+import android.os.Build;
+import android.util.Log;
+import android.util.Pair;
+import android.widget.Button;
+
+import com.android.internal.util.ArrayUtils;
+import com.android.systemui.statusbar.SmartReplyController;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Holder for inflated smart replies and actions. These objects should be inflated on a background
+ * thread, to later be accessed and modified on the (performance critical) UI thread.
+ */
+public class InflatedSmartReplies {
+    private static final String TAG = "InflatedSmartReplies";
+    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+    @Nullable private final SmartReplyView mSmartReplyView;
+    @Nullable private final List<Button> mSmartSuggestionButtons;
+    @NonNull private final SmartRepliesAndActions mSmartRepliesAndActions;
+
+    private InflatedSmartReplies(
+            @Nullable SmartReplyView smartReplyView,
+            @Nullable List<Button> smartSuggestionButtons,
+            @NonNull SmartRepliesAndActions smartRepliesAndActions) {
+        mSmartReplyView = smartReplyView;
+        mSmartSuggestionButtons = smartSuggestionButtons;
+        mSmartRepliesAndActions = smartRepliesAndActions;
+    }
+
+    @Nullable public SmartReplyView getSmartReplyView() {
+        return mSmartReplyView;
+    }
+
+    @Nullable public List<Button> getSmartSuggestionButtons() {
+        return mSmartSuggestionButtons;
+    }
+
+    @NonNull public SmartRepliesAndActions getSmartRepliesAndActions() {
+        return mSmartRepliesAndActions;
+    }
+
+    /**
+     * Inflate a SmartReplyView and its smart suggestions.
+     */
+    public static InflatedSmartReplies inflate(
+            Context context,
+            NotificationEntry entry,
+            SmartReplyConstants smartReplyConstants,
+            SmartReplyController smartReplyController,
+            HeadsUpManager headsUpManager) {
+        SmartRepliesAndActions smartRepliesAndActions =
+                chooseSmartRepliesAndActions(smartReplyConstants, entry);
+        if (!shouldShowSmartReplyView(entry, smartRepliesAndActions)) {
+            return new InflatedSmartReplies(null /* smartReplyView */,
+                    null /* smartSuggestionButtons */, smartRepliesAndActions);
+        }
+
+        SmartReplyView smartReplyView = SmartReplyView.inflate(context);
+
+        List<Button> suggestionButtons = new ArrayList<>();
+        if (smartRepliesAndActions.smartReplies != null) {
+            suggestionButtons.addAll(smartReplyView.inflateRepliesFromRemoteInput(
+                    smartRepliesAndActions.smartReplies, smartReplyController, entry));
+        }
+        if (smartRepliesAndActions.smartActions != null) {
+            suggestionButtons.addAll(
+                    smartReplyView.inflateSmartActions(smartRepliesAndActions.smartActions,
+                            smartReplyController, entry, headsUpManager));
+        }
+
+        return new InflatedSmartReplies(smartReplyView, suggestionButtons,
+                smartRepliesAndActions);
+    }
+
+    /**
+     * Returns whether we should show the smart reply view and its smart suggestions.
+     */
+    public static boolean shouldShowSmartReplyView(
+            NotificationEntry entry,
+            SmartRepliesAndActions smartRepliesAndActions) {
+        if (smartRepliesAndActions.smartReplies == null
+                && smartRepliesAndActions.smartActions == null) {
+            // There are no smart replies and no smart actions.
+            return false;
+        }
+        // If we are showing the spinner we don't want to add the buttons.
+        boolean showingSpinner = entry.notification.getNotification()
+                .extras.getBoolean(Notification.EXTRA_SHOW_REMOTE_INPUT_SPINNER, false);
+        if (showingSpinner) {
+            return false;
+        }
+        // If we are keeping the notification around while sending we don't want to add the buttons.
+        boolean hideSmartReplies = entry.notification.getNotification()
+                .extras.getBoolean(Notification.EXTRA_HIDE_SMART_REPLIES, false);
+        if (hideSmartReplies) {
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Chose what smart replies and smart actions to display. App generated suggestions take
+     * precedence. So if the app provides any smart replies, we don't show any
+     * replies or actions generated by the NotificationAssistantService (NAS), and if the app
+     * provides any smart actions we also don't show any NAS-generated replies or actions.
+     */
+    @NonNull
+    public static SmartRepliesAndActions chooseSmartRepliesAndActions(
+            SmartReplyConstants smartReplyConstants,
+            final NotificationEntry entry) {
+        Notification notification = entry.notification.getNotification();
+        Pair<RemoteInput, Notification.Action> remoteInputActionPair =
+                notification.findRemoteInputActionPair(false /* freeform */);
+        Pair<RemoteInput, Notification.Action> freeformRemoteInputActionPair =
+                notification.findRemoteInputActionPair(true /* freeform */);
+
+        if (!smartReplyConstants.isEnabled()) {
+            if (DEBUG) {
+                Log.d(TAG, "Smart suggestions not enabled, not adding suggestions for "
+                        + entry.notification.getKey());
+            }
+            return new SmartRepliesAndActions(null, null);
+        }
+        // Only use smart replies from the app if they target P or above. We have this check because
+        // the smart reply API has been used for other things (Wearables) in the past. The API to
+        // add smart actions is new in Q so it doesn't require a target-sdk check.
+        boolean enableAppGeneratedSmartReplies = (!smartReplyConstants.requiresTargetingP()
+                || entry.targetSdk >= Build.VERSION_CODES.P);
+
+        boolean appGeneratedSmartRepliesExist =
+                enableAppGeneratedSmartReplies
+                        && remoteInputActionPair != null
+                        && !ArrayUtils.isEmpty(remoteInputActionPair.first.getChoices())
+                        && remoteInputActionPair.second.actionIntent != null;
+
+        List<Notification.Action> appGeneratedSmartActions = notification.getContextualActions();
+        boolean appGeneratedSmartActionsExist = !appGeneratedSmartActions.isEmpty();
+
+        SmartReplyView.SmartReplies smartReplies = null;
+        SmartReplyView.SmartActions smartActions = null;
+        if (appGeneratedSmartRepliesExist) {
+            smartReplies = new SmartReplyView.SmartReplies(
+                    remoteInputActionPair.first.getChoices(),
+                    remoteInputActionPair.first,
+                    remoteInputActionPair.second.actionIntent,
+                    false /* fromAssistant */);
+        }
+        if (appGeneratedSmartActionsExist) {
+            smartActions = new SmartReplyView.SmartActions(appGeneratedSmartActions,
+                    false /* fromAssistant */);
+        }
+        // Apps didn't provide any smart replies / actions, use those from NAS (if any).
+        if (!appGeneratedSmartRepliesExist && !appGeneratedSmartActionsExist) {
+            boolean useGeneratedReplies = !ArrayUtils.isEmpty(entry.systemGeneratedSmartReplies)
+                    && freeformRemoteInputActionPair != null
+                    && freeformRemoteInputActionPair.second.getAllowGeneratedReplies()
+                    && freeformRemoteInputActionPair.second.actionIntent != null;
+            if (useGeneratedReplies) {
+                smartReplies = new SmartReplyView.SmartReplies(
+                        entry.systemGeneratedSmartReplies,
+                        freeformRemoteInputActionPair.first,
+                        freeformRemoteInputActionPair.second.actionIntent,
+                        true /* fromAssistant */);
+            }
+            boolean useSmartActions = !ArrayUtils.isEmpty(entry.systemGeneratedSmartActions)
+                    && notification.getAllowSystemGeneratedContextualActions();
+            if (useSmartActions) {
+                smartActions = new SmartReplyView.SmartActions(
+                        entry.systemGeneratedSmartActions, true /* fromAssistant */);
+            }
+        }
+        return new SmartRepliesAndActions(smartReplies, smartActions);
+    }
+
+    /**
+     * Returns whether the {@link Notification} represented by entry has a free-form remote input.
+     * Such an input can be used e.g. to implement smart reply buttons - by passing the replies
+     * through the remote input.
+     */
+    public static boolean hasFreeformRemoteInput(NotificationEntry entry) {
+        Notification notification = entry.notification.getNotification();
+        return null != notification.findRemoteInputActionPair(true /* freeform */);
+    }
+
+    /**
+     * A storage for smart replies and smart action.
+     */
+    public static class SmartRepliesAndActions {
+        @Nullable public final SmartReplyView.SmartReplies smartReplies;
+        @Nullable public final SmartReplyView.SmartActions smartActions;
+
+        SmartRepliesAndActions(
+                @Nullable SmartReplyView.SmartReplies smartReplies,
+                @Nullable SmartReplyView.SmartActions smartActions) {
+            this.smartReplies = smartReplies;
+            this.smartActions = smartActions;
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyConstants.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyConstants.java
index b22150b..72f4fc7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyConstants.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyConstants.java
@@ -21,13 +21,14 @@
 import android.app.RemoteInput;
 import android.content.Context;
 import android.content.res.Resources;
-import android.database.ContentObserver;
-import android.net.Uri;
 import android.os.Handler;
-import android.provider.Settings;
+import android.provider.DeviceConfig;
+import android.text.TextUtils;
 import android.util.KeyValueListParser;
 import android.util.Log;
 
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
 import com.android.systemui.R;
 
 import javax.inject.Inject;
@@ -35,20 +36,10 @@
 import javax.inject.Singleton;
 
 @Singleton
-public final class SmartReplyConstants extends ContentObserver {
+public final class SmartReplyConstants {
 
     private static final String TAG = "SmartReplyConstants";
 
-    private static final String KEY_ENABLED = "enabled";
-    private static final String KEY_REQUIRES_TARGETING_P = "requires_targeting_p";
-    private static final String KEY_MAX_SQUEEZE_REMEASURE_ATTEMPTS =
-            "max_squeeze_remeasure_attempts";
-    private static final String KEY_EDIT_CHOICES_BEFORE_SENDING =
-            "edit_choices_before_sending";
-    private static final String KEY_SHOW_IN_HEADS_UP = "show_in_heads_up";
-    private static final String KEY_MIN_NUM_REPLIES = "min_num_system_generated_replies";
-    private static final String KEY_MAX_NUM_ACTIONS = "max_num_actions";
-
     private final boolean mDefaultEnabled;
     private final boolean mDefaultRequiresP;
     private final int mDefaultMaxSqueezeRemeasureAttempts;
@@ -57,21 +48,25 @@
     private final int mDefaultMinNumSystemGeneratedReplies;
     private final int mDefaultMaxNumActions;
 
-    private boolean mEnabled;
-    private boolean mRequiresTargetingP;
-    private int mMaxSqueezeRemeasureAttempts;
-    private boolean mEditChoicesBeforeSending;
-    private boolean mShowInHeadsUp;
-    private int mMinNumSystemGeneratedReplies;
-    private int mMaxNumActions;
+    // These fields are updated on the UI thread but can be accessed on both the UI thread and
+    // background threads. We use the volatile keyword here instead of synchronization blocks since
+    // we only care about variable updates here being visible to other threads (and not for example
+    // whether the variables we are reading were updated in the same go).
+    private volatile boolean mEnabled;
+    private volatile boolean mRequiresTargetingP;
+    private volatile int mMaxSqueezeRemeasureAttempts;
+    private volatile boolean mEditChoicesBeforeSending;
+    private volatile boolean mShowInHeadsUp;
+    private volatile int mMinNumSystemGeneratedReplies;
+    private volatile int mMaxNumActions;
 
+    private final Handler mHandler;
     private final Context mContext;
     private final KeyValueListParser mParser = new KeyValueListParser(',');
 
     @Inject
     public SmartReplyConstants(@Named(MAIN_HANDLER_NAME) Handler handler, Context context) {
-        super(handler);
-
+        mHandler = handler;
         mContext = context;
         final Resources resources = mContext.getResources();
         mDefaultEnabled = resources.getBoolean(
@@ -89,35 +84,86 @@
         mDefaultMaxNumActions = resources.getInteger(
                 R.integer.config_smart_replies_in_notifications_max_num_actions);
 
-        mContext.getContentResolver().registerContentObserver(
-                Settings.Global.getUriFor(Settings.Global.SMART_REPLIES_IN_NOTIFICATIONS_FLAGS),
-                false, this);
+        registerDeviceConfigListener();
         updateConstants();
     }
 
-    @Override
-    public void onChange(boolean selfChange, Uri uri) {
+    private void registerDeviceConfigListener() {
+        DeviceConfig.addOnPropertyChangedListener(
+                DeviceConfig.NAMESPACE_SYSTEMUI,
+                this::postToHandler,
+                this::onDeviceConfigPropertyChanged);
+    }
+
+    private void postToHandler(Runnable r) {
+        this.mHandler.post(r);
+    }
+
+    @VisibleForTesting
+    void onDeviceConfigPropertyChanged(String namespace, String name, String value) {
+        if (!DeviceConfig.NAMESPACE_SYSTEMUI.equals(namespace)) {
+            Log.e(TAG, "Received update from DeviceConfig for unrelated namespace: "
+                    + namespace + " " + name + "=" + value);
+            return;
+        }
+
         updateConstants();
     }
 
     private void updateConstants() {
         synchronized (SmartReplyConstants.this) {
-            try {
-                mParser.setString(Settings.Global.getString(mContext.getContentResolver(),
-                        Settings.Global.SMART_REPLIES_IN_NOTIFICATIONS_FLAGS));
-            } catch (IllegalArgumentException e) {
-                Log.e(TAG, "Bad smart reply constants", e);
-            }
-            mEnabled = mParser.getBoolean(KEY_ENABLED, mDefaultEnabled);
-            mRequiresTargetingP = mParser.getBoolean(KEY_REQUIRES_TARGETING_P, mDefaultRequiresP);
-            mMaxSqueezeRemeasureAttempts = mParser.getInt(
-                    KEY_MAX_SQUEEZE_REMEASURE_ATTEMPTS, mDefaultMaxSqueezeRemeasureAttempts);
-            mEditChoicesBeforeSending = mParser.getBoolean(
-                    KEY_EDIT_CHOICES_BEFORE_SENDING, mDefaultEditChoicesBeforeSending);
-            mShowInHeadsUp = mParser.getBoolean(KEY_SHOW_IN_HEADS_UP, mDefaultShowInHeadsUp);
-            mMinNumSystemGeneratedReplies =
-                    mParser.getInt(KEY_MIN_NUM_REPLIES, mDefaultMinNumSystemGeneratedReplies);
-            mMaxNumActions = mParser.getInt(KEY_MAX_NUM_ACTIONS, mDefaultMaxNumActions);
+            mEnabled = readDeviceConfigBooleanOrDefaultIfEmpty(
+                    SystemUiDeviceConfigFlags.SSIN_ENABLED,
+                    mDefaultEnabled);
+            mRequiresTargetingP = readDeviceConfigBooleanOrDefaultIfEmpty(
+                    SystemUiDeviceConfigFlags.SSIN_REQUIRES_TARGETING_P,
+                    mDefaultRequiresP);
+            mMaxSqueezeRemeasureAttempts = readDeviceConfigIntegerOrDefaultIfEmpty(
+                    SystemUiDeviceConfigFlags.SSIN_MAX_SQUEEZE_REMEASURE_ATTEMPTS,
+                    mDefaultMaxSqueezeRemeasureAttempts);
+            mEditChoicesBeforeSending = readDeviceConfigBooleanOrDefaultIfEmpty(
+                    SystemUiDeviceConfigFlags.SSIN_EDIT_CHOICES_BEFORE_SENDING,
+                    mDefaultEditChoicesBeforeSending);
+            mShowInHeadsUp = readDeviceConfigBooleanOrDefaultIfEmpty(
+                    SystemUiDeviceConfigFlags.SSIN_SHOW_IN_HEADS_UP,
+                    mDefaultShowInHeadsUp);
+            mMinNumSystemGeneratedReplies = readDeviceConfigIntegerOrDefaultIfEmpty(
+                    SystemUiDeviceConfigFlags.SSIN_MIN_NUM_SYSTEM_GENERATED_REPLIES,
+                    mDefaultMinNumSystemGeneratedReplies);
+            mMaxNumActions = readDeviceConfigIntegerOrDefaultIfEmpty(
+                    SystemUiDeviceConfigFlags.SSIN_MAX_NUM_ACTIONS,
+                    mDefaultMaxNumActions);
+        }
+    }
+
+    private static boolean readDeviceConfigBooleanOrDefaultIfEmpty(String propertyName,
+            boolean defaultValue) {
+        String value = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_SYSTEMUI, propertyName);
+        if (TextUtils.isEmpty(value)) {
+            return defaultValue;
+        }
+        if ("true".equals(value)) {
+            return true;
+        }
+        if ("false".equals(value)) {
+            return false;
+        }
+        // For invalid configs we return the default value.
+        return defaultValue;
+    }
+
+    private static int readDeviceConfigIntegerOrDefaultIfEmpty(String propertyName,
+            int defaultValue) {
+        String value = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_SYSTEMUI, propertyName);
+        if (TextUtils.isEmpty(value)) {
+            return defaultValue;
+        }
+        try {
+            return Integer.parseInt(value);
+        } catch (NumberFormatException e) {
+            Log.e(TAG, "Tried to read an integer flag, property name="
+                    + propertyName + ", value=" + value);
+            return defaultValue;
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java
index 45d215e..ed5487f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java
@@ -196,66 +196,81 @@
     }
 
     /**
+     * Add buttons to the {@link SmartReplyView} - these buttons must have been preinflated using
+     * one of the methods in this class.
+     */
+    public void addPreInflatedButtons(List<Button> smartSuggestionButtons) {
+        for (Button button : smartSuggestionButtons) {
+            addView(button);
+        }
+        reallocateCandidateButtonQueueForSqueezing();
+    }
+
+    /**
      * Add smart replies to this view, using the provided {@link RemoteInput} and
      * {@link PendingIntent} to respond when the user taps a smart reply. Only the replies that fit
      * into the notification are shown.
      */
-    public void addRepliesFromRemoteInput(
-            SmartReplies smartReplies,
+    public List<Button> inflateRepliesFromRemoteInput(
+            @NonNull SmartReplies smartReplies,
             SmartReplyController smartReplyController, NotificationEntry entry) {
+        List<Button> buttons = new ArrayList<>();
+
         if (smartReplies.remoteInput != null && smartReplies.pendingIntent != null) {
             if (smartReplies.choices != null) {
                 for (int i = 0; i < smartReplies.choices.length; ++i) {
-                    Button replyButton = inflateReplyButton(
-                            getContext(), this, i, smartReplies, smartReplyController, entry);
-                    addView(replyButton);
+                    buttons.add(inflateReplyButton(
+                            this, getContext(), i, smartReplies, smartReplyController, entry));
                 }
                 this.mSmartRepliesGeneratedByAssistant = smartReplies.fromAssistant;
             }
         }
-        reallocateCandidateButtonQueueForSqueezing();
+        return buttons;
     }
 
     /**
      * Add smart actions to be shown next to smart replies. Only the actions that fit into the
      * notification are shown.
      */
-    public void addSmartActions(SmartActions smartActions,
+    public List<Button> inflateSmartActions(@NonNull SmartActions smartActions,
             SmartReplyController smartReplyController, NotificationEntry entry,
             HeadsUpManager headsUpManager) {
+        List<Button> buttons = new ArrayList<>();
         int numSmartActions = smartActions.actions.size();
         for (int n = 0; n < numSmartActions; n++) {
             Notification.Action action = smartActions.actions.get(n);
             if (action.actionIntent != null) {
-                Button actionButton = inflateActionButton(
-                        getContext(), this, n, smartActions, smartReplyController, entry,
-                        headsUpManager);
-                addView(actionButton);
+                buttons.add(inflateActionButton(
+                        this, getContext(), n, smartActions, smartReplyController, entry,
+                        headsUpManager));
             }
         }
-        reallocateCandidateButtonQueueForSqueezing();
+        return buttons;
     }
 
-    public static SmartReplyView inflate(Context context, ViewGroup root) {
-        return (SmartReplyView)
-                LayoutInflater.from(context).inflate(R.layout.smart_reply_view, root, false);
+    /**
+     * Inflate an instance of this class.
+     */
+    public static SmartReplyView inflate(Context context) {
+        return (SmartReplyView) LayoutInflater.from(context).inflate(
+                R.layout.smart_reply_view, null /* root */);
     }
 
     @VisibleForTesting
-    Button inflateReplyButton(Context context, ViewGroup root, int replyIndex,
-            SmartReplies smartReplies, SmartReplyController smartReplyController,
+    static Button inflateReplyButton(SmartReplyView smartReplyView, Context context,
+            int replyIndex, SmartReplies smartReplies, SmartReplyController smartReplyController,
             NotificationEntry entry) {
         Button b = (Button) LayoutInflater.from(context).inflate(
-                R.layout.smart_reply_button, root, false);
+                R.layout.smart_reply_button, smartReplyView, false);
         CharSequence choice = smartReplies.choices[replyIndex];
         b.setText(choice);
 
         OnDismissAction action = () -> {
-            if (mConstants.getEffectiveEditChoicesBeforeSending(
+            if (smartReplyView.mConstants.getEffectiveEditChoicesBeforeSending(
                     smartReplies.remoteInput.getEditChoicesBeforeSending())) {
                 EditedSuggestionInfo editedSuggestionInfo =
                         new EditedSuggestionInfo(choice, replyIndex);
-                mRemoteInputManager.activateRemoteInput(b,
+                smartReplyView.mRemoteInputManager.activateRemoteInput(b,
                         new RemoteInput[] { smartReplies.remoteInput }, smartReplies.remoteInput,
                         smartReplies.pendingIntent, editedSuggestionInfo);
                 return false;
@@ -276,33 +291,41 @@
             } catch (PendingIntent.CanceledException e) {
                 Log.w(TAG, "Unable to send smart reply", e);
             }
-            mSmartReplyContainer.setVisibility(View.GONE);
+            // Note that as inflateReplyButton is called mSmartReplyContainer is null, but when the
+            // reply Button is added to the SmartReplyView mSmartReplyContainer will be set. So, it
+            // will not be possible for a user to trigger this on-click-listener without
+            // mSmartReplyContainer being set.
+            smartReplyView.mSmartReplyContainer.setVisibility(View.GONE);
             return false; // do not defer
         };
 
         b.setOnClickListener(view -> {
-            mKeyguardDismissUtil.executeWhenUnlocked(action);
+            smartReplyView.mKeyguardDismissUtil.executeWhenUnlocked(action);
         });
 
         b.setAccessibilityDelegate(new AccessibilityDelegate() {
             public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
                 super.onInitializeAccessibilityNodeInfo(host, info);
-                String label = getResources().getString(R.string.accessibility_send_smart_reply);
+                String label = smartReplyView.getResources().getString(
+                        R.string.accessibility_send_smart_reply);
                 info.addAction(new AccessibilityAction(AccessibilityNodeInfo.ACTION_CLICK, label));
             }
         });
 
-        setColors(b, mCurrentBackgroundColor, mDefaultStrokeColor, mDefaultTextColor, mRippleColor);
+        SmartReplyView.setButtonColors(b, smartReplyView.mCurrentBackgroundColor,
+                smartReplyView.mDefaultStrokeColor, smartReplyView.mDefaultTextColor,
+                smartReplyView.mRippleColor, smartReplyView.mStrokeWidth);
         return b;
     }
 
     @VisibleForTesting
-    Button inflateActionButton(Context context, ViewGroup root, int actionIndex,
-            SmartActions smartActions, SmartReplyController smartReplyController,
-            NotificationEntry entry, HeadsUpManager headsUpManager) {
+    static Button inflateActionButton(SmartReplyView smartReplyView, Context context,
+            int actionIndex, SmartActions smartActions,
+            SmartReplyController smartReplyController, NotificationEntry entry,
+            HeadsUpManager headsUpManager) {
         Notification.Action action = smartActions.actions.get(actionIndex);
         Button button = (Button) LayoutInflater.from(context).inflate(
-                R.layout.smart_action_button, root, false);
+                R.layout.smart_action_button, smartReplyView, false);
         button.setText(action.title);
 
         Drawable iconDrawable = action.getIcon().loadDrawable(context);
@@ -313,7 +336,7 @@
         button.setCompoundDrawables(iconDrawable, null, null, null);
 
         button.setOnClickListener(view ->
-                getActivityStarter().startPendingIntentDismissingKeyguard(
+                smartReplyView.getActivityStarter().startPendingIntentDismissingKeyguard(
                         action.actionIntent,
                         () -> {
                             smartReplyController.smartActionClicked(
@@ -803,12 +826,13 @@
         int childCount = getChildCount();
         for (int i = 0; i < childCount; i++) {
             final Button child = (Button) getChildAt(i);
-            setColors(child, backgroundColor, strokeColor, textColor, rippleColor);
+            setButtonColors(child, backgroundColor, strokeColor, textColor, rippleColor,
+                    mStrokeWidth);
         }
     }
 
-    private void setColors(Button button, int backgroundColor, int strokeColor, int textColor,
-            int rippleColor) {
+    private static void setButtonColors(Button button, int backgroundColor, int strokeColor,
+            int textColor, int rippleColor, int strokeWidth) {
         Drawable drawable = button.getBackground();
         if (drawable instanceof RippleDrawable) {
             // Mutate in case other notifications are using this drawable.
@@ -821,7 +845,7 @@
                 if (background instanceof GradientDrawable) {
                     GradientDrawable gradientDrawable = (GradientDrawable) background;
                     gradientDrawable.setColor(backgroundColor);
-                    gradientDrawable.setStroke(mStrokeWidth, strokeColor);
+                    gradientDrawable.setStroke(strokeWidth, strokeColor);
                 }
             }
             button.setBackground(drawable);
diff --git a/packages/SystemUI/src/com/android/systemui/tuner/TunerFragment.java b/packages/SystemUI/src/com/android/systemui/tuner/TunerFragment.java
index ecf1784..0070dcf 100644
--- a/packages/SystemUI/src/com/android/systemui/tuner/TunerFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/tuner/TunerFragment.java
@@ -19,6 +19,7 @@
 import android.app.Dialog;
 import android.app.DialogFragment;
 import android.content.DialogInterface;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.os.Build;
 import android.os.Bundle;
 import android.provider.Settings;
@@ -29,7 +30,6 @@
 import androidx.preference.Preference;
 import androidx.preference.PreferenceFragment;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.systemui.R;
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
index 617b191..ffd8206 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
@@ -25,6 +25,7 @@
 import static android.media.AudioManager.STREAM_MUSIC;
 import static android.media.AudioManager.STREAM_RING;
 import static android.media.AudioManager.STREAM_VOICE_CALL;
+import static android.view.View.ACCESSIBILITY_LIVE_REGION_POLITE;
 import static android.view.View.GONE;
 import static android.view.View.VISIBLE;
 
@@ -431,8 +432,7 @@
         if (mSettingsIcon != null) {
             mSettingsIcon.setOnClickListener(v -> {
                 Events.writeEvent(mContext, Events.EVENT_SETTINGS_CLICK);
-                Intent intent = new Intent(Settings.ACTION_SOUND_SETTINGS);
-                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+                Intent intent = new Intent(Settings.Panel.ACTION_VOLUME);
                 dismissH(DISMISS_REASON_SETTINGS_CLICKED);
                 Dependency.get(ActivityStarter.class).startActivity(intent,
                         true /* dismissShade */);
@@ -442,6 +442,7 @@
 
     public void initRingerH() {
         if (mRingerIcon != null) {
+            mRingerIcon.setAccessibilityLiveRegion(ACCESSIBILITY_LIVE_REGION_POLITE);
             mRingerIcon.setOnClickListener(v -> {
                 Prefs.putBoolean(mContext, Prefs.Key.TOUCHED_RINGER_TOGGLE, true);
                 final StreamState ss = mState.states.get(AudioManager.STREAM_RING);
diff --git a/packages/SystemUI/tests/src/com/android/AAAPlusPlusVerifySysuiRequiredTestPropertiesTest.java b/packages/SystemUI/tests/src/com/android/AAAPlusPlusVerifySysuiRequiredTestPropertiesTest.java
index 7f83ed6..b97f55c 100644
--- a/packages/SystemUI/tests/src/com/android/AAAPlusPlusVerifySysuiRequiredTestPropertiesTest.java
+++ b/packages/SystemUI/tests/src/com/android/AAAPlusPlusVerifySysuiRequiredTestPropertiesTest.java
@@ -16,20 +16,20 @@
 
 import static org.hamcrest.Matchers.empty;
 import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertThat;
 
 import android.content.pm.PackageManager;
-import android.support.test.filters.LargeTest;
-import android.support.test.filters.MediumTest;
-import android.support.test.filters.SmallTest;
-import android.support.test.internal.runner.ClassPathScanner;
-import android.support.test.internal.runner.ClassPathScanner.ChainedClassNameFilter;
-import android.support.test.internal.runner.ClassPathScanner.ExternalClassNameFilter;
 import android.testing.AndroidTestingRunner;
 import android.text.TextUtils;
 import android.util.Log;
 
+import androidx.test.filters.LargeTest;
+import androidx.test.filters.MediumTest;
+import androidx.test.filters.SmallTest;
+import androidx.test.internal.runner.ClassPathScanner;
+import androidx.test.internal.runner.ClassPathScanner.ChainedClassNameFilter;
+import androidx.test.internal.runner.ClassPathScanner.ExternalClassNameFilter;
+
 import com.android.systemui.SysuiBaseFragmentTest;
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java
new file mode 100644
index 0000000..8e061cc
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java
@@ -0,0 +1,245 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.keyguard;
+
+
+import static android.telephony.SubscriptionManager.DATA_ROAMING_DISABLE;
+import static android.telephony.SubscriptionManager.DATA_ROAMING_ENABLE;
+import static android.telephony.SubscriptionManager.NAME_SOURCE_DEFAULT_SOURCE;
+
+import static junit.framework.Assert.assertTrue;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.wifi.WifiManager;
+import android.os.Handler;
+import android.telephony.SubscriptionInfo;
+import android.telephony.TelephonyManager;
+import android.test.suitebuilder.annotation.SmallTest;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+
+import com.android.internal.telephony.IccCardConstants;
+import com.android.systemui.Dependency;
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.keyguard.WakefulnessLifecycle;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+@TestableLooper.RunWithLooper
+public class CarrierTextControllerTest extends SysuiTestCase {
+
+    private static final CharSequence SEPARATOR = " \u2014 ";
+    private static final String TEST_CARRIER = "TEST_CARRIER";
+    private static final SubscriptionInfo TEST_SUBSCRIPTION = new SubscriptionInfo(0, "", 0,
+            TEST_CARRIER, TEST_CARRIER, NAME_SOURCE_DEFAULT_SOURCE, 0xFFFFFF, "",
+            DATA_ROAMING_DISABLE, null, null, null, null, false, null, "");
+    private static final SubscriptionInfo TEST_SUBSCRIPTION_ROAMING = new SubscriptionInfo(0, "", 0,
+            TEST_CARRIER, TEST_CARRIER, NAME_SOURCE_DEFAULT_SOURCE, 0xFFFFFF, "",
+            DATA_ROAMING_ENABLE, null, null, null, null, false, null, "");
+    @Mock
+    private WifiManager mWifiManager;
+    @Mock
+    private CarrierTextController.CarrierTextCallback mCarrierTextCallback;
+    @Mock
+    private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
+    @Mock
+    private ConnectivityManager mConnectivityManager;
+    @Mock
+    private TelephonyManager mTelephonyManager;
+    private CarrierTextController.CarrierTextCallbackInfo mCarrierTextCallbackInfo;
+
+    private CarrierTextController mCarrierTextController;
+    private TestableLooper mTestableLooper;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mTestableLooper = TestableLooper.get(this);
+
+        mContext.addMockSystemService(WifiManager.class, mWifiManager);
+        mContext.addMockSystemService(ConnectivityManager.class, mConnectivityManager);
+        mContext.addMockSystemService(TelephonyManager.class, mTelephonyManager);
+        mDependency.injectMockDependency(WakefulnessLifecycle.class);
+        mDependency.injectTestDependency(Dependency.MAIN_HANDLER,
+                new Handler(mTestableLooper.getLooper()));
+
+        mCarrierTextCallbackInfo = new CarrierTextController.CarrierTextCallbackInfo("",
+                new CharSequence[]{}, false, new int[]{});
+        when(mTelephonyManager.getPhoneCount()).thenReturn(2);
+        mCarrierTextController = new TestCarrierTextController(mContext, SEPARATOR, true, true,
+                mKeyguardUpdateMonitor);
+        // This should not start listening on any of the real dependencies
+        mCarrierTextController.setListening(mCarrierTextCallback);
+    }
+
+    @Test
+    public void testWrongSlots() {
+        reset(mCarrierTextCallback);
+        when(mKeyguardUpdateMonitor.getSubscriptionInfo(anyBoolean())).thenReturn(
+                new ArrayList<>());
+        when(mKeyguardUpdateMonitor.getSimState(anyInt())).thenReturn(
+                IccCardConstants.State.CARD_IO_ERROR);
+        // This should not produce an out of bounds error, even though there are no subscriptions
+        mCarrierTextController.mCallback.onSimStateChanged(0, -3,
+                IccCardConstants.State.CARD_IO_ERROR);
+        mCarrierTextController.mCallback.onSimStateChanged(0, 3, IccCardConstants.State.READY);
+        verify(mCarrierTextCallback, never()).updateCarrierInfo(any());
+    }
+
+    @Test
+    public void testMoreSlotsThanSubs() {
+        reset(mCarrierTextCallback);
+        when(mKeyguardUpdateMonitor.getSubscriptionInfo(anyBoolean())).thenReturn(
+                new ArrayList<>());
+        when(mKeyguardUpdateMonitor.getSimState(anyInt())).thenReturn(
+                IccCardConstants.State.CARD_IO_ERROR);
+        // This should not produce an out of bounds error, even though there are no subscriptions
+        mCarrierTextController.mCallback.onSimStateChanged(0, 1,
+                IccCardConstants.State.CARD_IO_ERROR);
+
+        mTestableLooper.processAllMessages();
+        verify(mCarrierTextCallback).updateCarrierInfo(
+                any(CarrierTextController.CarrierTextCallbackInfo.class));
+    }
+
+    @Test
+    public void testCallback() {
+        reset(mCarrierTextCallback);
+        mCarrierTextController.postToCallback(mCarrierTextCallbackInfo);
+        mTestableLooper.processAllMessages();
+
+        ArgumentCaptor<CarrierTextController.CarrierTextCallbackInfo> captor =
+                ArgumentCaptor.forClass(
+                        CarrierTextController.CarrierTextCallbackInfo.class);
+        verify(mCarrierTextCallback).updateCarrierInfo(captor.capture());
+        assertEquals(mCarrierTextCallbackInfo, captor.getValue());
+    }
+
+    @Test
+    public void testNullingCallback() {
+        reset(mCarrierTextCallback);
+
+        mCarrierTextController.postToCallback(mCarrierTextCallbackInfo);
+        mCarrierTextController.setListening(null);
+
+        // This shouldn't produce NPE
+        mTestableLooper.processAllMessages();
+        verify(mCarrierTextCallback).updateCarrierInfo(any());
+    }
+
+    @Test
+    public void testCreateInfo_OneValidSubscription() {
+        reset(mCarrierTextCallback);
+        List<SubscriptionInfo> list = new ArrayList<>();
+        list.add(TEST_SUBSCRIPTION);
+        when(mKeyguardUpdateMonitor.getSimState(anyInt())).thenReturn(IccCardConstants.State.READY);
+        when(mKeyguardUpdateMonitor.getSubscriptionInfo(anyBoolean())).thenReturn(list);
+        mKeyguardUpdateMonitor.mServiceStates = new HashMap<>();
+
+        ArgumentCaptor<CarrierTextController.CarrierTextCallbackInfo> captor =
+                ArgumentCaptor.forClass(
+                        CarrierTextController.CarrierTextCallbackInfo.class);
+
+        mCarrierTextController.updateCarrierText();
+        mTestableLooper.processAllMessages();
+        verify(mCarrierTextCallback).updateCarrierInfo(captor.capture());
+
+        CarrierTextController.CarrierTextCallbackInfo info = captor.getValue();
+        assertEquals(1, info.listOfCarriers.length);
+        assertEquals(TEST_CARRIER, info.listOfCarriers[0]);
+        assertEquals(1, info.subscriptionIds.length);
+    }
+
+    @Test
+    public void testCreateInfo_OneValidSubscriptionWithRoaming() {
+        reset(mCarrierTextCallback);
+        List<SubscriptionInfo> list = new ArrayList<>();
+        list.add(TEST_SUBSCRIPTION_ROAMING);
+        when(mKeyguardUpdateMonitor.getSimState(anyInt())).thenReturn(IccCardConstants.State.READY);
+        when(mKeyguardUpdateMonitor.getSubscriptionInfo(anyBoolean())).thenReturn(list);
+        mKeyguardUpdateMonitor.mServiceStates = new HashMap<>();
+
+        ArgumentCaptor<CarrierTextController.CarrierTextCallbackInfo> captor =
+                ArgumentCaptor.forClass(
+                        CarrierTextController.CarrierTextCallbackInfo.class);
+
+        mCarrierTextController.updateCarrierText();
+        mTestableLooper.processAllMessages();
+        verify(mCarrierTextCallback).updateCarrierInfo(captor.capture());
+
+        CarrierTextController.CarrierTextCallbackInfo info = captor.getValue();
+        assertEquals(1, info.listOfCarriers.length);
+        assertTrue(info.listOfCarriers[0].toString().contains(TEST_CARRIER));
+        assertEquals(1, info.subscriptionIds.length);
+    }
+
+    @Test
+    public void testCreateInfo_noSubscriptions() {
+        reset(mCarrierTextCallback);
+        when(mKeyguardUpdateMonitor.getSubscriptionInfo(anyBoolean())).thenReturn(
+                new ArrayList<>());
+        ArgumentCaptor<CarrierTextController.CarrierTextCallbackInfo> captor =
+                ArgumentCaptor.forClass(
+                        CarrierTextController.CarrierTextCallbackInfo.class);
+
+        mCarrierTextController.updateCarrierText();
+        mTestableLooper.processAllMessages();
+        verify(mCarrierTextCallback).updateCarrierInfo(captor.capture());
+
+        CarrierTextController.CarrierTextCallbackInfo info = captor.getValue();
+        assertEquals(0, info.listOfCarriers.length);
+        assertEquals(0, info.subscriptionIds.length);
+
+    }
+
+    public static class TestCarrierTextController extends CarrierTextController {
+        private KeyguardUpdateMonitor mKUM;
+
+        public TestCarrierTextController(Context context, CharSequence separator,
+                boolean showAirplaneMode, boolean showMissingSim, KeyguardUpdateMonitor kum) {
+            super(context, separator, showAirplaneMode, showMissingSim);
+            mKUM = kum;
+        }
+
+        @Override
+        public void setListening(CarrierTextCallback callback) {
+            super.setListening(callback);
+            mKeyguardUpdateMonitor = mKUM;
+        }
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockAccessibilityDelegateTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockAccessibilityDelegateTest.java
index e37ea95..dcafa72 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockAccessibilityDelegateTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockAccessibilityDelegateTest.java
@@ -20,12 +20,13 @@
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
-import android.support.test.filters.SmallTest;
 import android.text.TextUtils;
 import android.view.accessibility.AccessibilityEvent;
 import android.view.accessibility.AccessibilityNodeInfo;
 import android.widget.TextView;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPatternViewTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPatternViewTest.kt
index ab3a3e1..e7469c3 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPatternViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPatternViewTest.kt
@@ -16,7 +16,7 @@
 
 package com.android.keyguard
 
-import android.support.test.filters.SmallTest
+import androidx.test.filters.SmallTest
 import android.testing.AndroidTestingRunner
 import android.testing.TestableLooper
 import android.view.LayoutInflater
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinBasedInputViewTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinBasedInputViewTest.java
index 58870e4..eadb1b6 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinBasedInputViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinBasedInputViewTest.java
@@ -21,12 +21,13 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyZeroInteractions;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.KeyEvent;
 import android.view.LayoutInflater;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerTest.java
index fcf327b..8db195a 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerTest.java
@@ -16,19 +16,18 @@
 
 package com.android.keyguard;
 
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
 import android.content.Context;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.UiThreadTest;
-import android.util.Log;
 import android.view.LayoutInflater;
-import android.view.View;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.systemui.SysuiTestCase;
 
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class KeyguardSecurityContainerTest extends SysuiTestCase {
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/clock/BubbleClockControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/clock/BubbleClockControllerTest.java
index 9e946fa..267468f 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/clock/BubbleClockControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/clock/BubbleClockControllerTest.java
@@ -17,6 +17,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import android.content.res.Resources;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
@@ -40,8 +41,9 @@
 
     @Before
     public void setUp() {
+        Resources res = getContext().getResources();
         LayoutInflater layoutInflater = LayoutInflater.from(getContext());
-        mClockController = BubbleClockController.build(layoutInflater);
+        mClockController = new BubbleClockController(res, layoutInflater);
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockManagerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockManagerTest.java
index 58701e7..36265d4 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockManagerTest.java
@@ -31,6 +31,7 @@
 import com.android.systemui.colorextraction.SysuiColorExtractor;
 import com.android.systemui.dock.DockManager;
 import com.android.systemui.dock.DockManagerFake;
+import com.android.systemui.shared.plugins.PluginManager;
 import com.android.systemui.util.InjectionInflationController;
 
 import org.junit.After;
@@ -52,6 +53,7 @@
     private ContentObserver mContentObserver;
     private DockManagerFake mFakeDockManager;
     @Mock InjectionInflationController mMockInjectionInflationController;
+    @Mock PluginManager mMockPluginManager;
     @Mock SysuiColorExtractor mMockColorExtractor;
     @Mock ContentResolver mMockContentResolver;
     @Mock SettingsWrapper mMockSettingsWrapper;
@@ -66,7 +68,8 @@
 
         mFakeDockManager = new DockManagerFake();
         mClockManager = new ClockManager(getContext(), mMockInjectionInflationController,
-                mFakeDockManager, mMockColorExtractor, mMockContentResolver, mMockSettingsWrapper);
+                mMockPluginManager, mFakeDockManager, mMockColorExtractor, mMockContentResolver,
+                mMockSettingsWrapper);
 
         mClockManager.addOnClockChangedListener(mMockListener);
         mContentObserver = mClockManager.getContentObserver();
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/clock/StretchAnalogClockControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/clock/StretchAnalogClockControllerTest.java
index 8de8f3d..0659b4f 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/clock/StretchAnalogClockControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/clock/StretchAnalogClockControllerTest.java
@@ -17,6 +17,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import android.content.res.Resources;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
@@ -40,8 +41,9 @@
 
     @Before
     public void setUp() {
+        Resources res = getContext().getResources();
         LayoutInflater layoutInflater = LayoutInflater.from(getContext());
-        mClockController = StretchAnalogClockController.build(layoutInflater);
+        mClockController = new StretchAnalogClockController(res, layoutInflater);
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/BatteryMeterDrawableTest.java b/packages/SystemUI/tests/src/com/android/systemui/BatteryMeterDrawableTest.java
index e1f56a47..d1573c3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/BatteryMeterDrawableTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/BatteryMeterDrawableTest.java
@@ -16,8 +16,6 @@
 
 package com.android.systemui;
 
-import com.android.settingslib.graph.BatteryMeterDrawableBase;
-
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.anyFloat;
 import static org.mockito.Mockito.anyString;
@@ -30,9 +28,12 @@
 
 import android.content.res.Resources;
 import android.graphics.Canvas;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.settingslib.graph.BatteryMeterDrawableBase;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/DependencyTest.java b/packages/SystemUI/tests/src/com/android/systemui/DependencyTest.java
index 61bfa75..b1ca169 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/DependencyTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/DependencyTest.java
@@ -21,7 +21,8 @@
 import static org.mockito.Mockito.verify;
 
 import android.os.Looper;
-import android.support.test.filters.SmallTest;
+
+import androidx.test.filters.SmallTest;
 
 import com.android.systemui.Dependency.DependencyKey;
 import com.android.systemui.statusbar.policy.FlashlightController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ExpandHelperTest.java b/packages/SystemUI/tests/src/com/android/systemui/ExpandHelperTest.java
index 948e001..e07d17f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/ExpandHelperTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/ExpandHelperTest.java
@@ -22,12 +22,13 @@
 
 import android.animation.ObjectAnimator;
 import android.content.Context;
-import android.support.test.annotation.UiThreadTest;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.annotation.UiThreadTest;
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.statusbar.NotificationTestHelper;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.util.Assert;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceControllerTest.java
index 31e8071..8a6ee12 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceControllerTest.java
@@ -31,10 +31,11 @@
 import android.os.Bundle;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.widget.RemoteViews;
 
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.internal.messages.nano.SystemMessageProto;
 import com.android.systemui.statusbar.notification.NotificationEntryListener;
 import com.android.systemui.statusbar.notification.NotificationEntryManager;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ImageWallpaperTest.java b/packages/SystemUI/tests/src/com/android/systemui/ImageWallpaperTest.java
index e4d56d7..48a5369 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/ImageWallpaperTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/ImageWallpaperTest.java
@@ -16,9 +16,10 @@
 
 package com.android.systemui;
 
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/InitControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/InitControllerTest.java
index 4d33d43..e0ca87c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/InitControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/InitControllerTest.java
@@ -19,10 +19,11 @@
 import static junit.framework.TestCase.assertFalse;
 import static junit.framework.TestCase.assertTrue;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java b/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
index e91a7e9..64ab060 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
@@ -29,6 +29,7 @@
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
@@ -38,7 +39,6 @@
 import android.content.res.Configuration;
 import android.graphics.Rect;
 import android.os.Handler;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
@@ -46,6 +46,8 @@
 import android.view.View;
 import android.view.WindowManager;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.R.dimen;
 import com.android.systemui.ScreenDecorations.TunablePaddingTagListener;
 import com.android.systemui.fragments.FragmentHostManager;
@@ -82,6 +84,9 @@
         mTestableLooper = TestableLooper.get(this);
         mDependency.injectTestDependency(Dependency.MAIN_HANDLER,
                 new Handler(mTestableLooper.getLooper()));
+        mTunablePaddingService = mDependency.injectMockDependency(TunablePaddingService.class);
+        mTunerService = mDependency.injectMockDependency(TunerService.class);
+        mFragmentService = mDependency.injectMockDependency(FragmentService.class);
 
         mStatusBar = mock(StatusBar.class);
         mWindowManager = mock(WindowManager.class);
@@ -93,12 +98,9 @@
         when(mWindowManager.getDefaultDisplay()).thenReturn(display);
         mContext.addMockSystemService(WindowManager.class, mWindowManager);
 
-        mFragmentService = mDependency.injectMockDependency(FragmentService.class);
         mFragmentHostManager = mock(FragmentHostManager.class);
         when(mFragmentService.getFragmentHostManager(any())).thenReturn(mFragmentHostManager);
 
-        mTunerService = mDependency.injectMockDependency(TunerService.class);
-
 
         mScreenDecorations = new ScreenDecorations() {
             @Override
@@ -126,8 +128,7 @@
         };
         mScreenDecorations.mContext = mContext;
         mScreenDecorations.mComponents = mContext.getComponents();
-
-        mTunablePaddingService = mDependency.injectMockDependency(TunablePaddingService.class);
+        reset(mTunerService);
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/SliceBroadcastRelayHandlerTest.java b/packages/SystemUI/tests/src/com/android/systemui/SliceBroadcastRelayHandlerTest.java
index 383db05..c6e85c3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/SliceBroadcastRelayHandlerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/SliceBroadcastRelayHandlerTest.java
@@ -29,9 +29,10 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.net.Uri;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.settingslib.SliceBroadcastRelay;
 
 import org.junit.Test;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/SysuiBaseFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/SysuiBaseFragmentTest.java
index b6335f3..256cfb2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/SysuiBaseFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/SysuiBaseFragmentTest.java
@@ -19,10 +19,11 @@
 
 import android.app.Fragment;
 import android.app.Instrumentation;
-import android.support.test.InstrumentationRegistry;
 import android.testing.BaseFragmentTest;
 import android.testing.DexmakerShareClassLoaderRule;
 
+import androidx.test.InstrumentationRegistry;
+
 import com.android.systemui.utils.leaks.LeakCheckedTest;
 import com.android.systemui.utils.leaks.LeakCheckedTest.SysuiLeakCheck;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/SysuiTestCase.java b/packages/SystemUI/tests/src/com/android/systemui/SysuiTestCase.java
index 9c5a592..8d93f96 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/SysuiTestCase.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/SysuiTestCase.java
@@ -23,11 +23,12 @@
 import android.os.Looper;
 import android.os.MessageQueue;
 import android.os.ParcelFileDescriptor;
-import android.support.test.InstrumentationRegistry;
 import android.testing.DexmakerShareClassLoaderRule;
 import android.testing.LeakCheck;
 import android.util.Log;
 
+import androidx.test.InstrumentationRegistry;
+
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.systemui.util.Assert;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/appops/AppOpsControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/appops/AppOpsControllerTest.java
index 2582946..73ee0bd 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/appops/AppOpsControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/appops/AppOpsControllerTest.java
@@ -28,10 +28,11 @@
 
 import android.app.AppOpsManager;
 import android.os.UserHandle;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.Dependency;
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
index ca72602..0fd7834 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
@@ -25,12 +25,13 @@
 
 import android.app.IActivityManager;
 import android.content.Context;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.view.WindowManager;
 import android.widget.FrameLayout;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.NotificationTestHelper;
 import com.android.systemui.statusbar.notification.NotificationEntryListener;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/ExpandedAnimationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/ExpandedAnimationControllerTest.java
index b4059c5..b8add89 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/ExpandedAnimationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/ExpandedAnimationControllerTest.java
@@ -21,12 +21,12 @@
 import android.content.res.Resources;
 import android.graphics.Point;
 import android.graphics.PointF;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.view.View;
 import android.widget.FrameLayout;
 
 import androidx.dynamicanimation.animation.DynamicAnimation;
+import androidx.test.filters.SmallTest;
 
 import com.android.systemui.R;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTest.java
index c3214040..a50919b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTest.java
@@ -28,13 +28,13 @@
 import static org.mockito.Mockito.never;
 
 import android.os.SystemClock;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.view.View;
 import android.widget.FrameLayout;
 
 import androidx.dynamicanimation.animation.DynamicAnimation;
 import androidx.dynamicanimation.animation.SpringForce;
+import androidx.test.filters.SmallTest;
 
 import com.google.android.collect.Sets;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
index 97935ed..943d927 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
@@ -19,13 +19,13 @@
 import static org.junit.Assert.assertEquals;
 
 import android.graphics.PointF;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.view.View;
 import android.widget.FrameLayout;
 
 import androidx.dynamicanimation.animation.DynamicAnimation;
 import androidx.dynamicanimation.animation.SpringForce;
+import androidx.test.filters.SmallTest;
 
 import com.android.systemui.R;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/chooser/ChooserHelperTest.java b/packages/SystemUI/tests/src/com/android/systemui/chooser/ChooserHelperTest.java
index 19ad7ca..ecfb9ee 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/chooser/ChooserHelperTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/chooser/ChooserHelperTest.java
@@ -29,9 +29,10 @@
 import android.app.ActivityTaskManager;
 import android.content.Intent;
 import android.os.Binder;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Test;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/colorextraction/SysuiColorExtractorTests.java b/packages/SystemUI/tests/src/com/android/systemui/colorextraction/SysuiColorExtractorTests.java
index 13dc36d..1649f98 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/colorextraction/SysuiColorExtractorTests.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/colorextraction/SysuiColorExtractorTests.java
@@ -22,8 +22,9 @@
 import android.app.WallpaperColors;
 import android.app.WallpaperManager;
 import android.graphics.Color;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.colorextraction.ColorExtractor;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/AlwaysOnDisplayPolicyTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/AlwaysOnDisplayPolicyTest.java
index 0bbdeb5..ec9acdf 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/AlwaysOnDisplayPolicyTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/AlwaysOnDisplayPolicyTest.java
@@ -19,10 +19,11 @@
 import static com.google.common.truth.Truth.assertThat;
 
 import android.provider.Settings;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.text.format.DateUtils;
 
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeConfigurationTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeConfigurationTest.java
index 45342d4..20756c5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeConfigurationTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeConfigurationTest.java
@@ -18,12 +18,13 @@
 
 import static junit.framework.TestCase.assertEquals;
 
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.os.UserHandle;
 import android.provider.Settings;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeConfigurationUtil.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeConfigurationUtil.java
index e4558df..9438cbb 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeConfigurationUtil.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeConfigurationUtil.java
@@ -16,12 +16,13 @@
 
 package com.android.systemui.doze;
 
+import android.hardware.display.AmbientDisplayConfiguration;
+
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import static org.mockito.Mockito.withSettings;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.systemui.statusbar.phone.DozeParameters;
 
 import org.mockito.Answers;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeDockHandlerTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeDockHandlerTest.java
index 0fc0953..4ba2858 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeDockHandlerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeDockHandlerTest.java
@@ -27,15 +27,16 @@
 import static org.mockito.Mockito.when;
 
 import android.app.Instrumentation;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.os.Handler;
 import android.os.Looper;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.dock.DockManager;
 import com.android.systemui.dock.DockManagerFake;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java
index 5a6200f..6dfb19e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java
@@ -38,11 +38,12 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.testing.AndroidTestingRunner;
 import android.testing.UiThreadTest;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.util.wakelock.WakeLockFake;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenBrightnessTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenBrightnessTest.java
index 1cf73b0..cde3398 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenBrightnessTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenBrightnessTest.java
@@ -28,17 +28,16 @@
 import static com.android.systemui.doze.DozeMachine.State.UNINITIALIZED;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 
 import android.content.Intent;
 import android.os.PowerManager;
 import android.os.UserHandle;
 import android.provider.Settings;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.utils.hardware.FakeSensorManager;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenStatePreventingAdapterTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenStatePreventingAdapterTest.java
index a17a95f..903e4a1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenStatePreventingAdapterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenStatePreventingAdapterTest.java
@@ -22,9 +22,10 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.view.Display;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.phone.DozeParameters;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenStateTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenStateTest.java
index b6039b6..bfd448a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenStateTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenStateTest.java
@@ -30,19 +30,16 @@
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import android.os.Looper;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.view.Display;
 
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.phone.DozeParameters;
-import com.android.systemui.util.wakelock.WakeLock;
 import com.android.systemui.util.wakelock.WakeLockFake;
 import com.android.systemui.utils.os.FakeHandler;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSensorsTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSensorsTest.java
new file mode 100644
index 0000000..4467faf
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSensorsTest.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.doze;
+
+import static com.android.systemui.plugins.SensorManagerPlugin.Sensor.TYPE_WAKE_LOCK_SCREEN;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyFloat;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.app.AlarmManager;
+import android.hardware.display.AmbientDisplayConfiguration;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+import android.testing.TestableLooper.RunWithLooper;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.plugins.SensorManagerPlugin;
+import com.android.systemui.statusbar.phone.DozeParameters;
+import com.android.systemui.util.AsyncSensorManager;
+import com.android.systemui.util.wakelock.WakeLock;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.function.Consumer;
+
+@RunWith(AndroidTestingRunner.class)
+@RunWithLooper
+@SmallTest
+public class DozeSensorsTest extends SysuiTestCase {
+
+    @Mock
+    private AlarmManager mAlarmManager;
+    @Mock
+    private AsyncSensorManager mSensorManager;
+    @Mock
+    private DozeParameters mDozeParameters;
+    @Mock
+    private AmbientDisplayConfiguration mAmbientDisplayConfiguration;
+    @Mock
+    private WakeLock mWakeLock;
+    @Mock
+    private DozeSensors.Callback mCallback;
+    @Mock
+    private Consumer<Boolean> mProxCallback;
+    @Mock
+    private AlwaysOnDisplayPolicy mAlwaysOnDisplayPolicy;
+    private SensorManagerPlugin.SensorEventListener mWakeLockScreenListener;
+    private TestableLooper mTestableLooper;
+    private DozeSensors mDozeSensors;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mTestableLooper = TestableLooper.get(this);
+        when(mAmbientDisplayConfiguration.getWakeLockScreenDebounce()).thenReturn(5000L);
+        when(mAmbientDisplayConfiguration.alwaysOnEnabled(anyInt())).thenReturn(true);
+        doAnswer(invocation -> {
+            ((Runnable) invocation.getArgument(0)).run();
+            return null;
+        }).when(mWakeLock).wrap(any(Runnable.class));
+        mDozeSensors = new TestableDozeSensors();
+    }
+
+    @Test
+    public void testSensorDebounce() {
+        mDozeSensors.setListening(true);
+
+        mWakeLockScreenListener.onSensorChanged(mock(SensorManagerPlugin.SensorEvent.class));
+        mTestableLooper.processAllMessages();
+        verify(mCallback).onSensorPulse(eq(DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN),
+                anyBoolean(), anyFloat(), anyFloat(), eq(null));
+
+        mDozeSensors.requestTemporaryDisable();
+        reset(mCallback);
+        mWakeLockScreenListener.onSensorChanged(mock(SensorManagerPlugin.SensorEvent.class));
+        mTestableLooper.processAllMessages();
+        verify(mCallback, never()).onSensorPulse(eq(DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN),
+                anyBoolean(), anyFloat(), anyFloat(), eq(null));
+    }
+
+    private class TestableDozeSensors extends DozeSensors {
+
+        TestableDozeSensors() {
+            super(getContext(), mAlarmManager, mSensorManager, mDozeParameters,
+                    mAmbientDisplayConfiguration, mWakeLock, mCallback, mProxCallback,
+                    mAlwaysOnDisplayPolicy);
+            for (TriggerSensor sensor : mSensors) {
+                if (sensor instanceof PluginSensor
+                        && ((PluginSensor) sensor).mPluginSensor.getType()
+                        == TYPE_WAKE_LOCK_SCREEN) {
+                    mWakeLockScreenListener = (PluginSensor) sensor;
+                }
+            }
+        }
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSuspendScreenStatePreventingAdapterTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSuspendScreenStatePreventingAdapterTest.java
index ed93561..fac58a0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSuspendScreenStatePreventingAdapterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSuspendScreenStatePreventingAdapterTest.java
@@ -22,9 +22,10 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.view.Display;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.phone.DozeParameters;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java
index cdac7c97..8941182 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java
@@ -27,14 +27,15 @@
 
 import android.app.AlarmManager;
 import android.app.Instrumentation;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.os.Handler;
 import android.os.Looper;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.dock.DockManager;
 import com.android.systemui.dock.DockManagerFake;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeUiTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeUiTest.java
index 0d8d952..25231bc 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeUiTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeUiTest.java
@@ -27,19 +27,17 @@
 import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.clearInvocations;
-import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import android.app.AlarmManager;
 import android.os.Handler;
 import android.os.HandlerThread;
-import android.os.PowerManager;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.systemui.SysuiTestCase;
@@ -47,7 +45,6 @@
 import com.android.systemui.util.wakelock.WakeLockFake;
 
 import org.junit.After;
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -172,4 +169,4 @@
         mDozeUi.transitionTo(UNINITIALIZED, DOZE);
         verify(mHost).setAnimateWakeup(eq(false));
     }
-}
\ No newline at end of file
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeWallpaperStateTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeWallpaperStateTest.java
index 9eb94f4..beba905 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeWallpaperStateTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeWallpaperStateTest.java
@@ -24,7 +24,8 @@
 
 import android.app.IWallpaperManager;
 import android.os.RemoteException;
-import android.support.test.filters.SmallTest;
+
+import androidx.test.filters.SmallTest;
 
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.notification.stack.StackStateAnimator;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/DismissCallbackRegistryTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/DismissCallbackRegistryTest.java
index 308670d..d35fc30 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/DismissCallbackRegistryTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/DismissCallbackRegistryTest.java
@@ -19,12 +19,11 @@
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.policy.IKeyguardDismissCallback;
 import com.android.systemui.SysuiTestCase;
-import com.android.systemui.UiOffloadThread;
 
 import org.junit.Before;
 import org.junit.Test;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardSliceProviderTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardSliceProviderTest.java
index e1717be..63d42a7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardSliceProviderTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardSliceProviderTest.java
@@ -30,7 +30,6 @@
 import android.media.MediaMetadata;
 import android.net.Uri;
 import android.provider.Settings;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
@@ -41,6 +40,7 @@
 import androidx.slice.SliceSpecs;
 import androidx.slice.builders.ListBuilder;
 import androidx.slice.core.SliceQuery;
+import androidx.test.filters.SmallTest;
 
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/LifecycleTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/LifecycleTest.java
index e0807d6..50914c8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/LifecycleTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/LifecycleTest.java
@@ -19,9 +19,10 @@
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ScreenLifecycleTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ScreenLifecycleTest.java
index 8c918f6..06e597e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ScreenLifecycleTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ScreenLifecycleTest.java
@@ -21,9 +21,10 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoMoreInteractions;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/WakefulnessLifecycleTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/WakefulnessLifecycleTest.java
index 9eba9b8..1dc4150 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/WakefulnessLifecycleTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/WakefulnessLifecycleTest.java
@@ -22,9 +22,10 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoMoreInteractions;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/WorkLockActivityControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/WorkLockActivityControllerTest.java
index 199c4c2..d26ae6a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/WorkLockActivityControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/WorkLockActivityControllerTest.java
@@ -16,13 +16,13 @@
 
 package com.android.systemui.keyguard;
 
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.argThat;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.eq;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.argThat;
 
 import android.app.Activity;
 import android.app.ActivityManager;
@@ -36,13 +36,14 @@
 import android.os.Bundle;
 import android.os.IBinder;
 import android.os.UserHandle;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.shared.system.ActivityManagerWrapper;
-
 import com.android.systemui.shared.system.TaskStackChangeListener;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/WorkLockActivityTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/WorkLockActivityTest.java
index 9f3573f..6e726cf 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/WorkLockActivityTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/WorkLockActivityTest.java
@@ -17,13 +17,11 @@
 package com.android.systemui.keyguard;
 
 import static android.app.ActivityManager.TaskDescription;
+
 import static org.junit.Assert.assertEquals;
 import static org.mockito.Mockito.eq;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
-
 import android.annotation.ColorInt;
 import android.annotation.UserIdInt;
 import android.app.KeyguardManager;
@@ -33,6 +31,9 @@
 import android.graphics.Color;
 import android.os.Looper;
 
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.keyguard.WorkLockActivity;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/pip/phone/PipTouchStateTest.java b/packages/SystemUI/tests/src/com/android/systemui/pip/phone/PipTouchStateTest.java
index b7c1e8e..3155e57 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/pip/phone/PipTouchStateTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/pip/phone/PipTouchStateTest.java
@@ -26,13 +26,14 @@
 import android.os.Handler;
 import android.os.Looper;
 import android.os.SystemClock;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.MotionEvent;
 import android.view.ViewConfiguration;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/power/PowerNotificationWarningsTest.java b/packages/SystemUI/tests/src/com/android/systemui/power/PowerNotificationWarningsTest.java
index cd500b4..5876ae1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/power/PowerNotificationWarningsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/power/PowerNotificationWarningsTest.java
@@ -30,9 +30,10 @@
 
 import android.app.Notification;
 import android.app.NotificationManager;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.util.NotificationChannels;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogBuilderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogBuilderTest.kt
index b6e0d90..6302f9d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogBuilderTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogBuilderTest.kt
@@ -16,8 +16,8 @@
 
 package com.android.systemui.privacy
 
-import android.support.test.filters.SmallTest
-import android.support.test.runner.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import androidx.test.runner.AndroidJUnit4
 import com.android.systemui.SysuiTestCase
 import org.junit.Assert.assertEquals
 import org.junit.Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyItemControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyItemControllerTest.kt
index bb384dd..1783d9d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyItemControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyItemControllerTest.kt
@@ -24,7 +24,7 @@
 import android.os.Handler
 import android.os.UserHandle
 import android.os.UserManager
-import android.support.test.filters.SmallTest
+import androidx.test.filters.SmallTest
 import android.testing.AndroidTestingRunner
 import android.testing.TestableLooper
 import android.testing.TestableLooper.RunWithLooper
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/AutoAddTrackerTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/AutoAddTrackerTest.java
index dfc1852..0ae9461 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/AutoAddTrackerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/AutoAddTrackerTest.java
@@ -22,10 +22,11 @@
 import static org.junit.Assert.assertTrue;
 
 import android.provider.Settings.Secure;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.Prefs;
 import com.android.systemui.Prefs.Key;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSDetailTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSDetailTest.java
index f845f3a..8879e83 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSDetailTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSDetailTest.java
@@ -23,7 +23,6 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
@@ -31,6 +30,8 @@
 import android.view.LayoutInflater;
 import android.view.View;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSFooterImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSFooterImplTest.java
index 374a73c..a8b169c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSFooterImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSFooterImplTest.java
@@ -22,7 +22,6 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.telephony.SubscriptionManager;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
@@ -30,6 +29,8 @@
 import android.view.LayoutInflater;
 import android.view.View;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.keyguard.CarrierTextController.CarrierTextCallbackInfo;
 import com.android.systemui.R;
 import com.android.systemui.R.id;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java
index 823485f..10d1572 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java
@@ -23,7 +23,6 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Looper;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.LayoutInflaterBuilder;
 import android.testing.TestableLooper;
@@ -31,6 +30,8 @@
 import android.view.View;
 import android.widget.FrameLayout;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.keyguard.CarrierText;
 import com.android.systemui.Dependency;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSPanelTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSPanelTest.java
index 12a122a..c6b31d0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSPanelTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSPanelTest.java
@@ -23,13 +23,14 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.ViewGroup;
 import android.widget.FrameLayout;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
index 78700b8..a458928 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
@@ -19,9 +19,10 @@
 
 import static junit.framework.TestCase.assertFalse;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Test;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/SlashImageViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/SlashImageViewTest.java
index e2159d2..ea8c64a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/SlashImageViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/SlashImageViewTest.java
@@ -16,26 +16,25 @@
 
 package com.android.systemui.qs;
 
-import android.content.Context;
-import android.graphics.drawable.Drawable;
-import android.support.test.filters.SmallTest;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper.RunWithLooper;
-import com.android.systemui.SysuiTestCase;
-import com.android.systemui.plugins.qs.QSTile.SlashState;
-import com.android.systemui.qs.tileimpl.SlashImageView;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import android.content.Context;
+import android.graphics.drawable.Drawable;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper.RunWithLooper;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.plugins.qs.QSTile.SlashState;
+import com.android.systemui.qs.tileimpl.SlashImageView;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @SmallTest
 @RunWith(AndroidTestingRunner.class)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/TileLayoutTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/TileLayoutTest.java
index 2040e75..fef47bd 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/TileLayoutTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/TileLayoutTest.java
@@ -27,12 +27,12 @@
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
-import com.android.systemui.plugins.qs.QSIconView;
 import com.android.systemui.plugins.qs.QSTile;
 import com.android.systemui.qs.tileimpl.QSIconViewImpl;
 import com.android.systemui.qs.tileimpl.QSTileView;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/TouchAnimatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/TouchAnimatorTest.java
index 4cc0e20..c43c3e6 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/TouchAnimatorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/TouchAnimatorTest.java
@@ -14,17 +14,20 @@
 
 package com.android.systemui.qs;
 
-import android.support.test.runner.AndroidJUnit4;
+import static junit.framework.Assert.assertEquals;
+
 import android.test.suitebuilder.annotation.SmallTest;
 import android.view.View;
-import com.android.systemui.qs.TouchAnimator.Listener;
-import com.android.systemui.SysuiTestCase;
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.junit.Test;
-import org.mockito.Mockito;
 
-import static junit.framework.Assert.assertEquals;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.qs.TouchAnimator.Listener;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
 
 @SmallTest
 @RunWith(AndroidJUnit4.class)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileAdapterTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileAdapterTest.java
index 0239ab0..25bac7a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileAdapterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileAdapterTest.java
@@ -18,11 +18,12 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.qs.QSTileHost;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileQueryHelperTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileQueryHelperTest.java
index c3a3e63..12eed78 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileQueryHelperTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileQueryHelperTest.java
@@ -31,13 +31,14 @@
 
 import android.content.pm.PackageManager;
 import android.provider.Settings;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.text.TextUtils;
 import android.util.ArraySet;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileColorPickerTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileColorPickerTest.java
index ba451e1..ec8552b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileColorPickerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileColorPickerTest.java
@@ -15,17 +15,20 @@
  */
 package com.android.systemui.qs.external;
 
+import static junit.framework.Assert.assertEquals;
+
 import android.content.res.ColorStateList;
 import android.service.quicksettings.Tile;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import com.android.systemui.R;
-
-import static junit.framework.Assert.assertEquals;
 
 @SmallTest
 @RunWith(AndroidJUnit4.class)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileLifecycleManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileLifecycleManagerTest.java
index e5e8ae3..f35295c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileLifecycleManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileLifecycleManagerTest.java
@@ -40,9 +40,10 @@
 import android.service.quicksettings.IQSTileService;
 import android.service.quicksettings.Tile;
 import android.service.quicksettings.TileService;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.After;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileServiceManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileServiceManagerTest.java
index cc743245..683e8f4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileServiceManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileServiceManagerTest.java
@@ -15,12 +15,19 @@
  */
 package com.android.systemui.qs.external;
 
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
 import android.content.ComponentName;
 import android.os.Handler;
 import android.os.HandlerThread;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
+
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -28,10 +35,6 @@
 import org.mockito.ArgumentCaptor;
 import org.mockito.Mockito;
 
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertTrue;
-
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class TileServiceManagerTest extends SysuiTestCase {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSIconViewImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSIconViewImplTest.java
index c5e4043..8a36cfb 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSIconViewImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSIconViewImplTest.java
@@ -21,14 +21,14 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.content.res.ColorStateList;
 import android.graphics.drawable.Drawable;
 import android.service.quicksettings.Tile;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.UiThreadTest;
 import android.widget.ImageView;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.qs.QSTile.Icon;
 import com.android.systemui.plugins.qs.QSTile.State;
@@ -36,7 +36,6 @@
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.ArgumentMatcher;
 
 @RunWith(AndroidTestingRunner.class)
 @UiThreadTest
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSTileImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSTileImplTest.java
index 86f6cd3..3df8a8a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSTileImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSTileImplTest.java
@@ -34,15 +34,14 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import static java.lang.Thread.sleep;
-
 import android.content.Intent;
 import android.metrics.LogMaker;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.Dependency;
 import com.android.systemui.SysuiTestCase;
@@ -61,6 +60,8 @@
 import org.mockito.Captor;
 import org.mockito.MockitoAnnotations;
 
+import static java.lang.Thread.sleep;
+
 @RunWith(AndroidTestingRunner.class)
 @RunWithLooper
 @SmallTest
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/CastTileTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/CastTileTest.java
index efcbb76..ea8d4b2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/CastTileTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/CastTileTest.java
@@ -22,11 +22,11 @@
 import static org.mockito.Mockito.when;
 
 import android.service.quicksettings.Tile;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
 import androidx.lifecycle.LifecycleOwner;
+import androidx.test.filters.SmallTest;
 
 import com.android.systemui.Dependency;
 import com.android.systemui.SysuiTestCase;
@@ -46,7 +46,6 @@
 import java.util.HashSet;
 import java.util.Set;
 
-
 @RunWith(AndroidTestingRunner.class)
 @TestableLooper.RunWithLooper
 @SmallTest
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/SensorPrivacyTileTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/SensorPrivacyTileTest.java
index 751a616..6386c4c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/SensorPrivacyTileTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/SensorPrivacyTileTest.java
@@ -22,10 +22,11 @@
 import static org.mockito.Mockito.when;
 
 import android.hardware.SensorPrivacyManager;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.Dependency;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.ActivityStarter;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/settings/CurrentUserTrackerTest.java b/packages/SystemUI/tests/src/com/android/systemui/settings/CurrentUserTrackerTest.java
index 17d7a41..4162bc1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/settings/CurrentUserTrackerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/settings/CurrentUserTrackerTest.java
@@ -17,7 +17,8 @@
 package com.android.systemui.settings;
 
 import android.content.Intent;
-import android.support.test.filters.SmallTest;
+
+import androidx.test.filters.SmallTest;
 
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shared/plugins/PluginInstanceManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/shared/plugins/PluginInstanceManagerTest.java
index 3415c72..7d95563 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shared/plugins/PluginInstanceManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/shared/plugins/PluginInstanceManagerTest.java
@@ -41,10 +41,11 @@
 import android.content.pm.ServiceInfo;
 import android.os.HandlerThread;
 import android.os.UserHandle;
-import android.support.test.annotation.UiThreadTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.annotation.UiThreadTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.Plugin;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shared/plugins/VersionInfoTest.java b/packages/SystemUI/tests/src/com/android/systemui/shared/plugins/VersionInfoTest.java
index 9bad78d..218e7db 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shared/plugins/VersionInfoTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/shared/plugins/VersionInfoTest.java
@@ -17,15 +17,15 @@
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
-import android.support.test.filters.SmallTest;
+import androidx.test.filters.SmallTest;
 
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.OverlayPlugin;
-import com.android.systemui.shared.plugins.VersionInfo.InvalidVersionException;
 import com.android.systemui.plugins.annotations.Requires;
-import com.android.systemui.plugins.qs.QS;
 import com.android.systemui.plugins.qs.DetailAdapter;
+import com.android.systemui.plugins.qs.QS;
 import com.android.systemui.plugins.qs.QS.HeightListener;
+import com.android.systemui.shared.plugins.VersionInfo.InvalidVersionException;
 
 import org.junit.Rule;
 import org.junit.Test;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java
index 7b1253a..5c1f473 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java
@@ -32,16 +32,16 @@
 import android.os.Looper;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 
-
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/AmbientPulseManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/AmbientPulseManagerTest.java
index f0344e6..0b25a7c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/AmbientPulseManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/AmbientPulseManagerTest.java
@@ -19,10 +19,11 @@
 import static junit.framework.Assert.assertFalse;
 import static junit.framework.Assert.assertTrue;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java
index 51d94f0..dd26368 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java
@@ -25,7 +25,8 @@
 import android.content.ComponentName;
 import android.graphics.Rect;
 import android.os.Bundle;
-import android.support.test.filters.SmallTest;
+
+import androidx.test.filters.SmallTest;
 
 import com.android.internal.statusbar.StatusBarIcon;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java
index aae6d93..18ffbb5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java
@@ -33,12 +33,13 @@
 import android.graphics.Color;
 import android.hardware.fingerprint.FingerprintManager;
 import android.os.Looper;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.view.View;
 import android.view.ViewGroup;
 
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.keyguard.KeyguardUpdateMonitorCallback;
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NonPhoneDependencyTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NonPhoneDependencyTest.java
index 8e926848..42f476b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NonPhoneDependencyTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NonPhoneDependencyTest.java
@@ -19,10 +19,11 @@
 import static org.junit.Assert.assertFalse;
 
 import android.os.Handler;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.Dependency;
 import com.android.systemui.InitController;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java
index cffa9c7..2a01356 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java
@@ -27,10 +27,11 @@
 import android.os.UserHandle;
 import android.service.notification.NotificationListenerService;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.Dependency;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.notification.NotificationEntryManager;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java
index d7ca5b4..490b2ea 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java
@@ -35,10 +35,11 @@
 import android.os.Looper;
 import android.os.UserManager;
 import android.provider.Settings;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.Dependency;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.notification.NotificationEntryManager;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationRemoteInputManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationRemoteInputManagerTest.java
index c159516..b81e048 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationRemoteInputManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationRemoteInputManagerTest.java
@@ -16,10 +16,11 @@
 import android.os.UserHandle;
 import android.service.notification.NotificationListenerService;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.NotificationRemoteInputManager.RemoteInputActiveExtender;
 import com.android.systemui.statusbar.NotificationRemoteInputManager.RemoteInputHistoryExtender;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java
index 3c919a1..cef78db 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java
@@ -30,11 +30,12 @@
 import android.graphics.drawable.Icon;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.InstrumentationRegistry;
 import android.text.TextUtils;
 import android.view.LayoutInflater;
 import android.widget.RemoteViews;
 
+import androidx.test.InstrumentationRegistry;
+
 import com.android.systemui.R;
 import com.android.systemui.bubbles.BubblesTestActivity;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationUiAdjustmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationUiAdjustmentTest.java
index db1e049..f63389c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationUiAdjustmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationUiAdjustmentTest.java
@@ -22,7 +22,8 @@
 import android.app.RemoteInput;
 import android.content.Intent;
 import android.graphics.drawable.Icon;
-import android.support.test.filters.SmallTest;
+
+import androidx.test.filters.SmallTest;
 
 import com.android.internal.R;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationViewHierarchyManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationViewHierarchyManagerTest.java
index 62700c0..6b2e05b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationViewHierarchyManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationViewHierarchyManagerTest.java
@@ -26,13 +26,14 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.LinearLayout;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.Dependency;
 import com.android.systemui.InitController;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/ScrimViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/ScrimViewTest.java
index c2611e4..2020d4b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/ScrimViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/ScrimViewTest.java
@@ -18,23 +18,17 @@
 
 import static junit.framework.Assert.assertEquals;
 
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import android.graphics.Canvas;
 import android.graphics.Color;
-import android.graphics.Rect;
 import android.graphics.drawable.ColorDrawable;
 import android.graphics.drawable.Drawable;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.testing.ViewUtils;
 import android.view.View;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.colorextraction.ColorExtractor;
 import com.android.internal.colorextraction.drawable.GradientDrawable;
 import com.android.systemui.statusbar.policy.ConfigurationController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java
index 31cd280..81e373a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java
@@ -29,10 +29,11 @@
 import android.os.RemoteException;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.internal.statusbar.IStatusBarService;
 import com.android.systemui.R;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarIconListTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarIconListTest.java
index e529e4c..4c20b61 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarIconListTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarIconListTest.java
@@ -1,6 +1,7 @@
 package com.android.systemui.statusbar;
 
 import static com.android.systemui.statusbar.phone.StatusBarIconController.TAG_PRIMARY;
+
 import static junit.framework.Assert.assertEquals;
 import static junit.framework.Assert.assertNull;
 import static junit.framework.Assert.assertTrue;
@@ -8,19 +9,21 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.phone.StatusBarIconHolder;
 import com.android.systemui.statusbar.phone.StatusBarIconList;
 import com.android.systemui.statusbar.phone.StatusBarIconList.Slot;
 
-import java.util.ArrayList;
-import java.util.List;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.ArrayList;
+import java.util.List;
+
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class StatusBarIconListTest extends SysuiTestCase {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarIconViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarIconViewTest.java
index 8fee107..9971e0c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarIconViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarIconViewTest.java
@@ -38,8 +38,9 @@
 import android.graphics.Color;
 import android.graphics.drawable.Icon;
 import android.os.UserHandle;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.statusbar.StatusBarIcon;
 import com.android.internal.util.ContrastColorUtil;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/MediaNotificationProcessorTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/MediaNotificationProcessorTest.java
index 5d3a86d..b03abec 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/MediaNotificationProcessorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/MediaNotificationProcessorTest.java
@@ -27,10 +27,11 @@
 import android.app.Notification;
 import android.graphics.Bitmap;
 import android.graphics.drawable.Drawable;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.widget.RemoteViews;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
index 04e7cab..5543744 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
@@ -42,13 +42,13 @@
 import android.os.UserHandle;
 import android.service.notification.NotificationListenerService;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.util.ArraySet;
 import android.widget.FrameLayout;
 
 import androidx.annotation.NonNull;
+import androidx.test.filters.SmallTest;
 
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.Dependency;
@@ -67,6 +67,8 @@
 import com.android.systemui.statusbar.notification.collection.NotificationData;
 import com.android.systemui.statusbar.notification.collection.NotificationData.KeyguardEnvironment;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationRowBinder;
+import com.android.systemui.statusbar.notification.collection.NotificationRowBinderImpl;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.row.NotificationContentInflater.InflationFlag;
 import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
@@ -102,10 +104,8 @@
     @Mock private KeyguardEnvironment mEnvironment;
     @Mock private ExpandableNotificationRow mRow;
     @Mock private NotificationListContainer mListContainer;
-    @Mock
-    private NotificationEntryListener mEntryListener;
-    @Mock
-    private NotificationRowBinder.BindRowCallback mBindCallback;
+    @Mock private NotificationEntryListener mEntryListener;
+    @Mock private NotificationRowBinderImpl.BindRowCallback mBindCallback;
     @Mock private HeadsUpManager mHeadsUpManager;
     @Mock private NotificationListenerService.RankingMap mRankingMap;
     @Mock private RemoteInputController mRemoteInputController;
@@ -235,10 +235,12 @@
         mEntryManager.setUpWithPresenter(mPresenter, mListContainer, mHeadsUpManager);
         mEntryManager.addNotificationEntryListener(mEntryListener);
 
-        NotificationRowBinder notificationRowBinder = Dependency.get(NotificationRowBinder.class);
+        NotificationRowBinderImpl notificationRowBinder =
+                new NotificationRowBinderImpl(mContext, true /* allowLongPress */);
         notificationRowBinder.setUpWithPresenter(
                 mPresenter, mListContainer, mHeadsUpManager, mEntryManager, mBindCallback);
         notificationRowBinder.setNotificationClicker(mock(NotificationClicker.class));
+        mEntryManager.setRowBinder(notificationRowBinder);
 
         setUserSentiment(mEntry.key, NotificationListenerService.Ranking.USER_SENTIMENT_NEUTRAL);
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationFilterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationFilterTest.java
index 387475f..91a7ea8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationFilterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationFilterTest.java
@@ -31,12 +31,13 @@
 import android.content.pm.PackageManager;
 import android.os.Bundle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.annotation.UiThreadTest;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.annotation.UiThreadTest;
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.ForegroundServiceController;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.NotificationTestHelper;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java
index 4b5037b..311b81c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java
@@ -31,11 +31,12 @@
 import android.app.Notification;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.util.ArraySet;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.statusbar.NotificationVisibility;
 import com.android.systemui.ForegroundServiceController;
 import com.android.systemui.R;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/VisualStabilityManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/VisualStabilityManagerTest.java
index 813fc9d..b35dcb6 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/VisualStabilityManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/VisualStabilityManagerTest.java
@@ -24,9 +24,10 @@
 import static org.mockito.Mockito.when;
 
 import android.service.notification.StatusBarNotification;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.NotificationPresenter;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationDataTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationDataTest.java
index 9f36a1e..79a6ac4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationDataTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationDataTest.java
@@ -35,7 +35,6 @@
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -57,12 +56,13 @@
 import android.service.notification.NotificationListenerService.Ranking;
 import android.service.notification.SnoozeCriterion;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.util.ArraySet;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.Dependency;
 import com.android.systemui.ForegroundServiceController;
 import com.android.systemui.InitController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/ExpansionStateLoggerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/ExpansionStateLoggerTest.java
index f1d9003..2b343c2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/ExpansionStateLoggerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/ExpansionStateLoggerTest.java
@@ -22,10 +22,11 @@
 import static org.mockito.Mockito.verify;
 
 import android.os.RemoteException;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.statusbar.IStatusBarService;
 import com.android.internal.statusbar.NotificationVisibility;
 import com.android.systemui.Dependency;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java
index d47700b..5e587f8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java
@@ -30,10 +30,11 @@
 import android.os.Looper;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.statusbar.IStatusBarService;
 import com.android.internal.statusbar.NotificationVisibility;
 import com.android.systemui.Dependency;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java
index f6fb416..0aa103f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java
@@ -38,7 +38,6 @@
 
 import android.app.AppOpsManager;
 import android.app.NotificationChannel;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
@@ -46,6 +45,8 @@
 import android.view.NotificationHeaderView;
 import android.view.View;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
 import com.android.systemui.statusbar.NotificationTestHelper;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/FooterViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/FooterViewTest.java
index aa7889a..2336958 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/FooterViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/FooterViewTest.java
@@ -16,23 +16,18 @@
 
 package com.android.systemui.statusbar.notification.row;
 
-import static junit.framework.Assert.assertEquals;
 import static junit.framework.Assert.assertFalse;
 import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertNull;
 import static junit.framework.Assert.assertTrue;
 
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
 
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.view.LayoutInflater;
 import android.view.View;
 
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationBlockingHelperManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationBlockingHelperManagerTest.java
index 669b98e1..4fe364a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationBlockingHelperManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationBlockingHelperManagerTest.java
@@ -30,12 +30,13 @@
 import static org.mockito.Mockito.when;
 
 import android.content.Context;
-import android.support.test.filters.FlakyTest;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.view.View;
 
+import androidx.test.filters.FlakyTest;
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
 import com.android.systemui.statusbar.NotificationTestHelper;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java
index 99dc9f8..025296d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java
@@ -36,7 +36,6 @@
 import android.os.Handler;
 import android.os.Looper;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.util.ArrayMap;
@@ -44,6 +43,8 @@
 import android.view.ViewGroup;
 import android.widget.RemoteViews;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.InflationTask;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentViewTest.java
index c80396d..5cd0ca7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentViewTest.java
@@ -16,8 +16,6 @@
 
 package com.android.systemui.statusbar.notification.row;
 
-import static com.google.common.truth.Truth.assertThat;
-
 import static org.junit.Assert.assertFalse;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyFloat;
@@ -31,62 +29,32 @@
 import static org.mockito.Mockito.when;
 
 import android.app.AppOpsManager;
-import android.app.Notification;
-import android.app.PendingIntent;
-import android.app.RemoteInput;
-import android.content.Intent;
 import android.graphics.drawable.Icon;
-import android.service.notification.StatusBarNotification;
-import android.support.test.annotation.UiThreadTest;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.util.ArraySet;
-import android.util.Pair;
 import android.view.NotificationHeaderView;
 import android.view.View;
 
-import com.android.systemui.R;
+import androidx.test.annotation.UiThreadTest;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
-import com.android.systemui.statusbar.notification.collection.NotificationEntry;
-import com.android.systemui.statusbar.policy.SmartReplyConstants;
 
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.ArrayList;
-import java.util.List;
 
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class NotificationContentViewTest extends SysuiTestCase {
 
-    private static final String TEST_ACTION = "com.android.SMART_REPLY_VIEW_ACTION";
-
     NotificationContentView mView;
 
-    @Mock
-    SmartReplyConstants mSmartReplyConstants;
-    @Mock
-    StatusBarNotification mStatusBarNotification;
-    @Mock
-    Notification mNotification;
-    NotificationEntry mEntry;
-    @Mock
-    RemoteInput mRemoteInput;
-    @Mock
-    RemoteInput mFreeFormRemoteInput;
-
     private Icon mActionIcon;
 
-
     @Before
     @UiThreadTest
     public void setup() {
-        MockitoAnnotations.initMocks(this);
-
         mView = new NotificationContentView(mContext, null);
         ExpandableNotificationRow row = new ExpandableNotificationRow(mContext, null);
         ExpandableNotificationRow mockRow = spy(row);
@@ -103,13 +71,6 @@
 
         mView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
         mView.layout(0, 0, mView.getMeasuredWidth(), mView.getMeasuredHeight());
-
-        // Smart replies and actions
-        when(mNotification.getAllowSystemGeneratedContextualActions()).thenReturn(true);
-        when(mStatusBarNotification.getNotification()).thenReturn(mNotification);
-        mEntry = new NotificationEntry(mStatusBarNotification);
-        when(mSmartReplyConstants.isEnabled()).thenReturn(true);
-        mActionIcon = Icon.createWithResource(mContext, R.drawable.ic_person);
     }
 
     private View createViewWithHeight(int height) {
@@ -158,204 +119,4 @@
         verify(mockAmbient, never()).showAppOpsIcons(ops);
         verify(mockHeadsUp, times(1)).showAppOpsIcons(any());
     }
-
-    private void setupAppGeneratedReplies(CharSequence[] smartReplies) {
-        setupAppGeneratedReplies(smartReplies, true /* allowSystemGeneratedReplies */);
-    }
-
-    private void setupAppGeneratedReplies(
-            CharSequence[] smartReplies, boolean allowSystemGeneratedReplies) {
-        PendingIntent pendingIntent =
-                PendingIntent.getBroadcast(mContext, 0, new Intent(TEST_ACTION), 0);
-        Notification.Action action =
-                new Notification.Action.Builder(null, "Test Action", pendingIntent).build();
-        when(mRemoteInput.getChoices()).thenReturn(smartReplies);
-        Pair<RemoteInput, Notification.Action> remoteInputActionPair =
-                Pair.create(mRemoteInput, action);
-        when(mNotification.findRemoteInputActionPair(false)).thenReturn(remoteInputActionPair);
-
-        Notification.Action freeFormRemoteInputAction =
-                createActionBuilder("Freeform Test Action")
-                .setAllowGeneratedReplies(allowSystemGeneratedReplies)
-                .build();
-        Pair<RemoteInput, Notification.Action> freeFormRemoteInputActionPair =
-                Pair.create(mFreeFormRemoteInput, freeFormRemoteInputAction);
-        when(mNotification.findRemoteInputActionPair(true)).thenReturn(
-                freeFormRemoteInputActionPair);
-
-        when(mSmartReplyConstants.requiresTargetingP()).thenReturn(false);
-    }
-
-    private void setupAppGeneratedSuggestions(
-            CharSequence[] smartReplies, List<Notification.Action> smartActions) {
-        setupAppGeneratedReplies(smartReplies);
-        when(mNotification.getContextualActions()).thenReturn(smartActions);
-    }
-
-    @Test
-    public void chooseSmartRepliesAndActions_smartRepliesOff_noAppGeneratedSmartSuggestions() {
-        CharSequence[] smartReplies = new String[] {"Reply1", "Reply2"};
-        List<Notification.Action> smartActions =
-                createActions(new String[] {"Test Action 1", "Test Action 2"});
-        setupAppGeneratedSuggestions(smartReplies, smartActions);
-        when(mSmartReplyConstants.isEnabled()).thenReturn(false);
-
-        NotificationContentView.SmartRepliesAndActions repliesAndActions =
-                NotificationContentView.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
-
-        assertThat(repliesAndActions.smartReplies).isNull();
-        assertThat(repliesAndActions.smartActions).isNull();
-    }
-
-    @Test
-    public void chooseSmartRepliesAndActions_smartRepliesOff_noSystemGeneratedSmartSuggestions() {
-        mEntry.systemGeneratedSmartReplies =
-                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
-        mEntry.systemGeneratedSmartActions =
-                createActions(new String[] {"Sys Smart Action 1", "Sys Smart Action 2"});
-        when(mSmartReplyConstants.isEnabled()).thenReturn(false);
-
-        NotificationContentView.SmartRepliesAndActions repliesAndActions =
-                NotificationContentView.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
-
-        assertThat(repliesAndActions.smartReplies).isNull();
-        assertThat(repliesAndActions.smartActions).isNull();
-    }
-
-    @Test
-    public void chooseSmartRepliesAndActions_appGeneratedSmartReplies() {
-        CharSequence[] smartReplies = new String[] {"Reply1", "Reply2"};
-        setupAppGeneratedReplies(smartReplies);
-
-        NotificationContentView.SmartRepliesAndActions repliesAndActions =
-                NotificationContentView.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
-
-        assertThat(repliesAndActions.smartReplies.choices).isEqualTo(smartReplies);
-        assertThat(repliesAndActions.smartReplies.fromAssistant).isFalse();
-        assertThat(repliesAndActions.smartActions).isNull();
-    }
-
-    @Test
-    public void chooseSmartRepliesAndActions_appGeneratedSmartRepliesAndActions() {
-        CharSequence[] smartReplies = new String[] {"Reply1", "Reply2"};
-        List<Notification.Action> smartActions =
-                createActions(new String[] {"Test Action 1", "Test Action 2"});
-        setupAppGeneratedSuggestions(smartReplies, smartActions);
-
-        NotificationContentView.SmartRepliesAndActions repliesAndActions =
-                NotificationContentView.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
-
-        assertThat(repliesAndActions.smartReplies.choices).isEqualTo(smartReplies);
-        assertThat(repliesAndActions.smartReplies.fromAssistant).isFalse();
-        assertThat(repliesAndActions.smartActions.actions).isEqualTo(smartActions);
-        assertThat(repliesAndActions.smartActions.fromAssistant).isFalse();
-    }
-
-    @Test
-    public void chooseSmartRepliesAndActions_sysGeneratedSmartReplies() {
-        // Pass a null-array as app-generated smart replies, so that we use NAS-generated smart
-        // replies.
-        setupAppGeneratedReplies(null /* smartReplies */);
-
-        mEntry.systemGeneratedSmartReplies =
-                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
-        NotificationContentView.SmartRepliesAndActions repliesAndActions =
-                NotificationContentView.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
-
-        assertThat(repliesAndActions.smartReplies.choices).isEqualTo(
-                mEntry.systemGeneratedSmartReplies);
-        assertThat(repliesAndActions.smartReplies.fromAssistant).isTrue();
-        assertThat(repliesAndActions.smartActions).isNull();
-    }
-
-    @Test
-    public void chooseSmartRepliesAndActions_noSysGeneratedSmartRepliesIfNotAllowed() {
-        // Pass a null-array as app-generated smart replies, so that we use NAS-generated smart
-        // replies.
-        setupAppGeneratedReplies(null /* smartReplies */, false /* allowSystemGeneratedReplies */);
-
-        mEntry.systemGeneratedSmartReplies =
-                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
-        NotificationContentView.SmartRepliesAndActions repliesAndActions =
-                NotificationContentView.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
-
-        assertThat(repliesAndActions.smartReplies).isNull();
-        assertThat(repliesAndActions.smartActions).isNull();
-    }
-
-    @Test
-    public void chooseSmartRepliesAndActions_sysGeneratedSmartActions() {
-        // Pass a null-array as app-generated smart replies, so that we use NAS-generated smart
-        // actions.
-        setupAppGeneratedReplies(null /* smartReplies */);
-
-        mEntry.systemGeneratedSmartActions =
-                createActions(new String[] {"Sys Smart Action 1", "Sys Smart Action 2"});
-        NotificationContentView.SmartRepliesAndActions repliesAndActions =
-                NotificationContentView.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
-
-        assertThat(repliesAndActions.smartReplies).isNull();
-        assertThat(repliesAndActions.smartActions.actions)
-                .isEqualTo(mEntry.systemGeneratedSmartActions);
-        assertThat(repliesAndActions.smartActions.fromAssistant).isTrue();
-    }
-
-    @Test
-    public void chooseSmartRepliesAndActions_appGenPreferredOverSysGen() {
-        CharSequence[] appGenSmartReplies = new String[] {"Reply1", "Reply2"};
-        // Pass a null-array as app-generated smart replies, so that we use NAS-generated smart
-        // replies.
-        List<Notification.Action> appGenSmartActions =
-                createActions(new String[] {"Test Action 1", "Test Action 2"});
-        setupAppGeneratedSuggestions(appGenSmartReplies, appGenSmartActions);
-
-        mEntry.systemGeneratedSmartReplies =
-                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
-        mEntry.systemGeneratedSmartActions =
-                createActions(new String[] {"Sys Smart Action 1", "Sys Smart Action 2"});
-
-        NotificationContentView.SmartRepliesAndActions repliesAndActions =
-                NotificationContentView.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
-
-        assertThat(repliesAndActions.smartReplies.choices).isEqualTo(appGenSmartReplies);
-        assertThat(repliesAndActions.smartReplies.fromAssistant).isFalse();
-        assertThat(repliesAndActions.smartActions.actions).isEqualTo(appGenSmartActions);
-        assertThat(repliesAndActions.smartActions.fromAssistant).isFalse();
-    }
-
-    @Test
-    public void chooseSmartRepliesAndActions_disallowSysGenSmartActions() {
-        // Pass a null-array as app-generated smart replies, so that we use NAS-generated smart
-        // actions.
-        setupAppGeneratedReplies(null /* smartReplies */, false /* allowSystemGeneratedReplies */);
-        when(mNotification.getAllowSystemGeneratedContextualActions()).thenReturn(false);
-        mEntry.systemGeneratedSmartReplies =
-                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
-        mEntry.systemGeneratedSmartActions =
-                createActions(new String[] {"Sys Smart Action 1", "Sys Smart Action 2"});
-
-        NotificationContentView.SmartRepliesAndActions repliesAndActions =
-                NotificationContentView.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
-
-        assertThat(repliesAndActions.smartActions).isNull();
-        assertThat(repliesAndActions.smartReplies).isNull();
-    }
-
-    private Notification.Action.Builder createActionBuilder(String actionTitle) {
-        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0,
-                new Intent(TEST_ACTION), 0);
-        return new Notification.Action.Builder(mActionIcon, actionTitle, pendingIntent);
-    }
-
-    private Notification.Action createAction(String actionTitle) {
-        return createActionBuilder(actionTitle).build();
-    }
-
-    private List<Notification.Action> createActions(String[] actionTitles) {
-        List<Notification.Action> actions = new ArrayList<>();
-        for (String title : actionTitles) {
-            actions.add(createAction(title));
-        }
-        return actions;
-    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java
index 727e9af..785d5b0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java
@@ -49,12 +49,13 @@
 import android.os.Handler;
 import android.provider.Settings;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.util.ArraySet;
 import android.view.View;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationMenuRowTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationMenuRowTest.java
index 04d7509..e6389c4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationMenuRowTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationMenuRowTest.java
@@ -27,13 +27,14 @@
 
 import android.app.NotificationChannel;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.testing.ViewUtils;
 import android.view.ViewGroup;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.utils.leaks.LeakCheckedTest;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationCustomViewWrapperTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationCustomViewWrapperTest.java
index fed66af..63e18ce 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationCustomViewWrapperTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationCustomViewWrapperTest.java
@@ -16,13 +16,14 @@
 
 package com.android.systemui.statusbar.notification.row.wrapper;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.View;
 import android.widget.RemoteViews;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.NotificationTestHelper;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationViewWrapperTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationViewWrapperTest.java
index 637b30c..5463159 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationViewWrapperTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationViewWrapperTest.java
@@ -19,7 +19,6 @@
 import static org.mockito.Mockito.mock;
 
 import android.content.Context;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
@@ -27,6 +26,8 @@
 import android.widget.LinearLayout;
 import android.widget.TextView;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.NotificationTestHelper;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainerTest.java
index bbafb4e..eb465676 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainerTest.java
@@ -16,13 +16,14 @@
 
 package com.android.systemui.statusbar.notification.stack;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.NotificationHeaderView;
 import android.view.View;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.NotificationTestHelper;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationRoundnessManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationRoundnessManagerTest.java
index ff30a4d..1b4acd7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationRoundnessManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationRoundnessManagerTest.java
@@ -23,16 +23,16 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.AmbientPulseManager;
 import com.android.systemui.statusbar.NotificationTestHelper;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
-import com.android.systemui.statusbar.notification.row.ActivatableNotificationView;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.row.ExpandableView;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
index d835082..85eb8be 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
@@ -38,11 +38,12 @@
 
 import android.metrics.LogMaker;
 import android.provider.Settings;
-import android.support.test.annotation.UiThreadTest;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.view.View;
 
+import androidx.test.annotation.UiThreadTest;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto;
 import com.android.systemui.Dependency;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationSwipeHelperTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationSwipeHelperTest.java
index db39373..84a0d3c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationSwipeHelperTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationSwipeHelperTest.java
@@ -31,12 +31,13 @@
 import android.animation.ValueAnimator.AnimatorUpdateListener;
 import android.os.Handler;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.view.MotionEvent;
 import android.view.View;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SwipeHelper;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/AutoTileManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/AutoTileManagerTest.java
index f3740c4..1248cbb 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/AutoTileManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/AutoTileManagerTest.java
@@ -16,6 +16,7 @@
 
 package com.android.systemui.statusbar.phone;
 
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
@@ -23,14 +24,17 @@
 import android.hardware.display.ColorDisplayManager;
 import android.hardware.display.NightDisplayListener;
 import android.os.Handler;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.qs.AutoAddTracker;
 import com.android.systemui.qs.QSTileHost;
+import com.android.systemui.statusbar.policy.CastController;
+import com.android.systemui.statusbar.policy.CastController.CastDevice;
 import com.android.systemui.statusbar.policy.DataSaverController;
 import com.android.systemui.statusbar.policy.HotspotController;
 
@@ -40,6 +44,9 @@
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
+import java.util.Collections;
+import java.util.Set;
+
 @RunWith(AndroidTestingRunner.class)
 @RunWithLooper
 @SmallTest
@@ -47,6 +54,7 @@
 
     @Mock private QSTileHost mQsTileHost;
     @Mock private AutoAddTracker mAutoAddTracker;
+    @Mock private CastController mCastController;
 
     private AutoTileManager mAutoTileManager;
 
@@ -58,7 +66,8 @@
                 mock(HotspotController.class),
                 mock(DataSaverController.class),
                 mock(ManagedProfileController.class),
-                mock(NightDisplayListener.class));
+                mock(NightDisplayListener.class),
+                mCastController);
     }
 
     @Test
@@ -108,4 +117,24 @@
                 ColorDisplayManager.AUTO_MODE_DISABLED);
         verify(mQsTileHost, never()).addTile("night");
     }
+
+    private static Set<CastDevice> buildFakeCastDevice(boolean isCasting) {
+        CastDevice cd = new CastDevice();
+        cd.state = isCasting ? CastDevice.STATE_CONNECTED : CastDevice.STATE_DISCONNECTED;
+        return Collections.singleton(cd);
+    }
+
+    @Test
+    public void castTileAdded_whenDeviceIsCasting() {
+        doReturn(buildFakeCastDevice(true)).when(mCastController).getCastDevices();
+        mAutoTileManager.mCastCallback.onCastDevicesChanged();
+        verify(mQsTileHost).addTile("cast");
+    }
+
+    @Test
+    public void castTileNotAdded_whenDeviceIsNotCasting() {
+        doReturn(buildFakeCastDevice(false)).when(mCastController).getCastDevices();
+        mAutoTileManager.mCastCallback.onCastDevicesChanged();
+        verify(mQsTileHost, never()).addTile("cast");
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CollapsedStatusBarFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CollapsedStatusBarFragmentTest.java
index 3c5425c..33af96f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CollapsedStatusBarFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CollapsedStatusBarFragmentTest.java
@@ -24,12 +24,13 @@
 import static org.mockito.Mockito.when;
 
 import android.app.StatusBarManager;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.View;
 import android.view.ViewPropertyAnimator;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.R;
 import com.android.systemui.SysuiBaseFragmentTest;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ConfigurationControllerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ConfigurationControllerImplTest.kt
index 0d13e97..fee3ccb 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ConfigurationControllerImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ConfigurationControllerImplTest.kt
@@ -14,7 +14,7 @@
 
 package com.android.systemui.statusbar.phone
 
-import android.support.test.filters.SmallTest
+import androidx.test.filters.SmallTest
 import android.testing.AndroidTestingRunner
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.statusbar.policy.ConfigurationController.ConfigurationListener
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/DozeParametersTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/DozeParametersTest.java
index 532019f..f6f4eb48 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/DozeParametersTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/DozeParametersTest.java
@@ -16,11 +16,21 @@
 
 package com.android.systemui.statusbar.phone;
 
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+import static junit.framework.Assert.fail;
+
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+
 import android.content.Context;
 import android.os.PowerManager;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.doze.DozeScreenState;
 import com.android.systemui.statusbar.phone.DozeParameters.IntInOutMatcher;
@@ -29,18 +39,6 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.fail;
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class DozeParametersTest extends SysuiTestCase {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/DozeScrimControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/DozeScrimControllerTest.java
index fe36b6d..20c739f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/DozeScrimControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/DozeScrimControllerTest.java
@@ -20,10 +20,11 @@
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.doze.DozeHost;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java
index 38d9ae7..44df237 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java
@@ -22,13 +22,14 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.View;
 import android.widget.TextView;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.DarkIconDispatcher;
 import com.android.systemui.statusbar.HeadsUpStatusBarView;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
index 9ceb325..7797cb3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
@@ -21,11 +21,12 @@
 
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.view.View;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.statusbar.AlertingNotificationManager;
 import com.android.systemui.statusbar.AlertingNotificationManagerTest;
 import com.android.systemui.statusbar.notification.VisualStabilityManager;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaTest.kt
index 96f1976..3010996 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaTest.kt
@@ -1,6 +1,6 @@
 package com.android.systemui.statusbar.phone
 
-import android.support.test.filters.SmallTest
+import androidx.test.filters.SmallTest
 import android.testing.AndroidTestingRunner
 import android.testing.TestableLooper
 import android.view.LayoutInflater
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java
index f7a95c5..e84dd68 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java
@@ -30,13 +30,14 @@
 
 import android.content.res.ColorStateList;
 import android.graphics.Color;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.view.ViewGroup;
 import android.view.ViewTreeObserver;
 import android.widget.FrameLayout;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.widget.LockPatternUtils;
 import com.android.keyguard.KeyguardHostView;
 import com.android.keyguard.KeyguardSecurityModel;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithmTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithmTest.java
index cd52e87..fcf4c71 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithmTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithmTest.java
@@ -18,10 +18,11 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardPresentationTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardPresentationTest.java
index c587555..eec836f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardPresentationTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardPresentationTest.java
@@ -16,11 +16,12 @@
 
 package com.android.systemui.statusbar.phone;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.view.LayoutInflater;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LightBarTransitionsControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LightBarTransitionsControllerTest.java
index 0031c32..93fdce1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LightBarTransitionsControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LightBarTransitionsControllerTest.java
@@ -22,10 +22,11 @@
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.CommandQueue;
 import com.android.systemui.statusbar.phone.LightBarTransitionsController.DarkIntensityApplier;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarButtonTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarButtonTest.java
index 5c80718..81e8abf 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarButtonTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarButtonTest.java
@@ -25,13 +25,14 @@
 import android.hardware.display.VirtualDisplay;
 import android.media.ImageReader;
 import android.os.SystemClock;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.util.Log;
 import android.view.Display;
 import android.view.DisplayInfo;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.SysuiTestableContext;
 import com.android.systemui.statusbar.CommandQueue;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarContextTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarContextTest.java
index c792459..6293b06 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarContextTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarContextTest.java
@@ -17,26 +17,28 @@
 package com.android.systemui.statusbar.phone;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.doReturn;
 
 import android.graphics.drawable.Drawable;
-import android.support.test.filters.SmallTest;
 import android.view.View;
-import com.android.systemui.statusbar.policy.KeyButtonDrawable;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
+import com.android.systemui.statusbar.policy.KeyButtonDrawable;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import android.support.test.runner.AndroidJUnit4;
-
 /** atest NavigationBarContextTest */
 @SmallTest
 @RunWith(AndroidJUnit4.class)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java
index babd452..6a0d61d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java
@@ -22,7 +22,6 @@
 import android.content.Context;
 import android.os.Bundle;
 import android.os.Looper;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.LeakCheck.Tracker;
 import android.testing.TestableLooper.RunWithLooper;
@@ -30,6 +29,8 @@
 import android.view.WindowManager;
 import android.view.accessibility.AccessibilityManager.AccessibilityServicesStateChangeListener;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.Dependency;
 import com.android.systemui.SysuiBaseFragmentTest;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarInflaterViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarInflaterViewTest.java
index 093749a..cec7feb 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarInflaterViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarInflaterViewTest.java
@@ -22,13 +22,14 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.util.SparseArray;
 import android.view.View;
 import android.widget.FrameLayout;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.CommandQueue;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarRotationContextTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarRotationContextTest.java
index be26d91..28e91ea 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarRotationContextTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarRotationContextTest.java
@@ -22,13 +22,14 @@
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 
-import android.support.test.InstrumentationRegistry;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.view.View;
 
-import com.android.systemui.SysuiTestableContext;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
+import com.android.systemui.SysuiTestableContext;
 import com.android.systemui.TestableDependency;
 import com.android.systemui.statusbar.policy.KeyButtonDrawable;
 import com.android.systemui.statusbar.policy.RotationLockController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarTransitionsTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarTransitionsTest.java
index 40d5415..bb109bd 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarTransitionsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarTransitionsTest.java
@@ -21,11 +21,12 @@
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.IWindowManager;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.CommandQueue;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NearestTouchFrameTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NearestTouchFrameTest.java
index 4dee438..a04bcc0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NearestTouchFrameTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NearestTouchFrameTest.java
@@ -23,12 +23,13 @@
 import static org.mockito.Mockito.when;
 
 import android.content.res.Configuration;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.MotionEvent;
 import android.view.View;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupAlertTransferHelperTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupAlertTransferHelperTest.java
index cefd4ac..337c35c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupAlertTransferHelperTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupAlertTransferHelperTest.java
@@ -26,10 +26,11 @@
 
 import android.app.Notification;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.AmbientPulseManager;
 import com.android.systemui.statusbar.notification.NotificationEntryListener;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupManagerTest.java
index ecb3e4d..43685f0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupManagerTest.java
@@ -23,10 +23,11 @@
 import static org.junit.Assert.assertNull;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.AmbientPulseManager;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
@@ -40,7 +41,6 @@
 import org.mockito.junit.MockitoJUnit;
 import org.mockito.junit.MockitoRule;
 
-
 @SmallTest
 @RunWith(AndroidTestingRunner.class)
 @TestableLooper.RunWithLooper
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerTest.java
index 120d0b0..7f7a3e7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationIconAreaControllerTest.java
@@ -22,10 +22,11 @@
 import static org.junit.Assert.assertTrue;
 
 import android.provider.Settings;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.statusbar.NotificationListener;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationPanelViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationPanelViewTest.java
index a97fa1f..b7bcba4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationPanelViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationPanelViewTest.java
@@ -21,10 +21,11 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.keyguard.KeyguardStatusView;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/QuickStepControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/QuickStepControllerTest.java
index dbf00a3..7829830 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/QuickStepControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/QuickStepControllerTest.java
@@ -40,12 +40,13 @@
 
 import android.content.Context;
 import android.content.res.Resources;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.MotionEvent;
 import android.view.View;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.recents.OverviewProxyService;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
index f72d411..f88b64a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
@@ -38,12 +38,13 @@
 import android.graphics.Color;
 import android.os.Handler;
 import android.os.Looper;
-import android.support.test.filters.FlakyTest;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.view.View;
 
+import androidx.test.filters.FlakyTest;
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.colorextraction.ColorExtractor.GradientColors;
 import com.android.internal.util.function.TriConsumer;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarIconControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarIconControllerTest.java
index 4f95bc5..a27ed1e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarIconControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarIconControllerTest.java
@@ -22,12 +22,13 @@
 
 import static org.mockito.Mockito.mock;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.ViewGroup;
 import android.widget.LinearLayout;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.statusbar.StatusBarIcon;
 import com.android.systemui.plugins.DarkIconDispatcher;
 import com.android.systemui.statusbar.StatusBarIconView;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java
index 93dedfb..1a27765 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java
@@ -25,11 +25,12 @@
 import static org.mockito.Mockito.when;
 
 import android.content.Context;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.view.ViewGroup;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.widget.LockPatternUtils;
 import com.android.keyguard.ViewMediatorCallback;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java
index 12cb9957..e811e1d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java
@@ -26,13 +26,14 @@
 import android.metrics.LogMaker;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.support.test.metricshelper.MetricsAsserts;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.ViewGroup;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.internal.logging.testing.FakeMetricsLogger;
@@ -41,6 +42,7 @@
 import com.android.systemui.statusbar.notification.ActivityLaunchAnimator;
 import com.android.systemui.statusbar.notification.NotificationAlertingManager;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationRowBinderImpl;
 import com.android.systemui.statusbar.notification.row.ActivatableNotificationView;
 import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
 
@@ -74,7 +76,8 @@
                 statusBarWindowView, mock(NotificationListContainerViewGroup.class),
                 mock(DozeScrimController.class), mock(ScrimController.class),
                 mock(ActivityLaunchAnimator.class), mock(StatusBarKeyguardViewManager.class),
-                mock(NotificationAlertingManager.class));
+                mock(NotificationAlertingManager.class),
+                mock(NotificationRowBinderImpl.class));
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallbackTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallbackTest.java
index f28757f..a88a595 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallbackTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallbackTest.java
@@ -23,14 +23,13 @@
 import static org.mockito.Mockito.when;
 import static org.mockito.internal.verification.VerificationModeFactory.times;
 
-import android.content.BroadcastReceiver;
-import android.content.Context;
 import android.content.Intent;
 import android.os.UserManager;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.CommandQueue;
 import com.android.systemui.statusbar.NotificationLockscreenUserManager;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
index a95361f..f8bfc54 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
@@ -52,7 +52,6 @@
 import android.os.UserHandle;
 import android.service.dreams.IDreamManager;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.support.test.metricshelper.MetricsAsserts;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
@@ -60,6 +59,8 @@
 import android.util.SparseArray;
 import android.view.ViewGroup.LayoutParams;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.internal.logging.testing.FakeMetricsLogger;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowControllerTest.java
index 9996a9e..fea41a4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowControllerTest.java
@@ -25,12 +25,13 @@
 import static org.mockito.Mockito.when;
 
 import android.app.IActivityManager;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.ViewGroup;
 import android.view.WindowManager;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java
index 11284d6..ca0e1c6 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java
@@ -22,10 +22,11 @@
 import static org.mockito.Mockito.when;
 
 import android.os.SystemClock;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.view.MotionEvent;
 
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.Dependency;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/SystemUIDialogTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/SystemUIDialogTest.java
index 090963b..ca64823 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/SystemUIDialogTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/SystemUIDialogTest.java
@@ -23,10 +23,11 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Before;
@@ -34,7 +35,6 @@
 import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
 
-
 @RunWith(AndroidTestingRunner.class)
 @RunWithLooper
 @SmallTest
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BluetoothControllerImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BluetoothControllerImplTest.java
index b65b0f7..7f3c34e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BluetoothControllerImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BluetoothControllerImplTest.java
@@ -15,8 +15,8 @@
 package com.android.systemui.statusbar.policy;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -25,11 +25,11 @@
 import android.bluetooth.BluetoothDevice;
 import android.bluetooth.BluetoothProfile;
 import android.os.Looper;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
-import android.util.Log;
+
+import androidx.test.filters.SmallTest;
 
 import com.android.settingslib.bluetooth.BluetoothEventManager;
 import com.android.settingslib.bluetooth.CachedBluetoothDevice;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/CallbackControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/CallbackControllerTest.java
index 93c97ec..fa711f1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/CallbackControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/CallbackControllerTest.java
@@ -20,7 +20,6 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 
@@ -28,6 +27,7 @@
 import androidx.lifecycle.Lifecycle.Event;
 import androidx.lifecycle.LifecycleEventObserver;
 import androidx.lifecycle.LifecycleOwner;
+import androidx.test.filters.SmallTest;
 
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/CallbackHandlerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/CallbackHandlerTest.java
index ed0f9ab..85f6033 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/CallbackHandlerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/CallbackHandlerTest.java
@@ -15,29 +15,33 @@
  */
 package com.android.systemui.statusbar.policy;
 
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertTrue;
+
+import static org.mockito.Matchers.eq;
+
 import android.os.HandlerThread;
-import android.support.test.runner.AndroidJUnit4;
 import android.telephony.SubscriptionInfo;
 import android.test.suitebuilder.annotation.SmallTest;
+
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.policy.NetworkController.EmergencyListener;
 import com.android.systemui.statusbar.policy.NetworkController.IconState;
 import com.android.systemui.statusbar.policy.NetworkController.SignalCallback;
-import java.util.ArrayList;
-import java.util.List;
+
 import org.junit.Before;
-import org.junit.runner.RunWith;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
 import org.mockito.Mockito;
 import org.mockito.MockitoAnnotations;
 
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.Assert.assertEquals;
-
-import static org.mockito.Matchers.eq;
+import java.util.ArrayList;
+import java.util.List;
 
 @SmallTest
 @RunWith(AndroidJUnit4.class)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/CastControllerImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/CastControllerImplTest.java
index 1ee7094..016e402 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/CastControllerImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/CastControllerImplTest.java
@@ -1,28 +1,29 @@
 package com.android.systemui.statusbar.policy;
 
 
+import static org.junit.Assert.fail;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
-import static org.junit.Assert.fail;
 
 import android.media.MediaRouter;
 import android.media.projection.MediaProjectionInfo;
 import android.media.projection.MediaProjectionManager;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.policy.CastController.Callback;
 
 import org.junit.Before;
+import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
-import org.junit.Test;
 
 import java.util.ConcurrentModificationException;
 import java.util.concurrent.CountDownLatch;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/ExtensionControllerImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/ExtensionControllerImplTest.java
index 2553ac1..1240a48 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/ExtensionControllerImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/ExtensionControllerImplTest.java
@@ -23,11 +23,12 @@
 import static org.mockito.Mockito.when;
 
 import android.content.res.Configuration;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.OverlayPlugin;
 import com.android.systemui.plugins.Plugin;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/InflatedSmartRepliesTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/InflatedSmartRepliesTest.java
new file mode 100644
index 0000000..13651a5
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/InflatedSmartRepliesTest.java
@@ -0,0 +1,280 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.policy;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.when;
+
+import android.app.Notification;
+import android.app.PendingIntent;
+import android.app.RemoteInput;
+import android.content.Intent;
+import android.graphics.drawable.Icon;
+import android.service.notification.StatusBarNotification;
+import android.util.Pair;
+
+import androidx.test.annotation.UiThreadTest;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.systemui.R;
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.policy.InflatedSmartReplies.SmartRepliesAndActions;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class InflatedSmartRepliesTest extends SysuiTestCase {
+
+    private static final String TEST_ACTION = "com.android.SMART_REPLY_VIEW_ACTION";
+
+    @Mock
+    SmartReplyConstants mSmartReplyConstants;
+    @Mock
+    StatusBarNotification mStatusBarNotification;
+    @Mock
+    Notification mNotification;
+    NotificationEntry mEntry;
+    @Mock
+    RemoteInput mRemoteInput;
+    @Mock
+    RemoteInput mFreeFormRemoteInput;
+
+    private Icon mActionIcon;
+
+    @Before
+    @UiThreadTest
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+
+        when(mNotification.getAllowSystemGeneratedContextualActions()).thenReturn(true);
+        when(mStatusBarNotification.getNotification()).thenReturn(mNotification);
+        mEntry = new NotificationEntry(mStatusBarNotification);
+        when(mSmartReplyConstants.isEnabled()).thenReturn(true);
+        mActionIcon = Icon.createWithResource(mContext, R.drawable.ic_person);
+    }
+
+    @Test
+    public void chooseSmartRepliesAndActions_smartRepliesOff_noAppGeneratedSmartSuggestions() {
+        CharSequence[] smartReplies = new String[] {"Reply1", "Reply2"};
+        List<Notification.Action> smartActions =
+                createActions(new String[] {"Test Action 1", "Test Action 2"});
+        setupAppGeneratedSuggestions(smartReplies, smartActions);
+        when(mSmartReplyConstants.isEnabled()).thenReturn(false);
+
+        SmartRepliesAndActions repliesAndActions =
+                InflatedSmartReplies.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
+
+        assertThat(repliesAndActions.smartReplies).isNull();
+        assertThat(repliesAndActions.smartActions).isNull();
+    }
+
+    @Test
+    public void chooseSmartRepliesAndActions_smartRepliesOff_noSystemGeneratedSmartSuggestions() {
+        mEntry.systemGeneratedSmartReplies =
+                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
+        mEntry.systemGeneratedSmartActions =
+                createActions(new String[] {"Sys Smart Action 1", "Sys Smart Action 2"});
+        when(mSmartReplyConstants.isEnabled()).thenReturn(false);
+
+        SmartRepliesAndActions repliesAndActions =
+                InflatedSmartReplies.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
+
+        assertThat(repliesAndActions.smartReplies).isNull();
+        assertThat(repliesAndActions.smartActions).isNull();
+    }
+
+    @Test
+    public void chooseSmartRepliesAndActions_appGeneratedSmartReplies() {
+        CharSequence[] smartReplies = new String[] {"Reply1", "Reply2"};
+        setupAppGeneratedReplies(smartReplies);
+
+        SmartRepliesAndActions repliesAndActions =
+                InflatedSmartReplies.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
+
+        assertThat(repliesAndActions.smartReplies.choices).isEqualTo(smartReplies);
+        assertThat(repliesAndActions.smartReplies.fromAssistant).isFalse();
+        assertThat(repliesAndActions.smartActions).isNull();
+    }
+
+    @Test
+    public void chooseSmartRepliesAndActions_appGeneratedSmartRepliesAndActions() {
+        CharSequence[] smartReplies = new String[] {"Reply1", "Reply2"};
+        List<Notification.Action> smartActions =
+                createActions(new String[] {"Test Action 1", "Test Action 2"});
+        setupAppGeneratedSuggestions(smartReplies, smartActions);
+
+        SmartRepliesAndActions repliesAndActions =
+                InflatedSmartReplies.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
+
+        assertThat(repliesAndActions.smartReplies.choices).isEqualTo(smartReplies);
+        assertThat(repliesAndActions.smartReplies.fromAssistant).isFalse();
+        assertThat(repliesAndActions.smartActions.actions).isEqualTo(smartActions);
+        assertThat(repliesAndActions.smartActions.fromAssistant).isFalse();
+    }
+
+    @Test
+    public void chooseSmartRepliesAndActions_sysGeneratedSmartReplies() {
+        // Pass a null-array as app-generated smart replies, so that we use NAS-generated smart
+        // replies.
+        setupAppGeneratedReplies(null /* smartReplies */);
+
+        mEntry.systemGeneratedSmartReplies =
+                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
+        SmartRepliesAndActions repliesAndActions =
+                InflatedSmartReplies.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
+
+        assertThat(repliesAndActions.smartReplies.choices).isEqualTo(
+                mEntry.systemGeneratedSmartReplies);
+        assertThat(repliesAndActions.smartReplies.fromAssistant).isTrue();
+        assertThat(repliesAndActions.smartActions).isNull();
+    }
+
+    @Test
+    public void chooseSmartRepliesAndActions_noSysGeneratedSmartRepliesIfNotAllowed() {
+        // Pass a null-array as app-generated smart replies, so that we use NAS-generated smart
+        // replies.
+        setupAppGeneratedReplies(null /* smartReplies */, false /* allowSystemGeneratedReplies */);
+
+        mEntry.systemGeneratedSmartReplies =
+                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
+        SmartRepliesAndActions repliesAndActions =
+                InflatedSmartReplies.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
+
+        assertThat(repliesAndActions.smartReplies).isNull();
+        assertThat(repliesAndActions.smartActions).isNull();
+    }
+
+    @Test
+    public void chooseSmartRepliesAndActions_sysGeneratedSmartActions() {
+        // Pass a null-array as app-generated smart replies, so that we use NAS-generated smart
+        // actions.
+        setupAppGeneratedReplies(null /* smartReplies */);
+
+        mEntry.systemGeneratedSmartActions =
+                createActions(new String[] {"Sys Smart Action 1", "Sys Smart Action 2"});
+        SmartRepliesAndActions repliesAndActions =
+                InflatedSmartReplies.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
+
+        assertThat(repliesAndActions.smartReplies).isNull();
+        assertThat(repliesAndActions.smartActions.actions)
+                .isEqualTo(mEntry.systemGeneratedSmartActions);
+        assertThat(repliesAndActions.smartActions.fromAssistant).isTrue();
+    }
+
+    @Test
+    public void chooseSmartRepliesAndActions_appGenPreferredOverSysGen() {
+        CharSequence[] appGenSmartReplies = new String[] {"Reply1", "Reply2"};
+        // Pass a null-array as app-generated smart replies, so that we use NAS-generated smart
+        // replies.
+        List<Notification.Action> appGenSmartActions =
+                createActions(new String[] {"Test Action 1", "Test Action 2"});
+        setupAppGeneratedSuggestions(appGenSmartReplies, appGenSmartActions);
+
+        mEntry.systemGeneratedSmartReplies =
+                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
+        mEntry.systemGeneratedSmartActions =
+                createActions(new String[] {"Sys Smart Action 1", "Sys Smart Action 2"});
+
+        SmartRepliesAndActions repliesAndActions =
+                InflatedSmartReplies.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
+
+        assertThat(repliesAndActions.smartReplies.choices).isEqualTo(appGenSmartReplies);
+        assertThat(repliesAndActions.smartReplies.fromAssistant).isFalse();
+        assertThat(repliesAndActions.smartActions.actions).isEqualTo(appGenSmartActions);
+        assertThat(repliesAndActions.smartActions.fromAssistant).isFalse();
+    }
+
+    @Test
+    public void chooseSmartRepliesAndActions_disallowSysGenSmartActions() {
+        // Pass a null-array as app-generated smart replies, so that we use NAS-generated smart
+        // actions.
+        setupAppGeneratedReplies(null /* smartReplies */, false /* allowSystemGeneratedReplies */);
+        when(mNotification.getAllowSystemGeneratedContextualActions()).thenReturn(false);
+        mEntry.systemGeneratedSmartReplies =
+                new String[] {"Sys Smart Reply 1", "Sys Smart Reply 2"};
+        mEntry.systemGeneratedSmartActions =
+                createActions(new String[] {"Sys Smart Action 1", "Sys Smart Action 2"});
+
+        SmartRepliesAndActions repliesAndActions =
+                InflatedSmartReplies.chooseSmartRepliesAndActions(mSmartReplyConstants, mEntry);
+
+        assertThat(repliesAndActions.smartActions).isNull();
+        assertThat(repliesAndActions.smartReplies).isNull();
+    }
+
+    private void setupAppGeneratedReplies(CharSequence[] smartReplies) {
+        setupAppGeneratedReplies(smartReplies, true /* allowSystemGeneratedReplies */);
+    }
+
+    private void setupAppGeneratedReplies(
+            CharSequence[] smartReplies, boolean allowSystemGeneratedReplies) {
+        PendingIntent pendingIntent =
+                PendingIntent.getBroadcast(mContext, 0, new Intent(TEST_ACTION), 0);
+        Notification.Action action =
+                new Notification.Action.Builder(null, "Test Action", pendingIntent).build();
+        when(mRemoteInput.getChoices()).thenReturn(smartReplies);
+        Pair<RemoteInput, Notification.Action> remoteInputActionPair =
+                Pair.create(mRemoteInput, action);
+        when(mNotification.findRemoteInputActionPair(false)).thenReturn(remoteInputActionPair);
+
+        Notification.Action freeFormRemoteInputAction =
+                createActionBuilder("Freeform Test Action")
+                .setAllowGeneratedReplies(allowSystemGeneratedReplies)
+                .build();
+        Pair<RemoteInput, Notification.Action> freeFormRemoteInputActionPair =
+                Pair.create(mFreeFormRemoteInput, freeFormRemoteInputAction);
+        when(mNotification.findRemoteInputActionPair(true)).thenReturn(
+                freeFormRemoteInputActionPair);
+
+        when(mSmartReplyConstants.requiresTargetingP()).thenReturn(false);
+    }
+
+    private void setupAppGeneratedSuggestions(
+            CharSequence[] smartReplies, List<Notification.Action> smartActions) {
+        setupAppGeneratedReplies(smartReplies);
+        when(mNotification.getContextualActions()).thenReturn(smartActions);
+    }
+
+    private Notification.Action.Builder createActionBuilder(String actionTitle) {
+        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0,
+                new Intent(TEST_ACTION), 0);
+        return new Notification.Action.Builder(mActionIcon, actionTitle, pendingIntent);
+    }
+
+    private Notification.Action createAction(String actionTitle) {
+        return createActionBuilder(actionTitle).build();
+    }
+
+    private List<Notification.Action> createActions(String[] actionTitles) {
+        List<Notification.Action> actions = new ArrayList<>();
+        for (String title : actionTitles) {
+            actions.add(createAction(title));
+        }
+        return actions;
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/KeyButtonViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/KeyButtonViewTest.java
index f859235..39bdf20 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/KeyButtonViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/KeyButtonViewTest.java
@@ -21,12 +21,13 @@
 import static org.mockito.ArgumentMatchers.argThat;
 
 import android.metrics.LogMaker;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.view.KeyEvent;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/LocationControllerImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/LocationControllerImplTest.java
index a0fb330..3dcb34a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/LocationControllerImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/LocationControllerImplTest.java
@@ -20,11 +20,12 @@
 
 import android.content.Intent;
 import android.location.LocationManager;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.policy.LocationController.LocationChangeCallback;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerEthernetTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerEthernetTest.java
index eefdeee..93cf3e8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerEthernetTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerEthernetTest.java
@@ -1,7 +1,8 @@
 package com.android.systemui.statusbar.policy;
 
+import static junit.framework.Assert.assertEquals;
+
 import android.net.NetworkCapabilities;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
@@ -13,8 +14,6 @@
 import org.mockito.ArgumentCaptor;
 import org.mockito.Mockito;
 
-import static junit.framework.Assert.assertEquals;
-
 @SmallTest
 @RunWith(AndroidTestingRunner.class)
 @RunWithLooper
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerSignalTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerSignalTest.java
index c24336d..bcbba8b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerSignalTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerSignalTest.java
@@ -15,11 +15,16 @@
  */
 package com.android.systemui.statusbar.policy;
 
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import static org.mockito.Mockito.mock;
+
 import android.content.Intent;
 import android.net.ConnectivityManager;
 import android.net.NetworkCapabilities;
 import android.os.Looper;
-import android.support.test.runner.AndroidJUnit4;
 import android.telephony.ServiceState;
 import android.telephony.SignalStrength;
 import android.telephony.SubscriptionInfo;
@@ -42,11 +47,6 @@
 import java.util.ArrayList;
 import java.util.List;
 
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.Assert.assertFalse;
-import static org.mockito.Mockito.mock;
-
 @SmallTest
 @RunWith(AndroidTestingRunner.class)
 @RunWithLooper
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputQuickSettingsDisablerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputQuickSettingsDisablerTest.java
index 8b8e3f1..fea3a08 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputQuickSettingsDisablerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputQuickSettingsDisablerTest.java
@@ -24,9 +24,10 @@
 import static org.mockito.Mockito.verify;
 
 import android.content.res.Configuration;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.CommandQueue;
 import com.android.systemui.statusbar.policy.ConfigurationController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java
index 568ff55f..8bf1606 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java
@@ -26,7 +26,6 @@
 import android.os.Handler;
 import android.os.Process;
 import android.os.UserHandle;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.view.View;
@@ -35,6 +34,8 @@
 import android.widget.EditText;
 import android.widget.ImageButton;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SecurityControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SecurityControllerTest.java
index 3ac42de..854cc2f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SecurityControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SecurityControllerTest.java
@@ -23,11 +23,9 @@
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.argThat;
 import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import android.app.admin.DevicePolicyManager;
 import android.content.ComponentName;
@@ -37,30 +35,28 @@
 import android.content.pm.UserInfo;
 import android.net.ConnectivityManager;
 import android.net.ConnectivityManager.NetworkCallback;
-import android.net.NetworkCapabilities;
 import android.net.NetworkRequest;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.UserManager;
 import android.security.IKeyChainService;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
-import com.android.systemui.statusbar.policy.SecurityController.SecurityControllerCallback;
-import com.android.systemui.SysuiTestCase;
+import androidx.test.runner.AndroidJUnit4;
 
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.List;
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.statusbar.policy.SecurityController.SecurityControllerCallback;
 
 import org.junit.After;
 import org.junit.Before;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 @SmallTest
 @RunWith(AndroidJUnit4.class)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyConstantsTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyConstantsTest.java
index bc0f742..cd9069a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyConstantsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyConstantsTest.java
@@ -23,15 +23,17 @@
 import android.app.RemoteInput;
 import android.os.Handler;
 import android.os.Looper;
-import android.provider.Settings;
+import android.provider.DeviceConfig;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableResources;
 
+import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
 
+import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -47,7 +49,7 @@
 
     @Before
     public void setUp() {
-        overrideSetting(null); // No config.
+        resetAllDeviceConfigFlags();
         TestableResources resources = mContext.getOrCreateTestableResources();
         resources.addOverride(R.bool.config_smart_replies_in_notifications_enabled, true);
         resources.addOverride(
@@ -58,9 +60,16 @@
         resources.addOverride(
                 R.integer.config_smart_replies_in_notifications_min_num_system_generated_replies,
                 2);
+        resources.addOverride(
+                R.integer.config_smart_replies_in_notifications_max_num_actions, -1);
         mConstants = new SmartReplyConstants(Handler.createAsync(Looper.myLooper()), mContext);
     }
 
+    @After
+    public void tearDown() {
+        resetAllDeviceConfigFlags();
+    }
+
     @Test
     public void testIsEnabledWithNoConfig() {
         assertTrue(mConstants.isEnabled());
@@ -68,25 +77,25 @@
 
     @Test
     public void testIsEnabledWithInvalidConfig() {
-        overrideSetting("invalid config");
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_ENABLED, "invalid config");
         triggerConstantsOnChange();
         assertTrue(mConstants.isEnabled());
     }
 
     @Test
     public void testIsEnabledWithValidConfig() {
-        overrideSetting("enabled=false,max_squeeze_remeasure_attempts=5");
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_ENABLED, "false");
         triggerConstantsOnChange();
         assertFalse(mConstants.isEnabled());
     }
 
     @Test
     public void testRequiresTargetingPConfig() {
-        overrideSetting("enabled=true,requires_targeting_p=false");
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_REQUIRES_TARGETING_P, "false");
         triggerConstantsOnChange();
         assertEquals(false, mConstants.requiresTargetingP());
 
-        overrideSetting("enabled=true");
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_REQUIRES_TARGETING_P, "");
         triggerConstantsOnChange();
         assertEquals(true, mConstants.requiresTargetingP());
     }
@@ -99,21 +108,21 @@
 
     @Test
     public void testGetMaxSqueezeRemeasureAttemptsWithInvalidConfig() {
-        overrideSetting("invalid config");
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_MAX_SQUEEZE_REMEASURE_ATTEMPTS,
+                "invalid config");
         triggerConstantsOnChange();
         assertEquals(7, mConstants.getMaxSqueezeRemeasureAttempts());
     }
 
     @Test
     public void testGetMaxSqueezeRemeasureAttemptsWithValidConfig() {
-        overrideSetting("enabled=false,max_squeeze_remeasure_attempts=5");
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_MAX_SQUEEZE_REMEASURE_ATTEMPTS, "5");
         triggerConstantsOnChange();
         assertEquals(5, mConstants.getMaxSqueezeRemeasureAttempts());
     }
 
     @Test
     public void testGetEffectiveEditChoicesBeforeSendingWithNoConfig() {
-        overrideSetting("enabled=true");
         triggerConstantsOnChange();
         assertFalse(
                 mConstants.getEffectiveEditChoicesBeforeSending(
@@ -128,7 +137,7 @@
 
     @Test
     public void testGetEffectiveEditChoicesBeforeSendingWithEnabledConfig() {
-        overrideSetting("enabled=true,edit_choices_before_sending=true");
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_EDIT_CHOICES_BEFORE_SENDING, "true");
         triggerConstantsOnChange();
         assertTrue(
                 mConstants.getEffectiveEditChoicesBeforeSending(
@@ -143,7 +152,7 @@
 
     @Test
     public void testGetEffectiveEditChoicesBeforeSendingWithDisabledConfig() {
-        overrideSetting("enabled=true,edit_choices_before_sending=false");
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_EDIT_CHOICES_BEFORE_SENDING, "false");
         triggerConstantsOnChange();
         assertFalse(
                 mConstants.getEffectiveEditChoicesBeforeSending(
@@ -164,37 +173,19 @@
 
     @Test
     public void testShowInHeadsUpEnabled() {
-        overrideSetting("enabled=true,show_in_heads_up=true");
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_SHOW_IN_HEADS_UP, "true");
         triggerConstantsOnChange();
         assertTrue(mConstants.getShowInHeadsUp());
     }
 
     @Test
     public void testShowInHeadsUpDisabled() {
-        overrideSetting("enabled=true,show_in_heads_up=false");
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_SHOW_IN_HEADS_UP, "false");
         triggerConstantsOnChange();
         assertFalse(mConstants.getShowInHeadsUp());
     }
 
     @Test
-    public void testMaxNumActionsWithNoConfig() {
-        assertTrue(mConstants.isEnabled());
-        assertEquals(-1, mConstants.getMaxNumActions());
-    }
-
-    @Test
-    public void testMaxNumActionsSet() {
-        overrideSetting("enabled=true,max_num_actions=10");
-        triggerConstantsOnChange();
-        assertEquals(10, mConstants.getMaxNumActions());
-    }
-
-    private void overrideSetting(String flags) {
-        Settings.Global.putString(mContext.getContentResolver(),
-                Settings.Global.SMART_REPLIES_IN_NOTIFICATIONS_FLAGS, flags);
-    }
-
-    @Test
     public void testGetMinNumSystemGeneratedRepliesWithNoConfig() {
         assertTrue(mConstants.isEnabled());
         assertEquals(2, mConstants.getMinNumSystemGeneratedReplies());
@@ -202,15 +193,51 @@
 
     @Test
     public void testGetMinNumSystemGeneratedRepliesWithValidConfig() {
-        overrideSetting("enabled=true,min_num_system_generated_replies=5");
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_MIN_NUM_SYSTEM_GENERATED_REPLIES, "5");
         triggerConstantsOnChange();
         assertEquals(5, mConstants.getMinNumSystemGeneratedReplies());
     }
 
+    @Test
+    public void testMaxNumActionsWithNoConfig() {
+        assertTrue(mConstants.isEnabled());
+        assertEquals(-1, mConstants.getMaxNumActions());
+    }
+
+    @Test
+    public void testMaxNumActionsSet() {
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_MAX_NUM_ACTIONS, "10");
+        triggerConstantsOnChange();
+        assertEquals(10, mConstants.getMaxNumActions());
+    }
+
+    private void overrideSetting(String propertyName, String value) {
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
+                propertyName, value, false /* makeDefault */);
+    }
+
     private void triggerConstantsOnChange() {
-        // Since Settings.Global is mocked in TestableContext, we need to manually trigger the
-        // content observer.
-        mConstants.onChange(false,
-                Settings.Global.getUriFor(Settings.Global.SMART_REPLIES_IN_NOTIFICATIONS_FLAGS));
+        mConstants.onDeviceConfigPropertyChanged(DeviceConfig.NAMESPACE_SYSTEMUI,
+                "" /* name */, "" /* value */);
+    }
+
+    private void resetAllDeviceConfigFlags() {
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.SSIN_ENABLED, "", false /* makeDefault */);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.SSIN_REQUIRES_TARGETING_P, "", false /* makeDefault */);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.SSIN_MAX_SQUEEZE_REMEASURE_ATTEMPTS, "",
+                false /* makeDefault */);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.SSIN_EDIT_CHOICES_BEFORE_SENDING, "",
+                false /* makeDefault */);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.SSIN_SHOW_IN_HEADS_UP, "", false /* makeDefault */);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.SSIN_MIN_NUM_SYSTEM_GENERATED_REPLIES, "",
+                false /* makeDefault */);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
+                SystemUiDeviceConfigFlags.SSIN_MAX_NUM_ACTIONS, "", false /* makeDefault */);
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java
index 6793eca..0ce1df3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java
@@ -37,7 +37,6 @@
 import android.graphics.drawable.Drawable;
 import android.graphics.drawable.Icon;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.view.View;
@@ -45,6 +44,8 @@
 import android.widget.Button;
 import android.widget.LinearLayout;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
@@ -113,7 +114,7 @@
         mDependency.injectTestDependency(SmartReplyConstants.class, mConstants);
 
         mContainer = new View(mContext, null);
-        mView = SmartReplyView.inflate(mContext, null);
+        mView = SmartReplyView.inflate(mContext);
 
         // Any number of replies are fine.
         when(mConstants.getMinNumSystemGeneratedReplies()).thenReturn(0);
@@ -402,17 +403,18 @@
     }
 
     private void setSmartReplies(CharSequence[] choices) {
-        setSmartReplies(choices, false /* fromAssistant */);
+        mView.resetSmartSuggestions(mContainer);
+        List<Button> replyButtons = inflateSmartReplies(choices, false /* fromAssistant */);
+        mView.addPreInflatedButtons(replyButtons);
     }
 
-    private void setSmartReplies(CharSequence[] choices, boolean fromAssistant) {
+    private List<Button> inflateSmartReplies(CharSequence[] choices, boolean fromAssistant) {
         PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0,
                 new Intent(TEST_ACTION), 0);
         RemoteInput input = new RemoteInput.Builder(TEST_RESULT_KEY).setChoices(choices).build();
         SmartReplyView.SmartReplies smartReplies =
                 new SmartReplyView.SmartReplies(choices, input, pendingIntent, fromAssistant);
-        mView.resetSmartSuggestions(mContainer);
-        mView.addRepliesFromRemoteInput(smartReplies, mLogger, mEntry);
+        return mView.inflateRepliesFromRemoteInput(smartReplies, mLogger, mEntry);
     }
 
     private Notification.Action createAction(String actionTitle) {
@@ -431,11 +433,12 @@
 
     private void setSmartActions(String[] actionTitles) {
         mView.resetSmartSuggestions(mContainer);
-        mView.addSmartActions(
+        List<Button> actions = mView.inflateSmartActions(
                 new SmartReplyView.SmartActions(createActions(actionTitles), false),
                 mLogger,
                 mEntry,
                 mHeadsUpManager);
+        mView.addPreInflatedButtons(actions);
     }
 
     private void setSmartRepliesAndActions(CharSequence[] choices, String[] actionTitles) {
@@ -444,12 +447,14 @@
 
     private void setSmartRepliesAndActions(
             CharSequence[] choices, String[] actionTitles, boolean fromAssistant) {
-        setSmartReplies(choices, fromAssistant);
-        mView.addSmartActions(
+        mView.resetSmartSuggestions(mContainer);
+        List<Button> smartSuggestions = inflateSmartReplies(choices, fromAssistant);
+        smartSuggestions.addAll(mView.inflateSmartActions(
                 new SmartReplyView.SmartActions(createActions(actionTitles), fromAssistant),
                 mLogger,
                 mEntry,
-                mHeadsUpManager);
+                mHeadsUpManager));
+        mView.addPreInflatedButtons(smartSuggestions);
     }
 
     private ViewGroup buildExpectedView(CharSequence[] choices, int lineCount) {
@@ -485,8 +490,8 @@
         SmartReplyView.SmartReplies smartReplies =
                 new SmartReplyView.SmartReplies(choices, null, null, false);
         for (int i = 0; i < choices.length; ++i) {
-            Button current = mView.inflateReplyButton(mContext, mView, i, smartReplies,
-                    null, null);
+            Button current = SmartReplyView.inflateReplyButton(mView, mContext, i, smartReplies,
+                    null /* SmartReplyController */, null /* NotificationEntry */);
             current.setPadding(paddingHorizontal, current.getPaddingTop(), paddingHorizontal,
                     current.getPaddingBottom());
             if (previous != null) {
@@ -752,7 +757,7 @@
     }
 
     private Button inflateActionButton(Notification.Action action) {
-        return mView.inflateActionButton(getContext(), mView, 0,
+        return SmartReplyView.inflateActionButton(mView, getContext(), 0,
                 new SmartReplyView.SmartActions(Collections.singletonList(action), false),
                 mLogger, mEntry, mHeadsUpManager);
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/ZenModeControllerImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/ZenModeControllerImplTest.java
index 8f5f072..47e4492 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/ZenModeControllerImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/ZenModeControllerImplTest.java
@@ -27,10 +27,11 @@
 import android.os.Looper;
 import android.provider.Settings;
 import android.service.notification.ZenModeConfig;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.policy.ZenModeController.Callback;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/tuner/TunablePaddingTest.java b/packages/SystemUI/tests/src/com/android/systemui/tuner/TunablePaddingTest.java
index 1e27915..683397e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/tuner/TunablePaddingTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/tuner/TunablePaddingTest.java
@@ -20,14 +20,14 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.withSettings;
 
-import android.support.test.filters.SmallTest;
 import android.testing.LeakCheck.Tracker;
 import android.util.DisplayMetrics;
 import android.view.View;
 import android.view.WindowManager;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.utils.leaks.LeakCheckedTest;
 
 import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/AsyncSensorManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/AsyncSensorManagerTest.java
index 77df791..4a9b1b3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/AsyncSensorManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/AsyncSensorManagerTest.java
@@ -25,9 +25,10 @@
 
 import android.hardware.SensorEventListener;
 import android.hardware.SensorManager;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.SensorManagerPlugin;
 import com.android.systemui.shared.plugins.PluginManager;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/ChannelsTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/ChannelsTest.java
index 0d398be..f1c9980 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/ChannelsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/ChannelsTest.java
@@ -15,22 +15,19 @@
 package com.android.systemui.util;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
 
-import android.app.Notification;
 import android.app.NotificationChannel;
 import android.app.NotificationManager;
 import android.content.Context;
-import android.net.Uri;
 import android.provider.Settings;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.util.ArraySet;
+
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.util.NotificationChannels;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/LifecycleFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/LifecycleFragmentTest.java
index d4e38d8..0e1c560 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/LifecycleFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/LifecycleFragmentTest.java
@@ -27,12 +27,12 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
 import androidx.lifecycle.LifecycleEventObserver;
+import androidx.test.filters.SmallTest;
 
 import com.android.systemui.SysuiBaseFragmentTest;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/SysuiLifecycleTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/SysuiLifecycleTest.java
index d63bbe6..ce8085a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/SysuiLifecycleTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/SysuiLifecycleTest.java
@@ -29,7 +29,6 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
@@ -38,6 +37,7 @@
 
 import androidx.lifecycle.LifecycleEventObserver;
 import androidx.lifecycle.LifecycleOwner;
+import androidx.test.filters.SmallTest;
 
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/leak/GarbageMonitorTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/leak/GarbageMonitorTest.java
index c095472..bcc20c2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/leak/GarbageMonitorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/leak/GarbageMonitorTest.java
@@ -24,11 +24,12 @@
 
 import android.content.Context;
 import android.os.Looper;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 
 import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/leak/LeakDetectorTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/leak/LeakDetectorTest.java
index 11bb398..c68c920 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/leak/LeakDetectorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/leak/LeakDetectorTest.java
@@ -17,8 +17,8 @@
 package com.android.systemui.util.leak;
 
 
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.util.leak.ReferenceTestUtils.CollectionWaiter;
@@ -28,8 +28,6 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import java.io.FileDescriptor;
-import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.PrintWriter;
 import java.util.ArrayList;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/leak/LeakReporterTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/leak/LeakReporterTest.java
index 6711ce8..abec80e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/leak/LeakReporterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/leak/LeakReporterTest.java
@@ -24,8 +24,9 @@
 import static org.mockito.Mockito.verify;
 
 import android.app.NotificationManager;
-import android.support.test.filters.MediumTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.MediumTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/leak/ReferenceTestUtilsTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/leak/ReferenceTestUtilsTest.java
index b8a3e39..726187d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/leak/ReferenceTestUtilsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/leak/ReferenceTestUtilsTest.java
@@ -18,8 +18,8 @@
 
 import static org.junit.Assert.assertEquals;
 
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/leak/WeakIdentityHashMapTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/leak/WeakIdentityHashMapTest.java
index ce6212e..2b28e2f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/leak/WeakIdentityHashMapTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/leak/WeakIdentityHashMapTest.java
@@ -20,8 +20,8 @@
 import static org.junit.Assert.assertNotSame;
 import static org.junit.Assert.assertTrue;
 
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.util.leak.ReferenceTestUtils.CollectionWaiter;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/KeepAwakeAnimationListenerTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/KeepAwakeAnimationListenerTest.java
index 0792a05..20dcbb7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/KeepAwakeAnimationListenerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/KeepAwakeAnimationListenerTest.java
@@ -22,10 +22,11 @@
 
 import android.animation.Animator;
 import android.os.Looper;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.util.Assert;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/SettableWakeLockTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/SettableWakeLockTest.java
index f739fe6..d0eaaf5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/SettableWakeLockTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/SettableWakeLockTest.java
@@ -21,8 +21,8 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/WakeLockTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/WakeLockTest.java
index 4425def..66eb299 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/WakeLockTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/wakelock/WakeLockTest.java
@@ -20,8 +20,9 @@
 import static org.junit.Assert.assertTrue;
 
 import android.os.PowerManager;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/UtilTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/UtilTest.java
index 6b20a1e..fb82b8f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/UtilTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/UtilTest.java
@@ -16,7 +16,8 @@
 package com.android.systemui.volume;
 
 import android.media.MediaMetadata;
-import android.support.test.filters.SmallTest;
+
+import androidx.test.filters.SmallTest;
 
 import com.android.systemui.SysuiTestCase;
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogControllerImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogControllerImplTest.java
index a4ed459..f4d0854 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogControllerImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogControllerImplTest.java
@@ -25,7 +25,9 @@
 import android.content.Context;
 import android.media.AudioManager;
 import android.media.session.MediaSession;
-import android.support.test.filters.SmallTest;
+
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.statusbar.phone.StatusBar;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
index 5f02fad..617c17e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
@@ -16,37 +16,26 @@
 
 package com.android.systemui.volume;
 
-import static android.media.AudioManager.RINGER_MODE_NORMAL;
-import static android.media.AudioManager.RINGER_MODE_SILENT;
-import static android.media.AudioManager.RINGER_MODE_VIBRATE;
-import static android.media.AudioManager.STREAM_RING;
-
-import static com.android.systemui.volume.Events.DISMISS_REASON_UNKNOWN;
-import static com.android.systemui.volume.Events.SHOW_REASON_UNKNOWN;
 import static com.android.systemui.volume.VolumeDialogControllerImpl.STREAMS;
 
 import static junit.framework.Assert.assertTrue;
 
 import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
 
 import android.app.KeyguardManager;
 import android.media.AudioManager;
 import android.os.SystemClock;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
-import android.text.TextUtils;
 import android.view.InputDevice;
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.accessibility.AccessibilityManager;
-import android.widget.ImageView;
 
-import com.android.systemui.R;
+import androidx.test.filters.SmallTest;
+
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.VolumeDialogController;
 import com.android.systemui.plugins.VolumeDialogController.State;
diff --git a/proto/Android.bp b/proto/Android.bp
index 7f826b3..7b119a7 100644
--- a/proto/Android.bp
+++ b/proto/Android.bp
@@ -28,14 +28,4 @@
     srcs: ["src/metrics_constants/metrics_constants.proto"],
     no_framework_libs: true,
     sdk_version: "system_current",
-    // Pin java_version until jarjar is certified to support later versions. http://b/72703434
-    java_version: "1.8",
-    target: {
-        android: {
-            jarjar_rules: "jarjar-rules.txt",
-        },
-        host: {
-            static_libs: ["libprotobuf-java-nano"],
-        },
-    },
 }
diff --git a/proto/src/metrics_constants/metrics_constants.proto b/proto/src/metrics_constants/metrics_constants.proto
index b3e5f69..365c6b4 100644
--- a/proto/src/metrics_constants/metrics_constants.proto
+++ b/proto/src/metrics_constants/metrics_constants.proto
@@ -5434,7 +5434,7 @@
     FIELD_END_BATTERY_PERCENT = 1308;
 
     // ACTION: Settings > Display > Night Light
-    // SUBTYPE: com.android.server.display.ColorDisplayService.AutoMode value
+    // SUBTYPE: com.android.server.display.color.ColorDisplayService.AutoMode value
     // CATEGORY: SETTINGS
     // OS: P
     ACTION_NIGHT_DISPLAY_AUTO_MODE_CHANGED = 1309;
@@ -7017,6 +7017,54 @@
     // OS: Q
     ACTION_SWITCH_SHARE_PROFILE = 1661;
 
+    // ACTION: Show Contextual homepage, log latency in loading cards
+    ACTION_CONTEXTUAL_HOME_SHOW = 1662;
+
+    // ACTION: Contextual card displays
+    ACTION_CONTEXTUAL_CARD_SHOW = 1663;
+
+    // ACTION: Contextual cards are eligible to be shown, but don't rank high
+    ACTION_CONTEXTUAL_CARD_NOT_SHOW = 1664;
+
+    // ACTION: Settings > long press a card, and click dismiss
+    // Contextual card is dismissed
+    ACTION_CONTEXTUAL_CARD_DISMISS = 1665;
+
+    // ACTION: Settings > click a card
+    // Contextual card is clicked
+    ACTION_CONTEXTUAL_CARD_CLICK = 1666;
+
+    // Mapping: go/at-mapping
+    PAGE_ATSSI = 1667;
+
+    PAGE_ATSII = 1668;
+
+    PAGE_ATUS = 1669;
+
+    PAGE_ATSSP = 1670;
+
+    PAGE_ATSAP = 1671;
+
+    PAGE_ATSCP = 1672;
+
+    PAGE_ATHNP = 1673;
+
+    ACTION_ATSG = 1674;
+
+    ACTION_ATPG = 1675;
+
+    ACTION_ATCLPB = 1676;
+
+    ACTION_ATCGIB = 1677;
+
+    ACTION_ATCPAB = 1678;
+
+    ACTION_ATCSAUC = 1679;
+
+    ACTION_ATCSCUC = 1680;
+
+    ACTION_ATCHNUC = 1681;
+
     // ---- End Q Constants, all Q constants go above this line ----
     // Add new aosp constants above this line.
     // END OF AOSP CONSTANTS
diff --git a/proto/src/wifi.proto b/proto/src/wifi.proto
index ee3777d..2214ac5 100644
--- a/proto/src/wifi.proto
+++ b/proto/src/wifi.proto
@@ -521,6 +521,18 @@
 
   // Total number of saved networks with mac randomization enabled.
   optional int32 num_saved_networks_with_mac_randomization = 138;
+
+  // Link Probe metrics
+  optional LinkProbeStats link_probe_stats = 139;
+
+  // List of NetworkSelectionExperimentDecisions stats for each experiment
+  repeated NetworkSelectionExperimentDecisions network_selection_experiment_decisions_list = 140;
+
+  // Network Request API surface metrics.
+  optional WifiNetworkRequestApiLog wifi_network_request_api_log = 141;
+
+  // Network Suggestion API surface metrics.
+  optional WifiNetworkSuggestionApiLog wifi_network_suggestion_api_log = 142;
 }
 
 // Information that gets logged for every WiFi connection.
@@ -648,6 +660,39 @@
     HLF_UNWANTED = 4;
   }
 
+  // Entity that recommended connecting to this network.
+  enum ConnectionNominator {
+    // Unknown nominator
+    NOMINATOR_UNKNOWN = 0;
+
+    // User selected network manually
+    NOMINATOR_MANUAL = 1;
+
+    // Saved network
+    NOMINATOR_SAVED = 2;
+
+    // Suggestion API
+    NOMINATOR_SUGGESTION = 3;
+
+    // Passpoint
+    NOMINATOR_PASSPOINT = 4;
+
+    // Carrier suggestion
+    NOMINATOR_CARRIER = 5;
+
+    // External scorer
+    NOMINATOR_EXTERNAL_SCORED = 6;
+
+    // Netrec
+    NOMINATOR_NETREC = 7;
+
+    // User connected choice override
+    NOMINATOR_SAVED_USER_CONNECT_CHOICE = 8;
+
+    // Open Network Available Pop-up
+    NOMINATOR_OPEN_NETWORK_AVAILABLE = 9;
+  }
+
   // Start time of the connection.
   optional int64 start_time_millis = 1;// [(datapol.semantic_type) = ST_TIMESTAMP];
 
@@ -677,6 +722,12 @@
 
   // Connection is using locally generated random MAC address.
   optional bool use_randomized_mac = 10 [default = false];
+
+  // Who chose to connect.
+  optional ConnectionNominator connection_nominator = 11;
+
+  // The currently running network selector when this connection event occurred.
+  optional int32 network_selector_experiment_id = 12;
 }
 
 // Number of occurrences of a specific RSSI poll rssi value
@@ -1959,7 +2010,6 @@
   // The total duration elapsed while in this mobility state, in ms
   optional int64 total_duration_ms = 3;
 
-
   // the total duration elapsed while in this mobility state with PNO scans running, in ms
   optional int64 pno_duration_ms = 4;
 }
@@ -2098,6 +2148,8 @@
 
 // Easy Connect (DPP)
 message WifiDppLog {
+  reserved 6;
+
   // Number of Configurator-Initiator requests
   optional int32 num_dpp_configurator_initiator_requests = 1;
 
@@ -2114,7 +2166,7 @@
   repeated DppFailureStatusHistogramBucket dpp_failure_code = 5;
 
   // Easy Connect (DPP) operation time bucket
-  repeated HistogramBucket dpp_operation_time = 6;
+  repeated HistogramBucketInt32 dpp_operation_time = 7;
 
   // Histogram bucket for Wi-Fi DPP configurator success
   message DppConfiguratorSuccessStatusHistogramBucket {
@@ -2134,18 +2186,6 @@
     optional int32 count = 2;
   }
 
-  // Histogram bucket for Wi-Fi DPP logs. Range is [start, end)
-  message HistogramBucket {
-    // lower range of the bucket (inclusive)
-    optional int32 start = 1;
-
-    // upper range of the bucket (exclusive)
-    optional int32 end = 2;
-
-    // number of samples in the bucket
-    optional int32 count = 3;
-  }
-
   enum DppConfiguratorSuccessCode {
     // Unknown success code
     EASY_CONNECT_EVENT_SUCCESS_UNKNOWN = 0;
@@ -2211,3 +2251,135 @@
     optional int32 count = 3;
   }
 }
+
+// Histogram bucket counting with int32. Range is [start, end)
+message HistogramBucketInt32 {
+  // lower range of the bucket (inclusive)
+  optional int32 start = 1;
+
+  // upper range of the bucket (exclusive)
+  optional int32 end = 2;
+
+  // number of samples in the bucket
+  optional int32 count = 3;
+}
+
+// Single entry in a map from int32 => int32
+message MapEntryInt32Int32 {
+  // the key
+  optional int32 key = 1;
+
+  // the value
+  optional int32 value = 2;
+}
+
+message LinkProbeStats {
+  enum LinkProbeFailureReason {
+    // unknown reason
+    LINK_PROBE_FAILURE_REASON_UNKNOWN = 0;
+
+    // Specified MCS rate when it is unsupported by the driver.
+    LINK_PROBE_FAILURE_REASON_MCS_UNSUPPORTED = 1;
+
+    // Driver reported that no ACK was received for the transmitted probe.
+    LINK_PROBE_FAILURE_REASON_NO_ACK = 2;
+
+    // Driver failed to report on the status of the transmitted probe within the timeout.
+    LINK_PROBE_FAILURE_REASON_TIMEOUT = 3;
+
+    // An existing link probe is in progress.
+    LINK_PROBE_FAILURE_REASON_ALREADY_STARTED = 4;
+  }
+
+  // Counts the number of failures for each failure reason.
+  message LinkProbeFailureReasonCount {
+    // The failure reason.
+    optional LinkProbeFailureReason failure_reason = 1;
+
+    // The number of occurrences for this failure reason.
+    optional int32 count = 2;
+  }
+
+  // Counts the occurrences of RSSI values when a link probe succeeds.
+  repeated MapEntryInt32Int32 success_rssi_counts = 1;
+
+  // Counts the occurrences of RSSI values when a link probe fails.
+  repeated MapEntryInt32Int32 failure_rssi_counts = 2;
+
+  // Counts the occurrences of Link Speed values when a link probe succeeds.
+  repeated MapEntryInt32Int32 success_link_speed_counts = 3;
+
+  // Counts the occurrences of Link Speed values when a link probe fails.
+  repeated MapEntryInt32Int32 failure_link_speed_counts = 4;
+
+  // Histogram for the number of seconds since the last TX success when a link probe succeeds.
+  repeated HistogramBucketInt32 success_seconds_since_last_tx_success_histogram = 5;
+
+  // Histogram for the number of seconds since the last TX success when a link probe fails.
+  repeated HistogramBucketInt32 failure_seconds_since_last_tx_success_histogram = 6;
+
+  // Histogram for the elapsed time of successful link probes, in ms.
+  repeated HistogramBucketInt32 success_elapsed_time_ms_histogram = 7;
+
+  // Counts the occurrences of error codes for failed link probes.
+  repeated LinkProbeFailureReasonCount failure_reason_counts = 8;
+}
+
+// Stores the decisions that were made by a experiment when compared against another experiment
+message NetworkSelectionExperimentDecisions {
+  // the id of one experiment
+  optional int32 experiment1_id = 1;
+
+  // the id of the other experiment
+  optional int32 experiment2_id = 2;
+
+  // Counts occurrences of the number of network choices there were when experiment1 makes the
+  // same network selection as experiment2.
+  // The keys are the number of network choices, and the values are the number of occurrences of
+  // this number of network choices when exp1 and exp2 make the same network selection.
+  repeated MapEntryInt32Int32 same_selection_num_choices_counter = 3;
+
+  // Counts occurrences of the number of network choices there were when experiment1 makes the
+  // same network selection as experiment2.
+  // The keys are the number of network choices, and the values are the number of occurrences of
+  // this number of network choices when exp1 and exp2 make different network selections.
+  // Note that it is possible for the network selection to be different even when there only exists
+  // a single network choice, since choosing not to connect to that network is a valid choice.
+  repeated MapEntryInt32Int32 different_selection_num_choices_counter = 4;
+}
+
+// NetworkRequest API metrics.
+message WifiNetworkRequestApiLog {
+  // Number of requests via this API surface.
+  optional int32 num_request = 1;
+
+  // Histogram of requests via this API surface to number of networks matched in scan results.
+  repeated HistogramBucketInt32 network_match_size_histogram = 2;
+
+  // Number of successful network connection from this API.
+  optional int32 num_connect_success = 3;
+
+  // Number of requests via this API surface that bypassed user approval.
+  optional int32 num_user_approval_bypass = 4;
+
+  // Number of requests via this API surface that was rejected by the user.
+  optional int32 num_user_reject = 5;
+
+  // Number of unique apps using this API surface.
+  optional int32 num_apps = 6;
+}
+
+// NetworkSuggestion API metrics.
+message WifiNetworkSuggestionApiLog {
+  // Number of modifications to their suggestions by apps.
+  optional int32 num_modification = 1;
+
+  // Number of successful network connection from app suggestions.
+  optional int32 num_connect_success = 2;
+
+  // Number of network connection failures from app suggestions.
+  optional int32 num_connect_failure = 3;
+
+  // Histogram for size of the network lists provided by various apps on the device.
+  repeated HistogramBucketInt32 network_list_size_histogram = 4;
+}
diff --git a/services/art-profile b/services/art-profile
index 7892fcb..6de96e8 100644
--- a/services/art-profile
+++ b/services/art-profile
@@ -1013,7 +1013,7 @@
 HPLcom/android/server/display/AutomaticBrightnessController;->weightIntegral(J)F
 HPLcom/android/server/display/BrightnessTracker$Injector;->currentTimeMillis()J
 HPLcom/android/server/display/BrightnessTracker$Injector;->elapsedRealtimeNanos()J
-HPLcom/android/server/display/ColorDisplayService$ColorMatrixEvaluator;->evaluate(F[F[F)[F
+HPLcom/android/server/display/color/ColorDisplayService$ColorMatrixEvaluator;->evaluate(F[F[F)[F
 HPLcom/android/server/display/ColorFade;->draw(F)Z
 HPLcom/android/server/display/ColorFade;->drawFaded(FF)V
 HPLcom/android/server/display/DisplayManagerService$BinderService;->getDisplayIds()[I
@@ -3413,7 +3413,7 @@
 Lcom/android/server/devicepolicy/DevicePolicyManagerService$Lifecycle;
 Lcom/android/server/display/-$$Lambda$VirtualDisplayAdapter$PFyqe-aYIEBicSVtuy5lL_bT8B0;
 Lcom/android/server/display/AutomaticBrightnessController$Callbacks;
-Lcom/android/server/display/ColorDisplayService;
+Lcom/android/server/display/color/ColorDisplayService;
 Lcom/android/server/display/DisplayAdapter$1;
 Lcom/android/server/display/DisplayAdapter$2;
 Lcom/android/server/display/DisplayAdapter$Listener;
@@ -3433,7 +3433,7 @@
 Lcom/android/server/display/DisplayManagerService;
 Lcom/android/server/display/DisplayManagerShellCommand;
 Lcom/android/server/display/DisplayPowerController;
-Lcom/android/server/display/DisplayTransformManager;
+Lcom/android/server/display/color/DisplayTransformManager;
 Lcom/android/server/display/LocalDisplayAdapter$DisplayModeRecord;
 Lcom/android/server/display/LocalDisplayAdapter$HotplugDisplayEventReceiver;
 Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice$1;
@@ -10616,39 +10616,39 @@
 PLcom/android/server/display/BrightnessTracker;->writeAmbientBrightnessStats()V
 PLcom/android/server/display/BrightnessTracker;->writeEvents()V
 PLcom/android/server/display/BrightnessTracker;->writeEventsLocked(Ljava/io/OutputStream;)V
-PLcom/android/server/display/ColorDisplayService$2;-><init>(Lcom/android/server/display/ColorDisplayService;Lcom/android/server/display/DisplayTransformManager;)V
-PLcom/android/server/display/ColorDisplayService$2;->onAnimationUpdate(Landroid/animation/ValueAnimator;)V
-PLcom/android/server/display/ColorDisplayService$3;-><init>(Lcom/android/server/display/ColorDisplayService;Lcom/android/server/display/DisplayTransformManager;[F)V
-PLcom/android/server/display/ColorDisplayService$3;->onAnimationEnd(Landroid/animation/Animator;)V
-PLcom/android/server/display/ColorDisplayService$AutoMode;-><init>(Lcom/android/server/display/ColorDisplayService;)V
-PLcom/android/server/display/ColorDisplayService$AutoMode;-><init>(Lcom/android/server/display/ColorDisplayService;Lcom/android/server/display/ColorDisplayService$1;)V
-PLcom/android/server/display/ColorDisplayService$ColorMatrixEvaluator;-><init>()V
-PLcom/android/server/display/ColorDisplayService$ColorMatrixEvaluator;-><init>(Lcom/android/server/display/ColorDisplayService$1;)V
-PLcom/android/server/display/ColorDisplayService$ColorMatrixEvaluator;->evaluate(FLjava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
-PLcom/android/server/display/ColorDisplayService$CustomAutoMode$1;-><init>(Lcom/android/server/display/ColorDisplayService$CustomAutoMode;Lcom/android/server/display/ColorDisplayService;)V
-PLcom/android/server/display/ColorDisplayService$CustomAutoMode;-><init>(Lcom/android/server/display/ColorDisplayService;)V
-PLcom/android/server/display/ColorDisplayService$CustomAutoMode;->onActivated(Z)V
-PLcom/android/server/display/ColorDisplayService$CustomAutoMode;->onAlarm()V
-PLcom/android/server/display/ColorDisplayService$CustomAutoMode;->onStart()V
-PLcom/android/server/display/ColorDisplayService$CustomAutoMode;->updateActivated()V
-PLcom/android/server/display/ColorDisplayService$CustomAutoMode;->updateNextAlarm(Ljava/lang/Boolean;Ljava/time/LocalDateTime;)V
-PLcom/android/server/display/ColorDisplayService;-><init>(Landroid/content/Context;)V
-PLcom/android/server/display/ColorDisplayService;->access$1000(Lcom/android/server/display/ColorDisplayService;)Ljava/lang/Boolean;
-PLcom/android/server/display/ColorDisplayService;->access$602(Lcom/android/server/display/ColorDisplayService;Landroid/animation/ValueAnimator;)Landroid/animation/ValueAnimator;
-PLcom/android/server/display/ColorDisplayService;->applyTint(Z)V
-PLcom/android/server/display/ColorDisplayService;->getDateTimeAfter(Ljava/time/LocalTime;Ljava/time/LocalDateTime;)Ljava/time/LocalDateTime;
-PLcom/android/server/display/ColorDisplayService;->getDateTimeBefore(Ljava/time/LocalTime;Ljava/time/LocalDateTime;)Ljava/time/LocalDateTime;
-PLcom/android/server/display/ColorDisplayService;->isUserSetupCompleted(Landroid/content/ContentResolver;I)Z
-PLcom/android/server/display/ColorDisplayService;->onActivated(Z)V
-PLcom/android/server/display/ColorDisplayService;->onAutoModeChanged(I)V
-PLcom/android/server/display/ColorDisplayService;->onBootPhase(I)V
-PLcom/android/server/display/ColorDisplayService;->onDisplayColorModeChanged(I)V
-PLcom/android/server/display/ColorDisplayService;->onStart()V
-PLcom/android/server/display/ColorDisplayService;->onStartUser(I)V
-PLcom/android/server/display/ColorDisplayService;->onUserChanged(I)V
-PLcom/android/server/display/ColorDisplayService;->setCoefficientMatrix(Landroid/content/Context;Z)V
-PLcom/android/server/display/ColorDisplayService;->setMatrix(I[F)V
-PLcom/android/server/display/ColorDisplayService;->setUp()V
+PLcom/android/server/display/color/ColorDisplayService$2;-><init>(Lcom/android/server/display/color/ColorDisplayService;Lcom/android/server/display/color/DisplayTransformManager;)V
+PLcom/android/server/display/color/ColorDisplayService$2;->onAnimationUpdate(Landroid/animation/ValueAnimator;)V
+PLcom/android/server/display/color/ColorDisplayService$3;-><init>(Lcom/android/server/display/color/ColorDisplayService;Lcom/android/server/display/color/DisplayTransformManager;[F)V
+PLcom/android/server/display/color/ColorDisplayService$3;->onAnimationEnd(Landroid/animation/Animator;)V
+PLcom/android/server/display/color/ColorDisplayService$AutoMode;-><init>(Lcom/android/server/display/color/ColorDisplayService;)V
+PLcom/android/server/display/color/ColorDisplayService$AutoMode;-><init>(Lcom/android/server/display/color/ColorDisplayService;Lcom/android/server/display/color/ColorDisplayService$1;)V
+PLcom/android/server/display/color/ColorDisplayService$ColorMatrixEvaluator;-><init>()V
+PLcom/android/server/display/color/ColorDisplayService$ColorMatrixEvaluator;-><init>(Lcom/android/server/display/color/ColorDisplayService$1;)V
+PLcom/android/server/display/color/ColorDisplayService$ColorMatrixEvaluator;->evaluate(FLjava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
+PLcom/android/server/display/color/ColorDisplayService$CustomAutoMode$1;-><init>(Lcom/android/server/display/color/ColorDisplayService$CustomAutoMode;Lcom/android/server/display/color/ColorDisplayService;)V
+PLcom/android/server/display/color/ColorDisplayService$CustomAutoMode;-><init>(Lcom/android/server/display/color/ColorDisplayService;)V
+PLcom/android/server/display/color/ColorDisplayService$CustomAutoMode;->onActivated(Z)V
+PLcom/android/server/display/color/ColorDisplayService$CustomAutoMode;->onAlarm()V
+PLcom/android/server/display/color/ColorDisplayService$CustomAutoMode;->onStart()V
+PLcom/android/server/display/color/ColorDisplayService$CustomAutoMode;->updateActivated()V
+PLcom/android/server/display/color/ColorDisplayService$CustomAutoMode;->updateNextAlarm(Ljava/lang/Boolean;Ljava/time/LocalDateTime;)V
+PLcom/android/server/display/color/ColorDisplayService;-><init>(Landroid/content/Context;)V
+PLcom/android/server/display/color/ColorDisplayService;->access$1000(Lcom/android/server/display/color/ColorDisplayService;)Ljava/lang/Boolean;
+PLcom/android/server/display/color/ColorDisplayService;->access$602(Lcom/android/server/display/color/ColorDisplayService;Landroid/animation/ValueAnimator;)Landroid/animation/ValueAnimator;
+PLcom/android/server/display/color/ColorDisplayService;->applyTint(Z)V
+PLcom/android/server/display/color/ColorDisplayService;->getDateTimeAfter(Ljava/time/LocalTime;Ljava/time/LocalDateTime;)Ljava/time/LocalDateTime;
+PLcom/android/server/display/color/ColorDisplayService;->getDateTimeBefore(Ljava/time/LocalTime;Ljava/time/LocalDateTime;)Ljava/time/LocalDateTime;
+PLcom/android/server/display/color/ColorDisplayService;->isUserSetupCompleted(Landroid/content/ContentResolver;I)Z
+PLcom/android/server/display/color/ColorDisplayService;->onActivated(Z)V
+PLcom/android/server/display/color/ColorDisplayService;->onAutoModeChanged(I)V
+PLcom/android/server/display/color/ColorDisplayService;->onBootPhase(I)V
+PLcom/android/server/display/color/ColorDisplayService;->onDisplayColorModeChanged(I)V
+PLcom/android/server/display/color/ColorDisplayService;->onStart()V
+PLcom/android/server/display/color/ColorDisplayService;->onStartUser(I)V
+PLcom/android/server/display/color/ColorDisplayService;->onUserChanged(I)V
+PLcom/android/server/display/color/ColorDisplayService;->setCoefficientMatrix(Landroid/content/Context;Z)V
+PLcom/android/server/display/color/ColorDisplayService;->setMatrix(I[F)V
+PLcom/android/server/display/color/ColorDisplayService;->setUp()V
 PLcom/android/server/display/ColorFade$NaturalSurfaceLayout;-><init>(Landroid/hardware/display/DisplayManagerInternal;ILandroid/view/SurfaceControl;)V
 PLcom/android/server/display/ColorFade$NaturalSurfaceLayout;->dispose()V
 PLcom/android/server/display/ColorFade$NaturalSurfaceLayout;->onDisplayTransaction()V
@@ -10878,17 +10878,17 @@
 PLcom/android/server/display/DisplayPowerState;->setScreenBrightness(I)V
 PLcom/android/server/display/DisplayPowerState;->setScreenState(I)V
 PLcom/android/server/display/DisplayPowerState;->waitUntilClean(Ljava/lang/Runnable;)Z
-PLcom/android/server/display/DisplayTransformManager;->applyColorMatrix([F)V
-PLcom/android/server/display/DisplayTransformManager;->applySaturation(F)V
-PLcom/android/server/display/DisplayTransformManager;->computeColorMatrixLocked()[F
-PLcom/android/server/display/DisplayTransformManager;->getColorMatrix(I)[F
-PLcom/android/server/display/DisplayTransformManager;->needsLinearColorMatrix()Z
-PLcom/android/server/display/DisplayTransformManager;->needsLinearColorMatrix(I)Z
-PLcom/android/server/display/DisplayTransformManager;->setColorMatrix(I[F)V
-PLcom/android/server/display/DisplayTransformManager;->setColorMode(I[F)Z
-PLcom/android/server/display/DisplayTransformManager;->setDaltonizerMode(I)V
-PLcom/android/server/display/DisplayTransformManager;->setDisplayColor(I)V
-PLcom/android/server/display/DisplayTransformManager;->updateConfiguration()V
+PLcom/android/server/display/color/DisplayTransformManager;->applyColorMatrix([F)V
+PLcom/android/server/display/color/DisplayTransformManager;->applySaturation(F)V
+PLcom/android/server/display/color/DisplayTransformManager;->computeColorMatrixLocked()[F
+PLcom/android/server/display/color/DisplayTransformManager;->getColorMatrix(I)[F
+PLcom/android/server/display/color/DisplayTransformManager;->needsLinearColorMatrix()Z
+PLcom/android/server/display/color/DisplayTransformManager;->needsLinearColorMatrix(I)Z
+PLcom/android/server/display/color/DisplayTransformManager;->setColorMatrix(I[F)V
+PLcom/android/server/display/color/DisplayTransformManager;->setColorMode(I[F)Z
+PLcom/android/server/display/color/DisplayTransformManager;->setDaltonizerMode(I)V
+PLcom/android/server/display/color/DisplayTransformManager;->setDisplayColor(I)V
+PLcom/android/server/display/color/DisplayTransformManager;->updateConfiguration()V
 PLcom/android/server/display/HysteresisLevels;-><init>([I[I[I)V
 PLcom/android/server/display/HysteresisLevels;->getBrighteningThreshold(F)F
 PLcom/android/server/display/HysteresisLevels;->getDarkeningThreshold(F)F
@@ -19436,7 +19436,7 @@
 SPLcom/android/server/display/DisplayManagerService;->sendDisplayEventLocked(II)V
 SPLcom/android/server/display/DisplayManagerService;->updateDisplayStateLocked(Lcom/android/server/display/DisplayDevice;)Ljava/lang/Runnable;
 SPLcom/android/server/display/DisplayManagerService;->updateLogicalDisplaysLocked()Z
-SPLcom/android/server/display/DisplayTransformManager;-><init>()V
+SPLcom/android/server/display/color/DisplayTransformManager;-><init>()V
 SPLcom/android/server/display/LocalDisplayAdapter$DisplayModeRecord;-><init>(Landroid/view/SurfaceControl$PhysicalDisplayInfo;)V
 SPLcom/android/server/display/LocalDisplayAdapter$DisplayModeRecord;->hasMatchingMode(Landroid/view/SurfaceControl$PhysicalDisplayInfo;)Z
 SPLcom/android/server/display/LocalDisplayAdapter$HotplugDisplayEventReceiver;-><init>(Lcom/android/server/display/LocalDisplayAdapter;Landroid/os/Looper;)V
diff --git a/services/autofill/java/com/android/server/autofill/AutofillManagerService.java b/services/autofill/java/com/android/server/autofill/AutofillManagerService.java
index 1cca813..245e2c9 100644
--- a/services/autofill/java/com/android/server/autofill/AutofillManagerService.java
+++ b/services/autofill/java/com/android/server/autofill/AutofillManagerService.java
@@ -70,6 +70,7 @@
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.infra.AbstractRemoteService;
 import com.android.internal.os.IResultReceiver;
 import com.android.internal.util.DumpUtils;
 import com.android.internal.util.Preconditions;
@@ -109,6 +110,8 @@
     private static final char COMPAT_PACKAGE_URL_IDS_BLOCK_BEGIN = '[';
     private static final char COMPAT_PACKAGE_URL_IDS_BLOCK_END = ']';
 
+    private static final int DEFAULT_AUGMENTED_AUTOFILL_REQUEST_TIMEOUT_MILLIS = 5_000;
+
     /**
      * Maximum number of partitions that can be allowed in a session.
      *
@@ -162,6 +165,11 @@
     @GuardedBy("mLock")
     private int mSupportedSmartSuggestionModes;
 
+    @GuardedBy("mLock")
+    int mAugmentedServiceIdleUnbindTimeoutMs;
+    @GuardedBy("mLock")
+    int mAugmentedServiceRequestTimeoutMs;
+
     public AutofillManagerService(Context context) {
         super(context,
                 new SecureSettingsServiceNameResolver(context, Settings.Secure.AUTOFILL_SERVICE),
@@ -171,12 +179,12 @@
 
         DeviceConfig.addOnPropertyChangedListener(DeviceConfig.NAMESPACE_AUTOFILL,
                 ActivityThread.currentApplication().getMainExecutor(),
-                (namespace, name, value) -> setSmartSuggestionModesFromDeviceConfig(value));
+                (namespace, key, value) -> onDeviceConfigChange(key, value));
 
         setLogLevelFromSettings();
         setMaxPartitionsFromSettings();
         setMaxVisibleDatasetsFromSettings();
-        setSmartSuggestionModesFromDeviceConfig();
+        setDeviceConfigProperties();
 
         final IntentFilter filter = new IntentFilter();
         filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
@@ -227,6 +235,18 @@
         }
     }
 
+    private void onDeviceConfigChange(@NonNull String key, @Nullable String value) {
+        switch (key) {
+            case AutofillManager.DEVICE_CONFIG_AUTOFILL_SMART_SUGGESTION_SUPPORTED_MODES:
+            case AutofillManager.DEVICE_CONFIG_AUGMENTED_SERVICE_IDLE_UNBIND_TIMEOUT:
+            case AutofillManager.DEVICE_CONFIG_AUGMENTED_SERVICE_REQUEST_TIMEOUT:
+                setDeviceConfigProperties();
+                break;
+            default:
+                Slog.i(mTag, "Ignoring change on " + key);
+        }
+    }
+
     @Override // from AbstractMasterSystemService
     protected AutofillManagerServiceImpl newServiceLocked(@UserIdInt int resolvedUserId,
             boolean disabled) {
@@ -457,27 +477,24 @@
         }
     }
 
-    private void setSmartSuggestionModesFromDeviceConfig() {
-        final String value = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_AUTOFILL,
-                AutofillManager.DEVICE_CONFIG_AUTOFILL_SMART_SUGGESTION_SUPPORTED_MODES);
-        setSmartSuggestionModesFromDeviceConfig(value);
-    }
-
-    private void setSmartSuggestionModesFromDeviceConfig(@Nullable String value) {
-        if (sDebug) Slog.d(TAG, "setSmartSuggestionEmulationFromDeviceConfig(): value=" + value);
-        final int flags;
-        if (value == null) {
-            flags = AutofillManager.FLAG_SMART_SUGGESTION_SYSTEM;
-        } else {
-            try {
-                flags = Integer.parseInt(value);
-            } catch (Exception e) {
-                Slog.w(TAG, "setSmartSuggestionEmulationFromDeviceConfig(): NAN:" + value);
-                return;
-            }
-        }
+    private void setDeviceConfigProperties() {
         synchronized (mLock) {
-            mSupportedSmartSuggestionModes = flags;
+            mAugmentedServiceIdleUnbindTimeoutMs = Helper.getIntDeviceConfigProperty(
+                    AutofillManager.DEVICE_CONFIG_AUGMENTED_SERVICE_IDLE_UNBIND_TIMEOUT,
+                    (int) AbstractRemoteService.PERMANENT_BOUND_TIMEOUT_MS);
+            mAugmentedServiceRequestTimeoutMs = Helper.getIntDeviceConfigProperty(
+                    AutofillManager.DEVICE_CONFIG_AUGMENTED_SERVICE_REQUEST_TIMEOUT,
+                    DEFAULT_AUGMENTED_AUTOFILL_REQUEST_TIMEOUT_MILLIS);
+            mSupportedSmartSuggestionModes = Helper.getIntDeviceConfigProperty(
+                    AutofillManager.DEVICE_CONFIG_AUTOFILL_SMART_SUGGESTION_SUPPORTED_MODES,
+                    AutofillManager.FLAG_SMART_SUGGESTION_SYSTEM);
+            if (verbose) {
+                Slog.v(mTag, "setDeviceConfigProperties(): "
+                        + "augmentedIdleTimeout=" + mAugmentedServiceIdleUnbindTimeoutMs
+                        + ", augmentedRequestTimeout=" + mAugmentedServiceRequestTimeoutMs
+                        + ", smartSuggestionMode="
+                        + getSmartSuggestionModeToString(mSupportedSmartSuggestionModes));
+            }
         }
     }
 
@@ -1280,6 +1297,10 @@
                         pw.print("Smart Suggestion modes: ");
                         pw.println(getSmartSuggestionModeToString(mSupportedSmartSuggestionModes));
                     }
+                    pw.print("Augmented Service Idle Unbind Timeout: ");
+                    pw.println(mAugmentedServiceIdleUnbindTimeoutMs);
+                    pw.print("Augmented Service Request Timeout: ");
+                    pw.println(mAugmentedServiceRequestTimeoutMs);
                     if (showHistory) {
                         pw.println(); pw.println("Requests history:"); pw.println();
                         mRequestsHistory.reverseDump(fd, pw, args);
diff --git a/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java b/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
index 2e99654..3f33813 100644
--- a/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
+++ b/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
@@ -98,7 +98,7 @@
     private static final int MAX_SESSION_ID_CREATE_TRIES = 2048;
 
     /** Minimum interval to prune abandoned sessions */
-    private static final int MAX_ABANDONED_SESSION_MILLIS = 30000;
+    private static final int MAX_ABANDONED_SESSION_MILLIS = 30_000;
 
     private final AutoFillUI mUi;
     private final MetricsLogger mMetricsLogger = new MetricsLogger();
@@ -1087,7 +1087,9 @@
                             }
                             mRemoteAugmentedAutofillService = null;
                         }
-                    }, mMaster.isInstantServiceAllowed(), mMaster.verbose);
+                    }, mMaster.isInstantServiceAllowed(), mMaster.verbose,
+                    mMaster.mAugmentedServiceIdleUnbindTimeoutMs,
+                    mMaster.mAugmentedServiceRequestTimeoutMs);
         }
 
         return mRemoteAugmentedAutofillService;
@@ -1097,14 +1099,17 @@
      * Called when the {@link #mAugmentedAutofillResolver} changed (among other places).
      */
     private void updateRemoteAugmentedAutofillService(@Nullable String serviceName) {
-        if (serviceName == null) {
-            if (sVerbose) Slog.v(TAG, "updateRemoteAugmentedAutofillService(): time's up!");
-            synchronized (mLock) {
-                if (mRemoteAugmentedAutofillService != null) {
-                    mRemoteAugmentedAutofillService.destroy();
-                    mRemoteAugmentedAutofillService = null;
+        synchronized (mLock) {
+            if (mRemoteAugmentedAutofillService != null) {
+                if (sVerbose) {
+                    Slog.v(TAG, "updateRemoteAugmentedAutofillService(): "
+                            + "destroying old remote service");
                 }
+                mRemoteAugmentedAutofillService.destroy();
+                mRemoteAugmentedAutofillService = null;
             }
+
+            mRemoteAugmentedAutofillService = getRemoteAugmentedAutofillServiceLocked();
         }
     }
 
diff --git a/services/autofill/java/com/android/server/autofill/Helper.java b/services/autofill/java/com/android/server/autofill/Helper.java
index 3c0da7d..d300bf2 100644
--- a/services/autofill/java/com/android/server/autofill/Helper.java
+++ b/services/autofill/java/com/android/server/autofill/Helper.java
@@ -22,9 +22,11 @@
 import android.app.assist.AssistStructure.ViewNode;
 import android.content.ComponentName;
 import android.metrics.LogMaker;
+import android.provider.DeviceConfig;
 import android.service.autofill.Dataset;
 import android.util.ArrayMap;
 import android.util.ArraySet;
+import android.util.Log;
 import android.util.Slog;
 import android.view.WindowManager;
 import android.view.autofill.AutofillId;
@@ -205,6 +207,21 @@
         }
     }
 
+    /**
+     * Gets the value of a device config property from the Autofill namespace.
+     */
+    static int getIntDeviceConfigProperty(@NonNull String key, int defaultValue) {
+        final String value = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_AUTOFILL, key);
+        if (value == null) return defaultValue;
+
+        try {
+            return Integer.parseInt(value);
+        } catch (Exception e) {
+            Log.w(TAG, "error parsing value (" + value + ") of property " + key + ": " + e);
+            return defaultValue;
+        }
+    }
+
     private interface ViewNodeFilter {
         boolean matches(ViewNode node);
     }
diff --git a/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java b/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
index 88228fb..a38c3cf 100644
--- a/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
+++ b/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
@@ -31,7 +31,6 @@
 import android.service.autofill.augmented.AugmentedAutofillService;
 import android.service.autofill.augmented.IAugmentedAutofillService;
 import android.service.autofill.augmented.IFillCallback;
-import android.text.format.DateUtils;
 import android.util.Pair;
 import android.util.Slog;
 import android.view.autofill.AutofillId;
@@ -48,13 +47,17 @@
 
     private static final String TAG = RemoteAugmentedAutofillService.class.getSimpleName();
 
-    private static final long TIMEOUT_REMOTE_REQUEST_MILLIS = 5 * DateUtils.SECOND_IN_MILLIS;
+    private final int mIdleUnbindTimeoutMs;
+    private final int mRequestTimeoutMs;
 
     RemoteAugmentedAutofillService(Context context, ComponentName serviceName,
             int userId, RemoteAugmentedAutofillServiceCallbacks callbacks,
-            boolean bindInstantServiceAllowed, boolean verbose) {
+            boolean bindInstantServiceAllowed, boolean verbose, int idleUnbindTimeoutMs,
+            int requestTimeoutMs) {
         super(context, AugmentedAutofillService.SERVICE_INTERFACE, serviceName, userId, callbacks,
                 bindInstantServiceAllowed, verbose);
+        mIdleUnbindTimeoutMs = idleUnbindTimeoutMs;
+        mRequestTimeoutMs = requestTimeoutMs;
 
         // Bind right away.
         scheduleBind();
@@ -108,12 +111,12 @@
 
     @Override // from AbstractRemoteService
     protected long getTimeoutIdleBindMillis() {
-        return PERMANENT_BOUND_TIMEOUT_MS;
+        return mIdleUnbindTimeoutMs;
     }
 
     @Override // from AbstractRemoteService
     protected long getRemoteRequestMillis() {
-        return TIMEOUT_REMOTE_REQUEST_MILLIS;
+        return mRequestTimeoutMs;
     }
 
     /**
@@ -209,7 +212,7 @@
         protected void onTimeout(RemoteAugmentedAutofillService remoteService) {
             // TODO(b/122858578): must update the logged AUTOFILL_AUGMENTED_REQUEST with the
             // timeout
-            Slog.w(TAG, "PendingAutofillRequest timed out (" + TIMEOUT_REMOTE_REQUEST_MILLIS
+            Slog.w(TAG, "PendingAutofillRequest timed out (" + remoteService.mRequestTimeoutMs
                     + "ms) for " + remoteService);
             // NOTE: so far we don't need notify RemoteAugmentedAutofillServiceCallbacks
             finish();
diff --git a/services/autofill/java/com/android/server/autofill/Session.java b/services/autofill/java/com/android/server/autofill/Session.java
index 848f249..7fbfc42 100644
--- a/services/autofill/java/com/android/server/autofill/Session.java
+++ b/services/autofill/java/com/android/server/autofill/Session.java
@@ -17,6 +17,7 @@
 package com.android.server.autofill;
 
 import static android.service.autofill.AutofillFieldClassificationService.EXTRA_SCORES;
+import static android.service.autofill.FillRequest.FLAG_AUGMENTED_AUTOFILL_REQUEST;
 import static android.service.autofill.FillRequest.FLAG_MANUAL_REQUEST;
 import static android.service.autofill.FillRequest.INVALID_REQUEST_ID;
 import static android.view.autofill.AutofillManager.ACTION_START_SESSION;
@@ -334,7 +335,7 @@
                 if (mContexts == null) {
                     mContexts = new ArrayList<>(1);
                 }
-                mContexts.add(new FillContext(requestId, structure));
+                mContexts.add(new FillContext(requestId, structure, mCurrentViewId));
 
                 cancelCurrentRequestLocked();
 
@@ -527,6 +528,16 @@
      */
     @GuardedBy("mLock")
     private void requestNewFillResponseLocked(int flags) {
+
+        if ((flags & FLAG_AUGMENTED_AUTOFILL_REQUEST) != 0) {
+            // TODO(b/122858578): log metrics
+            if (sVerbose) {
+                Slog.v(TAG, "requestNewFillResponse(): triggering augmented autofill instead");
+            }
+            triggerAugmentedAutofillLocked();
+            return;
+        }
+
         int requestId;
 
         do {
diff --git a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
index d5713a1..9f7a940 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
@@ -52,6 +52,7 @@
 import android.view.contentcapture.UserDataRemovalRequest;
 
 import com.android.internal.annotations.GuardedBy;
+import com.android.internal.infra.AbstractRemoteService;
 import com.android.internal.os.IResultReceiver;
 import com.android.internal.util.DumpUtils;
 import com.android.internal.util.Preconditions;
@@ -103,11 +104,12 @@
     private boolean mDisabledByDeviceConfig;
 
     // Device-config settings that are cached and passed back to apps
-    public int mDevCfgLoggingLevel;
-    public int mDevCfgMaxBufferSize;
-    public int mDevCfgIdleFlushingFrequencyMs;
-    public int mDevCfgTextChangeFlushingFrequencyMs;
-    public int mDevCfgLogHistorySize;
+    @GuardedBy("mLock") int mDevCfgLoggingLevel;
+    @GuardedBy("mLock") int mDevCfgMaxBufferSize;
+    @GuardedBy("mLock") int mDevCfgIdleFlushingFrequencyMs;
+    @GuardedBy("mLock") int mDevCfgTextChangeFlushingFrequencyMs;
+    @GuardedBy("mLock") int mDevCfgLogHistorySize;
+    @GuardedBy("mLock") int mDevCfgIdleUnbindTimeoutMs;
 
     public ContentCaptureManagerService(@NonNull Context context) {
         super(context, new FrameworkResourcesServiceNameResolver(context,
@@ -238,6 +240,7 @@
             case ContentCaptureManager.DEVICE_CONFIG_PROPERTY_IDLE_FLUSH_FREQUENCY:
             case ContentCaptureManager.DEVICE_CONFIG_PROPERTY_LOG_HISTORY_SIZE:
             case ContentCaptureManager.DEVICE_CONFIG_PROPERTY_TEXT_CHANGE_FLUSH_FREQUENCY:
+            case ContentCaptureManager.DEVICE_CONFIG_PROPERTY_IDLE_UNBIND_TIMEOUT:
                 setFineTuneParamsFromDeviceConfig();
                 return;
             default:
@@ -246,22 +249,29 @@
     }
 
     private void setFineTuneParamsFromDeviceConfig() {
-        mDevCfgMaxBufferSize = ContentCaptureHelper.getIntDeviceConfigProperty(
-                ContentCaptureManager.DEVICE_CONFIG_PROPERTY_MAX_BUFFER_SIZE,
-                ContentCaptureManager.DEFAULT_MAX_BUFFER_SIZE);
-        mDevCfgIdleFlushingFrequencyMs = ContentCaptureHelper.getIntDeviceConfigProperty(
-                ContentCaptureManager.DEVICE_CONFIG_PROPERTY_IDLE_FLUSH_FREQUENCY,
-                ContentCaptureManager.DEFAULT_IDLE_FLUSHING_FREQUENCY_MS);
-        mDevCfgTextChangeFlushingFrequencyMs = ContentCaptureHelper.getIntDeviceConfigProperty(
-                ContentCaptureManager.DEVICE_CONFIG_PROPERTY_TEXT_CHANGE_FLUSH_FREQUENCY,
-                ContentCaptureManager.DEFAULT_TEXT_CHANGE_FLUSHING_FREQUENCY_MS);
-        mDevCfgLogHistorySize = ContentCaptureHelper.getIntDeviceConfigProperty(
-                ContentCaptureManager.DEVICE_CONFIG_PROPERTY_LOG_HISTORY_SIZE, 20);
-        if (verbose) {
-            Slog.v(mTag, "setFineTuneParamsFromDeviceConfig(): bufferSize=" + mDevCfgMaxBufferSize
-                    + ", idleFlush=" + mDevCfgIdleFlushingFrequencyMs
-                    + ", textFluxh=" + mDevCfgTextChangeFlushingFrequencyMs
-                    + ", logHistory=" + mDevCfgLogHistorySize);
+        synchronized (mLock) {
+            mDevCfgMaxBufferSize = ContentCaptureHelper.getIntDeviceConfigProperty(
+                    ContentCaptureManager.DEVICE_CONFIG_PROPERTY_MAX_BUFFER_SIZE,
+                    ContentCaptureManager.DEFAULT_MAX_BUFFER_SIZE);
+            mDevCfgIdleFlushingFrequencyMs = ContentCaptureHelper.getIntDeviceConfigProperty(
+                    ContentCaptureManager.DEVICE_CONFIG_PROPERTY_IDLE_FLUSH_FREQUENCY,
+                    ContentCaptureManager.DEFAULT_IDLE_FLUSHING_FREQUENCY_MS);
+            mDevCfgTextChangeFlushingFrequencyMs = ContentCaptureHelper.getIntDeviceConfigProperty(
+                    ContentCaptureManager.DEVICE_CONFIG_PROPERTY_TEXT_CHANGE_FLUSH_FREQUENCY,
+                    ContentCaptureManager.DEFAULT_TEXT_CHANGE_FLUSHING_FREQUENCY_MS);
+            mDevCfgLogHistorySize = ContentCaptureHelper.getIntDeviceConfigProperty(
+                    ContentCaptureManager.DEVICE_CONFIG_PROPERTY_LOG_HISTORY_SIZE, 20);
+            mDevCfgIdleUnbindTimeoutMs = ContentCaptureHelper.getIntDeviceConfigProperty(
+                    ContentCaptureManager.DEVICE_CONFIG_PROPERTY_IDLE_UNBIND_TIMEOUT,
+                    (int) AbstractRemoteService.PERMANENT_BOUND_TIMEOUT_MS);
+            if (verbose) {
+                Slog.v(mTag, "setFineTuneParamsFromDeviceConfig(): "
+                        + "bufferSize=" + mDevCfgMaxBufferSize
+                        + ", idleFlush=" + mDevCfgIdleFlushingFrequencyMs
+                        + ", textFluxh=" + mDevCfgTextChangeFlushingFrequencyMs
+                        + ", logHistory=" + mDevCfgLogHistorySize
+                        + ", idleUnbindTimeoutMs=" + mDevCfgIdleUnbindTimeoutMs);
+            }
         }
     }
 
@@ -472,6 +482,8 @@
         pw.print(prefix2); pw.print("textChangeFlushingFrequencyMs: ");
         pw.println(mDevCfgTextChangeFlushingFrequencyMs);
         pw.print(prefix2); pw.print("logHistorySize: "); pw.println(mDevCfgLogHistorySize);
+        pw.print(prefix2); pw.print("idleUnbindTimeoutMs: ");
+        pw.println(mDevCfgIdleUnbindTimeoutMs);
     }
 
     final class ContentCaptureManagerServiceStub extends IContentCaptureManager.Stub {
diff --git a/services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java b/services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java
index 5b48046..b33259d 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java
@@ -126,7 +126,7 @@
             mRemoteService = new RemoteContentCaptureService(mMaster.getContext(),
                     ContentCaptureService.SERVICE_INTERFACE, serviceComponentName,
                     mRemoteServiceCallback, mUserId, this, mMaster.isBindInstantServiceAllowed(),
-                    mMaster.verbose);
+                    mMaster.verbose, mMaster.mDevCfgIdleUnbindTimeoutMs);
         }
     }
 
diff --git a/services/contentcapture/java/com/android/server/contentcapture/RemoteContentCaptureService.java b/services/contentcapture/java/com/android/server/contentcapture/RemoteContentCaptureService.java
index f9fda64..dc07c0a 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/RemoteContentCaptureService.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/RemoteContentCaptureService.java
@@ -38,14 +38,16 @@
         IContentCaptureService> {
 
     private final IBinder mServerCallback;
+    private final int mIdleUnbindTimeoutMs;
 
     RemoteContentCaptureService(Context context, String serviceInterface,
             ComponentName serviceComponentName, IContentCaptureServiceCallback callback, int userId,
             ContentCaptureServiceCallbacks callbacks, boolean bindInstantServiceAllowed,
-            boolean verbose) {
+            boolean verbose, int idleUnbindTimeoutMs) {
         super(context, serviceInterface, serviceComponentName, userId, callbacks,
                 bindInstantServiceAllowed, verbose, /* initialCapacity= */ 2);
         mServerCallback = callback.asBinder();
+        mIdleUnbindTimeoutMs = idleUnbindTimeoutMs;
 
         // Bind right away, which will trigger a onConnected() on service's
         scheduleBind();
@@ -58,8 +60,7 @@
 
     @Override // from AbstractRemoteService
     protected long getTimeoutIdleBindMillis() {
-        // TODO(b/111276913): read from Settings so it can be changed in the field
-        return PERMANENT_BOUND_TIMEOUT_MS;
+        return mIdleUnbindTimeoutMs;
     }
 
     @Override // from RemoteService
diff --git a/services/contentsuggestions/java/com/android/server/contentsuggestions/ContentSuggestionsPerUserService.java b/services/contentsuggestions/java/com/android/server/contentsuggestions/ContentSuggestionsPerUserService.java
index 385bc6c..a18686d 100644
--- a/services/contentsuggestions/java/com/android/server/contentsuggestions/ContentSuggestionsPerUserService.java
+++ b/services/contentsuggestions/java/com/android/server/contentsuggestions/ContentSuggestionsPerUserService.java
@@ -80,12 +80,7 @@
     @Override // from PerUserSystemService
     protected boolean updateLocked(boolean disabled) {
         final boolean enabledChanged = super.updateLocked(disabled);
-        if (enabledChanged) {
-            if (!isEnabledLocked()) {
-                // Clear the remote service for the next call
-                mRemoteService = null;
-            }
-        }
+        updateRemoteServiceLocked();
         return enabledChanged;
     }
 
@@ -133,6 +128,15 @@
     }
 
     @GuardedBy("mLock")
+    private void updateRemoteServiceLocked() {
+        if (mRemoteService != null) {
+            mRemoteService.destroy();
+            mRemoteService = null;
+        }
+    }
+
+
+    @GuardedBy("mLock")
     @Nullable
     private RemoteContentSuggestionsService getRemoteServiceLocked() {
         if (mRemoteService == null) {
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index ed459db..9dc673b 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -71,6 +71,8 @@
 import android.net.INetworkPolicyListener;
 import android.net.INetworkPolicyManager;
 import android.net.INetworkStatsService;
+import android.net.InetAddresses;
+import android.net.IpPrefix;
 import android.net.LinkProperties;
 import android.net.LinkProperties.CompareResult;
 import android.net.MatchAllNetworkSpecifier;
@@ -1742,6 +1744,12 @@
                 }
             }
         }
+
+        @Override
+        public void onNat64PrefixEvent(int netId, boolean added,
+                                       String prefixString, int prefixLength) {
+            mHandler.post(() -> handleNat64PrefixEvent(netId, added, prefixString, prefixLength));
+        }
     };
 
     @VisibleForTesting
@@ -2375,6 +2383,11 @@
 
             pw.decreaseIndent();
         }
+
+        pw.println();
+        pw.println("NetworkStackClient logs:");
+        pw.increaseIndent();
+        NetworkStackClient.getInstance().dump(pw);
     }
 
     private void dumpNetworks(IndentingPrintWriter pw) {
@@ -2778,6 +2791,29 @@
         handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
     }
 
+    private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
+            int prefixLength) {
+        NetworkAgentInfo nai = mNetworkForNetId.get(netId);
+        if (nai == null) return;
+
+        log(String.format("NAT64 prefix %s on netId %d: %s/%d",
+                          (added ? "added" : "removed"), netId, prefixString, prefixLength));
+
+        IpPrefix prefix = null;
+        if (added) {
+            try {
+                prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
+                        prefixLength);
+            } catch (IllegalArgumentException e) {
+                loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
+                return;
+            }
+        }
+
+        nai.clatd.setNat64Prefix(prefix);
+        handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
+    }
+
     private void updateLingerState(NetworkAgentInfo nai, long now) {
         // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
         // 2. If the network was lingering and there are now requests, unlinger it.
@@ -2905,7 +2941,7 @@
             e.rethrowFromSystemServer();
         }
         mNetworkAgentInfos.remove(nai.messenger);
-        nai.maybeStopClat();
+        nai.clatd.update();
         synchronized (mNetworkForNetId) {
             // Remove the NetworkAgent, but don't mark the netId as
             // available until we've told netd to delete it below.
@@ -4094,12 +4130,14 @@
     }
 
     /**
-     * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
-     * and not available in ConnectivityManager.
+     * Return the information of all ongoing VPNs.
+     *
+     * <p>This method is used to update NetworkStatsService.
+     *
+     * <p>Must be called on the handler thread.
      */
-    @Override
-    public VpnInfo[] getAllVpnInfo() {
-        enforceConnectivityInternalPermission();
+    private VpnInfo[] getAllVpnInfo() {
+        ensureRunningOnConnectivityServiceThread();
         synchronized (mVpns) {
             if (mLockdownEnabled) {
                 return new VpnInfo[0];
@@ -5251,11 +5289,10 @@
             LinkProperties oldLp) {
         int netId = networkAgent.network.netId;
 
-        // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
-        // we do anything else, make sure its LinkProperties are accurate.
-        if (networkAgent.clatd != null) {
-            networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
-        }
+        // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
+        // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
+        // are accurate.
+        networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
 
         updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
         updateMtu(newLp, oldLp);
@@ -5285,8 +5322,8 @@
             synchronized (networkAgent) {
                 networkAgent.linkProperties = newLp;
             }
-            // Start or stop clat accordingly to network state.
-            networkAgent.updateClat(mNMS);
+            // Start or stop DNS64 detection and 464xlat according to network state.
+            networkAgent.clatd.update();
             notifyIfacesChangedForNetworkStats();
             if (networkAgent.everConnected) {
                 try {
@@ -6434,6 +6471,7 @@
      * Must be called on the handler thread.
      */
     private Network[] getDefaultNetworks() {
+        ensureRunningOnConnectivityServiceThread();
         ArrayList<Network> defaultNetworks = new ArrayList<>();
         NetworkAgentInfo defaultNetwork = getDefaultNetwork();
         for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
@@ -6449,8 +6487,15 @@
      * properties tracked by NetworkStatsService on an active iface has changed.
      */
     private void notifyIfacesChangedForNetworkStats() {
+        ensureRunningOnConnectivityServiceThread();
+        String activeIface = null;
+        LinkProperties activeLinkProperties = getActiveLinkProperties();
+        if (activeLinkProperties != null) {
+            activeIface = activeLinkProperties.getInterfaceName();
+        }
         try {
-            mStatsService.forceUpdateIfaces(getDefaultNetworks());
+            mStatsService.forceUpdateIfaces(
+                    getDefaultNetworks(), getAllVpnInfo(), getAllNetworkState(), activeIface);
         } catch (Exception ignored) {
         }
     }
diff --git a/services/core/java/com/android/server/ExtconUEventObserver.java b/services/core/java/com/android/server/ExtconUEventObserver.java
index 775e4c8..6b42b3d 100644
--- a/services/core/java/com/android/server/ExtconUEventObserver.java
+++ b/services/core/java/com/android/server/ExtconUEventObserver.java
@@ -162,15 +162,6 @@
     /** Does the {@link /sys/class/extcon} directory exist */
     public static boolean extconExists() {
         File extconDir = new File("/sys/class/extcon");
-        boolean retVal = extconDir.exists() && extconDir.isDirectory();
-        // TODO(b/124364409): return the correct value after selinux policy is updated.
-        if (retVal) {
-            Slog.w(TAG, extconDir + " exists " + extconDir.exists() + " isDir "
-                    + extconDir.isDirectory()
-                    + " but reporting it does not exist until selinux policies are updated."
-                    + " see b/124364409"
-            );
-        }
-        return false;
+        return extconDir.exists() && extconDir.isDirectory();
     }
 }
diff --git a/services/core/java/com/android/server/LocationManagerService.java b/services/core/java/com/android/server/LocationManagerService.java
index 5989a46..d7cc19b 100644
--- a/services/core/java/com/android/server/LocationManagerService.java
+++ b/services/core/java/com/android/server/LocationManagerService.java
@@ -337,7 +337,7 @@
                     @Override
                     public void onChange(boolean selfChange) {
                         synchronized (mLock) {
-                            onProviderAllowedChangedLocked(true);
+                            onProviderAllowedChangedLocked();
                         }
                     }
                 }, UserHandle.USER_ALL);
@@ -436,6 +436,10 @@
 
     @GuardedBy("mLock")
     private void onLocationModeChangedLocked(boolean broadcast) {
+        if (D) {
+            Log.d(TAG, "location enabled is now " + isLocationEnabled());
+        }
+
         for (LocationProvider p : mProviders) {
             p.onLocationModeChangedLocked();
         }
@@ -448,16 +452,10 @@
     }
 
     @GuardedBy("mLock")
-    private void onProviderAllowedChangedLocked(boolean broadcast) {
+    private void onProviderAllowedChangedLocked() {
         for (LocationProvider p : mProviders) {
             p.onAllowedChangedLocked();
         }
-
-        if (broadcast) {
-            mContext.sendBroadcastAsUser(
-                    new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
-                    UserHandle.ALL);
-        }
     }
 
     @GuardedBy("mLock")
@@ -827,6 +825,10 @@
             return;
         }
 
+        if (D) {
+            Log.d(TAG, "foreground user is changing to " + userId);
+        }
+
         // let providers know the current user is on the way out before changing the user
         for (LocationProvider p : mProviders) {
             p.onUserChangingLocked();
@@ -839,7 +841,12 @@
 
         // if the user changes, per-user settings may also have changed
         onLocationModeChangedLocked(false);
-        onProviderAllowedChangedLocked(false);
+        onProviderAllowedChangedLocked();
+
+        // always force useability to be rechecked, even if no per-user settings have changed
+        for (LocationProvider p : mProviders) {
+            p.onUseableChangedLocked(false);
+        }
     }
 
     private class LocationProvider implements AbstractLocationProvider.LocationProviderManager {
@@ -891,9 +898,13 @@
         public void attachLocked(AbstractLocationProvider provider) {
             checkNotNull(provider);
             checkState(mProvider == null);
-            mProvider = provider;
 
-            onUseableChangedLocked();
+            if (D) {
+                Log.d(TAG, mName + " provider attached");
+            }
+
+            mProvider = provider;
+            onUseableChangedLocked(false);
         }
 
         public String getName() {
@@ -1054,26 +1065,12 @@
                         return;
                     }
 
-                    mEnabled = enabled;
-
-                    // update provider allowed settings to reflect enabled status
-                    if (mIsManagedBySettings) {
-                        if (mEnabled && !mAllowed) {
-                            Settings.Secure.putStringForUser(
-                                    mContext.getContentResolver(),
-                                    Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
-                                    "+" + mName,
-                                    mCurrentUserId);
-                        } else if (!mEnabled && mAllowed) {
-                            Settings.Secure.putStringForUser(
-                                    mContext.getContentResolver(),
-                                    Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
-                                    "-" + mName,
-                                    mCurrentUserId);
-                        }
+                    if (D) {
+                        Log.d(TAG, mName + " provider enabled is now " + mEnabled);
                     }
 
-                    onUseableChangedLocked();
+                    mEnabled = enabled;
+                    onUseableChangedLocked(false);
                 }
             });
         }
@@ -1091,41 +1088,28 @@
 
         @GuardedBy("mLock")
         public void onLocationModeChangedLocked() {
-            onUseableChangedLocked();
-        }
-
-        private boolean isAllowed() {
-            return isAllowedForUser(mCurrentUserId);
-        }
-
-        private boolean isAllowedForUser(int userId) {
-            String allowedProviders = Settings.Secure.getStringForUser(
-                    mContext.getContentResolver(),
-                    Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
-                    userId);
-            return TextUtils.delimitedStringContains(allowedProviders, ',', mName);
+            onUseableChangedLocked(false);
         }
 
         @GuardedBy("mLock")
         public void onAllowedChangedLocked() {
             if (mIsManagedBySettings) {
-                boolean allowed = isAllowed();
+                String allowedProviders = Settings.Secure.getStringForUser(
+                        mContext.getContentResolver(),
+                        Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
+                        mCurrentUserId);
+                boolean allowed = TextUtils.delimitedStringContains(allowedProviders, ',', mName);
+
                 if (allowed == mAllowed) {
                     return;
                 }
-                mAllowed = allowed;
 
-                // make a best effort to keep the setting matching the real enabled state of the
-                // provider so that legacy applications aren't broken.
-                if (mAllowed && !mEnabled) {
-                    Settings.Secure.putStringForUser(
-                            mContext.getContentResolver(),
-                            Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
-                            "-" + mName,
-                            mCurrentUserId);
+                if (D) {
+                    Log.d(TAG, mName + " provider allowed is now " + mAllowed);
                 }
 
-                onUseableChangedLocked();
+                mAllowed = allowed;
+                onUseableChangedLocked(true);
             }
         }
 
@@ -1140,17 +1124,49 @@
         }
 
         @GuardedBy("mLock")
-        public void onUseableChangedLocked() {
+        private boolean isUseableIgnoringAllowedLocked() {
+            return mProvider != null && mProviders.contains(this) && isLocationEnabled()
+                    && mEnabled;
+        }
+
+        @GuardedBy("mLock")
+        public void onUseableChangedLocked(boolean isAllowedChanged) {
             // if any property that contributes to "useability" here changes state, it MUST result
             // in a direct or indrect call to onUseableChangedLocked. this allows the provider to
             // guarantee that it will always eventually reach the correct state.
-            boolean useable = mProvider != null
-                    && mProviders.contains(this) && isLocationEnabled() && mAllowed && mEnabled;
+            boolean useableIgnoringAllowed = isUseableIgnoringAllowedLocked();
+            boolean useable = useableIgnoringAllowed && mAllowed;
+
+            // update deprecated provider allowed settings for backwards compatibility, and do this
+            // even if there is no change in overall useability state. this may result in trying to
+            // overwrite the same value, but Settings handles deduping this.
+            if (mIsManagedBySettings) {
+                // a "-" change derived from the allowed setting should not be overwritten, but a
+                // "+" change should be corrected if necessary
+                if (useableIgnoringAllowed && !isAllowedChanged) {
+                    Settings.Secure.putStringForUser(
+                            mContext.getContentResolver(),
+                            Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
+                            "+" + mName,
+                            mCurrentUserId);
+                } else if (!useableIgnoringAllowed) {
+                    Settings.Secure.putStringForUser(
+                            mContext.getContentResolver(),
+                            Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
+                            "-" + mName,
+                            mCurrentUserId);
+                }
+            }
+
             if (useable == mUseable) {
                 return;
             }
             mUseable = useable;
 
+            if (D) {
+                Log.d(TAG, mName + " provider useable is now " + mUseable);
+            }
+
             if (!mUseable) {
                 // If any provider has been disabled, clear all last locations for all
                 // providers. This is to be on the safe side in case a provider has location
@@ -1160,6 +1176,10 @@
             }
 
             updateProviderUseableLocked(this);
+
+            mContext.sendBroadcastAsUser(
+                    new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
+                    UserHandle.ALL);
         }
 
         @GuardedBy("mLock")
@@ -1720,7 +1740,7 @@
         mProviders.add(provider);
 
         provider.onAllowedChangedLocked();  // allowed state may change while provider was inactive
-        provider.onUseableChangedLocked();
+        provider.onUseableChangedLocked(false);
     }
 
     @GuardedBy("mLock")
@@ -1728,7 +1748,7 @@
         if (mProviders.remove(provider)) {
             long identity = Binder.clearCallingIdentity();
             try {
-                provider.onUseableChangedLocked();
+                provider.onUseableChangedLocked(false);
             } finally {
                 Binder.restoreCallingIdentity(identity);
             }
@@ -1972,7 +1992,7 @@
                     continue;
                 }
 
-                // requests that ignore location settings will never provider notifications
+                // requests that ignore location settings will never provide notifications
                 if (isSettingsExemptLocked(record)) {
                     continue;
                 }
@@ -2010,19 +2030,22 @@
         WorkSource worksource = new WorkSource();
         ProviderRequest providerRequest = new ProviderRequest();
 
-        long backgroundThrottleInterval;
-
-        long identity = Binder.clearCallingIdentity();
-        try {
-            backgroundThrottleInterval = Settings.Global.getLong(
-                    mContext.getContentResolver(),
-                    Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
-                    DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
-        } finally {
-            Binder.restoreCallingIdentity(identity);
-        }
-
         if (records != null && !records.isEmpty()) {
+            long backgroundThrottleInterval;
+
+            long identity = Binder.clearCallingIdentity();
+            try {
+                backgroundThrottleInterval = Settings.Global.getLong(
+                        mContext.getContentResolver(),
+                        Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
+                        DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
+            } finally {
+                Binder.restoreCallingIdentity(identity);
+            }
+
+            final boolean isForegroundOnlyMode =
+                    mPowerManager.getLocationPowerSaveMode()
+                            == PowerManager.LOCATION_MODE_FOREGROUND_ONLY;
             // initialize the low power mode to true and set to false if any of the records requires
             providerRequest.lowPowerMode = true;
             for (UpdateRecord record : records) {
@@ -2037,7 +2060,9 @@
                         record.mReceiver.mAllowedResolutionLevel)) {
                     continue;
                 }
-                if (!provider.isUseableLocked()) {
+                final boolean isBatterySaverDisablingLocation =
+                        isForegroundOnlyMode && !record.mIsForegroundUid;
+                if (!provider.isUseableLocked() || isBatterySaverDisablingLocation) {
                     if (isSettingsExemptLocked(record)) {
                         providerRequest.locationSettingsIgnored = true;
                         providerRequest.lowPowerMode = false;
@@ -2108,7 +2133,6 @@
             }
         }
 
-        if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
         provider.setRequestLocked(providerRequest, worksource);
     }
 
@@ -2502,7 +2526,6 @@
 
     @Override
     public Location getLastLocation(LocationRequest r, String packageName) {
-        if (D) Log.d(TAG, "getLastLocation: " + r);
         synchronized (mLock) {
             LocationRequest request = r != null ? r : DEFAULT_LOCATION_REQUEST;
             int allowedResolutionLevel = getCallerAllowedResolutionLevel();
@@ -2638,33 +2661,33 @@
         synchronized (mLock) {
             checkResolutionLevelIsSufficientForProviderUseLocked(allowedResolutionLevel,
                     request.getProvider());
-            // Require that caller can manage given document
-            boolean callerHasLocationHardwarePermission =
-                    mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
-                            == PERMISSION_GRANTED;
-            LocationRequest sanitizedRequest = createSanitizedRequest(request,
+        }
+        // Require that caller can manage given document
+        boolean callerHasLocationHardwarePermission =
+                mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
+                        == PERMISSION_GRANTED;
+        LocationRequest sanitizedRequest = createSanitizedRequest(request,
+                allowedResolutionLevel,
+                callerHasLocationHardwarePermission);
+
+        if (D) {
+            Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
+        }
+
+        // geo-fence manager uses the public location API, need to clear identity
+        int uid = Binder.getCallingUid();
+        if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
+            // temporary measure until geofences work for secondary users
+            Log.w(TAG, "proximity alerts are currently available only to the primary user");
+            return;
+        }
+        long identity = Binder.clearCallingIdentity();
+        try {
+            mGeofenceManager.addFence(sanitizedRequest, geofence, intent,
                     allowedResolutionLevel,
-                    callerHasLocationHardwarePermission);
-
-            if (D) {
-                Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
-            }
-
-            // geo-fence manager uses the public location API, need to clear identity
-            int uid = Binder.getCallingUid();
-            if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
-                // temporary measure until geofences work for secondary users
-                Log.w(TAG, "proximity alerts are currently available only to the primary user");
-                return;
-            }
-            long identity = Binder.clearCallingIdentity();
-            try {
-                mGeofenceManager.addFence(sanitizedRequest, geofence, intent,
-                        allowedResolutionLevel,
-                        uid, packageName);
-            } finally {
-                Binder.restoreCallingIdentity(identity);
-            }
+                    uid, packageName);
+        } finally {
+            Binder.restoreCallingIdentity(identity);
         }
     }
 
diff --git a/services/core/java/com/android/server/PinnerService.java b/services/core/java/com/android/server/PinnerService.java
index 526aebe..097a7d6 100644
--- a/services/core/java/com/android/server/PinnerService.java
+++ b/services/core/java/com/android/server/PinnerService.java
@@ -42,6 +42,7 @@
 import android.os.Looper;
 import android.os.Message;
 import android.os.RemoteException;
+import android.os.SystemProperties;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.provider.MediaStore;
@@ -235,9 +236,17 @@
      * Handler for on start pinning message
      */
     private void handlePinOnStart() {
-         // Files to pin come from the overlay and can be specified per-device config
-        String[] filesToPin = mContext.getResources().getStringArray(
-                com.android.internal.R.array.config_defaultPinnerServiceFiles);
+        final String bootImage = SystemProperties.get("dalvik.vm.boot-image", "");
+        String[] filesToPin = null;
+        if (bootImage.endsWith("apex.art")) {
+            // Use the files listed for that specific boot image
+            filesToPin = mContext.getResources().getStringArray(
+                  com.android.internal.R.array.config_apexBootImagePinnerServiceFiles);
+        } else {
+            // Files to pin come from the overlay and can be specified per-device config
+            filesToPin = mContext.getResources().getStringArray(
+                  com.android.internal.R.array.config_defaultPinnerServiceFiles);
+        }
         // Continue trying to pin each file even if we fail to pin some of them
         for (String fileToPin : filesToPin) {
             PinnedFile pf = pinFile(fileToPin,
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index a5eab85..c8e8ef8 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -205,6 +205,9 @@
 
     private static final boolean ENABLE_ISOLATED_STORAGE = StorageManager.hasIsolatedStorage();
 
+    private static final boolean ENABLE_LEGACY_GREYLIST = SystemProperties
+            .getBoolean(StorageManager.PROP_LEGACY_GREYLIST, true);
+
     public static class Lifecycle extends SystemService {
         private StorageManagerService mStorageManagerService;
 
@@ -347,12 +350,6 @@
     @GuardedBy("mPackagesLock")
     private final SparseArray<ArraySet<String>> mPackages = new SparseArray<>();
 
-    /**
-     * List of volumes visible to any user.
-     * TODO: may be have a map of userId -> volumes?
-     */
-    private final CopyOnWriteArrayList<VolumeInfo> mVisibleVols = new CopyOnWriteArrayList<>();
-
     private volatile int mCurrentUserId = UserHandle.USER_SYSTEM;
 
     /** Holding lock for AppFuse business */
@@ -956,8 +953,6 @@
                 addInternalVolumeLocked();
             }
 
-            mVisibleVols.clear();
-
             try {
                 mVold.reset();
 
@@ -1895,9 +1890,6 @@
     private void mount(VolumeInfo vol) {
         try {
             mVold.mount(vol.id, vol.mountFlags, vol.mountUserId);
-            if ((vol.mountFlags & VolumeInfo.MOUNT_FLAG_VISIBLE) != 0) {
-                mVisibleVols.add(vol);
-            }
         } catch (Exception e) {
             Slog.wtf(TAG, e);
         }
@@ -1914,9 +1906,6 @@
     private void unmount(VolumeInfo vol) {
         try {
             mVold.unmount(vol.id);
-            if ((vol.mountFlags & VolumeInfo.MOUNT_FLAG_VISIBLE) != 0) {
-                mVisibleVols.remove(vol);
-            }
         } catch (Exception e) {
             Slog.wtf(TAG, e);
         }
@@ -2303,7 +2292,26 @@
                 refreshIsolatedStorageSettings();
 
                 // Perform hard reboot to kick policy into place
-                mContext.getSystemService(PowerManager.class).reboot(null);
+                mHandler.post(() -> {
+                    mContext.getSystemService(PowerManager.class).reboot(null);
+                });
+            } finally {
+                Binder.restoreCallingIdentity(token);
+            }
+        }
+
+        if ((mask & StorageManager.DEBUG_LEGACY_GREYLIST) != 0) {
+            final boolean enabled = (flags & StorageManager.DEBUG_LEGACY_GREYLIST) != 0;
+
+            final long token = Binder.clearCallingIdentity();
+            try {
+                SystemProperties.set(StorageManager.PROP_LEGACY_GREYLIST,
+                        Boolean.toString(enabled));
+
+                // Perform hard reboot to kick policy into place
+                mHandler.post(() -> {
+                    mContext.getSystemService(PowerManager.class).reboot(null);
+                });
             } finally {
                 Binder.restoreCallingIdentity(token);
             }
@@ -2653,8 +2661,8 @@
         mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
             "no permission to access the crypt keeper");
 
-        if (StorageManager.isFileEncryptedNativeOnly()) {
-            // Not supported on FBE devices
+        if (!StorageManager.isBlockEncrypted()) {
+            // Only supported on FDE devices
             return;
         }
 
@@ -2677,8 +2685,8 @@
         mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
             "no permission to access the crypt keeper");
 
-        if (StorageManager.isFileEncryptedNativeOnly()) {
-            // Not supported on FBE devices
+        if (!StorageManager.isBlockEncrypted()) {
+            // Only supported on FDE devices
             return null;
         }
 
@@ -2975,7 +2983,9 @@
 
     @Override
     public void mkdirs(String callingPkg, String appPath) {
-        final int userId = UserHandle.getUserId(Binder.getCallingUid());
+        final int callingPid = Binder.getCallingPid();
+        final int callingUid = Binder.getCallingUid();
+        final int userId = UserHandle.getUserId(callingUid);
         final UserEnvironment userEnv = new UserEnvironment(userId);
         final String propertyName = "sys.user." + userId + ".ce_available";
 
@@ -2993,7 +3003,7 @@
         // Validate that reported package name belongs to caller
         final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
                 Context.APP_OPS_SERVICE);
-        appOps.checkPackage(Binder.getCallingUid(), callingPkg);
+        appOps.checkPackage(callingUid, callingPkg);
 
         File appFile = null;
         try {
@@ -3012,11 +3022,13 @@
                 appPath = appPath + "/";
             }
 
+            final String systemPath = translateAppToSystem(appPath, callingPid, callingUid);
+
             try {
-                mVold.mkdirs(appPath);
+                mVold.mkdirs(systemPath);
                 return;
             } catch (Exception e) {
-                throw new IllegalStateException("Failed to prepare " + appPath + ": " + e);
+                throw new IllegalStateException("Failed to prepare " + systemPath + ": " + e);
             }
         }
 
@@ -3689,16 +3701,17 @@
             } else if (mPmInternal.isInstantApp(packageName, UserHandle.getUserId(uid))) {
                 return Zygote.MOUNT_EXTERNAL_NONE;
             } else {
-                // STOPSHIP: remove this temporary workaround once developers
-                // fix bugs where they're opening _data paths in native code
-                switch (packageName) {
-                    case "com.facebook.katana": // b/123996076
-                    case "jp.naver.line.android": // b/124767356
-                    case "com.mxtech.videoplayer.ad": // b/124531483
-                        return Zygote.MOUNT_EXTERNAL_LEGACY;
-                    default:
-                        return Zygote.MOUNT_EXTERNAL_WRITE;
+                if (ENABLE_LEGACY_GREYLIST) {
+                    // STOPSHIP: remove this temporary workaround once developers
+                    // fix bugs where they're opening _data paths in native code
+                    switch (packageName) {
+                        case "com.facebook.katana": // b/123996076
+                        case "jp.naver.line.android": // b/124767356
+                        case "com.mxtech.videoplayer.ad": // b/124531483
+                            return Zygote.MOUNT_EXTERNAL_LEGACY;
+                    }
                 }
+                return Zygote.MOUNT_EXTERNAL_WRITE;
             }
         } catch (RemoteException e) {
             // Should not happen
@@ -3851,14 +3864,6 @@
             pw.decreaseIndent();
 
             pw.println();
-            pw.println("mVisibleVols:");
-            pw.increaseIndent();
-            for (int i = 0; i < mVisibleVols.size(); i++) {
-                mVisibleVols.get(i).dump(pw);
-            }
-            pw.decreaseIndent();
-
-            pw.println();
             pw.println("Primary storage UUID: " + mPrimaryStorageUuid);
 
             pw.println();
@@ -4056,38 +4061,9 @@
         }
 
         @Override
-        public String[] getVisibleVolumesForUser(int userId) {
-            synchronized (mLock) {
-                if (!ArrayUtils.contains(mSystemUnlockedUsers, userId)) {
-                    return EmptyArray.STRING;
-                }
-            }
-            final ArrayList<String> visibleVolsForUser = new ArrayList<>();
-            for (int i = mVisibleVols.size() - 1; i >= 0; --i) {
-                final VolumeInfo vol = mVisibleVols.get(i);
-                if (vol.isVisibleForUser(userId)) {
-                    visibleVolsForUser.add(getVolumeLabel(vol));
-                }
-            }
-            return visibleVolsForUser.toArray(new String[visibleVolsForUser.size()]);
-        }
-
-        @Override
         public String getSandboxId(String packageName) {
             return StorageManagerService.this.getSandboxId(packageName,
                     mPmInternal.getSharedUserIdForPackage(packageName));
         }
-
-        private String getVolumeLabel(VolumeInfo vol) {
-            // STOPSHIP: Label needs to part of VolumeInfo and need to be passed on from vold
-            switch (vol.getType()) {
-                case VolumeInfo.TYPE_EMULATED:
-                    return "emulated";
-                case VolumeInfo.TYPE_PUBLIC:
-                    return vol.fsUuid == null ? vol.id : vol.fsUuid;
-                default:
-                    return null;
-            }
-        }
     }
 }
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index fd946cd..0955cc5 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -177,8 +177,6 @@
 
     private ServiceState[] mServiceState;
 
-    private int[] mNetworkType;
-
     private int[] mVoiceActivationState;
 
     private int[] mDataActivationState;
@@ -213,6 +211,9 @@
     private CallAttributes mCallAttributes = new CallAttributes(new PreciseCallState(),
             TelephonyManager.NETWORK_TYPE_UNKNOWN, new CallQuality());
 
+    // network type of the call associated with the mCallAttributes and mCallQuality
+    private int mCallNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
+
     private int[] mSrvccState;
 
     private int mDefaultSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
@@ -375,7 +376,6 @@
         mDataConnectionNetworkType = new int[numPhones];
         mCallIncomingNumber = new String[numPhones];
         mServiceState = new ServiceState[numPhones];
-        mNetworkType = new int[numPhones];
         mVoiceActivationState = new int[numPhones];
         mDataActivationState = new int[numPhones];
         mUserMobileDataState = new boolean[numPhones];
@@ -396,7 +396,6 @@
             mDataActivationState[i] = TelephonyManager.SIM_ACTIVATION_STATE_UNKNOWN;
             mCallIncomingNumber[i] =  "";
             mServiceState[i] =  new ServiceState();
-            mNetworkType[i] = mServiceState[i].getVoiceNetworkType();
             mSignalStrength[i] =  new SignalStrength();
             mUserMobileDataState[i] = false;
             mMessageWaiting[i] =  false;
@@ -998,21 +997,6 @@
             if (validatePhoneId(phoneId)) {
                 mServiceState[phoneId] = state;
 
-                boolean notifyCallAttributes = true;
-                if (mNetworkType[phoneId] != mServiceState[phoneId].getVoiceNetworkType()) {
-                    mNetworkType[phoneId] = state.getVoiceNetworkType();
-                    mCallAttributes = new CallAttributes(mPreciseCallState, mNetworkType[phoneId],
-                            mCallQuality);
-                } else {
-                    // No change to network type, so no need to notify call attributes
-                    notifyCallAttributes = false;
-                }
-
-                if (mCallQuality == null) {
-                    // No call quality reported yet, so no need to notify call attributes
-                    notifyCallAttributes = false;
-                }
-
                 for (Record r : mRecords) {
                     if (VDBG) {
                         log("notifyServiceStateForSubscriber: r=" + r + " subId=" + subId
@@ -1040,14 +1024,6 @@
                             mRemoveList.add(r.binder);
                         }
                     }
-                    if (notifyCallAttributes && r.matchPhoneStateListenerEvent(
-                                    PhoneStateListener.LISTEN_CALL_ATTRIBUTES_CHANGED)) {
-                        try {
-                            r.callback.onCallAttributesChanged(mCallAttributes);
-                        } catch (RemoteException ex) {
-                            mRemoveList.add(r.binder);
-                        }
-                    }
                 }
             } else {
                 log("notifyServiceStateForSubscriber: INVALID phoneId=" + phoneId);
@@ -1479,7 +1455,7 @@
         synchronized (mRecords) {
             mPreciseDataConnectionState = new PreciseDataConnectionState(
                     TelephonyManager.DATA_UNKNOWN,TelephonyManager.NETWORK_TYPE_UNKNOWN,
-                    ApnSetting.getApnTypesBitmaskFromString(apnType), "", null,
+                    ApnSetting.getApnTypesBitmaskFromString(apnType), null, null,
                     DataFailCause.NONE);
             for (Record r : mRecords) {
                 if (r.matchPhoneStateListenerEvent(
@@ -1495,7 +1471,7 @@
         }
         broadcastDataConnectionFailed(apnType, subId);
         broadcastPreciseDataConnectionStateChanged(TelephonyManager.DATA_UNKNOWN,
-                TelephonyManager.NETWORK_TYPE_UNKNOWN, apnType, "", null,
+                TelephonyManager.NETWORK_TYPE_UNKNOWN, apnType, null, null,
                 DataFailCause.NONE);
     }
 
@@ -1574,7 +1550,7 @@
                 log("notifyPreciseCallState: mCallQuality is null, skipping call attributes");
                 notifyCallAttributes = false;
             } else {
-                mCallAttributes = new CallAttributes(mPreciseCallState, mNetworkType[phoneId],
+                mCallAttributes = new CallAttributes(mPreciseCallState, mCallNetworkType,
                         mCallQuality);
             }
 
@@ -1840,16 +1816,16 @@
     }
 
     @Override
-    public void notifyCallQualityChanged(CallQuality callQuality, int phoneId) {
+    public void notifyCallQualityChanged(CallQuality callQuality, int phoneId,
+            int callNetworkType) {
         if (!checkNotifyPermission("notifyCallQualityChanged()")) {
             return;
         }
 
         // merge CallQuality with PreciseCallState and network type
         mCallQuality = callQuality;
-        mCallAttributes = new CallAttributes(mPreciseCallState,
-                mNetworkType[phoneId],
-                callQuality);
+        mCallNetworkType = callNetworkType;
+        mCallAttributes = new CallAttributes(mPreciseCallState, callNetworkType, callQuality);
 
         synchronized (mRecords) {
             TelephonyManager tm = (TelephonyManager) mContext.getSystemService(
@@ -1886,7 +1862,6 @@
                 pw.println("mCallState=" + mCallState[i]);
                 pw.println("mCallIncomingNumber=" + mCallIncomingNumber[i]);
                 pw.println("mServiceState=" + mServiceState[i]);
-                pw.println("mNetworkType=" + mNetworkType[i]);
                 pw.println("mVoiceActivationState= " + mVoiceActivationState[i]);
                 pw.println("mDataActivationState= " + mDataActivationState[i]);
                 pw.println("mUserMobileDataState= " + mUserMobileDataState[i]);
@@ -1900,6 +1875,7 @@
                 pw.println("mImsCallDisconnectCause=" + mImsReasonInfo.get(i).toString());
                 pw.decreaseIndent();
             }
+            pw.println("mCallNetworkType=" + mCallNetworkType);
             pw.println("mPreciseDataConnectionState=" + mPreciseDataConnectionState);
             pw.println("mPreciseCallState=" + mPreciseCallState);
             pw.println("mCallDisconnectCause=" + mCallDisconnectCause);
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index fb541e0..346492f 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -933,6 +933,27 @@
         }
     }
 
+    /**
+     * Return the current foregroundServiceType of the ServiceRecord.
+     * @param className ComponentName of the Service class.
+     * @param token IBinder token.
+     * @return current foreground service type.
+     */
+    public int getForegroundServiceTypeLocked(ComponentName className, IBinder token) {
+        final int userId = UserHandle.getCallingUserId();
+        final long origId = Binder.clearCallingIdentity();
+        int ret = ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
+        try {
+            ServiceRecord r = findServiceLocked(className, token, userId);
+            if (r != null) {
+                ret = r.foregroundServiceType;
+            }
+        } finally {
+            Binder.restoreCallingIdentity(origId);
+        }
+        return ret;
+    }
+
     boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
         if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
                 + aa.mUid);
diff --git a/services/core/java/com/android/server/am/ActivityManagerConstants.java b/services/core/java/com/android/server/am/ActivityManagerConstants.java
index d025d73..415a892 100644
--- a/services/core/java/com/android/server/am/ActivityManagerConstants.java
+++ b/services/core/java/com/android/server/am/ActivityManagerConstants.java
@@ -16,8 +16,6 @@
 
 package com.android.server.am;
 
-import static android.provider.DeviceConfig.ActivityManager.KEY_MAX_CACHED_PROCESSES;
-
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER_QUICK;
 
 import android.app.ActivityThread;
@@ -105,6 +103,12 @@
     private static final long DEFAULT_MEMORY_INFO_THROTTLE_TIME = 5*60*1000;
     private static final long DEFAULT_TOP_TO_FGS_GRACE_DURATION = 15 * 1000;
 
+    // Flag stored in the DeviceConfig API.
+    /**
+     * Maximum number of cached processes.
+     */
+    private static final String KEY_MAX_CACHED_PROCESSES = "max_cached_processes";
+
     // Maximum number of cached processes we will allow.
     public int MAX_CACHED_PROCESSES = DEFAULT_MAX_CACHED_PROCESSES;
 
@@ -292,7 +296,7 @@
         updateConstants();
         updateActivityStartsLoggingEnabled();
         updateBackgroundActivityStartsEnabled();
-        DeviceConfig.addOnPropertyChangedListener(DeviceConfig.ActivityManager.NAMESPACE,
+        DeviceConfig.addOnPropertyChangedListener(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
                 ActivityThread.currentApplication().getMainExecutor(),
                 mOnDeviceConfigChangedListener);
         updateMaxCachedProcesses();
@@ -402,7 +406,7 @@
 
     private void updateActivityStartsLoggingEnabled() {
         mFlagActivityStartsLoggingEnabled = Settings.Global.getInt(mResolver,
-                Settings.Global.ACTIVITY_STARTS_LOGGING_ENABLED, 0) == 1;
+                Settings.Global.ACTIVITY_STARTS_LOGGING_ENABLED, 1) == 1;
     }
 
     private void updateBackgroundActivityStartsEnabled() {
@@ -412,7 +416,7 @@
 
     private void updateMaxCachedProcesses() {
         String maxCachedProcessesFlag = DeviceConfig.getProperty(
-                DeviceConfig.ActivityManager.NAMESPACE, KEY_MAX_CACHED_PROCESSES);
+                DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_MAX_CACHED_PROCESSES);
         try {
             CUR_MAX_CACHED_PROCESSES = mOverrideMaxCachedProcesses < 0
                     ? (TextUtils.isEmpty(maxCachedProcessesFlag)
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 375c5c4..ccb9d82 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -1861,7 +1861,7 @@
                     ProcessRecord proc;
                     int procState;
                     int statType;
-                    int pid;
+                    int pid = -1;
                     long lastPssTime;
                     synchronized (ActivityManagerService.this) {
                         if (mPendingPssProcesses.size() <= 0) {
@@ -2129,6 +2129,7 @@
         private String mExemptionsStr;
         private List<String> mExemptions = Collections.emptyList();
         private int mLogSampleRate = -1;
+        private int mStatslogSampleRate = -1;
         @HiddenApiEnforcementPolicy private int mPolicy = HIDDEN_API_ENFORCEMENT_DEFAULT;
 
         public HiddenApiSettings(Handler handler, Context context) {
@@ -2146,6 +2147,11 @@
                     false,
                     this);
             mContext.getContentResolver().registerContentObserver(
+                    Settings.Global.getUriFor(
+                        Settings.Global.HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE),
+                    false,
+                    this);
+            mContext.getContentResolver().registerContentObserver(
                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_POLICY),
                     false,
                     this);
@@ -2181,6 +2187,15 @@
                 mLogSampleRate = logSampleRate;
                 ZYGOTE_PROCESS.setHiddenApiAccessLogSampleRate(mLogSampleRate);
             }
+            int statslogSampleRate = Settings.Global.getInt(mContext.getContentResolver(),
+                    Settings.Global.HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 0);
+            if (statslogSampleRate < 0 || statslogSampleRate > 0x10000) {
+                statslogSampleRate = -1;
+            }
+            if (statslogSampleRate != -1 && statslogSampleRate != mStatslogSampleRate) {
+                mStatslogSampleRate = statslogSampleRate;
+                ZYGOTE_PROCESS.setHiddenApiAccessStatslogSampleRate(mStatslogSampleRate);
+            }
             mPolicy = getValidEnforcementPolicy(Settings.Global.HIDDEN_API_POLICY);
         }
 
@@ -13586,6 +13601,13 @@
     }
 
     @Override
+    public int getForegroundServiceType(ComponentName className, IBinder token) {
+        synchronized (this) {
+            return mServices.getForegroundServiceTypeLocked(className, token);
+        }
+    }
+
+    @Override
     public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
             boolean requireFull, String name, String callerPackage) {
         return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
@@ -15039,7 +15061,7 @@
                         oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo,
                                 oldRecord.intent,
                                 Activity.RESULT_CANCELED, null, null,
-                                false, false, oldRecord.userId, oldRecord);
+                                false, false, oldRecord.userId);
                     } catch (RemoteException e) {
                         Slog.w(TAG, "Failure ["
                                 + queue.mQueueName + "] sending broadcast result of "
@@ -17110,6 +17132,13 @@
     }
 
     @Override
+    public boolean startUserInForegroundWithListener(final int userId,
+            @Nullable IProgressListener unlockListener) {
+        // Permission check done inside UserController.
+        return mUserController.startUser(userId, /* foreground */ true, unlockListener);
+    }
+
+    @Override
     public boolean unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener) {
         return mUserController.unlockUser(userId, token, secret, listener);
     }
diff --git a/services/core/java/com/android/server/am/AppCompactor.java b/services/core/java/com/android/server/am/AppCompactor.java
index 17ffd9c..1f21160 100644
--- a/services/core/java/com/android/server/am/AppCompactor.java
+++ b/services/core/java/com/android/server/am/AppCompactor.java
@@ -17,14 +17,6 @@
 package com.android.server.am;
 
 import static android.os.Process.THREAD_PRIORITY_FOREGROUND;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_ACTION_1;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_ACTION_2;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_STATSD_SAMPLE_RATE;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_THROTTLE_1;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_THROTTLE_2;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_THROTTLE_3;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_THROTTLE_4;
-import static android.provider.DeviceConfig.ActivityManager.KEY_USE_COMPACTION;
 
 import android.app.ActivityManager;
 import android.app.ActivityThread;
@@ -51,6 +43,17 @@
 
 public final class AppCompactor {
 
+    // Flags stored in the DeviceConfig API.
+    @VisibleForTesting static final String KEY_USE_COMPACTION = "use_compaction";
+    @VisibleForTesting static final String KEY_COMPACT_ACTION_1 = "compact_action_1";
+    @VisibleForTesting static final String KEY_COMPACT_ACTION_2 = "compact_action_2";
+    @VisibleForTesting static final String KEY_COMPACT_THROTTLE_1 = "compact_throttle_1";
+    @VisibleForTesting static final String KEY_COMPACT_THROTTLE_2 = "compact_throttle_2";
+    @VisibleForTesting static final String KEY_COMPACT_THROTTLE_3 = "compact_throttle_3";
+    @VisibleForTesting static final String KEY_COMPACT_THROTTLE_4 = "compact_throttle_4";
+    @VisibleForTesting static final String KEY_COMPACT_STATSD_SAMPLE_RATE =
+            "compact_statsd_sample_rate";
+
     // Phenotype sends int configurations and we map them to the strings we'll use on device,
     // preventing a weird string value entering the kernel.
     private static final int COMPACT_ACTION_FILE_FLAG = 1;
@@ -165,7 +168,7 @@
      * starts the background thread if necessary.
      */
     public void init() {
-        DeviceConfig.addOnPropertyChangedListener(DeviceConfig.ActivityManager.NAMESPACE,
+        DeviceConfig.addOnPropertyChangedListener(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
                 ActivityThread.currentApplication().getMainExecutor(), mOnFlagsChangedListener);
         synchronized (mPhenotypeFlagLock) {
             updateUseCompaction();
@@ -228,7 +231,7 @@
     @GuardedBy("mPhenotypeFlagLock")
     private void updateUseCompaction() {
         String useCompactionFlag =
-                DeviceConfig.getProperty(DeviceConfig.ActivityManager.NAMESPACE,
+                DeviceConfig.getProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
                     KEY_USE_COMPACTION);
         mUseCompaction = TextUtils.isEmpty(useCompactionFlag)
                 ? DEFAULT_USE_COMPACTION : Boolean.parseBoolean(useCompactionFlag);
@@ -241,10 +244,10 @@
     @GuardedBy("mPhenotypeFlagLock")
     private void updateCompactionActions() {
         String compactAction1Flag =
-                DeviceConfig.getProperty(DeviceConfig.ActivityManager.NAMESPACE,
+                DeviceConfig.getProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
                         KEY_COMPACT_ACTION_1);
         String compactAction2Flag =
-                DeviceConfig.getProperty(DeviceConfig.ActivityManager.NAMESPACE,
+                DeviceConfig.getProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
                         KEY_COMPACT_ACTION_2);
 
         int compactAction1 = DEFAULT_COMPACT_ACTION_1;
@@ -271,16 +274,16 @@
     private void updateCompactionThrottles() {
         boolean useThrottleDefaults = false;
         String throttleSomeSomeFlag =
-                DeviceConfig.getProperty(DeviceConfig.ActivityManager.NAMESPACE,
+                DeviceConfig.getProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
                     KEY_COMPACT_THROTTLE_1);
         String throttleSomeFullFlag =
-                DeviceConfig.getProperty(DeviceConfig.ActivityManager.NAMESPACE,
+                DeviceConfig.getProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
                     KEY_COMPACT_THROTTLE_2);
         String throttleFullSomeFlag =
-                DeviceConfig.getProperty(DeviceConfig.ActivityManager.NAMESPACE,
+                DeviceConfig.getProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
                     KEY_COMPACT_THROTTLE_3);
         String throttleFullFullFlag =
-                DeviceConfig.getProperty(DeviceConfig.ActivityManager.NAMESPACE,
+                DeviceConfig.getProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
                     KEY_COMPACT_THROTTLE_4);
 
         if (TextUtils.isEmpty(throttleSomeSomeFlag) || TextUtils.isEmpty(throttleSomeFullFlag)
@@ -309,7 +312,7 @@
 
     @GuardedBy("mPhenotypeFlagLock")
     private void updateStatsdSampleRate() {
-        String sampleRateFlag = DeviceConfig.getProperty(DeviceConfig.ActivityManager.NAMESPACE,
+        String sampleRateFlag = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
                 KEY_COMPACT_STATSD_SAMPLE_RATE);
         try {
             mStatsdSampleRate = TextUtils.isEmpty(sampleRateFlag)
diff --git a/services/core/java/com/android/server/am/BroadcastConstants.java b/services/core/java/com/android/server/am/BroadcastConstants.java
index 820caf1..be17b1b 100644
--- a/services/core/java/com/android/server/am/BroadcastConstants.java
+++ b/services/core/java/com/android/server/am/BroadcastConstants.java
@@ -38,6 +38,8 @@
     static final String KEY_DEFERRAL = "bcast_deferral";
     static final String KEY_DEFERRAL_DECAY_FACTOR = "bcast_deferral_decay_factor";
     static final String KEY_DEFERRAL_FLOOR = "bcast_deferral_floor";
+    static final String KEY_ALLOW_BG_ACTIVITY_START_TIMEOUT =
+            "bcast_allow_bg_activity_start_timeout";
 
     // All time intervals are in milliseconds
     private static final long DEFAULT_TIMEOUT = 10_000;
@@ -45,6 +47,7 @@
     private static final long DEFAULT_DEFERRAL = 5_000;
     private static final float DEFAULT_DEFERRAL_DECAY_FACTOR = 0.75f;
     private static final long DEFAULT_DEFERRAL_FLOOR = 0;
+    private static final long DEFAULT_ALLOW_BG_ACTIVITY_START_TIMEOUT = 10_000;
 
     // All time constants are in milliseconds
 
@@ -59,6 +62,8 @@
     public float DEFERRAL_DECAY_FACTOR = DEFAULT_DEFERRAL_DECAY_FACTOR;
     // Minimum that the deferral time can decay to until the backlog fully clears
     public long DEFERRAL_FLOOR = DEFAULT_DEFERRAL_FLOOR;
+    // For how long after a whitelisted receiver's start its process can start a background activity
+    public long ALLOW_BG_ACTIVITY_START_TIMEOUT = DEFAULT_ALLOW_BG_ACTIVITY_START_TIMEOUT;
 
     // Settings override tracking for this instance
     private String mSettingsKey;
@@ -113,6 +118,8 @@
             DEFERRAL_DECAY_FACTOR = mParser.getFloat(KEY_DEFERRAL_DECAY_FACTOR,
                     DEFERRAL_DECAY_FACTOR);
             DEFERRAL_FLOOR = mParser.getLong(KEY_DEFERRAL_FLOOR, DEFERRAL_FLOOR);
+            ALLOW_BG_ACTIVITY_START_TIMEOUT = mParser.getLong(KEY_ALLOW_BG_ACTIVITY_START_TIMEOUT,
+                    ALLOW_BG_ACTIVITY_START_TIMEOUT);
         }
     }
 
@@ -145,6 +152,9 @@
 
             pw.print("    "); pw.print(KEY_DEFERRAL_FLOOR); pw.print(" = ");
             TimeUtils.formatDuration(DEFERRAL_FLOOR, pw);
+
+            pw.print("    "); pw.print(KEY_ALLOW_BG_ACTIVITY_START_TIMEOUT); pw.print(" = ");
+            TimeUtils.formatDuration(ALLOW_BG_ACTIVITY_START_TIMEOUT, pw);
             pw.println();
         }
     }
diff --git a/services/core/java/com/android/server/am/BroadcastQueue.java b/services/core/java/com/android/server/am/BroadcastQueue.java
index d9ea1da..efb1c44 100644
--- a/services/core/java/com/android/server/am/BroadcastQueue.java
+++ b/services/core/java/com/android/server/am/BroadcastQueue.java
@@ -74,9 +74,6 @@
     static final int MAX_BROADCAST_SUMMARY_HISTORY
             = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
 
-    // For how long after a whitelisted receiver's start its process can start a background activity
-    private static final int RECEIVER_BG_ACTIVITY_START_TIMEOUT_MS = 10_000;
-
     final ActivityManagerService mService;
 
     /**
@@ -310,9 +307,6 @@
         r.curApp = app;
         app.curReceivers.add(r);
         app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
-        if (r.allowBackgroundActivityStarts) {
-            app.addAllowBackgroundActivityStartsToken(r);
-        }
         mService.mProcessList.updateLruProcessLocked(app, false, null);
         if (!skipOomAdj) {
             mService.updateOomAdjLocked();
@@ -454,8 +448,25 @@
             Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
         }
         if (r.allowBackgroundActivityStarts && r.curApp != null) {
-            r.curApp.removeAllowBackgroundActivityStartsToken(r);
-         }
+            if (elapsed > mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT) {
+                // if the receiver has run for more than allowed bg activity start timeout,
+                // just remove the token for this process now and we're done
+                r.curApp.removeAllowBackgroundActivityStartsToken(r);
+            } else {
+                // the receiver had run for less than allowed bg activity start timeout,
+                // so allow the process to still start activities from bg for some more time
+                String msgToken = (r.curApp.toShortString() + r.toString()).intern();
+                // first, if there exists a past scheduled request to remove this token, drop
+                // that request - we don't want the token to be swept from under our feet...
+                mHandler.removeCallbacksAndMessages(msgToken);
+                // ...then schedule the removal of the token after the extended timeout
+                mHandler.postAtTime(() -> {
+                    if (r.curApp != null) {
+                        r.curApp.removeAllowBackgroundActivityStartsToken(r);
+                    }
+                }, msgToken, (r.receiverTime + mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT));
+            }
+        }
         // If we're abandoning this broadcast before any receivers were actually spun up,
         // nextReceiver is zero; in which case time-to-process bookkeeping doesn't apply.
         if (r.nextReceiver > 0) {
@@ -554,7 +565,7 @@
 
     void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
             Intent intent, int resultCode, String data, Bundle extras,
-            boolean ordered, boolean sticky, int sendingUser, BroadcastRecord br)
+            boolean ordered, boolean sticky, int sendingUser)
             throws RemoteException {
         // Send the intent to the receiver asynchronously using one-way binder calls.
         if (app != null) {
@@ -562,15 +573,6 @@
                 // If we have an app thread, do the call through that so it is
                 // correctly ordered with other one-way calls.
                 try {
-                    if (br.allowBackgroundActivityStarts) {
-                        app.addAllowBackgroundActivityStartsToken(br);
-                        // schedule removal of the whitelisting token after the timeout
-                        mHandler.postDelayed(() -> {
-                            if (app != null) {
-                                app.removeAllowBackgroundActivityStartsToken(br);
-                            }
-                        }, RECEIVER_BG_ACTIVITY_START_TIMEOUT_MS);
-                    }
                     app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
                             data, extras, ordered, sticky, sendingUser, app.getReportedProcState());
                 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
@@ -794,9 +796,13 @@
                     skipReceiverLocked(r);
                 }
             } else {
+                if (r.receiverTime == 0) {
+                    r.receiverTime = SystemClock.uptimeMillis();
+                }
+                maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
                 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
                         new Intent(r.intent), r.resultCode, r.resultData,
-                        r.resultExtras, r.ordered, r.initialSticky, r.userId, r);
+                        r.resultExtras, r.ordered, r.initialSticky, r.userId);
             }
             if (ordered) {
                 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
@@ -1100,7 +1106,7 @@
                             }
                             performReceiveLocked(r.callerApp, r.resultTo,
                                     new Intent(r.intent), r.resultCode,
-                                    r.resultData, r.resultExtras, false, false, r.userId, r);
+                                    r.resultData, r.resultExtras, false, false, r.userId);
                             // Set this to null so that the reference
                             // (local and remote) isn't kept in the mBroadcastHistory.
                             r.resultTo = null;
@@ -1255,6 +1261,9 @@
                 r.state = BroadcastRecord.IDLE;
                 scheduleBroadcastsLocked();
             } else {
+                if (filter.receiverList != null) {
+                    maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
+                }
                 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
                     scheduleTempWhitelistLocked(filter.owningUid,
                             brOptions.getTemporaryAppWhitelistDuration(), r);
@@ -1561,6 +1570,7 @@
             try {
                 app.addPackage(info.activityInfo.packageName,
                         info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
+                maybeAddAllowBackgroundActivityStartsToken(app, r);
                 processCurBroadcastLocked(r, app, skipOomAdj);
                 return;
             } catch (RemoteException e) {
@@ -1611,10 +1621,23 @@
             return;
         }
 
+        maybeAddAllowBackgroundActivityStartsToken(r.curApp, r);
         mPendingBroadcast = r;
         mPendingBroadcastRecvIndex = recIdx;
     }
 
+    private void maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r) {
+        if (r == null || proc == null || !r.allowBackgroundActivityStarts) {
+            return;
+        }
+        String msgToken = (proc.toShortString() + r.toString()).intern();
+        // first, if there exists a past scheduled request to remove this token, drop
+        // that request - we don't want the token to be swept from under our feet...
+        mHandler.removeCallbacksAndMessages(msgToken);
+        // ...then add the token
+        proc.addAllowBackgroundActivityStartsToken(r);
+    }
+
     final void setBroadcastTimeoutLocked(long timeoutTime) {
         if (! mPendingBroadcastTimeoutMessage) {
             Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
diff --git a/services/core/java/com/android/server/am/ProcessList.java b/services/core/java/com/android/server/am/ProcessList.java
index 3a61dd9..30798a8 100644
--- a/services/core/java/com/android/server/am/ProcessList.java
+++ b/services/core/java/com/android/server/am/ProcessList.java
@@ -1764,8 +1764,6 @@
                     .getPackagesForUid(uid);
             final StorageManagerInternal storageManagerInternal =
                     LocalServices.getService(StorageManagerInternal.class);
-            final String[] visibleVolIds = storageManagerInternal
-                    .getVisibleVolumesForUser(UserHandle.getUserId(uid));
             final String sandboxId = storageManagerInternal.getSandboxId(app.info.packageName);
             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
                     app.processName);
@@ -1776,7 +1774,7 @@
                         app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                         app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                         app.info.dataDir, null, app.info.packageName,
-                        packageNames, visibleVolIds, sandboxId,
+                        packageNames, sandboxId,
                         new String[] {PROC_START_SEQ_IDENT + app.startSeq});
             } else if (hostingType.equals("app_zygote")) {
                 final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
@@ -1785,14 +1783,14 @@
                         app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                         app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                         app.info.dataDir, null, app.info.packageName,
-                        packageNames, visibleVolIds, sandboxId, /*useBlastulaPool=*/ false,
+                        packageNames, sandboxId, /*useBlastulaPool=*/ false,
                         new String[] {PROC_START_SEQ_IDENT + app.startSeq});
             } else {
                 startResult = Process.start(entryPoint,
                         app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                         app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                         app.info.dataDir, invokeWith, app.info.packageName,
-                        packageNames, visibleVolIds, sandboxId,
+                        packageNames, sandboxId,
                         new String[] {PROC_START_SEQ_IDENT + app.startSeq});
             }
             checkSlow(startTime, "startProcess: returned from zygote!");
diff --git a/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java b/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
index cbbbe47..894a704 100644
--- a/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
+++ b/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
@@ -38,8 +38,9 @@
 /**
  * Maps system settings to system properties.
  * <p>The properties are dynamically updated when settings change.
+ * @hide
  */
-class SettingsToPropertiesMapper {
+public class SettingsToPropertiesMapper {
 
     private static final String TAG = "SettingsToPropertiesMapper";
 
@@ -156,8 +157,8 @@
      * during current device booting.
      * @return
      */
-    public boolean isNativeFlagsResetPerformed() {
-        String value = systemPropertiesGet(RESET_PERFORMED_PROPERTY);
+    public static boolean isNativeFlagsResetPerformed() {
+        String value = SystemProperties.get(RESET_PERFORMED_PROPERTY);
         return "true".equals(value);
     }
 
@@ -166,7 +167,7 @@
      * booting.
      * @return
      */
-    public String[] getResetNativeCategories() {
+    public static String[] getResetNativeCategories() {
         if (!isNativeFlagsResetPerformed()) {
             return new String[0];
         }
@@ -214,7 +215,7 @@
         if (value == null) {
             // It's impossible to remove system property, therefore we check previous value to
             // avoid setting an empty string if the property wasn't set.
-            if (TextUtils.isEmpty(systemPropertiesGet(key))) {
+            if (TextUtils.isEmpty(SystemProperties.get(key))) {
                 return;
             }
             value = "";
@@ -224,7 +225,7 @@
         }
 
         try {
-            systemPropertiesSet(key, value);
+            SystemProperties.set(key, value);
         } catch (Exception e) {
             // Failure to set a property can be caused by SELinux denial. This usually indicates
             // that the property wasn't whitelisted in sepolicy.
@@ -250,17 +251,7 @@
     }
 
     @VisibleForTesting
-    protected String systemPropertiesGet(String key) {
-        return SystemProperties.get(key);
-    }
-
-    @VisibleForTesting
-    protected void systemPropertiesSet(String key, String value) {
-        SystemProperties.set(key, value);
-    }
-
-    @VisibleForTesting
-    protected String getResetFlagsFileContent() {
+    static String getResetFlagsFileContent() {
         String content = null;
         try {
             File reset_flag_file = new File(RESET_RECORD_FILE_PATH);
@@ -279,4 +270,4 @@
         String settingValue = Settings.Global.getString(mContentResolver, settingName);
         setProperty(propName, settingValue);
     }
-}
+}
\ No newline at end of file
diff --git a/services/core/java/com/android/server/am/UserController.java b/services/core/java/com/android/server/am/UserController.java
index ac20f6c..1e406c0 100644
--- a/services/core/java/com/android/server/am/UserController.java
+++ b/services/core/java/com/android/server/am/UserController.java
@@ -2214,7 +2214,11 @@
         void startUserWidgets(int userId) {
             AppWidgetManagerInternal awm = LocalServices.getService(AppWidgetManagerInternal.class);
             if (awm != null) {
-                awm.unlockUser(userId);
+                // Out of band, because this is called during a sequence with
+                // sensitive cross-service lock management
+                FgThread.getHandler().post(() -> {
+                    awm.unlockUser(userId);
+                });
             }
         }
 
diff --git a/services/core/java/com/android/server/appop/HistoricalRegistry.java b/services/core/java/com/android/server/appop/HistoricalRegistry.java
index 708de73..4485a54 100644
--- a/services/core/java/com/android/server/appop/HistoricalRegistry.java
+++ b/services/core/java/com/android/server/appop/HistoricalRegistry.java
@@ -144,7 +144,7 @@
      * Whether history is enabled.
      */
     @GuardedBy("mInMemoryLock")
-    private int mMode = AppOpsManager.HISTORICAL_MODE_ENABLED_ACTIVE;
+    private int mMode = AppOpsManager.HISTORICAL_MODE_DISABLED;
 
     /**
      * This granularity has been chosen to allow clean delineation for intervals
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index afdfbe3..6bd412b 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -88,6 +88,9 @@
 import android.media.audiopolicy.AudioMix;
 import android.media.audiopolicy.AudioPolicy;
 import android.media.audiopolicy.AudioPolicyConfig;
+import android.media.audiopolicy.AudioProductStrategies;
+import android.media.audiopolicy.AudioVolumeGroup;
+import android.media.audiopolicy.AudioVolumeGroups;
 import android.media.audiopolicy.IAudioPolicyCallback;
 import android.media.projection.IMediaProjection;
 import android.media.projection.IMediaProjectionManager;
@@ -127,6 +130,7 @@
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.util.DumpUtils;
+import com.android.internal.util.Preconditions;
 import com.android.internal.util.XmlUtils;
 import com.android.server.EventLogTags;
 import com.android.server.LocalServices;
@@ -274,6 +278,11 @@
 
     private SettingsObserver mSettingsObserver;
 
+    /** @see AudioProductStrategies */
+    private static AudioProductStrategies sAudioProductStrategies;
+    /** @see AudioVolumeGroups */
+    private static AudioVolumeGroups sAudioVolumeGroups;
+
     private int mMode = AudioSystem.MODE_NORMAL;
     // protects mRingerMode
     private final Object mSettingsLock = new Object();
@@ -624,6 +633,9 @@
         mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
         mHasVibrator = mVibrator == null ? false : mVibrator.hasVibrator();
 
+        sAudioProductStrategies = new AudioProductStrategies();
+        sAudioVolumeGroups = new AudioVolumeGroups();
+
         // Initialize volume
         int maxCallVolume = SystemProperties.getInt("ro.config.vc_call_vol_steps", -1);
         if (maxCallVolume != -1) {
@@ -988,6 +1000,22 @@
         }
     }
 
+    /**
+     * @return the {@link android.media.audiopolicy.AudioProductStrategies} discovered from the
+     * platform configuration file.
+     */
+    public @NonNull AudioProductStrategies getAudioProductStrategies() {
+        return sAudioProductStrategies;
+    }
+
+    /**
+     * @return the {@link android.media.audiopolicy.AudioVolumeGroups} discovered from the
+     * platform configuration file.
+     */
+    public @NonNull AudioVolumeGroups listAudioVolumeGroups() {
+        return sAudioVolumeGroups;
+    }
+
     private void checkAllAliasStreamVolumes() {
         synchronized (mSettingsLock) {
             synchronized (VolumeStreamState.class) {
@@ -1878,6 +1906,62 @@
         mStreamStates[stream].mute(index == 0);
     }
 
+    private void enforceModifyAudioRoutingPermission() {
+        if (mContext.checkCallingPermission(
+                    android.Manifest.permission.MODIFY_AUDIO_ROUTING)
+                != PackageManager.PERMISSION_GRANTED) {
+            throw new SecurityException("Missing MODIFY_AUDIO_ROUTING permission");
+        }
+    }
+
+    /** @see AudioManager#setVolumeIndexForAttributes(attr, int, int) */
+    public void setVolumeIndexForAttributes(@NonNull AudioAttributes attr, int index, int flags,
+                                            String callingPackage) {
+        enforceModifyAudioRoutingPermission();
+        Preconditions.checkNotNull(attr, "attr must not be null");
+        // @todo not hold the caller context, post message
+        int stream = sAudioProductStrategies.getLegacyStreamTypeForAudioAttributes(attr);
+        final int device = getDeviceForStream(stream);
+
+        int oldIndex = AudioSystem.getVolumeIndexForAttributes(attr, device);
+
+        AudioSystem.setVolumeIndexForAttributes(attr, index, device);
+
+        final int volumeGroup = sAudioProductStrategies.getVolumeGroupIdForAttributes(attr);
+        final AudioVolumeGroup avg = sAudioVolumeGroups.getById(volumeGroup);
+        if (avg == null) {
+            return;
+        }
+        for (final int groupedStream : avg.getLegacyStreamTypes()) {
+            setStreamVolume(stream, index, flags, callingPackage, callingPackage,
+                            Binder.getCallingUid());
+        }
+    }
+
+    /** @see AudioManager#getVolumeIndexForAttributes(attr) */
+    public int getVolumeIndexForAttributes(@NonNull AudioAttributes attr) {
+        enforceModifyAudioRoutingPermission();
+        Preconditions.checkNotNull(attr, "attr must not be null");
+        int stream = sAudioProductStrategies.getLegacyStreamTypeForAudioAttributes(attr);
+        final int device = getDeviceForStream(stream);
+
+        return AudioSystem.getVolumeIndexForAttributes(attr, device);
+    }
+
+    /** @see AudioManager#getMaxVolumeIndexForAttributes(attr) */
+    public int getMaxVolumeIndexForAttributes(@NonNull AudioAttributes attr) {
+        enforceModifyAudioRoutingPermission();
+        Preconditions.checkNotNull(attr, "attr must not be null");
+        return AudioSystem.getMaxVolumeIndexForAttributes(attr);
+    }
+
+    /** @see AudioManager#getMinVolumeIndexForAttributes(attr) */
+    public int getMinVolumeIndexForAttributes(@NonNull AudioAttributes attr) {
+        enforceModifyAudioRoutingPermission();
+        Preconditions.checkNotNull(attr, "attr must not be null");
+        return AudioSystem.getMinVolumeIndexForAttributes(attr);
+    }
+
     /** @see AudioManager#setStreamVolume(int, int, int) */
     public void setStreamVolume(int streamType, int index, int flags, String callingPackage) {
         if ((streamType == AudioManager.STREAM_ACCESSIBILITY) && !canChangeAccessibilityVolume()) {
@@ -5787,7 +5871,7 @@
     // - wired: logged before onSetWiredDeviceConnectionState() is executed
     // - A2DP: logged at reception of method call
     /*package*/ static final AudioEventLogger sDeviceLogger = new AudioEventLogger(
-            LOG_NB_EVENTS_DEVICE_CONNECTION, "wired/A2DP/hearing aid device connection BLABLI");
+            LOG_NB_EVENTS_DEVICE_CONNECTION, "wired/A2DP/hearing aid device connection");
 
     static final AudioEventLogger sForceUseLogger = new AudioEventLogger(
             LOG_NB_EVENTS_FORCE_USE,
diff --git a/services/core/java/com/android/server/biometrics/BiometricServiceBase.java b/services/core/java/com/android/server/biometrics/BiometricServiceBase.java
index 92a8d93..d787758 100644
--- a/services/core/java/com/android/server/biometrics/BiometricServiceBase.java
+++ b/services/core/java/com/android/server/biometrics/BiometricServiceBase.java
@@ -542,6 +542,9 @@
                     + " failed to respond to cancel, starting client "
                     + (mPendingClient != null ? mPendingClient.getOwnerString() : "null"));
 
+            StatsLog.write(StatsLog.BIOMETRIC_SYSTEM_HEALTH_ISSUE_DETECTED,
+                    statsModality(), BiometricsProtoEnums.ISSUE_CANCEL_TIMED_OUT);
+
             mCurrentClient = null;
             startClient(mPendingClient, false);
         }
@@ -817,6 +820,7 @@
         mHandler.post(() -> {
             ClientMonitor client = mCurrentClient;
             if (client instanceof EnrollClient && client.getToken() == token) {
+                if (DEBUG) Slog.v(getTag(), "Cancelling enrollment");
                 client.stop(client.getToken() == token);
             }
         });
diff --git a/services/core/java/com/android/server/biometrics/ClientMonitor.java b/services/core/java/com/android/server/biometrics/ClientMonitor.java
index e80b39b..87b9eaa 100644
--- a/services/core/java/com/android/server/biometrics/ClientMonitor.java
+++ b/services/core/java/com/android/server/biometrics/ClientMonitor.java
@@ -158,6 +158,7 @@
      */
     public boolean onAcquired(int acquiredInfo, int vendorCode) {
         super.logOnAcquired(acquiredInfo, vendorCode, getTargetUserId());
+        if (DEBUG) Slog.v(getLogTag(), "Acquired: " + acquiredInfo + " " + vendorCode);
         try {
             if (mListener != null) {
                 mListener.onAcquired(getHalDeviceId(), acquiredInfo, vendorCode);
@@ -209,11 +210,7 @@
     public void binderDied() {
         // If the current client dies we should cancel the current operation.
         Slog.e(getLogTag(), "Binder died, cancelling client");
-        try {
-            getDaemonWrapper().cancel();
-        } catch (RemoteException e) {
-            Slog.e(getLogTag(), "Remote exception", e);
-        }
+        stop(false /* initiatedByClient */);
         mToken = null;
         mListener = null;
     }
diff --git a/services/core/java/com/android/server/biometrics/EnrollClient.java b/services/core/java/com/android/server/biometrics/EnrollClient.java
index 882a929..d5e626a 100644
--- a/services/core/java/com/android/server/biometrics/EnrollClient.java
+++ b/services/core/java/com/android/server/biometrics/EnrollClient.java
@@ -76,7 +76,10 @@
         }
         mMetricsLogger.action(mMetrics.actionBiometricEnroll());
         try {
-            getListener().onEnrollResult(identifier, remaining);
+            final BiometricServiceBase.ServiceListener listener = getListener();
+            if (listener != null) {
+                listener.onEnrollResult(identifier, remaining);
+            }
             return remaining == 0;
         } catch (RemoteException e) {
             Slog.w(getLogTag(), "Failed to notify EnrollResult:", e);
diff --git a/services/core/java/com/android/server/connectivity/Nat464Xlat.java b/services/core/java/com/android/server/connectivity/Nat464Xlat.java
index 9d9b1cf..2646d76 100644
--- a/services/core/java/com/android/server/connectivity/Nat464Xlat.java
+++ b/services/core/java/com/android/server/connectivity/Nat464Xlat.java
@@ -18,19 +18,24 @@
 
 import android.net.ConnectivityManager;
 import android.net.INetd;
+import android.net.InetAddresses;
 import android.net.InterfaceConfiguration;
+import android.net.IpPrefix;
 import android.net.LinkAddress;
 import android.net.LinkProperties;
 import android.net.NetworkInfo;
 import android.net.RouteInfo;
 import android.os.INetworkManagementService;
 import android.os.RemoteException;
+import android.os.ServiceSpecificException;
 import android.util.Slog;
 
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.ArrayUtils;
 import com.android.server.net.BaseNetworkObserver;
 
 import java.net.Inet4Address;
+import java.net.Inet6Address;
 import java.util.Objects;
 
 /**
@@ -67,15 +72,16 @@
     private final NetworkAgentInfo mNetwork;
 
     private enum State {
-        IDLE,       // start() not called. Base iface and stacked iface names are null.
-        STARTING,   // start() called. Base iface and stacked iface names are known.
-        RUNNING,    // start() called, and the stacked iface is known to be up.
-        STOPPING;   // stop() called, this Nat464Xlat is still registered as a network observer for
-                    // the stacked interface.
+        IDLE,         // start() not called. Base iface and stacked iface names are null.
+        DISCOVERING,  // same as IDLE, except prefix discovery in progress.
+        STARTING,     // start() called. Base iface and stacked iface names are known.
+        RUNNING,      // start() called, and the stacked iface is known to be up.
     }
 
+    private IpPrefix mNat64Prefix;
     private String mBaseIface;
     private String mIface;
+    private Inet6Address mIPv6Address;
     private State mState = State.IDLE;
 
     public Nat464Xlat(NetworkAgentInfo nai, INetd netd, INetworkManagementService nmService) {
@@ -85,20 +91,51 @@
     }
 
     /**
-     * Determines whether a network requires clat.
+     * Whether to attempt 464xlat on this network. This is true for an IPv6-only network that is
+     * currently connected and where the NetworkAgent has not disabled 464xlat. It is the signal to
+     * enable NAT64 prefix discovery.
+     *
      * @param network the NetworkAgentInfo corresponding to the network.
      * @return true if the network requires clat, false otherwise.
      */
-    public static boolean requiresClat(NetworkAgentInfo nai) {
+    @VisibleForTesting
+    protected static boolean requiresClat(NetworkAgentInfo nai) {
         // TODO: migrate to NetworkCapabilities.TRANSPORT_*.
         final boolean supported = ArrayUtils.contains(NETWORK_TYPES, nai.networkInfo.getType());
         final boolean connected = ArrayUtils.contains(NETWORK_STATES, nai.networkInfo.getState());
-        // We only run clat on networks that don't have a native IPv4 address.
-        final boolean hasIPv4Address =
-                (nai.linkProperties != null) && nai.linkProperties.hasIPv4Address();
-        final boolean skip464xlat =
-                (nai.netMisc() != null) && nai.netMisc().skip464xlat;
-        return supported && connected && !hasIPv4Address && !skip464xlat;
+
+        // Only run clat on networks that have a global IPv6 address and don't have a native IPv4
+        // address.
+        LinkProperties lp = nai.linkProperties;
+        final boolean isIpv6OnlyNetwork = (lp != null) && lp.hasGlobalIPv6Address()
+                && !lp.hasIPv4Address();
+
+        // If the network tells us it doesn't use clat, respect that.
+        final boolean skip464xlat = (nai.netMisc() != null) && nai.netMisc().skip464xlat;
+
+        return supported && connected && isIpv6OnlyNetwork && !skip464xlat;
+    }
+
+    /**
+     * Whether the clat demon should be started on this network now. This is true if requiresClat is
+     * true and a NAT64 prefix has been discovered.
+     *
+     * @param nai the NetworkAgentInfo corresponding to the network.
+     * @return true if the network should start clat, false otherwise.
+     */
+    @VisibleForTesting
+    protected static boolean shouldStartClat(NetworkAgentInfo nai) {
+        LinkProperties lp = nai.linkProperties;
+        return requiresClat(nai) && lp != null && lp.getNat64Prefix() != null;
+    }
+
+    /**
+     * @return true if we have started prefix discovery and not yet stopped it (regardless of
+     * whether it is still running or has succeeded).
+     * A true result corresponds to internal states DISCOVERING, STARTING and RUNNING.
+     */
+    public boolean isPrefixDiscoveryStarted() {
+        return mState == State.DISCOVERING || isStarted();
     }
 
     /**
@@ -106,7 +143,7 @@
      * A true result corresponds to internal states STARTING and RUNNING.
      */
     public boolean isStarted() {
-        return mState != State.IDLE;
+        return (mState == State.STARTING || mState == State.RUNNING);
     }
 
     /**
@@ -124,32 +161,31 @@
     }
 
     /**
-     * @return true if clatd has been stopped.
-     */
-    public boolean isStopping() {
-        return mState == State.STOPPING;
-    }
-
-    /**
      * Start clatd, register this Nat464Xlat as a network observer for the stacked interface,
      * and set internal state.
      */
     private void enterStartingState(String baseIface) {
         try {
             mNMService.registerObserver(this);
-        } catch(RemoteException e) {
-            Slog.e(TAG,
-                    "startClat: Can't register interface observer for clat on " + mNetwork.name());
+        } catch (RemoteException e) {
+            Slog.e(TAG, "Can't register interface observer for clat on " + mNetwork.name());
             return;
         }
+
+        String addrStr = null;
         try {
-            mNetd.clatdStart(baseIface);
-        } catch(RemoteException|IllegalStateException e) {
-            Slog.e(TAG, "Error starting clatd on " + baseIface, e);
+            addrStr = mNetd.clatdStart(baseIface, mNat64Prefix.toString());
+        } catch (RemoteException | ServiceSpecificException e) {
+            Slog.e(TAG, "Error starting clatd on " + baseIface + ": " + e);
         }
         mIface = CLAT_PREFIX + baseIface;
         mBaseIface = baseIface;
         mState = State.STARTING;
+        try {
+            mIPv6Address = (Inet6Address) InetAddresses.parseNumericAddress(addrStr);
+        } catch (ClassCastException | IllegalArgumentException | NullPointerException e) {
+            Slog.e(TAG, "Invalid IPv6 address " + addrStr);
+        }
     }
 
     /**
@@ -161,37 +197,27 @@
     }
 
     /**
-     * Stop clatd, and turn ND offload on if it had been turned off.
-     */
-    private void enterStoppingState() {
-        try {
-            mNetd.clatdStop(mBaseIface);
-        } catch(RemoteException|IllegalStateException e) {
-            Slog.e(TAG, "Error stopping clatd on " + mBaseIface, e);
-        }
-
-        mState = State.STOPPING;
-    }
-
-    /**
      * Unregister as a base observer for the stacked interface, and clear internal state.
      */
-    private void enterIdleState() {
+    private void leaveStartedState() {
         try {
             mNMService.unregisterObserver(this);
-        } catch(RemoteException|IllegalStateException e) {
-            Slog.e(TAG, "Error unregistering clatd observer on " + mBaseIface, e);
+        } catch (RemoteException | IllegalStateException e) {
+            Slog.e(TAG, "Error unregistering clatd observer on " + mBaseIface + ": " + e);
         }
-
         mIface = null;
         mBaseIface = null;
         mState = State.IDLE;
+        if (requiresClat(mNetwork)) {
+            mState = State.DISCOVERING;
+        } else {
+            stopPrefixDiscovery();
+            mState = State.IDLE;
+        }
     }
 
-    /**
-     * Starts the clat daemon.
-     */
-    public void start() {
+    @VisibleForTesting
+    protected void start() {
         if (isStarted()) {
             Slog.e(TAG, "startClat: already started");
             return;
@@ -212,20 +238,82 @@
         enterStartingState(baseIface);
     }
 
-    /**
-     * Stops the clat daemon.
-     */
-    public void stop() {
+    @VisibleForTesting
+    protected void stop() {
         if (!isStarted()) {
+            Slog.e(TAG, "stopClat: already stopped");
             return;
         }
-        Slog.i(TAG, "Stopping clatd on " + mBaseIface);
 
-        boolean wasStarting = isStarting();
-        enterStoppingState();
-        if (wasStarting) {
-            enterIdleState();
+        Slog.i(TAG, "Stopping clatd on " + mBaseIface);
+        try {
+            mNetd.clatdStop(mBaseIface);
+        } catch (RemoteException | ServiceSpecificException e) {
+            Slog.e(TAG, "Error stopping clatd on " + mBaseIface + ": " + e);
         }
+
+        String iface = mIface;
+        boolean wasRunning = isRunning();
+
+        // Change state before updating LinkProperties. handleUpdateLinkProperties ends up calling
+        // fixupLinkProperties, and if at that time the state is still RUNNING, fixupLinkProperties
+        // would wrongly inform ConnectivityService that there is still a stacked interface.
+        leaveStartedState();
+
+        if (wasRunning) {
+            LinkProperties lp = new LinkProperties(mNetwork.linkProperties);
+            lp.removeStackedLink(iface);
+            mNetwork.connService().handleUpdateLinkProperties(mNetwork, lp);
+        }
+    }
+
+    private void startPrefixDiscovery() {
+        try {
+            mNetd.resolverStartPrefix64Discovery(getNetId());
+            mState = State.DISCOVERING;
+        } catch (RemoteException | ServiceSpecificException e) {
+            Slog.e(TAG, "Error starting prefix discovery on netId " + getNetId() + ": " + e);
+        }
+    }
+
+    private void stopPrefixDiscovery() {
+        try {
+            mNetd.resolverStopPrefix64Discovery(getNetId());
+        } catch (RemoteException | ServiceSpecificException e) {
+            Slog.e(TAG, "Error stopping prefix discovery on netId " + getNetId() + ": " + e);
+        }
+    }
+
+    /**
+     * Starts/stops NAT64 prefix discovery and clatd as necessary.
+     */
+    public void update() {
+        // TODO: turn this class into a proper StateMachine. // http://b/126113090
+        if (requiresClat(mNetwork)) {
+            if (!isPrefixDiscoveryStarted()) {
+                startPrefixDiscovery();
+            } else if (shouldStartClat(mNetwork)) {
+                // NAT64 prefix detected. Start clatd.
+                // TODO: support the NAT64 prefix changing after it's been discovered. There is no
+                // need to support this at the moment because it cannot happen without changes to
+                // the Dns64Configuration code in netd.
+                start();
+            } else {
+                // NAT64 prefix removed. Stop clatd and go back into DISCOVERING state.
+                stop();
+            }
+        } else {
+            // Network no longer requires clat. Stop clat and prefix discovery.
+            if (isStarted()) {
+                stop();
+            } else if (isPrefixDiscoveryStarted()) {
+                leaveStartedState();
+            }
+        }
+    }
+
+    public void setNat64Prefix(IpPrefix nat64Prefix) {
+        mNat64Prefix = nat64Prefix;
     }
 
     /**
@@ -234,6 +322,8 @@
      * has no idea that 464xlat is running on top of it.
      */
     public void fixupLinkProperties(LinkProperties oldLp, LinkProperties lp) {
+        lp.setNat64Prefix(mNat64Prefix);
+
         if (!isRunning()) {
             return;
         }
@@ -272,7 +362,7 @@
         try {
             InterfaceConfiguration config = mNMService.getInterfaceConfig(iface);
             return config.getLinkAddress();
-        } catch(RemoteException|IllegalStateException e) {
+        } catch (RemoteException | IllegalStateException e) {
             Slog.e(TAG, "Error getting link properties: " + e);
             return null;
         }
@@ -282,6 +372,20 @@
      * Adds stacked link on base link and transitions to RUNNING state.
      */
     private void handleInterfaceLinkStateChanged(String iface, boolean up) {
+        // TODO: if we call start(), then stop(), then start() again, and the
+        // interfaceLinkStateChanged notification for the first start is delayed past the first
+        // stop, then the code becomes out of sync with system state and will behave incorrectly.
+        //
+        // This is not trivial to fix because:
+        // 1. It is not guaranteed that start() will eventually result in the interface coming up,
+        //    because there could be an error starting clat (e.g., if the interface goes down before
+        //    the packet socket can be bound).
+        // 2. If start is called multiple times, there is nothing in the interfaceLinkStateChanged
+        //    notification that says which start() call the interface was created by.
+        //
+        // Once this code is converted to StateMachine, it will be possible to use deferMessage to
+        // ensure it stays in STARTING state until the interfaceLinkStateChanged notification fires,
+        // and possibly use a timeout (or provide some guarantees at the lower layer) to address #1.
         if (!isStarting() || !up || !Objects.equals(mIface, iface)) {
             return;
         }
@@ -307,20 +411,16 @@
         if (!Objects.equals(mIface, iface)) {
             return;
         }
-        if (!isRunning() && !isStopping()) {
+        if (!isRunning()) {
             return;
         }
 
         Slog.i(TAG, "interface " + iface + " removed");
-        if (!isStopping()) {
-            // Ensure clatd is stopped if stop() has not been called: this likely means that clatd
-            // has crashed.
-            enterStoppingState();
-        }
-        enterIdleState();
-        LinkProperties lp = new LinkProperties(mNetwork.linkProperties);
-        lp.removeStackedLink(iface);
-        mNetwork.connService().handleUpdateLinkProperties(mNetwork, lp);
+        // If we're running, and the interface was removed, then we didn't call stop(), and it's
+        // likely that clatd crashed. Ensure we call stop() so we can start clatd again. Calling
+        // stop() will also update LinkProperties, and if clatd crashed, the LinkProperties update
+        // will cause ConnectivityService to call start() again.
+        stop();
     }
 
     @Override
@@ -337,4 +437,9 @@
     public String toString() {
         return "mBaseIface: " + mBaseIface + ", mIface: " + mIface + ", mState: " + mState;
     }
+
+    @VisibleForTesting
+    protected int getNetId() {
+        return mNetwork.network.netId;
+    }
 }
diff --git a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
index cd4ce2d..6ef9fbb 100644
--- a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
+++ b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
@@ -238,7 +238,7 @@
     public final int factorySerialNumber;
 
     // Used by ConnectivityService to keep track of 464xlat.
-    public Nat464Xlat clatd;
+    public final Nat464Xlat clatd;
 
     // Set after asynchronous creation of the NetworkMonitor.
     private volatile INetworkMonitor mNetworkMonitor;
@@ -246,8 +246,6 @@
     private static final String TAG = ConnectivityService.class.getSimpleName();
     private static final boolean VDBG = false;
     private final ConnectivityService mConnService;
-    private final INetd mNetd;
-    private final INetworkManagementService mNMS;
     private final Context mContext;
     private final Handler mHandler;
 
@@ -262,9 +260,8 @@
         linkProperties = lp;
         networkCapabilities = nc;
         currentScore = score;
+        clatd = new Nat464Xlat(this, netd, nms);
         mConnService = connService;
-        mNetd = netd;
-        mNMS = nms;
         mContext = context;
         mHandler = handler;
         networkMisc = misc;
@@ -598,32 +595,6 @@
         for (LingerTimer timer : mLingerTimers) { pw.println(timer); }
     }
 
-    public void updateClat(INetworkManagementService netd) {
-        if (Nat464Xlat.requiresClat(this)) {
-            maybeStartClat();
-        } else {
-            maybeStopClat();
-        }
-    }
-
-    /** Ensure clat has started for this network. */
-    public void maybeStartClat() {
-        if (clatd != null && clatd.isStarted()) {
-            return;
-        }
-        clatd = new Nat464Xlat(this, mNetd, mNMS);
-        clatd.start();
-    }
-
-    /** Ensure clat has stopped for this network. */
-    public void maybeStopClat() {
-        if (clatd == null) {
-            return;
-        }
-        clatd.stop();
-        clatd = null;
-    }
-
     public String toString() {
         return "NetworkAgentInfo{ ni{" + networkInfo + "}  "
                 + "network{" + network + "}  nethandle{" + network.getNetworkHandle() + "}  "
diff --git a/services/core/java/com/android/server/connectivity/PermissionMonitor.java b/services/core/java/com/android/server/connectivity/PermissionMonitor.java
index 420b23e..d84a4d2 100644
--- a/services/core/java/com/android/server/connectivity/PermissionMonitor.java
+++ b/services/core/java/com/android/server/connectivity/PermissionMonitor.java
@@ -19,10 +19,11 @@
 import static android.Manifest.permission.CHANGE_NETWORK_STATE;
 import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
 import static android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS;
+import static android.Manifest.permission.INTERNET;
 import static android.Manifest.permission.NETWORK_STACK;
-import static android.content.pm.ApplicationInfo.FLAG_SYSTEM;
-import static android.content.pm.ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
+import static android.Manifest.permission.UPDATE_DEVICE_STATS;
 import static android.content.pm.PackageManager.GET_PERMISSIONS;
+import static android.content.pm.PackageManager.MATCH_ANY_USER;
 import static android.os.Process.INVALID_UID;
 import static android.os.Process.SYSTEM_UID;
 
@@ -32,23 +33,31 @@
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.PackageManagerInternal;
 import android.content.pm.UserInfo;
-import android.net.Uri;
+import android.net.INetd;
+import android.net.util.NetdService;
 import android.os.Build;
 import android.os.INetworkManagementService;
 import android.os.RemoteException;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.util.Log;
+import android.util.Slog;
+import android.util.SparseIntArray;
 
+import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.ArrayUtils;
+import com.android.server.LocalServices;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Map.Entry;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Set;
 
 /**
@@ -75,6 +84,59 @@
     // Keys are App IDs. Values are true for SYSTEM permission and false for NETWORK permission.
     private final Map<Integer, Boolean> mApps = new HashMap<>();
 
+    // Keys are App packageNames, Values are app uids. . We need to keep track of this information
+    // because PackageListObserver#onPackageRemoved does not pass the UID.
+    @GuardedBy("mPackageNameUidMap")
+    private final Map<String, Integer> mPackageNameUidMap = new HashMap<>();
+
+    private class PackageListObserver implements PackageManagerInternal.PackageListObserver {
+        @Override
+        public void onPackageAdded(String packageName) {
+            final PackageInfo app = getPackageInfo(packageName);
+            if (app == null) {
+                Slog.wtf(TAG, "Failed to get information of installed package: " + packageName);
+                return;
+            }
+            int uid = (app.applicationInfo != null) ? app.applicationInfo.uid : INVALID_UID;
+            if (uid == INVALID_UID) {
+                Slog.wtf(TAG, "Failed to get the uid of installed package: " + packageName
+                        + "uid: " + uid);
+                return;
+            }
+            if (app.requestedPermissions == null) {
+                return;
+            }
+            sendPackagePermissionsForUid(uid,
+                    filterPermission(Arrays.asList(app.requestedPermissions)));
+            synchronized (mPackageNameUidMap) {
+                mPackageNameUidMap.put(packageName, uid);
+            }
+        }
+
+        @Override
+        public void onPackageRemoved(String packageName) {
+            int uid;
+            synchronized (mPackageNameUidMap) {
+                if (!mPackageNameUidMap.containsKey(packageName)) {
+                    return;
+                }
+                uid = mPackageNameUidMap.get(packageName);
+                mPackageNameUidMap.remove(packageName);
+            }
+            int permission = 0;
+            String[] packages = mPackageManager.getPackagesForUid(uid);
+            if (packages != null && packages.length > 0) {
+                for (String name : packages) {
+                    final PackageInfo app = getPackageInfo(name);
+                    if (app != null && app.requestedPermissions != null) {
+                        permission |= filterPermission(Arrays.asList(app.requestedPermissions));
+                    }
+                }
+            }
+            sendPackagePermissionsForUid(uid, permission);
+        }
+    }
+
     public PermissionMonitor(Context context, INetworkManagementService netd) {
         mContext = context;
         mPackageManager = context.getPackageManager();
@@ -87,12 +149,21 @@
     public synchronized void startMonitoring() {
         log("Monitoring");
 
-        List<PackageInfo> apps = mPackageManager.getInstalledPackages(GET_PERMISSIONS);
+        PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
+        if (pmi != null) {
+            pmi.getPackageList(new PackageListObserver());
+        } else {
+            loge("failed to get the PackageManagerInternal service");
+        }
+        List<PackageInfo> apps = mPackageManager.getInstalledPackages(GET_PERMISSIONS
+                | MATCH_ANY_USER);
         if (apps == null) {
             loge("No apps");
             return;
         }
 
+        SparseIntArray netdPermsUids = new SparseIntArray();
+
         for (PackageInfo app : apps) {
             int uid = app.applicationInfo != null ? app.applicationInfo.uid : INVALID_UID;
             if (uid < 0) {
@@ -110,6 +181,17 @@
                     mApps.put(uid, hasRestrictedPermission);
                 }
             }
+
+            //TODO: unify the management of the permissions into one codepath.
+            if (app.requestedPermissions != null) {
+                int otherNetdPerms = filterPermission(Arrays.asList(app.requestedPermissions));
+                if (otherNetdPerms != 0) {
+                    netdPermsUids.put(uid, netdPermsUids.get(uid) | otherNetdPerms);
+                    synchronized (mPackageNameUidMap) {
+                        mPackageNameUidMap.put(app.applicationInfo.packageName, uid);
+                    }
+                }
+            }
         }
 
         List<UserInfo> users = mUserManager.getUsers(true);  // exclude dying users
@@ -121,6 +203,7 @@
 
         log("Users: " + mUsers.size() + ", Apps: " + mApps.size());
         update(mUsers, mApps, true);
+        sendPackagePermissionsToNetd(netdPermsUids);
     }
 
     @VisibleForTesting
@@ -339,6 +422,107 @@
         }
     }
 
+    private static int filterPermission(List<String> requestedPermissions) {
+        int permissions = 0;
+        if (requestedPermissions.contains(INTERNET)) {
+            permissions |= INetd.PERMISSION_INTERNET;
+        }
+        if (requestedPermissions.contains(UPDATE_DEVICE_STATS)) {
+            permissions |= INetd.PERMISSION_UPDATE_DEVICE_STATS;
+        }
+        return permissions;
+    }
+
+    private PackageInfo getPackageInfo(String packageName) {
+        try {
+            PackageInfo app = mPackageManager.getPackageInfo(packageName, GET_PERMISSIONS
+                    | MATCH_ANY_USER);
+            return app;
+        } catch (NameNotFoundException e) {
+            // App not found.
+            loge("NameNotFoundException " + packageName);
+            return null;
+        }
+    }
+
+    /**
+     * Called by PackageListObserver when a package is installed/uninstalled. Send the updated
+     * permission information to netd.
+     *
+     * @param uid the app uid of the package installed
+     * @param permissions the permissions the app requested and netd cares about.
+     *
+     * @hide
+     */
+    private void sendPackagePermissionsForUid(int uid, int permissions) {
+        SparseIntArray netdPermissionsAppIds = new SparseIntArray();
+        netdPermissionsAppIds.put(uid, permissions);
+        sendPackagePermissionsToNetd(netdPermissionsAppIds);
+    }
+
+    /**
+     * Called by packageManagerService to send IPC to netd. Grant or revoke the INTERNET
+     * and/or UPDATE_DEVICE_STATS permission of the uids in array.
+     *
+     * @param netdPermissionsAppIds integer pairs of uids and the permission granted to it. If the
+     * permission is 0, revoke all permissions of that uid.
+     *
+     * @hide
+     */
+    private void sendPackagePermissionsToNetd(SparseIntArray netdPermissionsAppIds) {
+        INetd netdService = NetdService.getInstance();
+        if (netdService == null) {
+            Log.e(TAG, "Failed to get the netd service");
+            return;
+        }
+        ArrayList<Integer> allPermissionAppIds = new ArrayList<>();
+        ArrayList<Integer> internetPermissionAppIds = new ArrayList<>();
+        ArrayList<Integer> updateStatsPermissionAppIds = new ArrayList<>();
+        ArrayList<Integer> uninstalledAppIds = new ArrayList<>();
+        for (int i = 0; i < netdPermissionsAppIds.size(); i++) {
+            int permissions = netdPermissionsAppIds.valueAt(i);
+            switch(permissions) {
+                case (INetd.PERMISSION_INTERNET | INetd.PERMISSION_UPDATE_DEVICE_STATS):
+                    allPermissionAppIds.add(netdPermissionsAppIds.keyAt(i));
+                    break;
+                case INetd.PERMISSION_INTERNET:
+                    internetPermissionAppIds.add(netdPermissionsAppIds.keyAt(i));
+                    break;
+                case INetd.PERMISSION_UPDATE_DEVICE_STATS:
+                    updateStatsPermissionAppIds.add(netdPermissionsAppIds.keyAt(i));
+                    break;
+                case INetd.NO_PERMISSIONS:
+                    uninstalledAppIds.add(netdPermissionsAppIds.keyAt(i));
+                    break;
+                default:
+                    Log.e(TAG, "unknown permission type: " + permissions + "for uid: "
+                            + netdPermissionsAppIds.keyAt(i));
+            }
+        }
+        try {
+            // TODO: add a lock inside netd to protect IPC trafficSetNetPermForUids()
+            if (allPermissionAppIds.size() != 0) {
+                netdService.trafficSetNetPermForUids(
+                        INetd.PERMISSION_INTERNET | INetd.PERMISSION_UPDATE_DEVICE_STATS,
+                        ArrayUtils.convertToIntArray(allPermissionAppIds));
+            }
+            if (internetPermissionAppIds.size() != 0) {
+                netdService.trafficSetNetPermForUids(INetd.PERMISSION_INTERNET,
+                        ArrayUtils.convertToIntArray(internetPermissionAppIds));
+            }
+            if (updateStatsPermissionAppIds.size() != 0) {
+                netdService.trafficSetNetPermForUids(INetd.PERMISSION_UPDATE_DEVICE_STATS,
+                        ArrayUtils.convertToIntArray(updateStatsPermissionAppIds));
+            }
+            if (uninstalledAppIds.size() != 0) {
+                netdService.trafficSetNetPermForUids(INetd.NO_PERMISSIONS,
+                        ArrayUtils.convertToIntArray(uninstalledAppIds));
+            }
+        } catch (RemoteException e) {
+            Log.e(TAG, "Pass appId list of special permission failed." + e);
+        }
+    }
+
     private static void log(String s) {
         if (DBG) {
             Log.d(TAG, s);
diff --git a/services/core/java/com/android/server/content/SyncManager.java b/services/core/java/com/android/server/content/SyncManager.java
index 8a208a5..9f80a83 100644
--- a/services/core/java/com/android/server/content/SyncManager.java
+++ b/services/core/java/com/android/server/content/SyncManager.java
@@ -1639,13 +1639,12 @@
             }
         }
 
-        if (syncOperation.isAppStandbyExempted()) {
-            final UsageStatsManagerInternal usmi = LocalServices.getService(
-                    UsageStatsManagerInternal.class);
-            if (usmi != null) {
-                usmi.reportExemptedSyncScheduled(syncOperation.owningPackage,
-                        UserHandle.getUserId(syncOperation.owningUid));
-            }
+        final UsageStatsManagerInternal usmi =
+                LocalServices.getService(UsageStatsManagerInternal.class);
+        if (usmi != null) {
+            usmi.reportSyncScheduled(syncOperation.owningPackage,
+                    UserHandle.getUserId(syncOperation.owningUid),
+                    syncOperation.isAppStandbyExempted());
         }
 
         getJobScheduler().scheduleAsPackage(b.build(), syncOperation.owningPackage,
diff --git a/services/core/java/com/android/server/display/AutomaticBrightnessController.java b/services/core/java/com/android/server/display/AutomaticBrightnessController.java
index d57431e..1f28a6c 100644
--- a/services/core/java/com/android/server/display/AutomaticBrightnessController.java
+++ b/services/core/java/com/android/server/display/AutomaticBrightnessController.java
@@ -288,6 +288,10 @@
         return mScreenAutoBrightness;
     }
 
+    public boolean hasValidAmbientLux() {
+        return mAmbientLuxValid;
+    }
+
     public float getAutomaticScreenBrightnessAdjustment() {
         return mBrightnessMapper.getAutoBrightnessAdjustment();
     }
@@ -648,9 +652,9 @@
                 mLightSensorWarmUpTimeConfig + mLightSensorEnableTime;
             if (time < timeWhenSensorWarmedUp) {
                 if (mLoggingEnabled) {
-                    Slog.d(TAG, "updateAmbientLux: Sensor not  ready yet: " +
-                            "time=" + time + ", " +
-                            "timeWhenSensorWarmedUp=" + timeWhenSensorWarmedUp);
+                    Slog.d(TAG, "updateAmbientLux: Sensor not ready yet: "
+                            + "time=" + time + ", "
+                            + "timeWhenSensorWarmedUp=" + timeWhenSensorWarmedUp);
                 }
                 mHandler.sendEmptyMessageAtTime(MSG_UPDATE_AMBIENT_LUX,
                         timeWhenSensorWarmedUp);
diff --git a/services/core/java/com/android/server/display/DisplayManagerService.java b/services/core/java/com/android/server/display/DisplayManagerService.java
index b020997..1aaaf41 100644
--- a/services/core/java/com/android/server/display/DisplayManagerService.java
+++ b/services/core/java/com/android/server/display/DisplayManagerService.java
@@ -37,7 +37,9 @@
 import android.content.res.Resources;
 import android.content.res.TypedArray;
 import android.graphics.ColorSpace;
+import android.graphics.GraphicBuffer;
 import android.graphics.Point;
+import android.graphics.Rect;
 import android.hardware.SensorManager;
 import android.hardware.display.AmbientBrightnessDayStats;
 import android.hardware.display.BrightnessChangeEvent;
@@ -94,7 +96,6 @@
 import com.android.server.LocalServices;
 import com.android.server.SystemService;
 import com.android.server.UiThread;
-import com.android.server.display.ColorDisplayService.ColorDisplayServiceInternal;
 import com.android.server.wm.SurfaceAnimationThread;
 import com.android.server.wm.WindowManagerInternal;
 
@@ -355,7 +356,6 @@
         publishBinderService(Context.DISPLAY_SERVICE, new BinderService(),
                 true /*allowIsolated*/);
         publishLocalService(DisplayManagerInternal.class, new LocalService());
-        publishLocalService(DisplayTransformManager.class, new DisplayTransformManager());
     }
 
     @Override
@@ -1277,7 +1277,14 @@
         if (token == null) {
             return false;
         }
-        SurfaceControl.screenshot(token, outSurface);
+        final GraphicBuffer gb = SurfaceControl.screenshotToBufferWithSecureLayersUnsafe(
+                token, new Rect(), 0 /* width */, 0 /* height */, false /* useIdentityTransform */,
+                0 /* rotation */);
+        try {
+            outSurface.attachAndQueueBuffer(gb);
+        } catch (RuntimeException e) {
+            Slog.w(TAG, "Failed to take screenshot - " + e.getMessage());
+        }
         return true;
     }
 
@@ -1526,13 +1533,6 @@
 
             pw.println();
             mPersistentDataStore.dump(pw);
-
-            final ColorDisplayServiceInternal cds = LocalServices.getService(
-                    ColorDisplayServiceInternal.class);
-            if (cds != null) {
-                pw.println();
-                cds.dump(pw);
-            }
         }
     }
 
diff --git a/services/core/java/com/android/server/display/DisplayPowerController.java b/services/core/java/com/android/server/display/DisplayPowerController.java
index 15c7ef7..74cda9d 100644
--- a/services/core/java/com/android/server/display/DisplayPowerController.java
+++ b/services/core/java/com/android/server/display/DisplayPowerController.java
@@ -874,7 +874,7 @@
 
         // If the brightness is already set then it's been overridden by something other than the
         // user, or is a temporary adjustment.
-        final boolean userInitiatedChange = brightness < 0
+        boolean userInitiatedChange = brightness < 0
                 && (autoBrightnessAdjustmentChanged || userSetBrightnessChanged);
 
         boolean hadUserBrightnessPoint = false;
@@ -1010,6 +1010,12 @@
             }
 
             if (!brightnessIsTemporary) {
+                if (userInitiatedChange && (mAutomaticBrightnessController == null
+                        || !mAutomaticBrightnessController.hasValidAmbientLux())) {
+                    // If we don't have a valid lux reading we can't report a valid
+                    // slider event so notify as if the system changed the brightness.
+                    userInitiatedChange = false;
+                }
                 notifyBrightnessChanged(brightness, userInitiatedChange, hadUserBrightnessPoint);
             }
 
diff --git a/services/core/java/com/android/server/display/LocalDisplayAdapter.java b/services/core/java/com/android/server/display/LocalDisplayAdapter.java
index 4891947..77df10b 100644
--- a/services/core/java/com/android/server/display/LocalDisplayAdapter.java
+++ b/services/core/java/com/android/server/display/LocalDisplayAdapter.java
@@ -65,7 +65,8 @@
             new LongSparseArray<LocalDisplayDevice>();
 
     @SuppressWarnings("unused")  // Becomes active at instantiation time.
-    private HotplugDisplayEventReceiver mHotplugReceiver;
+    private PhysicalDisplayEventReceiver mPhysicalDisplayEventReceiver;
+
 
     // Called with SyncRoot lock held.
     public LocalDisplayAdapter(DisplayManagerService.SyncRoot syncRoot,
@@ -77,7 +78,7 @@
     public void registerLocked() {
         super.registerLocked();
 
-        mHotplugReceiver = new HotplugDisplayEventReceiver(getHandler().getLooper());
+        mPhysicalDisplayEventReceiver = new PhysicalDisplayEventReceiver(getHandler().getLooper());
 
         for (long physicalDisplayId : SurfaceControl.getPhysicalDisplayIds()) {
             tryConnectDisplayLocked(physicalDisplayId);
@@ -727,8 +728,8 @@
         }
     }
 
-    private final class HotplugDisplayEventReceiver extends DisplayEventReceiver {
-        public HotplugDisplayEventReceiver(Looper looper) {
+    private final class PhysicalDisplayEventReceiver extends DisplayEventReceiver {
+        PhysicalDisplayEventReceiver(Looper looper) {
             super(looper, VSYNC_SOURCE_APP);
         }
 
@@ -742,5 +743,15 @@
                 }
             }
         }
+
+        @Override
+        public void onConfigChanged(long timestampNanos, long physicalDisplayId, int configId) {
+            if (DEBUG) {
+                Slog.d(TAG, "onConfigChanged("
+                        + "timestampNanos=" + timestampNanos
+                        + ", builtInDisplayId=" + physicalDisplayId
+                        + ", configId=" + configId + ")");
+            }
+        }
     }
 }
diff --git a/services/core/java/com/android/server/display/OWNERS b/services/core/java/com/android/server/display/OWNERS
index 0d64dbd..25cb5ae 100644
--- a/services/core/java/com/android/server/display/OWNERS
+++ b/services/core/java/com/android/server/display/OWNERS
@@ -2,5 +2,3 @@
 dangittik@google.com
 hackbod@google.com
 ogunwale@google.com
-
-per-file ColorDisplayService.java=christyfranks@google.com
diff --git a/services/core/java/com/android/server/display/AppSaturationController.java b/services/core/java/com/android/server/display/color/AppSaturationController.java
similarity index 98%
rename from services/core/java/com/android/server/display/AppSaturationController.java
rename to services/core/java/com/android/server/display/color/AppSaturationController.java
index 5d5e4f7..e42be02 100644
--- a/services/core/java/com/android/server/display/AppSaturationController.java
+++ b/services/core/java/com/android/server/display/color/AppSaturationController.java
@@ -14,14 +14,14 @@
  * limitations under the License.
  */
 
-package com.android.server.display;
+package com.android.server.display.color;
 
 import android.annotation.UserIdInt;
 import android.util.SparseArray;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.server.display.ColorDisplayService.ColorTransformController;
+import com.android.server.display.color.ColorDisplayService.ColorTransformController;
 
 import java.io.PrintWriter;
 import java.lang.ref.WeakReference;
diff --git a/services/core/java/com/android/server/display/ColorDisplayService.java b/services/core/java/com/android/server/display/color/ColorDisplayService.java
similarity index 96%
rename from services/core/java/com/android/server/display/ColorDisplayService.java
rename to services/core/java/com/android/server/display/color/ColorDisplayService.java
index 7dd3b36..b1e5510 100644
--- a/services/core/java/com/android/server/display/ColorDisplayService.java
+++ b/services/core/java/com/android/server/display/color/ColorDisplayService.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.display;
+package com.android.server.display.color;
 
 import static android.hardware.display.ColorDisplayManager.AUTO_MODE_CUSTOM_TIME;
 import static android.hardware.display.ColorDisplayManager.AUTO_MODE_DISABLED;
@@ -24,9 +24,9 @@
 import static android.hardware.display.ColorDisplayManager.COLOR_MODE_NATURAL;
 import static android.hardware.display.ColorDisplayManager.COLOR_MODE_SATURATED;
 
-import static com.android.server.display.DisplayTransformManager.LEVEL_COLOR_MATRIX_DISPLAY_WHITE_BALANCE;
-import static com.android.server.display.DisplayTransformManager.LEVEL_COLOR_MATRIX_NIGHT_DISPLAY;
-import static com.android.server.display.DisplayTransformManager.LEVEL_COLOR_MATRIX_SATURATION;
+import static com.android.server.display.color.DisplayTransformManager.LEVEL_COLOR_MATRIX_DISPLAY_WHITE_BALANCE;
+import static com.android.server.display.color.DisplayTransformManager.LEVEL_COLOR_MATRIX_NIGHT_DISPLAY;
+import static com.android.server.display.color.DisplayTransformManager.LEVEL_COLOR_MATRIX_SATURATION;
 
 import android.Manifest;
 import android.animation.Animator;
@@ -233,6 +233,7 @@
     public void onStart() {
         publishBinderService(Context.COLOR_DISPLAY_SERVICE, new BinderService());
         publishLocalService(ColorDisplayServiceInternal.class, new ColorDisplayServiceInternal());
+        publishLocalService(DisplayTransformManager.class, new DisplayTransformManager());
     }
 
     @Override
@@ -632,9 +633,9 @@
     @VisibleForTesting
     void updateDisplayWhiteBalanceStatus() {
         boolean oldActivated = mDisplayWhiteBalanceTintController.isActivated();
-        mDisplayWhiteBalanceTintController.setActivated(isDisplayWhiteBalanceSettingEnabled() &&
-                !mNightDisplayTintController.isActivated() &&
-                DisplayTransformManager.needsLinearColorMatrix());
+        mDisplayWhiteBalanceTintController.setActivated(isDisplayWhiteBalanceSettingEnabled()
+                && !mNightDisplayTintController.isActivated()
+                && DisplayTransformManager.needsLinearColorMatrix());
         boolean activated = mDisplayWhiteBalanceTintController.isActivated();
 
         if (mDisplayWhiteBalanceListener != null && oldActivated != activated) {
@@ -819,7 +820,7 @@
     /**
      * Get the current color mode from system properties, or return -1 if invalid.
      *
-     * See {@link com.android.server.display.DisplayTransformManager}
+     * See {@link DisplayTransformManager}
      */
     private @ColorMode int getCurrentColorModeFromSystemProperties() {
         final int displayColorSetting = SystemProperties.getInt("persist.sys.sf.native_mode", 0);
@@ -851,7 +852,7 @@
     private void dumpInternal(PrintWriter pw) {
         pw.println("COLOR DISPLAY MANAGER dumpsys (color_display)");
 
-        pw.println("Night Display:");
+        pw.println("Night display:");
         if (mNightDisplayTintController.isAvailable(getContext())) {
             pw.println("    Activated: " + mNightDisplayTintController.isActivated());
             pw.println("    Color temp: " + mNightDisplayTintController.getColorTemperature());
@@ -923,14 +924,15 @@
 
             if (mLastActivatedTime != null) {
                 // Maintain the existing activated state if within the current period.
-                if (mLastActivatedTime.isBefore(now) && mLastActivatedTime.isAfter(start)
+                if (mLastActivatedTime.isBefore(now)
+                        && mLastActivatedTime.isAfter(start)
                         && (mLastActivatedTime.isAfter(end) || now.isBefore(end))) {
                     activate = mNightDisplayTintController.isActivatedSetting();
                 }
             }
 
-            if (mNightDisplayTintController.isActivatedStateNotSet() || (
-                    mNightDisplayTintController.isActivated() != activate)) {
+            if (mNightDisplayTintController.isActivatedStateNotSet()
+                    || (mNightDisplayTintController.isActivated() != activate)) {
                 mNightDisplayTintController.setActivated(activate);
             }
 
@@ -1305,10 +1307,11 @@
     }
 
     final class DisplayWhiteBalanceTintController extends TintController {
+
         // Three chromaticity coordinates per color: X, Y, and Z
-        private final int NUM_VALUES_PER_PRIMARY = 3;
+        private static final int NUM_VALUES_PER_PRIMARY = 3;
         // Four colors: red, green, blue, and white
-        private final int NUM_DISPLAY_PRIMARIES_VALS = 4 * NUM_VALUES_PER_PRIMARY;
+        private static final int NUM_DISPLAY_PRIMARIES_VALS = 4 * NUM_VALUES_PER_PRIMARY;
 
         private final Object mLock = new Object();
         @VisibleForTesting
@@ -1478,25 +1481,25 @@
                 pw.println("    mTemperatureMax = " + mTemperatureMax);
                 pw.println("    mTemperatureDefault = " + mTemperatureDefault);
                 pw.println("    mCurrentColorTemperature = " + mCurrentColorTemperature);
-                pw.println("    mCurrentColorTemperatureXYZ = " +
-                        matrixToString(mCurrentColorTemperatureXYZ, 3));
-                pw.println("    mDisplayColorSpaceRGB RGB-to-XYZ = " +
-                        matrixToString(mDisplayColorSpaceRGB.getTransform(), 3));
-                pw.println("    mChromaticAdaptationMatrix = " +
-                        matrixToString(mChromaticAdaptationMatrix, 3));
-                pw.println("    mDisplayColorSpaceRGB XYZ-to-RGB = " +
-                        matrixToString(mDisplayColorSpaceRGB.getInverseTransform(), 3));
-                pw.println("    mMatrixDisplayWhiteBalance = " +
-                        matrixToString(mMatrixDisplayWhiteBalance, 4));
+                pw.println("    mCurrentColorTemperatureXYZ = "
+                        + matrixToString(mCurrentColorTemperatureXYZ, 3));
+                pw.println("    mDisplayColorSpaceRGB RGB-to-XYZ = "
+                        + matrixToString(mDisplayColorSpaceRGB.getTransform(), 3));
+                pw.println("    mChromaticAdaptationMatrix = "
+                        + matrixToString(mChromaticAdaptationMatrix, 3));
+                pw.println("    mDisplayColorSpaceRGB XYZ-to-RGB = "
+                        + matrixToString(mDisplayColorSpaceRGB.getInverseTransform(), 3));
+                pw.println("    mMatrixDisplayWhiteBalance = "
+                        + matrixToString(mMatrixDisplayWhiteBalance, 4));
             }
         }
 
         private ColorSpace.Rgb makeRgbColorSpaceFromXYZ(float[] redGreenBlueXYZ, float[] whiteXYZ) {
             return new ColorSpace.Rgb(
-                "Display Color Space",
-                redGreenBlueXYZ,
-                whiteXYZ,
-                2.2f // gamma, unused for display white balance
+                    "Display Color Space",
+                    redGreenBlueXYZ,
+                    whiteXYZ,
+                    2.2f // gamma, unused for display white balance
             );
         }
 
@@ -1507,19 +1510,19 @@
             }
 
             DisplayPrimaries primaries = SurfaceControl.getDisplayNativePrimaries(displayToken);
-            if (primaries == null || primaries.red == null || primaries.green == null ||
-                primaries.blue == null || primaries.white == null) {
+            if (primaries == null || primaries.red == null || primaries.green == null
+                    || primaries.blue == null || primaries.white == null) {
                 return null;
             }
 
             return makeRgbColorSpaceFromXYZ(
-                    new float[] {
-                        primaries.red.X, primaries.red.Y, primaries.red.Z,
-                        primaries.green.X, primaries.green.Y, primaries.green.Z,
-                        primaries.blue.X, primaries.blue.Y, primaries.blue.Z,
+                    new float[]{
+                            primaries.red.X, primaries.red.Y, primaries.red.Z,
+                            primaries.green.X, primaries.green.Y, primaries.green.Z,
+                            primaries.blue.X, primaries.blue.Y, primaries.blue.Z,
                     },
-                    new float[] { primaries.white.X, primaries.white.Y, primaries.white.Z }
-                    );
+                    new float[]{primaries.white.X, primaries.white.Y, primaries.white.Z}
+            );
         }
 
         private ColorSpace.Rgb getDisplayColorSpaceFromResources(Resources res) {
@@ -1540,7 +1543,7 @@
 
             return makeRgbColorSpaceFromXYZ(displayRedGreenBlueXYZ, displayWhiteXYZ);
         }
-    };
+    }
 
     /**
      * Local service that allows color transforms to be enabled from other system services.
@@ -1572,10 +1575,6 @@
             return mDisplayWhiteBalanceTintController.isActivated();
         }
 
-        public void dump(PrintWriter pw) {
-            mDisplayWhiteBalanceTintController.dump(pw);
-        }
-
         /**
          * Adds a {@link WeakReference<ColorTransformController>} for a newly started activity, and
          * invokes {@link ColorTransformController#applyAppSaturation(float[], float[])} if needed.
diff --git a/services/core/java/com/android/server/display/DisplayTransformManager.java b/services/core/java/com/android/server/display/color/DisplayTransformManager.java
similarity index 96%
rename from services/core/java/com/android/server/display/DisplayTransformManager.java
rename to services/core/java/com/android/server/display/color/DisplayTransformManager.java
index ef92401..026837f 100644
--- a/services/core/java/com/android/server/display/DisplayTransformManager.java
+++ b/services/core/java/com/android/server/display/color/DisplayTransformManager.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.display;
+package com.android.server.display.color;
 
 import android.app.ActivityTaskManager;
 import android.hardware.display.ColorDisplayManager;
@@ -117,12 +117,12 @@
     /**
      * Sets and applies a current color transform matrix for a given level.
      * <p>
-     * Note: all color transforms are first composed to a single matrix in ascending order based
-     * on level before being applied to the display.
+     * Note: all color transforms are first composed to a single matrix in ascending order based on
+     * level before being applied to the display.
      *
      * @param level the level used to identify and compose the color transform (low -> high)
      * @param value the 4x4 color transform matrix (in column-major order), or {@code null} to
-     *              remove the color transform matrix associated with the provided level
+     * remove the color transform matrix associated with the provided level
      */
     public void setColorMatrix(int level, float[] value) {
         if (value != null && value.length != 16) {
@@ -235,13 +235,15 @@
     }
 
     /**
-     * Return true when the specified colorMode requires the color matrix to
-     * work in linear space.
+     * Return true when the specified colorMode requires the color matrix to work in linear space.
      */
     public static boolean needsLinearColorMatrix(int colorMode) {
         return colorMode != ColorDisplayManager.COLOR_MODE_SATURATED;
     }
 
+    /**
+     * Sets color mode and updates night display transform values.
+     */
     public boolean setColorMode(int colorMode, float[] nightDisplayMatrix) {
         if (colorMode == ColorDisplayManager.COLOR_MODE_NATURAL) {
             applySaturation(COLOR_SATURATION_NATURAL);
@@ -264,8 +266,8 @@
     }
 
     /**
-     * Returns whether the screen is color managed via SurfaceFlinger's
-     * {@link #SURFACE_FLINGER_TRANSACTION_QUERY_COLOR_MANAGED}.
+     * Returns whether the screen is color managed via SurfaceFlinger's {@link
+     * #SURFACE_FLINGER_TRANSACTION_QUERY_COLOR_MANAGED}.
      */
     public boolean isDeviceColorManaged() {
         final IBinder flinger = ServiceManager.getService(SURFACE_FLINGER);
diff --git a/services/core/java/com/android/server/display/color/OWNERS b/services/core/java/com/android/server/display/color/OWNERS
new file mode 100644
index 0000000..27adf12
--- /dev/null
+++ b/services/core/java/com/android/server/display/color/OWNERS
@@ -0,0 +1,4 @@
+christyfranks@google.com
+justinklaassen@google.com
+
+per-file DisplayTransformManager.java=michaelwr@google.com
\ No newline at end of file
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
index d95e92b..e7181e2 100644
--- a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
@@ -22,7 +22,7 @@
 
 import com.android.internal.util.Preconditions;
 import com.android.server.LocalServices;
-import com.android.server.display.ColorDisplayService.ColorDisplayServiceInternal;
+import com.android.server.display.color.ColorDisplayService.ColorDisplayServiceInternal;
 import com.android.server.display.utils.History;
 
 import java.io.PrintWriter;
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceSettings.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceSettings.java
index a53e91c..1b7251c 100644
--- a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceSettings.java
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceSettings.java
@@ -29,8 +29,8 @@
 
 import com.android.internal.util.Preconditions;
 import com.android.server.LocalServices;
-import com.android.server.display.ColorDisplayService;
-import com.android.server.display.ColorDisplayService.ColorDisplayServiceInternal;
+import com.android.server.display.color.ColorDisplayService;
+import com.android.server.display.color.ColorDisplayService.ColorDisplayServiceInternal;
 import com.android.server.display.whitebalance.DisplayWhiteBalanceController.Callbacks;
 
 import java.io.PrintWriter;
diff --git a/services/core/java/com/android/server/dreams/DreamManagerService.java b/services/core/java/com/android/server/dreams/DreamManagerService.java
index bffa8f4..3052e3c 100644
--- a/services/core/java/com/android/server/dreams/DreamManagerService.java
+++ b/services/core/java/com/android/server/dreams/DreamManagerService.java
@@ -28,6 +28,7 @@
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.pm.ServiceInfo;
 import android.database.ContentObserver;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.hardware.input.InputManagerInternal;
 import android.os.Binder;
 import android.os.Build;
@@ -46,7 +47,6 @@
 import android.util.Slog;
 import android.view.Display;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.internal.util.DumpUtils;
 import com.android.server.FgThread;
 import com.android.server.LocalServices;
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystem.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystem.java
index 6710986..2026957 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystem.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystem.java
@@ -31,6 +31,8 @@
 import android.media.AudioManager;
 import android.media.AudioSystem;
 import android.media.tv.TvContract;
+import android.media.tv.TvInputInfo;
+import android.media.tv.TvInputManager.TvInputCallback;
 import android.os.SystemProperties;
 import android.provider.Settings.Global;
 import android.util.Slog;
@@ -84,10 +86,13 @@
             .get(Constants.PROPERTY_SYSTEM_AUDIO_DEVICE_ARC_PORT, "0").contains("tvinput");
 
     // Keeps the mapping (HDMI port ID to TV input URI) to keep track of the TV inputs ready to
-    // accept input switching request from HDMI devices. Requests for which the corresponding
-    // input ID is not yet registered by TV input framework need to be buffered for delayed
-    // processing.
-    private final HashMap<Integer, String> mTvInputs = new HashMap<>();
+    // accept input switching request from HDMI devices.
+    @GuardedBy("mLock")
+    private final HashMap<Integer, String> mPortIdToTvInputs = new HashMap<>();
+
+    // A map from TV input id to HDMI device info.
+    @GuardedBy("mLock")
+    private final HashMap<String, HdmiDeviceInfo> mTvInputsToDeviceInfo = new HashMap<>();
 
     // Copy of mDeviceInfos to guarantee thread-safety.
     @GuardedBy("mLock")
@@ -103,14 +108,57 @@
             mService.readBooleanSetting(Global.HDMI_CEC_SWITCH_ENABLED, false);
         mSystemAudioControlFeatureEnabled =
             mService.readBooleanSetting(Global.HDMI_SYSTEM_AUDIO_CONTROL_ENABLED, true);
-        // TODO(amyjojo): Maintain a portId to TvinputId map.
-        mTvInputs.put(2, "com.droidlogic.tvinput/.services.Hdmi1InputService/HW5");
-        mTvInputs.put(4, "com.droidlogic.tvinput/.services.Hdmi2InputService/HW6");
-        mTvInputs.put(1, "com.droidlogic.tvinput/.services.Hdmi3InputService/HW7");
     }
 
     private static final String SHORT_AUDIO_DESCRIPTOR_CONFIG_PATH = "/vendor/etc/sadConfig.xml";
 
+    private final TvInputCallback mTvInputCallback = new TvInputCallback() {
+        @Override
+        public void onInputAdded(String inputId) {
+            addOrUpdateTvInput(inputId);
+        }
+
+        @Override
+        public void onInputRemoved(String inputId) {
+            removeTvInput(inputId);
+        }
+
+        @Override
+        public void onInputUpdated(String inputId) {
+            addOrUpdateTvInput(inputId);
+        }
+    };
+
+    @ServiceThreadOnly
+    private void addOrUpdateTvInput(String inputId) {
+        assertRunOnServiceThread();
+        synchronized (mLock) {
+            TvInputInfo tvInfo = mService.getTvInputManager().getTvInputInfo(inputId);
+            if (tvInfo == null) {
+                return;
+            }
+            HdmiDeviceInfo info = tvInfo.getHdmiDeviceInfo();
+            if (info == null) {
+                return;
+            }
+            mPortIdToTvInputs.put(info.getPortId(), inputId);
+            mTvInputsToDeviceInfo.put(inputId, info);
+        }
+    }
+
+    @ServiceThreadOnly
+    private void removeTvInput(String inputId) {
+        assertRunOnServiceThread();
+        synchronized (mLock) {
+            if (mTvInputsToDeviceInfo.get(inputId) == null) {
+                return;
+            }
+            int portId = mTvInputsToDeviceInfo.get(inputId).getPortId();
+            mPortIdToTvInputs.remove(portId);
+            mTvInputsToDeviceInfo.remove(inputId);
+        }
+    }
+
     /**
      * Called when a device is newly added or a new device is detected or
      * an existing device is updated.
@@ -248,17 +296,29 @@
         }
         if (mService.getPortInfo(portId).getType() == HdmiPortInfo.PORT_OUTPUT) {
             mCecMessageCache.flushAll();
-        } else {
-            if (connected) {
-                launchDeviceDiscovery();
-            } else {
-                // TODO(amyjojo): remove device from mDeviceInfo
+        } else if (!connected && mPortIdToTvInputs.get(portId) != null) {
+            String tvInputId = mPortIdToTvInputs.get(portId);
+            HdmiDeviceInfo info = mTvInputsToDeviceInfo.get(tvInputId);
+            if (info == null) {
+                return;
             }
+            // Update with TIF on the device removal. TIF callback will update
+            // mPortIdToTvInputs and mPortIdToTvInputs.
+            removeCecDevice(info.getLogicalAddress());
         }
     }
 
     @Override
     @ServiceThreadOnly
+    protected void disableDevice(boolean initiatedByCec, PendingActionClearedCallback callback) {
+        super.disableDevice(initiatedByCec, callback);
+        assertRunOnServiceThread();
+        mService.unregisterTvInputCallback(mTvInputCallback);
+        // TODO(amyjojo): check disableDevice and onStandby behaviors per spec
+    }
+
+    @Override
+    @ServiceThreadOnly
     protected void onStandby(boolean initiatedByCec, int standbyAction) {
         assertRunOnServiceThread();
         mTvSystemAudioModeSupport = false;
@@ -284,6 +344,7 @@
                         mAddress, mService.getPhysicalAddress(), mDeviceType));
         mService.sendCecCommand(
                 HdmiCecMessageBuilder.buildDeviceVendorIdCommand(mAddress, mService.getVendorId()));
+        mService.registerTvInputCallback(mTvInputCallback);
         int systemAudioControlOnPowerOnProp =
                 SystemProperties.getInt(
                         PROPERTY_SYSTEM_AUDIO_CONTROL_ON_POWER_ON,
@@ -996,6 +1057,17 @@
         }
         // Wake up device
         mService.wakeUp();
+        // If Audio device is the active source or is on the active path,
+        // enable system audio mode without querying TV's support on sam.
+        // This is per HDMI spec 1.4b CEC 13.15.4.2.
+        if (mService.pathToPortId(getActiveSource().physicalAddress)
+                != Constants.INVALID_PORT_ID) {
+            setSystemAudioMode(true);
+            mService.sendCecCommand(
+                HdmiCecMessageBuilder.buildSetSystemAudioMode(
+                    mAddress, Constants.ADDR_BROADCAST, true));
+            return;
+        }
         // Check if TV supports System Audio Control.
         // Handle broadcasting setSystemAudioMode on or aborting message on callback.
         queryTvSystemAudioModeSupport(new TvSystemAudioModeSupportedCallback() {
@@ -1064,9 +1136,9 @@
             setLocalActivePort(portId);
             return;
         } else {
-            String uri = mTvInputs.get(portId);
+            String uri = mPortIdToTvInputs.get(portId);
             if (uri != null) {
-                switchToTvInput(mTvInputs.get(portId));
+                switchToTvInput(uri);
             } else {
                 HdmiLogger.debug("Port number does not match any Tv Input.");
                 return;
@@ -1215,7 +1287,8 @@
         pw.println("mArcIntentUsed: " + mArcIntentUsed);
         pw.println("mRoutingPort: " + getRoutingPort());
         pw.println("mLocalActivePort: " + getLocalActivePort());
-        HdmiUtils.dumpMap(pw, "mTvInputs:", mTvInputs);
+        HdmiUtils.dumpMap(pw, "mPortIdToTvInputs:", mPortIdToTvInputs);
+        HdmiUtils.dumpMap(pw, "mTvInputsToDeviceInfo:", mTvInputsToDeviceInfo);
         HdmiUtils.dumpSparseArray(pw, "mDeviceInfos:", mDeviceInfos);
         pw.decreaseIndent();
         super.dump(pw);
diff --git a/services/core/java/com/android/server/hdmi/HdmiControlService.java b/services/core/java/com/android/server/hdmi/HdmiControlService.java
index 072238e..f5adb01 100644
--- a/services/core/java/com/android/server/hdmi/HdmiControlService.java
+++ b/services/core/java/com/android/server/hdmi/HdmiControlService.java
@@ -576,7 +576,8 @@
                 Global.HDMI_SYSTEM_AUDIO_CONTROL_ENABLED,
                 Global.MHL_INPUT_SWITCHING_ENABLED,
                 Global.MHL_POWER_CHARGE_ENABLED,
-                Global.HDMI_CEC_SWITCH_ENABLED
+                Global.HDMI_CEC_SWITCH_ENABLED,
+                Global.DEVICE_NAME
         };
         for (String s : settings) {
             resolver.registerContentObserver(Global.getUriFor(s), false, mSettingsObserver,
@@ -642,6 +643,10 @@
                 case Global.MHL_POWER_CHARGE_ENABLED:
                     mMhlController.setOption(OPTION_MHL_POWER_CHARGE, toInt(enabled));
                     break;
+                case Global.DEVICE_NAME:
+                    String deviceName = readStringSetting(option, Build.MODEL);
+                    setDisplayName(deviceName);
+                    break;
             }
         }
     }
@@ -670,6 +675,15 @@
         return SystemProperties.getBoolean(key, defVal);
     }
 
+    String readStringSetting(String key, String defVal) {
+        ContentResolver cr = getContext().getContentResolver();
+        String content = Global.getString(cr, key);
+        if (TextUtils.isEmpty(content)) {
+            return defVal;
+        }
+        return content;
+    }
+
     private void initializeCec(int initiatedBy) {
         mAddressAllocated = false;
         mCecController.setOption(OptionKey.SYSTEM_CEC_CONTROL, true);
@@ -1178,13 +1192,29 @@
     }
 
     private HdmiDeviceInfo createDeviceInfo(int logicalAddress, int deviceType, int powerStatus) {
-        // TODO: find better name instead of model name.
-        String displayName = Build.MODEL;
+        String displayName = readStringSetting(Global.DEVICE_NAME, Build.MODEL);
         return new HdmiDeviceInfo(logicalAddress,
                 getPhysicalAddress(), pathToPortId(getPhysicalAddress()), deviceType,
                 getVendorId(), displayName, powerStatus);
     }
 
+    // Set the display name in HdmiDeviceInfo of the current devices to content provided by
+    // Global.DEVICE_NAME. Only set and broadcast if the new name is different.
+    private void setDisplayName(String newDisplayName) {
+        for (HdmiCecLocalDevice device : getAllLocalDevices()) {
+            HdmiDeviceInfo deviceInfo = device.getDeviceInfo();
+            if (deviceInfo.getDisplayName().equals(newDisplayName)) {
+                continue;
+            }
+            device.setDeviceInfo(new HdmiDeviceInfo(
+                    deviceInfo.getLogicalAddress(), deviceInfo.getPhysicalAddress(),
+                    deviceInfo.getPortId(), deviceInfo.getDeviceType(), deviceInfo.getVendorId(),
+                    newDisplayName, deviceInfo.getDevicePowerStatus()));
+            sendCecCommand(HdmiCecMessageBuilder.buildSetOsdNameCommand(
+                    device.mAddress, Constants.ADDR_TV, newDisplayName));
+        }
+    }
+
     @ServiceThreadOnly
     void handleMhlHotplugEvent(int portId, boolean connected) {
         assertRunOnServiceThread();
diff --git a/services/core/java/com/android/server/infra/AbstractMasterSystemService.java b/services/core/java/com/android/server/infra/AbstractMasterSystemService.java
index 2bfb31f..d2ccfcc 100644
--- a/services/core/java/com/android/server/infra/AbstractMasterSystemService.java
+++ b/services/core/java/com/android/server/infra/AbstractMasterSystemService.java
@@ -133,7 +133,8 @@
      * {@link com.android.internal.infra.AbstractRemoteService} instances, or
      * {@code null} when the service doesn't bind to remote services.
      * @param disallowProperty when not {@code null}, defines a {@link UserManager} restriction that
-     *        disables the service.
+     *        disables the service. <b>NOTE: </b> you'll also need to add it to
+     *        {@code UserRestrictionsUtils.USER_RESTRICTIONS}.
      */
     protected AbstractMasterSystemService(@NonNull Context context,
             @Nullable ServiceNameResolver serviceNameResolver,
diff --git a/services/core/java/com/android/server/job/controllers/StorageController.java b/services/core/java/com/android/server/job/controllers/StorageController.java
index c2ae53f..51187df 100644
--- a/services/core/java/com/android/server/job/controllers/StorageController.java
+++ b/services/core/java/com/android/server/job/controllers/StorageController.java
@@ -81,20 +81,16 @@
         synchronized (mLock) {
             for (int i = mTrackedTasks.size() - 1; i >= 0; i--) {
                 final JobStatus ts = mTrackedTasks.valueAt(i);
-                boolean previous = ts.setStorageNotLowConstraintSatisfied(storageNotLow);
-                if (previous != storageNotLow) {
-                    reportChange = true;
-                }
+                reportChange |= ts.setStorageNotLowConstraintSatisfied(storageNotLow);
             }
         }
-        // Let the scheduler know that state has changed. This may or may not result in an
-        // execution.
-        if (reportChange) {
-            mStateChangedListener.onControllerStateChanged();
-        }
-        // Also tell the scheduler that any ready jobs should be flushed.
         if (storageNotLow) {
+            // Tell the scheduler that any ready jobs should be flushed.
             mStateChangedListener.onRunJobNow(null);
+        } else if (reportChange) {
+            // Let the scheduler know that state has changed. This may or may not result in an
+            // execution.
+            mStateChangedListener.onControllerStateChanged();
         }
     }
 
@@ -143,9 +139,10 @@
                             + sElapsedRealtimeClock.millis());
                 }
                 mStorageLow = true;
+                maybeReportNewStorageState();
             } else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action)) {
                 if (DEBUG) {
-                    Slog.d(TAG, "Available stoage high enough to do work. @ "
+                    Slog.d(TAG, "Available storage high enough to do work. @ "
                             + sElapsedRealtimeClock.millis());
                 }
                 mStorageLow = false;
diff --git a/services/core/java/com/android/server/location/GnssLocationProvider.java b/services/core/java/com/android/server/location/GnssLocationProvider.java
index 243b6fe..ae91503 100644
--- a/services/core/java/com/android/server/location/GnssLocationProvider.java
+++ b/services/core/java/com/android/server/location/GnssLocationProvider.java
@@ -140,6 +140,9 @@
     private static final int LOCATION_HAS_SPEED_ACCURACY = 64;
     private static final int LOCATION_HAS_BEARING_ACCURACY = 128;
 
+    // these need to match ElapsedRealtimeFlags enum in types.hal
+    private static final int ELAPSED_REALTIME_HAS_TIMESTAMP_NS = 1;
+
     // IMPORTANT - the GPS_DELETE_* symbols here must match GnssAidingData enum in IGnss.hal
     private static final int GPS_DELETE_EPHEMERIS = 0x0001;
     private static final int GPS_DELETE_ALMANAC = 0x0002;
@@ -527,6 +530,7 @@
                 mPowerManager.getPowerSaveState(ServiceType.LOCATION);
         switch (result.locationMode) {
             case PowerManager.LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF:
+            case PowerManager.LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF:
                 // If we are in battery saver mode and the screen is off, disable GPS.
                 disableGps |= result.batterySaverEnabled && !mPowerManager.isInteractive();
                 break;
@@ -683,7 +687,7 @@
         }
     }
 
-    private void handleRequestLocation(boolean independentFromGnss) {
+    private void handleRequestLocation(boolean independentFromGnss, boolean isUserEmergency) {
         if (isRequestLocationRateLimited()) {
             if (DEBUG) {
                 Log.d(TAG, "RequestLocation is denied due to too frequent requests.");
@@ -719,9 +723,17 @@
                 String.format(
                         "GNSS HAL Requesting location updates from %s provider for %d millis.",
                         provider, durationMillis));
+
+        LocationRequest locationRequest = LocationRequest.createFromDeprecatedProvider(provider,
+                LOCATION_UPDATE_MIN_TIME_INTERVAL_MILLIS, /* minDistance= */ 0,
+                /* singleShot= */ false);
+
+        // Ignore location settings if in emergency mode.
+        if (isUserEmergency && mNIHandler.getInEmergency()) {
+            locationRequest.setLocationSettingsIgnored(true);
+        }
         try {
-            locationManager.requestLocationUpdates(provider,
-                    LOCATION_UPDATE_MIN_TIME_INTERVAL_MILLIS, /*minDistance=*/ 0,
+            locationManager.requestLocationUpdates(locationRequest,
                     locationListener, mHandler.getLooper());
             locationListener.mNumLocationUpdateRequest++;
             mHandler.postDelayed(() -> {
@@ -756,10 +768,16 @@
         float speedAccuracyMetersPerSecond = location.getSpeedAccuracyMetersPerSecond();
         float bearingAccuracyDegrees = location.getBearingAccuracyDegrees();
         long timestamp = location.getTime();
-        native_inject_best_location(gnssLocationFlags, latitudeDegrees, longitudeDegrees,
-                altitudeMeters, speedMetersPerSec, bearingDegrees, horizontalAccuracyMeters,
-                verticalAccuracyMeters, speedAccuracyMetersPerSecond, bearingAccuracyDegrees,
-                timestamp);
+
+        int elapsedRealtimeFlags = ELAPSED_REALTIME_HAS_TIMESTAMP_NS;
+        long elapsedRealtimeNanos = location.getElapsedRealtimeNanos();
+
+        native_inject_best_location(
+                gnssLocationFlags, latitudeDegrees, longitudeDegrees,
+                altitudeMeters, speedMetersPerSec, bearingDegrees,
+                horizontalAccuracyMeters, verticalAccuracyMeters,
+                speedAccuracyMetersPerSecond, bearingAccuracyDegrees, timestamp,
+                elapsedRealtimeFlags, elapsedRealtimeNanos);
     }
 
     /** Returns true if the location request is too frequent. */
@@ -1259,9 +1277,6 @@
 
         if (VERBOSE) Log.v(TAG, "reportLocation " + location.toString());
 
-        // It would be nice to push the elapsed real-time timestamp
-        // further down the stack, but this is still useful
-        location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
         location.setExtras(mLocationExtras.getBundle());
 
         reportLocation(location);
@@ -1821,11 +1836,13 @@
     }
 
     @NativeEntryPoint
-    private void requestLocation(boolean independentFromGnss) {
+    private void requestLocation(boolean independentFromGnss, boolean isUserEmergency) {
         if (DEBUG) {
-            Log.d(TAG, "requestLocation. independentFromGnss: " + independentFromGnss);
+            Log.d(TAG, "requestLocation. independentFromGnss: " + independentFromGnss
+                    + ", isUserEmergency: "
+                    + isUserEmergency);
         }
-        sendMessage(REQUEST_LOCATION, 0, independentFromGnss);
+        sendMessage(REQUEST_LOCATION, independentFromGnss ? 1 : 0, isUserEmergency);
     }
 
     @NativeEntryPoint
@@ -1916,7 +1933,7 @@
                     mNtpTimeHelper.retrieveAndInjectNtpTime();
                     break;
                 case REQUEST_LOCATION:
-                    handleRequestLocation((boolean) msg.obj);
+                    handleRequestLocation(msg.arg1 == 1, (boolean) msg.obj);
                     break;
                 case DOWNLOAD_XTRA_DATA:
                     handleDownloadXtraData();
@@ -2150,17 +2167,11 @@
     private native int native_read_nmea(byte[] buffer, int bufferSize);
 
     private native void native_inject_best_location(
-            int gnssLocationFlags,
-            double latitudeDegrees,
-            double longitudeDegrees,
-            double altitudeMeters,
-            float speedMetersPerSec,
-            float bearingDegrees,
-            float horizontalAccuracyMeters,
-            float verticalAccuracyMeters,
-            float speedAccuracyMetersPerSecond,
-            float bearingAccuracyDegrees,
-            long timestamp);
+            int gnssLocationFlags, double latitudeDegrees, double longitudeDegrees,
+            double altitudeMeters, float speedMetersPerSec, float bearingDegrees,
+            float horizontalAccuracyMeters, float verticalAccuracyMeters,
+            float speedAccuracyMetersPerSecond, float bearingAccuracyDegrees,
+            long timestamp, int elapsedRealtimeFlags, long elapsedRealtimeNanos);
 
     private native void native_inject_location(double latitude, double longitude, float accuracy);
 
@@ -2187,4 +2198,4 @@
             int lac, int cid);
 
     private native void native_agps_set_id(int type, String setid);
-}
\ No newline at end of file
+}
diff --git a/services/core/java/com/android/server/location/LocationProviderProxy.java b/services/core/java/com/android/server/location/LocationProviderProxy.java
index afe3473..00e1ffa 100644
--- a/services/core/java/com/android/server/location/LocationProviderProxy.java
+++ b/services/core/java/com/android/server/location/LocationProviderProxy.java
@@ -34,13 +34,11 @@
 import com.android.internal.location.ILocationProviderManager;
 import com.android.internal.location.ProviderProperties;
 import com.android.internal.location.ProviderRequest;
-import com.android.internal.os.TransferPipe;
 import com.android.server.FgThread;
 import com.android.server.LocationManagerService;
 import com.android.server.ServiceWatcher;
 
 import java.io.FileDescriptor;
-import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.Collections;
@@ -189,14 +187,6 @@
                 pw.println("  additional packages=" + mProviderPackages);
             }
         }
-        mServiceWatcher.runOnBinderBlocking(binder -> {
-            try {
-                TransferPipe.dumpAsync(binder, fd, args);
-            } catch (IOException | RemoteException e) {
-                pw.println("  <failed to dump location provider: " + e + ">");
-            }
-            return null;
-        }, null);
     }
 
     @Override
diff --git a/services/core/java/com/android/server/locksettings/LockSettingsService.java b/services/core/java/com/android/server/locksettings/LockSettingsService.java
index aa85c83..ee968c8 100644
--- a/services/core/java/com/android/server/locksettings/LockSettingsService.java
+++ b/services/core/java/com/android/server/locksettings/LockSettingsService.java
@@ -123,7 +123,6 @@
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.PrintWriter;
-import java.nio.charset.StandardCharsets;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
 import java.security.KeyStoreException;
@@ -277,7 +276,7 @@
      * @param managedUserPassword Managed profile original password (when it has separated lock).
      *            NULL when it does not have a separated lock before.
      */
-    public void tieManagedProfileLockIfNecessary(int managedUserId, String managedUserPassword) {
+    public void tieManagedProfileLockIfNecessary(int managedUserId, byte[] managedUserPassword) {
         if (DEBUG) Slog.v(TAG, "Check child profile lock for user: " + managedUserId);
         // Only for managed profile
         if (!mUserManager.getUserInfo(managedUserId).isManagedProfile()) {
@@ -312,7 +311,12 @@
         byte[] randomLockSeed = new byte[] {};
         try {
             randomLockSeed = SecureRandom.getInstance("SHA1PRNG").generateSeed(40);
-            String newPassword = String.valueOf(HexEncoding.encode(randomLockSeed));
+            char[] newPasswordChars = HexEncoding.encode(randomLockSeed);
+            byte[] newPassword = new byte[newPasswordChars.length];
+            for (int i = 0; i < newPasswordChars.length; i++) {
+                newPassword[i] = (byte) newPasswordChars[i];
+            }
+            Arrays.fill(newPasswordChars, '\u0000');
             final int quality = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
             setLockCredentialInternal(newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
                     managedUserPassword, quality, managedUserId);
@@ -321,6 +325,7 @@
             // password directly, so we always store a password.
             setLong(LockPatternUtils.PASSWORD_TYPE_KEY, quality, managedUserId);
             tieProfileLockToParent(managedUserId, newPassword);
+            Arrays.fill(newPassword, (byte) 0);
         } catch (NoSuchAlgorithmException | RemoteException e) {
             Slog.e(TAG, "Fail to tie managed profile", e);
             // Nothing client can do to fix this issue, so we do not throw exception out
@@ -618,7 +623,7 @@
 
             try {
                 final long handle = getSyntheticPasswordHandleLocked(userId);
-                final String noCredential = null;
+                final byte[] noCredential = null;
                 AuthenticationResult result =
                         mSpManager.unwrapPasswordBasedSyntheticPassword(
                                 getGateKeeperService(), handle, noCredential, userId, null);
@@ -956,7 +961,7 @@
 
     @Override
     public void setSeparateProfileChallengeEnabled(int userId, boolean enabled,
-            String managedUserPassword) {
+            byte[] managedUserPassword) {
         checkWritePermission(userId);
         if (!mLockPatternUtils.hasSecureLockScreen()) {
             throw new UnsupportedOperationException(
@@ -969,8 +974,8 @@
     }
 
     @GuardedBy("mSeparateChallengeLock")
-    private void setSeparateProfileChallengeEnabledLocked(@UserIdInt int userId, boolean enabled,
-            String managedUserPassword) {
+    private void setSeparateProfileChallengeEnabledLocked(@UserIdInt int userId,
+            boolean enabled, byte[] managedUserPassword) {
         final boolean old = getBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, false, userId);
         setBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, enabled, userId);
         try {
@@ -1113,24 +1118,28 @@
         return mStorage.hasCredential(userId);
     }
 
-    private void setKeystorePassword(String password, int userHandle) {
+    private void setKeystorePassword(byte[] password, int userHandle) {
         final KeyStore ks = KeyStore.getInstance();
-        ks.onUserPasswordChanged(userHandle, password);
+        // TODO(b/120484642): Update keystore to accept byte[] passwords
+        String passwordString = password == null ? null : new String(password);
+        ks.onUserPasswordChanged(userHandle, passwordString);
     }
 
-    private void unlockKeystore(String password, int userHandle) {
+    private void unlockKeystore(byte[] password, int userHandle) {
         if (DEBUG) Slog.v(TAG, "Unlock keystore for user: " + userHandle);
+        // TODO(b/120484642): Update keystore to accept byte[] passwords
+        String passwordString = password == null ? null : new String(password);
         final KeyStore ks = KeyStore.getInstance();
-        ks.unlock(userHandle, password);
+        ks.unlock(userHandle, passwordString);
     }
 
     @VisibleForTesting
-    protected String getDecryptedPasswordForTiedProfile(int userId)
+    protected byte[] getDecryptedPasswordForTiedProfile(int userId)
             throws KeyStoreException, UnrecoverableKeyException,
             NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
             InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
             CertificateException, IOException {
-        if (DEBUG) Slog.v(TAG, "Get child profile decrytped key");
+        if (DEBUG) Slog.v(TAG, "Get child profile decrypted key");
         byte[] storedData = mStorage.readChildProfileLock(userId);
         if (storedData == null) {
             throw new FileNotFoundException("Child profile lock file not found");
@@ -1149,7 +1158,7 @@
 
         cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new GCMParameterSpec(128, iv));
         decryptionResult = cipher.doFinal(encryptedPassword);
-        return new String(decryptionResult, StandardCharsets.UTF_8);
+        return decryptionResult;
     }
 
     private void unlockChildProfile(int profileHandle, boolean ignoreUserNotAuthenticated)
@@ -1226,11 +1235,11 @@
                 && mUserManager.isUserRunning(userInfo.id);
     }
 
-    private Map<Integer, String> getDecryptedPasswordsForAllTiedProfiles(int userId) {
+    private Map<Integer, byte[]> getDecryptedPasswordsForAllTiedProfiles(int userId) {
         if (mUserManager.getUserInfo(userId).isManagedProfile()) {
             return null;
         }
-        Map<Integer, String> result = new ArrayMap<Integer, String>();
+        Map<Integer, byte[]> result = new ArrayMap<Integer, byte[]>();
         final List<UserInfo> profiles = mUserManager.getProfiles(userId);
         final int size = profiles.size();
         for (int i = 0; i < size; i++) {
@@ -1268,7 +1277,7 @@
      * terminates when the user is a managed profile.
      */
     private void synchronizeUnifiedWorkChallengeForProfiles(int userId,
-            Map<Integer, String> profilePasswordMap) throws RemoteException {
+            Map<Integer, byte[]> profilePasswordMap) throws RemoteException {
         if (mUserManager.getUserInfo(userId).isManagedProfile()) {
             return;
         }
@@ -1317,9 +1326,10 @@
     // This method should be called by LockPatternUtil only, all internal methods in this class
     // should call setLockCredentialInternal.
     @Override
-    public void setLockCredential(String credential, int type, String savedCredential,
-            int requestedQuality, int userId)
+    public void setLockCredential(byte[] credential, int type,
+            byte[] savedCredential, int requestedQuality, int userId)
             throws RemoteException {
+
         if (!mLockPatternUtils.hasSecureLockScreen()) {
             throw new UnsupportedOperationException(
                     "This operation requires secure lock screen feature");
@@ -1333,14 +1343,14 @@
         notifySeparateProfileChallengeChanged(userId);
     }
 
-    private void setLockCredentialInternal(String credential, int credentialType,
-            String savedCredential, int requestedQuality, int userId) throws RemoteException {
+    private void setLockCredentialInternal(byte[] credential, int credentialType,
+            byte[] savedCredential, int requestedQuality, int userId) throws RemoteException {
         // Normalize savedCredential and credential such that empty string is always represented
         // as null.
-        if (TextUtils.isEmpty(savedCredential)) {
+        if (savedCredential == null || savedCredential.length == 0) {
             savedCredential = null;
         }
-        if (TextUtils.isEmpty(credential)) {
+        if (credential == null || credential.length == 0) {
             credential = null;
         }
         synchronized (mSpManager) {
@@ -1409,7 +1419,7 @@
             mStorage.writeCredentialHash(willStore, userId);
             // push new secret and auth token to vold
             GateKeeperResponse gkResponse = getGateKeeperService()
-                    .verifyChallenge(userId, 0, willStore.hash, credential.getBytes());
+                    .verifyChallenge(userId, 0, willStore.hash, credential);
             setUserKeyProtection(userId, credential, convertResponse(gkResponse));
             fixateNewestUserKeyAuth(userId);
             // Refresh the auth token
@@ -1429,9 +1439,8 @@
     }
 
     @VisibleForTesting
-    protected void tieProfileLockToParent(int userId, String password) {
+    protected void tieProfileLockToParent(int userId, byte[] password) {
         if (DEBUG) Slog.v(TAG, "tieProfileLockToParent for user: " + userId);
-        byte[] randomLockSeed = password.getBytes(StandardCharsets.UTF_8);
         byte[] encryptionResult;
         byte[] iv;
         try {
@@ -1465,7 +1474,7 @@
                         KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_GCM + "/"
                                 + KeyProperties.ENCRYPTION_PADDING_NONE);
                 cipher.init(Cipher.ENCRYPT_MODE, keyStoreEncryptionKey);
-                encryptionResult = cipher.doFinal(randomLockSeed);
+                encryptionResult = cipher.doFinal(password);
                 iv = cipher.getIV();
             } finally {
                 // The original key can now be discarded.
@@ -1490,17 +1499,11 @@
     }
 
     private byte[] enrollCredential(byte[] enrolledHandle,
-            String enrolledCredential, String toEnroll, int userId)
+            byte[] enrolledCredential, byte[] toEnroll, int userId)
             throws RemoteException {
         checkWritePermission(userId);
-        byte[] enrolledCredentialBytes = enrolledCredential == null
-                ? null
-                : enrolledCredential.getBytes();
-        byte[] toEnrollBytes = toEnroll == null
-                ? null
-                : toEnroll.getBytes();
         GateKeeperResponse response = getGateKeeperService().enroll(userId, enrolledHandle,
-                enrolledCredentialBytes, toEnrollBytes);
+                enrolledCredential, toEnroll);
 
         if (response == null) {
             return null;
@@ -1521,7 +1524,7 @@
         addUserKeyAuth(userId, null, key);
     }
 
-    private void setUserKeyProtection(int userId, String credential, VerifyCredentialResponse vcr)
+    private void setUserKeyProtection(int userId, byte[] credential, VerifyCredentialResponse vcr)
             throws RemoteException {
         if (DEBUG) Slog.d(TAG, "setUserKeyProtection: user=" + userId);
         if (vcr == null) {
@@ -1543,16 +1546,15 @@
         addUserKeyAuth(userId, null, null);
     }
 
-    private static byte[] secretFromCredential(String credential) throws RemoteException {
+    private static byte[] secretFromCredential(byte[] credential) throws RemoteException {
         try {
             MessageDigest digest = MessageDigest.getInstance("SHA-512");
             // Personalize the hash
-            byte[] personalization = "Android FBE credential hash"
-                    .getBytes(StandardCharsets.UTF_8);
+            byte[] personalization = "Android FBE credential hash".getBytes();
             // Pad it to the block size of the hash function
             personalization = Arrays.copyOf(personalization, 128);
             digest.update(personalization);
-            digest.update(credential.getBytes(StandardCharsets.UTF_8));
+            digest.update(credential);
             return digest.digest();
         } catch (NoSuchAlgorithmException e) {
             throw new RuntimeException("NoSuchAlgorithmException for SHA-512");
@@ -1588,7 +1590,7 @@
         checkWritePermission(userId);
         if (DEBUG) Slog.v(TAG, "Reset keystore for user: " + userId);
         int managedUserId = -1;
-        String managedUserDecryptedPassword = null;
+        byte[] managedUserDecryptedPassword = null;
         final List<UserInfo> profiles = mUserManager.getProfiles(userId);
         for (UserInfo pi : profiles) {
             // Unlock managed profile with unified lock
@@ -1625,17 +1627,20 @@
                 tieProfileLockToParent(managedUserId, managedUserDecryptedPassword);
             }
         }
+        if (managedUserDecryptedPassword != null && managedUserDecryptedPassword.length > 0) {
+            Arrays.fill(managedUserDecryptedPassword, (byte) 0);
+        }
     }
 
     @Override
-    public VerifyCredentialResponse checkCredential(String credential, int type, int userId,
+    public VerifyCredentialResponse checkCredential(byte[] credential, int type, int userId,
             ICheckCredentialProgressCallback progressCallback) throws RemoteException {
         checkPasswordReadPermission(userId);
         return doVerifyCredential(credential, type, false, 0, userId, progressCallback);
     }
 
     @Override
-    public VerifyCredentialResponse verifyCredential(String credential, int type, long challenge,
+    public VerifyCredentialResponse verifyCredential(byte[] credential, int type, long challenge,
             int userId) throws RemoteException {
         checkPasswordReadPermission(userId);
         return doVerifyCredential(credential, type, true, challenge, userId,
@@ -1646,10 +1651,10 @@
      * Verify user credential and unlock the user. Fix pattern bug by deprecating the old base zero
      * format.
      */
-    private VerifyCredentialResponse doVerifyCredential(String credential, int credentialType,
+    private VerifyCredentialResponse doVerifyCredential(byte[] credential, int credentialType,
             boolean hasChallenge, long challenge, int userId,
             ICheckCredentialProgressCallback progressCallback) throws RemoteException {
-        if (TextUtils.isEmpty(credential)) {
+        if (credential == null || credential.length == 0) {
             throw new IllegalArgumentException("Credential can't be null or empty");
         }
         if (userId == USER_FRP && Settings.Global.getInt(mContext.getContentResolver(),
@@ -1684,9 +1689,9 @@
         boolean shouldReEnrollBaseZero = storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN
                 && storedHash.isBaseZeroPattern;
 
-        String credentialToVerify;
+        byte[] credentialToVerify;
         if (shouldReEnrollBaseZero) {
-            credentialToVerify = LockPatternUtils.patternStringToBaseZero(credential);
+            credentialToVerify = LockPatternUtils.patternByteArrayToBaseZero(credential);
         } else {
             credentialToVerify = credential;
         }
@@ -1706,7 +1711,7 @@
     }
 
     @Override
-    public VerifyCredentialResponse verifyTiedProfileChallenge(String credential, int type,
+    public VerifyCredentialResponse verifyTiedProfileChallenge(byte[] credential, int type,
             long challenge, int userId) throws RemoteException {
         checkPasswordReadPermission(userId);
         if (!isManagedProfileWithUnifiedLock(userId)) {
@@ -1748,14 +1753,15 @@
      * hash to GK.
      */
     private VerifyCredentialResponse verifyCredential(int userId, CredentialHash storedHash,
-            String credential, boolean hasChallenge, long challenge,
+            byte[] credential, boolean hasChallenge, long challenge,
             ICheckCredentialProgressCallback progressCallback) throws RemoteException {
-        if ((storedHash == null || storedHash.hash.length == 0) && TextUtils.isEmpty(credential)) {
+        if ((storedHash == null || storedHash.hash.length == 0)
+                    && (credential == null || credential.length == 0)) {
             // don't need to pass empty credentials to GateKeeper
             return VerifyCredentialResponse.OK;
         }
 
-        if (storedHash == null || TextUtils.isEmpty(credential)) {
+        if (storedHash == null || credential == null || credential.length == 0) {
             return VerifyCredentialResponse.ERROR;
         }
 
@@ -1766,14 +1772,14 @@
         if (storedHash.version == CredentialHash.VERSION_LEGACY) {
             final byte[] hash;
             if (storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN) {
-                hash = LockPatternUtils.patternToHash(LockPatternUtils.stringToPattern(credential));
+                hash = LockPatternUtils.patternToHash(
+                        LockPatternUtils.byteArrayToPattern(credential));
             } else {
-                hash = mLockPatternUtils.legacyPasswordToHash(credential, userId)
-                        .getBytes(StandardCharsets.UTF_8);
+                hash = mLockPatternUtils.legacyPasswordToHash(credential, userId).getBytes();
             }
             if (Arrays.equals(hash, storedHash.hash)) {
                 if (storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN) {
-                    unlockKeystore(LockPatternUtils.patternStringToBaseZero(credential), userId);
+                    unlockKeystore(LockPatternUtils.patternByteArrayToBaseZero(credential), userId);
                 } else {
                     unlockKeystore(credential, userId);
                 }
@@ -1804,7 +1810,7 @@
             }
         }
         GateKeeperResponse gateKeeperResponse = getGateKeeperService()
-                .verifyChallenge(userId, challenge, storedHash.hash, credential.getBytes());
+                .verifyChallenge(userId, challenge, storedHash.hash, credential);
         VerifyCredentialResponse response = convertResponse(gateKeeperResponse);
         boolean shouldReEnroll = gateKeeperResponse.getShouldReEnroll();
 
@@ -1863,7 +1869,7 @@
      * Call this method to notify DPMS regarding the latest password metric. This should be called
      * when the user is authenticating or when a new password is being set.
      */
-    private void notifyActivePasswordMetricsAvailable(String password, @UserIdInt int userId) {
+    private void notifyActivePasswordMetricsAvailable(byte[] password, @UserIdInt int userId) {
         final PasswordMetrics metrics;
         if (password == null) {
             metrics = new PasswordMetrics();
@@ -1912,6 +1918,7 @@
         // service can't connect to vold, it restarts, and then the new instance
         // does successfully connect.
         final IStorageManager service = mInjector.getStorageManager();
+        // TODO(b/120484642): Update vold to return a password as a byte array
         String password;
         long identity = Binder.clearCallingIdentity();
         try {
@@ -1926,8 +1933,8 @@
 
         try {
             if (mLockPatternUtils.isLockPatternEnabled(userId)) {
-                if (checkCredential(password, LockPatternUtils.CREDENTIAL_TYPE_PATTERN, userId,
-                        null /* progressCallback */)
+                if (checkCredential(password.getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
+                        userId, null /* progressCallback */)
                                 .getResponseCode() == GateKeeperResponse.RESPONSE_OK) {
                     return true;
                 }
@@ -1937,8 +1944,8 @@
 
         try {
             if (mLockPatternUtils.isLockPasswordEnabled(userId)) {
-                if (checkCredential(password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, userId,
-                        null /* progressCallback */)
+                if (checkCredential(password.getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
+                        userId, null /* progressCallback */)
                                 .getResponseCode() == GateKeeperResponse.RESPONSE_OK) {
                     return true;
                 }
@@ -1966,7 +1973,8 @@
         } catch (RemoteException ex) {
             Slog.w(TAG, "unable to clear GK secure user id");
         }
-        if (unknownUser || mUserManager.getUserInfo(userId).isManagedProfile()) {
+        UserInfo userInfo = mUserManager.getUserInfo(userId);
+        if (unknownUser || userInfo == null || userInfo.isManagedProfile()) {
             removeKeystoreProfileKey(userId);
         }
     }
@@ -2322,7 +2330,7 @@
     @GuardedBy("mSpManager")
     @VisibleForTesting
     protected AuthenticationToken initializeSyntheticPasswordLocked(byte[] credentialHash,
-            String credential, int credentialType, int requestedQuality,
+            byte[] credential, int credentialType, int requestedQuality,
             int userId) throws RemoteException {
         Slog.i(TAG, "Initialize SyntheticPassword for user: " + userId);
         final AuthenticationToken auth = mSpManager.newSyntheticPasswordAndSid(
@@ -2383,7 +2391,7 @@
         setLong(SYNTHETIC_PASSWORD_ENABLED_KEY, 1, UserHandle.USER_SYSTEM);
     }
 
-    private VerifyCredentialResponse spBasedDoVerifyCredential(String userCredential, int
+    private VerifyCredentialResponse spBasedDoVerifyCredential(byte[] userCredential, int
             credentialType, boolean hasChallenge, long challenge, int userId,
             ICheckCredentialProgressCallback progressCallback) throws RemoteException {
         if (DEBUG) Slog.d(TAG, "spBasedDoVerifyCredential: user=" + userId);
@@ -2482,12 +2490,12 @@
      * added back when new password is set in future.
      */
     @GuardedBy("mSpManager")
-    private long setLockCredentialWithAuthTokenLocked(String credential, int credentialType,
+    private long setLockCredentialWithAuthTokenLocked(byte[] credential, int credentialType,
             AuthenticationToken auth, int requestedQuality, int userId) throws RemoteException {
         if (DEBUG) Slog.d(TAG, "setLockCredentialWithAuthTokenLocked: user=" + userId);
         long newHandle = mSpManager.createPasswordBasedSyntheticPassword(getGateKeeperService(),
                 credential, credentialType, auth, requestedQuality, userId);
-        final Map<Integer, String> profilePasswords;
+        final Map<Integer, byte[]> profilePasswords;
         if (credential != null) {
             // // not needed by synchronizeUnifiedWorkChallengeForProfiles()
             profilePasswords = null;
@@ -2526,12 +2534,19 @@
         synchronizeUnifiedWorkChallengeForProfiles(userId, profilePasswords);
 
         notifyActivePasswordMetricsAvailable(credential, userId);
+
+        if (profilePasswords != null) {
+            for (Map.Entry<Integer, byte[]> entry : profilePasswords.entrySet()) {
+                Arrays.fill(entry.getValue(), (byte) 0);
+            }
+        }
+
         return newHandle;
     }
 
     @GuardedBy("mSpManager")
-    private void spBasedSetLockCredentialInternalLocked(String credential, int credentialType,
-            String savedCredential, int requestedQuality, int userId) throws RemoteException {
+    private void spBasedSetLockCredentialInternalLocked(byte[] credential, int credentialType,
+            byte[] savedCredential, int requestedQuality, int userId) throws RemoteException {
         if (DEBUG) Slog.d(TAG, "spBasedSetLockCredentialInternalLocked: user=" + userId);
         if (isManagedProfileWithUnifiedLock(userId)) {
             // get credential from keystore when managed profile has unified lock
@@ -2604,9 +2619,9 @@
      * If user is a managed profile with unified challenge, currentCredential is ignored.
      */
     @Override
-    public byte[] getHashFactor(String currentCredential, int userId) throws RemoteException {
+    public byte[] getHashFactor(byte[] currentCredential, int userId) throws RemoteException {
         checkPasswordReadPermission(userId);
-        if (TextUtils.isEmpty(currentCredential)) {
+        if (currentCredential == null || currentCredential.length == 0) {
             currentCredential = null;
         }
         if (isManagedProfileWithUnifiedLock(userId)) {
@@ -2700,7 +2715,7 @@
         }
     }
 
-    private boolean setLockCredentialWithToken(String credential, int type, long tokenHandle,
+    private boolean setLockCredentialWithToken(byte[] credential, int type, long tokenHandle,
             byte[] token, int requestedQuality, int userId) throws RemoteException {
         boolean result;
         synchronized (mSpManager) {
@@ -2720,7 +2735,7 @@
         return result;
     }
 
-    private boolean setLockCredentialWithTokenInternal(String credential, int type,
+    private boolean setLockCredentialWithTokenInternal(byte[] credential, int type,
             long tokenHandle, byte[] token, int requestedQuality, int userId) throws RemoteException {
         final AuthenticationResult result;
         synchronized (mSpManager) {
@@ -2947,8 +2962,8 @@
         }
 
         @Override
-        public boolean setLockCredentialWithToken(String credential, int type, long tokenHandle,
-                byte[] token, int requestedQuality, int userId) {
+        public boolean setLockCredentialWithToken(byte[] credential, int type,
+                long tokenHandle, byte[] token, int requestedQuality, int userId) {
             if (!mLockPatternUtils.hasSecureLockScreen()) {
                 throw new UnsupportedOperationException(
                         "This operation requires secure lock screen feature.");
diff --git a/services/core/java/com/android/server/locksettings/LockSettingsShellCommand.java b/services/core/java/com/android/server/locksettings/LockSettingsShellCommand.java
index 6163077..ee22264 100644
--- a/services/core/java/com/android/server/locksettings/LockSettingsShellCommand.java
+++ b/services/core/java/com/android/server/locksettings/LockSettingsShellCommand.java
@@ -190,22 +190,30 @@
     }
 
     private void runSetPattern() {
-        mLockPatternUtils.saveLockPattern(stringToPattern(mNew), mOld, mCurrentUserId);
+        byte[] oldBytes = mOld != null ? mOld.getBytes() : null;
+        mLockPatternUtils.saveLockPattern(stringToPattern(mNew), oldBytes, mCurrentUserId);
         getOutPrintWriter().println("Pattern set to '" + mNew + "'");
     }
 
     private void runSetPassword() {
-        mLockPatternUtils.saveLockPassword(mNew, mOld, PASSWORD_QUALITY_ALPHABETIC, mCurrentUserId);
+        byte[] newBytes = mNew != null ? mNew.getBytes() : null;
+        byte[] oldBytes = mOld != null ? mOld.getBytes() : null;
+        mLockPatternUtils.saveLockPassword(newBytes, oldBytes, PASSWORD_QUALITY_ALPHABETIC,
+                mCurrentUserId);
         getOutPrintWriter().println("Password set to '" + mNew + "'");
     }
 
     private void runSetPin() {
-        mLockPatternUtils.saveLockPassword(mNew, mOld, PASSWORD_QUALITY_NUMERIC, mCurrentUserId);
+        byte[] newBytes = mNew != null ? mNew.getBytes() : null;
+        byte[] oldBytes = mOld != null ? mOld.getBytes() : null;
+        mLockPatternUtils.saveLockPassword(newBytes, oldBytes, PASSWORD_QUALITY_NUMERIC,
+                mCurrentUserId);
         getOutPrintWriter().println("Pin set to '" + mNew + "'");
     }
 
     private void runClear() {
-        mLockPatternUtils.clearLock(mOld, mCurrentUserId);
+        byte[] oldBytes = mOld != null ? mOld.getBytes() : null;
+        mLockPatternUtils.clearLock(oldBytes, mCurrentUserId);
         getOutPrintWriter().println("Lock credential cleared");
     }
 
@@ -232,7 +240,8 @@
             try {
                 final boolean result;
                 if (havePassword) {
-                    result = mLockPatternUtils.checkPassword(mOld, mCurrentUserId);
+                    byte[] passwordBytes = mOld != null ? mOld.getBytes() : null;
+                    result = mLockPatternUtils.checkPassword(passwordBytes, mCurrentUserId);
                 } else {
                     result = mLockPatternUtils.checkPattern(stringToPattern(mOld), mCurrentUserId);
                 }
diff --git a/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java b/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java
index 0e195bc..ea39dff 100644
--- a/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java
+++ b/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java
@@ -97,7 +97,7 @@
     private static final String WEAVER_SLOT_NAME = "weaver";
 
     public static final long DEFAULT_HANDLE = 0L;
-    private static final String DEFAULT_PASSWORD = "default-password";
+    private static final byte[] DEFAULT_PASSWORD = "default-password".getBytes();
 
     private static final byte WEAVER_VERSION = 1;
     private static final int INVALID_WEAVER_SLOT = -1;
@@ -165,7 +165,7 @@
             }
         }
 
-        public String deriveKeyStorePassword() {
+        public byte[] deriveKeyStorePassword() {
             return bytesToHex(derivePassword(PERSONALIZATION_KEY_STORE_PASSWORD));
         }
 
@@ -454,11 +454,11 @@
      *
      */
     public AuthenticationToken newSyntheticPasswordAndSid(IGateKeeperService gatekeeper,
-            byte[] hash, String credential, int userId) throws RemoteException {
+            byte[] hash, byte[] credential, int userId) throws RemoteException {
         AuthenticationToken result = AuthenticationToken.create();
         GateKeeperResponse response;
         if (hash != null) {
-            response = gatekeeper.enroll(userId, hash, credential.getBytes(),
+            response = gatekeeper.enroll(userId, hash, credential,
                     result.deriveGkPassword());
             if (response.getResponseCode() != GateKeeperResponse.RESPONSE_OK) {
                 Log.w(TAG, "Fail to migrate SID, assuming no SID, user " + userId);
@@ -616,7 +616,7 @@
      * @see #clearSidForUser
      */
     public long createPasswordBasedSyntheticPassword(IGateKeeperService gatekeeper,
-            String credential, int credentialType, AuthenticationToken authToken,
+            byte[] credential, int credentialType, AuthenticationToken authToken,
             int requestedQuality, int userId)
                     throws RemoteException {
         if (credential == null || credentialType == LockPatternUtils.CREDENTIAL_TYPE_NONE) {
@@ -670,7 +670,7 @@
     }
 
     public VerifyCredentialResponse verifyFrpCredential(IGateKeeperService gatekeeper,
-            String userCredential, int credentialType,
+            byte[] userCredential, int credentialType,
             ICheckCredentialProgressCallback progressCallback) throws RemoteException {
         PersistentData persistentData = mStorage.readPersistentDataBlock();
         if (persistentData.type == PersistentData.TYPE_SP) {
@@ -839,7 +839,7 @@
      * unknown. Caller might choose to validate it by examining AuthenticationResult.credentialType
      */
     public AuthenticationResult unwrapPasswordBasedSyntheticPassword(IGateKeeperService gatekeeper,
-            long handle, String credential, int userId,
+            long handle, byte[] credential, int userId,
             ICheckCredentialProgressCallback progressCallback) throws RemoteException {
         if (credential == null) {
             credential = DEFAULT_PASSWORD;
@@ -1152,7 +1152,7 @@
         return String.format("%s%x", LockPatternUtils.SYNTHETIC_PASSWORD_KEY_PREFIX, handle);
     }
 
-    private byte[] computePasswordToken(String password, PasswordData data) {
+    private byte[] computePasswordToken(byte[] password, PasswordData data) {
         return scrypt(password, data.salt, 1 << data.scryptN, 1 << data.scryptR, 1 << data.scryptP,
                 PASSWORD_TOKEN_LENGTH);
     }
@@ -1173,8 +1173,8 @@
         return nativeSidFromPasswordHandle(handle);
     }
 
-    protected byte[] scrypt(String password, byte[] salt, int N, int r, int p, int outLen) {
-        return new Scrypt().scrypt(password.getBytes(), salt, N, r, p, outLen);
+    protected byte[] scrypt(byte[] password, byte[] salt, int n, int r, int p, int outLen) {
+        return new Scrypt().scrypt(password, salt, n, r, p, outLen);
     }
 
     native long nativeSidFromPasswordHandle(byte[] handle);
@@ -1195,17 +1195,17 @@
         return result;
     }
 
-    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
-    public static String bytesToHex(byte[] bytes) {
+    protected static final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes();
+    private static byte[] bytesToHex(byte[] bytes) {
         if (bytes == null) {
-            return "null";
+            return "null".getBytes();
         }
-        char[] hexChars = new char[bytes.length * 2];
+        byte[] hexBytes = new byte[bytes.length * 2];
         for ( int j = 0; j < bytes.length; j++ ) {
             int v = bytes[j] & 0xFF;
-            hexChars[j * 2] = hexArray[v >>> 4];
-            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
+            hexBytes[j * 2] = HEX_ARRAY[v >>> 4];
+            hexBytes[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
         }
-        return new String(hexChars);
+        return hexBytes;
     }
 }
diff --git a/services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java b/services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java
index e7a71b9..5676da2 100644
--- a/services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java
+++ b/services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java
@@ -38,7 +38,6 @@
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.nio.ByteOrder;
-import java.nio.charset.StandardCharsets;
 import java.security.GeneralSecurityException;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
@@ -51,6 +50,7 @@
 import java.security.cert.CertPath;
 import java.security.cert.CertificateException;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 
@@ -85,7 +85,7 @@
     private final RecoverableKeyStoreDb mRecoverableKeyStoreDb;
     private final int mUserId;
     private final int mCredentialType;
-    private final String mCredential;
+    private final byte[] mCredential;
     private final boolean mCredentialUpdated;
     private final PlatformKeyManager mPlatformKeyManager;
     private final RecoverySnapshotStorage mRecoverySnapshotStorage;
@@ -100,7 +100,7 @@
             RecoverySnapshotListenersStorage recoverySnapshotListenersStorage,
             int userId,
             int credentialType,
-            String credential,
+            byte[] credential,
             boolean credentialUpdated
     ) throws NoSuchAlgorithmException, KeyStoreException, InsecureUserException {
         return new KeySyncTask(
@@ -134,7 +134,7 @@
             RecoverySnapshotListenersStorage recoverySnapshotListenersStorage,
             int userId,
             int credentialType,
-            String credential,
+            byte[] credential,
             boolean credentialUpdated,
             PlatformKeyManager platformKeyManager,
             TestOnlyInsecureCertificateHelper testOnlyInsecureCertificateHelper,
@@ -450,7 +450,7 @@
      */
     @VisibleForTesting
     @KeyChainProtectionParams.LockScreenUiFormat static int getUiFormat(
-            int credentialType, String credential) {
+            int credentialType, byte[] credential) {
         if (credentialType == LockPatternUtils.CREDENTIAL_TYPE_PATTERN) {
             return KeyChainProtectionParams.UI_FORMAT_PATTERN;
         } else if (isPin(credential)) {
@@ -475,13 +475,13 @@
      * Returns {@code true} if {@code credential} looks like a pin.
      */
     @VisibleForTesting
-    static boolean isPin(@Nullable String credential) {
+    static boolean isPin(@Nullable byte[] credential) {
         if (credential == null) {
             return false;
         }
-        int length = credential.length();
+        int length = credential.length;
         for (int i = 0; i < length; i++) {
-            if (!Character.isDigit(credential.charAt(i))) {
+            if (!Character.isDigit((char) credential[i])) {
                 return false;
             }
         }
@@ -494,8 +494,7 @@
      * @return The SHA-256 hash.
      */
     @VisibleForTesting
-    static byte[] hashCredentialsBySaltedSha256(byte[] salt, String credentials) {
-        byte[] credentialsBytes = credentials.getBytes(StandardCharsets.UTF_8);
+    static byte[] hashCredentialsBySaltedSha256(byte[] salt, byte[] credentialsBytes) {
         ByteBuffer byteBuffer = ByteBuffer.allocate(
                 salt.length + credentialsBytes.length + LENGTH_PREFIX_BYTES * 2);
         byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
@@ -506,17 +505,19 @@
         byte[] bytes = byteBuffer.array();
 
         try {
-            return MessageDigest.getInstance(LOCK_SCREEN_HASH_ALGORITHM).digest(bytes);
+            byte[] hash = MessageDigest.getInstance(LOCK_SCREEN_HASH_ALGORITHM).digest(bytes);
+            Arrays.fill(bytes, (byte) 0);
+            return hash;
         } catch (NoSuchAlgorithmException e) {
             // Impossible, SHA-256 must be supported on Android.
             throw new RuntimeException(e);
         }
     }
 
-    private byte[] hashCredentialsByScrypt(byte[] salt, String credentials) {
+    private byte[] hashCredentialsByScrypt(byte[] salt, byte[] credentials) {
         return mScrypt.scrypt(
-                credentials.getBytes(StandardCharsets.UTF_8), salt,
-                SCRYPT_PARAM_N, SCRYPT_PARAM_R, SCRYPT_PARAM_P, SCRYPT_PARAM_OUTLEN_BYTES);
+                credentials, salt, SCRYPT_PARAM_N, SCRYPT_PARAM_R, SCRYPT_PARAM_P,
+                SCRYPT_PARAM_OUTLEN_BYTES);
     }
 
     private static SecretKey generateRecoveryKey() throws NoSuchAlgorithmException {
diff --git a/services/core/java/com/android/server/locksettings/recoverablekeystore/RecoverableKeyStoreManager.java b/services/core/java/com/android/server/locksettings/recoverablekeystore/RecoverableKeyStoreManager.java
index ed864c0..47b9c27 100644
--- a/services/core/java/com/android/server/locksettings/recoverablekeystore/RecoverableKeyStoreManager.java
+++ b/services/core/java/com/android/server/locksettings/recoverablekeystore/RecoverableKeyStoreManager.java
@@ -892,13 +892,13 @@
      * This function can only be used inside LockSettingsService.
      *
      * @param storedHashType from {@code CredentialHash}
-     * @param credential - unencrypted String. Password length should be at most 16 symbols {@code
-     *     mPasswordMaxLength}
+     * @param credential - unencrypted byte array. Password length should be at most 16 symbols
+     *     {@code mPasswordMaxLength}
      * @param userId for user who just unlocked the device.
      * @hide
      */
     public void lockScreenSecretAvailable(
-            int storedHashType, @NonNull String credential, int userId) {
+            int storedHashType, @NonNull byte[] credential, int userId) {
         // So as not to block the critical path unlocking the phone, defer to another thread.
         try {
             mExecutorService.execute(KeySyncTask.newInstance(
@@ -923,13 +923,13 @@
      * This function can only be used inside LockSettingsService.
      *
      * @param storedHashType from {@code CredentialHash}
-     * @param credential - unencrypted String
+     * @param credential - unencrypted byte array
      * @param userId for the user whose lock screen credentials were changed.
      * @hide
      */
     public void lockScreenSecretChanged(
             int storedHashType,
-            @Nullable String credential,
+            @Nullable byte[] credential,
             int userId) {
         // So as not to block the critical path unlocking the phone, defer to another thread.
         try {
diff --git a/services/core/java/com/android/server/locksettings/recoverablekeystore/TestOnlyInsecureCertificateHelper.java b/services/core/java/com/android/server/locksettings/recoverablekeystore/TestOnlyInsecureCertificateHelper.java
index 057429c..90a36723 100644
--- a/services/core/java/com/android/server/locksettings/recoverablekeystore/TestOnlyInsecureCertificateHelper.java
+++ b/services/core/java/com/android/server/locksettings/recoverablekeystore/TestOnlyInsecureCertificateHelper.java
@@ -87,10 +87,30 @@
                 || isTestOnlyCertificateAlias(rootCertificateAlias);
     }
 
-    public boolean doesCredentialSupportInsecureMode(int credentialType, String credential) {
-        return (credentialType == LockPatternUtils.CREDENTIAL_TYPE_PASSWORD)
-            && (credential != null)
-            && credential.startsWith(TrustedRootCertificates.INSECURE_PASSWORD_PREFIX);
+    /**
+     * Checks whether a password is in "Insecure mode"
+     * @param credentialType the type of credential, e.g. pattern and password
+     * @param credential the pattern or password
+     * @return true, if the credential is in "Insecure mode"
+     */
+    public boolean doesCredentialSupportInsecureMode(int credentialType, byte[] credential) {
+        if (credential == null) {
+            return false;
+        }
+        if (credentialType != LockPatternUtils.CREDENTIAL_TYPE_PASSWORD) {
+            return false;
+        }
+        byte[] insecurePasswordPrefixBytes =
+                TrustedRootCertificates.INSECURE_PASSWORD_PREFIX.getBytes();
+        if (credential.length < insecurePasswordPrefixBytes.length) {
+            return false;
+        }
+        for (int i = 0; i < insecurePasswordPrefixBytes.length; i++) {
+            if (credential[i] != insecurePasswordPrefixBytes[i]) {
+                return false;
+            }
+        }
+        return true;
     }
 
     public Map<String, Pair<SecretKey, byte[]>> keepOnlyWhitelistedInsecureKeys(
diff --git a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
index fccff57..270fbc6 100644
--- a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
+++ b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
@@ -16,17 +16,15 @@
 
 package com.android.server.media.projection;
 
-import com.android.server.Watchdog;
-
 import android.Manifest;
 import android.app.AppOpsManager;
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.hardware.display.DisplayManager;
 import android.media.MediaRouter;
-import android.media.projection.IMediaProjectionManager;
 import android.media.projection.IMediaProjection;
 import android.media.projection.IMediaProjectionCallback;
+import android.media.projection.IMediaProjectionManager;
 import android.media.projection.IMediaProjectionWatcherCallback;
 import android.media.projection.MediaProjectionInfo;
 import android.media.projection.MediaProjectionManager;
@@ -41,6 +39,7 @@
 
 import com.android.internal.util.DumpUtils;
 import com.android.server.SystemService;
+import com.android.server.Watchdog;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
@@ -361,8 +360,9 @@
 
         @Override // Binder call
         public boolean canProjectAudio() {
-            return mType == MediaProjectionManager.TYPE_MIRRORING ||
-                    mType == MediaProjectionManager.TYPE_PRESENTATION;
+            return mType == MediaProjectionManager.TYPE_MIRRORING
+                || mType == MediaProjectionManager.TYPE_PRESENTATION
+                || mType == MediaProjectionManager.TYPE_SCREEN_CAPTURE;
         }
 
         @Override // Binder call
diff --git a/services/core/java/com/android/server/net/NetworkStatsService.java b/services/core/java/com/android/server/net/NetworkStatsService.java
index bffd60b..205ddb0 100644
--- a/services/core/java/com/android/server/net/NetworkStatsService.java
+++ b/services/core/java/com/android/server/net/NetworkStatsService.java
@@ -82,7 +82,6 @@
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.net.DataUsageRequest;
-import android.net.IConnectivityManager;
 import android.net.INetworkManagementEventObserver;
 import android.net.INetworkStatsService;
 import android.net.INetworkStatsSession;
@@ -196,8 +195,6 @@
 
     private final boolean mUseBpfTrafficStats;
 
-    private IConnectivityManager mConnManager;
-
     @VisibleForTesting
     public static final String ACTION_NETWORK_STATS_POLL =
             "com.android.server.action.NETWORK_STATS_POLL";
@@ -259,6 +256,7 @@
     private final ArrayMap<String, NetworkIdentitySet> mActiveUidIfaces = new ArrayMap<>();
 
     /** Current default active iface. */
+    @GuardedBy("mStatsLock")
     private String mActiveIface;
 
     /** Set of any ifaces associated with mobile networks since boot. */
@@ -269,6 +267,10 @@
     @GuardedBy("mStatsLock")
     private Network[] mDefaultNetworks = new Network[0];
 
+    /** Set containing info about active VPNs and their underlying networks. */
+    @GuardedBy("mStatsLock")
+    private VpnInfo[] mVpnInfos = new VpnInfo[0];
+
     private final DropBoxNonMonotonicObserver mNonMonotonicObserver =
             new DropBoxNonMonotonicObserver();
 
@@ -382,10 +384,6 @@
         mHandlerCallback = callback;
     }
 
-    public void bindConnectivityManager(IConnectivityManager connManager) {
-        mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
-    }
-
     public void systemReady() {
         mSystemReady = true;
 
@@ -864,13 +862,17 @@
     }
 
     @Override
-    public void forceUpdateIfaces(Network[] defaultNetworks) {
+    public void forceUpdateIfaces(
+            Network[] defaultNetworks,
+            VpnInfo[] vpnArray,
+            NetworkState[] networkStates,
+            String activeIface) {
         mContext.enforceCallingOrSelfPermission(READ_NETWORK_USAGE_HISTORY, TAG);
         assertBandwidthControlEnabled();
 
         final long token = Binder.clearCallingIdentity();
         try {
-            updateIfaces(defaultNetworks);
+            updateIfaces(defaultNetworks, vpnArray, networkStates, activeIface);
         } finally {
             Binder.restoreCallingIdentity(token);
         }
@@ -1134,11 +1136,17 @@
         }
     };
 
-    private void updateIfaces(Network[] defaultNetworks) {
+    private void updateIfaces(
+            Network[] defaultNetworks,
+            VpnInfo[] vpnArray,
+            NetworkState[] networkStates,
+            String activeIface) {
         synchronized (mStatsLock) {
             mWakeLock.acquire();
             try {
-                updateIfacesLocked(defaultNetworks);
+                mVpnInfos = vpnArray;
+                mActiveIface = activeIface;
+                updateIfacesLocked(defaultNetworks, networkStates);
             } finally {
                 mWakeLock.release();
             }
@@ -1152,7 +1160,7 @@
      * {@link NetworkIdentitySet}.
      */
     @GuardedBy("mStatsLock")
-    private void updateIfacesLocked(Network[] defaultNetworks) {
+    private void updateIfacesLocked(Network[] defaultNetworks, NetworkState[] states) {
         if (!mSystemReady) return;
         if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
 
@@ -1164,18 +1172,6 @@
         // will be persisted during next alarm poll event.
         performPollLocked(FLAG_PERSIST_NETWORK);
 
-        final NetworkState[] states;
-        final LinkProperties activeLink;
-        try {
-            states = mConnManager.getAllNetworkState();
-            activeLink = mConnManager.getActiveLinkProperties();
-        } catch (RemoteException e) {
-            // ignored; service lives in system_server
-            return;
-        }
-
-        mActiveIface = activeLink != null ? activeLink.getInterfaceName() : null;
-
         // Rebuild active interfaces based on connected networks
         mActiveIfaces.clear();
         mActiveUidIfaces.clear();
@@ -1287,7 +1283,7 @@
         Trace.traceEnd(TRACE_TAG_NETWORK);
 
         // For per-UID stats, pass the VPN info so VPN traffic is reattributed to responsible apps.
-        VpnInfo[] vpnArray = mConnManager.getAllVpnInfo();
+        VpnInfo[] vpnArray = mVpnInfos;
         Trace.traceBegin(TRACE_TAG_NETWORK, "recordUid");
         mUidRecorder.recordSnapshotLocked(uidSnapshot, mActiveUidIfaces, vpnArray, currentTime);
         Trace.traceEnd(TRACE_TAG_NETWORK);
diff --git a/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java b/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java
index 1dada92..85a3ba1 100644
--- a/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java
+++ b/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java
@@ -78,7 +78,12 @@
         Preconditions.checkNotNull(bugreportFd);
         Preconditions.checkNotNull(listener);
         validateBugreportMode(bugreportMode);
-        ensureIsPrimaryUser();
+        final long identity = Binder.clearCallingIdentity();
+        try {
+            ensureIsPrimaryUser();
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
 
         int callingUid = Binder.getCallingUid();
         mAppOps.checkPackage(callingUid, callingPackage);
@@ -146,8 +151,8 @@
         if (isDumpstateBinderServiceRunningLocked()) {
             Slog.w(TAG, "'dumpstate' is already running. Cannot start a new bugreport"
                     + " while another one is currently in progress.");
-            // TODO(b/111441001): Use a new error code; add this to the documentation of the API.
-            reportError(listener, IDumpstateListener.BUGREPORT_ERROR_RUNTIME_ERROR);
+            reportError(listener,
+                    IDumpstateListener.BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS);
             return;
         }
 
diff --git a/services/core/java/com/android/server/pm/ApexManager.java b/services/core/java/com/android/server/pm/ApexManager.java
index d52e237..a4c04b2 100644
--- a/services/core/java/com/android/server/pm/ApexManager.java
+++ b/services/core/java/com/android/server/pm/ApexManager.java
@@ -22,6 +22,10 @@
 import android.apex.ApexInfoList;
 import android.apex.ApexSessionInfo;
 import android.apex.IApexService;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageParser;
 import android.content.pm.PackageParser.PackageParserException;
@@ -49,17 +53,29 @@
 class ApexManager {
     static final String TAG = "ApexManager";
     private final IApexService mApexService;
+    private final Context mContext;
     private final Object mLock = new Object();
     @GuardedBy("mLock")
     private Map<String, PackageInfo> mActivePackagesCache;
 
-    ApexManager() {
+    ApexManager(Context context) {
         try {
             mApexService = IApexService.Stub.asInterface(
                 ServiceManager.getServiceOrThrow("apexservice"));
         } catch (ServiceNotFoundException e) {
             throw new IllegalStateException("Required service apexservice not available");
         }
+        mContext = context;
+    }
+
+    void systemReady() {
+        mContext.registerReceiver(new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                onBootCompleted();
+                mContext.unregisterReceiver(this);
+            }
+        }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
     }
 
     private void populateActivePackagesCacheIfNeeded() {
@@ -207,6 +223,7 @@
      * @return true if APEX packages can be managed on this device, false otherwise.
      */
     boolean isApexSupported() {
+        populateActivePackagesCacheIfNeeded();
         // There is no system-wide property available to check if APEX are flattened and hence can't
         // be updated. In absence of such property, we assume that if we didn't index APEX packages
         // since they were flattened, no APEX management should be possible.
@@ -214,6 +231,21 @@
     }
 
     /**
+     * Abandons the (only) active session previously submitted.
+     *
+     * @return {@code true} upon success, {@code false} if any remote exception occurs
+     */
+    boolean abortActiveSession() {
+        try {
+            mApexService.abortActiveSession();
+            return true;
+        } catch (RemoteException re) {
+            Slog.e(TAG, "Unable to contact apexservice", re);
+            return false;
+        }
+    }
+
+    /**
      * Dumps various state information to the provided {@link PrintWriter} object.
      *
      * @param pw the {@link PrintWriter} object to send information to.
@@ -255,6 +287,12 @@
                     ipw.println("State: ACTIVATED");
                 } else if (si.isActivationFailed) {
                     ipw.println("State: ACTIVATION FAILED");
+                } else if (si.isSuccess) {
+                    ipw.println("State: SUCCESS");
+                } else if (si.isRollbackInProgress) {
+                    ipw.println("State: ROLLBACK IN PROGRESS");
+                } else if (si.isRolledBack) {
+                    ipw.println("State: ROLLED BACK");
                 }
                 ipw.decreaseIndent();
             }
diff --git a/services/core/java/com/android/server/pm/DynamicCodeLoggingService.java b/services/core/java/com/android/server/pm/DynamicCodeLoggingService.java
index d53d81c..a1ff76fc 100644
--- a/services/core/java/com/android/server/pm/DynamicCodeLoggingService.java
+++ b/services/core/java/com/android/server/pm/DynamicCodeLoggingService.java
@@ -61,7 +61,7 @@
     private static final Pattern EXECUTE_NATIVE_AUDIT_PATTERN =
             Pattern.compile(".*\\bavc: granted \\{ execute(?:_no_trans|) \\} .*"
                     + "\\bpath=(?:\"([^\" ]*)\"|([0-9A-F]+)) .*"
-                    + "\\bscontext=u:r:untrusted_app_2(?:5|7):.*"
+                    + "\\bscontext=u:r:untrusted_app(?:_25|_27)?:.*"
                     + "\\btcontext=u:object_r:app_data_file:.*"
                     + "\\btclass=file\\b.*");
 
diff --git a/services/core/java/com/android/server/pm/OtaDexoptService.java b/services/core/java/com/android/server/pm/OtaDexoptService.java
index b52c021..1c9028d 100644
--- a/services/core/java/com/android/server/pm/OtaDexoptService.java
+++ b/services/core/java/com/android/server/pm/OtaDexoptService.java
@@ -333,7 +333,7 @@
         PackageDexOptimizer optimizer = new OTADexoptPackageDexOptimizer(
                 collectingInstaller, mPackageManagerService.mInstallLock, mContext);
 
-        optimizer.performDexOpt(pkg, pkg.usesLibraryInfos,
+        optimizer.performDexOpt(pkg,
                 null /* ISAs */,
                 null /* CompilerStats.PackageStats */,
                 mPackageManagerService.getDexManager().getPackageUseInfoOrDefault(pkg.packageName),
diff --git a/services/core/java/com/android/server/pm/PackageDexOptimizer.java b/services/core/java/com/android/server/pm/PackageDexOptimizer.java
index 5b38208..4b46374 100644
--- a/services/core/java/com/android/server/pm/PackageDexOptimizer.java
+++ b/services/core/java/com/android/server/pm/PackageDexOptimizer.java
@@ -47,10 +47,12 @@
 import android.content.pm.dex.DexMetadataHelper;
 import android.os.FileUtils;
 import android.os.PowerManager;
+import android.os.Process;
 import android.os.SystemClock;
 import android.os.SystemProperties;
 import android.os.UserHandle;
 import android.os.WorkSource;
+import android.os.storage.StorageManager;
 import android.util.Log;
 import android.util.Slog;
 
@@ -125,7 +127,7 @@
      * <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are
      * synchronized on {@link #mInstallLock}.
      */
-    int performDexOpt(PackageParser.Package pkg, List<SharedLibraryInfo> sharedLibraries,
+    int performDexOpt(PackageParser.Package pkg,
             String[] instructionSets, CompilerStats.PackageStats packageStats,
             PackageDexUsage.PackageUseInfo packageUseInfo, DexoptOptions options) {
         if (pkg.applicationInfo.uid == -1) {
@@ -138,7 +140,7 @@
         synchronized (mInstallLock) {
             final long acquireTime = acquireWakeLockLI(pkg.applicationInfo.uid);
             try {
-                return performDexOptLI(pkg, sharedLibraries, instructionSets,
+                return performDexOptLI(pkg, instructionSets,
                         packageStats, packageUseInfo, options);
             } finally {
                 releaseWakeLockLI(acquireTime);
@@ -146,15 +148,60 @@
         }
     }
 
+    int performDexOpt(SharedLibraryInfo info, String[] instructionSets, DexoptOptions options) {
+        String classLoaderContext = DexoptUtils.getClassLoaderContext(info);
+        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
+        String compilerFilter = PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
+                PackageManagerService.REASON_SHARED);
+        int result = DEX_OPT_SKIPPED;
+        for (String instructionSet : dexCodeInstructionSets) {
+            int dexoptNeeded = getDexoptNeeded(
+                        info.getPath(), instructionSet, compilerFilter,
+                        classLoaderContext, false /* newProfile */,
+                        false /* downgrade */);
+            if (Math.abs(dexoptNeeded) == DexFile.NO_DEXOPT_NEEDED) {
+                continue;
+            }
+            // Special string recognized by installd.
+            final String packageName = "*";
+            final String outputPath = null;
+            int dexFlags = DEXOPT_PUBLIC
+                    | (options.isBootComplete() ? DEXOPT_BOOTCOMPLETE : 0)
+                    | (options.isDexoptIdleBackgroundJob() ? DEXOPT_IDLE_BACKGROUND_JOB : 0);
+            dexFlags = adjustDexoptFlags(dexFlags);
+            final String uuid = StorageManager.UUID_SYSTEM;
+            final String seInfo = null;
+            final int targetSdkVersion = 0;  // Builtin libraries targets the system's SDK version
+            try {
+                mInstaller.dexopt(info.getPath(), Process.SYSTEM_UID, packageName,
+                        instructionSet, dexoptNeeded, outputPath, dexFlags, compilerFilter,
+                        uuid, classLoaderContext, seInfo, false /* downgrade */,
+                        targetSdkVersion, /*profileName*/ null, /*dexMetadataPath*/ null,
+                        getReasonName(options.getCompilationReason()));
+                // The end result is:
+                //  - FAILED if any path failed,
+                //  - PERFORMED if at least one path needed compilation,
+                //  - SKIPPED when all paths are up to date
+                if (result != DEX_OPT_FAILED) {
+                    result = DEX_OPT_PERFORMED;
+                }
+            } catch (InstallerException e) {
+                Slog.w(TAG, "Failed to dexopt", e);
+                result = DEX_OPT_FAILED;
+            }
+        }
+        return result;
+    }
+
     /**
      * Performs dexopt on all code paths of the given package.
      * It assumes the install lock is held.
      */
     @GuardedBy("mInstallLock")
     private int performDexOptLI(PackageParser.Package pkg,
-            List<SharedLibraryInfo> sharedLibraries,
             String[] targetInstructionSets, CompilerStats.PackageStats packageStats,
             PackageDexUsage.PackageUseInfo packageUseInfo, DexoptOptions options) {
+        final List<SharedLibraryInfo> sharedLibraries = pkg.usesLibraryInfos;
         final String[] instructionSets = targetInstructionSets != null ?
                 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
         final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java
index cced0f4..b72e836 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerService.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerService.java
@@ -28,10 +28,8 @@
 import android.app.PackageDeleteObserver;
 import android.app.PackageInstallObserver;
 import android.app.admin.DevicePolicyManagerInternal;
-import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
-import android.content.IntentFilter;
 import android.content.IntentSender;
 import android.content.IntentSender.SendIntentException;
 import android.content.pm.ApplicationInfo;
@@ -141,7 +139,7 @@
 
     private final Callbacks mCallbacks;
 
-    private volatile boolean mBootCompleted = false;
+    private volatile boolean mOkToSendBroadcasts = false;
 
     /**
      * File storing persisted {@link #mSessions} metadata.
@@ -206,29 +204,17 @@
         mSessionsDir.mkdirs();
 
         mApexManager = am;
-        mStagingManager = new StagingManager(pm, this, am);
+
+        mStagingManager = new StagingManager(pm, this, am, context);
     }
 
-    private void onBootCompleted()  {
-        mBootCompleted = true;
-        // Tell APEX manager about it as well
-        mApexManager.onBootCompleted();
-    }
-
-    boolean isBootCompleted()  {
-        return mBootCompleted;
+    boolean okToSendBroadcasts()  {
+        return mOkToSendBroadcasts;
     }
 
     public void systemReady() {
         mAppOps = mContext.getSystemService(AppOpsManager.class);
 
-        mContext.registerReceiver(new BroadcastReceiver() {
-            @Override
-            public void onReceive(Context context, Intent intent) {
-                onBootCompleted();
-                mContext.unregisterReceiver(this);
-            }
-        }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
         synchronized (mSessions) {
             readSessionsLocked();
 
@@ -271,6 +257,16 @@
         for (PackageInstallerSession session : stagedSessionsToRestore) {
             mStagingManager.restoreSession(session);
         }
+        // Broadcasts are not sent while we restore sessions on boot, since no processes would be
+        // ready to listen to them. From now on, we greedily assume that broadcasts requests are
+        // safe to send out. The worst that can happen is that a broadcast is attempted before
+        // ActivityManagerService completes its own systemReady(), in which case it will be rejected
+        // with an otherwise harmless exception.
+        // A more appropriate way to do this would be to wait until the correct  boot phase is
+        // reached, but since we are not a SystemService we can't override onBootPhase.
+        // Waiting on the BOOT_COMPLETED broadcast can take several minutes, so that's not a viable
+        // way either.
+        mOkToSendBroadcasts = true;
     }
 
     @GuardedBy("mSessions")
@@ -1189,7 +1185,7 @@
 
         public void onStagedSessionChanged(PackageInstallerSession session) {
             writeSessionsAsync();
-            if (mBootCompleted) {
+            if (mOkToSendBroadcasts) {
                 mPm.sendSessionUpdatedBroadcast(session.generateInfo(false),
                         session.userId);
             }
diff --git a/services/core/java/com/android/server/pm/PackageInstallerSession.java b/services/core/java/com/android/server/pm/PackageInstallerSession.java
index 9cd220a..45b3b5b 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerSession.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerSession.java
@@ -1867,6 +1867,15 @@
         synchronized (mLock) {
             assertCallerIsOwnerOrRootLocked();
 
+            if (mCommitted && params.isStaged) {
+                synchronized (mLock) {
+                    mDestroyed = true;
+                }
+                mStagingManager.abortCommittedSession(this);
+
+                cleanStageDir();
+            }
+
             if (mRelinquished) {
                 Slog.d(TAG, "Ignoring abandon after commit relinquished control");
                 return;
@@ -1999,7 +2008,7 @@
 
         // Send broadcast to default launcher only if it's a new install
         final boolean isNewInstall = extras == null || !extras.getBoolean(Intent.EXTRA_REPLACING);
-        if (success && isNewInstall && mPm.mInstallerService.isBootCompleted()) {
+        if (success && isNewInstall && mPm.mInstallerService.okToSendBroadcasts()) {
             mPm.sendSessionCommitBroadcast(generateInfo(), userId);
         }
 
@@ -2087,9 +2096,8 @@
             }
         }
         // For staged sessions, we don't delete the directory where the packages have been copied,
-        // since these packages are supposed to be read on reboot. StagingManager is in charge of
-        // deleting these dirs when the staged session has reached a final state.
-        // TODO(b/118865310): Implement packageDir deletion in StagingManager.
+        // since these packages are supposed to be read on reboot.
+        // Those dirs are deleted when the staged session has reached a final state.
         if (stageDir != null && !params.isStaged) {
             try {
                 mPm.mInstaller.rmPackageDir(stageDir.getAbsolutePath());
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index e7e3e83..15a00d5 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -1935,7 +1935,7 @@
                             final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
                             if (pkgSetting.getInstallReason(userId)
                                     != PackageManager.INSTALL_REASON_DEVICE_RESTORE) {
-                                setDefaultBrowserPackageName(null, userId);
+                                setDefaultBrowserAsyncLPw(null, userId);
                             }
                         }
 
@@ -3101,7 +3101,7 @@
                 }
             }
 
-            mApexManager = new ApexManager();
+            mApexManager = new ApexManager(context);
             mInstallerService = new PackageInstallerService(context, this, mApexManager);
             final Pair<ComponentName, String> instantAppResolverComponent =
                     getInstantAppResolverLPr();
@@ -9404,21 +9404,30 @@
         // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
         // and the first package that uses the library will dexopt it. The
         // others will see that the compiled code for the library is up to date.
-        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
+        Collection<SharedLibraryInfo> deps = findSharedLibraries(p);
         final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
         if (!deps.isEmpty()) {
             DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
                     options.getCompilationReason(), options.getCompilerFilter(),
                     options.getSplitName(),
                     options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
-            for (PackageParser.Package depPackage : deps) {
-                // TODO: Analyze and investigate if we (should) profile libraries.
-                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
-                        getOrCreateCompilerPackageStats(depPackage),
-                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
+            for (SharedLibraryInfo info : deps) {
+                PackageParser.Package depPackage = null;
+                synchronized (mPackages) {
+                    depPackage = mPackages.get(info.getPackageName());
+                }
+                if (depPackage != null) {
+                    // TODO: Analyze and investigate if we (should) profile libraries.
+                    pdo.performDexOpt(depPackage, instructionSets,
+                            getOrCreateCompilerPackageStats(depPackage),
+                            mDexManager.getPackageUseInfoOrDefault(depPackage.packageName),
+                            libraryOptions);
+                } else {
+                    pdo.performDexOpt(info, instructionSets, libraryOptions);
+                }
             }
         }
-        return pdo.performDexOpt(p, p.usesLibraryInfos, instructionSets,
+        return pdo.performDexOpt(p, instructionSets,
                 getOrCreateCompilerPackageStats(p),
                 mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
     }
@@ -9461,63 +9470,48 @@
         }
     }
 
-    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
-        if (p.usesLibraries != null || p.usesOptionalLibraries != null
-                || p.usesStaticLibraries != null) {
-            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
+    private static List<SharedLibraryInfo> findSharedLibraries(PackageParser.Package p) {
+        if (p.usesLibraryInfos != null) {
+            ArrayList<SharedLibraryInfo> retValue = new ArrayList<>();
             Set<String> collectedNames = new HashSet<>();
-            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
-
-            retValue.remove(p);
-
+            for (SharedLibraryInfo info : p.usesLibraryInfos) {
+                findSharedLibrariesRecursive(info, retValue, collectedNames);
+            }
             return retValue;
         } else {
             return Collections.emptyList();
         }
     }
 
-    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
-            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
-        if (!collectedNames.contains(p.packageName)) {
-            collectedNames.add(p.packageName);
-            collected.add(p);
+    private static void findSharedLibrariesRecursive(SharedLibraryInfo info,
+            ArrayList<SharedLibraryInfo> collected, Set<String> collectedNames) {
+        if (!collectedNames.contains(info.getName())) {
+            collectedNames.add(info.getName());
+            collected.add(info);
 
-            if (p.usesLibraries != null) {
-                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
-                        null, collected, collectedNames);
-            }
-            if (p.usesOptionalLibraries != null) {
-                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
-                        null, collected, collectedNames);
-            }
-            if (p.usesStaticLibraries != null) {
-                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
-                        p.usesStaticLibrariesVersions, collected, collectedNames);
+            if (info.getDependencies() != null) {
+                for (SharedLibraryInfo dep : info.getDependencies()) {
+                    findSharedLibrariesRecursive(dep, collected, collectedNames);
+                }
             }
         }
     }
 
-    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
-            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
-        final int libNameCount = libs.size();
-        for (int i = 0; i < libNameCount; i++) {
-            String libName = libs.get(i);
-            long version = (versions != null && versions.length == libNameCount)
-                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
-            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
-            if (libPkg != null) {
-                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
+    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package pkg) {
+        List<SharedLibraryInfo> deps = findSharedLibraries(pkg);
+        if (!deps.isEmpty()) {
+            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
+            synchronized (mPackages) {
+                for (SharedLibraryInfo info : deps) {
+                    PackageParser.Package depPackage = mPackages.get(info.getPackageName());
+                    if (depPackage != null) {
+                        retValue.add(depPackage);
+                    }
+                }
             }
-        }
-    }
-
-    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
-        synchronized (mPackages) {
-            SharedLibraryInfo libraryInfo = getSharedLibraryInfoLPr(name, version);
-            if (libraryInfo != null) {
-                return mPackages.get(libraryInfo.getPackageName());
-            }
-            return null;
+            return retValue;
+        } else {
+            return Collections.emptyList();
         }
     }
 
@@ -13687,6 +13681,23 @@
         return true;
     }
 
+    private void setDefaultBrowserAsyncLPw(@Nullable String packageName, @UserIdInt int userId) {
+        if (userId == UserHandle.USER_ALL) {
+            return;
+        }
+        if (mDefaultBrowserProvider == null) {
+            Slog.e(TAG, "mDefaultBrowserProvider is null");
+            return;
+        }
+        mDefaultBrowserProvider.setDefaultBrowserAsync(packageName, userId);
+        if (packageName != null) {
+            synchronized (mPackages) {
+                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(packageName,
+                        userId);
+            }
+        }
+    }
+
     @Override
     public String getDefaultBrowserPackageName(int userId) {
         if (UserHandle.getCallingUserId() != userId) {
@@ -14346,27 +14357,8 @@
                 }
 
                 if (dataOwnerPkg != null) {
-                    // If installed, the package will get access to data left on the device by its
-                    // predecessor. As a security measure, this is permited only if this is not a
-                    // version downgrade or if the predecessor package is marked as debuggable and
-                    // a downgrade is explicitly requested.
-                    //
-                    // On debuggable platform builds, downgrades are permitted even for
-                    // non-debuggable packages to make testing easier. Debuggable platform builds do
-                    // not offer security guarantees and thus it's OK to disable some security
-                    // mechanisms to make debugging/testing easier on those builds. However, even on
-                    // debuggable builds downgrades of packages are permitted only if requested via
-                    // installFlags. This is because we aim to keep the behavior of debuggable
-                    // platform builds as close as possible to the behavior of non-debuggable
-                    // platform builds.
-                    final boolean downgradeRequested =
-                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
-                    final boolean packageDebuggable =
-                                (dataOwnerPkg.applicationInfo.flags
-                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
-                    final boolean downgradePermitted =
-                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
-                    if (!downgradePermitted) {
+                    if (!PackageManagerServiceUtils.isDowngradePermitted(installFlags,
+                            dataOwnerPkg.applicationInfo.flags)) {
                         try {
                             checkDowngrade(dataOwnerPkg, pkgLite);
                         } catch (PackageManagerException e) {
@@ -16324,7 +16316,7 @@
                         REASON_INSTALL,
                         DexoptOptions.DEXOPT_BOOT_COMPLETE
                                 | DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
-                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryInfos,
+                mPackageDexOptimizer.performDexOpt(pkg,
                         null /* instructionSets */,
                         getOrCreateCompilerPackageStats(pkg),
                         mDexManager.getPackageUseInfoOrDefault(packageName),
@@ -20706,6 +20698,7 @@
         storage.registerListener(mStorageListener);
 
         mInstallerService.systemReady();
+        mApexManager.systemReady();
         mPackageDexOptimizer.systemReady();
 
         getStorageManagerInternal().addExternalStoragePolicy(
@@ -23118,6 +23111,18 @@
             }
             return 0;
         }
+
+        @Override
+        public boolean[] isAudioPlaybackCaptureAllowed(String[] packageNames)
+                throws RemoteException {
+            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
+            boolean[] results = new boolean[packageNames.length];
+            for (int i = results.length - 1; i >= 0; --i) {
+                ApplicationInfo appInfo = getApplicationInfo(packageNames[i], 0, callingUser);
+                results[i] = appInfo == null ? false : appInfo.isAudioPlaybackCaptureAllowed();
+            }
+            return results;
+        }
     }
 
     private class PackageManagerInternalImpl extends PackageManagerInternal {
diff --git a/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java b/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
index 6134d30..3218c86 100644
--- a/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
+++ b/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
@@ -32,6 +32,7 @@
 import android.app.AppGlobals;
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageInfoLite;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageParser;
@@ -796,6 +797,36 @@
     }
 
     /**
+     * Checks whenever downgrade of an app is permitted.
+     *
+     * @param installFlags flags of the current install.
+     * @param applicationFlags flags of the currently installed version of the app.
+     * @return {@code true} if downgrade is permitted according to the {@code installFlags} and
+     *         {@code applicationFlags}.
+     */
+    public static boolean isDowngradePermitted(int installFlags, int applicationFlags) {
+        // If installed, the package will get access to data left on the device by its
+        // predecessor. As a security measure, this is permited only if this is not a
+        // version downgrade or if the predecessor package is marked as debuggable and
+        // a downgrade is explicitly requested.
+        //
+        // On debuggable platform builds, downgrades are permitted even for
+        // non-debuggable packages to make testing easier. Debuggable platform builds do
+        // not offer security guarantees and thus it's OK to disable some security
+        // mechanisms to make debugging/testing easier on those builds. However, even on
+        // debuggable builds downgrades of packages are permitted only if requested via
+        // installFlags. This is because we aim to keep the behavior of debuggable
+        // platform builds as close as possible to the behavior of non-debuggable
+        // platform builds.
+        final boolean downgradeRequested =
+                (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
+        final boolean packageDebuggable =
+                (applicationFlags
+                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
+        return (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
+    }
+
+    /**
      * Copy package to the target location.
      *
      * @param packagePath absolute path to the package to be copied. Can be
diff --git a/services/core/java/com/android/server/pm/Settings.java b/services/core/java/com/android/server/pm/Settings.java
index 92fe377..59e5d77 100644
--- a/services/core/java/com/android/server/pm/Settings.java
+++ b/services/core/java/com/android/server/pm/Settings.java
@@ -4372,6 +4372,7 @@
             ApplicationInfo.PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE, "PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE",
             ApplicationInfo.PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION, "PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION",
             ApplicationInfo.PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_UNRESIZEABLE, "PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_UNRESIZEABLE",
+            ApplicationInfo.PRIVATE_FLAG_ALLOW_AUDIO_PLAYBACK_CAPTURE, "ALLOW_AUDIO_PLAYBACK_CAPTURE",
             ApplicationInfo.PRIVATE_FLAG_BACKUP_IN_FOREGROUND, "BACKUP_IN_FOREGROUND",
             ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE, "CANT_SAVE_STATE",
             ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE, "DEFAULT_TO_DEVICE_PROTECTED_STORAGE",
diff --git a/services/core/java/com/android/server/pm/ShortcutService.java b/services/core/java/com/android/server/pm/ShortcutService.java
index ff6d7a8..9deea9e 100644
--- a/services/core/java/com/android/server/pm/ShortcutService.java
+++ b/services/core/java/com/android/server/pm/ShortcutService.java
@@ -2173,7 +2173,8 @@
     public boolean hasShareTargets(String packageName, String packageToCheck,
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
-        enforceSystem();
+        enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APP_PREDICTIONS,
+                "hasShareTargets");
 
         synchronized (mLock) {
             throwIfUserLockedL(userId);
diff --git a/services/core/java/com/android/server/pm/StagingManager.java b/services/core/java/com/android/server/pm/StagingManager.java
index a38c836..22a85eb 100644
--- a/services/core/java/com/android/server/pm/StagingManager.java
+++ b/services/core/java/com/android/server/pm/StagingManager.java
@@ -39,6 +39,7 @@
 import android.os.Handler;
 import android.os.IBinder;
 import android.os.ParcelFileDescriptor;
+import android.os.PowerManager;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.util.Slog;
@@ -68,15 +69,18 @@
     private final PackageInstallerService mPi;
     private final PackageManagerService mPm;
     private final ApexManager mApexManager;
+    private final PowerManager mPowerManager;
     private final Handler mBgHandler;
 
     @GuardedBy("mStagedSessions")
     private final SparseArray<PackageInstallerSession> mStagedSessions = new SparseArray<>();
 
-    StagingManager(PackageManagerService pm, PackageInstallerService pi, ApexManager am) {
+    StagingManager(PackageManagerService pm, PackageInstallerService pi, ApexManager am,
+            Context context) {
         mPm = pm;
         mPi = pi;
         mApexManager = am;
+        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
         mBgHandler = BackgroundThread.getHandler();
     }
 
@@ -140,12 +144,40 @@
     private boolean submitSessionToApexService(@NonNull PackageInstallerSession session,
                                                List<PackageInstallerSession> childSessions,
                                                ApexInfoList apexInfoList) {
-        return mApexManager.submitStagedSession(
+        boolean submittedToApexd = mApexManager.submitStagedSession(
                 session.sessionId,
                 childSessions != null
                         ? childSessions.stream().mapToInt(s -> s.sessionId).toArray() :
                         new int[]{},
                 apexInfoList);
+        if (!submittedToApexd) {
+            session.setStagedSessionFailed(
+                    SessionInfo.STAGED_SESSION_VERIFICATION_FAILED,
+                    "APEX staging failed, check logcat messages from apexd for more details.");
+            return false;
+        }
+        for (ApexInfo newPackage : apexInfoList.apexInfos) {
+            PackageInfo activePackage = mApexManager.getActivePackage(newPackage.packageName);
+            if (activePackage == null) {
+                continue;
+            }
+            long activeVersion = activePackage.applicationInfo.longVersionCode;
+            boolean allowsDowngrade = PackageManagerServiceUtils.isDowngradePermitted(
+                    session.params.installFlags, activePackage.applicationInfo.flags);
+            if (activeVersion > newPackage.versionCode && !allowsDowngrade) {
+                session.setStagedSessionFailed(
+                        SessionInfo.STAGED_SESSION_VERIFICATION_FAILED,
+                        "Downgrade of APEX package " + newPackage.packageName
+                                + " is not allowed. Active version: " + activeVersion
+                                + " attempted: " + newPackage.versionCode);
+
+                if (!mApexManager.abortActiveSession()) {
+                    Slog.e(TAG, "Failed to abort apex session " + session.sessionId);
+                }
+                return false;
+            }
+        }
+        return true;
     }
 
     private static boolean isApexSession(@NonNull PackageInstallerSession session) {
@@ -180,9 +212,7 @@
         }
 
         if (!success) {
-            session.setStagedSessionFailed(
-                    SessionInfo.STAGED_SESSION_VERIFICATION_FAILED,
-                    "APEX staging failed, check logcat messages from apexd for more details.");
+            // submitSessionToApexService will populate error.
             return;
         }
 
@@ -257,7 +287,7 @@
                         + "activated");
                 return;
             }
-            if (apexSessionInfo.isActivationFailed || apexSessionInfo.isUnknown) {
+            if (isApexSessionFailed(apexSessionInfo)) {
                 session.setStagedSessionFailed(SessionInfo.STAGED_SESSION_ACTIVATION_FAILED,
                         "APEX activation failed. Check logcat messages from apexd for "
                                 + "more information.");
@@ -286,6 +316,20 @@
             session.setStagedSessionFailed(SessionInfo.STAGED_SESSION_ACTIVATION_FAILED,
                     "Staged installation of APKs failed. Check logcat messages for"
                         + "more information.");
+
+            if (!hasApex) {
+                return;
+            }
+
+            if (!mApexManager.abortActiveSession()) {
+                Slog.e(TAG, "Failed to abort APEXd session");
+            } else {
+                Slog.e(TAG,
+                        "Successfully aborted apexd session. Rebooting device in order to revert "
+                                + "to the previous state of APEXd.");
+                mPowerManager.reboot(null);
+            }
+
             return;
         }
 
@@ -445,11 +489,40 @@
 
     void abortSession(@NonNull PackageInstallerSession session) {
         synchronized (mStagedSessions) {
-            updateStoredSession(session);
             mStagedSessions.remove(session.sessionId);
         }
     }
 
+    void abortCommittedSession(@NonNull PackageInstallerSession session) {
+        if (session.isStagedSessionApplied()) {
+            Slog.w(TAG, "Cannot abort applied session!");
+            return;
+        }
+        if (isStagedSessionFinalized(session.sessionId)) {
+            Slog.w(TAG, "Cannot abort session because it is not active or APEXD is not reachable");
+            return;
+        }
+
+        mApexManager.abortActiveSession();
+
+        abortSession(session);
+    }
+
+    private boolean isStagedSessionFinalized(int sessionId) {
+        ApexSessionInfo session = mApexManager.getStagedSessionInfo(sessionId);
+
+        /* checking if the session is in a final state, i.e., not active anymore */
+        return session.isUnknown || session.isActivationFailed || session.isSuccess
+                || session.isRolledBack;
+    }
+
+    private static boolean isApexSessionFailed(ApexSessionInfo apexSessionInfo) {
+        // isRollbackInProgress is included to cover the scenario, when a device is rebooted in
+        // during the rollback, and apexd fails to resume the rollback after reboot.
+        return apexSessionInfo.isActivationFailed || apexSessionInfo.isUnknown
+                || apexSessionInfo.isRolledBack || apexSessionInfo.isRollbackInProgress;
+    }
+
     @GuardedBy("mStagedSessions")
     private boolean isMultiPackageSessionComplete(@NonNull PackageInstallerSession session) {
         // This method assumes that the argument is either a parent session of a multi-package
diff --git a/services/core/java/com/android/server/pm/dex/DexoptUtils.java b/services/core/java/com/android/server/pm/dex/DexoptUtils.java
index 91ad11e..5a473c1 100644
--- a/services/core/java/com/android/server/pm/dex/DexoptUtils.java
+++ b/services/core/java/com/android/server/pm/dex/DexoptUtils.java
@@ -174,6 +174,18 @@
     }
 
     /**
+     * Creates the class loader context for the given shared library.
+     */
+    public static String getClassLoaderContext(SharedLibraryInfo info) {
+        String sharedLibrariesContext = "";
+        if (info.getDependencies() != null) {
+            sharedLibrariesContext = encodeSharedLibraries(info.getDependencies());
+        }
+        return encodeClassLoader(
+                "", SHARED_LIBRARY_LOADER_TYPE, sharedLibrariesContext);
+    }
+
+    /**
      * Recursive method to generate the class loader context dependencies for the split with the
      * given index. {@param classLoaderContexts} acts as an accumulator. Upton return
      * {@code classLoaderContexts[index]} will contain the split dependency.
diff --git a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
index 93a3d0a..447234e 100644
--- a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
@@ -850,7 +850,7 @@
         }
         for (String packageName : packageNames) {
             grantPermissionsToSystemPackage(packageName, userId,
-                    PHONE_PERMISSIONS, LOCATION_PERMISSIONS, SMS_PERMISSIONS);
+                    PHONE_PERMISSIONS, ALWAYS_LOCATION_PERMISSIONS, SMS_PERMISSIONS);
         }
     }
 
diff --git a/services/core/java/com/android/server/policy/DisplayFoldController.java b/services/core/java/com/android/server/policy/DisplayFoldController.java
index cf026e9..0db3d78 100644
--- a/services/core/java/com/android/server/policy/DisplayFoldController.java
+++ b/services/core/java/com/android/server/policy/DisplayFoldController.java
@@ -35,10 +35,12 @@
 
 /**
  * Controls the behavior of foldable devices whose screen can literally bend and fold.
+ * TODO(b/126160895): Move DisplayFoldController from PhoneWindowManager to DisplayPolicy.
  */
 class DisplayFoldController {
 
     private static final String TAG = "DisplayFoldController";
+
     private final WindowManagerInternal mWindowManagerInternal;
     private final DisplayManagerInternal mDisplayManagerInternal;
     private final int mDisplayId;
@@ -52,6 +54,8 @@
     private final DisplayInfo mNonOverrideDisplayInfo = new DisplayInfo();
     private final RemoteCallbackList<IDisplayFoldListener> mListeners = new RemoteCallbackList<>();
     private Boolean mFolded;
+    private String mFocusedApp;
+    private final DisplayFoldDurationLogger mDurationLogger = new DisplayFoldDurationLogger();
 
     DisplayFoldController(WindowManagerInternal windowManagerInternal,
             DisplayManagerInternal displayManagerInternal, int displayId, Rect foldedArea,
@@ -63,6 +67,14 @@
         mHandler = handler;
     }
 
+    void finishedGoingToSleep() {
+        mDurationLogger.onFinishedGoingToSleep();
+    }
+
+    void finishedWakingUp() {
+        mDurationLogger.onFinishedWakingUp(mFolded);
+    }
+
     void requestDeviceFolded(boolean folded) {
         mHandler.post(() -> setDeviceFolded(folded));
     }
@@ -97,6 +109,8 @@
             mWindowManagerInternal.clearForcedDisplaySize(mDisplayId);
             mDisplayManagerInternal.setDisplayOffsets(mDisplayId, 0, 0);
         }
+        mDurationLogger.setDeviceFolded(folded);
+        mDurationLogger.logFocusedAppWithFoldState(folded, mFocusedApp);
         mFolded = folded;
 
         final int n = mListeners.beginBroadcast();
@@ -167,6 +181,10 @@
         return result;
     }
 
+    void onDefaultDisplayFocusChanged(String pkg) {
+        mFocusedApp = pkg;
+    }
+
     static DisplayFoldController create(Context context, int displayId) {
         final DisplayManagerInternal displayService =
                 LocalServices.getService(DisplayManagerInternal.class);
diff --git a/services/core/java/com/android/server/policy/DisplayFoldDurationLogger.java b/services/core/java/com/android/server/policy/DisplayFoldDurationLogger.java
new file mode 100644
index 0000000..bdcd2cd
--- /dev/null
+++ b/services/core/java/com/android/server/policy/DisplayFoldDurationLogger.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.policy;
+
+import android.annotation.IntDef;
+import android.metrics.LogMaker;
+import android.os.SystemClock;
+
+import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.nano.MetricsProto;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Logger for tracking duration of usage in folded vs unfolded state.
+ */
+class DisplayFoldDurationLogger {
+    static final int SCREEN_STATE_UNKNOWN = -1;
+    static final int SCREEN_STATE_OFF = 0;
+    static final int SCREEN_STATE_ON_UNFOLDED = 1;
+    static final int SCREEN_STATE_ON_FOLDED = 2;
+
+    @IntDef(flag = true, prefix = {"SCREEN_STATE_"}, value = {
+            SCREEN_STATE_UNKNOWN,
+            SCREEN_STATE_OFF,
+            SCREEN_STATE_ON_UNFOLDED,
+            SCREEN_STATE_ON_FOLDED
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface ScreenState {}
+
+    private @ScreenState int mScreenState = SCREEN_STATE_UNKNOWN;
+    private Long mLastChanged = null;
+
+    private static final int LOG_SUBTYPE_UNFOLDED = 0;
+    private static final int LOG_SUBTYPE_FOLDED = 1;
+    private static final int LOG_SUBTYPE_DURATION_MASK = 0x80000000;
+
+    private final MetricsLogger mLogger = new MetricsLogger();
+
+    void onFinishedWakingUp(Boolean folded) {
+        if (folded == null) {
+            mScreenState = SCREEN_STATE_UNKNOWN;
+        } else if (folded) {
+            mScreenState = SCREEN_STATE_ON_FOLDED;
+        } else {
+            mScreenState = SCREEN_STATE_ON_UNFOLDED;
+        }
+        mLastChanged = SystemClock.uptimeMillis();
+    }
+
+    void onFinishedGoingToSleep() {
+        log();
+        mScreenState = SCREEN_STATE_OFF;
+        mLastChanged = null;
+    }
+
+    void setDeviceFolded(boolean folded) {
+        // This function is called even when the screen is in ADO mode, but we're only
+        // interested in the case that the screen is actually on.
+        if (!isOn()) {
+            return;
+        }
+        log();
+        mScreenState = folded ? SCREEN_STATE_ON_FOLDED : SCREEN_STATE_ON_UNFOLDED;
+        mLastChanged = SystemClock.uptimeMillis();
+    }
+
+    void logFocusedAppWithFoldState(boolean folded, String packageName) {
+        mLogger.write(
+                new LogMaker(MetricsProto.MetricsEvent.ACTION_DISPLAY_FOLD)
+                        .setType(MetricsProto.MetricsEvent.TYPE_ACTION)
+                        .setSubtype(folded ? LOG_SUBTYPE_FOLDED : LOG_SUBTYPE_UNFOLDED)
+                        .setPackageName(packageName));
+    }
+
+    private void log() {
+        if (mLastChanged == null) {
+            return;
+        }
+        int subtype;
+        switch (mScreenState) {
+            case SCREEN_STATE_ON_UNFOLDED:
+                subtype = LOG_SUBTYPE_UNFOLDED | LOG_SUBTYPE_DURATION_MASK;
+                break;
+            case SCREEN_STATE_ON_FOLDED:
+                subtype = LOG_SUBTYPE_FOLDED | LOG_SUBTYPE_DURATION_MASK;
+                break;
+            default:
+                return;
+        }
+        mLogger.write(
+                new LogMaker(MetricsProto.MetricsEvent.ACTION_DISPLAY_FOLD)
+                        .setType(MetricsProto.MetricsEvent.TYPE_ACTION)
+                        .setSubtype(subtype)
+                        .setLatency(SystemClock.uptimeMillis() - mLastChanged));
+    }
+
+    private boolean isOn() {
+        return mScreenState == SCREEN_STATE_ON_UNFOLDED || mScreenState == SCREEN_STATE_ON_FOLDED;
+    }
+}
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 0759419..c0e5974 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -3241,6 +3241,14 @@
     }
 
     @Override
+    public void onDefaultDisplayFocusChangedLw(WindowState newFocus) {
+        if (mDisplayFoldController != null) {
+            mDisplayFoldController.onDefaultDisplayFocusChanged(
+                    newFocus != null ? newFocus.getOwningPackage() : null);
+        }
+    }
+
+    @Override
     public void registerShortcutKey(long shortcutCode, IShortcutService shortcutService)
             throws RemoteException {
         synchronized (mLock) {
@@ -4440,6 +4448,9 @@
             mKeyguardDelegate.onFinishedGoingToSleep(why,
                     mCameraGestureTriggeredDuringGoingToSleep);
         }
+        if (mDisplayFoldController != null) {
+            mDisplayFoldController.finishedGoingToSleep();
+        }
         mCameraGestureTriggeredDuringGoingToSleep = false;
     }
 
@@ -4480,6 +4491,9 @@
         if (mKeyguardDelegate != null) {
             mKeyguardDelegate.onFinishedWakingUp();
         }
+        if (mDisplayFoldController != null) {
+            mDisplayFoldController.finishedWakingUp();
+        }
     }
 
     private void wakeUpFromPowerKey(long eventTime) {
diff --git a/services/core/java/com/android/server/policy/WindowManagerPolicy.java b/services/core/java/com/android/server/policy/WindowManagerPolicy.java
index 5cd0014..d58707c 100644
--- a/services/core/java/com/android/server/policy/WindowManagerPolicy.java
+++ b/services/core/java/com/android/server/policy/WindowManagerPolicy.java
@@ -1489,6 +1489,11 @@
     }
 
     /**
+     * A new window on default display has been focused.
+     */
+    default void onDefaultDisplayFocusChangedLw(WindowState newFocus) {}
+
+    /**
      * Updates the flag about whether AOD is showing.
      *
      * @return whether the value was changed.
diff --git a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java
index ae1090c..c408549 100644
--- a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java
+++ b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java
@@ -209,11 +209,8 @@
             mKeyguardState.reset();
             mHandler.post(() -> {
                 try {
-                    // There are no longer any keyguard windows on secondary displays, so pass
-                    // {@code null}. All that means is that showWhenLocked activities on
-                    // external displays now get to show.
                     ActivityTaskManager.getService().setLockScreenShown(true /* keyguardShowing */,
-                            false /* aodShowing */, null /* secondaryDisplaysShowing */);
+                            false /* aodShowing */);
                 } catch (RemoteException e) {
                     // Local call.
                 }
diff --git a/services/core/java/com/android/server/power/AttentionDetector.java b/services/core/java/com/android/server/power/AttentionDetector.java
index 8740256..406cbc1 100644
--- a/services/core/java/com/android/server/power/AttentionDetector.java
+++ b/services/core/java/com/android/server/power/AttentionDetector.java
@@ -19,9 +19,13 @@
 import android.attention.AttentionManagerInternal;
 import android.attention.AttentionManagerInternal.AttentionCallbackInternal;
 import android.content.Context;
+import android.database.ContentObserver;
+import android.os.Handler;
 import android.os.PowerManager;
 import android.os.PowerManagerInternal;
 import android.os.SystemClock;
+import android.os.UserHandle;
+import android.provider.Settings;
 import android.service.attention.AttentionService;
 import android.util.Slog;
 import android.util.StatsLog;
@@ -44,6 +48,8 @@
     private static final String TAG = "AttentionDetector";
     private static final boolean DEBUG = false;
 
+    private boolean mIsSettingEnabled;
+
     /**
      * Invoked whenever user attention is detected.
      */
@@ -128,15 +134,35 @@
         mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE;
     }
 
+    @VisibleForTesting
+    void updateEnabledFromSettings(Context context) {
+        mIsSettingEnabled = Settings.System.getIntForUser(context.getContentResolver(),
+                Settings.System.ADAPTIVE_SLEEP, 0, UserHandle.USER_CURRENT) == 1;
+    }
+
     public void systemReady(Context context) {
+        updateEnabledFromSettings(context);
         mAttentionManager = LocalServices.getService(AttentionManagerInternal.class);
         mMaximumExtensionMillis = context.getResources().getInteger(
                 com.android.internal.R.integer.config_attentionMaximumExtension);
         mMaxAttentionApiTimeoutMillis = context.getResources().getInteger(
                 com.android.internal.R.integer.config_attentionApiTimeout);
+
+        context.getContentResolver().registerContentObserver(Settings.System.getUriFor(
+                Settings.System.ADAPTIVE_SLEEP),
+                false, new ContentObserver(new Handler()) {
+                    @Override
+                    public void onChange(boolean selfChange) {
+                        updateEnabledFromSettings(context);
+                    }
+                }, UserHandle.USER_ALL);
     }
 
     public long updateUserActivity(long nextScreenDimming) {
+        if (!mIsSettingEnabled) {
+            return nextScreenDimming;
+        }
+
         if (!isAttentionServiceSupported()) {
             return nextScreenDimming;
         }
@@ -182,7 +208,7 @@
      * the activity happened.
      *
      * @param eventTime Activity time, in uptime millis.
-     * @param event Activity type as defined in {@link PowerManager}.
+     * @param event     Activity type as defined in {@link PowerManager}.
      * @return 0 when activity was ignored, 1 when handled, -1 when invalid.
      */
     public int onUserActivity(long eventTime, int event) {
diff --git a/services/core/java/com/android/server/power/PowerManagerService.java b/services/core/java/com/android/server/power/PowerManagerService.java
index 176dbbf..bb23bc0 100644
--- a/services/core/java/com/android/server/power/PowerManagerService.java
+++ b/services/core/java/com/android/server/power/PowerManagerService.java
@@ -36,6 +36,7 @@
 import android.database.ContentObserver;
 import android.hardware.SensorManager;
 import android.hardware.SystemSensorManager;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.hardware.display.DisplayManagerInternal;
 import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
 import android.hardware.power.V1_0.PowerHint;
@@ -81,7 +82,6 @@
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.app.IAppOpsService;
 import com.android.internal.app.IBatteryStats;
-import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.internal.os.BackgroundThread;
 import com.android.internal.util.DumpUtils;
 import com.android.server.EventLogTags;
@@ -715,6 +715,15 @@
         NativeWrapper createNativeWrapper() {
             return new NativeWrapper();
         }
+
+        WirelessChargerDetector createWirelessChargerDetector(
+                SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler) {
+            return new WirelessChargerDetector(sensorManager, suspendBlocker, handler);
+        }
+
+        AmbientDisplayConfiguration createAmbientDisplayConfiguration(Context context) {
+            return new AmbientDisplayConfiguration(context);
+        }
     }
 
     final Constants mConstants;
@@ -747,7 +756,7 @@
         mHandlerThread.start();
         mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
         mConstants = new Constants(mHandler);
-        mAmbientDisplayConfiguration = new AmbientDisplayConfiguration(mContext);
+        mAmbientDisplayConfiguration = mInjector.createAmbientDisplayConfiguration(context);
         mAttentionDetector = new AttentionDetector(this::onUserAttention, mLock);
 
         mBatterySavingStats = new BatterySavingStats(mLock);
@@ -833,7 +842,7 @@
                     mInjector.createSuspendBlocker(this, "PowerManagerService.Broadcasts"),
                     mPolicy);
 
-            mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,
+            mWirelessChargerDetector = mInjector.createWirelessChargerDetector(sensorManager,
                     mInjector.createSuspendBlocker(
                             this, "PowerManagerService.WirelessChargerDetector"),
                     mHandler);
@@ -932,7 +941,8 @@
         mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
     }
 
-    private void readConfigurationLocked() {
+    @VisibleForTesting
+    void readConfigurationLocked() {
         final Resources resources = mContext.getResources();
 
         mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
@@ -3865,7 +3875,8 @@
         return workSource != null ? new WorkSource(workSource) : null;
     }
 
-    private final class BatteryReceiver extends BroadcastReceiver {
+    @VisibleForTesting
+    final class BatteryReceiver extends BroadcastReceiver {
         @Override
         public void onReceive(Context context, Intent intent) {
             synchronized (mLock) {
@@ -3883,7 +3894,8 @@
         }
     }
 
-    private final class UserSwitchedReceiver extends BroadcastReceiver {
+    @VisibleForTesting
+    final class UserSwitchedReceiver extends BroadcastReceiver {
         @Override
         public void onReceive(Context context, Intent intent) {
             synchronized (mLock) {
diff --git a/services/core/java/com/android/server/power/WirelessChargerDetector.java b/services/core/java/com/android/server/power/WirelessChargerDetector.java
index 18e5ce4..e8e9c67 100644
--- a/services/core/java/com/android/server/power/WirelessChargerDetector.java
+++ b/services/core/java/com/android/server/power/WirelessChargerDetector.java
@@ -28,6 +28,8 @@
 import android.util.TimeUtils;
 import android.util.proto.ProtoOutputStream;
 
+import com.android.internal.annotations.VisibleForTesting;
+
 import java.io.PrintWriter;
 
 /**
@@ -70,7 +72,8 @@
  * sensor to detect this case.
  * </p>
  */
-final class WirelessChargerDetector {
+@VisibleForTesting
+public class WirelessChargerDetector {
     private static final String TAG = "WirelessChargerDetector";
     private static final boolean DEBUG = false;
 
diff --git a/services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java b/services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java
index e6fa500..af78995 100644
--- a/services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java
+++ b/services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java
@@ -280,7 +280,7 @@
                 Settings.Global.DYNAMIC_POWER_SAVINGS_DISABLE_THRESHOLD,
                 mDynamicPowerSavingsDefaultDisableThreshold);
         final boolean isStickyAutoDisableEnabled = getGlobalSetting(
-                Settings.Global.LOW_POWER_MODE_STICKY_AUTO_DISABLE_ENABLED, 0) != 0;
+                Settings.Global.LOW_POWER_MODE_STICKY_AUTO_DISABLE_ENABLED, 1) != 0;
         final int stickyAutoDisableThreshold = getGlobalSetting(
                 Settings.Global.LOW_POWER_MODE_STICKY_AUTO_DISABLE_LEVEL, 90);
 
diff --git a/services/core/java/com/android/server/role/RoleManagerService.java b/services/core/java/com/android/server/role/RoleManagerService.java
index 17d3066..f533ad1 100644
--- a/services/core/java/com/android/server/role/RoleManagerService.java
+++ b/services/core/java/com/android/server/role/RoleManagerService.java
@@ -743,6 +743,25 @@
                 return false;
             }
         }
+
+        @Override
+        public void setDefaultBrowserAsync(@Nullable String packageName, @UserIdInt int userId) {
+            IRoleManagerCallback callback = new IRoleManagerCallback.Stub() {
+                @Override
+                public void onSuccess() {}
+                @Override
+                public void onFailure() {
+                    Slog.e(LOG_TAG, "Failed to set default browser: " + packageName);
+                }
+            };
+            if (packageName != null) {
+                getOrCreateControllerService(userId).onAddRoleHolder(RoleManager.ROLE_BROWSER,
+                        packageName, 0, callback);
+            } else {
+                getOrCreateControllerService(userId).onClearRoleHolders(RoleManager.ROLE_BROWSER, 0,
+                        callback);
+            }
+        }
     }
 
     private class DefaultHomeProvider implements PackageManagerInternal.DefaultHomeProvider {
diff --git a/services/core/java/com/android/server/rollback/AppDataRollbackHelper.java b/services/core/java/com/android/server/rollback/AppDataRollbackHelper.java
index e9ccea54..56e1d08 100644
--- a/services/core/java/com/android/server/rollback/AppDataRollbackHelper.java
+++ b/services/core/java/com/android/server/rollback/AppDataRollbackHelper.java
@@ -18,7 +18,6 @@
 
 import android.content.rollback.PackageRollbackInfo;
 import android.content.rollback.PackageRollbackInfo.RestoreInfo;
-import android.content.rollback.RollbackInfo;
 import android.os.storage.StorageManager;
 import android.util.IntArray;
 import android.util.Log;
@@ -30,9 +29,11 @@
 
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 /**
  * Encapsulates the logic for initiating userdata snapshots and rollbacks via installd.
@@ -153,7 +154,7 @@
     }
 
     /**
-     * Computes the list of pending backups for {@code userId} given lists of available rollbacks.
+     * Computes the list of pending backups for {@code userId} given lists of rollbacks.
      * Packages pending backup for the given user are added to {@code pendingBackupPackages} along
      * with their corresponding {@code PackageRollbackInfo}.
      *
@@ -162,11 +163,11 @@
      */
     private static List<RollbackData> computePendingBackups(int userId,
             Map<String, PackageRollbackInfo> pendingBackupPackages,
-            List<RollbackData> availableRollbacks) {
+            List<RollbackData> rollbacks) {
         List<RollbackData> rd = new ArrayList<>();
 
-        for (RollbackData data : availableRollbacks) {
-            for (PackageRollbackInfo info : data.packages) {
+        for (RollbackData data : rollbacks) {
+            for (PackageRollbackInfo info : data.info.getPackages()) {
                 final IntArray pendingBackupUsers = info.getPendingBackups();
                 if (pendingBackupUsers != null) {
                     final int idx = pendingBackupUsers.indexOf(userId);
@@ -183,20 +184,20 @@
     }
 
     /**
-     * Computes the list of pending restores for {@code userId} given lists of recent rollbacks.
+     * Computes the list of pending restores for {@code userId} given lists of rollbacks.
      * Packages pending restore are added to {@code pendingRestores} along with their corresponding
      * {@code PackageRollbackInfo}.
      *
-     * @return the list of {@code RollbackInfo} that has pending restores. Note that some of the
+     * @return the list of {@code RollbackData} that has pending restores. Note that some of the
      *         restores won't be performed, because they might be counteracted by pending backups.
      */
-    private static List<RollbackInfo> computePendingRestores(int userId,
+    private static List<RollbackData> computePendingRestores(int userId,
             Map<String, PackageRollbackInfo> pendingRestorePackages,
-            List<RollbackInfo> recentRollbacks) {
-        List<RollbackInfo> rd = new ArrayList<>();
+            List<RollbackData> rollbacks) {
+        List<RollbackData> rd = new ArrayList<>();
 
-        for (RollbackInfo data : recentRollbacks) {
-            for (PackageRollbackInfo info : data.getPackages()) {
+        for (RollbackData data : rollbacks) {
+            for (PackageRollbackInfo info : data.info.getPackages()) {
                 final RestoreInfo ri = info.getRestoreInfo(userId);
                 if (ri != null) {
                     pendingRestorePackages.put(info.getPackageName(), info);
@@ -215,18 +216,18 @@
      * backups updates corresponding {@code changedRollbackData} with a mapping from {@code userId}
      * to a inode of theirs CE user data snapshot.
      *
-     * @return a list {@code RollbackData} that have been changed and should be stored on disk.
+     * @return the set of {@code RollbackData} that have been changed and should be stored on disk.
      */
-    public List<RollbackData> commitPendingBackupAndRestoreForUser(int userId,
-            List<RollbackData> availableRollbacks, List<RollbackInfo> recentlyExecutedRollbacks) {
+    public Set<RollbackData> commitPendingBackupAndRestoreForUser(int userId,
+            List<RollbackData> rollbacks) {
 
         final Map<String, PackageRollbackInfo> pendingBackupPackages = new HashMap<>();
         final List<RollbackData> pendingBackups = computePendingBackups(userId,
-                pendingBackupPackages, availableRollbacks);
+                pendingBackupPackages, rollbacks);
 
         final Map<String, PackageRollbackInfo> pendingRestorePackages = new HashMap<>();
-        final List<RollbackInfo> pendingRestores = computePendingRestores(userId,
-                pendingRestorePackages, recentlyExecutedRollbacks);
+        final List<RollbackData> pendingRestores = computePendingRestores(userId,
+                pendingRestorePackages, rollbacks);
 
         // First remove unnecessary backups, i.e. when user did not unlock their phone between the
         // request to backup data and the request to restore it.
@@ -246,13 +247,13 @@
 
         if (!pendingBackupPackages.isEmpty()) {
             for (RollbackData data : pendingBackups) {
-                for (PackageRollbackInfo info : data.packages) {
+                for (PackageRollbackInfo info : data.info.getPackages()) {
                     final IntArray pendingBackupUsers = info.getPendingBackups();
                     final int idx = pendingBackupUsers.indexOf(userId);
                     if (idx != -1) {
                         try {
                             long ceSnapshotInode = mInstaller.snapshotAppData(info.getPackageName(),
-                                    userId, data.rollbackId, Installer.FLAG_STORAGE_CE);
+                                    userId, data.info.getRollbackId(), Installer.FLAG_STORAGE_CE);
                             info.putCeSnapshotInode(userId, ceSnapshotInode);
                             pendingBackupUsers.remove(idx);
                         } catch (InstallerException ie) {
@@ -266,13 +267,13 @@
         }
 
         if (!pendingRestorePackages.isEmpty()) {
-            for (RollbackInfo data : pendingRestores) {
-                for (PackageRollbackInfo info : data.getPackages()) {
+            for (RollbackData data : pendingRestores) {
+                for (PackageRollbackInfo info : data.info.getPackages()) {
                     final RestoreInfo ri = info.getRestoreInfo(userId);
                     if (ri != null) {
                         try {
                             mInstaller.restoreAppDataSnapshot(info.getPackageName(), ri.appId,
-                                    ri.seInfo, userId, data.getRollbackId(),
+                                    ri.seInfo, userId, data.info.getRollbackId(),
                                     Installer.FLAG_STORAGE_CE);
                             info.removeRestoreInfo(ri);
                         } catch (InstallerException ie) {
@@ -284,7 +285,9 @@
             }
         }
 
-        return pendingBackups;
+        final Set<RollbackData> changed = new HashSet<>(pendingBackups);
+        changed.addAll(pendingRestores);
+        return changed;
     }
 
     /**
diff --git a/services/core/java/com/android/server/rollback/RollbackData.java b/services/core/java/com/android/server/rollback/RollbackData.java
index fcd5297..8a95877 100644
--- a/services/core/java/com/android/server/rollback/RollbackData.java
+++ b/services/core/java/com/android/server/rollback/RollbackData.java
@@ -16,27 +16,49 @@
 
 package com.android.server.rollback;
 
-import android.content.rollback.PackageRollbackInfo;
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.content.rollback.RollbackInfo;
 
 import java.io.File;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
 import java.time.Instant;
 import java.util.ArrayList;
-import java.util.List;
 
 /**
  * Information about a rollback available for a set of atomically installed
  * packages.
  */
 class RollbackData {
-    /**
-     * A unique identifier for this rollback.
-     */
-    public final int rollbackId;
+    @IntDef(flag = true, prefix = { "ROLLBACK_STATE_" }, value = {
+            ROLLBACK_STATE_ENABLING,
+            ROLLBACK_STATE_AVAILABLE,
+            ROLLBACK_STATE_COMMITTED,
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    @interface RollbackState {}
 
     /**
-     * The per-package rollback information.
+     * The rollback is in the process of being enabled. It is not yet
+     * available for use.
      */
-    public final List<PackageRollbackInfo> packages = new ArrayList<>();
+    static final int ROLLBACK_STATE_ENABLING = 0;
+
+    /**
+     * The rollback is currently available.
+     */
+    static final int ROLLBACK_STATE_AVAILABLE = 1;
+
+    /**
+     * The rollback has been committed.
+     */
+    static final int ROLLBACK_STATE_COMMITTED = 3;
+
+    /**
+     * The rollback info for this rollback.
+     */
+    public final RollbackInfo info;
 
     /**
      * The directory where the rollback data is stored.
@@ -46,22 +68,23 @@
     /**
      * The time when the upgrade occurred, for purposes of expiring
      * rollback data.
+     *
+     * The timestamp is not applicable for all rollback states, but we make
+     * sure to keep it non-null to avoid potential errors there.
      */
-    public Instant timestamp;
+    public @NonNull Instant timestamp;
 
     /**
      * The session ID for the staged session if this rollback data represents a staged session,
      * {@code -1} otherwise.
      */
-    public int stagedSessionId;
+    public final int stagedSessionId;
 
     /**
-     * A flag to indicate whether the rollback should be considered available
-     * for use. This will always be true for rollbacks of non-staged sessions.
-     * For rollbacks of staged sessions, this is not set to true until after
-     * the staged session has been applied.
+     * The current state of the rollback.
+     * ENABLING, AVAILABLE, or COMMITTED.
      */
-    public boolean isAvailable;
+    public @RollbackState int state;
 
     /**
      * The id of the post-reboot apk session for a staged install, if any.
@@ -69,24 +92,50 @@
     public int apkSessionId = -1;
 
     /**
-     * Whether this Rollback is currently in progress. This field is true from the point
-     * we commit a {@code PackageInstaller} session containing these packages to the point the
-     * {@code PackageInstaller} calls into the {@code onFinished} callback.
+     * True if we are expecting the package manager to call restoreUserData
+     * for this rollback because it has just been committed but the rollback
+     * has not yet been fully applied.
      */
     // NOTE: All accesses to this field are from the RollbackManager handler thread.
-    public boolean inProgress = false;
+    public boolean restoreUserDataInProgress = false;
 
-    RollbackData(int rollbackId, File backupDir, int stagedSessionId, boolean isAvailable) {
-        this.rollbackId = rollbackId;
+    /**
+     * Constructs a new, empty RollbackData instance.
+     *
+     * @param rollbackId the id of the rollback.
+     * @param backupDir the directory where the rollback data is stored.
+     * @param stagedSessionId the session id if this is a staged rollback, -1 otherwise.
+     */
+    RollbackData(int rollbackId, File backupDir, int stagedSessionId) {
+        this.info = new RollbackInfo(rollbackId,
+                /* packages */ new ArrayList<>(),
+                /* isStaged */ stagedSessionId != -1,
+                /* causePackages */ new ArrayList<>(),
+                /* committedSessionId */ -1);
         this.backupDir = backupDir;
         this.stagedSessionId = stagedSessionId;
-        this.isAvailable = isAvailable;
+        this.state = ROLLBACK_STATE_ENABLING;
+        this.timestamp = Instant.now();
+    }
+
+    /**
+     * Constructs a RollbackData instance with full rollback data information.
+     */
+    RollbackData(RollbackInfo info, File backupDir, Instant timestamp, int stagedSessionId,
+            @RollbackState int state, int apkSessionId, boolean restoreUserDataInProgress) {
+        this.info = info;
+        this.backupDir = backupDir;
+        this.timestamp = timestamp;
+        this.stagedSessionId = stagedSessionId;
+        this.state = state;
+        this.apkSessionId = apkSessionId;
+        this.restoreUserDataInProgress = restoreUserDataInProgress;
     }
 
     /**
      * Whether the rollback is for rollback of a staged install.
      */
     public boolean isStaged() {
-        return stagedSessionId != -1;
+        return info.isStaged();
     }
 }
diff --git a/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java b/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
index d2c0ee3..f52f3a3 100644
--- a/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
+++ b/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
@@ -23,6 +23,7 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.IntentSender;
+import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageInstaller;
 import android.content.pm.PackageManager;
@@ -40,6 +41,7 @@
 import android.os.HandlerThread;
 import android.os.ParcelFileDescriptor;
 import android.os.Process;
+import android.os.SystemClock;
 import android.provider.DeviceConfig;
 import android.util.IntArray;
 import android.util.Log;
@@ -47,6 +49,7 @@
 import android.util.SparseLongArray;
 
 import com.android.internal.annotations.GuardedBy;
+import com.android.internal.util.ArrayUtils;
 import com.android.server.LocalServices;
 import com.android.server.pm.Installer;
 
@@ -61,6 +64,7 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Random;
+import java.util.Set;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
 
@@ -72,7 +76,6 @@
     private static final String TAG = "RollbackManager";
 
     // Rollbacks expire after 48 hours.
-    // TODO: How to test rollback expiration works properly?
     private static final long DEFAULT_ROLLBACK_LIFETIME_DURATION_MILLIS =
             TimeUnit.HOURS.toMillis(48);
 
@@ -103,15 +106,10 @@
     @GuardedBy("mLock")
     private final Map<Integer, Integer> mChildSessions = new HashMap<>();
 
-    // Package rollback data available to be used for rolling back a package.
+    // The list of all rollbacks, including available and committed rollbacks.
     // This list is null until the rollback data has been loaded.
     @GuardedBy("mLock")
-    private List<RollbackData> mAvailableRollbacks;
-
-    // The list of recently executed rollbacks.
-    // This list is null until the rollback data has been loaded.
-    @GuardedBy("mLock")
-    private List<RollbackInfo> mRecentlyExecutedRollbacks;
+    private List<RollbackData> mRollbacks;
 
     private final RollbackStore mRollbackStore;
 
@@ -121,6 +119,13 @@
     private final RollbackPackageHealthObserver mPackageHealthObserver;
     private final AppDataRollbackHelper mAppDataRollbackHelper;
 
+    // This field stores the difference in Millis between the uptime (millis since device
+    // has booted) and current time (device wall clock) - it's used to update rollback data
+    // timestamps when the time is changed, by the user or by change of timezone.
+    // No need for guarding with lock because value is only accessed in handler thread.
+    private long  mRelativeBootTime = calculateRelativeBootTime();
+
+
     RollbackManagerServiceImpl(Context context) {
         mContext = context;
         // Note that we're calling onStart here because this object is only constructed on
@@ -166,17 +171,6 @@
             }
         }, filter, null, getHandler());
 
-        // NOTE: A new intent filter is being created here because this broadcast
-        // doesn't use a data scheme ("package") like above.
-        IntentFilter sessionUpdatedFilter = new IntentFilter();
-        sessionUpdatedFilter.addAction(PackageInstaller.ACTION_SESSION_UPDATED);
-        mContext.registerReceiver(new BroadcastReceiver() {
-            @Override
-            public void onReceive(Context context, Intent intent) {
-                onStagedSessionUpdated(intent);
-            }
-        }, sessionUpdatedFilter, null, getHandler());
-
         IntentFilter enableRollbackFilter = new IntentFilter();
         enableRollbackFilter.addAction(Intent.ACTION_PACKAGE_ENABLE_ROLLBACK);
         try {
@@ -217,6 +211,8 @@
                 }
             }
         }, enableRollbackFilter, null, getHandler());
+
+        registerTimeChangeReceiver();
     }
 
     @Override
@@ -228,11 +224,10 @@
         synchronized (mLock) {
             ensureRollbackDataLoadedLocked();
             List<RollbackInfo> rollbacks = new ArrayList<>();
-            for (int i = 0; i < mAvailableRollbacks.size(); ++i) {
-                RollbackData data = mAvailableRollbacks.get(i);
-                if (data.isAvailable) {
-                    rollbacks.add(new RollbackInfo(data.rollbackId,
-                                data.packages, data.isStaged()));
+            for (int i = 0; i < mRollbacks.size(); ++i) {
+                RollbackData data = mRollbacks.get(i);
+                if (data.state == RollbackData.ROLLBACK_STATE_AVAILABLE) {
+                    rollbacks.add(data.info);
                 }
             }
             return new ParceledListSlice<>(rollbacks);
@@ -247,7 +242,13 @@
 
         synchronized (mLock) {
             ensureRollbackDataLoadedLocked();
-            List<RollbackInfo> rollbacks = new ArrayList<>(mRecentlyExecutedRollbacks);
+            List<RollbackInfo> rollbacks = new ArrayList<>();
+            for (int i = 0; i < mRollbacks.size(); ++i) {
+                RollbackData data = mRollbacks.get(i);
+                if (data.state == RollbackData.ROLLBACK_STATE_COMMITTED) {
+                    rollbacks.add(data.info);
+                }
+            }
             return new ParceledListSlice<>(rollbacks);
         }
     }
@@ -268,6 +269,36 @@
                     callerPackageName, statusReceiver));
     }
 
+    private void registerTimeChangeReceiver() {
+        final BroadcastReceiver timeChangeIntentReceiver = new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                final long oldRelativeBootTime = mRelativeBootTime;
+                mRelativeBootTime = calculateRelativeBootTime();
+                final long timeDifference = mRelativeBootTime - oldRelativeBootTime;
+
+                synchronized (mLock) {
+                    ensureRollbackDataLoadedLocked();
+
+                    Iterator<RollbackData> iter = mRollbacks.iterator();
+                    while (iter.hasNext()) {
+                        RollbackData data = iter.next();
+                        data.timestamp = data.timestamp.plusMillis(timeDifference);
+                        saveRollbackData(data);
+                    }
+                }
+            }
+        };
+        final IntentFilter filter = new IntentFilter();
+        filter.addAction(Intent.ACTION_TIME_CHANGED);
+        mContext.registerReceiver(timeChangeIntentReceiver, filter,
+                null /* broadcastPermission */, getHandler());
+    }
+
+    private static long calculateRelativeBootTime() {
+        return System.currentTimeMillis() - SystemClock.elapsedRealtime();
+    }
+
     /**
      * Performs the actual work to commit a rollback.
      * The work is done on the current thread. This may be a long running
@@ -278,18 +309,12 @@
         Log.i(TAG, "Initiating rollback");
 
         RollbackData data = getRollbackForId(rollbackId);
-        if (data == null) {
+        if (data == null || data.state != RollbackData.ROLLBACK_STATE_AVAILABLE) {
             sendFailure(statusReceiver, RollbackManager.STATUS_FAILURE_ROLLBACK_UNAVAILABLE,
                     "Rollback unavailable");
             return;
         }
 
-        if (data.inProgress) {
-            sendFailure(statusReceiver, RollbackManager.STATUS_FAILURE_ROLLBACK_UNAVAILABLE,
-                    "Rollback for package is already in progress.");
-            return;
-        }
-
         // Verify the RollbackData is up to date with what's installed on
         // device.
         // TODO: We assume that between now and the time we commit the
@@ -298,7 +323,7 @@
         // rollback racing with a roll-forward fix of a buggy package.
         // Figure out how to ensure we don't commit the rollback if
         // roll forward happens at the same time.
-        for (PackageRollbackInfo info : data.packages) {
+        for (PackageRollbackInfo info : data.info.getPackages()) {
             VersionedPackage installedVersion = getInstalledPackageVersion(info.getPackageName());
             if (installedVersion == null) {
                 // TODO: Test this case
@@ -340,7 +365,7 @@
             int parentSessionId = packageInstaller.createSession(parentParams);
             PackageInstaller.Session parentSession = packageInstaller.openSession(parentSessionId);
 
-            for (PackageRollbackInfo info : data.packages) {
+            for (PackageRollbackInfo info : data.info.getPackages()) {
                 PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
                         PackageInstaller.SessionParams.MODE_FULL_INSTALL);
                 // TODO: We can't get the installerPackageName for apex
@@ -362,20 +387,24 @@
                 int sessionId = packageInstaller.createSession(params);
                 PackageInstaller.Session session = packageInstaller.openSession(sessionId);
 
-                File packageCode = RollbackStore.getPackageCode(data, info.getPackageName());
-                if (packageCode == null) {
+                File[] packageCodePaths = RollbackStore.getPackageCodePaths(
+                        data, info.getPackageName());
+                if (packageCodePaths == null) {
                     sendFailure(statusReceiver, RollbackManager.STATUS_FAILURE,
-                            "Backup copy of package code inaccessible");
+                            "Backup copy of package inaccessible");
                     return;
                 }
 
-                try (ParcelFileDescriptor fd = ParcelFileDescriptor.open(packageCode,
-                        ParcelFileDescriptor.MODE_READ_ONLY)) {
-                    final long token = Binder.clearCallingIdentity();
-                    try {
-                        session.write(packageCode.getName(), 0, packageCode.length(), fd);
-                    } finally {
-                        Binder.restoreCallingIdentity(token);
+                for (File packageCodePath : packageCodePaths) {
+                    try (ParcelFileDescriptor fd = ParcelFileDescriptor.open(packageCodePath,
+                                ParcelFileDescriptor.MODE_READ_ONLY)) {
+                        final long token = Binder.clearCallingIdentity();
+                        try {
+                            session.write(packageCodePath.getName(), 0, packageCodePath.length(),
+                                    fd);
+                        } finally {
+                            Binder.restoreCallingIdentity(token);
+                        }
                     }
                 }
                 parentSession.addChildSessionId(sessionId);
@@ -384,13 +413,25 @@
             final LocalIntentReceiver receiver = new LocalIntentReceiver(
                     (Intent result) -> {
                         getHandler().post(() -> {
-                            // We've now completed the rollback, so we mark it as no longer in
-                            // progress.
-                            data.inProgress = false;
 
                             int status = result.getIntExtra(PackageInstaller.EXTRA_STATUS,
                                     PackageInstaller.STATUS_FAILURE);
                             if (status != PackageInstaller.STATUS_SUCCESS) {
+                                // Committing the rollback failed, but we
+                                // still have all the info we need to try
+                                // rolling back again, so restore the rollback
+                                // state to how it was before we tried
+                                // committing.
+                                // TODO: Should we just kill this rollback if
+                                // commit failed? Why would we expect commit
+                                // not to fail again?
+                                synchronized (mLock) {
+                                    // TODO: Could this cause a rollback to be
+                                    // resurrected if it should otherwise have
+                                    // expired by now?
+                                    data.state = RollbackData.ROLLBACK_STATE_AVAILABLE;
+                                    data.restoreUserDataInProgress = false;
+                                }
                                 sendFailure(statusReceiver, RollbackManager.STATUS_FAILURE_INSTALL,
                                         "Rollback downgrade install failed: "
                                         + result.getStringExtra(
@@ -398,9 +439,19 @@
                                 return;
                             }
 
-                            addRecentlyExecutedRollback(new RollbackInfo(
-                                        data.rollbackId, data.packages, data.isStaged(),
-                                        causePackages, parentSessionId));
+                            synchronized (mLock) {
+                                if (!data.isStaged()) {
+                                    // All calls to restoreUserData should have
+                                    // completed by now for a non-staged install.
+                                    data.restoreUserDataInProgress = false;
+                                }
+
+                                data.info.setCommittedSessionId(parentSessionId);
+                                data.info.getCausePackages().addAll(causePackages);
+                            }
+                            mRollbackStore.deletePackageCodePaths(data);
+                            saveRollbackData(data);
+
                             sendSuccess(statusReceiver);
 
                             Intent broadcast = new Intent(Intent.ACTION_ROLLBACK_COMMITTED);
@@ -414,7 +465,10 @@
                     }
             );
 
-            data.inProgress = true;
+            synchronized (mLock) {
+                data.state = RollbackData.ROLLBACK_STATE_COMMITTED;
+                data.restoreUserDataInProgress = true;
+            }
             parentSession.commit(receiver.getIntentSender());
         } catch (IOException e) {
             Log.e(TAG, "Rollback failed", e);
@@ -431,10 +485,12 @@
                 "reloadPersistedData");
 
         synchronized (mLock) {
-            mAvailableRollbacks = null;
-            mRecentlyExecutedRollbacks = null;
+            mRollbacks = null;
         }
-        getHandler().post(() -> ensureRollbackDataLoaded());
+        getHandler().post(() -> {
+            updateRollbackLifetimeDurationInMillis();
+            ensureRollbackDataLoaded();
+        });
     }
 
     @Override
@@ -442,17 +498,12 @@
         mContext.enforceCallingOrSelfPermission(
                 android.Manifest.permission.MANAGE_ROLLBACKS,
                 "expireRollbackForPackage");
-
-        // TODO: Should this take a package version number in addition to
-        // package name? For now, just remove all rollbacks matching the
-        // package name. This method is only currently used to facilitate
-        // testing anyway.
         synchronized (mLock) {
             ensureRollbackDataLoadedLocked();
-            Iterator<RollbackData> iter = mAvailableRollbacks.iterator();
+            Iterator<RollbackData> iter = mRollbacks.iterator();
             while (iter.hasNext()) {
                 RollbackData data = iter.next();
-                for (PackageRollbackInfo info : data.packages) {
+                for (PackageRollbackInfo info : data.info.getPackages()) {
                     if (info.getPackageName().equals(packageName)) {
                         iter.remove();
                         deleteRollback(data);
@@ -465,28 +516,16 @@
 
     void onUnlockUser(int userId) {
         getHandler().post(() -> {
-            final List<RollbackData> availableRollbacks;
-            final List<RollbackInfo> recentlyExecutedRollbacks;
+            final List<RollbackData> rollbacks;
             synchronized (mLock) {
-                ensureRollbackDataLoadedLocked();
-                availableRollbacks = new ArrayList<>(mAvailableRollbacks);
-                recentlyExecutedRollbacks = new ArrayList<>(mRecentlyExecutedRollbacks);
+                rollbacks = new ArrayList<>(mRollbacks);
             }
 
-            final List<RollbackData> changed =
-                    mAppDataRollbackHelper.commitPendingBackupAndRestoreForUser(userId,
-                            availableRollbacks, recentlyExecutedRollbacks);
+            final Set<RollbackData> changed =
+                    mAppDataRollbackHelper.commitPendingBackupAndRestoreForUser(userId, rollbacks);
 
             for (RollbackData rd : changed) {
-                try {
-                    mRollbackStore.saveAvailableRollback(rd);
-                } catch (IOException ioe) {
-                    Log.e(TAG, "Unable to save rollback info for : " + rd.rollbackId, ioe);
-                }
-            }
-
-            synchronized (mLock) {
-                mRollbackStore.saveRecentlyExecutedRollbacks(mRecentlyExecutedRollbacks);
+                saveRollbackData(rd);
             }
         });
     }
@@ -511,42 +550,55 @@
         scheduleExpiration(0);
 
         getHandler().post(() -> {
-            // Check to see if any staged sessions with rollback enabled have
-            // been applied.
-            List<RollbackData> staged = new ArrayList<>();
+            // Check to see if any rollback-enabled staged sessions or staged
+            // rollback sessions been applied.
+            List<RollbackData> enabling = new ArrayList<>();
+            List<RollbackData> restoreInProgress = new ArrayList<>();
             synchronized (mLock) {
                 ensureRollbackDataLoadedLocked();
-                for (RollbackData data : mAvailableRollbacks) {
-                    if (data.stagedSessionId != -1) {
-                        staged.add(data);
+                for (RollbackData data : mRollbacks) {
+                    if (data.isStaged()) {
+                        if (data.state == RollbackData.ROLLBACK_STATE_ENABLING) {
+                            enabling.add(data);
+                        } else if (data.restoreUserDataInProgress) {
+                            restoreInProgress.add(data);
+                        }
                     }
                 }
             }
 
-            for (RollbackData data : staged) {
+            for (RollbackData data : enabling) {
                 PackageInstaller installer = mContext.getPackageManager().getPackageInstaller();
                 PackageInstaller.SessionInfo session = installer.getSessionInfo(
                         data.stagedSessionId);
+                // TODO: What if session is null?
                 if (session != null) {
                     if (session.isStagedSessionApplied()) {
-                        synchronized (mLock) {
-                            data.isAvailable = true;
-                        }
-                        try {
-                            mRollbackStore.saveAvailableRollback(data);
-                        } catch (IOException ioe) {
-                            Log.e(TAG, "Unable to save rollback info for : "
-                                    + data.rollbackId, ioe);
-                        }
+                        makeRollbackAvailable(data);
                     } else if (session.isStagedSessionFailed()) {
                         // TODO: Do we need to remove this from
-                        // mAvailableRollbacks, or is it okay to leave as
+                        // mRollbacks, or is it okay to leave as
                         // unavailable until the next reboot when it will go
                         // away on its own?
                         deleteRollback(data);
                     }
                 }
             }
+
+            for (RollbackData data : restoreInProgress) {
+                PackageInstaller installer = mContext.getPackageManager().getPackageInstaller();
+                PackageInstaller.SessionInfo session = installer.getSessionInfo(
+                        data.stagedSessionId);
+                // TODO: What if session is null?
+                if (session != null) {
+                    if (session.isStagedSessionApplied() || session.isStagedSessionFailed()) {
+                        synchronized (mLock) {
+                            data.restoreUserDataInProgress = false;
+                        }
+                        saveRollbackData(data);
+                    }
+                }
+            }
         });
     }
 
@@ -563,12 +615,11 @@
 
     /**
      * Load rollback data from storage if it has not already been loaded.
-     * After calling this function, mAvailableRollbacks and
-     * mRecentlyExecutedRollbacks will be non-null.
+     * After calling this function, mRollbacks will be non-null.
      */
     @GuardedBy("mLock")
     private void ensureRollbackDataLoadedLocked() {
-        if (mAvailableRollbacks == null) {
+        if (mRollbacks == null) {
             loadAllRollbackDataLocked();
         }
     }
@@ -581,14 +632,9 @@
      */
     @GuardedBy("mLock")
     private void loadAllRollbackDataLocked() {
-        mAvailableRollbacks = mRollbackStore.loadAvailableRollbacks();
-        for (RollbackData data : mAvailableRollbacks) {
-            mAllocatedRollbackIds.put(data.rollbackId, true);
-        }
-
-        mRecentlyExecutedRollbacks = mRollbackStore.loadRecentlyExecutedRollbacks();
-        for (RollbackInfo info : mRecentlyExecutedRollbacks) {
-            mAllocatedRollbackIds.put(info.getRollbackId(), true);
+        mRollbacks = mRollbackStore.loadAllRollbackData();
+        for (RollbackData data : mRollbacks) {
+            mAllocatedRollbackIds.put(data.info.getRollbackId(), true);
         }
     }
 
@@ -604,17 +650,21 @@
 
         synchronized (mLock) {
             ensureRollbackDataLoadedLocked();
-            Iterator<RollbackData> iter = mAvailableRollbacks.iterator();
+            Iterator<RollbackData> iter = mRollbacks.iterator();
             while (iter.hasNext()) {
                 RollbackData data = iter.next();
-                for (PackageRollbackInfo info : data.packages) {
-                    if (info.getPackageName().equals(packageName)
-                            && !packageVersionsEqual(
-                                        info.getVersionRolledBackFrom(),
-                                        installedVersion)) {
-                        iter.remove();
-                        deleteRollback(data);
-                        break;
+                // TODO: Should we remove rollbacks in the ENABLING state here?
+                if (data.state == RollbackData.ROLLBACK_STATE_AVAILABLE
+                        || data.state == RollbackData.ROLLBACK_STATE_ENABLING) {
+                    for (PackageRollbackInfo info : data.info.getPackages()) {
+                        if (info.getPackageName().equals(packageName)
+                                && !packageVersionsEqual(
+                                    info.getVersionRolledBackFrom(),
+                                    installedVersion)) {
+                            iter.remove();
+                            deleteRollback(data);
+                            break;
+                        }
                     }
                 }
             }
@@ -627,53 +677,6 @@
      */
     private void onPackageFullyRemoved(String packageName) {
         expireRollbackForPackage(packageName);
-
-        synchronized (mLock) {
-            ensureRollbackDataLoadedLocked();
-            Iterator<RollbackInfo> iter = mRecentlyExecutedRollbacks.iterator();
-            boolean changed = false;
-            while (iter.hasNext()) {
-                RollbackInfo rollback = iter.next();
-                for (PackageRollbackInfo info : rollback.getPackages()) {
-                    if (packageName.equals(info.getPackageName())) {
-                        iter.remove();
-                        changed = true;
-                        break;
-                    }
-                }
-            }
-
-            if (changed) {
-                mRollbackStore.saveRecentlyExecutedRollbacks(mRecentlyExecutedRollbacks);
-            }
-        }
-    }
-
-    /**
-     * Records that the given package has been recently rolled back.
-     */
-    private void addRecentlyExecutedRollback(RollbackInfo rollback) {
-        // TODO: if the list of rollbacks gets too big, trim it to only those
-        // that are necessary to keep track of.
-        synchronized (mLock) {
-            ensureRollbackDataLoadedLocked();
-
-            // This should never happen because we can't have any pending backups left after
-            // a rollback has been executed. See AppDataRollbackHelper#restoreAppData where we
-            // clear all pending backups at the point of restore because they're guaranteed to be
-            // no-ops.
-            //
-            // We may, however, have one or more pending restores left to handle.
-            for (PackageRollbackInfo target : rollback.getPackages()) {
-                if (target.getPendingBackups().size() > 0) {
-                    Log.e(TAG, "No backups allowed to be pending for: " + target);
-                    target.getPendingBackups().clear();
-                }
-            }
-
-            mRecentlyExecutedRollbacks.add(rollback);
-            mRollbackStore.saveRecentlyExecutedRollbacks(mRecentlyExecutedRollbacks);
-        }
     }
 
     /**
@@ -710,17 +713,16 @@
 
     // Check to see if anything needs expiration, and if so, expire it.
     // Schedules future expiration as appropriate.
-    // TODO: Handle cases where the user changes time on the device.
     private void runExpiration() {
         Instant now = Instant.now();
         Instant oldest = null;
         synchronized (mLock) {
             ensureRollbackDataLoadedLocked();
 
-            Iterator<RollbackData> iter = mAvailableRollbacks.iterator();
+            Iterator<RollbackData> iter = mRollbacks.iterator();
             while (iter.hasNext()) {
                 RollbackData data = iter.next();
-                if (!data.isAvailable) {
+                if (data.state != RollbackData.ROLLBACK_STATE_AVAILABLE) {
                     continue;
                 }
                 if (!now.isBefore(data.timestamp.plusMillis(mRollbackLifetimeDurationInMillis))) {
@@ -818,8 +820,8 @@
         RollbackData rd = null;
         synchronized (mLock) {
             ensureRollbackDataLoadedLocked();
-            for (int i = 0; i < mAvailableRollbacks.size(); ++i) {
-                RollbackData data = mAvailableRollbacks.get(i);
+            for (int i = 0; i < mRollbacks.size(); ++i) {
+                RollbackData data = mRollbacks.get(i);
                 if (data.apkSessionId == parentSessionId) {
                     rd = data;
                     break;
@@ -839,19 +841,11 @@
                 return false;
             }
             String packageName = newPackage.packageName;
-            for (PackageRollbackInfo info : rd.packages) {
+            for (PackageRollbackInfo info : rd.info.getPackages()) {
                 if (info.getPackageName().equals(packageName)) {
                     info.getInstalledUsers().addAll(IntArray.wrap(installedUsers));
-                    mAppDataRollbackHelper.snapshotAppData(rd.rollbackId, info);
-                    try {
-                        mRollbackStore.saveAvailableRollback(rd);
-                    } catch (IOException ioe) {
-                        // TODO: Hopefully this is okay because we will try
-                        // again to save the rollback when the staged session
-                        // is applied. Just so long as the device doesn't
-                        // reboot before then.
-                        Log.e(TAG, "Unable to save rollback info for : " + rd.rollbackId, ioe);
-                    }
+                    mAppDataRollbackHelper.snapshotAppData(rd.info.getRollbackId(), info);
+                    saveRollbackData(rd);
                     return true;
                 }
             }
@@ -931,14 +925,13 @@
                 if (data == null) {
                     int rollbackId = allocateRollbackIdLocked();
                     if (session.isStaged()) {
-                        data = mRollbackStore.createPendingStagedRollback(rollbackId,
-                            parentSessionId);
+                        data = mRollbackStore.createStagedRollback(rollbackId, parentSessionId);
                     } else {
-                        data = mRollbackStore.createAvailableRollback(rollbackId);
+                        data = mRollbackStore.createNonStagedRollback(rollbackId);
                     }
                     mPendingRollbacks.put(parentSessionId, data);
                 }
-                data.packages.add(info);
+                data.info.getPackages().add(info);
             }
         } catch (IOException e) {
             Log.e(TAG, "Unable to create rollback for " + packageName, e);
@@ -946,11 +939,17 @@
         }
 
         if (snapshotUserData && !isApex) {
-            mAppDataRollbackHelper.snapshotAppData(data.rollbackId, info);
+            mAppDataRollbackHelper.snapshotAppData(data.info.getRollbackId(), info);
         }
 
         try {
-            RollbackStore.backupPackageCode(data, packageName, pkgInfo.applicationInfo.sourceDir);
+            ApplicationInfo appInfo = pkgInfo.applicationInfo;
+            RollbackStore.backupPackageCodePath(data, packageName, appInfo.sourceDir);
+            if (!ArrayUtils.isEmpty(appInfo.splitSourceDirs)) {
+                for (String sourceDir : appInfo.splitSourceDirs) {
+                    RollbackStore.backupPackageCodePath(data, packageName, sourceDir);
+                }
+            }
         } catch (IOException e) {
             Log.e(TAG, "Unable to copy package for rollback for " + packageName, e);
             return false;
@@ -975,32 +974,33 @@
 
     private void restoreUserDataInternal(String packageName, int[] userIds, int appId,
             long ceDataInode, String seInfo, int token) {
-        final RollbackData rollbackData = getRollbackForPackage(packageName);
+        PackageRollbackInfo info = null;
+        RollbackData rollbackData = null;
+        synchronized (mLock) {
+            ensureRollbackDataLoadedLocked();
+            for (int i = 0; i < mRollbacks.size(); ++i) {
+                RollbackData data = mRollbacks.get(i);
+                if (data.restoreUserDataInProgress) {
+                    info = getPackageRollbackInfo(data, packageName);
+                    if (info != null) {
+                        rollbackData = data;
+                        break;
+                    }
+                }
+            }
+        }
+
         if (rollbackData == null) {
             return;
         }
 
-        if (!rollbackData.inProgress) {
-            Log.e(TAG, "Request to restore userData for: " + packageName
-                    + ", but no rollback in progress.");
-            return;
-        }
-
         for (int userId : userIds) {
-            final PackageRollbackInfo info = getPackageRollbackInfo(rollbackData, packageName);
             final boolean changedRollbackData = mAppDataRollbackHelper.restoreAppData(
-                    rollbackData.rollbackId, info, userId, appId, seInfo);
+                    rollbackData.info.getRollbackId(), info, userId, appId, seInfo);
 
             // We've updated metadata about this rollback, so save it to flash.
             if (changedRollbackData) {
-                try {
-                    mRollbackStore.saveAvailableRollback(rollbackData);
-                } catch (IOException ioe) {
-                    // TODO(narayan): What is the right thing to do here ? This isn't a fatal
-                    // error, since it will only result in us trying to restore data again,
-                    // which will be a no-op if there's no data available.
-                    Log.e(TAG, "Unable to save available rollback: " + packageName, ioe);
-                }
+                saveRollbackData(rollbackData);
             }
         }
     }
@@ -1044,6 +1044,7 @@
                 }
             }
 
+            completeEnableRollback(sessionId, true);
             result.offer(true);
         });
 
@@ -1061,8 +1062,8 @@
             RollbackData rd = null;
             synchronized (mLock) {
                 ensureRollbackDataLoadedLocked();
-                for (int i = 0; i < mAvailableRollbacks.size(); ++i) {
-                    RollbackData data = mAvailableRollbacks.get(i);
+                for (int i = 0; i < mRollbacks.size(); ++i) {
+                    RollbackData data = mRollbacks.get(i);
                     if (data.stagedSessionId == originalSessionId) {
                         data.apkSessionId = apkSessionId;
                         rd = data;
@@ -1072,11 +1073,7 @@
             }
 
             if (rd != null) {
-                try {
-                    mRollbackStore.saveAvailableRollback(rd);
-                } catch (IOException ioe) {
-                    Log.e(TAG, "Unable to save rollback info for : " + rd.rollbackId, ioe);
-                }
+                saveRollbackData(rd);
             }
         });
     }
@@ -1118,21 +1115,21 @@
 
         @Override
         public void onFinished(int sessionId, boolean success) {
-            // If sessionId refers to a staged session, we can't deal with it here since the
-            // session might take an unbounded amount of time to become "ready" after the package
-            // installer session is committed. In those cases, we respond to it in response to
-            // a session ready broadcast.
-            PackageInstaller packageInstaller = mContext.getPackageManager().getPackageInstaller();
-            PackageInstaller.SessionInfo si = packageInstaller.getSessionInfo(sessionId);
-            if (si != null && si.isStaged()) {
-                return;
+            RollbackData rollback = completeEnableRollback(sessionId, success);
+            if (rollback != null && !rollback.isStaged()) {
+                makeRollbackAvailable(rollback);
             }
-
-            completeEnableRollback(sessionId, success);
         }
     }
 
-    private void completeEnableRollback(int sessionId, boolean success) {
+    /**
+     * Add a rollback to the list of rollbacks.
+     * This should be called after rollback has been enabled for all packages
+     * in the rollback. It does not make the rollback available yet.
+     *
+     * @return the rollback data for a successfully enable-completed rollback.
+     */
+    private RollbackData completeEnableRollback(int sessionId, boolean success) {
         RollbackData data = null;
         synchronized (mLock) {
             Integer parentSessionId = mChildSessions.remove(sessionId);
@@ -1143,107 +1140,71 @@
             data = mPendingRollbacks.remove(sessionId);
         }
 
-        if (data != null) {
-            if (success) {
-                try {
-                    data.timestamp = Instant.now();
-
-                    mRollbackStore.saveAvailableRollback(data);
-                    synchronized (mLock) {
-                        // Note: There is a small window of time between when
-                        // the session has been committed by the package
-                        // manager and when we make the rollback available
-                        // here. Presumably the window is small enough that
-                        // nobody will want to roll back the newly installed
-                        // package before we make the rollback available.
-                        // TODO: We'll lose the rollback data if the
-                        // device reboots between when the session is
-                        // committed and this point. Revisit this after
-                        // adding support for rollback of staged installs.
-                        ensureRollbackDataLoadedLocked();
-                        mAvailableRollbacks.add(data);
-                    }
-                    // TODO(zezeozue): Provide API to explicitly start observing instead
-                    // of doing this for all rollbacks. If we do this for all rollbacks,
-                    // should document in PackageInstaller.SessionParams#setEnableRollback
-                    // After enabling and commiting any rollback, observe packages and
-                    // prepare to rollback if packages crashes too frequently.
-                    List<String> packages = new ArrayList<>();
-                    for (int i = 0; i < data.packages.size(); i++) {
-                        packages.add(data.packages.get(i).getPackageName());
-                    }
-                    mPackageHealthObserver.startObservingHealth(packages,
-                            mRollbackLifetimeDurationInMillis);
-                    scheduleExpiration(mRollbackLifetimeDurationInMillis);
-                } catch (IOException e) {
-                    Log.e(TAG, "Unable to enable rollback", e);
-                    deleteRollback(data);
-                }
-            } else {
-                // The install session was aborted, clean up the pending
-                // install.
-                deleteRollback(data);
-            }
-        }
-    }
-
-    private void onStagedSessionUpdated(Intent intent) {
-        PackageInstaller.SessionInfo pi = intent.getParcelableExtra(PackageInstaller.EXTRA_SESSION);
-        if (pi == null) {
-            Log.e(TAG, "Missing intent extra: " + PackageInstaller.EXTRA_SESSION);
-            return;
+        if (data == null) {
+            return null;
         }
 
-        if (pi.isStaged()) {
-            if (!pi.isStagedSessionFailed()) {
-                // TODO: The session really isn't "enabled" at this point, since more work might
-                // be required post reboot.
-                // TODO: We need to make this case consistent with the call from onFinished.
-                //  Ideally, we'd call completeEnableRollback excatly once per multi-package session
-                //  with the parentSessionId only.
-                completeEnableRollback(pi.sessionId, pi.isStagedSessionReady());
-            } else {
-                // TODO: Clean up the saved rollback when the session fails. This may need to be
-                // unified with the case where things fail post reboot.
-            }
-        } else {
-            Log.e(TAG, "Received onStagedSessionUpdated for: " + pi.sessionId
-                    + ", which isn't staged");
+        if (!success) {
+            // The install session was aborted, clean up the pending install.
+            deleteRollback(data);
+            return null;
         }
-    }
 
-    /*
-     * Returns the RollbackData, if any, for an available rollback that would
-     * roll back the given package. Note: This assumes we have at most one
-     * available rollback for a given package at any one time.
-     */
-    private RollbackData getRollbackForPackage(String packageName) {
+        saveRollbackData(data);
         synchronized (mLock) {
-            // TODO: Have ensureRollbackDataLoadedLocked return the list of
-            // available rollbacks, to hopefully avoid forgetting to call it?
+            // Note: There is a small window of time between when
+            // the session has been committed by the package
+            // manager and when we make the rollback available
+            // here. Presumably the window is small enough that
+            // nobody will want to roll back the newly installed
+            // package before we make the rollback available.
+            // TODO: We'll lose the rollback data if the
+            // device reboots between when the session is
+            // committed and this point. Revisit this after
+            // adding support for rollback of staged installs.
             ensureRollbackDataLoadedLocked();
-            for (int i = 0; i < mAvailableRollbacks.size(); ++i) {
-                RollbackData data = mAvailableRollbacks.get(i);
-                if (data.isAvailable && getPackageRollbackInfo(data, packageName) != null) {
-                    return data;
-                }
-            }
+            mRollbacks.add(data);
         }
-        return null;
+
+        return data;
+    }
+
+    private void makeRollbackAvailable(RollbackData data) {
+        // TODO: What if the rollback has since been expired, for example due
+        // to a new package being installed. Won't this revive an expired
+        // rollback? Consider adding a ROLLBACK_STATE_EXPIRED to address this.
+        synchronized (mLock) {
+            data.state = RollbackData.ROLLBACK_STATE_AVAILABLE;
+            data.timestamp = Instant.now();
+        }
+        saveRollbackData(data);
+
+        // TODO(zezeozue): Provide API to explicitly start observing instead
+        // of doing this for all rollbacks. If we do this for all rollbacks,
+        // should document in PackageInstaller.SessionParams#setEnableRollback
+        // After enabling and commiting any rollback, observe packages and
+        // prepare to rollback if packages crashes too frequently.
+        List<String> packages = new ArrayList<>();
+        for (int i = 0; i < data.info.getPackages().size(); i++) {
+            packages.add(data.info.getPackages().get(i).getPackageName());
+        }
+        mPackageHealthObserver.startObservingHealth(packages,
+                mRollbackLifetimeDurationInMillis);
+        scheduleExpiration(mRollbackLifetimeDurationInMillis);
     }
 
     /*
-     * Returns the RollbackData, if any, for an available rollback with the
-     * given rollbackId.
+     * Returns the RollbackData, if any, for a rollback with the given
+     * rollbackId.
      */
     private RollbackData getRollbackForId(int rollbackId) {
         synchronized (mLock) {
             // TODO: Have ensureRollbackDataLoadedLocked return the list of
             // available rollbacks, to hopefully avoid forgetting to call it?
             ensureRollbackDataLoadedLocked();
-            for (int i = 0; i < mAvailableRollbacks.size(); ++i) {
-                RollbackData data = mAvailableRollbacks.get(i);
-                if (data.isAvailable && data.rollbackId == rollbackId) {
+            for (int i = 0; i < mRollbacks.size(); ++i) {
+                RollbackData data = mRollbacks.get(i);
+                if (data.info.getRollbackId() == rollbackId) {
                     return data;
                 }
             }
@@ -1258,7 +1219,7 @@
      */
     private static PackageRollbackInfo getPackageRollbackInfo(RollbackData data,
             String packageName) {
-        for (PackageRollbackInfo info : data.packages) {
+        for (PackageRollbackInfo info : data.info.getPackages()) {
             if (info.getPackageName().equals(packageName)) {
                 return info;
             }
@@ -1283,14 +1244,29 @@
     }
 
     private void deleteRollback(RollbackData rollbackData) {
-        for (PackageRollbackInfo info : rollbackData.packages) {
+        for (PackageRollbackInfo info : rollbackData.info.getPackages()) {
             IntArray installedUsers = info.getInstalledUsers();
             for (int i = 0; i < installedUsers.size(); i++) {
                 int userId = installedUsers.get(i);
-                mAppDataRollbackHelper.destroyAppDataSnapshot(rollbackData.rollbackId, info,
-                        userId);
+                mAppDataRollbackHelper.destroyAppDataSnapshot(rollbackData.info.getRollbackId(),
+                        info, userId);
             }
         }
-        mRollbackStore.deleteAvailableRollback(rollbackData);
+        mRollbackStore.deleteRollbackData(rollbackData);
+    }
+
+    /**
+     * Saves rollback data, swallowing any IOExceptions.
+     * For those times when it's not obvious what to do about the IOException.
+     * TODO: Double check we can't do a better job handling the IOException in
+     * a cases where this method is called.
+     */
+    private void saveRollbackData(RollbackData rollbackData) {
+        try {
+            mRollbackStore.saveRollbackData(rollbackData);
+        } catch (IOException ioe) {
+            Log.e(TAG, "Unable to save rollback info for: "
+                    + rollbackData.info.getRollbackId(), ioe);
+        }
     }
 }
diff --git a/services/core/java/com/android/server/rollback/RollbackStore.java b/services/core/java/com/android/server/rollback/RollbackStore.java
index be904ea..4f8f685 100644
--- a/services/core/java/com/android/server/rollback/RollbackStore.java
+++ b/services/core/java/com/android/server/rollback/RollbackStore.java
@@ -35,6 +35,7 @@
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.nio.file.Files;
+import java.text.ParseException;
 import java.time.Instant;
 import java.time.format.DateTimeParseException;
 import java.util.ArrayList;
@@ -47,60 +48,44 @@
     private static final String TAG = "RollbackManager";
 
     // Assuming the rollback data directory is /data/rollback, we use the
-    // following directory structure to store persisted data for available and
-    // recently executed rollbacks:
+    // following directory structure to store persisted data for rollbacks:
     //   /data/rollback/
-    //      available/
-    //          XXX/
-    //              rollback.json
-    //              com.package.A/
-    //                  base.apk
-    //              com.package.B/
-    //                  base.apk
-    //          YYY/
-    //              rollback.json
-    //              com.package.C/
-    //                  base.apk
-    //      recently_executed.json
+    //       XXX/
+    //           rollback.json
+    //           com.package.A/
+    //               base.apk
+    //           com.package.B/
+    //               base.apk
+    //       YYY/
+    //           rollback.json
     //
     // * XXX, YYY are the rollbackIds for the corresponding rollbacks.
-    // * rollback.json contains all relevant metadata for the rollback. This
-    //   file is not written until the rollback is made available.
+    // * rollback.json contains all relevant metadata for the rollback.
     //
     // TODO: Use AtomicFile for all the .json files?
     private final File mRollbackDataDir;
-    private final File mAvailableRollbacksDir;
-    private final File mRecentlyExecutedRollbacksFile;
 
     RollbackStore(File rollbackDataDir) {
         mRollbackDataDir = rollbackDataDir;
-        mAvailableRollbacksDir = new File(mRollbackDataDir, "available");
-        mRecentlyExecutedRollbacksFile = new File(mRollbackDataDir, "recently_executed.json");
     }
 
     /**
-     * Reads the list of available rollbacks from persistent storage.
+     * Reads the rollback data from persistent storage.
      */
-    List<RollbackData> loadAvailableRollbacks() {
-        List<RollbackData> availableRollbacks = new ArrayList<>();
-        mAvailableRollbacksDir.mkdirs();
-        for (File rollbackDir : mAvailableRollbacksDir.listFiles()) {
+    List<RollbackData> loadAllRollbackData() {
+        List<RollbackData> rollbacks = new ArrayList<>();
+        mRollbackDataDir.mkdirs();
+        for (File rollbackDir : mRollbackDataDir.listFiles()) {
             if (rollbackDir.isDirectory()) {
                 try {
-                    RollbackData data = loadRollbackData(rollbackDir);
-                    availableRollbacks.add(data);
+                    rollbacks.add(loadRollbackData(rollbackDir));
                 } catch (IOException e) {
-                    // Note: Deleting the rollbackDir here will cause pending
-                    // rollbacks to be deleted. This should only ever happen
-                    // if reloadPersistedData is called while there are
-                    // pending rollbacks. The reloadPersistedData method is
-                    // currently only for testing, so that should be okay.
                     Log.e(TAG, "Unable to read rollback data at " + rollbackDir, e);
                     removeFile(rollbackDir);
                 }
             }
         }
-        return availableRollbacks;
+        return rollbacks;
     }
 
     /**
@@ -183,60 +168,50 @@
         return ceSnapshotInodes;
     }
 
-    /**
-     * Reads the list of recently executed rollbacks from persistent storage.
-     */
-    List<RollbackInfo> loadRecentlyExecutedRollbacks() {
-        List<RollbackInfo> recentlyExecutedRollbacks = new ArrayList<>();
-        if (mRecentlyExecutedRollbacksFile.exists()) {
-            try {
-                // TODO: How to cope with changes to the format of this file from
-                // when RollbackStore is updated in the future?
-                String jsonString = IoUtils.readFileAsString(
-                        mRecentlyExecutedRollbacksFile.getAbsolutePath());
-                JSONObject object = new JSONObject(jsonString);
-                JSONArray array = object.getJSONArray("recentlyExecuted");
-                for (int i = 0; i < array.length(); ++i) {
-                    JSONObject element = array.getJSONObject(i);
-                    int rollbackId = element.getInt("rollbackId");
-                    List<PackageRollbackInfo> packages = packageRollbackInfosFromJson(
-                            element.getJSONArray("packages"));
-                    boolean isStaged = element.getBoolean("isStaged");
-                    List<VersionedPackage> causePackages = versionedPackagesFromJson(
-                            element.getJSONArray("causePackages"));
-                    int committedSessionId = element.getInt("committedSessionId");
-                    RollbackInfo rollback = new RollbackInfo(rollbackId, packages, isStaged,
-                            causePackages, committedSessionId);
-                    recentlyExecutedRollbacks.add(rollback);
-                }
-            } catch (IOException | JSONException e) {
-                // TODO: What to do here? Surely we shouldn't just forget about
-                // everything after the point of exception?
-                Log.e(TAG, "Failed to read recently executed rollbacks", e);
-            }
-        }
+    private static JSONObject rollbackInfoToJson(RollbackInfo rollback) throws JSONException {
+        JSONObject json = new JSONObject();
+        json.put("rollbackId", rollback.getRollbackId());
+        json.put("packages", toJson(rollback.getPackages()));
+        json.put("isStaged", rollback.isStaged());
+        json.put("causePackages", versionedPackagesToJson(rollback.getCausePackages()));
+        json.put("committedSessionId", rollback.getCommittedSessionId());
+        return json;
+    }
 
-        return recentlyExecutedRollbacks;
+    private static RollbackInfo rollbackInfoFromJson(JSONObject json) throws JSONException {
+        return new RollbackInfo(
+                json.getInt("rollbackId"),
+                packageRollbackInfosFromJson(json.getJSONArray("packages")),
+                json.getBoolean("isStaged"),
+                versionedPackagesFromJson(json.getJSONArray("causePackages")),
+                json.getInt("committedSessionId"));
     }
 
     /**
-     * Creates a new RollbackData instance with backupDir assigned.
+     * Creates a new RollbackData instance for a non-staged rollback with
+     * backupDir assigned.
      */
-    RollbackData createAvailableRollback(int rollbackId) throws IOException {
-        File backupDir = new File(mAvailableRollbacksDir, Integer.toString(rollbackId));
-        return new RollbackData(rollbackId, backupDir, -1, true);
+    RollbackData createNonStagedRollback(int rollbackId) throws IOException {
+        File backupDir = new File(mRollbackDataDir, Integer.toString(rollbackId));
+        return new RollbackData(rollbackId, backupDir, -1);
     }
 
-    RollbackData createPendingStagedRollback(int rollbackId, int stagedSessionId)
+    /**
+     * Creates a new RollbackData instance for a staged rollback with
+     * backupDir assigned.
+     */
+    RollbackData createStagedRollback(int rollbackId, int stagedSessionId)
             throws IOException {
-        File backupDir = new File(mAvailableRollbacksDir, Integer.toString(rollbackId));
-        return new RollbackData(rollbackId, backupDir, stagedSessionId, false);
+        File backupDir = new File(mRollbackDataDir, Integer.toString(rollbackId));
+        return new RollbackData(rollbackId, backupDir, stagedSessionId);
     }
 
     /**
-     * Creates a backup copy of the apk or apex for a package.
+     * Creates a backup copy of an apk or apex for a package.
+     * For packages containing splits, this method should be called for each
+     * of the package's split apks in addition to the base apk.
      */
-    static void backupPackageCode(RollbackData data, String packageName, String codePath)
+    static void backupPackageCodePath(RollbackData data, String packageName, String codePath)
             throws IOException {
         File sourceFile = new File(codePath);
         File targetDir = new File(data.backupDir, packageName);
@@ -248,30 +223,41 @@
     }
 
     /**
-     * Returns the apk or apex file backed up for the given package.
-     * Returns null if none found.
+     * Returns the apk or apex files backed up for the given package.
+     * Includes the base apk and any splits. Returns null if none found.
      */
-    static File getPackageCode(RollbackData data, String packageName) {
+    static File[] getPackageCodePaths(RollbackData data, String packageName) {
         File targetDir = new File(data.backupDir, packageName);
         File[] files = targetDir.listFiles();
-        if (files == null || files.length != 1) {
+        if (files == null || files.length == 0) {
             return null;
         }
-        return files[0];
+        return files;
     }
 
     /**
-     * Writes the metadata for an available rollback to persistent storage.
+     * Deletes all backed up apks and apex files associated with the given
+     * rollback.
      */
-    void saveAvailableRollback(RollbackData data) throws IOException {
+    static void deletePackageCodePaths(RollbackData data) {
+        for (PackageRollbackInfo info : data.info.getPackages()) {
+            File targetDir = new File(data.backupDir, info.getPackageName());
+            removeFile(targetDir);
+        }
+    }
+
+    /**
+     * Saves the rollback data to persistent storage.
+     */
+    void saveRollbackData(RollbackData data) throws IOException {
         try {
             JSONObject dataJson = new JSONObject();
-            dataJson.put("rollbackId", data.rollbackId);
-            dataJson.put("packages", toJson(data.packages));
+            dataJson.put("info", rollbackInfoToJson(data.info));
             dataJson.put("timestamp", data.timestamp.toString());
             dataJson.put("stagedSessionId", data.stagedSessionId);
-            dataJson.put("isAvailable", data.isAvailable);
+            dataJson.put("state", rollbackStateToString(data.state));
             dataJson.put("apkSessionId", data.apkSessionId);
+            dataJson.put("restoreUserDataInProgress", data.restoreUserDataInProgress);
 
             PrintWriter pw = new PrintWriter(new File(data.backupDir, "rollback.json"));
             pw.println(dataJson.toString());
@@ -282,80 +268,49 @@
     }
 
     /**
-     * Removes all persistant storage associated with the given available
-     * rollback.
+     * Removes all persistant storage associated with the given rollback data.
      */
-    void deleteAvailableRollback(RollbackData data) {
+    void deleteRollbackData(RollbackData data) {
         removeFile(data.backupDir);
     }
 
     /**
-     * Writes the list of recently executed rollbacks to storage.
-     */
-    void saveRecentlyExecutedRollbacks(List<RollbackInfo> recentlyExecutedRollbacks) {
-        try {
-            JSONObject json = new JSONObject();
-            JSONArray array = new JSONArray();
-            json.put("recentlyExecuted", array);
-
-            for (int i = 0; i < recentlyExecutedRollbacks.size(); ++i) {
-                RollbackInfo rollback = recentlyExecutedRollbacks.get(i);
-                JSONObject element = new JSONObject();
-                element.put("rollbackId", rollback.getRollbackId());
-                element.put("packages", toJson(rollback.getPackages()));
-                element.put("isStaged", rollback.isStaged());
-                element.put("causePackages", versionedPackagesToJson(rollback.getCausePackages()));
-                element.put("committedSessionId", rollback.getCommittedSessionId());
-                array.put(element);
-            }
-
-            PrintWriter pw = new PrintWriter(mRecentlyExecutedRollbacksFile);
-            pw.println(json.toString());
-            pw.close();
-        } catch (IOException | JSONException e) {
-            // TODO: What to do here?
-            Log.e(TAG, "Failed to save recently executed rollbacks", e);
-        }
-    }
-
-    /**
      * Reads the metadata for a rollback from the given directory.
      * @throws IOException in case of error reading the data.
      */
-    private RollbackData loadRollbackData(File backupDir) throws IOException {
+    private static RollbackData loadRollbackData(File backupDir) throws IOException {
         try {
             File rollbackJsonFile = new File(backupDir, "rollback.json");
             JSONObject dataJson = new JSONObject(
                     IoUtils.readFileAsString(rollbackJsonFile.getAbsolutePath()));
 
-            int rollbackId = dataJson.getInt("rollbackId");
-            int stagedSessionId = dataJson.getInt("stagedSessionId");
-            boolean isAvailable = dataJson.getBoolean("isAvailable");
-            RollbackData data = new RollbackData(rollbackId, backupDir,
-                    stagedSessionId, isAvailable);
-            data.packages.addAll(packageRollbackInfosFromJson(dataJson.getJSONArray("packages")));
-            data.timestamp = Instant.parse(dataJson.getString("timestamp"));
-            data.apkSessionId = dataJson.getInt("apkSessionId");
-            return data;
-        } catch (JSONException | DateTimeParseException e) {
+            return new RollbackData(
+                    rollbackInfoFromJson(dataJson.getJSONObject("info")),
+                    backupDir,
+                    Instant.parse(dataJson.getString("timestamp")),
+                    dataJson.getInt("stagedSessionId"),
+                    rollbackStateFromString(dataJson.getString("state")),
+                    dataJson.getInt("apkSessionId"),
+                    dataJson.getBoolean("restoreUserDataInProgress"));
+        } catch (JSONException | DateTimeParseException | ParseException e) {
             throw new IOException(e);
         }
     }
 
-    private JSONObject toJson(VersionedPackage pkg) throws JSONException {
+    private static JSONObject toJson(VersionedPackage pkg) throws JSONException {
         JSONObject json = new JSONObject();
         json.put("packageName", pkg.getPackageName());
         json.put("longVersionCode", pkg.getLongVersionCode());
         return json;
     }
 
-    private VersionedPackage versionedPackageFromJson(JSONObject json) throws JSONException {
+    private static VersionedPackage versionedPackageFromJson(JSONObject json) throws JSONException {
         String packageName = json.getString("packageName");
         long longVersionCode = json.getLong("longVersionCode");
         return new VersionedPackage(packageName, longVersionCode);
     }
 
-    private JSONObject toJson(PackageRollbackInfo info) throws JSONException {
+    private static JSONObject toJson(PackageRollbackInfo info) throws JSONException {
         JSONObject json = new JSONObject();
         json.put("versionRolledBackFrom", toJson(info.getVersionRolledBackFrom()));
         json.put("versionRolledBackTo", toJson(info.getVersionRolledBackTo()));
@@ -374,7 +329,8 @@
         return json;
     }
 
-    private PackageRollbackInfo packageRollbackInfoFromJson(JSONObject json) throws JSONException {
+    private static PackageRollbackInfo packageRollbackInfoFromJson(JSONObject json)
+            throws JSONException {
         VersionedPackage versionRolledBackFrom = versionedPackageFromJson(
                 json.getJSONObject("versionRolledBackFrom"));
         VersionedPackage versionRolledBackTo = versionedPackageFromJson(
@@ -395,7 +351,7 @@
                 pendingBackups, pendingRestores, isApex, installedUsers, ceSnapshotInodes);
     }
 
-    private JSONArray versionedPackagesToJson(List<VersionedPackage> packages)
+    private static JSONArray versionedPackagesToJson(List<VersionedPackage> packages)
             throws JSONException {
         JSONArray json = new JSONArray();
         for (VersionedPackage pkg : packages) {
@@ -404,7 +360,8 @@
         return json;
     }
 
-    private List<VersionedPackage> versionedPackagesFromJson(JSONArray json) throws JSONException {
+    private static List<VersionedPackage> versionedPackagesFromJson(JSONArray json)
+            throws JSONException {
         List<VersionedPackage> packages = new ArrayList<>();
         for (int i = 0; i < json.length(); ++i) {
             packages.add(versionedPackageFromJson(json.getJSONObject(i)));
@@ -412,7 +369,7 @@
         return packages;
     }
 
-    private JSONArray toJson(List<PackageRollbackInfo> infos) throws JSONException {
+    private static JSONArray toJson(List<PackageRollbackInfo> infos) throws JSONException {
         JSONArray json = new JSONArray();
         for (PackageRollbackInfo info : infos) {
             json.put(toJson(info));
@@ -420,7 +377,7 @@
         return json;
     }
 
-    private List<PackageRollbackInfo> packageRollbackInfosFromJson(JSONArray json)
+    private static List<PackageRollbackInfo> packageRollbackInfosFromJson(JSONArray json)
             throws JSONException {
         List<PackageRollbackInfo> infos = new ArrayList<>();
         for (int i = 0; i < json.length(); ++i) {
@@ -434,7 +391,7 @@
      * If the file is a directory, its contents are deleted as well.
      * Has no effect if the directory does not exist.
      */
-    private void removeFile(File file) {
+    private static void removeFile(File file) {
         if (file.isDirectory()) {
             for (File child : file.listFiles()) {
                 removeFile(child);
@@ -444,4 +401,23 @@
             file.delete();
         }
     }
+
+    private static String rollbackStateToString(@RollbackData.RollbackState int state) {
+        switch (state) {
+            case RollbackData.ROLLBACK_STATE_ENABLING: return "enabling";
+            case RollbackData.ROLLBACK_STATE_AVAILABLE: return "available";
+            case RollbackData.ROLLBACK_STATE_COMMITTED: return "committed";
+        }
+        throw new AssertionError("Invalid rollback state: " + state);
+    }
+
+    private static @RollbackData.RollbackState int rollbackStateFromString(String state)
+            throws ParseException {
+        switch (state) {
+            case "enabling": return RollbackData.ROLLBACK_STATE_ENABLING;
+            case "available": return RollbackData.ROLLBACK_STATE_AVAILABLE;
+            case "committed": return RollbackData.ROLLBACK_STATE_COMMITTED;
+        }
+        throw new ParseException("Invalid rollback state: " + state, 0);
+    }
 }
diff --git a/services/core/java/com/android/server/timezone/RulesManagerService.java b/services/core/java/com/android/server/timezone/RulesManagerService.java
index 4b413e5..296a652 100644
--- a/services/core/java/com/android/server/timezone/RulesManagerService.java
+++ b/services/core/java/com/android/server/timezone/RulesManagerService.java
@@ -16,14 +16,13 @@
 
 package com.android.server.timezone;
 
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.server.EventLogTags;
-import com.android.server.SystemService;
-import com.android.timezone.distro.DistroException;
-import com.android.timezone.distro.DistroVersion;
-import com.android.timezone.distro.StagedDistroOperation;
-import com.android.timezone.distro.TimeZoneDistro;
-import com.android.timezone.distro.installer.TimeZoneDistroInstaller;
+import static android.app.timezone.RulesState.DISTRO_STATUS_INSTALLED;
+import static android.app.timezone.RulesState.DISTRO_STATUS_NONE;
+import static android.app.timezone.RulesState.DISTRO_STATUS_UNKNOWN;
+import static android.app.timezone.RulesState.STAGED_OPERATION_INSTALL;
+import static android.app.timezone.RulesState.STAGED_OPERATION_NONE;
+import static android.app.timezone.RulesState.STAGED_OPERATION_UNINSTALL;
+import static android.app.timezone.RulesState.STAGED_OPERATION_UNKNOWN;
 
 import android.app.timezone.Callback;
 import android.app.timezone.DistroFormatVersion;
@@ -37,6 +36,21 @@
 import android.os.RemoteException;
 import android.util.Slog;
 
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.EventLogTags;
+import com.android.server.SystemService;
+import com.android.timezone.distro.DistroException;
+import com.android.timezone.distro.DistroVersion;
+import com.android.timezone.distro.StagedDistroOperation;
+import com.android.timezone.distro.TimeZoneDistro;
+import com.android.timezone.distro.installer.TimeZoneDistroInstaller;
+
+import libcore.icu.ICU;
+import libcore.timezone.TimeZoneDataFiles;
+import libcore.timezone.TimeZoneFinder;
+import libcore.timezone.TzDataSetVersion;
+import libcore.timezone.ZoneInfoDB;
+
 import java.io.File;
 import java.io.FileDescriptor;
 import java.io.FileInputStream;
@@ -46,18 +60,6 @@
 import java.util.Arrays;
 import java.util.concurrent.Executor;
 import java.util.concurrent.atomic.AtomicBoolean;
-import libcore.icu.ICU;
-import libcore.timezone.TzDataSetVersion;
-import libcore.timezone.TimeZoneFinder;
-import libcore.timezone.ZoneInfoDB;
-
-import static android.app.timezone.RulesState.DISTRO_STATUS_INSTALLED;
-import static android.app.timezone.RulesState.DISTRO_STATUS_NONE;
-import static android.app.timezone.RulesState.DISTRO_STATUS_UNKNOWN;
-import static android.app.timezone.RulesState.STAGED_OPERATION_INSTALL;
-import static android.app.timezone.RulesState.STAGED_OPERATION_NONE;
-import static android.app.timezone.RulesState.STAGED_OPERATION_UNINSTALL;
-import static android.app.timezone.RulesState.STAGED_OPERATION_UNKNOWN;
 
 public final class RulesManagerService extends IRulesManager.Stub {
 
@@ -96,8 +98,6 @@
     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
     static final String REQUIRED_QUERY_PERMISSION =
             android.Manifest.permission.QUERY_TIME_ZONE_RULES;
-    private static final File SYSTEM_TZ_DATA_FILE = new File("/system/usr/share/zoneinfo/tzdata");
-    private static final File TZ_DATA_DIR = new File("/data/misc/zoneinfo");
 
     private final AtomicBoolean mOperationInProgress = new AtomicBoolean(false);
     private final PermissionHelper mPermissionHelper;
@@ -108,12 +108,14 @@
 
     private static RulesManagerService create(Context context) {
         RulesManagerServiceHelperImpl helper = new RulesManagerServiceHelperImpl(context);
+        File baseVersionFile = new File(TimeZoneDataFiles.getRuntimeModuleTzVersionFile());
+        File tzDataDir = new File(TimeZoneDataFiles.getDataTimeZoneRootDir());
         return new RulesManagerService(
                 helper /* permissionHelper */,
                 helper /* executor */,
                 helper /* intentHelper */,
                 PackageTracker.create(context),
-                new TimeZoneDistroInstaller(TAG, SYSTEM_TZ_DATA_FILE, TZ_DATA_DIR));
+                new TimeZoneDistroInstaller(TAG, baseVersionFile, tzDataDir));
     }
 
     // A constructor that can be used by tests to supply mocked / faked dependencies.
@@ -143,11 +145,11 @@
     /** Like {@link #getRulesState()} without the permission check. */
     private RulesState getRulesStateInternal() {
         synchronized(this) {
-            String systemRulesVersion;
+            TzDataSetVersion baseVersion;
             try {
-                systemRulesVersion = mInstaller.getSystemRulesVersion();
+                baseVersion = mInstaller.readBaseVersion();
             } catch (IOException e) {
-                Slog.w(TAG, "Failed to read system rules", e);
+                Slog.w(TAG, "Failed to read base rules version", e);
                 return null;
             }
 
@@ -196,7 +198,7 @@
                     Slog.w(TAG, "Failed to read staged distro.", e);
                 }
             }
-            return new RulesState(systemRulesVersion, DISTRO_FORMAT_VERSION_SUPPORTED,
+            return new RulesState(baseVersion.rulesVersion, DISTRO_FORMAT_VERSION_SUPPORTED,
                     operationInProgress, stagedOperationStatus, stagedDistroRulesVersion,
                     distroStatus, installedDistroRulesVersion);
         }
@@ -454,13 +456,13 @@
                             pw.println("Operation in progress: " + value);
                             break;
                         }
-                        case 's': {
-                            // Report system image rules version
+                        case 'b': {
+                            // Report base rules version
                             String value = "Unknown";
                             if (rulesState != null) {
-                                value = rulesState.getSystemRulesVersion();
+                                value = rulesState.getBaseRulesVersion();
                             }
-                            pw.println("System rules version: " + value);
+                            pw.println("Base rules version: " + value);
                             break;
                         }
                         case 'c': {
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index 087de69..f70adef 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -289,10 +289,11 @@
     private int windowFlags;        // custom window flags for preview window.
     private TaskRecord task;        // the task this is in.
     private long createTime = System.currentTimeMillis();
-    long lastVisibleTime;   // last time this activity became visible
-    long cpuTimeAtResume;   // the cpu time of host process at the time of resuming activity
-    long pauseTime;         // last time we started pausing the activity
-    long launchTickTime;    // base time for launch tick messages
+    long lastVisibleTime;         // last time this activity became visible
+    long cpuTimeAtResume;         // the cpu time of host process at the time of resuming activity
+    long pauseTime;               // last time we started pausing the activity
+    long launchTickTime;          // base time for launch tick messages
+    long topResumedStateLossTime; // last time we reported top resumed state loss to an activity
     // Last configuration reported to the activity in the client process.
     private MergedConfiguration mLastReportedConfiguration;
     private int mLastReportedDisplayId;
@@ -694,14 +695,14 @@
 
     void scheduleTopResumedActivityChanged(boolean onTop) {
         if (!attachedToProcess()) {
-            if (DEBUG_CONFIGURATION) {
+            if (DEBUG_STATES) {
                 Slog.w(TAG, "Can't report activity position update - client not running"
                                 + ", activityRecord=" + this);
             }
             return;
         }
         try {
-            if (DEBUG_CONFIGURATION) {
+            if (DEBUG_STATES) {
                 Slog.v(TAG, "Sending position change to " + this + ", onTop: " + onTop);
             }
 
@@ -2751,7 +2752,9 @@
                 final Configuration srcConfig = task.getConfiguration();
                 overrideConfig.colorMode = srcConfig.colorMode;
                 overrideConfig.densityDpi = srcConfig.densityDpi;
-                overrideConfig.screenLayout = srcConfig.screenLayout;
+                overrideConfig.screenLayout = srcConfig.screenLayout
+                        & (Configuration.SCREENLAYOUT_LONG_MASK
+                                | Configuration.SCREENLAYOUT_SIZE_MASK);
                 // The smallest screen width is the short side of screen bounds. Because the bounds
                 // and density won't be changed, smallestScreenWidthDp is also fixed.
                 overrideConfig.smallestScreenWidthDp = srcConfig.smallestScreenWidthDp;
@@ -3283,7 +3286,7 @@
             transaction.addCallback(callbackItem);
             transaction.setLifecycleStateRequest(lifecycleItem);
             mAtmService.getLifecycleManager().scheduleTransaction(transaction);
-            mRootActivityContainer.updateTopResumedActivityIfNeeded();
+            mStackSupervisor.updateTopResumedActivityIfNeeded();
             // Note: don't need to call pauseIfSleepingLocked() here, because the caller will only
             // request resume if this activity is currently resumed, which implies we aren't
             // sleeping.
diff --git a/services/core/java/com/android/server/wm/ActivityStack.java b/services/core/java/com/android/server/wm/ActivityStack.java
index a4457e2..ea2aff2 100644
--- a/services/core/java/com/android/server/wm/ActivityStack.java
+++ b/services/core/java/com/android/server/wm/ActivityStack.java
@@ -1491,6 +1491,7 @@
                 + " callers=" + Debug.getCallers(5));
         r.setState(RESUMED, "minimalResumeActivityLocked");
         r.completeResumeLocked();
+        mStackSupervisor.updateTopResumedActivityIfNeeded();
         if (DEBUG_SAVED_STATE) Slog.i(TAG_SAVED_STATE,
                 "Launch completed; removing icicle of " + r.icicle);
     }
@@ -2575,7 +2576,7 @@
             // Protect against recursion.
             mInResumeTopActivity = true;
             result = resumeTopActivityInnerLocked(prev, options);
-            mRootActivityContainer.updateTopResumedActivityIfNeeded();
+            mStackSupervisor.updateTopResumedActivityIfNeeded();
 
             // When resuming the top activity, it may be necessary to pause the top activity (for
             // example, returning to the lock screen. We suppress the normal pause logic in
diff --git a/services/core/java/com/android/server/wm/ActivityStackSupervisor.java b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
index df76030..758a765 100644
--- a/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
@@ -170,6 +170,9 @@
     // How long we can hold the launch wake lock before giving up.
     static final int LAUNCH_TIMEOUT = 10 * 1000;
 
+    /** How long we wait until giving up on the activity telling us it released the top state. */
+    static final int TOP_RESUMED_STATE_LOSS_TIMEOUT = 500;
+
     static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG;
     static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_STACK_MSG + 1;
     static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_STACK_MSG + 2;
@@ -179,6 +182,7 @@
     static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 14;
     static final int REPORT_PIP_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 15;
     static final int REPORT_HOME_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 16;
+    static final int TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 17;
 
     // Used to indicate that windows of activities should be preserved during the resize.
     static final boolean PRESERVE_WINDOWS = true;
@@ -300,6 +304,18 @@
      */
     final ArrayList<ActivityRecord> mNoAnimActivities = new ArrayList<>();
 
+    /**
+     * Cached value of the topmost resumed activity in the system. Updated when new activity is
+     * resumed.
+     */
+    private ActivityRecord mTopResumedActivity;
+
+    /**
+     * Flag indicating whether we're currently waiting for the previous top activity to handle the
+     * loss of the state and report back before making new activity top resumed.
+     */
+    private boolean mTopResumedActivityWaitingForPrev;
+
     /** The target stack bounds for the picture-in-picture mode changed that we need to report to
      * the application */
     Rect mPipModeChangedTargetStackBounds;
@@ -844,7 +860,7 @@
 
                 // Schedule transaction.
                 mService.getLifecycleManager().scheduleTransaction(clientTransaction);
-                mRootActivityContainer.updateTopResumedActivityIfNeeded();
+                updateTopResumedActivityIfNeeded();
 
                 if ((proc.mInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0
                         && mService.mHasHeavyWeightFeature) {
@@ -2296,6 +2312,73 @@
         mHandler.sendEmptyMessage(IDLE_NOW_MSG);
     }
 
+    /**
+     * Updates the record of top resumed activity when it changes and handles reporting of the
+     * state changes to previous and new top activities. It will immediately dispatch top resumed
+     * state loss message to previous top activity (if haven't done it already). After the previous
+     * activity releases the top state and reports back, message about acquiring top state will be
+     * sent to the new top resumed activity.
+     */
+    void updateTopResumedActivityIfNeeded() {
+        final ActivityRecord prevTopActivity = mTopResumedActivity;
+        final ActivityStack topStack = mRootActivityContainer.getTopDisplayFocusedStack();
+        if (topStack == null || topStack.mResumedActivity == prevTopActivity) {
+            return;
+        }
+
+        // Ask previous activity to release the top state.
+        final boolean prevActivityReceivedTopState =
+                prevTopActivity != null && !mTopResumedActivityWaitingForPrev;
+        // mTopResumedActivityWaitingForPrev == true at this point would mean that an activity
+        // before the prevTopActivity one hasn't reported back yet. So server never sent the top
+        // resumed state change message to prevTopActivity.
+        if (prevActivityReceivedTopState) {
+            prevTopActivity.scheduleTopResumedActivityChanged(false /* onTop */);
+            scheduleTopResumedStateLossTimeout(prevTopActivity);
+            mTopResumedActivityWaitingForPrev = true;
+        }
+
+        // Update the current top activity.
+        mTopResumedActivity = topStack.mResumedActivity;
+        scheduleTopResumedActivityStateIfNeeded();
+    }
+
+    /** Schedule top resumed state change if previous top activity already reported back. */
+    private void scheduleTopResumedActivityStateIfNeeded() {
+        if (mTopResumedActivity != null && !mTopResumedActivityWaitingForPrev) {
+            mTopResumedActivity.scheduleTopResumedActivityChanged(true /* onTop */);
+        }
+    }
+
+    /**
+     * Limit the time given to the app to report handling of the state loss.
+     */
+    private void scheduleTopResumedStateLossTimeout(ActivityRecord r) {
+        final Message msg = mHandler.obtainMessage(TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG);
+        msg.obj = r;
+        r.topResumedStateLossTime = SystemClock.uptimeMillis();
+        mHandler.sendMessageDelayed(msg, TOP_RESUMED_STATE_LOSS_TIMEOUT);
+        if (DEBUG_STATES) Slog.v(TAG_STATES, "Waiting for top state to be released by " + r);
+    }
+
+    /**
+     * Handle a loss of top resumed state by an activity - update internal state and inform next top
+     * activity if needed.
+     */
+    void handleTopResumedStateReleased(boolean timeout) {
+        if (DEBUG_STATES) {
+            Slog.v(TAG_STATES, "Top resumed state released "
+                    + (timeout ? " (due to timeout)" : " (transition complete)"));
+        }
+        mHandler.removeMessages(TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG);
+        if (!mTopResumedActivityWaitingForPrev) {
+            // Top resumed activity state loss already handled.
+            return;
+        }
+        mTopResumedActivityWaitingForPrev = false;
+        scheduleTopResumedActivityStateIfNeeded();
+    }
+
     void removeTimeoutsForActivityLocked(ActivityRecord r) {
         if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
                 + Debug.getCallers(4));
@@ -2351,6 +2434,9 @@
                 // Suppress the warning toast if the preferredDisplay was set to singleTask.
                 // The singleTaskInstance displays will only contain one task and any attempt to
                 // launch new task will re-route to the default display.
+                mService.getTaskChangeNotificationController()
+                        .notifyActivityLaunchOnSecondaryDisplayRerouted(task.getTaskInfo(),
+                                preferredDisplayId);
                 return;
             }
 
@@ -2587,8 +2673,18 @@
                         // Start home activities on displays with no activities.
                         mRootActivityContainer.startHomeOnEmptyDisplays("homeChanged");
                     }
-                }
-                break;
+                } break;
+                case TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG: {
+                    ActivityRecord r = (ActivityRecord) msg.obj;
+                    Slog.w(TAG, "Activity top resumed state loss timeout for " + r);
+                    synchronized (mService.mGlobalLock) {
+                        if (r.hasProcess()) {
+                            mService.logAppTooSlow(r.app, r.topResumedStateLossTime,
+                                    "top state loss for " + r);
+                        }
+                    }
+                    handleTopResumedStateReleased(true /* timeout */);
+                } break;
             }
         }
     }
diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
index cb4664f..d747198 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@@ -1634,6 +1634,15 @@
     }
 
     @Override
+    public final void activityTopResumedStateLost() {
+        final long origId = Binder.clearCallingIdentity();
+        synchronized (mGlobalLock) {
+            mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
+        }
+        Binder.restoreCallingIdentity(origId);
+    }
+
+    @Override
     public final void activityPaused(IBinder token) {
         final long origId = Binder.clearCallingIdentity();
         synchronized (mGlobalLock) {
@@ -3098,8 +3107,7 @@
     }
 
     @Override
-    public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
-            int[] secondaryDisplaysShowing) {
+    public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
         if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
                 != PackageManager.PERMISSION_GRANTED) {
             throw new SecurityException("Requires permission "
@@ -3116,8 +3124,7 @@
                 mH.sendMessage(msg);
             }
             try {
-                mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
-                        secondaryDisplaysShowing);
+                mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
             } finally {
                 Binder.restoreCallingIdentity(ident);
             }
diff --git a/services/core/java/com/android/server/wm/AppWindowThumbnail.java b/services/core/java/com/android/server/wm/AppWindowThumbnail.java
index 5519729..bbbf11d 100644
--- a/services/core/java/com/android/server/wm/AppWindowThumbnail.java
+++ b/services/core/java/com/android/server/wm/AppWindowThumbnail.java
@@ -118,7 +118,8 @@
         anim.scaleCurrentDuration(mAppToken.mWmService.getTransitionAnimationScaleLocked());
         mSurfaceAnimator.startAnimation(t, new LocalAnimationAdapter(
                 new WindowAnimationSpec(anim, position,
-                        mAppToken.getDisplayContent().mAppTransition.canSkipFirstFrame()),
+                        mAppToken.getDisplayContent().mAppTransition.canSkipFirstFrame(),
+                        mAppToken.mWmService.mWindowCornerRadius),
                 mAppToken.mWmService.mSurfaceAnimationRunner), false /* hidden */);
     }
 
diff --git a/services/core/java/com/android/server/wm/AppWindowToken.java b/services/core/java/com/android/server/wm/AppWindowToken.java
index 88c8b95..78199d44 100644
--- a/services/core/java/com/android/server/wm/AppWindowToken.java
+++ b/services/core/java/com/android/server/wm/AppWindowToken.java
@@ -118,7 +118,7 @@
 import com.android.internal.util.ToBooleanFunction;
 import com.android.server.AttributeCache;
 import com.android.server.LocalServices;
-import com.android.server.display.ColorDisplayService;
+import com.android.server.display.color.ColorDisplayService;
 import com.android.server.policy.WindowManagerPolicy;
 import com.android.server.policy.WindowManagerPolicy.StartingSurface;
 import com.android.server.wm.RemoteAnimationController.RemoteAnimationRecord;
@@ -582,6 +582,8 @@
                     }
                 }
             }
+            // Changes in opening apps and closing apps may cause orientation change.
+            reportDescendantOrientationChangeIfNeeded();
             return;
         }
 
@@ -729,11 +731,31 @@
                 }
                 SurfaceControl.closeTransaction();
             }
+
+            // Visibility changes may cause orientation request change.
+            reportDescendantOrientationChangeIfNeeded();
         }
 
         return delayed;
     }
 
+    private void reportDescendantOrientationChangeIfNeeded() {
+        // Orientation request is exposed only when we're visible. Therefore visibility change
+        // will change requested orientation. Notify upward the hierarchy ladder to adjust
+        // configuration. This is important to cases where activities with incompatible
+        // orientations launch, or user goes back from an activity of bi-orientation to an
+        // activity with specified orientation.
+        if (mActivityRecord.getRequestedConfigurationOrientation() == getConfiguration().orientation
+                || getOrientationIgnoreVisibility() == SCREEN_ORIENTATION_UNSET) {
+            return;
+        }
+
+        final IBinder freezeToken =
+                mActivityRecord.mayFreezeScreenLocked(mActivityRecord.app)
+                        ? mActivityRecord.appToken : null;
+        onDescendantOrientationChanged(freezeToken, mActivityRecord);
+    }
+
     /**
      * @return The to top most child window for which {@link LayoutParams#isFullscreen()} returns
      *         true.
@@ -2526,7 +2548,8 @@
                             new WindowAnimationSpec(a, mTmpPoint, mTmpRect,
                                     getDisplayContent().mAppTransition.canSkipFirstFrame(),
                                     appStackClipMode,
-                                    true /* isAppAnimation */),
+                                    true /* isAppAnimation */,
+                                    mWmService.mWindowCornerRadius),
                             mWmService.mSurfaceAnimationRunner);
                     if (a.getZAdjustment() == Animation.ZORDER_TOP) {
                         mNeedsZBoost = true;
diff --git a/services/core/java/com/android/server/wm/DisplayPolicy.java b/services/core/java/com/android/server/wm/DisplayPolicy.java
index 91d573d..b028569 100644
--- a/services/core/java/com/android/server/wm/DisplayPolicy.java
+++ b/services/core/java/com/android/server/wm/DisplayPolicy.java
@@ -2787,6 +2787,9 @@
     public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
         mFocusedWindow = newFocus;
         mLastFocusedWindow = lastFocus;
+        if (mDisplayContent.isDefaultDisplay) {
+            mService.mPolicy.onDefaultDisplayFocusChangedLw(newFocus);
+        }
         if ((updateSystemUiVisibilityLw() & SYSTEM_UI_CHANGING_LAYOUT) != 0) {
             // If the navigation bar has been hidden or shown, we need to do another
             // layout pass to update that window.
@@ -3271,7 +3274,12 @@
         }
 
         final WindowState w = mTopFullscreenOpaqueWindowState;
-        if (w != mFocusedWindow) {
+        if (w == null || w != mFocusedWindow) {
+            return false;
+        }
+        // If the bounds of activity window is different from its parent, then reject to be seamless
+        // because the window position may change after rotation that will look like a sudden jump.
+        if (w.mAppToken != null && !w.mAppToken.matchParentBounds()) {
             return false;
         }
 
@@ -3279,8 +3287,7 @@
         // it and is in the fullscreen opaque state. Seamless rotation
         // requires freezing various Surface states and won't work well
         // with animations, so we disable it in the animation case for now.
-        if (w != null && !w.isAnimatingLw()
-                && w.getAttrs().rotationAnimation == ROTATION_ANIMATION_SEAMLESS) {
+        if (!w.isAnimatingLw() && w.getAttrs().rotationAnimation == ROTATION_ANIMATION_SEAMLESS) {
             return true;
         }
         return false;
diff --git a/services/core/java/com/android/server/wm/KeyguardController.java b/services/core/java/com/android/server/wm/KeyguardController.java
index b5be2ac5..8c8b05f 100644
--- a/services/core/java/com/android/server/wm/KeyguardController.java
+++ b/services/core/java/com/android/server/wm/KeyguardController.java
@@ -29,6 +29,7 @@
 import static android.view.WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_TO_SHADE;
 import static android.view.WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_WITH_WALLPAPER;
 
+import static com.android.server.am.KeyguardControllerProto.AOD_SHOWING;
 import static com.android.server.am.KeyguardControllerProto.KEYGUARD_OCCLUDED_STATES;
 import static com.android.server.am.KeyguardControllerProto.KEYGUARD_SHOWING;
 import static com.android.server.am.KeyguardOccludedProto.DISPLAY_ID;
@@ -49,7 +50,6 @@
 import com.android.server.wm.ActivityTaskManagerInternal.SleepToken;
 
 import java.io.PrintWriter;
-import java.util.Arrays;
 
 /**
  * Controls Keyguard occluding, dismissing and transitions depending on what kind of activities are
@@ -87,7 +87,7 @@
 
     /**
      * @return true if either Keyguard or AOD are showing, not going away, and not being occluded
-     *         on the given display, false otherwise
+     *         on the given display, false otherwise.
      */
     boolean isKeyguardOrAodShowing(int displayId) {
         return (mKeyguardShowing || mAodShowing) && !mKeyguardGoingAway
@@ -95,6 +95,16 @@
     }
 
     /**
+     * @return {@code true} if 1) Keyguard is showing, not going away, and not being occluded on the
+     *         given display, or 2) AOD is showing, {@code false} otherwise.
+     * TODO(b/125198167): Replace isKeyguardOrAodShowing() by this logic.
+     */
+    boolean isKeyguardUnoccludedOrAodShowing(int displayId) {
+        return (mKeyguardShowing && !mKeyguardGoingAway && !isDisplayOccluded(displayId))
+                || mAodShowing;
+    }
+
+    /**
      * @return true if Keyguard is showing, not going away, and not being occluded on the given
      *         display, false otherwise
      */
@@ -120,18 +130,15 @@
     /**
      * Update the Keyguard showing state.
      */
-    void setKeyguardShown(boolean keyguardShowing, boolean aodShowing,
-            int[] secondaryDisplaysShowing) {
+    void setKeyguardShown(boolean keyguardShowing, boolean aodShowing) {
         boolean showingChanged = keyguardShowing != mKeyguardShowing || aodShowing != mAodShowing;
         // If keyguard is going away, but SystemUI aborted the transition, need to reset state.
         showingChanged |= mKeyguardGoingAway && keyguardShowing;
-        if (!showingChanged && Arrays.equals(secondaryDisplaysShowing,
-                mSecondaryDisplayIdsShowing)) {
+        if (!showingChanged) {
             return;
         }
         mKeyguardShowing = keyguardShowing;
         mAodShowing = aodShowing;
-        mSecondaryDisplayIdsShowing = secondaryDisplaysShowing;
         mWindowManager.setAodShowing(aodShowing);
         if (showingChanged) {
             dismissDockedStackIfNeeded();
@@ -384,10 +391,11 @@
         for (int displayNdx = mRootActivityContainer.getChildCount() - 1;
              displayNdx >= 0; displayNdx--) {
             final ActivityDisplay display = mRootActivityContainer.getChildAt(displayNdx);
-            final KeyguardDisplayState state = getDisplay(display.mDisplayId);
-            if (isKeyguardOrAodShowing(display.mDisplayId) && state.mSleepToken == null) {
+            final int displayId = display.mDisplayId;
+            final KeyguardDisplayState state = getDisplay(displayId);
+            if (isKeyguardUnoccludedOrAodShowing(displayId) && state.mSleepToken == null) {
                 state.acquiredSleepToken();
-            } else if (!isKeyguardOrAodShowing(display.mDisplayId) && state.mSleepToken != null) {
+            } else if (!isKeyguardUnoccludedOrAodShowing(displayId) && state.mSleepToken != null) {
                 state.releaseSleepToken();
             }
         }
@@ -532,6 +540,7 @@
 
     void writeToProto(ProtoOutputStream proto, long fieldId) {
         final long token = proto.start(fieldId);
+        proto.write(AOD_SHOWING, mAodShowing);
         proto.write(KEYGUARD_SHOWING, mKeyguardShowing);
         writeDisplayStatesToProto(proto, KEYGUARD_OCCLUDED_STATES);
         proto.end(token);
diff --git a/services/core/java/com/android/server/wm/RecentTasks.java b/services/core/java/com/android/server/wm/RecentTasks.java
index c6c85fd..0480d43 100644
--- a/services/core/java/com/android/server/wm/RecentTasks.java
+++ b/services/core/java/com/android/server/wm/RecentTasks.java
@@ -1159,7 +1159,8 @@
     /**
      * @return whether the given active task should be presented to the user through SystemUI.
      */
-    private boolean isVisibleRecentTask(TaskRecord task) {
+    @VisibleForTesting
+    boolean isVisibleRecentTask(TaskRecord task) {
         if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "isVisibleRecentTask: task=" + task
                 + " minVis=" + mMinNumVisibleTasks + " maxVis=" + mMaxNumVisibleTasks
                 + " sessionDuration=" + mActiveTasksSessionDurationMs
@@ -1195,6 +1196,17 @@
                 }
         }
 
+        // Tasks managed by/associated with an ActivityView should be excluded from recents.
+        // singleTaskInstance is set on the VirtualDisplay managed by ActivityView
+        // TODO(b/126185105): Find a different signal to use besides isSingleTaskInstance
+        final ActivityStack stack = task.getStack();
+        if (stack != null) {
+            ActivityDisplay display = stack.getDisplay();
+            if (display != null && display.isSingleTaskInstance()) {
+                return false;
+            }
+        }
+
         // If we're in lock task mode, ignore the root task
         if (task == mService.getLockTaskController().getRootTask()) {
             return false;
diff --git a/services/core/java/com/android/server/wm/RootActivityContainer.java b/services/core/java/com/android/server/wm/RootActivityContainer.java
index 6988357..e3beb19 100644
--- a/services/core/java/com/android/server/wm/RootActivityContainer.java
+++ b/services/core/java/com/android/server/wm/RootActivityContainer.java
@@ -175,12 +175,6 @@
     private ActivityDisplay mDefaultDisplay;
     private final SparseArray<IntArray> mDisplayAccessUIDs = new SparseArray<>();
 
-    /**
-     * Cached value of the topmost resumed activity in the system. Updated when new activity is
-     * resumed.
-     */
-    private ActivityRecord mTopResumedActivity;
-
     /** The current user */
     int mCurrentUser;
     /** Stack id of the front stack when user switched, indexed by userId. */
@@ -1155,23 +1149,6 @@
         return result;
     }
 
-    void updateTopResumedActivityIfNeeded() {
-        final ActivityRecord prevTopActivity = mTopResumedActivity;
-        final ActivityStack topStack = getTopDisplayFocusedStack();
-        if (topStack == null || topStack.mResumedActivity == prevTopActivity) {
-            return;
-        }
-        // Clear previous top state
-        if (prevTopActivity != null) {
-            prevTopActivity.scheduleTopResumedActivityChanged(false /* onTop */);
-        }
-        // Update the current top activity
-        mTopResumedActivity = topStack.mResumedActivity;
-        if (mTopResumedActivity != null) {
-            mTopResumedActivity.scheduleTopResumedActivityChanged(true /* onTop */);
-        }
-    }
-
     void applySleepTokens(boolean applyToStacks) {
         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
             // Set the sleeping state of the display.
@@ -1434,7 +1411,7 @@
             mActivityDisplays.remove(display);
             mActivityDisplays.add(position, display);
         }
-        updateTopResumedActivityIfNeeded();
+        mStackSupervisor.updateTopResumedActivityIfNeeded();
     }
 
     @VisibleForTesting
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 888d741..499cbaf 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -330,7 +330,7 @@
         // No one in higher hierarchy handles this request, let's adjust our bounds to fulfill
         // it if possible.
         // TODO: Move to TaskRecord after unification is done.
-        if (mTaskRecord != null) {
+        if (mTaskRecord != null && mTaskRecord.getParent() != null) {
             mTaskRecord.onConfigurationChanged(mTaskRecord.getParent().getConfiguration());
             return true;
         }
diff --git a/services/core/java/com/android/server/wm/TaskChangeNotificationController.java b/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
index 789f987..42d2583 100644
--- a/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
+++ b/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
@@ -50,6 +50,7 @@
     private static final int NOTIFY_PINNED_STACK_ANIMATION_STARTED_LISTENERS_MSG = 16;
     private static final int NOTIFY_ACTIVITY_UNPINNED_LISTENERS_MSG = 17;
     private static final int NOTIFY_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_FAILED_MSG = 18;
+    private static final int NOTIFY_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_REROUTED_MSG = 19;
 
     // Delay in notifying task stack change listeners (in millis)
     private static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_DELAY = 100;
@@ -130,6 +131,10 @@
         l.onActivityLaunchOnSecondaryDisplayFailed((RunningTaskInfo) m.obj, m.arg1);
     };
 
+    private final TaskStackConsumer mNotifyActivityLaunchOnSecondaryDisplayRerouted = (l, m) -> {
+        l.onActivityLaunchOnSecondaryDisplayRerouted((RunningTaskInfo) m.obj, m.arg1);
+    };
+
     private final TaskStackConsumer mNotifyTaskProfileLocked = (l, m) -> {
         l.onTaskProfileLocked(m.arg1, m.arg2);
     };
@@ -202,6 +207,9 @@
                 case NOTIFY_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_FAILED_MSG:
                     forAllRemoteListeners(mNotifyActivityLaunchOnSecondaryDisplayFailed, msg);
                     break;
+                case NOTIFY_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_REROUTED_MSG:
+                    forAllRemoteListeners(mNotifyActivityLaunchOnSecondaryDisplayRerouted, msg);
+                    break;
                 case NOTIFY_TASK_PROFILE_LOCKED_LISTENERS_MSG:
                     forAllRemoteListeners(mNotifyTaskProfileLocked, msg);
                     break;
@@ -355,6 +363,15 @@
         msg.sendToTarget();
     }
 
+    void notifyActivityLaunchOnSecondaryDisplayRerouted(TaskInfo ti, int requestedDisplayId) {
+        mHandler.removeMessages(NOTIFY_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_REROUTED_MSG);
+        final Message msg = mHandler.obtainMessage(
+                NOTIFY_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_REROUTED_MSG, requestedDisplayId,
+                0 /* unused */, ti);
+        forAllLocalListeners(mNotifyActivityLaunchOnSecondaryDisplayRerouted, msg);
+        msg.sendToTarget();
+    }
+
     void notifyTaskCreated(int taskId, ComponentName componentName) {
         final Message msg = mHandler.obtainMessage(NOTIFY_TASK_ADDED_LISTENERS_MSG,
                 taskId, 0 /* unused */, componentName);
diff --git a/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java b/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java
index f3050a9..904c503 100644
--- a/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java
+++ b/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java
@@ -235,8 +235,7 @@
         // STEP 2.3: Adjust launch parameters as needed for freeform display. We enforce the policy
         // that legacy (pre-D) apps and those apps that can't handle multiple screen density well
         // are forced to be maximized. The rest of this step is to define the default policy when
-        // there is no initial bounds or a fully resolved current params from callers. Right now we
-        // launch all possible tasks/activities that can handle freeform into freeform mode.
+        // there is no initial bounds or a fully resolved current params from callers.
         if (display.inFreeformWindowingMode()) {
             if (launchMode == WINDOWING_MODE_PINNED) {
                 if (DEBUG) appendLog("picture-in-picture");
@@ -247,17 +246,6 @@
                 launchMode = WINDOWING_MODE_FULLSCREEN;
                 outParams.mBounds.setEmpty();
                 if (DEBUG) appendLog("forced-maximize");
-            } else if (fullyResolvedCurrentParam) {
-                // Don't adjust launch mode if that's inherited, except when we're launching an
-                // activity that should be forced to maximize.
-                if (DEBUG) appendLog("skip-adjustment-fully-resolved-params");
-            } else if (launchMode != WINDOWING_MODE_FREEFORM
-                    && (isNOrGreater(root) || isPreNResizeable(root))) {
-                // We're launching a pre-N and post-D activity that supports resizing, or a post-N
-                // activity. They can handle freeform nicely so launch them in freeform.
-                // Use undefined because we know we're in a freeform display.
-                launchMode = WINDOWING_MODE_UNDEFINED;
-                if (DEBUG) appendLog("should-be-freeform");
             }
         } else {
             if (DEBUG) appendLog("non-freeform-display");
@@ -441,10 +429,6 @@
         return !root.isResizeable();
     }
 
-    private boolean isNOrGreater(@NonNull ActivityRecord root) {
-        return root.appInfo.targetSdkVersion >= Build.VERSION_CODES.N;
-    }
-
     /**
      * Resolves activity requested orientation to 4 categories:
      * 1) {@link ActivityInfo#SCREEN_ORIENTATION_LOCKED} indicating app wants to lock down
@@ -485,10 +469,6 @@
         return orientation;
     }
 
-    private boolean isPreNResizeable(ActivityRecord root) {
-        return root.appInfo.targetSdkVersion < Build.VERSION_CODES.N && root.isResizeable();
-    }
-
     private void cascadeBounds(@NonNull Rect srcBounds, @NonNull ActivityDisplay display,
             @NonNull Rect outBounds) {
         outBounds.set(srcBounds);
diff --git a/services/core/java/com/android/server/wm/WindowAnimationSpec.java b/services/core/java/com/android/server/wm/WindowAnimationSpec.java
index 98c77ac..57311e1 100644
--- a/services/core/java/com/android/server/wm/WindowAnimationSpec.java
+++ b/services/core/java/com/android/server/wm/WindowAnimationSpec.java
@@ -17,10 +17,10 @@
 package com.android.server.wm;
 
 import static com.android.server.wm.AnimationAdapter.STATUS_BAR_TRANSITION_DURATION;
-import static com.android.server.wm.WindowStateAnimator.STACK_CLIP_AFTER_ANIM;
-import static com.android.server.wm.WindowStateAnimator.STACK_CLIP_NONE;
 import static com.android.server.wm.AnimationSpecProto.WINDOW;
 import static com.android.server.wm.WindowAnimationSpecProto.ANIMATION;
+import static com.android.server.wm.WindowStateAnimator.STACK_CLIP_AFTER_ANIM;
+import static com.android.server.wm.WindowStateAnimator.STACK_CLIP_NONE;
 
 import android.graphics.Point;
 import android.graphics.Rect;
@@ -51,18 +51,22 @@
     private final Rect mStackBounds = new Rect();
     private int mStackClipMode;
     private final Rect mTmpRect = new Rect();
+    private final float mWindowCornerRadius;
 
-    public WindowAnimationSpec(Animation animation, Point position, boolean canSkipFirstFrame)  {
+    public WindowAnimationSpec(Animation animation, Point position, boolean canSkipFirstFrame,
+            float windowCornerRadius)  {
         this(animation, position, null /* stackBounds */, canSkipFirstFrame, STACK_CLIP_NONE,
-                false /* isAppAnimation */);
+                false /* isAppAnimation */, windowCornerRadius);
     }
 
     public WindowAnimationSpec(Animation animation, Point position, Rect stackBounds,
-            boolean canSkipFirstFrame, int stackClipMode, boolean isAppAnimation) {
+            boolean canSkipFirstFrame, int stackClipMode, boolean isAppAnimation,
+            float windowCornerRadius) {
         mAnimation = animation;
         if (position != null) {
             mPosition.set(position.x, position.y);
         }
+        mWindowCornerRadius = windowCornerRadius;
         mCanSkipFirstFrame = canSkipFirstFrame;
         mIsAppAnimation = isAppAnimation;
         mStackClipMode = stackClipMode;
@@ -101,6 +105,9 @@
             mTmpRect.intersect(tmp.transformation.getClipRect());
             t.setWindowCrop(leash, mTmpRect);
         }
+        if (mAnimation.hasRoundedCorners() && mWindowCornerRadius > 0) {
+            t.setCornerRadius(leash, mWindowCornerRadius);
+        }
     }
 
     @Override
diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java
index 76f080b..05d4760 100644
--- a/services/core/java/com/android/server/wm/WindowContainer.java
+++ b/services/core/java/com/android/server/wm/WindowContainer.java
@@ -1292,6 +1292,7 @@
      * Called when an animation has finished running.
      */
     protected void onAnimationFinished() {
+        mWmService.onAnimationFinished();
     }
 
     /**
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index e19c7c6..1bd1795 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -145,6 +145,7 @@
 import android.hardware.display.DisplayManager;
 import android.hardware.display.DisplayManagerInternal;
 import android.hardware.input.InputManager;
+import android.hardware.input.InputManagerInternal;
 import android.net.Uri;
 import android.os.Binder;
 import android.os.Build;
@@ -234,6 +235,7 @@
 import com.android.internal.os.IResultReceiver;
 import com.android.internal.policy.IKeyguardDismissCallback;
 import com.android.internal.policy.IShortcutService;
+import com.android.internal.policy.ScreenDecorationsUtils;
 import com.android.internal.util.DumpUtils;
 import com.android.internal.util.FastPrintWriter;
 import com.android.internal.util.LatencyTracker;
@@ -372,6 +374,8 @@
     private static final int TRANSITION_ANIMATION_SCALE = 1;
     private static final int ANIMATION_DURATION_SCALE = 2;
 
+    private static final int ANIMATION_COMPLETED_TIMEOUT_MS = 5000;
+
     final WindowTracing mWindowTracing;
 
     final private KeyguardDisableHandler mKeyguardDisableHandler;
@@ -751,24 +755,27 @@
     final DisplayManager mDisplayManager;
     final ActivityTaskManagerService mAtmService;
 
-    // Indicates whether this device supports wide color gamut / HDR rendering
+    /** Corner radius that windows should have in order to match the display. */
+    final float mWindowCornerRadius;
+
+    /** Indicates whether this device supports wide color gamut / HDR rendering */
     private boolean mHasWideColorGamutSupport;
     private boolean mHasHdrSupport;
 
-    // Who is holding the screen on.
+    /** Who is holding the screen on. */
     private Session mHoldingScreenOn;
     private PowerManager.WakeLock mHoldingScreenWakeLock;
 
-    // Whether or not a layout can cause a wake up when theater mode is enabled.
+    /** Whether or not a layout can cause a wake up when theater mode is enabled. */
     boolean mAllowTheaterModeWakeFromLayout;
 
     final TaskPositioningController mTaskPositioningController;
     final DragDropController mDragDropController;
 
-    // For frozen screen animations.
+    /** For frozen screen animations. */
     private int mExitAnimId, mEnterAnimId;
 
-    // The display that the rotation animation is applying to.
+    /** The display that the rotation animation is applying to. */
     private int mFrozenDisplayId;
 
     /** Skip repeated AppWindowTokens initialization. Note that AppWindowsToken's version of this
@@ -975,7 +982,7 @@
         mInputManager = inputManager; // Must be before createDisplayContentLocked.
         mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
         mDisplayWindowSettings = new DisplayWindowSettings(this);
-
+        mWindowCornerRadius = ScreenDecorationsUtils.getWindowCornerRadius(context.getResources());
 
         mTransactionFactory = transactionFactory;
         mTransaction = mTransactionFactory.make();
@@ -7424,13 +7431,38 @@
 
     @Override
     public boolean injectInputAfterTransactionsApplied(InputEvent ev, int mode) {
+        waitForAnimationsToComplete();
+
         synchronized (mGlobalLock) {
             mWindowPlacerLocked.performSurfacePlacementIfScheduled();
-            new SurfaceControl.Transaction()
-                    .syncInputWindows()
-                    .apply(true);
         }
 
-        return mInputManager.injectInputEvent(ev, mode);
+        new SurfaceControl.Transaction().syncInputWindows().apply(true);
+
+        return LocalServices.getService(InputManagerInternal.class).injectInputEvent(ev, mode);
+    }
+
+    private void waitForAnimationsToComplete() {
+        synchronized (mGlobalLock) {
+            long timeoutRemaining = ANIMATION_COMPLETED_TIMEOUT_MS;
+            while (mRoot.isSelfOrChildAnimating() && timeoutRemaining > 0) {
+                long startTime = System.currentTimeMillis();
+                try {
+                    mGlobalLock.wait(timeoutRemaining);
+                } catch (InterruptedException e) {
+                }
+                timeoutRemaining -= (System.currentTimeMillis() - startTime);
+            }
+
+            if (mRoot.isSelfOrChildAnimating()) {
+                Log.w(TAG, "Timed out waiting for animations to complete.");
+            }
+        }
+    }
+
+    void onAnimationFinished() {
+        synchronized (mGlobalLock) {
+            mGlobalLock.notifyAll();
+        }
     }
 }
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index ab1b6ae..b7925f20 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -4373,7 +4373,11 @@
             Slog.d(TAG, "relayoutVisibleWindow: " + this + " mAnimatingExit=true, mRemoveOnExit="
                     + mRemoveOnExit + ", mDestroying=" + mDestroying);
 
-            mWinAnimator.cancelExitAnimationForNextAnimationLocked();
+            // Cancel the existing exit animation for the next enter animation.
+            if (isSelfAnimating()) {
+                cancelAnimation();
+                destroySurfaceUnchecked();
+            }
             mAnimatingExit = false;
         }
         if (mDestroying) {
@@ -4454,7 +4458,8 @@
         anim.restrictDuration(MAX_ANIMATION_DURATION);
         anim.scaleCurrentDuration(mWmService.getWindowAnimationScaleLocked());
         final AnimationAdapter adapter = new LocalAnimationAdapter(
-                new WindowAnimationSpec(anim, mSurfacePosition, false /* canSkipFirstFrame */),
+                new WindowAnimationSpec(anim, mSurfacePosition, false /* canSkipFirstFrame */,
+                        mWmService.mWindowCornerRadius),
                 mWmService.mSurfaceAnimationRunner);
         startAnimation(mPendingTransaction, adapter);
         commitPendingTransaction();
@@ -4485,6 +4490,7 @@
 
     @Override
     protected void onAnimationFinished() {
+        super.onAnimationFinished();
         mWinAnimator.onAnimationFinished();
     }
 
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index 2e2da6d..969ced4 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -248,14 +248,6 @@
         mWallpaperControllerLocked = win.getDisplayContent().mWallpaperController;
     }
 
-    void cancelExitAnimationForNextAnimationLocked() {
-        if (DEBUG_ANIM) Slog.d(TAG,
-                "cancelExitAnimationForNextAnimationLocked: " + mWin);
-
-        mWin.cancelAnimation();
-        mWin.destroySurfaceUnchecked();
-    }
-
     void onAnimationFinished() {
         // Done animating, clean up.
         if (DEBUG_ANIM) Slog.v(
diff --git a/services/core/java/com/android/server/wm/WindowTraceBuffer.java b/services/core/java/com/android/server/wm/WindowTraceBuffer.java
index 2ce6e6c..a4ee907 100644
--- a/services/core/java/com/android/server/wm/WindowTraceBuffer.java
+++ b/services/core/java/com/android/server/wm/WindowTraceBuffer.java
@@ -98,9 +98,8 @@
                 ProtoOutputStream proto = new ProtoOutputStream();
                 proto.write(MAGIC_NUMBER, MAGIC_NUMBER_VALUE);
                 os.write(proto.getBytes());
-                while (!mBuffer.isEmpty()) {
-                    proto = mBuffer.poll();
-                    mBufferUsedSize -= proto.getRawSize();
+                for (ProtoOutputStream protoOutputStream : mBuffer) {
+                    proto = protoOutputStream;
                     byte[] protoBytes = proto.getBytes();
                     os.write(protoBytes);
                 }
diff --git a/services/core/java/com/android/server/wm/WindowTracing.java b/services/core/java/com/android/server/wm/WindowTracing.java
index 3b17abc..48b9340 100644
--- a/services/core/java/com/android/server/wm/WindowTracing.java
+++ b/services/core/java/com/android/server/wm/WindowTracing.java
@@ -208,6 +208,7 @@
                 pw.println("  frame: Log trace once per frame");
                 pw.println("  transaction: Log each transaction");
                 pw.println("  size: Set the maximum log size (in KB)");
+                pw.println("  status: Print trace status");
                 pw.println("  level [lvl]: Set the log level between");
                 pw.println("    lvl may be one of:");
                 pw.println("      critical: Only visible windows with reduced information");
diff --git a/services/core/jni/com_android_server_location_GnssLocationProvider.cpp b/services/core/jni/com_android_server_location_GnssLocationProvider.cpp
index fe94168..d39f20c 100644
--- a/services/core/jni/com_android_server_location_GnssLocationProvider.cpp
+++ b/services/core/jni/com_android_server_location_GnssLocationProvider.cpp
@@ -36,13 +36,14 @@
 #include "android_runtime/Log.h"
 
 #include <arpa/inet.h>
+#include <cinttypes>
+#include <iomanip>
 #include <limits>
 #include <linux/in.h>
 #include <linux/in6.h>
 #include <pthread.h>
 #include <string.h>
-#include <cinttypes>
-#include <iomanip>
+#include <utils/SystemClock.h>
 
 static jobject mCallbacksObj = nullptr;
 
@@ -111,10 +112,9 @@
 using android::hardware::hidl_vec;
 using android::hardware::hidl_string;
 using android::hardware::hidl_death_recipient;
-using android::hardware::gnss::V1_0::GnssConstellationType;
-using android::hardware::gnss::V1_0::GnssLocation;
-using android::hardware::gnss::V1_0::GnssLocationFlags;
 
+using android::hardware::gnss::V1_0::GnssConstellationType;
+using android::hardware::gnss::V1_0::GnssLocationFlags;
 using android::hardware::gnss::V1_0::IAGnssRilCallback;
 using android::hardware::gnss::V1_0::IGnssBatching;
 using android::hardware::gnss::V1_0::IGnssBatchingCallback;
@@ -128,13 +128,17 @@
 using android::hardware::gnss::V1_0::IGnssXtra;
 using android::hardware::gnss::V1_0::IGnssXtraCallback;
 
+using android::hardware::gnss::V2_0::ElapsedRealtimeFlags;
 using android::hardware::gnss::V2_0::IGnssCallback;
+
 using android::hardware::gnss::measurement_corrections::V1_0::MeasurementCorrections;
 using android::hardware::gnss::measurement_corrections::V1_0::SingleSatCorrection;
 using android::hardware::gnss::measurement_corrections::V1_0::ReflectingPlane;
 
 using android::hidl::base::V1_0::IBase;
 
+using GnssLocation_V1_0 = android::hardware::gnss::V1_0::GnssLocation;
+using GnssLocation_V2_0 = android::hardware::gnss::V2_0::GnssLocation;
 using IGnss_V1_0 = android::hardware::gnss::V1_0::IGnss;
 using IGnss_V1_1 = android::hardware::gnss::V1_1::IGnss;
 using IGnss_V2_0 = android::hardware::gnss::V2_0::IGnss;
@@ -204,6 +208,20 @@
 
 namespace android {
 
+namespace {
+
+// Returns true if location has lat/long information.
+bool hasLatLong(const GnssLocation_V1_0& location) {
+    return (static_cast<uint32_t>(location.gnssLocationFlags) &
+            GnssLocationFlags::HAS_LAT_LONG) != 0;
+}
+
+// Returns true if location has lat/long information.
+bool hasLatLong(const GnssLocation_V2_0& location) {
+    return hasLatLong(location.v1_0);
+}
+
+}  // namespace
 template<class T>
 class JavaMethodHelper {
  public:
@@ -216,7 +234,7 @@
            T value);
 
  private:
-    static const char *const signature_;
+    static const char* const signature_;
 };
 
 template<class T>
@@ -234,6 +252,8 @@
  public:
     JavaObject(JNIEnv* env, const char* class_name);
     JavaObject(JNIEnv* env, const char* class_name, const char * sz_arg_1);
+    JavaObject(JNIEnv* env, const char* class_name, jobject object);
+
     virtual ~JavaObject();
 
     template<class T>
@@ -260,6 +280,11 @@
     object_ = env_->NewObject(clazz_, ctor, env->NewStringUTF(sz_arg_1));
 }
 
+JavaObject::JavaObject(JNIEnv* env, const char* class_name, jobject object)
+    : env_(env), object_(object) {
+    clazz_ = env_->FindClass(class_name);
+}
+
 JavaObject::~JavaObject() {
     env_->DeleteLocalRef(clazz_);
 }
@@ -303,6 +328,8 @@
 template<>
 const char *const JavaMethodHelper<int64_t>::signature_ = "(J)V";
 template<>
+const char *const JavaMethodHelper<uint64_t>::signature_ = "(J)V";
+template<>
 const char *const JavaMethodHelper<float>::signature_ = "(F)V";
 template<>
 const char *const JavaMethodHelper<double>::signature_ = "(D)V";
@@ -416,7 +443,8 @@
     return env;
 }
 
-static jobject translateLocation(JNIEnv* env, const GnssLocation& location) {
+static jobject translateGnssLocation(JNIEnv* env,
+                                     const GnssLocation_V1_0& location) {
     JavaObject object(env, "android/location/Location", "gps");
 
     uint16_t flags = static_cast<uint32_t>(location.gnssLocationFlags);
@@ -446,23 +474,33 @@
         SET(BearingAccuracyDegrees, location.bearingAccuracyDegrees);
     }
     SET(Time, location.timestamp);
+    SET(ElapsedRealtimeNanos, android::elapsedRealtimeNano());
 
     return object.get();
 }
 
-static GnssLocation createGnssLocation(
-        jint gnssLocationFlags,
-        jdouble latitudeDegrees,
-        jdouble longitudeDegrees,
-        jdouble altitudeMeters,
-        jfloat speedMetersPerSec,
-        jfloat bearingDegrees,
-        jfloat horizontalAccuracyMeters,
-        jfloat verticalAccuracyMeters,
-        jfloat speedAccuracyMetersPerSecond,
-        jfloat bearingAccuracyDegrees,
+static jobject translateGnssLocation(JNIEnv* env,
+                                     const GnssLocation_V2_0& location) {
+    JavaObject object(env, "android/location/Location",
+                      translateGnssLocation(env, location.v1_0));
+
+    const uint16_t flags = static_cast<uint16_t>(location.elapsedRealtime.flags);
+
+    // Overwrite ElapsedRealtimeNanos when available from HAL.
+    if (flags & ElapsedRealtimeFlags::HAS_TIMESTAMP_NS) {
+        SET(ElapsedRealtimeNanos, location.elapsedRealtime.timestampNs);
+    }
+
+    return object.get();
+}
+
+static GnssLocation_V1_0 createGnssLocation_V1_0(
+        jint gnssLocationFlags, jdouble latitudeDegrees, jdouble longitudeDegrees,
+        jdouble altitudeMeters, jfloat speedMetersPerSec, jfloat bearingDegrees,
+        jfloat horizontalAccuracyMeters, jfloat verticalAccuracyMeters,
+        jfloat speedAccuracyMetersPerSecond, jfloat bearingAccuracyDegrees,
         jlong timestamp) {
-    GnssLocation location;
+    GnssLocation_V1_0 location;
     location.gnssLocationFlags = static_cast<uint16_t>(gnssLocationFlags);
     location.latitudeDegrees = static_cast<double>(latitudeDegrees);
     location.longitudeDegrees = static_cast<double>(longitudeDegrees);
@@ -478,11 +516,30 @@
     return location;
 }
 
+static GnssLocation_V2_0 createGnssLocation_V2_0(
+        jint gnssLocationFlags, jdouble latitudeDegrees, jdouble longitudeDegrees,
+        jdouble altitudeMeters, jfloat speedMetersPerSec, jfloat bearingDegrees,
+        jfloat horizontalAccuracyMeters, jfloat verticalAccuracyMeters,
+        jfloat speedAccuracyMetersPerSecond, jfloat bearingAccuracyDegrees,
+        jlong timestamp, jint elapsedRealtimeFlags, jlong elapsedRealtimeNanos) {
+    GnssLocation_V2_0 location;
+    location.v1_0 = createGnssLocation_V1_0(
+            gnssLocationFlags, latitudeDegrees, longitudeDegrees, altitudeMeters,
+            speedMetersPerSec, bearingDegrees, horizontalAccuracyMeters,
+            verticalAccuracyMeters, speedAccuracyMetersPerSecond,
+            bearingAccuracyDegrees, timestamp);
+
+    location.elapsedRealtime.flags = static_cast<uint16_t>(elapsedRealtimeFlags);
+    location.elapsedRealtime.timestampNs = static_cast<uint64_t>(elapsedRealtimeNanos);
+
+    return location;
+}
+
 /*
  * GnssCallback class implements the callback methods for IGnss interface.
  */
 struct GnssCallback : public IGnssCallback {
-    Return<void> gnssLocationCb(const GnssLocation& location) override;
+    Return<void> gnssLocationCb(const GnssLocation_V1_0& location) override;
     Return<void> gnssStatusCb(const IGnssCallback::GnssStatusValue status) override;
     Return<void> gnssSvStatusCb(const IGnssCallback::GnssSvStatus& svStatus) override;
     Return<void> gnssNmeaCb(int64_t timestamp, const android::hardware::hidl_string& nmea) override;
@@ -491,12 +548,21 @@
     Return<void> gnssReleaseWakelockCb() override;
     Return<void> gnssRequestTimeCb() override;
     Return<void> gnssRequestLocationCb(const bool independentFromGnss) override;
+
     Return<void> gnssSetSystemInfoCb(const IGnssCallback::GnssSystemInfo& info) override;
 
     // New in 1.1
     Return<void> gnssNameCb(const android::hardware::hidl_string& name) override;
 
+    // New in 2.0
+    Return<void> gnssRequestLocationCb_2_0(const bool independentFromGnss, const bool isUserEmergency)
+            override;
     Return<void> gnssSetCapabilitiesCb_2_0(uint32_t capabilities) override;
+    Return<void> gnssLocationCb_2_0(const GnssLocation_V2_0& location) override;
+
+    // Templated implementation for gnnsLocationCb and gnnsLocationCb_2_0.
+    template <class T>
+    Return<void> gnssLocationCbImpl(const T& location);
 
     // TODO(b/73306084): Reconsider allocation cost vs threadsafety on these statics
     static const char* sNmeaString;
@@ -517,22 +583,30 @@
 const char* GnssCallback::sNmeaString = nullptr;
 size_t GnssCallback::sNmeaStringLength = 0;
 
-Return<void> GnssCallback::gnssLocationCb(const GnssLocation& location) {
+template<class T>
+Return<void> GnssCallback::gnssLocationCbImpl(const T& location) {
     JNIEnv* env = getJniEnv();
 
-    jobject jLocation = translateLocation(env, location);
-    bool hasLatLong = (static_cast<uint32_t>(location.gnssLocationFlags) &
-            GnssLocationFlags::HAS_LAT_LONG) != 0;
+    jobject jLocation = translateGnssLocation(env, location);
 
     env->CallVoidMethod(mCallbacksObj,
                         method_reportLocation,
-                        boolToJbool(hasLatLong),
+                        boolToJbool(hasLatLong(location)),
                         jLocation);
     checkAndClearExceptionFromCallback(env, __FUNCTION__);
     env->DeleteLocalRef(jLocation);
     return Void();
 }
 
+Return<void> GnssCallback::gnssLocationCb(const GnssLocation_V1_0& location) {
+    return gnssLocationCbImpl<GnssLocation_V1_0>(location);
+}
+
+Return<void>
+GnssCallback::gnssLocationCb_2_0(const GnssLocation_V2_0& location) {
+    return gnssLocationCbImpl<GnssLocation_V2_0>(location);
+}
+
 Return<void> GnssCallback::gnssStatusCb(const IGnssCallback::GnssStatusValue status) {
     JNIEnv* env = getJniEnv();
     env->CallVoidMethod(mCallbacksObj, method_reportStatus, status);
@@ -642,8 +716,15 @@
 }
 
 Return<void> GnssCallback::gnssRequestLocationCb(const bool independentFromGnss) {
+    return GnssCallback::gnssRequestLocationCb_2_0(independentFromGnss, /* isUserEmergency= */
+            false);
+}
+
+Return<void> GnssCallback::gnssRequestLocationCb_2_0(const bool independentFromGnss, const bool
+        isUserEmergency) {
     JNIEnv* env = getJniEnv();
-    env->CallVoidMethod(mCallbacksObj, method_requestLocation, boolToJbool(independentFromGnss));
+    env->CallVoidMethod(mCallbacksObj, method_requestLocation, boolToJbool(independentFromGnss),
+            boolToJbool(isUserEmergency));
     checkAndClearExceptionFromCallback(env, __FUNCTION__);
     return Void();
 }
@@ -681,12 +762,13 @@
     // Methods from ::android::hardware::gps::V1_0::IGnssGeofenceCallback follow.
     Return<void> gnssGeofenceTransitionCb(
             int32_t geofenceId,
-            const GnssLocation& location,
+            const GnssLocation_V1_0& location,
             GeofenceTransition transition,
             hardware::gnss::V1_0::GnssUtcTime timestamp) override;
-    Return<void> gnssGeofenceStatusCb(
+    Return<void>
+    gnssGeofenceStatusCb(
             GeofenceAvailability status,
-            const GnssLocation& location) override;
+            const GnssLocation_V1_0& location) override;
     Return<void> gnssGeofenceAddCb(int32_t geofenceId,
                                    GeofenceStatus status) override;
     Return<void> gnssGeofenceRemoveCb(int32_t geofenceId,
@@ -698,13 +780,12 @@
 };
 
 Return<void> GnssGeofenceCallback::gnssGeofenceTransitionCb(
-        int32_t geofenceId,
-        const GnssLocation& location,
+        int32_t geofenceId, const GnssLocation_V1_0& location,
         GeofenceTransition transition,
         hardware::gnss::V1_0::GnssUtcTime timestamp) {
     JNIEnv* env = getJniEnv();
 
-    jobject jLocation = translateLocation(env, location);
+    jobject jLocation = translateGnssLocation(env, location);
 
     env->CallVoidMethod(mCallbacksObj,
                         method_reportGeofenceTransition,
@@ -718,16 +799,14 @@
     return Void();
 }
 
-Return<void> GnssGeofenceCallback::gnssGeofenceStatusCb(
-        GeofenceAvailability status,
-        const GnssLocation& location) {
+Return<void>
+GnssGeofenceCallback::gnssGeofenceStatusCb(GeofenceAvailability status,
+                                           const GnssLocation_V1_0& location) {
     JNIEnv* env = getJniEnv();
 
-    jobject jLocation = translateLocation(env, location);
+    jobject jLocation = translateGnssLocation(env, location);
 
-    env->CallVoidMethod(mCallbacksObj,
-                        method_reportGeofenceStatus,
-                        status,
+    env->CallVoidMethod(mCallbacksObj, method_reportGeofenceStatus, status,
                         jLocation);
     checkAndClearExceptionFromCallback(env, __FUNCTION__);
     env->DeleteLocalRef(jLocation);
@@ -1296,18 +1375,18 @@
     * Methods from ::android::hardware::gps::V1_0::IGnssBatchingCallback
     * follow.
     */
-    Return<void> gnssLocationBatchCb(const hidl_vec<GnssLocation> & locations)
-        override;
+    Return<void> gnssLocationBatchCb(const hidl_vec<GnssLocation_V1_0>& locations) override;
 };
 
-Return<void> GnssBatchingCallback::gnssLocationBatchCb(const hidl_vec<GnssLocation> & locations) {
+Return<void> GnssBatchingCallback::gnssLocationBatchCb(
+    const hidl_vec<GnssLocation_V1_0>& locations) {
     JNIEnv* env = getJniEnv();
 
     jobjectArray jLocations = env->NewObjectArray(locations.size(),
             env->FindClass("android/location/Location"), nullptr);
 
     for (uint16_t i = 0; i < locations.size(); ++i) {
-        jobject jLocation = translateLocation(env, locations[i]);
+        jobject jLocation = translateGnssLocation(env, locations[i]);
         env->SetObjectArrayElement(jLocations, i, jLocation);
         env->DeleteLocalRef(jLocation);
     }
@@ -1353,7 +1432,7 @@
     method_xtraDownloadRequest = env->GetMethodID(clazz, "xtraDownloadRequest", "()V");
     method_reportNiNotification = env->GetMethodID(clazz, "reportNiNotification",
             "(IIIIILjava/lang/String;Ljava/lang/String;II)V");
-    method_requestLocation = env->GetMethodID(clazz, "requestLocation", "(Z)V");
+    method_requestLocation = env->GetMethodID(clazz, "requestLocation", "(ZZ)V");
     method_requestRefLocation = env->GetMethodID(clazz, "requestRefLocation", "()V");
     method_requestSetID = env->GetMethodID(clazz, "requestSetID", "(I)V");
     method_requestUtcTime = env->GetMethodID(clazz, "requestUtcTime", "()V");
@@ -1760,7 +1839,7 @@
     agnssRilIface->setRefLocation(location);
 }
 
-static void android_location_GnssLocationProvider_agps_set_id(JNIEnv *env, jobject /* obj */,
+static void android_location_GnssLocationProvider_agps_set_id(JNIEnv* env, jobject /* obj */,
                                                              jint type, jstring  setid_string) {
     if (agnssRilIface == nullptr) {
         ALOGE("no AGPS RIL interface in agps_set_id");
@@ -1806,9 +1885,34 @@
         jfloat verticalAccuracyMeters,
         jfloat speedAccuracyMetersPerSecond,
         jfloat bearingAccuracyDegrees,
-        jlong timestamp) {
+        jlong timestamp,
+        jint elapsedRealtimeFlags,
+        jlong elapsedRealtimeNanos) {
+    if (gnssHal_V2_0 != nullptr) {
+        GnssLocation_V2_0 location = createGnssLocation_V2_0(
+                gnssLocationFlags,
+                latitudeDegrees,
+                longitudeDegrees,
+                altitudeMeters,
+                speedMetersPerSec,
+                bearingDegrees,
+                horizontalAccuracyMeters,
+                verticalAccuracyMeters,
+                speedAccuracyMetersPerSecond,
+                bearingAccuracyDegrees,
+                timestamp,
+                elapsedRealtimeFlags,
+                elapsedRealtimeNanos);
+        auto result = gnssHal_V2_0->injectBestLocation_2_0(location);
+
+        if (!result.isOk() || !result) {
+            ALOGE("%s: Gnss injectBestLocation() failed.", __func__);
+        }
+        return;
+    }
+
     if (gnssHal_V1_1 != nullptr) {
-        GnssLocation location = createGnssLocation(
+        GnssLocation_V1_0 location = createGnssLocation_V1_0(
                 gnssLocationFlags,
                 latitudeDegrees,
                 longitudeDegrees,
@@ -1821,12 +1925,14 @@
                 bearingAccuracyDegrees,
                 timestamp);
         auto result = gnssHal_V1_1->injectBestLocation(location);
+
         if (!result.isOk() || !result) {
             ALOGE("%s: Gnss injectBestLocation() failed.", __func__);
         }
-    } else {
-        ALOGE("%s: injectBestLocation() is called but gnssHal_V1_1 is not available.", __func__);
+        return;
     }
+
+    ALOGE("%s: injectBestLocation() is called but gnssHal_V1_1 is not available.", __func__);
 }
 
 static void android_location_GnssLocationProvider_inject_location(JNIEnv* /* env */,
@@ -2695,45 +2801,36 @@
     {"native_init", "()Z", reinterpret_cast<void *>(android_location_GnssLocationProvider_init)},
     {"native_cleanup", "()V", reinterpret_cast<void *>(
             android_location_GnssLocationProvider_cleanup)},
-    {"native_set_position_mode",
-            "(IIIIIZ)Z",
-            reinterpret_cast<void*>(android_location_GnssLocationProvider_set_position_mode)},
-    {"native_start", "()Z", reinterpret_cast<void*>(android_location_GnssLocationProvider_start)},
-    {"native_stop", "()Z", reinterpret_cast<void*>(android_location_GnssLocationProvider_stop)},
-    {"native_delete_aiding_data",
-            "(I)V",
-            reinterpret_cast<void*>(android_location_GnssLocationProvider_delete_aiding_data)},
+    {"native_set_position_mode", "(IIIIIZ)Z", reinterpret_cast<void *>(
+            android_location_GnssLocationProvider_set_position_mode)},
+    {"native_start", "()Z", reinterpret_cast<void *>(
+            android_location_GnssLocationProvider_start)},
+    {"native_stop", "()Z", reinterpret_cast<void *>(
+            android_location_GnssLocationProvider_stop)},
+    {"native_delete_aiding_data", "(I)V", reinterpret_cast<void *>(
+            android_location_GnssLocationProvider_delete_aiding_data)},
     {"native_read_nmea", "([BI)I", reinterpret_cast<void *>(
             android_location_GnssLocationProvider_read_nmea)},
     {"native_inject_time", "(JJI)V", reinterpret_cast<void *>(
             android_location_GnssLocationProvider_inject_time)},
-    {"native_inject_best_location",
-            "(IDDDFFFFFFJ)V",
-            reinterpret_cast<void *>(android_location_GnssLocationProvider_inject_best_location)},
-    {"native_inject_location",
-            "(DDF)V",
-            reinterpret_cast<void *>(android_location_GnssLocationProvider_inject_location)},
+    {"native_inject_best_location", "(IDDDFFFFFFJIJ)V", reinterpret_cast<void *>(
+            android_location_GnssLocationProvider_inject_best_location)},
+    {"native_inject_location", "(DDF)V", reinterpret_cast<void *>(
+            android_location_GnssLocationProvider_inject_location)},
     {"native_supports_xtra", "()Z", reinterpret_cast<void *>(
             android_location_GnssLocationProvider_supports_xtra)},
-    {"native_inject_xtra_data",
-            "([BI)V",
-            reinterpret_cast<void *>(android_location_GnssLocationProvider_inject_xtra_data)},
-    {"native_agps_set_id",
-            "(ILjava/lang/String;)V",
-            reinterpret_cast<void *>(android_location_GnssLocationProvider_agps_set_id)},
-    {"native_agps_set_ref_location_cellid",
-            "(IIIII)V",
-            reinterpret_cast<void *>(
-                    android_location_GnssLocationProvider_agps_set_reference_location_cellid)},
-    {"native_set_agps_server",
-            "(ILjava/lang/String;I)V",
-            reinterpret_cast<void *>(android_location_GnssLocationProvider_set_agps_server)},
-    {"native_send_ni_response",
-            "(II)V",
-            reinterpret_cast<void *>(android_location_GnssLocationProvider_send_ni_response)},
-    {"native_get_internal_state",
-            "()Ljava/lang/String;",
-            reinterpret_cast<void *>(android_location_GnssLocationProvider_get_internal_state)},
+    {"native_inject_xtra_data", "([BI)V", reinterpret_cast<void *>(
+            android_location_GnssLocationProvider_inject_xtra_data)},
+    {"native_agps_set_id", "(ILjava/lang/String;)V", reinterpret_cast<void *>(
+            android_location_GnssLocationProvider_agps_set_id)},
+    {"native_agps_set_ref_location_cellid", "(IIIII)V", reinterpret_cast<void *>(
+            android_location_GnssLocationProvider_agps_set_reference_location_cellid)},
+    {"native_set_agps_server", "(ILjava/lang/String;I)V", reinterpret_cast<void *>(
+            android_location_GnssLocationProvider_set_agps_server)},
+    {"native_send_ni_response", "(II)V", reinterpret_cast<void *>(
+            android_location_GnssLocationProvider_send_ni_response)},
+    {"native_get_internal_state", "()Ljava/lang/String;", reinterpret_cast<void *>(
+            android_location_GnssLocationProvider_get_internal_state)},
     {"native_is_gnss_visibility_control_supported", "()Z", reinterpret_cast<void *>(
             android_location_GnssLocationProvider_is_gnss_visibility_control_supported)},
 };
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index 3070488..f496e81 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -5046,7 +5046,8 @@
             if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
                 quality = PASSWORD_QUALITY_UNSPECIFIED;
             }
-            final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password);
+            // TODO(b/120484642): remove getBytes() below
+            final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password.getBytes());
             final int realQuality = metrics.quality;
             if (realQuality < quality
                     && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
@@ -5133,16 +5134,22 @@
         try {
             if (token == null) {
                 if (!TextUtils.isEmpty(password)) {
-                    mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
+                    mLockPatternUtils.saveLockPassword(password.getBytes(), null, quality,
+                            userHandle);
                 } else {
                     mLockPatternUtils.clearLock(null, userHandle);
                 }
                 result = true;
             } else {
-                result = mLockPatternUtils.setLockCredentialWithToken(password,
-                        TextUtils.isEmpty(password) ? LockPatternUtils.CREDENTIAL_TYPE_NONE
-                                : LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
-                        quality, tokenHandle, token, userHandle);
+                if (!TextUtils.isEmpty(password)) {
+                    result = mLockPatternUtils.setLockCredentialWithToken(password.getBytes(),
+                            LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
+                            quality, tokenHandle, token, userHandle);
+                } else {
+                    result = mLockPatternUtils.setLockCredentialWithToken(null,
+                            LockPatternUtils.CREDENTIAL_TYPE_NONE,
+                            quality, tokenHandle, token, userHandle);
+                }
             }
             boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
             if (requireEntry) {
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 8d88c5a..a19d5d5 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -89,8 +89,8 @@
 import com.android.server.connectivity.IpConnectivityMetrics;
 import com.android.server.coverage.CoverageService;
 import com.android.server.devicepolicy.DevicePolicyManagerService;
-import com.android.server.display.ColorDisplayService;
 import com.android.server.display.DisplayManagerService;
+import com.android.server.display.color.ColorDisplayService;
 import com.android.server.dreams.DreamManagerService;
 import com.android.server.emergency.EmergencyAffordanceService;
 import com.android.server.gpu.GpuService;
@@ -1366,7 +1366,6 @@
                 ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity,
                         /* allowIsolated= */ false,
                         DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL);
-                networkStats.bindConnectivityManager(connectivity);
                 networkPolicy.bindConnectivityManager(connectivity);
             } catch (Throwable e) {
                 reportWtf("starting Connectivity Service", e);
diff --git a/services/net/java/android/net/NetworkStackClient.java b/services/net/java/android/net/NetworkStackClient.java
index 1eb7b98..830dbbe 100644
--- a/services/net/java/android/net/NetworkStackClient.java
+++ b/services/net/java/android/net/NetworkStackClient.java
@@ -30,6 +30,7 @@
 import android.net.dhcp.DhcpServingParamsParcel;
 import android.net.dhcp.IDhcpServerCallbacks;
 import android.net.ip.IIpClientCallbacks;
+import android.net.util.SharedLog;
 import android.os.Binder;
 import android.os.IBinder;
 import android.os.Process;
@@ -40,6 +41,7 @@
 
 import com.android.internal.annotations.GuardedBy;
 
+import java.io.PrintWriter;
 import java.lang.reflect.InvocationTargetException;
 import java.util.ArrayList;
 
@@ -61,6 +63,9 @@
     @GuardedBy("mPendingNetStackRequests")
     private INetworkStackConnector mConnector;
 
+    @GuardedBy("mLog")
+    private final SharedLog mLog = new SharedLog(TAG);
+
     private volatile boolean mNetworkStackStartRequested = false;
 
     private interface NetworkStackCallback {
@@ -129,13 +134,14 @@
     private class NetworkStackConnection implements ServiceConnection {
         @Override
         public void onServiceConnected(ComponentName name, IBinder service) {
+            log("Network stack service connected");
             registerNetworkStackService(service);
         }
 
         @Override
         public void onServiceDisconnected(ComponentName name) {
             // TODO: crash/reboot the system ?
-            Slog.wtf(TAG, "Lost network stack connector");
+            logWtf("Lost network stack connector", null);
         }
     };
 
@@ -144,6 +150,7 @@
 
         ServiceManager.addService(Context.NETWORK_STACK_SERVICE, service, false /* allowIsolated */,
                 DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL);
+        log("Network stack service registered");
 
         final ArrayList<NetworkStackCallback> requests;
         synchronized (mPendingNetStackRequests) {
@@ -166,6 +173,7 @@
      * started.
      */
     public void start(Context context) {
+        log("Starting network stack");
         mNetworkStackStartRequested = true;
         // Try to bind in-process if the library is available
         IBinder connector = null;
@@ -177,7 +185,7 @@
             connector = (IBinder) service.getMethod("makeConnector", Context.class)
                     .invoke(null, context);
         } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
-            Slog.wtf(TAG, "Could not create network stack connector from NetworkStackService");
+            logWtf("Could not create network stack connector from NetworkStackService", e);
             // TODO: crash/reboot system here ?
             return;
         } catch (ClassNotFoundException e) {
@@ -186,26 +194,28 @@
 
         // In-process network stack. Add the service to the service manager here.
         if (connector != null) {
+            log("Registering in-process network stack connector");
             registerNetworkStackService(connector);
             return;
         }
         // Start the network stack process. The service will be added to the service manager in
         // NetworkStackConnection.onServiceConnected().
+        log("Starting network stack process");
         final Intent intent = new Intent(INetworkStackConnector.class.getName());
         final ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
         intent.setComponent(comp);
 
         if (comp == null) {
-            Slog.wtf(TAG, "Could not resolve the network stack with " + intent);
+            logWtf("Could not resolve the network stack with " + intent, null);
             // TODO: crash/reboot system server ?
             return;
         }
         final PackageManager pm = context.getPackageManager();
         int uid = -1;
         try {
-            uid = pm.getPackageUid(comp.getPackageName(), UserHandle.USER_SYSTEM);
+            uid = pm.getPackageUidAsUser(comp.getPackageName(), UserHandle.USER_SYSTEM);
         } catch (PackageManager.NameNotFoundException e) {
-            Slog.wtf("Network stack package not found", e);
+            logWtf("Network stack package not found", e);
             // Fall through
         }
         if (uid != Process.NETWORK_STACK_UID) {
@@ -221,10 +231,31 @@
 
         if (!context.bindServiceAsUser(intent, new NetworkStackConnection(),
                 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.SYSTEM)) {
-            Slog.wtf(TAG,
-                    "Could not bind to network stack in-process, or in app with " + intent);
+            logWtf("Could not bind to network stack in-process, or in app with " + intent, null);
+            return;
             // TODO: crash/reboot system server if no network stack after a timeout ?
         }
+
+        log("Network stack service start requested");
+    }
+
+    private void log(@NonNull String message) {
+        synchronized (mLog) {
+            mLog.log(message);
+        }
+    }
+
+    private void logWtf(@NonNull String message, @Nullable Throwable e) {
+        Slog.wtf(TAG, message);
+        synchronized (mLog) {
+            mLog.e(message, e);
+        }
+    }
+
+    private void loge(@NonNull String message, @Nullable Throwable e) {
+        synchronized (mLog) {
+            mLog.e(message, e);
+        }
     }
 
     /**
@@ -243,12 +274,12 @@
             while ((connector = ServiceManager.getService(Context.NETWORK_STACK_SERVICE)) == null) {
                 Thread.sleep(20);
                 if (System.currentTimeMillis() - before > NETWORKSTACK_TIMEOUT_MS) {
-                    Slog.e(TAG, "Timeout waiting for NetworkStack connector");
+                    loge("Timeout waiting for NetworkStack connector", null);
                     return null;
                 }
             }
         } catch (InterruptedException e) {
-            Slog.e(TAG, "Error waiting for NetworkStack connector", e);
+            loge("Error waiting for NetworkStack connector", e);
             return null;
         }
 
@@ -286,4 +317,20 @@
 
         request.onNetworkStackConnected(connector);
     }
+
+    /**
+     * Dump NetworkStackClient logs to the specified {@link PrintWriter}.
+     */
+    public void dump(PrintWriter pw) {
+        // dump is thread-safe on SharedLog
+        mLog.dump(null, pw, null);
+
+        final int requestsQueueLength;
+        synchronized (mPendingNetStackRequests) {
+            requestsQueueLength = mPendingNetStackRequests.size();
+        }
+
+        pw.println();
+        pw.println("pendingNetStackRequests length: " + requestsQueueLength);
+    }
 }
diff --git a/services/net/java/android/net/ip/RouterAdvertisementDaemon.java b/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
index 8e3023b..339607b 100644
--- a/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
+++ b/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
@@ -275,6 +275,9 @@
 
     public void stop() {
         closeSocket();
+        // Wake up mMulticastTransmitter thread to interrupt a potential 1 day sleep before
+        // the thread's termination.
+        maybeNotifyMulticastTransmitter();
         mMulticastTransmitter = null;
         mUnicastResponder = null;
     }
diff --git a/services/tests/mockingservicestests/Android.bp b/services/tests/mockingservicestests/Android.bp
index ebc816d..782196d 100644
--- a/services/tests/mockingservicestests/Android.bp
+++ b/services/tests/mockingservicestests/Android.bp
@@ -23,6 +23,7 @@
         "androidx.test.runner",
         "mockito-target-extended-minus-junit4",
         "platform-test-annotations",
+        "truth-prebuilt",
     ],
 
     libs: [
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/AppCompactorTest.java b/services/tests/mockingservicestests/src/com/android/server/am/AppCompactorTest.java
new file mode 100644
index 0000000..e100d16
--- /dev/null
+++ b/services/tests/mockingservicestests/src/com/android/server/am/AppCompactorTest.java
@@ -0,0 +1,412 @@
+/*
+ * 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.am;
+
+import static com.android.server.am.ActivityManagerService.Injector;
+import static com.android.server.am.AppCompactor.compactActionIntToString;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.provider.DeviceConfig;
+
+import com.android.server.appop.AppOpsService;
+import com.android.server.testables.TestableDeviceConfig;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import java.io.File;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Tests for {@link AppCompactor}.
+ *
+ * Build/Install/Run:
+ * atest FrameworksServicesTests:AppCompactorTest
+ */
+@RunWith(MockitoJUnitRunner.class)
+public final class AppCompactorTest {
+
+    @Mock
+    private AppOpsService mAppOpsService;
+    private AppCompactor mCompactorUnderTest;
+    private HandlerThread mHandlerThread;
+    private Handler mHandler;
+    private CountDownLatch mCountDown;
+
+    @Rule
+    public TestableDeviceConfig mDeviceConfig = new TestableDeviceConfig();
+
+    @Before
+    public void setUp() {
+        mHandlerThread = new HandlerThread("");
+        mHandlerThread.start();
+        mHandler = new Handler(mHandlerThread.getLooper());
+        ActivityManagerService ams = new ActivityManagerService(new TestInjector());
+        mCompactorUnderTest = new AppCompactor(ams,
+                new AppCompactor.PropertyChangedCallbackForTest() {
+                    @Override
+                    public void onPropertyChanged() {
+                        if (mCountDown != null) {
+                            mCountDown.countDown();
+                        }
+                    }
+                });
+    }
+
+    @After
+    public void tearDown() {
+        mHandlerThread.quit();
+        mCountDown = null;
+    }
+
+    @Test
+    public void init_setsDefaults() {
+        mCompactorUnderTest.init();
+        assertThat(mCompactorUnderTest.useCompaction()).isEqualTo(
+                AppCompactor.DEFAULT_USE_COMPACTION);
+        assertThat(mCompactorUnderTest.mCompactActionSome).isEqualTo(
+                compactActionIntToString(AppCompactor.DEFAULT_COMPACT_ACTION_1));
+        assertThat(mCompactorUnderTest.mCompactActionFull).isEqualTo(
+                compactActionIntToString(AppCompactor.DEFAULT_COMPACT_ACTION_2));
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_1);
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_2);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_3);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_4);
+        assertThat(mCompactorUnderTest.mStatsdSampleRate).isEqualTo(
+                AppCompactor.DEFAULT_STATSD_SAMPLE_RATE);
+    }
+
+    @Test
+    public void init_withDeviceConfigSetsParameters() {
+        // When the DeviceConfig already has a flag value stored (note this test will need to
+        // change if the default value changes from false).
+        assertThat(AppCompactor.DEFAULT_USE_COMPACTION).isFalse();
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_USE_COMPACTION, "true", false);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_ACTION_1,
+                Integer.toString((AppCompactor.DEFAULT_COMPACT_ACTION_1 + 1 % 4) + 1), false);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_ACTION_2,
+                Integer.toString((AppCompactor.DEFAULT_COMPACT_ACTION_2 + 1 % 4) + 1), false);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_THROTTLE_1,
+                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_1 + 1), false);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_THROTTLE_2,
+                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_2 + 1), false);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_THROTTLE_3,
+                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_3 + 1), false);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_THROTTLE_4,
+                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_4 + 1), false);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_STATSD_SAMPLE_RATE,
+                Float.toString(AppCompactor.DEFAULT_STATSD_SAMPLE_RATE + 0.1f), false);
+
+        // Then calling init will read and set that flag.
+        mCompactorUnderTest.init();
+        assertThat(mCompactorUnderTest.useCompaction()).isTrue();
+        assertThat(mCompactorUnderTest.mCompactionThread.isAlive()).isTrue();
+
+        assertThat(mCompactorUnderTest.mCompactActionSome).isEqualTo(
+                compactActionIntToString((AppCompactor.DEFAULT_COMPACT_ACTION_1 + 1 % 4) + 1));
+        assertThat(mCompactorUnderTest.mCompactActionFull).isEqualTo(
+                compactActionIntToString((AppCompactor.DEFAULT_COMPACT_ACTION_2 + 1 % 4) + 1));
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_1 + 1);
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_2 + 1);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_3 + 1);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_4 + 1);
+        assertThat(mCompactorUnderTest.mStatsdSampleRate).isEqualTo(
+                AppCompactor.DEFAULT_STATSD_SAMPLE_RATE + 0.1f);
+    }
+
+    @Test
+    public void useCompaction_listensToDeviceConfigChanges() throws InterruptedException {
+        assertThat(mCompactorUnderTest.useCompaction()).isEqualTo(
+                AppCompactor.DEFAULT_USE_COMPACTION);
+        // When we call init and change some the flag value...
+        mCompactorUnderTest.init();
+        mCountDown = new CountDownLatch(1);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_USE_COMPACTION, "true", false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+
+        // Then that new flag value is updated in the implementation.
+        assertThat(mCompactorUnderTest.useCompaction()).isTrue();
+        assertThat(mCompactorUnderTest.mCompactionThread.isAlive()).isTrue();
+
+        // And again, setting the flag the other way.
+        mCountDown = new CountDownLatch(1);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_USE_COMPACTION, "false", false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+        assertThat(mCompactorUnderTest.useCompaction()).isFalse();
+    }
+
+    @Test
+    public void useCompaction_listensToDeviceConfigChangesBadValues() throws InterruptedException {
+        assertThat(mCompactorUnderTest.useCompaction()).isEqualTo(
+                AppCompactor.DEFAULT_USE_COMPACTION);
+        mCompactorUnderTest.init();
+
+        // When we push an invalid flag value...
+        mCountDown = new CountDownLatch(1);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_USE_COMPACTION, "foobar", false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+
+        // Then we set the default.
+        assertThat(mCompactorUnderTest.useCompaction()).isEqualTo(
+                AppCompactor.DEFAULT_USE_COMPACTION);
+    }
+
+    @Test
+    public void compactAction_listensToDeviceConfigChanges() throws InterruptedException {
+        mCompactorUnderTest.init();
+
+        // When we override new values for the compaction action with reasonable values...
+
+        // There are four possible values for compactAction[Some|Full].
+        for (int i = 1; i < 5; i++) {
+            mCountDown = new CountDownLatch(2);
+            int expectedSome = (AppCompactor.DEFAULT_COMPACT_ACTION_1 + i) % 4 + 1;
+            DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                    AppCompactor.KEY_COMPACT_ACTION_1, Integer.toString(expectedSome), false);
+            int expectedFull = (AppCompactor.DEFAULT_COMPACT_ACTION_2 + i) % 4 + 1;
+            DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                    AppCompactor.KEY_COMPACT_ACTION_2, Integer.toString(expectedFull), false);
+            assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+
+            // Then the updates are reflected in the flags.
+            assertThat(mCompactorUnderTest.mCompactActionSome).isEqualTo(
+                    compactActionIntToString(expectedSome));
+            assertThat(mCompactorUnderTest.mCompactActionFull).isEqualTo(
+                    compactActionIntToString(expectedFull));
+        }
+    }
+
+    @Test
+    public void compactAction_listensToDeviceConfigChangesBadValues() throws InterruptedException {
+        mCompactorUnderTest.init();
+
+        // When we override new values for the compaction action with bad values ...
+        mCountDown = new CountDownLatch(2);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_ACTION_1, "foo", false);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_ACTION_2, "foo", false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+
+        // Then the default values are reflected in the flag
+        assertThat(mCompactorUnderTest.mCompactActionSome).isEqualTo(
+                compactActionIntToString(AppCompactor.DEFAULT_COMPACT_ACTION_1));
+        assertThat(mCompactorUnderTest.mCompactActionFull).isEqualTo(
+                compactActionIntToString(AppCompactor.DEFAULT_COMPACT_ACTION_2));
+
+        mCountDown = new CountDownLatch(2);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_ACTION_1, "", false);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_ACTION_2, "", false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+
+        assertThat(mCompactorUnderTest.mCompactActionSome).isEqualTo(
+                compactActionIntToString(AppCompactor.DEFAULT_COMPACT_ACTION_1));
+        assertThat(mCompactorUnderTest.mCompactActionFull).isEqualTo(
+                compactActionIntToString(AppCompactor.DEFAULT_COMPACT_ACTION_2));
+    }
+
+    @Test
+    public void compactThrottle_listensToDeviceConfigChanges() throws InterruptedException {
+        mCompactorUnderTest.init();
+
+        // When we override new reasonable throttle values after init...
+        mCountDown = new CountDownLatch(4);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_THROTTLE_1,
+                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_1 + 1), false);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_THROTTLE_2,
+                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_2 + 1), false);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_THROTTLE_3,
+                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_3 + 1), false);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_THROTTLE_4,
+                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_4 + 1), false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+
+        // Then those flags values are reflected in the compactor.
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_1 + 1);
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_2 + 1);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_3 + 1);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_4 + 1);
+    }
+
+    @Test
+    public void compactThrottle_listensToDeviceConfigChangesBadValues()
+            throws InterruptedException {
+        mCompactorUnderTest.init();
+
+        // When one of the throttles is overridden with a bad value...
+        mCountDown = new CountDownLatch(1);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_THROTTLE_1, "foo", false);
+        // Then all the throttles have the defaults set.
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_1);
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_2);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_3);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_4);
+
+        // Repeat for each of the throttle keys.
+        mCountDown = new CountDownLatch(1);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_THROTTLE_2, "foo", false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_1);
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_2);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_3);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_4);
+
+        mCountDown = new CountDownLatch(1);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_THROTTLE_3, "foo", false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_1);
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_2);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_3);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_4);
+
+        mCountDown = new CountDownLatch(1);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_THROTTLE_4, "foo", false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_1);
+        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_2);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullSome).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_3);
+        assertThat(mCompactorUnderTest.mCompactThrottleFullFull).isEqualTo(
+                AppCompactor.DEFAULT_COMPACT_THROTTLE_4);
+    }
+
+    @Test
+    public void statsdSampleRate_listensToDeviceConfigChanges() throws InterruptedException {
+        mCompactorUnderTest.init();
+
+        // When we override mStatsdSampleRate with a reasonable values ...
+        mCountDown = new CountDownLatch(1);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_STATSD_SAMPLE_RATE,
+                Float.toString(AppCompactor.DEFAULT_STATSD_SAMPLE_RATE + 0.1f), false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+
+        // Then that override is reflected in the compactor.
+        assertThat(mCompactorUnderTest.mStatsdSampleRate).isEqualTo(
+                AppCompactor.DEFAULT_STATSD_SAMPLE_RATE + 0.1f);
+    }
+
+    @Test
+    public void statsdSanokeRate_listensToDeviceConfigChangesBadValues()
+            throws InterruptedException {
+        mCompactorUnderTest.init();
+
+        // When we override mStatsdSampleRate with a reasonable values ...
+        mCountDown = new CountDownLatch(1);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_STATSD_SAMPLE_RATE, "foo", false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+
+        // Then that override is reflected in the compactor.
+        assertThat(mCompactorUnderTest.mStatsdSampleRate).isEqualTo(
+                AppCompactor.DEFAULT_STATSD_SAMPLE_RATE);
+    }
+
+    @Test
+    public void statsdSanokeRate_listensToDeviceConfigChangesOutOfRangeValues()
+            throws InterruptedException {
+        mCompactorUnderTest.init();
+
+        // When we override mStatsdSampleRate with an value outside of [0..1]...
+        mCountDown = new CountDownLatch(1);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_STATSD_SAMPLE_RATE,
+                Float.toString(-1.0f), false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+
+        // Then the values is capped in the range.
+        assertThat(mCompactorUnderTest.mStatsdSampleRate).isEqualTo(0.0f);
+
+        mCountDown = new CountDownLatch(1);
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                AppCompactor.KEY_COMPACT_STATSD_SAMPLE_RATE,
+                Float.toString(1.01f), false);
+        assertThat(mCountDown.await(5, TimeUnit.SECONDS)).isTrue();
+
+        // Then the values is capped in the range.
+        assertThat(mCompactorUnderTest.mStatsdSampleRate).isEqualTo(1.0f);
+    }
+
+    private class TestInjector extends Injector {
+        @Override
+        public AppOpsService getAppOpsService(File file, Handler handler) {
+            return mAppOpsService;
+        }
+
+        @Override
+        public Handler getUiHandler(ActivityManagerService service) {
+            return mHandler;
+        }
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/am/SettingsToPropertiesMapperTest.java b/services/tests/mockingservicestests/src/com/android/server/am/SettingsToPropertiesMapperTest.java
similarity index 60%
rename from services/tests/servicestests/src/com/android/server/am/SettingsToPropertiesMapperTest.java
rename to services/tests/mockingservicestests/src/com/android/server/am/SettingsToPropertiesMapperTest.java
index 0fd5921..5db8867 100644
--- a/services/tests/servicestests/src/com/android/server/am/SettingsToPropertiesMapperTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/SettingsToPropertiesMapperTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2018 The Android Open Source Project
+ * Copyright (C) 2019 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -16,52 +16,98 @@
 
 package com.android.server.am;
 
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.any;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.anyString;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doAnswer;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
+
 import android.content.ContentResolver;
+import android.os.SystemProperties;
 import android.provider.Settings;
-import android.test.mock.MockContentResolver;
 import android.text.TextUtils;
 
-import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
+import com.android.dx.mockito.inline.extended.ExtendedMockito;
 
-import com.android.internal.util.Preconditions;
-import com.android.internal.util.test.FakeSettingsProvider;
-
+import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.mockito.Answers;
+import org.mockito.Mock;
+import org.mockito.MockitoSession;
+import org.mockito.quality.Strictness;
+import org.mockito.stubbing.Answer;
 
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Map;
 
 /**
- * Tests for {@link SettingsToPropertiesMapper}
- *
- *  Build/Install/Run:
- *  atest FrameworksServicesTests:SettingsToPropertiesMapperTest
+ * Test SettingsToPropertiesMapper.
  */
-@RunWith(AndroidJUnit4.class)
-@SmallTest
 public class SettingsToPropertiesMapperTest {
     private static final String NAME_VALID_CHARACTERS_REGEX = "^[\\w\\-@:]*$";
     private static final String[] TEST_MAPPING = new String[] {
             Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS
     };
 
-    private TestMapper mTestMapper;
-    private MockContentResolver mMockContentResolver;
+    private MockitoSession mSession;
+
+    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
+    private ContentResolver mMockContentResolver;
+
+    private SettingsToPropertiesMapper mTestMapper;
+
+    private HashMap<String, String> mSystemSettingsMap;
+    private HashMap<String, String> mGlobalSettingsMap;
 
     @Before
-    public void setupForEach() {
-        // Use FakeSettingsProvider to not affect global state
-        mMockContentResolver = new MockContentResolver(InstrumentationRegistry.getContext());
-        mMockContentResolver.addProvider(Settings.AUTHORITY, new FakeSettingsProvider());
-        mTestMapper = new TestMapper(mMockContentResolver);
+    public void setUp() throws Exception {
+        mSession =
+                ExtendedMockito.mockitoSession().initMocks(
+                        this)
+                        .strictness(Strictness.LENIENT)
+                        .spyStatic(SystemProperties.class)
+                        .spyStatic(Settings.Global.class)
+                        .spyStatic(SettingsToPropertiesMapper.class)
+                        .startMocking();
+        mSystemSettingsMap = new HashMap<>();
+        mGlobalSettingsMap = new HashMap<>();
+
+        // Mock SystemProperties setter and various getters
+        doAnswer((Answer<Void>) invocationOnMock -> {
+                    String key = invocationOnMock.getArgument(0);
+                    String value = invocationOnMock.getArgument(1);
+
+                    mSystemSettingsMap.put(key, value);
+                    return null;
+                }
+        ).when(() -> SystemProperties.set(anyString(), anyString()));
+
+        doAnswer((Answer<String>) invocationOnMock -> {
+                    String key = invocationOnMock.getArgument(0);
+
+                    String storedValue = mSystemSettingsMap.get(key);
+                    return storedValue == null ? "" : storedValue;
+                }
+        ).when(() -> SystemProperties.get(anyString()));
+
+        // Mock Settings.Global methods
+        doAnswer((Answer<String>) invocationOnMock -> {
+                    String key = invocationOnMock.getArgument(1);
+
+                    return mGlobalSettingsMap.get(key);
+                }
+        ).when(() -> Settings.Global.getString(any(), anyString()));
+
+        mTestMapper = new SettingsToPropertiesMapper(
+            mMockContentResolver, TEST_MAPPING, new String[] {});
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        mSession.finishMocking();
     }
 
     @Test
@@ -108,30 +154,27 @@
 
     @Test
     public void testUpdatePropertiesFromSettings() {
-        Settings.Global.putString(mMockContentResolver,
-                Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS, "testValue");
+        mGlobalSettingsMap.put(Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS, "testValue");
 
         String systemPropertyName = "persist.device_config.global_settings."
                 + "sqlite_compatibility_wal_flags";
 
         mTestMapper.updatePropertiesFromSettings();
-        String propValue = mTestMapper.systemPropertiesGet(systemPropertyName);
+        String propValue = mSystemSettingsMap.get(systemPropertyName);
         Assert.assertEquals("testValue", propValue);
 
-        Settings.Global.putString(mMockContentResolver,
-                Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS, "testValue2");
+        mGlobalSettingsMap.put(Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS, "testValue2");
         mTestMapper.updatePropertyFromSetting(
                 Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS,
                 systemPropertyName);
-        propValue = mTestMapper.systemPropertiesGet(systemPropertyName);
+        propValue = mSystemSettingsMap.get(systemPropertyName);
         Assert.assertEquals("testValue2", propValue);
 
-        Settings.Global.putString(mMockContentResolver,
-                Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS, null);
+        mGlobalSettingsMap.put(Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS, null);
         mTestMapper.updatePropertyFromSetting(
                 Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS,
                 systemPropertyName);
-        propValue = mTestMapper.systemPropertiesGet(systemPropertyName);
+        propValue = mSystemSettingsMap.get(systemPropertyName);
         Assert.assertEquals("", propValue);
     }
 
@@ -163,71 +206,37 @@
     public void testUpdatePropertiesFromSettings_PropertyAndSettingNotPresent() {
         // Test that empty property will not not be set if setting is not set
         mTestMapper.updatePropertiesFromSettings();
-        String propValue = mTestMapper.systemPropertiesGet("TestProperty");
+        String propValue = mSystemSettingsMap.get("TestProperty");
         Assert.assertNull("Property should not be set if setting is null", propValue);
     }
 
     @Test
     public void testIsNativeFlagsResetPerformed() {
-        mTestMapper.systemPropertiesSet("device_config.reset_performed", "true");
+        mSystemSettingsMap.put("device_config.reset_performed", "true");
         Assert.assertTrue(mTestMapper.isNativeFlagsResetPerformed());
 
-        mTestMapper.systemPropertiesSet("device_config.reset_performed", "false");
+        mSystemSettingsMap.put("device_config.reset_performed", "false");
         Assert.assertFalse(mTestMapper.isNativeFlagsResetPerformed());
 
-        mTestMapper.systemPropertiesSet("device_config.reset_performed", "");
+        mSystemSettingsMap.put("device_config.reset_performed", "");
         Assert.assertFalse(mTestMapper.isNativeFlagsResetPerformed());
     }
 
     @Test
     public void testGetResetNativeCategories() {
-        mTestMapper.systemPropertiesSet("device_config.reset_performed", "");
-        Assert.assertEquals(mTestMapper.getResetNativeCategories().length, 0);
-
-        mTestMapper.systemPropertiesSet("device_config.reset_performed", "true");
-        mTestMapper.setFileContent("");
-        Assert.assertEquals(mTestMapper.getResetNativeCategories().length, 0);
-
-        mTestMapper.systemPropertiesSet("device_config.reset_performed", "true");
-        mTestMapper.setFileContent("persist.device_config.category1.flag;"
+        doReturn("persist.device_config.category1.flag;"
                 + "persist.device_config.category2.flag;persist.device_config.category3.flag;"
-                + "persist.device_config.category3.flag2");
+                + "persist.device_config.category3.flag2")
+            .when(() -> SettingsToPropertiesMapper.getResetFlagsFileContent());
+
+        mSystemSettingsMap.put("device_config.reset_performed", "");
+        Assert.assertEquals(mTestMapper.getResetNativeCategories().length, 0);
+
+        mSystemSettingsMap.put("device_config.reset_performed", "true");
         List<String> categories = Arrays.asList(mTestMapper.getResetNativeCategories());
         Assert.assertEquals(3, categories.size());
         Assert.assertTrue(categories.contains("category1"));
         Assert.assertTrue(categories.contains("category2"));
         Assert.assertTrue(categories.contains("category3"));
     }
-
-    private static class TestMapper extends SettingsToPropertiesMapper {
-        private final Map<String, String> mProps = new HashMap<>();
-
-        private String mFileContent = "";
-
-        TestMapper(ContentResolver contentResolver) {
-            super(contentResolver, TEST_MAPPING, new String[] {});
-        }
-
-        @Override
-        protected String systemPropertiesGet(String key) {
-            Preconditions.checkNotNull(key);
-            return mProps.get(key);
-        }
-
-        @Override
-        protected void systemPropertiesSet(String key, String value) {
-            Preconditions.checkNotNull(value);
-            Preconditions.checkNotNull(key);
-            mProps.put(key, value);
-        }
-
-        protected void setFileContent(String fileContent) {
-            mFileContent = fileContent;
-        }
-
-        @Override
-        protected String getResetFlagsFileContent() {
-            return mFileContent;
-        }
-    }
 }
diff --git a/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfig.java b/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfig.java
new file mode 100644
index 0000000..b766822
--- /dev/null
+++ b/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfig.java
@@ -0,0 +1,131 @@
+/*
+ * 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.testables;
+
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doAnswer;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyString;
+
+import android.provider.DeviceConfig;
+import android.util.Pair;
+
+import com.android.dx.mockito.inline.extended.StaticMockitoSession;
+
+import org.junit.rules.TestRule;
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+import org.mockito.quality.Strictness;
+import org.mockito.stubbing.Answer;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executor;
+
+/**
+ * TestableDeviceConfig uses ExtendedMockito to replace the real implementation of DeviceConfig
+ * with essentially a local HashMap in the callers process. This allows for unit testing that do not
+ * modify the real DeviceConfig on the device at all.
+ *
+ * <p>TestableDeviceConfig should be defined as a rule on your test so it can clean up after itself.
+ * Like the following:</p>
+ * <pre class="prettyprint">
+ * &#064;Rule
+ * public final TestableDeviceConfig mTestableDeviceConfig = new TestableDeviceConfig();
+ * </pre>
+ */
+public final class TestableDeviceConfig implements TestRule {
+
+    private StaticMockitoSession mMockitoSession;
+    private Map<DeviceConfig.OnPropertyChangedListener, Pair<String, Executor>>
+            mOnPropertyChangedListenerMap = new HashMap<>();
+    private Map<String, String> mKeyValueMap = new ConcurrentHashMap<>();
+
+    /**
+     * Clears out all local overrides.
+     */
+    public void clearDeviceConfig() {
+        mKeyValueMap.clear();
+    }
+
+    @Override
+    public Statement apply(Statement base, Description description) {
+        mMockitoSession = mockitoSession()
+                .initMocks(this)
+                .strictness(Strictness.LENIENT)
+                .spyStatic(DeviceConfig.class)
+                .startMocking();
+
+        doAnswer((Answer<Void>) invocationOnMock -> {
+            String namespace = invocationOnMock.getArgument(0);
+            Executor executor = invocationOnMock.getArgument(1);
+            DeviceConfig.OnPropertyChangedListener onPropertyChangedListener =
+                    invocationOnMock.getArgument(2);
+            mOnPropertyChangedListenerMap.put(
+                    onPropertyChangedListener, new Pair<>(namespace, executor));
+            return null;
+        }).when(() -> DeviceConfig.addOnPropertyChangedListener(
+                anyString(), any(Executor.class),
+                any(DeviceConfig.OnPropertyChangedListener.class)));
+
+        doAnswer((Answer<Boolean>) invocationOnMock -> {
+                    String namespace = invocationOnMock.getArgument(0);
+                    String name = invocationOnMock.getArgument(1);
+                    String value = invocationOnMock.getArgument(2);
+                    mKeyValueMap.put(getKey(namespace, name), value);
+                    for (DeviceConfig.OnPropertyChangedListener listener :
+                            mOnPropertyChangedListenerMap.keySet()) {
+                        if (namespace.equals(mOnPropertyChangedListenerMap.get(listener).first)) {
+                            mOnPropertyChangedListenerMap.get(listener).second.execute(
+                                    () -> listener.onPropertyChanged(namespace, name, value));
+                        }
+                    }
+                    return true;
+                }
+        ).when(() -> DeviceConfig.setProperty(anyString(), anyString(), anyString(), anyBoolean()));
+
+        doAnswer((Answer<String>) invocationOnMock -> {
+            String namespace = invocationOnMock.getArgument(0);
+            String name = invocationOnMock.getArgument(1);
+            return mKeyValueMap.get(getKey(namespace, name));
+        }).when(() -> DeviceConfig.getProperty(anyString(), anyString()));
+
+
+        return new TestWatcher() {
+            @Override
+            protected void succeeded(Description description) {
+                mMockitoSession.finishMocking();
+                mOnPropertyChangedListenerMap.clear();
+            }
+
+            @Override
+            protected void failed(Throwable e, Description description) {
+                mMockitoSession.finishMocking(e);
+                mOnPropertyChangedListenerMap.clear();
+            }
+        }.apply(base, description);
+    }
+
+    private static String getKey(String namespace, String name) {
+        return namespace + "/" + name;
+    }
+
+}
diff --git a/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfigTest.java b/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfigTest.java
new file mode 100644
index 0000000..39b5840
--- /dev/null
+++ b/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfigTest.java
@@ -0,0 +1,115 @@
+/*
+ * 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.testables;
+
+import static android.provider.DeviceConfig.OnPropertyChangedListener;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.app.ActivityThread;
+import android.platform.test.annotations.Presubmit;
+import android.provider.DeviceConfig;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/** Tests that ensure appropriate settings are backed up. */
+@Presubmit
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class TestableDeviceConfigTest {
+    private static final String sNamespace = "namespace1";
+    private static final String sKey = "key1";
+    private static final String sValue = "value1";
+    private static final long WAIT_FOR_PROPERTY_CHANGE_TIMEOUT_MILLIS = 2000; // 2 sec
+
+    @Rule
+    public TestableDeviceConfig mTestableDeviceConfig = new TestableDeviceConfig();
+
+    @Test
+    public void getProperty_empty() {
+        String result = DeviceConfig.getProperty(sNamespace, sKey);
+        assertThat(result).isNull();
+    }
+
+    @Test
+    public void setAndGetProperty_sameNamespace() {
+        DeviceConfig.setProperty(sNamespace, sKey, sValue, false);
+        String result = DeviceConfig.getProperty(sNamespace, sKey);
+        assertThat(result).isEqualTo(sValue);
+    }
+
+    @Test
+    public void setAndGetProperty_differentNamespace() {
+        String newNamespace = "namespace2";
+        DeviceConfig.setProperty(sNamespace, sKey, sValue, false);
+        String result = DeviceConfig.getProperty(newNamespace, sKey);
+        assertThat(result).isNull();
+    }
+
+    @Test
+    public void setAndGetProperty_multipleNamespaces() {
+        String newNamespace = "namespace2";
+        String newValue = "value2";
+        DeviceConfig.setProperty(sNamespace, sKey, sValue, false);
+        DeviceConfig.setProperty(newNamespace, sKey, newValue, false);
+        String result = DeviceConfig.getProperty(sNamespace, sKey);
+        assertThat(result).isEqualTo(sValue);
+        result = DeviceConfig.getProperty(newNamespace, sKey);
+        assertThat(result).isEqualTo(newValue);
+    }
+
+    @Test
+    public void setAndGetProperty_overrideValue() {
+        String newValue = "value2";
+        DeviceConfig.setProperty(sNamespace, sKey, sValue, false);
+        DeviceConfig.setProperty(sNamespace, sKey, newValue, false);
+        String result = DeviceConfig.getProperty(sNamespace, sKey);
+        assertThat(result).isEqualTo(newValue);
+    }
+
+    @Test
+    public void testListener() throws InterruptedException {
+        CountDownLatch countDownLatch = new CountDownLatch(1);
+
+        OnPropertyChangedListener changeListener = (namespace, name, value) -> {
+            assertThat(namespace).isEqualTo(sNamespace);
+            assertThat(name).isEqualTo(sKey);
+            assertThat(value).isEqualTo(sValue);
+            countDownLatch.countDown();
+        };
+        try {
+            DeviceConfig.addOnPropertyChangedListener(sNamespace,
+                    ActivityThread.currentApplication().getMainExecutor(), changeListener);
+            DeviceConfig.setProperty(sNamespace, sKey, sValue, false);
+            assertThat(countDownLatch.await(
+                    WAIT_FOR_PROPERTY_CHANGE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)).isTrue();
+        } finally {
+            DeviceConfig.removeOnPropertyChangedListener(changeListener);
+        }
+    }
+
+}
+
+
diff --git a/services/tests/rescueparty/how_to_run.txt b/services/tests/rescueparty/how_to_run.txt
index 9528d39..a3a26d6 100644
--- a/services/tests/rescueparty/how_to_run.txt
+++ b/services/tests/rescueparty/how_to_run.txt
@@ -1,4 +1,3 @@
-# Per http://go/westworld-local-development#step3-test-atom-and-metric-locally-on-device ,
 # In one terminal:
 make statsd_testdrive
 ./out/host/linux-x86/bin/statsd_testdrive 122
diff --git a/services/tests/servicestests/src/com/android/server/am/AppCompactorTest.java b/services/tests/servicestests/src/com/android/server/am/AppCompactorTest.java
deleted file mode 100644
index 63015be..0000000
--- a/services/tests/servicestests/src/com/android/server/am/AppCompactorTest.java
+++ /dev/null
@@ -1,449 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.am;
-
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_ACTION_1;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_ACTION_2;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_STATSD_SAMPLE_RATE;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_THROTTLE_1;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_THROTTLE_2;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_THROTTLE_3;
-import static android.provider.DeviceConfig.ActivityManager.KEY_COMPACT_THROTTLE_4;
-import static android.provider.DeviceConfig.ActivityManager.KEY_USE_COMPACTION;
-
-import static com.android.server.am.ActivityManagerService.Injector;
-import static com.android.server.am.AppCompactor.compactActionIntToString;
-
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-
-import android.os.Handler;
-import android.os.HandlerThread;
-import android.provider.DeviceConfig;
-import android.support.test.uiautomator.UiDevice;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.runner.AndroidJUnit4;
-
-import com.android.server.appop.AppOpsService;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Tests for {@link AppCompactor}.
- *
- * Build/Install/Run:
- * atest FrameworksServicesTests:AppCompactorTest
- */
-@RunWith(AndroidJUnit4.class)
-public final class AppCompactorTest {
-
-    private static final String CLEAR_DEVICE_CONFIG_KEY_CMD =
-            "device_config delete activity_manager";
-
-    @Mock private AppOpsService mAppOpsService;
-    private AppCompactor mCompactorUnderTest;
-    private HandlerThread mHandlerThread;
-    private Handler mHandler;
-    private CountDownLatch mCountDown;
-
-    private static void clearDeviceConfig() throws IOException  {
-        UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
-        uiDevice.executeShellCommand(
-                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + KEY_USE_COMPACTION);
-        uiDevice.executeShellCommand(
-                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + KEY_COMPACT_ACTION_1);
-        uiDevice.executeShellCommand(
-                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + KEY_COMPACT_ACTION_2);
-        uiDevice.executeShellCommand(
-                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + KEY_COMPACT_THROTTLE_1);
-        uiDevice.executeShellCommand(
-                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + KEY_COMPACT_THROTTLE_2);
-        uiDevice.executeShellCommand(
-                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + KEY_COMPACT_THROTTLE_3);
-        uiDevice.executeShellCommand(
-                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + KEY_COMPACT_THROTTLE_4);
-        uiDevice.executeShellCommand(
-                CLEAR_DEVICE_CONFIG_KEY_CMD + " " + KEY_COMPACT_STATSD_SAMPLE_RATE);
-    }
-
-    @Before
-    public void setUp() throws IOException {
-        MockitoAnnotations.initMocks(this);
-        clearDeviceConfig();
-        mHandlerThread = new HandlerThread("");
-        mHandlerThread.start();
-        mHandler = new Handler(mHandlerThread.getLooper());
-        ActivityManagerService ams = new ActivityManagerService(new TestInjector());
-        mCompactorUnderTest = new AppCompactor(ams,
-                new AppCompactor.PropertyChangedCallbackForTest() {
-                    @Override
-                    public void onPropertyChanged() {
-                        if (mCountDown != null) {
-                            mCountDown.countDown();
-                        }
-                    }
-                });
-    }
-
-    @After
-    public void tearDown() throws IOException {
-        mHandlerThread.quit();
-        mCountDown = null;
-        clearDeviceConfig();
-    }
-
-    @Test
-    public void init_setsDefaults() {
-        mCompactorUnderTest.init();
-        assertThat(mCompactorUnderTest.useCompaction(),
-                is(mCompactorUnderTest.DEFAULT_USE_COMPACTION));
-        assertThat(mCompactorUnderTest.mCompactActionSome, is(
-                compactActionIntToString(mCompactorUnderTest.DEFAULT_COMPACT_ACTION_1)));
-        assertThat(mCompactorUnderTest.mCompactActionFull, is(
-                compactActionIntToString(mCompactorUnderTest.DEFAULT_COMPACT_ACTION_2)));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_1));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_2));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_3));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_4));
-        assertThat(mCompactorUnderTest.mStatsdSampleRate,
-                is(AppCompactor.DEFAULT_STATSD_SAMPLE_RATE));
-    }
-
-    @Test
-    public void init_withDeviceConfigSetsParameters() {
-        // When the DeviceConfig already has a flag value stored (note this test will need to
-        // change if the default value changes from false).
-        assertThat(mCompactorUnderTest.DEFAULT_USE_COMPACTION, is(false));
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_USE_COMPACTION, "true", false);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_ACTION_1,
-                Integer.toString((AppCompactor.DEFAULT_COMPACT_ACTION_1 + 1 % 4) + 1), false);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_ACTION_2,
-                Integer.toString((AppCompactor.DEFAULT_COMPACT_ACTION_2 + 1 % 4) + 1), false);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_THROTTLE_1,
-                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_1 + 1), false);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_THROTTLE_2,
-                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_2 + 1), false);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_THROTTLE_3,
-                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_3 + 1), false);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_THROTTLE_4,
-                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_4 + 1), false);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_STATSD_SAMPLE_RATE,
-                Float.toString(AppCompactor.DEFAULT_STATSD_SAMPLE_RATE + 0.1f), false);
-
-        // Then calling init will read and set that flag.
-        mCompactorUnderTest.init();
-        assertThat(mCompactorUnderTest.useCompaction(), is(true));
-        assertThat(mCompactorUnderTest.mCompactionThread.isAlive(), is(true));
-
-        assertThat(mCompactorUnderTest.mCompactActionSome,
-                is(compactActionIntToString((AppCompactor.DEFAULT_COMPACT_ACTION_1 + 1 % 4) + 1)));
-        assertThat(mCompactorUnderTest.mCompactActionFull,
-                is(compactActionIntToString((AppCompactor.DEFAULT_COMPACT_ACTION_2 + 1 % 4) + 1)));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_1 + 1));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_2 + 1));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_3 + 1));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_4 + 1));
-        assertThat(mCompactorUnderTest.mStatsdSampleRate,
-                is(AppCompactor.DEFAULT_STATSD_SAMPLE_RATE + 0.1f));
-    }
-
-    @Test
-    public void useCompaction_listensToDeviceConfigChanges() throws InterruptedException {
-        assertThat(mCompactorUnderTest.useCompaction(),
-                is(mCompactorUnderTest.DEFAULT_USE_COMPACTION));
-        // When we call init and change some the flag value...
-        mCompactorUnderTest.init();
-        mCountDown = new CountDownLatch(1);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_USE_COMPACTION, "true", false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-
-        // Then that new flag value is updated in the implementation.
-        assertThat(mCompactorUnderTest.useCompaction(), is(true));
-        assertThat(mCompactorUnderTest.mCompactionThread.isAlive(), is(true));
-
-        // And again, setting the flag the other way.
-        mCountDown = new CountDownLatch(1);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_USE_COMPACTION, "false", false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-        assertThat(mCompactorUnderTest.useCompaction(), is(false));
-    }
-
-    @Test
-    public void useCompaction_listensToDeviceConfigChangesBadValues() throws InterruptedException {
-        assertThat(mCompactorUnderTest.useCompaction(),
-                is(mCompactorUnderTest.DEFAULT_USE_COMPACTION));
-        mCompactorUnderTest.init();
-
-        // When we push an invalid flag value...
-        mCountDown = new CountDownLatch(1);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_USE_COMPACTION, "foobar", false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-
-        // Then we set the default.
-        assertThat(mCompactorUnderTest.useCompaction(), is(AppCompactor.DEFAULT_USE_COMPACTION));
-    }
-
-    @Test
-    public void compactAction_listensToDeviceConfigChanges() throws InterruptedException {
-        mCompactorUnderTest.init();
-
-        // When we override new values for the compaction action with reasonable values...
-
-        // There are four possible values for compactAction[Some|Full].
-        for (int i = 1; i < 5; i++) {
-            mCountDown = new CountDownLatch(2);
-            int expectedSome = (mCompactorUnderTest.DEFAULT_COMPACT_ACTION_1 + i) % 4 + 1;
-            DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                    KEY_COMPACT_ACTION_1, Integer.toString(expectedSome), false);
-            int expectedFull = (mCompactorUnderTest.DEFAULT_COMPACT_ACTION_2 + i) % 4 + 1;
-            DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                    KEY_COMPACT_ACTION_2, Integer.toString(expectedFull), false);
-            assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-
-            // Then the updates are reflected in the flags.
-            assertThat(mCompactorUnderTest.mCompactActionSome,
-                    is(compactActionIntToString(expectedSome)));
-            assertThat(mCompactorUnderTest.mCompactActionFull,
-                    is(compactActionIntToString(expectedFull)));
-        }
-    }
-
-    @Test
-    public void compactAction_listensToDeviceConfigChangesBadValues() throws InterruptedException {
-        mCompactorUnderTest.init();
-
-        // When we override new values for the compaction action with bad values ...
-        mCountDown = new CountDownLatch(2);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_ACTION_1, "foo", false);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_ACTION_2, "foo", false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-
-        // Then the default values are reflected in the flag
-        assertThat(mCompactorUnderTest.mCompactActionSome,
-                is(compactActionIntToString(AppCompactor.DEFAULT_COMPACT_ACTION_1)));
-        assertThat(mCompactorUnderTest.mCompactActionFull,
-                is(compactActionIntToString(AppCompactor.DEFAULT_COMPACT_ACTION_2)));
-
-        mCountDown = new CountDownLatch(2);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_ACTION_1, "", false);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_ACTION_2, "", false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-
-        assertThat(mCompactorUnderTest.mCompactActionSome,
-                is(compactActionIntToString(AppCompactor.DEFAULT_COMPACT_ACTION_1)));
-        assertThat(mCompactorUnderTest.mCompactActionFull,
-                is(compactActionIntToString(AppCompactor.DEFAULT_COMPACT_ACTION_2)));
-    }
-
-    @Test
-    public void compactThrottle_listensToDeviceConfigChanges() throws InterruptedException {
-        mCompactorUnderTest.init();
-
-        // When we override new reasonable throttle values after init...
-        mCountDown = new CountDownLatch(4);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_THROTTLE_1,
-                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_1 + 1), false);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_THROTTLE_2,
-                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_2 + 1), false);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_THROTTLE_3,
-                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_3 + 1), false);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_THROTTLE_4,
-                Long.toString(AppCompactor.DEFAULT_COMPACT_THROTTLE_4 + 1), false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-
-        // Then those flags values are reflected in the compactor.
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_1 + 1));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_2 + 1));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_3 + 1));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_4 + 1));
-    }
-
-    @Test
-    public void compactThrottle_listensToDeviceConfigChangesBadValues()
-            throws IOException, InterruptedException {
-        mCompactorUnderTest.init();
-
-        // When one of the throttles is overridden with a bad value...
-        mCountDown = new CountDownLatch(1);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_THROTTLE_1, "foo", false);
-        // Then all the throttles have the defaults set.
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_1));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_2));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_3));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_4));
-        clearDeviceConfig();
-
-        // Repeat for each of the throttle keys.
-        mCountDown = new CountDownLatch(1);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_THROTTLE_2, "foo", false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_1));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_2));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_3));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_4));
-        clearDeviceConfig();
-
-        mCountDown = new CountDownLatch(1);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_THROTTLE_3, "foo", false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_1));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_2));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_3));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_4));
-        clearDeviceConfig();
-
-        mCountDown = new CountDownLatch(1);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_THROTTLE_4, "foo", false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_1));
-        assertThat(mCompactorUnderTest.mCompactThrottleSomeFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_2));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullSome,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_3));
-        assertThat(mCompactorUnderTest.mCompactThrottleFullFull,
-                is(AppCompactor.DEFAULT_COMPACT_THROTTLE_4));
-    }
-
-    @Test
-    public void statsdSampleRate_listensToDeviceConfigChanges() throws InterruptedException {
-        mCompactorUnderTest.init();
-
-        // When we override mStatsdSampleRate with a reasonable values ...
-        mCountDown = new CountDownLatch(1);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_STATSD_SAMPLE_RATE,
-                Float.toString(AppCompactor.DEFAULT_STATSD_SAMPLE_RATE + 0.1f), false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-
-        // Then that override is reflected in the compactor.
-        assertThat(mCompactorUnderTest.mStatsdSampleRate,
-                is(AppCompactor.DEFAULT_STATSD_SAMPLE_RATE + 0.1f));
-    }
-
-    @Test
-    public void statsdSanokeRate_listensToDeviceConfigChangesBadValues()
-            throws InterruptedException {
-        mCompactorUnderTest.init();
-
-        // When we override mStatsdSampleRate with a reasonable values ...
-        mCountDown = new CountDownLatch(1);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_STATSD_SAMPLE_RATE, "foo", false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-
-        // Then that override is reflected in the compactor.
-        assertThat(mCompactorUnderTest.mStatsdSampleRate,
-                is(AppCompactor.DEFAULT_STATSD_SAMPLE_RATE));
-    }
-
-    @Test
-    public void statsdSanokeRate_listensToDeviceConfigChangesOutOfRangeValues()
-            throws InterruptedException {
-        mCompactorUnderTest.init();
-
-        // When we override mStatsdSampleRate with an value outside of [0..1]...
-        mCountDown = new CountDownLatch(1);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_STATSD_SAMPLE_RATE,
-                Float.toString(-1.0f), false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-
-        // Then the values is capped in the range.
-        assertThat(mCompactorUnderTest.mStatsdSampleRate, is(0.0f));
-
-        mCountDown = new CountDownLatch(1);
-        DeviceConfig.setProperty(DeviceConfig.ActivityManager.NAMESPACE,
-                KEY_COMPACT_STATSD_SAMPLE_RATE,
-                Float.toString(1.01f), false);
-        assertThat(mCountDown.await(5, TimeUnit.SECONDS), is(true));
-
-        // Then the values is capped in the range.
-        assertThat(mCompactorUnderTest.mStatsdSampleRate, is(1.0f));
-    }
-
-    private class TestInjector extends Injector {
-        @Override
-        public AppOpsService getAppOpsService(File file, Handler handler) {
-            return mAppOpsService;
-        }
-
-        @Override
-        public Handler getUiHandler(ActivityManagerService service) {
-            return mHandler;
-        }
-    }
-}
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
index de782a5..4293247 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
@@ -4167,7 +4167,7 @@
         assertTrue(dpm.isResetPasswordTokenActive(admin1));
 
         // test reset password with token
-        when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
+        when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password.getBytes()),
                 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
                 eq(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC), eq(handle), eq(token),
                 eq(UserHandle.USER_SYSTEM)))
@@ -5214,7 +5214,7 @@
                 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
         dpms.mUserPasswordMetrics.put(
                 DpmMockContext.CALLER_USER_HANDLE,
-                PasswordMetrics.computeForPassword("asdf"));
+                PasswordMetrics.computeForPassword("asdf".getBytes()));
 
         assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
     }
@@ -5231,10 +5231,10 @@
 
         dpms.mUserPasswordMetrics.put(
                 DpmMockContext.CALLER_USER_HANDLE,
-                PasswordMetrics.computeForPassword("asdf"));
+                PasswordMetrics.computeForPassword("asdf".getBytes()));
         dpms.mUserPasswordMetrics.put(
                 parentUser.id,
-                PasswordMetrics.computeForPassword("parentUser"));
+                PasswordMetrics.computeForPassword("parentUser".getBytes()));
 
         assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
     }
diff --git a/services/tests/servicestests/src/com/android/server/display/AppSaturationControllerTest.java b/services/tests/servicestests/src/com/android/server/display/color/AppSaturationControllerTest.java
similarity index 95%
rename from services/tests/servicestests/src/com/android/server/display/AppSaturationControllerTest.java
rename to services/tests/servicestests/src/com/android/server/display/color/AppSaturationControllerTest.java
index e518844..7c9a81d 100644
--- a/services/tests/servicestests/src/com/android/server/display/AppSaturationControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/color/AppSaturationControllerTest.java
@@ -14,9 +14,9 @@
  * limitations under the License.
  */
 
-package com.android.server.display;
+package com.android.server.display.color;
 
-import static com.android.server.display.AppSaturationController.TRANSLATION_VECTOR;
+import static com.android.server.display.color.AppSaturationController.TRANSLATION_VECTOR;
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
@@ -29,7 +29,7 @@
 
 import androidx.test.runner.AndroidJUnit4;
 
-import com.android.server.display.ColorDisplayService.ColorTransformController;
+import com.android.server.display.color.ColorDisplayService.ColorTransformController;
 
 import org.junit.After;
 import org.junit.Before;
diff --git a/services/tests/servicestests/src/com/android/server/display/ColorDisplayServiceTest.java b/services/tests/servicestests/src/com/android/server/display/color/ColorDisplayServiceTest.java
similarity index 95%
rename from services/tests/servicestests/src/com/android/server/display/ColorDisplayServiceTest.java
rename to services/tests/servicestests/src/com/android/server/display/color/ColorDisplayServiceTest.java
index 01759d2..2f427b0 100644
--- a/services/tests/servicestests/src/com/android/server/display/ColorDisplayServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/color/ColorDisplayServiceTest.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.display;
+package com.android.server.display.color;
 
 import static com.google.common.truth.Truth.assertWithMessage;
 
@@ -70,7 +70,7 @@
 
     private MockTwilightManager mTwilightManager;
 
-    private ColorDisplayService mColorDisplayService;
+    private ColorDisplayService mCds;
     private ColorDisplayService.BinderService mBinderService;
 
     @BeforeClass
@@ -96,17 +96,17 @@
         mTwilightManager = new MockTwilightManager();
         LocalServices.addService(TwilightManager.class, mTwilightManager);
 
-        mColorDisplayService = new ColorDisplayService(mContext);
-        mBinderService = mColorDisplayService.new BinderService();
+        mCds = new ColorDisplayService(mContext);
+        mBinderService = mCds.new BinderService();
         LocalServices.addService(ColorDisplayService.ColorDisplayServiceInternal.class,
-                        mColorDisplayService.new ColorDisplayServiceInternal());
+                mCds.new ColorDisplayServiceInternal());
     }
 
     @After
     public void tearDown() {
         LocalServices.removeServiceForTest(TwilightManager.class);
 
-        mColorDisplayService = null;
+        mCds = null;
 
         mTwilightManager = null;
 
@@ -1003,7 +1003,7 @@
 
         /* Since we are using FakeSettingsProvider which could not trigger observer change,
          * force an update here.*/
-        mColorDisplayService.updateDisplayWhiteBalanceStatus();
+        mCds.updateDisplayWhiteBalanceStatus();
         assertDwbActive(false);
     }
 
@@ -1015,12 +1015,12 @@
         setAutoModeTwilight(-120 /* sunsetOffset */, -60 /* sunriseOffset */);
         setActivated(true /* activated */, -30 /* lastActivatedTimeOffset */);
 
-        mColorDisplayService.updateDisplayWhiteBalanceStatus();
+        mCds.updateDisplayWhiteBalanceStatus();
         assertDwbActive(false);
 
         /* Disable nightlight */
         setActivated(false /* activated */, -30 /* lastActivatedTimeOffset */);
-        mColorDisplayService.updateDisplayWhiteBalanceStatus();
+        mCds.updateDisplayWhiteBalanceStatus();
         assertDwbActive(true);
     }
 
@@ -1031,48 +1031,48 @@
         startService();
         mBinderService.setColorMode(ColorDisplayManager.COLOR_MODE_NATURAL);
 
-        mColorDisplayService.updateDisplayWhiteBalanceStatus();
+        mCds.updateDisplayWhiteBalanceStatus();
         assertDwbActive(true);
     }
 
     @Test
     public void displayWhiteBalance_setTemperatureOverMax() {
-        int max = mColorDisplayService.mDisplayWhiteBalanceTintController.mTemperatureMax;
+        int max = mCds.mDisplayWhiteBalanceTintController.mTemperatureMax;
 
         ColorDisplayService.ColorDisplayServiceInternal cdsInternal = LocalServices.getService(
-                        ColorDisplayService.ColorDisplayServiceInternal.class);
-        cdsInternal.setDisplayWhiteBalanceColorTemperature(max+1);
+                ColorDisplayService.ColorDisplayServiceInternal.class);
+        cdsInternal.setDisplayWhiteBalanceColorTemperature(max + 1);
 
         assertWithMessage("Unexpected temperature set")
-                .that(mColorDisplayService.mDisplayWhiteBalanceTintController.mCurrentColorTemperature)
+                .that(mCds.mDisplayWhiteBalanceTintController.mCurrentColorTemperature)
                 .isEqualTo(max);
     }
 
     @Test
     public void displayWhiteBalance_setTemperatureBelowMin() {
-        int min = mColorDisplayService.mDisplayWhiteBalanceTintController.mTemperatureMin;
+        int min = mCds.mDisplayWhiteBalanceTintController.mTemperatureMin;
 
         ColorDisplayService.ColorDisplayServiceInternal cdsInternal = LocalServices.getService(
-                        ColorDisplayService.ColorDisplayServiceInternal.class);
+                ColorDisplayService.ColorDisplayServiceInternal.class);
         cdsInternal.setDisplayWhiteBalanceColorTemperature(min - 1);
 
         assertWithMessage("Unexpected temperature set")
-                .that(mColorDisplayService.mDisplayWhiteBalanceTintController.mCurrentColorTemperature)
+                .that(mCds.mDisplayWhiteBalanceTintController.mCurrentColorTemperature)
                 .isEqualTo(min);
     }
 
     @Test
     public void displayWhiteBalance_setValidTemperature() {
-        int min = mColorDisplayService.mDisplayWhiteBalanceTintController.mTemperatureMin;
-        int max = mColorDisplayService.mDisplayWhiteBalanceTintController.mTemperatureMax;
+        int min = mCds.mDisplayWhiteBalanceTintController.mTemperatureMin;
+        int max = mCds.mDisplayWhiteBalanceTintController.mTemperatureMax;
         int valToSet = (min + max) / 2;
 
         ColorDisplayService.ColorDisplayServiceInternal cdsInternal = LocalServices.getService(
-                        ColorDisplayService.ColorDisplayServiceInternal.class);
+                ColorDisplayService.ColorDisplayServiceInternal.class);
         cdsInternal.setDisplayWhiteBalanceColorTemperature(valToSet);
 
         assertWithMessage("Unexpected temperature set")
-                .that(mColorDisplayService.mDisplayWhiteBalanceTintController.mCurrentColorTemperature)
+                .that(mCds.mDisplayWhiteBalanceTintController.mCurrentColorTemperature)
                 .isEqualTo(valToSet);
     }
 
@@ -1171,14 +1171,14 @@
     }
 
     /**
-     * Convenience method to start {@link #mColorDisplayService}.
+     * Convenience method to start {@link #mCds}.
      */
     private void startService() {
         Secure.putIntForUser(mContext.getContentResolver(), Secure.USER_SETUP_COMPLETE, 1, mUserId);
 
         InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
-            mColorDisplayService.onBootPhase(SystemService.PHASE_BOOT_COMPLETED);
-            mColorDisplayService.onStartUser(mUserId);
+            mCds.onBootPhase(SystemService.PHASE_BOOT_COMPLETED);
+            mCds.onStartUser(mUserId);
         });
     }
 
@@ -1224,7 +1224,7 @@
      */
     private void assertDwbActive(boolean enabled) {
         assertWithMessage("Incorrect Display White Balance state")
-                .that(mColorDisplayService.mDisplayWhiteBalanceTintController.isActivated())
+                .that(mCds.mDisplayWhiteBalanceTintController.isActivated())
                 .isEqualTo(enabled);
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/CachedSyntheticPasswordTests.java b/services/tests/servicestests/src/com/android/server/locksettings/CachedSyntheticPasswordTests.java
index d2caa0a..94d21dd 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/CachedSyntheticPasswordTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/CachedSyntheticPasswordTests.java
@@ -18,24 +18,22 @@
 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
 
-import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PASSWORD;
 import static com.android.server.testutils.TestUtils.assertExpectException;
 
 import static org.mockito.Mockito.anyInt;
 import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.when;
 import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import android.os.RemoteException;
 
 import com.android.internal.widget.LockPatternUtils;
 import com.android.internal.widget.VerifyCredentialResponse;
-import com.android.server.locksettings.SyntheticPasswordManager.AuthenticationResult;
-
-import java.util.ArrayList;
 
 import org.mockito.ArgumentCaptor;
 
+import java.util.ArrayList;
+
 /**
  * Run the synthetic password tests with caching enabled.
  *
@@ -56,10 +54,10 @@
     }
 
     public void testSyntheticPasswordClearCredentialUntrusted() throws RemoteException {
-        final String PASSWORD = "testSyntheticPasswordClearCredential-password";
-        final String NEWPASSWORD = "testSyntheticPasswordClearCredential-newpassword";
+        final byte[] password = "testSyntheticPasswordClearCredential-password".getBytes();
+        final byte[] newPassword = "testSyntheticPasswordClearCredential-newpassword".getBytes();
 
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         long sid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         // clear password
         mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE, null,
@@ -67,45 +65,46 @@
         assertEquals(0, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
 
         // set a new password
-        mService.setLockCredential(NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
+        mService.setLockCredential(newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
-        assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
-                    .getResponseCode());
+        assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(newPassword,
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+                        .getResponseCode());
         assertNotEquals(sid, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
     }
 
     public void testSyntheticPasswordChangeCredentialUntrusted() throws RemoteException {
-        final String PASSWORD = "testSyntheticPasswordClearCredential-password";
-        final String NEWPASSWORD = "testSyntheticPasswordClearCredential-newpassword";
+        final byte[] password = "testSyntheticPasswordClearCredential-password".getBytes();
+        final byte[] newPassword = "testSyntheticPasswordClearCredential-newpassword".getBytes();
 
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         long sid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         // Untrusted change password
-        mService.setLockCredential(NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
+        mService.setLockCredential(newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
         assertNotEquals(0, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
         assertNotEquals(sid, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
 
         // Verify the password
-        assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
-                    .getResponseCode());
+        assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(newPassword,
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID).getResponseCode());
     }
 
     public void testUntrustedCredentialChangeMaintainsAuthSecret() throws RemoteException {
-        final String PASSWORD = "testUntrustedCredentialChangeMaintainsAuthSecret-password";
-        final String NEWPASSWORD = "testUntrustedCredentialChangeMaintainsAuthSecret-newpassword";
+        final byte[] password =
+                "testUntrustedCredentialChangeMaintainsAuthSecret-password".getBytes();
+        final byte[] newPassword =
+                "testUntrustedCredentialChangeMaintainsAuthSecret-newpassword".getBytes();
 
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         // Untrusted change password
-        mService.setLockCredential(NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
+        mService.setLockCredential(newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
 
         // Verify the password
-        assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
-                    .getResponseCode());
+        assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(newPassword,
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+                        .getResponseCode());
 
         // Ensure the same secret was passed each time
         ArgumentCaptor<ArrayList<Byte>> secret = ArgumentCaptor.forClass(ArrayList.class);
@@ -114,27 +113,29 @@
     }
 
     public void testUntrustedCredentialChangeBlockedIfSpNotCached() throws RemoteException {
-        final String PASSWORD = "testUntrustedCredentialChangeBlockedIfSpNotCached-password";
-        final String NEWPASSWORD = "testUntrustedCredentialChangeBlockedIfSpNotCached-newpassword";
+        final byte[] password =
+                "testUntrustedCredentialChangeBlockedIfSpNotCached-password".getBytes();
+        final byte[] newPassword =
+                "testUntrustedCredentialChangeBlockedIfSpNotCached-newpassword".getBytes();
 
         // Disable caching for this test
         enableSpCaching(false);
 
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         long sid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         // Untrusted change password
         assertExpectException(IllegalStateException.class, /* messageRegex= */ null,
-                () -> mService.setLockCredential(
-                        NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
-                        null, PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID));
+                () -> mService.setLockCredential(newPassword,
+                        LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
+                        PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID));
         assertEquals(sid, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
 
         // Verify the new password doesn't work but the old one still does
-        assertEquals(VerifyCredentialResponse.RESPONSE_ERROR, mService.verifyCredential(
-                NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+        assertEquals(VerifyCredentialResponse.RESPONSE_ERROR, mService.verifyCredential(newPassword,
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                         .getResponseCode());
-        assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                PASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+        assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(password,
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                         .getResponseCode());
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java
index bf71318..f4632db 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java
@@ -133,12 +133,12 @@
     }
 
     @Override
-    protected void tieProfileLockToParent(int userId, String password) {
-        mStorage.writeChildProfileLock(userId, password.getBytes());
+    protected void tieProfileLockToParent(int userId, byte[] password) {
+        mStorage.writeChildProfileLock(userId, password);
     }
 
     @Override
-    protected String getDecryptedPasswordForTiedProfile(int userId) throws FileNotFoundException,
+    protected byte[] getDecryptedPasswordForTiedProfile(int userId) throws FileNotFoundException,
             KeyPermanentlyInvalidatedException {
         byte[] storedData = mStorage.readChildProfileLock(userId);
         if (storedData == null) {
@@ -151,7 +151,7 @@
         } catch (RemoteException e) {
             // shouldn't happen.
         }
-        return new String(storedData);
+        return storedData;
     }
 
 }
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
index 5124803..6e0ba3c 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
@@ -84,8 +84,8 @@
         initializeStorageWithCredential(PRIMARY_USER_ID, "password", CREDENTIAL_TYPE_PASSWORD, sid);
 
         try {
-            mService.setLockCredential("newpwd", CREDENTIAL_TYPE_PASSWORD, "badpwd",
-                    PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+            mService.setLockCredential("newpwd".getBytes(), CREDENTIAL_TYPE_PASSWORD,
+                    "badpwd".getBytes(), PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
             fail("Did not fail when enrolling using incorrect credential");
         } catch (RemoteException expected) {
             assertTrue(expected.getMessage().equals(FAILED_MESSAGE));
@@ -96,7 +96,7 @@
     public void testClearPasswordPrimaryUser() throws RemoteException {
         final String PASSWORD = "password";
         initializeStorageWithCredential(PRIMARY_USER_ID, PASSWORD, CREDENTIAL_TYPE_PASSWORD, 1234);
-        mService.setLockCredential(null, CREDENTIAL_TYPE_NONE, PASSWORD,
+        mService.setLockCredential(null, CREDENTIAL_TYPE_NONE, PASSWORD.getBytes(),
                 PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
         assertFalse(mService.havePassword(PRIMARY_USER_ID));
         assertFalse(mService.havePattern(PRIMARY_USER_ID));
@@ -106,7 +106,8 @@
     public void testManagedProfileUnifiedChallenge() throws RemoteException {
         final String firstUnifiedPassword = "testManagedProfileUnifiedChallenge-pwd-1";
         final String secondUnifiedPassword = "testManagedProfileUnifiedChallenge-pwd-2";
-        mService.setLockCredential(firstUnifiedPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
+        mService.setLockCredential(firstUnifiedPassword.getBytes(),
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
                 null, PASSWORD_QUALITY_COMPLEX, PRIMARY_USER_ID);
         mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, false, null);
         final long primarySid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
@@ -125,8 +126,8 @@
         mGateKeeperService.clearAuthToken(TURNED_OFF_PROFILE_USER_ID);
         // verify credential
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                firstUnifiedPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
-                .getResponseCode());
+                firstUnifiedPassword.getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0,
+                PRIMARY_USER_ID).getResponseCode());
 
         // Verify that we have a new auth token for the profile
         assertNotNull(mGateKeeperService.getAuthToken(MANAGED_PROFILE_USER_ID));
@@ -141,15 +142,16 @@
          */
         mStorageManager.setIgnoreBadUnlock(true);
         // Change primary password and verify that profile SID remains
-        mService.setLockCredential(secondUnifiedPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
-                firstUnifiedPassword, PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+        mService.setLockCredential(secondUnifiedPassword.getBytes(),
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
+                firstUnifiedPassword.getBytes(), PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
         mStorageManager.setIgnoreBadUnlock(false);
         assertEquals(profileSid, mGateKeeperService.getSecureUserId(MANAGED_PROFILE_USER_ID));
         assertNull(mGateKeeperService.getAuthToken(TURNED_OFF_PROFILE_USER_ID));
 
         // Clear unified challenge
         mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE,
-                secondUnifiedPassword, PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
+                secondUnifiedPassword.getBytes(), PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
         assertEquals(0, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
         assertEquals(0, mGateKeeperService.getSecureUserId(MANAGED_PROFILE_USER_ID));
         assertEquals(0, mGateKeeperService.getSecureUserId(TURNED_OFF_PROFILE_USER_ID));
@@ -158,14 +160,16 @@
     public void testManagedProfileSeparateChallenge() throws RemoteException {
         final String primaryPassword = "testManagedProfileSeparateChallenge-primary";
         final String profilePassword = "testManagedProfileSeparateChallenge-profile";
-        mService.setLockCredential(primaryPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
+        mService.setLockCredential(primaryPassword.getBytes(),
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
                 PASSWORD_QUALITY_COMPLEX, PRIMARY_USER_ID);
         /* Currently in LockSettingsService.setLockCredential, unlockUser() is called with the new
          * credential as part of verifyCredential() before the new credential is committed in
          * StorageManager. So we relax the check in our mock StorageManager to allow that.
          */
         mStorageManager.setIgnoreBadUnlock(true);
-        mService.setLockCredential(profilePassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
+        mService.setLockCredential(profilePassword.getBytes(),
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
                 PASSWORD_QUALITY_COMPLEX, MANAGED_PROFILE_USER_ID);
         mStorageManager.setIgnoreBadUnlock(false);
 
@@ -179,31 +183,32 @@
         mGateKeeperService.clearAuthToken(MANAGED_PROFILE_USER_ID);
         // verify primary credential
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                primaryPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
-                .getResponseCode());
+                primaryPassword.getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0,
+                PRIMARY_USER_ID).getResponseCode());
         assertNull(mGateKeeperService.getAuthToken(MANAGED_PROFILE_USER_ID));
 
         // verify profile credential
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                profilePassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0,
+                profilePassword.getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0,
                 MANAGED_PROFILE_USER_ID).getResponseCode());
         assertNotNull(mGateKeeperService.getAuthToken(MANAGED_PROFILE_USER_ID));
         assertEquals(profileSid, mGateKeeperService.getSecureUserId(MANAGED_PROFILE_USER_ID));
 
         // Change primary credential and make sure we don't affect profile
         mStorageManager.setIgnoreBadUnlock(true);
-        mService.setLockCredential("pwd", LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
-                primaryPassword, PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+        mService.setLockCredential("pwd".getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
+                primaryPassword.getBytes(), PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
         mStorageManager.setIgnoreBadUnlock(false);
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                profilePassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0,
+                profilePassword.getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0,
                 MANAGED_PROFILE_USER_ID).getResponseCode());
         assertEquals(profileSid, mGateKeeperService.getSecureUserId(MANAGED_PROFILE_USER_ID));
     }
 
     private void testCreateCredential(int userId, String credential, int type, int quality)
             throws RemoteException {
-        mService.setLockCredential(credential, type, null, quality, userId);
+        mService.setLockCredential(credential.getBytes(), type, null, quality,
+                userId);
         assertVerifyCredentials(userId, credential, type, -1);
     }
 
@@ -212,7 +217,8 @@
         mHasSecureLockScreen = false;
 
         try {
-            mService.setLockCredential(credential, type, null, quality, userId);
+            mService.setLockCredential(credential.getBytes(), type, null, quality,
+                    userId);
             fail("An exception should have been thrown.");
         } catch (UnsupportedOperationException e) {
             // Success - the exception was expected.
@@ -226,15 +232,16 @@
             String oldCredential, int oldType, int quality) throws RemoteException {
         final long sid = 1234;
         initializeStorageWithCredential(userId, oldCredential, oldType, sid);
-        mService.setLockCredential(newCredential, newType, oldCredential, quality, userId);
+        mService.setLockCredential(newCredential.getBytes(), newType, oldCredential.getBytes(),
+                quality, userId);
         assertVerifyCredentials(userId, newCredential, newType, sid);
     }
 
     private void assertVerifyCredentials(int userId, String credential, int type, long sid)
             throws RemoteException{
         final long challenge = 54321;
-        VerifyCredentialResponse response = mService.verifyCredential(credential, type, challenge,
-                userId);
+        VerifyCredentialResponse response = mService.verifyCredential(credential.getBytes(),
+                type, challenge, userId);
 
         assertEquals(GateKeeperResponse.RESPONSE_OK, response.getResponseCode());
         if (sid != -1) assertEquals(sid, mGateKeeperService.getSecureUserId(userId));
@@ -253,18 +260,19 @@
             incorrectType = LockPatternUtils.CREDENTIAL_TYPE_PASSWORD;
         }
         // check for bad type
-        assertEquals(GateKeeperResponse.RESPONSE_ERROR, mService.verifyCredential(credential,
-                incorrectType, challenge, userId).getResponseCode());
+        assertEquals(GateKeeperResponse.RESPONSE_ERROR, mService.verifyCredential(
+                credential.getBytes(), incorrectType, challenge, userId).getResponseCode());
         // check for bad credential
-        assertEquals(GateKeeperResponse.RESPONSE_ERROR, mService.verifyCredential("0" + credential,
-                type, challenge, userId).getResponseCode());
+        assertEquals(GateKeeperResponse.RESPONSE_ERROR, mService.verifyCredential(
+                ("0" + credential).getBytes(), type, challenge, userId).getResponseCode());
     }
 
     private void initializeStorageWithCredential(int userId, String credential, int type, long sid)
             throws RemoteException {
+        byte[] credentialBytes = credential == null ? null : credential.getBytes();
         byte[] oldHash = new VerifyHandle(credential.getBytes(), sid).toBytes();
         if (mService.shouldMigrateToSyntheticPasswordLocked(userId)) {
-            mService.initializeSyntheticPasswordLocked(oldHash, credential, type,
+            mService.initializeSyntheticPasswordLocked(oldHash, credentialBytes, type,
                     type == LockPatternUtils.CREDENTIAL_TYPE_PASSWORD ? PASSWORD_QUALITY_ALPHABETIC
                             : PASSWORD_QUALITY_SOMETHING, userId);
         } else {
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsShellCommandTest.java b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsShellCommandTest.java
index 929c3b5..fcfc6d2 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsShellCommandTest.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsShellCommandTest.java
@@ -85,23 +85,24 @@
     public void testWrongPassword() throws Exception {
         when(mLockPatternUtils.isLockPatternEnabled(mUserId)).thenReturn(false);
         when(mLockPatternUtils.isLockPasswordEnabled(mUserId)).thenReturn(true);
-        when(mLockPatternUtils.checkPassword("1234", mUserId)).thenReturn(false);
+        when(mLockPatternUtils.checkPassword("1234".getBytes(), mUserId)).thenReturn(false);
         assertEquals(-1, mCommand.exec(mBinder, in, out, err,
                 new String[] { "set-pin", "--old", "1234" },
                 mShellCallback, mResultReceiver));
-        verify(mLockPatternUtils, never()).saveLockPassword(any(), any(), anyInt(), anyInt());
+        verify(mLockPatternUtils, never()).saveLockPassword(any(byte[].class), any(byte[].class),
+                anyInt(), anyInt());
     }
 
     @Test
     public void testChangePin() throws Exception {
         when(mLockPatternUtils.isLockPatternEnabled(mUserId)).thenReturn(false);
         when(mLockPatternUtils.isLockPasswordEnabled(mUserId)).thenReturn(true);
-        when(mLockPatternUtils.checkPassword("1234", mUserId)).thenReturn(true);
+        when(mLockPatternUtils.checkPassword("1234".getBytes(), mUserId)).thenReturn(true);
         assertEquals(0, mCommand.exec(new Binder(), in, out, err,
                 new String[] { "set-pin", "--old", "1234", "4321" },
                 mShellCallback, mResultReceiver));
-        verify(mLockPatternUtils).saveLockPassword("4321", "1234", PASSWORD_QUALITY_NUMERIC,
-                mUserId);
+        verify(mLockPatternUtils).saveLockPassword("4321".getBytes(), "1234".getBytes(),
+                PASSWORD_QUALITY_NUMERIC, mUserId);
     }
 
     @Test
@@ -118,12 +119,12 @@
     public void testChangePassword() throws Exception {
         when(mLockPatternUtils.isLockPatternEnabled(mUserId)).thenReturn(false);
         when(mLockPatternUtils.isLockPasswordEnabled(mUserId)).thenReturn(true);
-        when(mLockPatternUtils.checkPassword("1234", mUserId)).thenReturn(true);
+        when(mLockPatternUtils.checkPassword("1234".getBytes(), mUserId)).thenReturn(true);
         assertEquals(0,  mCommand.exec(new Binder(), in, out, err,
                 new String[] { "set-password", "--old", "1234", "4321" },
                 mShellCallback, mResultReceiver));
-        verify(mLockPatternUtils).saveLockPassword("4321", "1234", PASSWORD_QUALITY_ALPHABETIC,
-                mUserId);
+        verify(mLockPatternUtils).saveLockPassword("4321".getBytes(), "1234".getBytes(),
+                PASSWORD_QUALITY_ALPHABETIC, mUserId);
     }
 
     @Test
@@ -144,7 +145,8 @@
         assertEquals(0, mCommand.exec(new Binder(), in, out, err,
                 new String[] { "set-pattern", "--old", "1234", "4321" },
                 mShellCallback, mResultReceiver));
-        verify(mLockPatternUtils).saveLockPattern(stringToPattern("4321"), "1234", mUserId);
+        verify(mLockPatternUtils).saveLockPattern(stringToPattern("4321"), "1234".getBytes(),
+                mUserId);
     }
 
     @Test
@@ -165,6 +167,6 @@
         assertEquals(0, mCommand.exec(new Binder(), in, out, err,
                 new String[] { "clear", "--old", "1234" },
                 mShellCallback, mResultReceiver));
-        verify(mLockPatternUtils).clearLock("1234", mUserId);
+        verify(mLockPatternUtils).clearLock("1234".getBytes(), mUserId);
     }
 }
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/MockSyntheticPasswordManager.java b/services/tests/servicestests/src/com/android/server/locksettings/MockSyntheticPasswordManager.java
index 6f68179..b9cb730 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/MockSyntheticPasswordManager.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/MockSyntheticPasswordManager.java
@@ -93,9 +93,13 @@
     }
 
     @Override
-    protected byte[] scrypt(String password, byte[] salt, int N, int r, int p, int outLen) {
+    protected byte[] scrypt(byte[] password, byte[] salt, int n, int r, int p, int outLen) {
         try {
-            PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 10, outLen * 8);
+            char[] passwordChars = new char[password.length];
+            for (int i = 0; i < password.length; i++) {
+                passwordChars[i] = (char) password[i];
+            }
+            PBEKeySpec spec = new PBEKeySpec(passwordChars, salt, 10, outLen * 8);
             SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
             return f.generateSecret(spec).getEncoded();
         } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java b/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java
index 89e155e..e6e020d 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java
@@ -65,22 +65,23 @@
 
     public void testPasswordBasedSyntheticPassword() throws RemoteException {
         final int USER_ID = 10;
-        final String PASSWORD = "user-password";
-        final String BADPASSWORD = "bad-password";
+        final byte[] password = "user-password".getBytes();
+        final byte[] badPassword = "bad-password".getBytes();
         MockSyntheticPasswordManager manager = new MockSyntheticPasswordManager(mContext, mStorage,
                 mGateKeeperService, mUserManager);
         AuthenticationToken authToken = manager.newSyntheticPasswordAndSid(mGateKeeperService, null,
                 null, USER_ID);
-        long handle = manager.createPasswordBasedSyntheticPassword(mGateKeeperService, PASSWORD,
-                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, authToken, PASSWORD_QUALITY_ALPHABETIC,
-                USER_ID);
+        long handle = manager.createPasswordBasedSyntheticPassword(mGateKeeperService,
+                password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, authToken,
+                PASSWORD_QUALITY_ALPHABETIC, USER_ID);
 
         AuthenticationResult result = manager.unwrapPasswordBasedSyntheticPassword(
-                mGateKeeperService, handle, PASSWORD, USER_ID, null);
-        assertEquals(result.authToken.deriveKeyStorePassword(), authToken.deriveKeyStorePassword());
+                mGateKeeperService, handle, password, USER_ID, null);
+        assertArrayEquals(result.authToken.deriveKeyStorePassword(),
+                authToken.deriveKeyStorePassword());
 
         result = manager.unwrapPasswordBasedSyntheticPassword(mGateKeeperService, handle,
-                BADPASSWORD, USER_ID, null);
+                badPassword, USER_ID, null);
         assertNull(result.authToken);
     }
 
@@ -97,30 +98,30 @@
     }
 
     public void testPasswordMigration() throws RemoteException {
-        final String PASSWORD = "testPasswordMigration-password";
+        final byte[] password = "testPasswordMigration-password".getBytes();
 
         disableSyntheticPassword();
-        mService.setLockCredential(PASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
+        mService.setLockCredential(password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
         long sid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         final byte[] primaryStorageKey = mStorageManager.getUserUnlockToken(PRIMARY_USER_ID);
         enableSyntheticPassword();
         // Performs migration
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                PASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+                password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                     .getResponseCode());
         assertEquals(sid, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
         assertTrue(hasSyntheticPassword(PRIMARY_USER_ID));
 
         // SP-based verification
-        assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                PASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+        assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(password,
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                         .getResponseCode());
         assertArrayNotEquals(primaryStorageKey,
                 mStorageManager.getUserUnlockToken(PRIMARY_USER_ID));
     }
 
-    protected void initializeCredentialUnderSP(String password, int userId) throws RemoteException {
+    protected void initializeCredentialUnderSP(byte[] password, int userId) throws RemoteException {
         enableSyntheticPassword();
         int quality = password != null ? PASSWORD_QUALITY_ALPHABETIC
                 : PASSWORD_QUALITY_UNSPECIFIED;
@@ -130,62 +131,64 @@
     }
 
     public void testSyntheticPasswordChangeCredential() throws RemoteException {
-        final String PASSWORD = "testSyntheticPasswordChangeCredential-password";
-        final String NEWPASSWORD = "testSyntheticPasswordChangeCredential-newpassword";
+        final byte[] password = "testSyntheticPasswordChangeCredential-password".getBytes();
+        final byte[] newPassword = "testSyntheticPasswordChangeCredential-newpassword".getBytes();
 
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         long sid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
-        mService.setLockCredential(NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, PASSWORD,
+        mService.setLockCredential(newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, password,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+                newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                         .getResponseCode());
         assertEquals(sid, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
     }
 
     public void testSyntheticPasswordVerifyCredential() throws RemoteException {
-        final String PASSWORD = "testSyntheticPasswordVerifyCredential-password";
-        final String BADPASSWORD = "testSyntheticPasswordVerifyCredential-badpassword";
+        final byte[] password = "testSyntheticPasswordVerifyCredential-password".getBytes();
+        final byte[] badPassword = "testSyntheticPasswordVerifyCredential-badpassword".getBytes();
 
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                PASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+                password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                         .getResponseCode());
 
         assertEquals(VerifyCredentialResponse.RESPONSE_ERROR, mService.verifyCredential(
-                BADPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
-                    .getResponseCode());
+                badPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+                        .getResponseCode());
     }
 
     public void testSyntheticPasswordClearCredential() throws RemoteException {
-        final String PASSWORD = "testSyntheticPasswordClearCredential-password";
-        final String NEWPASSWORD = "testSyntheticPasswordClearCredential-newpassword";
+        final byte[] password = "testSyntheticPasswordClearCredential-password".getBytes();
+        final byte[] badPassword = "testSyntheticPasswordClearCredential-newpassword".getBytes();
 
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         long sid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         // clear password
-        mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE, PASSWORD,
+        mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE, password,
                 PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
         assertEquals(0 ,mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
 
         // set a new password
-        mService.setLockCredential(NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
+        mService.setLockCredential(badPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
-                    .getResponseCode());
+                badPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+                        .getResponseCode());
         assertNotEquals(sid, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
     }
 
     public void testSyntheticPasswordChangeCredentialKeepsAuthSecret() throws RemoteException {
-        final String PASSWORD = "testSyntheticPasswordChangeCredentialKeepsAuthSecret-password";
-        final String NEWPASSWORD = "testSyntheticPasswordChangeCredentialKeepsAuthSecret-new";
+        final byte[] password =
+                "testSyntheticPasswordChangeCredentialKeepsAuthSecret-password".getBytes();
+        final byte[] badPassword =
+                "testSyntheticPasswordChangeCredentialKeepsAuthSecret-new".getBytes();
 
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
-        mService.setLockCredential(NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, PASSWORD,
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
+        mService.setLockCredential(badPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, password,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+                badPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                         .getResponseCode());
 
         // Check the same secret was passed each time
@@ -195,24 +198,25 @@
     }
 
     public void testSyntheticPasswordVerifyPassesPrimaryUserAuthSecret() throws RemoteException {
-        final String PASSWORD = "testSyntheticPasswordVerifyPassesPrimaryUserAuthSecret-password";
-        final String NEWPASSWORD = "testSyntheticPasswordVerifyPassesPrimaryUserAuthSecret-new";
+        final byte[] password =
+                "testSyntheticPasswordVerifyPassesPrimaryUserAuthSecret-password".getBytes();
+        final byte[] newPassword =
+                "testSyntheticPasswordVerifyPassesPrimaryUserAuthSecret-new".getBytes();
 
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         reset(mAuthSecretService);
-        assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                PASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+        assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(password,
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                         .getResponseCode());
         verify(mAuthSecretService).primaryUserCredential(any(ArrayList.class));
     }
 
     public void testSecondaryUserDoesNotPassAuthSecret() throws RemoteException {
-        final String PASSWORD = "testSecondaryUserDoesNotPassAuthSecret-password";
-        final String NEWPASSWORD = "testSecondaryUserDoesNotPassAuthSecret-new";
+        final byte[] password = "testSecondaryUserDoesNotPassAuthSecret-password".getBytes();
 
-        initializeCredentialUnderSP(PASSWORD, SECONDARY_USER_ID);
+        initializeCredentialUnderSP(password, SECONDARY_USER_ID);
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                PASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, SECONDARY_USER_ID)
+                password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, SECONDARY_USER_ID)
                         .getResponseCode());
         verify(mAuthSecretService, never()).primaryUserCredential(any(ArrayList.class));
     }
@@ -228,8 +232,8 @@
     }
 
     public void testSyntheticPasswordAndCredentialDoesNotPassAuthSecret() throws RemoteException {
-        final String PASSWORD = "passwordForASyntheticPassword";
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
+        final byte[] password = "passwordForASyntheticPassword".getBytes();
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
 
         reset(mAuthSecretService);
         mService.onUnlockUser(PRIMARY_USER_ID);
@@ -238,9 +242,9 @@
     }
 
     public void testSyntheticPasswordButNoCredentialPassesAuthSecret() throws RemoteException {
-        final String PASSWORD = "getASyntheticPassword";
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
-        mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE, PASSWORD,
+        final byte[] password = "getASyntheticPassword".getBytes();
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
+        mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE, password,
                 PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
 
         reset(mAuthSecretService);
@@ -250,7 +254,7 @@
     }
 
     public void testManagedProfileUnifiedChallengeMigration() throws RemoteException {
-        final String UnifiedPassword = "testManagedProfileUnifiedChallengeMigration-pwd";
+        final byte[] UnifiedPassword = "testManagedProfileUnifiedChallengeMigration-pwd".getBytes();
         disableSyntheticPassword();
         mService.setLockCredential(UnifiedPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
@@ -284,8 +288,10 @@
     }
 
     public void testManagedProfileSeparateChallengeMigration() throws RemoteException {
-        final String primaryPassword = "testManagedProfileSeparateChallengeMigration-primary";
-        final String profilePassword = "testManagedProfileSeparateChallengeMigration-profile";
+        final byte[] primaryPassword =
+                "testManagedProfileSeparateChallengeMigration-primary".getBytes();
+        final byte[] profilePassword =
+                "testManagedProfileSeparateChallengeMigration-profile".getBytes();
         disableSyntheticPassword();
         mService.setLockCredential(primaryPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
@@ -326,92 +332,92 @@
     }
 
     public void testTokenBasedResetPassword() throws RemoteException {
-        final String PASSWORD = "password";
-        final String PATTERN = "123654";
-        final String TOKEN = "some-high-entropy-secure-token";
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
+        final byte[] password = "password".getBytes();
+        final byte[] pattern = "123654".getBytes();
+        final byte[] token = "some-high-entropy-secure-token".getBytes();
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         final byte[] storageKey = mStorageManager.getUserUnlockToken(PRIMARY_USER_ID);
 
-        long handle = mLocalService.addEscrowToken(TOKEN.getBytes(), PRIMARY_USER_ID);
+        long handle = mLocalService.addEscrowToken(token, PRIMARY_USER_ID);
         assertFalse(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
 
-        mService.verifyCredential(PASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0,
+        mService.verifyCredential(password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0,
                 PRIMARY_USER_ID).getResponseCode();
         assertTrue(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
 
-        mLocalService.setLockCredentialWithToken(PATTERN, LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
-                handle, TOKEN.getBytes(), PASSWORD_QUALITY_SOMETHING, PRIMARY_USER_ID);
+        mLocalService.setLockCredentialWithToken(pattern, LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
+                handle, token, PASSWORD_QUALITY_SOMETHING, PRIMARY_USER_ID);
 
         // Verify DPM gets notified about new device lock
         mService.mHandler.runWithScissors(() -> {}, 0 /*now*/); // Flush runnables on handler
-        PasswordMetrics metric = PasswordMetrics.computeForPassword(PATTERN);
+        PasswordMetrics metric = PasswordMetrics.computeForPassword(pattern);
         metric.quality = PASSWORD_QUALITY_SOMETHING;
         verify(mDevicePolicyManager).setActivePasswordState(metric, PRIMARY_USER_ID);
 
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                PATTERN, LockPatternUtils.CREDENTIAL_TYPE_PATTERN, 0, PRIMARY_USER_ID)
+                pattern, LockPatternUtils.CREDENTIAL_TYPE_PATTERN, 0, PRIMARY_USER_ID)
                     .getResponseCode());
         assertArrayEquals(storageKey, mStorageManager.getUserUnlockToken(PRIMARY_USER_ID));
     }
 
     public void testTokenBasedClearPassword() throws RemoteException {
-        final String PASSWORD = "password";
-        final String PATTERN = "123654";
-        final String TOKEN = "some-high-entropy-secure-token";
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
+        final byte[] password = "password".getBytes();
+        final byte[] pattern = "123654".getBytes();
+        final byte[] token = "some-high-entropy-secure-token".getBytes();
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         final byte[] storageKey = mStorageManager.getUserUnlockToken(PRIMARY_USER_ID);
 
-        long handle = mLocalService.addEscrowToken(TOKEN.getBytes(), PRIMARY_USER_ID);
+        long handle = mLocalService.addEscrowToken(token, PRIMARY_USER_ID);
         assertFalse(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
 
-        mService.verifyCredential(PASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
+        mService.verifyCredential(password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
                 0, PRIMARY_USER_ID).getResponseCode();
         assertTrue(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
 
         mLocalService.setLockCredentialWithToken(null, LockPatternUtils.CREDENTIAL_TYPE_NONE,
-                handle, TOKEN.getBytes(), PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
-        mLocalService.setLockCredentialWithToken(PATTERN, LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
-                handle, TOKEN.getBytes(), PASSWORD_QUALITY_SOMETHING, PRIMARY_USER_ID);
+                handle, token, PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
+        mLocalService.setLockCredentialWithToken(pattern, LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
+                handle, token, PASSWORD_QUALITY_SOMETHING, PRIMARY_USER_ID);
 
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                PATTERN, LockPatternUtils.CREDENTIAL_TYPE_PATTERN, 0, PRIMARY_USER_ID)
+                pattern, LockPatternUtils.CREDENTIAL_TYPE_PATTERN, 0, PRIMARY_USER_ID)
                         .getResponseCode());
         assertArrayEquals(storageKey, mStorageManager.getUserUnlockToken(PRIMARY_USER_ID));
     }
 
     public void testTokenBasedResetPasswordAfterCredentialChanges() throws RemoteException {
-        final String PASSWORD = "password";
-        final String PATTERN = "123654";
-        final String NEWPASSWORD = "password";
-        final String TOKEN = "some-high-entropy-secure-token";
-        initializeCredentialUnderSP(PASSWORD, PRIMARY_USER_ID);
+        final byte[] password = "password".getBytes();
+        final byte[] pattern = "123654".getBytes();
+        final byte[] newPassword = "password".getBytes();
+        final byte[] token = "some-high-entropy-secure-token".getBytes();
+        initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         final byte[] storageKey = mStorageManager.getUserUnlockToken(PRIMARY_USER_ID);
 
-        long handle = mLocalService.addEscrowToken(TOKEN.getBytes(), PRIMARY_USER_ID);
+        long handle = mLocalService.addEscrowToken(token, PRIMARY_USER_ID);
         assertFalse(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
 
-        mService.verifyCredential(PASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
+        mService.verifyCredential(password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
                 0, PRIMARY_USER_ID).getResponseCode();
         assertTrue(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
 
-        mService.setLockCredential(PATTERN, LockPatternUtils.CREDENTIAL_TYPE_PATTERN, PASSWORD,
+        mService.setLockCredential(pattern, LockPatternUtils.CREDENTIAL_TYPE_PATTERN, password,
                 PASSWORD_QUALITY_SOMETHING, PRIMARY_USER_ID);
 
-        mLocalService.setLockCredentialWithToken(NEWPASSWORD,
-                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, handle, TOKEN.getBytes(),
+        mLocalService.setLockCredentialWithToken(newPassword,
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, handle, token,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
 
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                NEWPASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+                newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                     .getResponseCode());
         assertArrayEquals(storageKey, mStorageManager.getUserUnlockToken(PRIMARY_USER_ID));
     }
 
     public void testEscrowTokenActivatedImmediatelyIfNoUserPasswordNeedsMigration()
             throws RemoteException {
-        final String TOKEN = "some-high-entropy-secure-token";
+        final String token = "some-high-entropy-secure-token";
         enableSyntheticPassword();
-        long handle = mLocalService.addEscrowToken(TOKEN.getBytes(), PRIMARY_USER_ID);
+        long handle = mLocalService.addEscrowToken(token.getBytes(), PRIMARY_USER_ID);
         assertTrue(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
         assertEquals(0, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
         assertTrue(hasSyntheticPassword(PRIMARY_USER_ID));
@@ -419,9 +425,9 @@
 
     public void testEscrowTokenActivatedImmediatelyIfNoUserPasswordNoMigration()
             throws RemoteException {
-        final String TOKEN = "some-high-entropy-secure-token";
+        final String token = "some-high-entropy-secure-token";
         initializeCredentialUnderSP(null, PRIMARY_USER_ID);
-        long handle = mLocalService.addEscrowToken(TOKEN.getBytes(), PRIMARY_USER_ID);
+        long handle = mLocalService.addEscrowToken(token.getBytes(), PRIMARY_USER_ID);
         assertTrue(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
         assertEquals(0, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
         assertTrue(hasSyntheticPassword(PRIMARY_USER_ID));
@@ -429,38 +435,38 @@
 
     public void testEscrowTokenActivatedLaterWithUserPasswordNeedsMigration()
             throws RemoteException {
-        final String TOKEN = "some-high-entropy-secure-token";
-        final String PASSWORD = "password";
+        final byte[] token = "some-high-entropy-secure-token".getBytes();
+        final byte[] password = "password".getBytes();
         // Set up pre-SP user password
         disableSyntheticPassword();
-        mService.setLockCredential(PASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
+        mService.setLockCredential(password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
         enableSyntheticPassword();
 
-        long handle = mLocalService.addEscrowToken(TOKEN.getBytes(), PRIMARY_USER_ID);
+        long handle = mLocalService.addEscrowToken(token, PRIMARY_USER_ID);
         // Token not activated immediately since user password exists
         assertFalse(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
         // Activate token (password gets migrated to SP at the same time)
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
-                PASSWORD, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
+                password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                     .getResponseCode());
         // Verify token is activated
         assertTrue(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
     }
 
     public void testSetLockCredentialWithTokenFailsWithoutLockScreen() throws Exception {
-        final String password = "password";
-        final String pattern = "123654";
-        final String token = "some-high-entropy-secure-token";
+        final byte[] password = "password".getBytes();
+        final byte[] pattern = "123654".getBytes();
+        final byte[] token = "some-high-entropy-secure-token".getBytes();
 
         mHasSecureLockScreen = false;
         enableSyntheticPassword();
-        long handle = mLocalService.addEscrowToken(token.getBytes(), PRIMARY_USER_ID);
+        long handle = mLocalService.addEscrowToken(token, PRIMARY_USER_ID);
         assertTrue(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
 
         try {
             mLocalService.setLockCredentialWithToken(password,
-                    LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, handle, token.getBytes(),
+                    LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, handle, token,
                     PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
             fail("An exception should have been thrown.");
         } catch (UnsupportedOperationException e) {
@@ -470,7 +476,7 @@
 
         try {
             mLocalService.setLockCredentialWithToken(pattern,
-                    LockPatternUtils.CREDENTIAL_TYPE_PATTERN, handle, token.getBytes(),
+                    LockPatternUtils.CREDENTIAL_TYPE_PATTERN, handle, token,
                     PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
             fail("An exception should have been thrown.");
         } catch (UnsupportedOperationException e) {
@@ -480,14 +486,14 @@
     }
 
     public void testgetHashFactorPrimaryUser() throws RemoteException {
-        final String password = "password";
+        final byte[] password = "password".getBytes();
         mService.setLockCredential(password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
         final byte[] hashFactor = mService.getHashFactor(password, PRIMARY_USER_ID);
         assertNotNull(hashFactor);
 
-        mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE, password,
-                PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
+        mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE,
+                password, PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
         final byte[] newHashFactor = mService.getHashFactor(null, PRIMARY_USER_ID);
         assertNotNull(newHashFactor);
         // Hash factor should never change after password change/removal
@@ -495,16 +501,16 @@
     }
 
     public void testgetHashFactorManagedProfileUnifiedChallenge() throws RemoteException {
-        final String pattern = "1236";
-        mService.setLockCredential(pattern, LockPatternUtils.CREDENTIAL_TYPE_PATTERN, null,
-                PASSWORD_QUALITY_SOMETHING, PRIMARY_USER_ID);
+        final byte[] pattern = "1236".getBytes();
+        mService.setLockCredential(pattern, LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
+                null, PASSWORD_QUALITY_SOMETHING, PRIMARY_USER_ID);
         mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, false, null);
         assertNotNull(mService.getHashFactor(null, MANAGED_PROFILE_USER_ID));
     }
 
     public void testgetHashFactorManagedProfileSeparateChallenge() throws RemoteException {
-        final String primaryPassword = "primary";
-        final String profilePassword = "profile";
+        final byte[] primaryPassword = "primary".getBytes();
+        final byte[] profilePassword = "profile".getBytes();
         mService.setLockCredential(primaryPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
                 PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
         mService.setLockCredential(profilePassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
@@ -557,7 +563,7 @@
     public void testGsiDisablesAuthSecret() throws RemoteException {
         mGsiService.setIsGsiRunning(true);
 
-        final String password = "testGsiDisablesAuthSecret-password";
+        final byte[] password = "testGsiDisablesAuthSecret-password".getBytes();
 
         initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/KeySyncTaskTest.java b/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/KeySyncTaskTest.java
index c2d4846..a992dd1 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/KeySyncTaskTest.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/KeySyncTaskTest.java
@@ -139,7 +139,7 @@
                 mSnapshotListenersStorage,
                 TEST_USER_ID,
                 TEST_CREDENTIAL_TYPE,
-                TEST_CREDENTIAL,
+                TEST_CREDENTIAL.getBytes(),
                 /*credentialUpdated=*/ false,
                 mPlatformKeyManager,
                 mTestOnlyInsecureCertificateHelper,
@@ -163,17 +163,17 @@
 
     @Test
     public void isPin_isTrueForNumericString() {
-        assertTrue(KeySyncTask.isPin("3298432574398654376547"));
+        assertTrue(KeySyncTask.isPin("3298432574398654376547".getBytes()));
     }
 
     @Test
     public void isPin_isFalseForStringContainingLetters() {
-        assertFalse(KeySyncTask.isPin("398i54369548654"));
+        assertFalse(KeySyncTask.isPin("398i54369548654".getBytes()));
     }
 
     @Test
     public void isPin_isFalseForStringContainingSymbols() {
-        assertFalse(KeySyncTask.isPin("-3987543643"));
+        assertFalse(KeySyncTask.isPin("-3987543643".getBytes()));
     }
 
     @Test
@@ -182,8 +182,8 @@
         byte[] salt = randomBytes(16);
 
         assertArrayEquals(
-                KeySyncTask.hashCredentialsBySaltedSha256(salt, credentials),
-                KeySyncTask.hashCredentialsBySaltedSha256(salt, credentials));
+                KeySyncTask.hashCredentialsBySaltedSha256(salt, credentials.getBytes()),
+                KeySyncTask.hashCredentialsBySaltedSha256(salt, credentials.getBytes()));
     }
 
     @Test
@@ -192,8 +192,8 @@
 
         assertFalse(
                 Arrays.equals(
-                    KeySyncTask.hashCredentialsBySaltedSha256(salt, "password1234"),
-                    KeySyncTask.hashCredentialsBySaltedSha256(salt, "password12345")));
+                    KeySyncTask.hashCredentialsBySaltedSha256(salt, "password1234".getBytes()),
+                    KeySyncTask.hashCredentialsBySaltedSha256(salt, "password12345".getBytes())));
     }
 
     @Test
@@ -202,34 +202,38 @@
 
         assertFalse(
                 Arrays.equals(
-                        KeySyncTask.hashCredentialsBySaltedSha256(randomBytes(64), credentials),
-                        KeySyncTask.hashCredentialsBySaltedSha256(randomBytes(64), credentials)));
+                        KeySyncTask.hashCredentialsBySaltedSha256(randomBytes(64),
+                                credentials.getBytes()),
+                        KeySyncTask.hashCredentialsBySaltedSha256(randomBytes(64),
+                                credentials.getBytes())));
     }
 
     @Test
     public void hashCredentialsBySaltedSha256_returnsDifferentHashEvenIfConcatIsSame() {
         assertFalse(
                 Arrays.equals(
-                        KeySyncTask.hashCredentialsBySaltedSha256(utf8Bytes("123"), "4567"),
-                        KeySyncTask.hashCredentialsBySaltedSha256(utf8Bytes("1234"), "567")));
+                        KeySyncTask.hashCredentialsBySaltedSha256(utf8Bytes("123"),
+                                "4567".getBytes()),
+                        KeySyncTask.hashCredentialsBySaltedSha256(utf8Bytes("1234"),
+                                "567".getBytes())));
     }
 
     @Test
     public void getUiFormat_returnsPinIfPin() {
         assertEquals(UI_FORMAT_PIN,
-                KeySyncTask.getUiFormat(CREDENTIAL_TYPE_PASSWORD, "1234"));
+                KeySyncTask.getUiFormat(CREDENTIAL_TYPE_PASSWORD, "1234".getBytes()));
     }
 
     @Test
     public void getUiFormat_returnsPasswordIfPassword() {
         assertEquals(UI_FORMAT_PASSWORD,
-                KeySyncTask.getUiFormat(CREDENTIAL_TYPE_PASSWORD, "1234a"));
+                KeySyncTask.getUiFormat(CREDENTIAL_TYPE_PASSWORD, "1234a".getBytes()));
     }
 
     @Test
     public void getUiFormat_returnsPatternIfPattern() {
         assertEquals(UI_FORMAT_PATTERN,
-                KeySyncTask.getUiFormat(CREDENTIAL_TYPE_PATTERN, "1234"));
+                KeySyncTask.getUiFormat(CREDENTIAL_TYPE_PATTERN, "1234".getBytes()));
 
     }
 
@@ -291,7 +295,7 @@
                 mSnapshotListenersStorage,
                 TEST_USER_ID,
                 CREDENTIAL_TYPE_PASSWORD,
-                /*credential=*/ password,
+                /*credential=*/ password.getBytes(),
                 /*credentialUpdated=*/ false,
                 mPlatformKeyManager,
                 mTestOnlyInsecureCertificateHelper,
@@ -332,7 +336,7 @@
                 mSnapshotListenersStorage,
                 TEST_USER_ID,
                 CREDENTIAL_TYPE_PATTERN,
-                /*credential=*/ pattern,
+                /*credential=*/ pattern.getBytes(),
                 /*credentialUpdated=*/ false,
                 mPlatformKeyManager,
                 mTestOnlyInsecureCertificateHelper,
@@ -366,7 +370,7 @@
                 mSnapshotListenersStorage,
                 TEST_USER_ID,
                 CREDENTIAL_TYPE_PASSWORD,
-                /*credential=*/ shortPassword,
+                /*credential=*/ shortPassword.getBytes(),
                 /*credentialUpdated=*/ false,
                 mPlatformKeyManager,
                 mTestOnlyInsecureCertificateHelper,
@@ -526,7 +530,7 @@
         verify(mSnapshotListenersStorage).recoverySnapshotAvailable(TEST_RECOVERY_AGENT_UID);
         byte[] lockScreenHash = KeySyncTask.hashCredentialsBySaltedSha256(
                 keyDerivationParams.getSalt(),
-                TEST_CREDENTIAL);
+                TEST_CREDENTIAL.getBytes());
         Long counterId = mRecoverableKeyStoreDb.getCounterId(TEST_USER_ID, TEST_RECOVERY_AGENT_UID);
         assertThat(counterId).isNotNull();
         byte[] recoveryKey = decryptThmEncryptedKey(
@@ -649,7 +653,7 @@
                 mSnapshotListenersStorage,
                 TEST_USER_ID,
                 CREDENTIAL_TYPE_PASSWORD,
-                password,
+                password.getBytes(),
                 /*credentialUpdated=*/ false,
                 mPlatformKeyManager,
                 mTestOnlyInsecureCertificateHelper,
@@ -680,7 +684,7 @@
                 mSnapshotListenersStorage,
                 TEST_USER_ID,
                 CREDENTIAL_TYPE_PASSWORD,
-                /*credential=*/ pin,
+                /*credential=*/ pin.getBytes(),
                 /*credentialUpdated=*/ false,
                 mPlatformKeyManager,
                 mTestOnlyInsecureCertificateHelper,
@@ -712,7 +716,7 @@
                 mSnapshotListenersStorage,
                 TEST_USER_ID,
                 CREDENTIAL_TYPE_PATTERN,
-                "12345",
+                "12345".getBytes(),
                 /*credentialUpdated=*/ false,
                 mPlatformKeyManager,
                 mTestOnlyInsecureCertificateHelper,
@@ -796,7 +800,7 @@
           mSnapshotListenersStorage,
           TEST_USER_ID,
           /*credentialType=*/ 3,
-          "12345",
+          "12345".getBytes(),
           /*credentialUpdated=*/ false,
           mPlatformKeyManager,
           mTestOnlyInsecureCertificateHelper,
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/TestOnlyInsecureCertificateHelperTest.java b/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/TestOnlyInsecureCertificateHelperTest.java
index 9b4c3be..6921bb2 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/TestOnlyInsecureCertificateHelperTest.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/TestOnlyInsecureCertificateHelperTest.java
@@ -27,30 +27,30 @@
     @Test
     public void testDoesCredentailSupportInsecureMode_forNonWhitelistedPassword() throws Exception {
         assertThat(mHelper.doesCredentialSupportInsecureMode(
-                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, "secret12345")).isFalse();
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, "secret12345".getBytes())).isFalse();
         assertThat(mHelper.doesCredentialSupportInsecureMode(
-                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, "1234")).isFalse();
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, "1234".getBytes())).isFalse();
     }
 
     @Test
     public void testDoesCredentailSupportInsecureMode_forWhitelistedPassword() throws Exception {
         assertThat(mHelper.doesCredentialSupportInsecureMode(
                 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
-                TrustedRootCertificates.INSECURE_PASSWORD_PREFIX)).isTrue();
+                TrustedRootCertificates.INSECURE_PASSWORD_PREFIX.getBytes())).isTrue();
 
         assertThat(mHelper.doesCredentialSupportInsecureMode(
                 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
-                TrustedRootCertificates.INSECURE_PASSWORD_PREFIX + "12")).isTrue();
+                (TrustedRootCertificates.INSECURE_PASSWORD_PREFIX + "12").getBytes())).isTrue();
     }
 
     @Test
     public void testDoesCredentailSupportInsecureMode_Pattern() throws Exception {
         assertThat(mHelper.doesCredentialSupportInsecureMode(
                 LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
-                TrustedRootCertificates.INSECURE_PASSWORD_PREFIX)).isFalse();
+                TrustedRootCertificates.INSECURE_PASSWORD_PREFIX.getBytes())).isFalse();
         assertThat(mHelper.doesCredentialSupportInsecureMode(
                 LockPatternUtils.CREDENTIAL_TYPE_NONE,
-                TrustedRootCertificates.INSECURE_PASSWORD_PREFIX)).isFalse();
+                TrustedRootCertificates.INSECURE_PASSWORD_PREFIX.getBytes())).isFalse();
     }
 
     @Test
diff --git a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest1.java b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest1.java
index 76beb8f..7e6b7da 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest1.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest1.java
@@ -6286,6 +6286,15 @@
         mManager.getShareTargets(filter);
     }
 
+    public void testHasShareTargets_permission() {
+        assertExpectException(SecurityException.class, "Missing permission", () ->
+                mManager.hasShareTargets(CALLING_PACKAGE_1));
+
+        // Has permission, now it should pass.
+        mCallerPermissions.add(permission.MANAGE_APP_PREDICTIONS);
+        mManager.hasShareTargets(CALLING_PACKAGE_1);
+    }
+
     public void testDumpsys_crossProfile() {
         prepareCrossProfileDataSet();
         dumpsysOnLogcat("test1", /* force= */ true);
diff --git a/services/tests/servicestests/src/com/android/server/pm/dex/DexoptUtilsTest.java b/services/tests/servicestests/src/com/android/server/pm/dex/DexoptUtilsTest.java
index d9faaa4..3a55c22 100644
--- a/services/tests/servicestests/src/com/android/server/pm/dex/DexoptUtilsTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/dex/DexoptUtilsTest.java
@@ -333,6 +333,20 @@
     }
 
     @Test
+    public void testSharedLibraryContext() {
+        SharedLibraryInfo sharedLibrary =
+                createMockSharedLibrary(new String[] {"a.dex", "b.dex"}).get(0);
+        String context = DexoptUtils.getClassLoaderContext(sharedLibrary);
+        assertEquals("PCL[]", context);
+
+        SharedLibraryInfo otherSharedLibrary =
+                createMockSharedLibrary(new String[] {"c.dex"}).get(0);
+        otherSharedLibrary.addDependency(sharedLibrary);
+        context = DexoptUtils.getClassLoaderContext(otherSharedLibrary);
+        assertEquals("PCL[]{PCL[a.dex:b.dex]}", context);
+    }
+
+    @Test
     public void testProcessContextForDexLoad() {
         List<String> classLoaders = Arrays.asList(
                 DELEGATE_LAST_CLASS_LOADER_NAME,
diff --git a/services/tests/servicestests/src/com/android/server/power/AttentionDetectorTest.java b/services/tests/servicestests/src/com/android/server/power/AttentionDetectorTest.java
index 6a937fa..a2f1f01 100644
--- a/services/tests/servicestests/src/com/android/server/power/AttentionDetectorTest.java
+++ b/services/tests/servicestests/src/com/android/server/power/AttentionDetectorTest.java
@@ -32,10 +32,13 @@
 import android.os.PowerManager;
 import android.os.PowerManagerInternal;
 import android.os.SystemClock;
+import android.os.UserHandle;
+import android.provider.Settings;
 import android.service.attention.AttentionService;
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.mockito.Mock;
@@ -49,6 +52,7 @@
     private TestableAttentionDetector mAttentionDetector;
     private long mAttentionTimeout;
     private long mNextDimming;
+    private int mIsSettingEnabled;
 
     @Before
     public void setUp() {
@@ -59,6 +63,20 @@
         mAttentionDetector.onWakefulnessChangeStarted(PowerManagerInternal.WAKEFULNESS_AWAKE);
         mAttentionDetector.setAttentionServiceSupported(true);
         mNextDimming = SystemClock.uptimeMillis() + 3000L;
+
+        // Save the existing state.
+        mIsSettingEnabled = Settings.System.getIntForUser(getContext().getContentResolver(),
+                Settings.System.ADAPTIVE_SLEEP, 0, UserHandle.USER_CURRENT);
+
+        Settings.System.putIntForUser(getContext().getContentResolver(),
+                Settings.System.ADAPTIVE_SLEEP, 1, UserHandle.USER_CURRENT);
+        mAttentionDetector.updateEnabledFromSettings(getContext());
+    }
+
+    @After
+    public void tearDown() {
+        Settings.System.putIntForUser(getContext().getContentResolver(),
+                Settings.System.ADAPTIVE_SLEEP, mIsSettingEnabled, UserHandle.USER_CURRENT);
     }
 
     @Test
@@ -69,6 +87,16 @@
     }
 
     @Test
+    public void testOnUserActivity_doesntCheckIfNotEnabled() {
+        Settings.System.putIntForUser(getContext().getContentResolver(),
+                Settings.System.ADAPTIVE_SLEEP, 0, UserHandle.USER_CURRENT);
+        mAttentionDetector.updateEnabledFromSettings(getContext());
+        long when = registerAttention();
+        verify(mAttentionManagerInternal, never()).checkAttention(anyInt(), anyLong(), any());
+        assertThat(mNextDimming).isEqualTo(when);
+    }
+
+    @Test
     public void testOnUserActivity_doesntCheckIfNotSupported() {
         mAttentionDetector.setAttentionServiceSupported(false);
         long when = registerAttention();
diff --git a/services/tests/servicestests/src/com/android/server/power/PowerManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/power/PowerManagerServiceTest.java
index 911c4a2..1bda412 100644
--- a/services/tests/servicestests/src/com/android/server/power/PowerManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/power/PowerManagerServiceTest.java
@@ -18,44 +18,67 @@
 
 import static android.os.PowerManagerInternal.WAKEFULNESS_ASLEEP;
 import static android.os.PowerManagerInternal.WAKEFULNESS_AWAKE;
+import static android.os.PowerManagerInternal.WAKEFULNESS_DOZING;
+import static android.os.PowerManagerInternal.WAKEFULNESS_DREAMING;
 
 import static com.google.common.truth.Truth.assertThat;
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.argThat;
 import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isA;
+import static org.mockito.ArgumentMatchers.isNull;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import android.app.ActivityManagerInternal;
 import android.attention.AttentionManagerInternal;
 import android.content.Context;
+import android.content.ContextWrapper;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.res.Resources;
+import android.hardware.SensorManager;
+import android.hardware.display.AmbientDisplayConfiguration;
 import android.hardware.display.DisplayManagerInternal;
 import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
+import android.os.BatteryManager;
 import android.os.BatteryManagerInternal;
 import android.os.Binder;
+import android.os.Handler;
+import android.os.IBinder;
 import android.os.Looper;
 import android.os.PowerManager;
 import android.os.PowerSaveState;
 import android.os.SystemClock;
 import android.os.SystemProperties;
-import android.test.AndroidTestCase;
-import android.test.suitebuilder.annotation.MediumTest;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.os.UserHandle;
+import android.provider.Settings;
+
+import androidx.test.InstrumentationRegistry;
 
 import com.android.internal.app.IBatteryStats;
 import com.android.server.LocalServices;
 import com.android.server.SystemService;
 import com.android.server.lights.LightsManager;
 import com.android.server.policy.WindowManagerPolicy;
+import com.android.server.power.PowerManagerService.BatteryReceiver;
 import com.android.server.power.PowerManagerService.Injector;
 import com.android.server.power.PowerManagerService.NativeWrapper;
+import com.android.server.power.PowerManagerService.UserSwitchedReceiver;
 import com.android.server.power.batterysaver.BatterySaverPolicy;
 import com.android.server.power.batterysaver.BatterySavingStats;
 
-import org.junit.Rule;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.ArgumentMatcher;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
@@ -65,29 +88,54 @@
 /**
  * Tests for {@link com.android.server.power.PowerManagerService}
  */
-public class PowerManagerServiceTest extends AndroidTestCase {
+public class PowerManagerServiceTest {
     private static final float PRECISION = 0.001f;
     private static final float BRIGHTNESS_FACTOR = 0.7f;
     private static final boolean BATTERY_SAVER_ENABLED = true;
     private static final String TEST_LAST_REBOOT_PROPERTY = "test.sys.boot.reason";
 
-    private @Mock BatterySaverPolicy mBatterySaverPolicyMock;
-    private @Mock LightsManager mLightsManagerMock;
-    private @Mock DisplayManagerInternal mDisplayManagerInternalMock;
-    private @Mock BatteryManagerInternal mBatteryManagerInternalMock;
-    private @Mock ActivityManagerInternal mActivityManagerInternalMock;
-    private @Mock AttentionManagerInternal mAttentionManagerInternalMock;
-    private @Mock PowerManagerService.NativeWrapper mNativeWrapperMock;
-    private @Mock Notifier mNotifierMock;
+    @Mock private BatterySaverPolicy mBatterySaverPolicyMock;
+    @Mock private LightsManager mLightsManagerMock;
+    @Mock private DisplayManagerInternal mDisplayManagerInternalMock;
+    @Mock private BatteryManagerInternal mBatteryManagerInternalMock;
+    @Mock private ActivityManagerInternal mActivityManagerInternalMock;
+    @Mock private AttentionManagerInternal mAttentionManagerInternalMock;
+    @Mock private PowerManagerService.NativeWrapper mNativeWrapperMock;
+    @Mock private Notifier mNotifierMock;
+    @Mock private WirelessChargerDetector mWirelessChargerDetectorMock;
+    @Mock private AmbientDisplayConfiguration mAmbientDisplayConfigurationMock;
+
     private PowerManagerService mService;
     private PowerSaveState mPowerSaveState;
     private DisplayPowerRequest mDisplayPowerRequest;
+    private ContextWrapper mContextSpy;
+    private BatteryReceiver mBatteryReceiver;
+    private UserSwitchedReceiver mUserSwitchedReceiver;
+    private Resources mResourcesSpy;
 
+    private class IntentFilterMatcher implements ArgumentMatcher<IntentFilter> {
+        private final IntentFilter mFilter;
 
+        IntentFilterMatcher(IntentFilter filter) {
+            mFilter = filter;
+        }
 
-    @Rule
+        @Override
+        public boolean matches(IntentFilter other) {
+            if (other.countActions() != mFilter.countActions()) {
+                return false;
+            }
+            for (int i = 0; i < mFilter.countActions(); i++) {
+                if (!mFilter.getAction(i).equals(other.getAction(i))) {
+                    return false;
+                }
+            }
+            return true;
+        }
+    }
+
+    @Before
     public void setUp() throws Exception {
-        super.setUp();
         MockitoAnnotations.initMocks(this);
 
         mPowerSaveState = new PowerSaveState.Builder()
@@ -105,33 +153,54 @@
         addLocalServiceMock(ActivityManagerInternal.class, mActivityManagerInternalMock);
         addLocalServiceMock(AttentionManagerInternal.class, mAttentionManagerInternalMock);
 
-        mService = new PowerManagerService(getContext(), new Injector() {
+        mContextSpy = spy(new ContextWrapper(InstrumentationRegistry.getContext()));
+        mResourcesSpy = spy(mContextSpy.getResources());
+        when(mContextSpy.getResources()).thenReturn(mResourcesSpy);
+
+        mService = new PowerManagerService(mContextSpy, new Injector() {
+            @Override
             Notifier createNotifier(Looper looper, Context context, IBatteryStats batteryStats,
                     SuspendBlocker suspendBlocker, WindowManagerPolicy policy) {
                 return mNotifierMock;
             }
 
+            @Override
             SuspendBlocker createSuspendBlocker(PowerManagerService service, String name) {
                 return mock(SuspendBlocker.class);
             }
 
+            @Override
             BatterySaverPolicy createBatterySaverPolicy(
                     Object lock, Context context, BatterySavingStats batterySavingStats) {
                 return mBatterySaverPolicyMock;
             }
 
+            @Override
             NativeWrapper createNativeWrapper() {
                 return mNativeWrapperMock;
             }
+
+            @Override
+            WirelessChargerDetector createWirelessChargerDetector(
+                    SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler) {
+                return mWirelessChargerDetectorMock;
+            }
+
+            @Override
+            AmbientDisplayConfiguration createAmbientDisplayConfiguration(Context context) {
+                return mAmbientDisplayConfigurationMock;
+            }
         });
     }
 
-    @Override
+    @After
     public void tearDown() throws Exception {
         LocalServices.removeServiceForTest(LightsManager.class);
         LocalServices.removeServiceForTest(DisplayManagerInternal.class);
         LocalServices.removeServiceForTest(BatteryManagerInternal.class);
         LocalServices.removeServiceForTest(ActivityManagerInternal.class);
+        Settings.Global.putInt(
+                mContextSpy.getContentResolver(), Settings.Global.THEATER_MODE_ON, 0);
     }
 
     /**
@@ -142,7 +211,56 @@
         LocalServices.addService(clazz, mock);
     }
 
-    @SmallTest
+    private void startSystem() throws Exception {
+        mService.systemReady(null);
+
+        // Grab the BatteryReceiver
+        ArgumentCaptor<BatteryReceiver> batCaptor = ArgumentCaptor.forClass(BatteryReceiver.class);
+        IntentFilter batFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
+        batFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
+        verify(mContextSpy).registerReceiver(batCaptor.capture(),
+                argThat(new IntentFilterMatcher(batFilter)), isNull(), isA(Handler.class));
+        mBatteryReceiver = batCaptor.getValue();
+
+        // Grab the UserSwitchedReceiver
+        ArgumentCaptor<UserSwitchedReceiver> userSwitchedCaptor =
+                ArgumentCaptor.forClass(UserSwitchedReceiver.class);
+        IntentFilter usFilter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
+        verify(mContextSpy).registerReceiver(userSwitchedCaptor.capture(),
+                argThat(new IntentFilterMatcher(usFilter)), isNull(), isA(Handler.class));
+        mUserSwitchedReceiver = userSwitchedCaptor.getValue();
+
+        mService.onBootPhase(SystemService.PHASE_BOOT_COMPLETED);
+    }
+
+    private void forceSleep() {
+        mService.getBinderServiceInstance().goToSleep(SystemClock.uptimeMillis(),
+                PowerManager.GO_TO_SLEEP_REASON_APPLICATION, PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
+    }
+
+    private void forceDream() {
+        mService.getBinderServiceInstance().nap(SystemClock.uptimeMillis());
+    }
+
+    private void forceAwake() {
+        mService.getBinderServiceInstance().wakeUp(SystemClock.uptimeMillis(),
+                PowerManager.WAKE_REASON_UNKNOWN, "testing IPowerManager.wakeUp()", "pkg.name");
+    }
+
+    private void forceDozing() {
+        mService.getBinderServiceInstance().goToSleep(SystemClock.uptimeMillis(),
+                PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0);
+    }
+
+    private void setPluggedIn(boolean isPluggedIn) {
+        // Set the callback to return the new state
+        when(mBatteryManagerInternalMock.isPowered(BatteryManager.BATTERY_PLUGGED_ANY))
+                .thenReturn(isPluggedIn);
+        // Trigger PowerManager to reread the plug-in state
+        mBatteryReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_BATTERY_CHANGED));
+    }
+
+    @Test
     public void testUpdatePowerScreenPolicy_UpdateDisplayPowerRequest() {
         mService.updatePowerRequestFromBatterySaverPolicy(mDisplayPowerRequest);
         assertThat(mDisplayPowerRequest.lowPowerMode).isEqualTo(BATTERY_SAVER_ENABLED);
@@ -150,7 +268,7 @@
                 .isWithin(PRECISION).of(BRIGHTNESS_FACTOR);
     }
 
-    @SmallTest
+    @Test
     public void testGetLastShutdownReasonInternal() {
         SystemProperties.set(TEST_LAST_REBOOT_PROPERTY, "shutdown,thermal");
         int reason = mService.getLastShutdownReasonInternal(TEST_LAST_REBOOT_PROPERTY);
@@ -158,7 +276,7 @@
         assertThat(reason).isEqualTo(PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN);
     }
 
-    @SmallTest
+    @Test
     public void testGetDesiredScreenPolicy_WithVR() throws Exception {
         // Brighten up the screen
         mService.setWakefulnessLocked(WAKEFULNESS_AWAKE, PowerManager.WAKE_REASON_UNKNOWN, 0);
@@ -187,42 +305,171 @@
                 DisplayPowerRequest.POLICY_BRIGHT);
     }
 
-    @SmallTest
+    @Test
     public void testWakefulnessAwake_InitialValue() throws Exception {
         assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
     }
 
-    @SmallTest
+    @Test
     public void testWakefulnessSleep_NoDozeSleepFlag() throws Exception {
         // Start with AWAKE state
+        startSystem();
         assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
 
-        mService.systemReady(null);
-        mService.onBootPhase(SystemService.PHASE_BOOT_COMPLETED);
-
-        // Take a nap with a flag.
+        // Take a nap and verify.
         mService.getBinderServiceInstance().goToSleep(SystemClock.uptimeMillis(),
-            PowerManager.GO_TO_SLEEP_REASON_APPLICATION, PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
-
+                PowerManager.GO_TO_SLEEP_REASON_APPLICATION, PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
         assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
     }
 
-    @MediumTest
+    @Test
+    public void testWakefulnessAwake_AcquireCausesWakeup() throws Exception {
+        startSystem();
+        forceSleep();
+
+        IBinder token = new Binder();
+        String tag = "acq_causes_wakeup";
+        String packageName = "pkg.name";
+
+        // First, ensure that a normal full wake lock does not cause a wakeup
+        int flags = PowerManager.FULL_WAKE_LOCK;
+        mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
+                null /* workSource */, null /* historyTag */);
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
+        mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
+
+        // Ensure that the flag does *NOT* work with a partial wake lock.
+        flags = PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
+        mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
+                null /* workSource */, null /* historyTag */);
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
+        mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
+
+        // Verify that flag forces a wakeup when paired to a FULL_WAKE_LOCK
+        flags = PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
+        mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
+                null /* workSource */, null /* historyTag */);
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
+        mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
+    }
+
+    @Test
+    public void testWakefulnessAwake_IPowerManagerWakeUp() throws Exception {
+        startSystem();
+        forceSleep();
+        mService.getBinderServiceInstance().wakeUp(SystemClock.uptimeMillis(),
+                PowerManager.WAKE_REASON_UNKNOWN, "testing IPowerManager.wakeUp()", "pkg.name");
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
+    }
+
+    /**
+     * Tests a series of variants that control whether a device wakes-up when it is plugged in
+     * or docked.
+     */
+    @Test
+    public void testWakefulnessAwake_ShouldWakeUpWhenPluggedIn() throws Exception {
+        boolean powerState;
+        startSystem();
+        forceSleep();
+
+        // Test 1:
+        // Set config to prevent it wake up, test, verify, reset config value.
+        when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_unplugTurnsOnScreen))
+                .thenReturn(false);
+        mService.readConfigurationLocked();
+        setPluggedIn(true);
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
+        when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_unplugTurnsOnScreen))
+                .thenReturn(true);
+        mService.readConfigurationLocked();
+
+        // Test 2:
+        // Turn the power off, sleep, then plug into a wireless charger.
+        // Verify that we do not wake up if the phone is being plugged into a wireless charger.
+        setPluggedIn(false);
+        forceSleep();
+        when(mBatteryManagerInternalMock.getPlugType())
+                .thenReturn(BatteryManager.BATTERY_PLUGGED_WIRELESS);
+        when(mWirelessChargerDetectorMock.update(true /* isPowered */,
+                BatteryManager.BATTERY_PLUGGED_WIRELESS)).thenReturn(false);
+        setPluggedIn(true);
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
+
+        // Test 3:
+        // Do not wake up if the phone is being REMOVED from a wireless charger
+        when(mBatteryManagerInternalMock.getPlugType()).thenReturn(0);
+        setPluggedIn(false);
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
+
+        // Test 4:
+        // Do not wake if we are dreaming.
+        forceAwake();  // Needs to be awake first before it can dream.
+        forceDream();
+        setPluggedIn(true);
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_DREAMING);
+        forceSleep();
+
+        // Test 5:
+        // Don't wake if the device is configured not to wake up in theater mode (and theater
+        // mode is enabled).
+        Settings.Global.putInt(
+                mContextSpy.getContentResolver(), Settings.Global.THEATER_MODE_ON, 1);
+        mUserSwitchedReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_USER_SWITCHED));
+        when(mResourcesSpy.getBoolean(
+                com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug))
+                .thenReturn(false);
+        setPluggedIn(false);
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
+        Settings.Global.putInt(
+                mContextSpy.getContentResolver(), Settings.Global.THEATER_MODE_ON, 0);
+        mUserSwitchedReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_USER_SWITCHED));
+
+        // Test 6:
+        // Don't wake up if we are Dozing away and always-on is enabled.
+        when(mAmbientDisplayConfigurationMock.alwaysOnEnabled(UserHandle.USER_CURRENT))
+                .thenReturn(true);
+        mUserSwitchedReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_USER_SWITCHED));
+        forceAwake();
+        forceDozing();
+        setPluggedIn(true);
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_DOZING);
+
+        // Test 7:
+        // Finally, take away all the factors above and ensure the device wakes up!
+        forceAwake();
+        forceSleep();
+        setPluggedIn(false);
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
+    }
+
+    @Test
+    public void testWakefulnessDoze_goToSleep() throws Exception {
+        // Start with AWAKE state
+        startSystem();
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
+
+        // Take a nap and verify.
+        mService.getBinderServiceInstance().goToSleep(SystemClock.uptimeMillis(),
+                PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0);
+        assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_DOZING);
+    }
+
+    @Test
     public void testWasDeviceIdleFor_true() {
         int interval = 1000;
         mService.onUserActivity();
-        SystemClock.sleep(interval);
+        SystemClock.sleep(interval + 1 /* just a little more */);
         assertThat(mService.wasDeviceIdleForInternal(interval)).isTrue();
     }
 
-    @SmallTest
+    @Test
     public void testWasDeviceIdleFor_false() {
         int interval = 1000;
         mService.onUserActivity();
         assertThat(mService.wasDeviceIdleForInternal(interval)).isFalse();
     }
 
-    @SmallTest
+    @Test
     public void testForceSuspend_putsDeviceToSleep() {
         mService.systemReady(null);
         mService.onBootPhase(SystemService.PHASE_BOOT_COMPLETED);
@@ -244,11 +491,11 @@
         assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
     }
 
-    @SmallTest
+    @Test
     public void testForceSuspend_pakeLocksDisabled() {
         final String tag = "TestWakelockTag_098213";
         final int flags = PowerManager.PARTIAL_WAKE_LOCK;
-        final String pkg = getContext().getOpPackageName();
+        final String pkg = mContextSpy.getOpPackageName();
 
         // Set up the Notification mock to keep track of the wakelocks that are currently
         // active or disabled. We'll use this to verify that wakelocks are disabled when
@@ -292,7 +539,7 @@
 
     }
 
-    @SmallTest
+    @Test
     public void testForceSuspend_forceSuspendFailurePropogated() {
         when(mNativeWrapperMock.nativeForceSuspend()).thenReturn(false);
         assertThat(mService.getBinderServiceInstance().forceSuspend()).isFalse();
diff --git a/services/tests/servicestests/src/com/android/server/rollback/AppDataRollbackHelperTest.java b/services/tests/servicestests/src/com/android/server/rollback/AppDataRollbackHelperTest.java
index d848b2d..7986055 100644
--- a/services/tests/servicestests/src/com/android/server/rollback/AppDataRollbackHelperTest.java
+++ b/services/tests/servicestests/src/com/android/server/rollback/AppDataRollbackHelperTest.java
@@ -31,7 +31,6 @@
 import android.content.pm.VersionedPackage;
 import android.content.rollback.PackageRollbackInfo;
 import android.content.rollback.PackageRollbackInfo.RestoreInfo;
-import android.content.rollback.RollbackInfo;
 import android.util.IntArray;
 import android.util.SparseLongArray;
 
@@ -46,8 +45,7 @@
 import java.io.File;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
+import java.util.Set;
 
 @RunWith(JUnit4.class)
 public class AppDataRollbackHelperTest {
@@ -236,24 +234,24 @@
         wasRecentlyRestored.getPendingRestores().add(
                 new RestoreInfo(73 /* userId */, 239 /* appId*/, "seInfo"));
 
-        RollbackData dataWithPendingBackup = new RollbackData(101, new File("/does/not/exist"), -1,
-                true);
-        dataWithPendingBackup.packages.add(pendingBackup);
+        RollbackData dataWithPendingBackup = new RollbackData(101, new File("/does/not/exist"), -1);
+        dataWithPendingBackup.info.getPackages().add(pendingBackup);
 
         RollbackData dataWithRecentRestore = new RollbackData(17239, new File("/does/not/exist"),
-                -1, true);
-        dataWithRecentRestore.packages.add(wasRecentlyRestored);
+                -1);
+        dataWithRecentRestore.info.getPackages().add(wasRecentlyRestored);
 
         RollbackData dataForDifferentUser = new RollbackData(17239, new File("/does/not/exist"),
-                -1, true);
-        dataForDifferentUser.packages.add(ignoredInfo);
+                -1);
+        dataForDifferentUser.info.getPackages().add(ignoredInfo);
 
-        RollbackInfo rollbackInfo = new RollbackInfo(17239,
-                Arrays.asList(pendingRestore, wasRecentlyRestored), false);
+        RollbackData dataForRestore = new RollbackData(17239, new File("/does/not/exist"), -1);
+        dataForRestore.info.getPackages().add(pendingRestore);
+        dataForRestore.info.getPackages().add(wasRecentlyRestored);
 
-        List<RollbackData> changed = helper.commitPendingBackupAndRestoreForUser(37,
-                Arrays.asList(dataWithPendingBackup, dataWithRecentRestore, dataForDifferentUser),
-                Collections.singletonList(rollbackInfo));
+        Set<RollbackData> changed = helper.commitPendingBackupAndRestoreForUser(37,
+                Arrays.asList(dataWithPendingBackup, dataWithRecentRestore, dataForDifferentUser,
+                    dataForRestore));
         InOrder inOrder = Mockito.inOrder(installer);
 
         // Check that pending backup and restore for the same package mutually destroyed each other.
@@ -267,9 +265,10 @@
         assertEquals(53, pendingBackup.getCeSnapshotInodes().get(37));
 
         // Check that changed returns correct RollbackData.
-        assertEquals(2, changed.size());
-        assertEquals(dataWithPendingBackup, changed.get(0));
-        assertEquals(dataWithRecentRestore, changed.get(1));
+        assertEquals(3, changed.size());
+        assertTrue(changed.contains(dataWithPendingBackup));
+        assertTrue(changed.contains(dataWithRecentRestore));
+        assertTrue(changed.contains(dataForRestore));
 
         // Check that restore was performed.
         inOrder.verify(installer).restoreAppDataSnapshot(
diff --git a/services/tests/servicestests/src/com/android/server/timezone/RulesManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/timezone/RulesManagerServiceTest.java
index 1b106dd..5c6fe0f 100644
--- a/services/tests/servicestests/src/com/android/server/timezone/RulesManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/timezone/RulesManagerServiceTest.java
@@ -16,34 +16,9 @@
 
 package com.android.server.timezone;
 
-import com.android.timezone.distro.DistroVersion;
-import com.android.timezone.distro.StagedDistroOperation;
-import com.android.timezone.distro.TimeZoneDistro;
-import com.android.timezone.distro.installer.TimeZoneDistroInstaller;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import android.app.timezone.Callback;
-import android.app.timezone.DistroRulesVersion;
-import android.app.timezone.ICallback;
-import android.app.timezone.RulesManager;
-import android.app.timezone.RulesState;
-import android.os.ParcelFileDescriptor;
-
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.concurrent.Executor;
-import javax.annotation.Nullable;
-
-import libcore.io.IoUtils;
-import libcore.timezone.TzDataSetVersion;
-
 import static com.android.server.timezone.RulesManagerService.REQUIRED_QUERY_PERMISSION;
 import static com.android.server.timezone.RulesManagerService.REQUIRED_UPDATER_PERMISSION;
+
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
@@ -61,11 +36,43 @@
 import static org.mockito.Mockito.verifyZeroInteractions;
 import static org.mockito.Mockito.when;
 
+import android.app.timezone.Callback;
+import android.app.timezone.DistroRulesVersion;
+import android.app.timezone.ICallback;
+import android.app.timezone.RulesManager;
+import android.app.timezone.RulesState;
+import android.os.ParcelFileDescriptor;
+
+import com.android.timezone.distro.DistroVersion;
+import com.android.timezone.distro.StagedDistroOperation;
+import com.android.timezone.distro.TimeZoneDistro;
+import com.android.timezone.distro.installer.TimeZoneDistroInstaller;
+
+import libcore.io.IoUtils;
+import libcore.timezone.TzDataSetVersion;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.concurrent.Executor;
+
+import javax.annotation.Nullable;
+
 /**
  * White box interaction / unit testing of the {@link RulesManagerService}.
  */
 public class RulesManagerServiceTest {
 
+    private static final int CURRENT_FORMAT_MAJOR_VERSION =
+            TzDataSetVersion.currentFormatMajorVersion();
+    private static final int CURRENT_FORMAT_MINOR_VERSION =
+            TzDataSetVersion.currentFormatMinorVersion();
+
     private RulesManagerService mRulesManagerService;
 
     private FakeExecutor mFakeExecutor;
@@ -116,8 +123,8 @@
     }
 
     @Test
-    public void getRulesState_systemRulesError() throws Exception {
-        configureDeviceCannotReadSystemRulesVersion();
+    public void getRulesState_baseVersionError() throws Exception {
+        configureDeviceCannotReadBaseVersion();
 
         assertNull(mRulesManagerService.getRulesState());
     }
@@ -126,18 +133,18 @@
     public void getRulesState_stagedInstall() throws Exception {
         configureCallerHasPermission();
 
-        configureDeviceSystemRulesVersion("2016a");
+        configureDeviceBaseVersion("2016a");
 
         DistroVersion stagedDistroVersion = new DistroVersion(
-                TzDataSetVersion.currentFormatMajorVersion(),
-                TzDataSetVersion.currentFormatMinorVersion() - 1,
+                CURRENT_FORMAT_MAJOR_VERSION,
+                CURRENT_FORMAT_MINOR_VERSION - 1,
                 "2016c",
-                3);
+                3 /* revision */);
         configureStagedInstall(stagedDistroVersion);
 
         DistroVersion installedDistroVersion = new DistroVersion(
-                TzDataSetVersion.currentFormatMajorVersion(),
-                TzDataSetVersion.currentFormatMinorVersion() - 1,
+                CURRENT_FORMAT_MAJOR_VERSION,
+                CURRENT_FORMAT_MINOR_VERSION - 1,
                 "2016b",
                 4);
         configureInstalledDistroVersion(installedDistroVersion);
@@ -158,13 +165,13 @@
     public void getRulesState_nothingStaged() throws Exception {
         configureCallerHasPermission();
 
-        configureDeviceSystemRulesVersion("2016a");
+        configureDeviceBaseVersion("2016a");
 
         configureNoStagedOperation();
 
         DistroVersion installedDistroVersion = new DistroVersion(
-                TzDataSetVersion.currentFormatMajorVersion(),
-                TzDataSetVersion.currentFormatMinorVersion() - 1,
+                CURRENT_FORMAT_MAJOR_VERSION,
+                CURRENT_FORMAT_MINOR_VERSION - 1,
                 "2016b",
                 4);
         configureInstalledDistroVersion(installedDistroVersion);
@@ -183,13 +190,13 @@
     public void getRulesState_uninstallStaged() throws Exception {
         configureCallerHasPermission();
 
-        configureDeviceSystemRulesVersion("2016a");
+        configureDeviceBaseVersion("2016a");
 
         configureStagedUninstall();
 
         DistroVersion installedDistroVersion = new DistroVersion(
-                TzDataSetVersion.currentFormatMajorVersion(),
-                TzDataSetVersion.currentFormatMinorVersion() - 1,
+                CURRENT_FORMAT_MAJOR_VERSION,
+                CURRENT_FORMAT_MINOR_VERSION - 1,
                 "2016b",
                 4);
         configureInstalledDistroVersion(installedDistroVersion);
@@ -208,8 +215,8 @@
     public void getRulesState_installedRulesError() throws Exception {
         configureCallerHasPermission();
 
-        String systemRulesVersion = "2016a";
-        configureDeviceSystemRulesVersion(systemRulesVersion);
+        String baseRulesVersion = "2016a";
+        configureDeviceBaseVersion(baseRulesVersion);
 
         configureStagedUninstall();
         configureDeviceCannotReadInstalledDistroVersion();
@@ -226,14 +233,14 @@
     public void getRulesState_stagedRulesError() throws Exception {
         configureCallerHasPermission();
 
-        String systemRulesVersion = "2016a";
-        configureDeviceSystemRulesVersion(systemRulesVersion);
+        String baseRulesVersion = "2016a";
+        configureDeviceBaseVersion(baseRulesVersion);
 
         configureDeviceCannotReadStagedDistroOperation();
 
         DistroVersion installedDistroVersion = new DistroVersion(
-                TzDataSetVersion.currentFormatMajorVersion(),
-                TzDataSetVersion.currentFormatMinorVersion() - 1,
+                CURRENT_FORMAT_MAJOR_VERSION,
+                CURRENT_FORMAT_MINOR_VERSION - 1,
                 "2016b",
                 4);
         configureInstalledDistroVersion(installedDistroVersion);
@@ -252,13 +259,13 @@
     public void getRulesState_noInstalledRules() throws Exception {
         configureCallerHasPermission();
 
-        String systemRulesVersion = "2016a";
-        configureDeviceSystemRulesVersion(systemRulesVersion);
+        String baseRulesVersion = "2016a";
+        configureDeviceBaseVersion(baseRulesVersion);
         configureNoStagedOperation();
         configureInstalledDistroVersion(null);
 
         RulesState expectedRuleState = new RulesState(
-                systemRulesVersion, RulesManagerService.DISTRO_FORMAT_VERSION_SUPPORTED,
+                baseRulesVersion, RulesManagerService.DISTRO_FORMAT_VERSION_SUPPORTED,
                 false /* operationInProgress */,
                 RulesState.STAGED_OPERATION_NONE, null /* stagedDistroRulesVersion */,
                 RulesState.DISTRO_STATUS_NONE, null /* installedDistroRulesVersion */);
@@ -269,15 +276,15 @@
     public void getRulesState_operationInProgress() throws Exception {
         configureCallerHasPermission();
 
-        String systemRulesVersion = "2016a";
+        String baseRulesVersion = "2016a";
         String installedRulesVersion = "2016b";
         int revision = 3;
 
-        configureDeviceSystemRulesVersion(systemRulesVersion);
+        configureDeviceBaseVersion(baseRulesVersion);
 
         DistroVersion installedDistroVersion = new DistroVersion(
-                TzDataSetVersion.currentFormatMajorVersion(),
-                TzDataSetVersion.currentFormatMinorVersion() - 1,
+                CURRENT_FORMAT_MAJOR_VERSION,
+                CURRENT_FORMAT_MINOR_VERSION - 1,
                 installedRulesVersion,
                 revision);
         configureInstalledDistroVersion(installedDistroVersion);
@@ -297,7 +304,7 @@
         DistroRulesVersion expectedInstalledDistroRulesVersion =
                 new DistroRulesVersion(installedRulesVersion, revision);
         RulesState expectedRuleState = new RulesState(
-                systemRulesVersion, RulesManagerService.DISTRO_FORMAT_VERSION_SUPPORTED,
+                baseRulesVersion, RulesManagerService.DISTRO_FORMAT_VERSION_SUPPORTED,
                 true /* operationInProgress */,
                 RulesState.STAGED_OPERATION_UNKNOWN, null /* stagedDistroRulesVersion */,
                 RulesState.DISTRO_STATUS_INSTALLED, expectedInstalledDistroRulesVersion);
@@ -858,11 +865,20 @@
                 .thenReturn(true);
 
         // Set up the mocks to return (arbitrary) information about the current device state.
-        when(mMockTimeZoneDistroInstaller.getSystemRulesVersion()).thenReturn("2017a");
-        when(mMockTimeZoneDistroInstaller.getInstalledDistroVersion()).thenReturn(
-                new DistroVersion(2, 3, "2017b", 4));
+        TzDataSetVersion baseVersion = new TzDataSetVersion(
+                CURRENT_FORMAT_MAJOR_VERSION, CURRENT_FORMAT_MINOR_VERSION, "2017a",
+                1 /* revision */);
+        when(mMockTimeZoneDistroInstaller.readBaseVersion()).thenReturn(baseVersion);
+        DistroVersion installedDistroVersion = new DistroVersion(
+                CURRENT_FORMAT_MAJOR_VERSION, CURRENT_FORMAT_MINOR_VERSION, "2017b",
+                4 /* revision */);
+        when(mMockTimeZoneDistroInstaller.getInstalledDistroVersion())
+                .thenReturn(installedDistroVersion);
+        DistroVersion stagedDistroVersion = new DistroVersion(
+                CURRENT_FORMAT_MAJOR_VERSION, CURRENT_FORMAT_MINOR_VERSION, "2017c",
+                7 /* revision */);
         when(mMockTimeZoneDistroInstaller.getStagedDistroOperation()).thenReturn(
-                StagedDistroOperation.install(new DistroVersion(5, 6, "2017c", 7)));
+                StagedDistroOperation.install(stagedDistroVersion));
 
         // Do the dump call.
         String dumpedOutput = doDumpCallAndCapture(rulesManagerService, args);
@@ -973,8 +989,11 @@
         return new CheckToken(1, new PackageVersions(1, 1));
     }
 
-    private void configureDeviceSystemRulesVersion(String systemRulesVersion) throws Exception {
-        when(mMockTimeZoneDistroInstaller.getSystemRulesVersion()).thenReturn(systemRulesVersion);
+    private void configureDeviceBaseVersion(String baseRulesVersion) throws Exception {
+        TzDataSetVersion tzDataSetVersion = new TzDataSetVersion(
+                CURRENT_FORMAT_MAJOR_VERSION, CURRENT_FORMAT_MINOR_VERSION, baseRulesVersion,
+                1 /* revision */);
+        when(mMockTimeZoneDistroInstaller.readBaseVersion()).thenReturn(tzDataSetVersion);
     }
 
     private void configureInstalledDistroVersion(@Nullable DistroVersion installedDistroVersion)
@@ -1002,8 +1021,8 @@
                 .thenThrow(new IOException("Simulated failure"));
     }
 
-    private void configureDeviceCannotReadSystemRulesVersion() throws Exception {
-        when(mMockTimeZoneDistroInstaller.getSystemRulesVersion())
+    private void configureDeviceCannotReadBaseVersion() throws Exception {
+        when(mMockTimeZoneDistroInstaller.readBaseVersion())
                 .thenThrow(new IOException("Simulated failure"));
     }
 
diff --git a/services/tests/uiservicestests/Android.bp b/services/tests/uiservicestests/Android.bp
index f4443fe..e4ab257 100644
--- a/services/tests/uiservicestests/Android.bp
+++ b/services/tests/uiservicestests/Android.bp
@@ -17,7 +17,7 @@
         "services.net",
         "services.usage",
         "guava",
-        "android-support-test",
+        "androidx.test.rules", "hamcrest-library",
         "mockito-target-inline-minus-junit4",
         "platform-test-annotations",
         "hamcrest-library",
diff --git a/services/tests/uiservicestests/src/com/android/server/UiServiceTestCase.java b/services/tests/uiservicestests/src/com/android/server/UiServiceTestCase.java
index 56d3a20..a1d48cc 100644
--- a/services/tests/uiservicestests/src/com/android/server/UiServiceTestCase.java
+++ b/services/tests/uiservicestests/src/com/android/server/UiServiceTestCase.java
@@ -16,15 +16,15 @@
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.when;
 
 import android.content.pm.PackageManagerInternal;
 import android.net.Uri;
 import android.os.Build;
-import android.support.test.InstrumentationRegistry;
 import android.testing.TestableContext;
 
+import androidx.test.InstrumentationRegistry;
+
 import com.android.server.uri.UriGrantsManagerInternal;
 
 import org.junit.Before;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/AlertRateLimiterTest.java b/services/tests/uiservicestests/src/com/android/server/notification/AlertRateLimiterTest.java
index d4c41e0..dc7f118 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/AlertRateLimiterTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/AlertRateLimiterTest.java
@@ -20,9 +20,10 @@
 import static junit.framework.Assert.assertFalse;
 import static junit.framework.Assert.assertTrue;
 
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Before;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/BadgeExtractorTest.java b/services/tests/uiservicestests/src/com/android/server/notification/BadgeExtractorTest.java
index cfc7430..e1f3913 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/BadgeExtractorTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/BadgeExtractorTest.java
@@ -15,26 +15,26 @@
  */
 package com.android.server.notification;
 
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertTrue;
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
 import static android.app.NotificationManager.IMPORTANCE_HIGH;
 import static android.app.NotificationManager.IMPORTANCE_UNSPECIFIED;
 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_BADGE;
 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_LIGHTS;
 
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import static org.mockito.Mockito.when;
+
 import android.app.ActivityManager;
 import android.app.Notification;
 import android.app.Notification.Builder;
 import android.app.NotificationChannel;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Before;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/BubbleExtractorTest.java b/services/tests/uiservicestests/src/com/android/server/notification/BubbleExtractorTest.java
index 3e01fb5..273a9e6 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/BubbleExtractorTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/BubbleExtractorTest.java
@@ -17,8 +17,6 @@
 
 import static android.app.NotificationManager.IMPORTANCE_HIGH;
 import static android.app.NotificationManager.IMPORTANCE_UNSPECIFIED;
-import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_BADGE;
-import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_LIGHTS;
 
 import static junit.framework.Assert.assertFalse;
 import static junit.framework.Assert.assertTrue;
@@ -31,9 +29,10 @@
 import android.app.NotificationChannel;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Before;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/BuzzBeepBlinkTest.java b/services/tests/uiservicestests/src/com/android/server/notification/BuzzBeepBlinkTest.java
index 20c5f5d..6be2c2e 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/BuzzBeepBlinkTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/BuzzBeepBlinkTest.java
@@ -62,13 +62,14 @@
 import android.provider.Settings;
 import android.service.notification.NotificationListenerService;
 import android.service.notification.StatusBarNotification;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.view.accessibility.AccessibilityEvent;
 import android.view.accessibility.AccessibilityManager;
 import android.view.accessibility.IAccessibilityManager;
 import android.view.accessibility.IAccessibilityManagerClient;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.internal.util.IntPair;
 import com.android.server.UiServiceTestCase;
 import com.android.server.lights.Light;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/GlobalSortKeyComparatorTest.java b/services/tests/uiservicestests/src/com/android/server/notification/GlobalSortKeyComparatorTest.java
index 97f2104..5041779 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/GlobalSortKeyComparatorTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/GlobalSortKeyComparatorTest.java
@@ -16,18 +16,16 @@
 package com.android.server.notification;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.eq;
 
 import android.app.Notification;
 import android.app.NotificationChannel;
 import android.app.NotificationManager;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Test;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java
index 84ef0c9..f652c5a 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java
@@ -25,6 +25,15 @@
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 
+import android.app.Notification;
+import android.os.UserHandle;
+import android.service.notification.StatusBarNotification;
+import android.test.suitebuilder.annotation.SmallTest;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.UiServiceTestCase;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -32,14 +41,6 @@
 import org.mockito.Mockito;
 import org.mockito.MockitoAnnotations;
 
-import android.app.Notification;
-import android.os.UserHandle;
-import android.service.notification.StatusBarNotification;
-import android.support.test.runner.AndroidJUnit4;
-import android.test.suitebuilder.annotation.SmallTest;
-
-import com.android.server.UiServiceTestCase;
-
 import java.util.ArrayList;
 import java.util.LinkedHashSet;
 import java.util.List;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ImportanceExtractorTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ImportanceExtractorTest.java
index abc6e3c..e9515fa 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ImportanceExtractorTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ImportanceExtractorTest.java
@@ -15,31 +15,30 @@
  */
 package com.android.server.notification;
 
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.ActivityManager;
-import android.app.Notification;
-import android.app.Notification.Builder;
-import android.app.NotificationManager;
-import android.app.NotificationChannel;
-import android.os.UserHandle;
-import android.service.notification.StatusBarNotification;
-import android.support.test.runner.AndroidJUnit4;
-import android.test.suitebuilder.annotation.SmallTest;
-
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
+import static org.junit.Assert.assertEquals;
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.when;
 
-import static org.junit.Assert.assertEquals;
+import android.app.ActivityManager;
+import android.app.Notification;
+import android.app.Notification.Builder;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.os.UserHandle;
+import android.service.notification.StatusBarNotification;
+import android.test.suitebuilder.annotation.SmallTest;
+
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.server.UiServiceTestCase;
 
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class ImportanceExtractorTest extends UiServiceTestCase {
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationChannelTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationChannelTest.java
index ca473c6..1408749 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationChannelTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationChannelTest.java
@@ -24,10 +24,11 @@
 import android.app.NotificationChannel;
 import android.net.Uri;
 import android.os.Parcel;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.util.Xml;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.internal.util.FastXmlSerializer;
 import com.android.server.UiServiceTestCase;
 
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java
index 0681295..e15af3d 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java
@@ -35,10 +35,11 @@
 import android.os.UserHandle;
 import android.provider.Settings;
 import android.service.notification.StatusBarNotification;
-import android.support.test.runner.AndroidJUnit4;
 import android.telecom.TelecomManager;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Before;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationListenerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationListenerServiceTest.java
index 2162f28..52c199a3 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationListenerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationListenerServiceTest.java
@@ -39,9 +39,10 @@
 import android.service.notification.NotificationListenerService.Ranking;
 import android.service.notification.NotificationRankingUpdate;
 import android.service.notification.SnoozeCriterion;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Test;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java
index b9ae7d5..9f11472 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java
@@ -56,8 +56,9 @@
 import android.provider.Settings;
 import android.service.notification.Adjustment;
 import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.R;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationStatsTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationStatsTest.java
index bae8564..20d7a2a 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationStatsTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationStatsTest.java
@@ -17,7 +17,6 @@
 
 import static android.service.notification.NotificationStats.DISMISSAL_PEEK;
 import static android.service.notification.NotificationStats.DISMISS_SENTIMENT_NEGATIVE;
-import static android.service.notification.NotificationStats.DISMISS_SENTIMENT_POSITIVE;
 
 import static junit.framework.Assert.assertEquals;
 import static junit.framework.Assert.assertFalse;
@@ -25,9 +24,10 @@
 
 import android.os.Parcel;
 import android.service.notification.NotificationStats;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Test;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationTest.java
index 55c16b3..0ea53fa 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationTest.java
@@ -22,20 +22,18 @@
 
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.anyInt;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.when;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
 
 import android.app.ActivityManager;
 import android.app.Notification;
-import android.app.Person;
 import android.app.PendingIntent;
+import android.app.Person;
 import android.app.RemoteInput;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
 import android.content.res.Resources;
 import android.graphics.Bitmap;
 import android.graphics.Color;
@@ -43,14 +41,15 @@
 import android.graphics.drawable.Icon;
 import android.net.Uri;
 import android.os.Build;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.text.SpannableStringBuilder;
 import android.text.Spanned;
 import android.text.style.StyleSpan;
 import android.util.Pair;
 import android.widget.RemoteViews;
 
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Before;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotifyingAppTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotifyingAppTest.java
index fbb8c33..25e10d0 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotifyingAppTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotifyingAppTest.java
@@ -20,9 +20,10 @@
 
 import android.os.Parcel;
 import android.service.notification.NotifyingApp;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Test;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
index 05bb307..39e47ec 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
@@ -59,13 +59,14 @@
 import android.os.UserHandle;
 import android.provider.Settings;
 import android.provider.Settings.Secure;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.testing.TestableContentResolver;
 import android.util.ArrayMap;
 import android.util.Xml;
 
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.internal.util.FastXmlSerializer;
 import com.android.server.UiServiceTestCase;
 
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/RankingHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/RankingHelperTest.java
index b322887..2abd340 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/RankingHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/RankingHelperTest.java
@@ -41,13 +41,13 @@
 import android.net.Uri;
 import android.os.Build;
 import android.os.UserHandle;
-import android.provider.Settings.Secure;
 import android.service.notification.StatusBarNotification;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.testing.TestableContentResolver;
 
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Before;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/RateEstimatorTest.java b/services/tests/uiservicestests/src/com/android/server/notification/RateEstimatorTest.java
index 5d8d48f1..68aa1dc 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/RateEstimatorTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/RateEstimatorTest.java
@@ -15,17 +15,19 @@
  */
 package com.android.server.notification;
 
-import android.support.test.runner.AndroidJUnit4;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
 import android.test.suitebuilder.annotation.SmallTest;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.UiServiceTestCase;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-
-import com.android.server.UiServiceTestCase;
-
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class RateEstimatorTest extends UiServiceTestCase {
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ScheduleCalendarTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ScheduleCalendarTest.java
index 110e3fe..042c9d9 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ScheduleCalendarTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ScheduleCalendarTest.java
@@ -23,14 +23,14 @@
 
 import android.service.notification.ScheduleCalendar;
 import android.service.notification.ZenModeConfig;
-import android.support.test.filters.FlakyTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.filters.FlakyTest;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Before;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ScheduleConditionProviderTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ScheduleConditionProviderTest.java
index efa70e7..551e186 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ScheduleConditionProviderTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ScheduleConditionProviderTest.java
@@ -10,11 +10,11 @@
 import android.service.notification.Condition;
 import android.service.notification.ScheduleCalendar;
 import android.service.notification.ZenModeConfig;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Before;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/SnoozeHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/SnoozeHelperTest.java
index 174c5fa..1e64543 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/SnoozeHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/SnoozeHelperTest.java
@@ -15,12 +15,17 @@
  */
 package com.android.server.notification;
 
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyLong;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import android.app.AlarmManager;
 import android.app.Notification;
@@ -30,24 +35,19 @@
 import android.os.SystemClock;
 import android.os.UserHandle;
 import android.service.notification.StatusBarNotification;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.util.IntArray;
 
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyLong;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.server.UiServiceTestCase;
 
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
 
 @SmallTest
 @RunWith(AndroidJUnit4.class)
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ValidateNotificationPeopleTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ValidateNotificationPeopleTest.java
index 025b11a..b1ee120 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ValidateNotificationPeopleTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ValidateNotificationPeopleTest.java
@@ -15,23 +15,24 @@
  */
 package com.android.server.notification;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
 import android.app.Notification;
 import android.app.Person;
 import android.os.Bundle;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.text.SpannableString;
 
-import java.util.ArrayList;
-import java.util.Arrays;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.UiServiceTestCase;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertEquals;
-
-import com.android.server.UiServiceTestCase;
+import java.util.ArrayList;
+import java.util.Arrays;
 
 @SmallTest
 @RunWith(AndroidJUnit4.class)
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java
index 9c7e028..dcab78e 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java
@@ -28,10 +28,11 @@
 import android.service.notification.ZenModeConfig;
 import android.service.notification.ZenModeConfig.EventInfo;
 import android.service.notification.ZenPolicy;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.util.Xml;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.internal.util.FastXmlSerializer;
 import com.android.server.UiServiceTestCase;
 
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenPolicyTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenPolicyTest.java
index 7c6b1c1..a0ee417 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ZenPolicyTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenPolicyTest.java
@@ -19,14 +19,14 @@
 import static junit.framework.Assert.assertEquals;
 
 import android.service.notification.ZenPolicy;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.Mock;
 
 @SmallTest
 @RunWith(AndroidJUnit4.class)
diff --git a/services/tests/uiservicestests/src/com/android/server/slice/PackageMatchingCacheTest.java b/services/tests/uiservicestests/src/com/android/server/slice/PackageMatchingCacheTest.java
index c6aea88..f6c854e 100644
--- a/services/tests/uiservicestests/src/com/android/server/slice/PackageMatchingCacheTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/slice/PackageMatchingCacheTest.java
@@ -21,10 +21,11 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.server.UiServiceTestCase;
 import com.android.server.slice.SliceManagerService.PackageMatchingCache;
 
diff --git a/services/tests/uiservicestests/src/com/android/server/slice/PinnedSliceStateTest.java b/services/tests/uiservicestests/src/com/android/server/slice/PinnedSliceStateTest.java
index a71aca5..4c2822a 100644
--- a/services/tests/uiservicestests/src/com/android/server/slice/PinnedSliceStateTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/slice/PinnedSliceStateTest.java
@@ -26,11 +26,12 @@
 import android.os.IBinder;
 import android.os.IBinder.DeathRecipient;
 import android.os.RemoteException;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Before;
diff --git a/services/tests/uiservicestests/src/com/android/server/slice/SliceClientPermissionsTest.java b/services/tests/uiservicestests/src/com/android/server/slice/SliceClientPermissionsTest.java
index 1efa415..ff2236d 100644
--- a/services/tests/uiservicestests/src/com/android/server/slice/SliceClientPermissionsTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/slice/SliceClientPermissionsTest.java
@@ -24,14 +24,15 @@
 
 import android.content.ContentResolver;
 import android.net.Uri;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.util.Xml.Encoding;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.server.UiServiceTestCase;
-import com.android.server.slice.SlicePermissionManager.PkgUser;
 import com.android.server.slice.SliceClientPermissions.SliceAuthority;
+import com.android.server.slice.SlicePermissionManager.PkgUser;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
diff --git a/services/tests/uiservicestests/src/com/android/server/slice/SliceFullAccessListTest.java b/services/tests/uiservicestests/src/com/android/server/slice/SliceFullAccessListTest.java
index bc28150..d942c5a 100644
--- a/services/tests/uiservicestests/src/com/android/server/slice/SliceFullAccessListTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/slice/SliceFullAccessListTest.java
@@ -19,9 +19,10 @@
 import static org.junit.Assert.assertTrue;
 
 import android.os.UserHandle;
-import android.support.test.filters.SmallTest;
 import android.util.Xml.Encoding;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Before;
diff --git a/services/tests/uiservicestests/src/com/android/server/slice/SliceManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/slice/SliceManagerServiceTest.java
index 6d4f5f8..7182f0f 100644
--- a/services/tests/uiservicestests/src/com/android/server/slice/SliceManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/slice/SliceManagerServiceTest.java
@@ -34,18 +34,18 @@
 import android.app.AppOpsManager;
 import android.app.slice.SliceSpec;
 import android.app.usage.UsageStatsManagerInternal;
-import android.content.pm.PackageManagerInternal;
 import android.net.Uri;
 import android.os.Binder;
 import android.os.IBinder;
 import android.os.Process;
 import android.os.RemoteException;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableContext;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.server.LocalServices;
 import com.android.server.UiServiceTestCase;
 
diff --git a/services/tests/uiservicestests/src/com/android/server/slice/SlicePermissionManagerTest.java b/services/tests/uiservicestests/src/com/android/server/slice/SlicePermissionManagerTest.java
index efefee1..1872530b 100644
--- a/services/tests/uiservicestests/src/com/android/server/slice/SlicePermissionManagerTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/slice/SlicePermissionManagerTest.java
@@ -23,13 +23,14 @@
 import android.net.Uri;
 import android.net.Uri.Builder;
 import android.os.FileUtils;
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.util.Log;
 import android.util.Xml.Encoding;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.server.UiServiceTestCase;
 
 import org.junit.Test;
diff --git a/services/tests/uiservicestests/src/com/android/server/slice/SliceProviderPermissionsTest.java b/services/tests/uiservicestests/src/com/android/server/slice/SliceProviderPermissionsTest.java
index 5775991..8e61d21 100644
--- a/services/tests/uiservicestests/src/com/android/server/slice/SliceProviderPermissionsTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/slice/SliceProviderPermissionsTest.java
@@ -20,11 +20,12 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 
-import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.util.Xml.Encoding;
 
+import androidx.test.filters.SmallTest;
+
 import com.android.server.UiServiceTestCase;
 import com.android.server.slice.SlicePermissionManager.PkgUser;
 import com.android.server.slice.SliceProviderPermissions.SliceAuthority;
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
index a1db3e8..1319bad 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
@@ -406,7 +406,7 @@
     }
 
     @Test
-    public void testFixedScreenConfigurationWhenMovingToDisplay() {
+    public void testSizeCompatMode_FixedScreenConfigurationWhenMovingToDisplay() {
         // Initialize different bounds on a new display.
         final ActivityDisplay newDisplay = addNewActivityDisplayAt(ActivityDisplay.POSITION_TOP);
         newDisplay.setBounds(0, 0, 1000, 2000);
@@ -431,7 +431,7 @@
     }
 
     @Test
-    public void testFixedScreenBoundsWhenDisplaySizeChanged() {
+    public void testSizeCompatMode_FixedScreenBoundsWhenDisplaySizeChanged() {
         when(mActivity.mAppWindowToken.getOrientationIgnoreVisibility()).thenReturn(
                 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
         mTask.getWindowConfiguration().setAppBounds(mStack.getDisplay().getBounds());
@@ -446,4 +446,28 @@
 
         assertEquals(originalBounds, mActivity.getBounds());
     }
+
+    @Test
+    public void testSizeCompatMode_FixedScreenLayoutSizeBits() {
+        final int fixedScreenLayout = Configuration.SCREENLAYOUT_LONG_NO
+                | Configuration.SCREENLAYOUT_SIZE_NORMAL;
+        mTask.getConfiguration().screenLayout = fixedScreenLayout
+                | Configuration.SCREENLAYOUT_LAYOUTDIR_LTR;
+        mTask.getWindowConfiguration().setAppBounds(mStack.getDisplay().getBounds());
+        mActivity.info.resizeMode = ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
+        mActivity.info.maxAspectRatio = 1.5f;
+        ensureActivityConfiguration();
+
+        // The initial configuration should inherit from parent.
+        assertEquals(mTask.getConfiguration().screenLayout,
+                mActivity.getConfiguration().screenLayout);
+
+        mTask.getConfiguration().screenLayout = Configuration.SCREENLAYOUT_LAYOUTDIR_RTL
+                | Configuration.SCREENLAYOUT_LONG_YES | Configuration.SCREENLAYOUT_SIZE_LARGE;
+        mActivity.onConfigurationChanged(mTask.getConfiguration());
+
+        // The size and aspect ratio bits don't change, but the layout direction should be updated.
+        assertEquals(fixedScreenLayout | Configuration.SCREENLAYOUT_LAYOUTDIR_RTL,
+                mActivity.getConfiguration().screenLayout);
+    }
 }
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenAnimationTests.java b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenAnimationTests.java
index e007c86..a98a604 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenAnimationTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenAnimationTests.java
@@ -29,7 +29,6 @@
 import android.platform.test.annotations.Presubmit;
 import android.view.SurfaceControl;
 
-import androidx.test.filters.FlakyTest;
 import androidx.test.filters.SmallTest;
 
 import com.android.server.wm.WindowTestUtils.TestAppWindowToken;
@@ -49,7 +48,6 @@
  */
 @SmallTest
 @Presubmit
-@FlakyTest(bugId = 124357362)
 public class AppWindowTokenAnimationTests extends WindowTestsBase {
 
     private TestAppWindowToken mToken;
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java
index 2c575f5..68b40b9 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java
@@ -18,11 +18,11 @@
 
 import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
 import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
-import static android.content.ActivityInfoProto.SCREEN_ORIENTATION_UNSPECIFIED;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_BEHIND;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSET;
+import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
 import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
 import static android.view.WindowManager.LayoutParams.FIRST_SUB_WINDOW;
 import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
@@ -42,12 +42,16 @@
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.verify;
 
 import android.content.res.Configuration;
 import android.graphics.Point;
 import android.graphics.Rect;
 import android.platform.test.annotations.Presubmit;
+import android.view.Display;
 import android.view.Surface;
 import android.view.WindowManager;
 
@@ -55,6 +59,7 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.mockito.Mockito;
 
 /**
  * Tests for the {@link AppWindowToken} class.
@@ -332,6 +337,46 @@
     }
 
     @Test
+    public void testReportOrientationChangeOnVisibilityChange() {
+        synchronized (mWm.mGlobalLock) {
+            mToken.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
+
+            mDisplayContent.getDisplayRotation().setFixedToUserRotation(
+                    DisplayRotation.FIXED_TO_USER_ROTATION_ENABLED);
+
+            doReturn(Configuration.ORIENTATION_LANDSCAPE).when(mToken.mActivityRecord)
+                    .getRequestedConfigurationOrientation();
+
+            mTask.mTaskRecord = Mockito.mock(TaskRecord.class, RETURNS_DEEP_STUBS);
+            mToken.commitVisibility(null, false /* visible */, TRANSIT_UNSET,
+                    true /* performLayout */, false /* isVoiceInteraction */);
+        }
+
+        verify(mTask.mTaskRecord).onConfigurationChanged(any(Configuration.class));
+    }
+
+    @Test
+    public void testReportOrientationChangeOnOpeningClosingAppChange() {
+        synchronized (mWm.mGlobalLock) {
+            mToken.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
+
+            mDisplayContent.getDisplayRotation().setFixedToUserRotation(
+                    DisplayRotation.FIXED_TO_USER_ROTATION_ENABLED);
+            mDisplayContent.getDisplayInfo().state = Display.STATE_ON;
+            mDisplayContent.prepareAppTransition(WindowManager.TRANSIT_ACTIVITY_CLOSE,
+                    false /* alwaysKeepCurrent */, 0 /* flags */, true /* forceOverride */);
+
+            doReturn(Configuration.ORIENTATION_LANDSCAPE).when(mToken.mActivityRecord)
+                    .getRequestedConfigurationOrientation();
+
+            mTask.mTaskRecord = Mockito.mock(TaskRecord.class, RETURNS_DEEP_STUBS);
+            mToken.setVisibility(false, false);
+        }
+
+        verify(mTask.mTaskRecord).onConfigurationChanged(any(Configuration.class));
+    }
+
+    @Test
     public void testCreateRemoveStartingWindow() {
         mToken.addStartingWindow(mPackageName,
                 android.R.style.Theme, null, "Test", 0, 0, 0, 0, null, true, true, false, true,
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
index 69f7ced..b26aa05 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
@@ -68,7 +68,6 @@
 import android.view.ViewRootImpl;
 import android.view.test.InsetsModeSession;
 
-import androidx.test.filters.FlakyTest;
 import androidx.test.filters.SmallTest;
 
 import com.android.dx.mockito.inline.extended.ExtendedMockito;
@@ -97,7 +96,6 @@
 public class DisplayContentTests extends WindowTestsBase {
 
     @Test
-    @FlakyTest(detail = "Promote to presubmit when shown to be stable.")
     public void testForAllWindows() {
         final WindowState exitingAppWindow = createWindow(null, TYPE_BASE_APPLICATION,
                 mDisplayContent, "exiting app");
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTests.java
index 8349ac7f..07dd93c 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTests.java
@@ -25,20 +25,27 @@
 import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
 import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
 import static android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
+import static android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_SEAMLESS;
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
 import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
 import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
 
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
 import static com.android.server.policy.WindowManagerPolicy.NAV_BAR_BOTTOM;
 import static com.android.server.policy.WindowManagerPolicy.NAV_BAR_RIGHT;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.when;
 
 import android.graphics.PixelFormat;
 import android.platform.test.annotations.Presubmit;
+import android.view.Surface;
 import android.view.WindowManager;
 
 import androidx.test.filters.SmallTest;
@@ -196,4 +203,33 @@
                 DisplayPolicy.updateLightNavigationBarLw(0, opaqueDarkNavBar,
                         opaqueDarkNavBar, imeDrawLightNavBar, imeDrawLightNavBar));
     }
+
+    @Test
+    public void testShouldRotateSeamlessly() {
+        final DisplayPolicy policy = mDisplayContent.getDisplayPolicy();
+        final WindowManager.LayoutParams attrs = mAppWindow.mAttrs;
+        attrs.x = attrs.y = 0;
+        attrs.height = attrs.width = WindowManager.LayoutParams.MATCH_PARENT;
+        attrs.rotationAnimation = ROTATION_ANIMATION_SEAMLESS;
+        final DisplayRotation displayRotation = mock(DisplayRotation.class);
+        doReturn(Surface.ROTATION_180).when(displayRotation).getUpsideDownRotation();
+
+        synchronized (mWm.mGlobalLock) {
+            policy.focusChangedLw(null /* lastFocus */, mAppWindow);
+            policy.applyPostLayoutPolicyLw(
+                    mAppWindow, attrs, null /* attached */, null /* imeTarget */);
+            spyOn(policy);
+            doReturn(true).when(policy).navigationBarCanMove();
+            // The focused fullscreen opaque window without override bounds should be able to be
+            // rotated seamlessly.
+            assertTrue(policy.shouldRotateSeamlessly(
+                    displayRotation, Surface.ROTATION_0, Surface.ROTATION_90));
+
+            spyOn(mAppWindow.mAppToken);
+            doReturn(false).when(mAppWindow.mAppToken).matchParentBounds();
+            // No seamless rotation if the window may be positioned with offset after rotation.
+            assertFalse(policy.shouldRotateSeamlessly(
+                    displayRotation, Surface.ROTATION_0, Surface.ROTATION_90));
+        }
+    }
 }
diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
index 3e025f6..fc1eb1c 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
@@ -30,7 +30,6 @@
 import static android.view.Display.DEFAULT_DISPLAY;
 
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.spy;
 
 import static com.google.common.truth.Truth.assertThat;
 import static com.google.common.truth.Truth.assertWithMessage;
@@ -96,6 +95,7 @@
     private TestActivityTaskManagerService mTestService;
     private ActivityDisplay mDisplay;
     private ActivityDisplay mOtherDisplay;
+    private ActivityDisplay mSingleTaskDisplay;
     private ActivityStack mStack;
     private ActivityStack mHomeStack;
     private TestTaskPersister mTaskPersister;
@@ -547,6 +547,41 @@
         assertTrimmed(mTasks.get(0), mTasks.get(1));
     }
 
+    /**
+     * Tests that tasks on singleTaskDisplay are not visible and not trimmed/removed.
+     */
+    @Test
+    public void testVisibleTasks_singleTaskDisplay() {
+        mRecentTasks.setOnlyTestVisibleRange();
+        mRecentTasks.setParameters(-1 /* min */, 3 /* max */, -1 /* ms */);
+
+        ActivityStack singleTaskStack = mSingleTaskDisplay.createStack(
+                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
+
+        TaskRecord excludedTask1 = createTaskBuilder(".ExcludedTask1")
+                .setStack(singleTaskStack)
+                .build();
+
+        assertFalse("Tasks on singleTaskDisplay should not be visible recents",
+                mRecentTasks.isVisibleRecentTask(excludedTask1));
+
+        mRecentTasks.add(excludedTask1);
+
+        // Add N+1 visible tasks.
+        mRecentTasks.add(mTasks.get(0));
+        mRecentTasks.add(mTasks.get(1));
+        mRecentTasks.add(mTasks.get(2));
+        mRecentTasks.add(mTasks.get(3));
+
+        // excludedTask is not trimmed.
+        assertTrimmed(mTasks.get(0));
+
+        mRecentTasks.removeAllVisibleTasks();
+
+        // Only visible tasks removed.
+        assertTrimmed(mTasks.get(0), mTasks.get(1), mTasks.get(2), mTasks.get(3));
+    }
+
     @Test
     public void testBackStackTasks_expectNoTrim() {
         mRecentTasks.setParameters(-1 /* min */, 1 /* max */, -1 /* ms */);
@@ -879,8 +914,12 @@
             super.createDefaultDisplay();
             mDisplay = mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
             mOtherDisplay = TestActivityDisplay.create(mTestStackSupervisor, DEFAULT_DISPLAY + 1);
+            mSingleTaskDisplay = TestActivityDisplay.create(mTestStackSupervisor,
+                    DEFAULT_DISPLAY + 2);
+            mSingleTaskDisplay.setDisplayToSingleTaskInstance();
             mRootActivityContainer.addChild(mOtherDisplay, ActivityDisplay.POSITION_TOP);
             mRootActivityContainer.addChild(mDisplay, ActivityDisplay.POSITION_TOP);
+            mRootActivityContainer.addChild(mSingleTaskDisplay, ActivityDisplay.POSITION_TOP);
         }
     }
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java b/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java
index 6cce9f0..c483489 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java
@@ -213,7 +213,8 @@
         final Animation a = new TranslateAnimation(-10, 10, 0, 0);
         a.initialize(0, 0, 0, 0);
         a.setDuration(50);
-        return new WindowAnimationSpec(a, new Point(0, 0), false /* canSkipFirstFrame */);
+        return new WindowAnimationSpec(a, new Point(0, 0), false /* canSkipFirstFrame */,
+                0 /* windowCornerRadius */);
     }
 
     /**
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java
index ace179a..cdbb121 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java
@@ -29,13 +29,11 @@
 import static android.util.DisplayMetrics.DENSITY_DEFAULT;
 import static android.view.Display.DEFAULT_DISPLAY;
 
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.when;
 import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_CONTINUE;
 import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_SKIP;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
 
 import android.app.ActivityOptions;
 import android.content.pm.ActivityInfo;
@@ -474,6 +472,22 @@
     }
 
     @Test
+    public void testUsesFullscreenWhenRequestedOnFreeformDisplay() {
+        final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+                WINDOWING_MODE_FREEFORM);
+
+        final ActivityOptions options = ActivityOptions.makeBasic();
+        options.setLaunchDisplayId(freeformDisplay.mDisplayId);
+        options.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);
+
+        assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, /* layout */ null,
+                mActivity, /* source */ null, options, mCurrent, mResult));
+
+        assertEquivalentWindowingMode(WINDOWING_MODE_FULLSCREEN, mResult.mWindowingMode,
+                WINDOWING_MODE_FREEFORM);
+    }
+
+    @Test
     public void testUsesFreeformByDefaultForPostNApp() {
         final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
                 WINDOWING_MODE_FREEFORM);
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskStackTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskStackTests.java
index b1f942e..70ed62a 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskStackTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskStackTests.java
@@ -175,10 +175,14 @@
     @Test
     public void testStackOutset() {
         final TaskStack stack = createTaskStackOnDisplay(mDisplayContent);
-        spyOn(stack);
-
         final int stackOutset = 10;
-        doReturn(stackOutset).when(stack).getStackOutset();
+        // Clear the handler and hold the lock for mock, to prevent multi-thread issue.
+        waitUntilHandlersIdle();
+        synchronized (mWm.mGlobalLock) {
+            spyOn(stack);
+
+            doReturn(stackOutset).when(stack).getStackOutset();
+        }
 
         final Rect stackBounds = new Rect(200, 200, 800, 1000);
         // Update surface position and size by the given bounds.
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowAnimationSpecTest.java b/services/tests/wmtests/src/com/android/server/wm/WindowAnimationSpecTest.java
index 9a825e0..897f0a2 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowAnimationSpecTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowAnimationSpecTest.java
@@ -24,6 +24,8 @@
 
 import static org.mockito.ArgumentMatchers.argThat;
 import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.when;
 
 import android.graphics.Point;
 import android.graphics.Rect;
@@ -56,7 +58,7 @@
         Animation a = createClipRectAnimation(windowCrop, windowCrop);
         WindowAnimationSpec windowAnimationSpec = new WindowAnimationSpec(a, null,
                 mStackBounds, false /* canSkipFirstFrame */, STACK_CLIP_NONE,
-                true /* isAppAnimation */);
+                true /* isAppAnimation */, 0 /* windowCornerRadius */);
         windowAnimationSpec.apply(mTransaction, mSurfaceControl, 0);
         verify(mTransaction).setWindowCrop(eq(mSurfaceControl),
                 argThat(rect -> rect.equals(windowCrop)));
@@ -66,7 +68,7 @@
     public void testApply_clipAfter() {
         WindowAnimationSpec windowAnimationSpec = new WindowAnimationSpec(mAnimation, null,
                 mStackBounds, false /* canSkipFirstFrame */, STACK_CLIP_AFTER_ANIM,
-                true /* isAppAnimation */);
+                true /* isAppAnimation */, 0 /* windowCornerRadius */);
         windowAnimationSpec.apply(mTransaction, mSurfaceControl, 0);
         verify(mTransaction).setWindowCrop(eq(mSurfaceControl), argThat(Rect::isEmpty));
     }
@@ -76,8 +78,7 @@
         // Stack bounds is (0, 0, 10, 10) position is (20, 40)
         WindowAnimationSpec windowAnimationSpec = new WindowAnimationSpec(mAnimation,
                 new Point(20, 40), mStackBounds, false /* canSkipFirstFrame */,
-                STACK_CLIP_AFTER_ANIM,
-                true /* isAppAnimation */);
+                STACK_CLIP_AFTER_ANIM, true /* isAppAnimation */, 0 /* windowCornerRadius */);
         windowAnimationSpec.apply(mTransaction, mSurfaceControl, 0);
         verify(mTransaction).setWindowCrop(eq(mSurfaceControl), argThat(Rect::isEmpty));
     }
@@ -87,7 +88,7 @@
         // Stack bounds is (0, 0, 10, 10) animation clip is (0, 0, 0, 0)
         WindowAnimationSpec windowAnimationSpec = new WindowAnimationSpec(mAnimation, null,
                 mStackBounds, false /* canSkipFirstFrame */, STACK_CLIP_BEFORE_ANIM,
-                true /* isAppAnimation */);
+                true /* isAppAnimation */, 0 /* windowCornerRadius */);
         windowAnimationSpec.apply(mTransaction, mSurfaceControl, 0);
         verify(mTransaction).setWindowCrop(eq(mSurfaceControl),
                 argThat(rect -> rect.equals(mStackBounds)));
@@ -101,19 +102,32 @@
         a.initialize(0, 0, 0, 0);
         WindowAnimationSpec windowAnimationSpec = new WindowAnimationSpec(a, null,
                 null, false /* canSkipFirstFrame */, STACK_CLIP_BEFORE_ANIM,
-                true /* isAppAnimation */);
+                true /* isAppAnimation */, 0 /* windowCornerRadius */);
         windowAnimationSpec.apply(mTransaction, mSurfaceControl, 0);
         verify(mTransaction).setWindowCrop(eq(mSurfaceControl), argThat(Rect::isEmpty));
     }
 
     @Test
+    public void testApply_setCornerRadius() {
+        final float windowCornerRadius = 30f;
+        WindowAnimationSpec windowAnimationSpec = new WindowAnimationSpec(mAnimation, null,
+                mStackBounds, false /* canSkipFirstFrame */, STACK_CLIP_BEFORE_ANIM,
+                true /* isAppAnimation */, windowCornerRadius);
+        windowAnimationSpec.apply(mTransaction, mSurfaceControl, 0);
+        verify(mTransaction, never()).setCornerRadius(eq(mSurfaceControl), eq(windowCornerRadius));
+        when(mAnimation.hasRoundedCorners()).thenReturn(true);
+        windowAnimationSpec.apply(mTransaction, mSurfaceControl, 0);
+        verify(mTransaction).setCornerRadius(eq(mSurfaceControl), eq(windowCornerRadius));
+    }
+
+    @Test
     public void testApply_clipBeforeSmallerAnimationClip() {
         // Stack bounds is (0, 0, 10, 10) animation clip is (0, 0, 5, 5)
         Rect windowCrop = new Rect(0, 0, 5, 5);
         Animation a = createClipRectAnimation(windowCrop, windowCrop);
         WindowAnimationSpec windowAnimationSpec = new WindowAnimationSpec(a, null,
                 mStackBounds, false /* canSkipFirstFrame */, STACK_CLIP_BEFORE_ANIM,
-                true /* isAppAnimation */);
+                true /* isAppAnimation */, 0 /* windowCornerRadius */);
         windowAnimationSpec.apply(mTransaction, mSurfaceControl, 0);
         verify(mTransaction).setWindowCrop(eq(mSurfaceControl),
                 argThat(rect -> rect.equals(windowCrop)));
@@ -126,7 +140,7 @@
         Animation a = createClipRectAnimation(windowCrop, windowCrop);
         WindowAnimationSpec windowAnimationSpec = new WindowAnimationSpec(a, null,
                 mStackBounds, false /* canSkipFirstFrame */, STACK_CLIP_BEFORE_ANIM,
-                true /* isAppAnimation */);
+                true /* isAppAnimation */, 0 /* windowCornerRadius */);
         windowAnimationSpec.apply(mTransaction, mSurfaceControl, 0);
         verify(mTransaction).setWindowCrop(eq(mSurfaceControl),
                 argThat(rect -> rect.equals(mStackBounds)));
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
index b0e20b8..b03f63b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
@@ -110,8 +110,11 @@
         // TODO: Let the insets source with new mode keep the visibility control, and remove this
         // setup code. Now mTopFullscreenOpaqueWindowState will take back the control of insets
         // visibility.
-        spyOn(mDisplayContent);
-        doNothing().when(mDisplayContent).layoutAndAssignWindowLayersIfNeeded();
+        // Hold the lock to protect the mock from accesssing by other threads.
+        synchronized (mWm.mGlobalLock) {
+            spyOn(mDisplayContent);
+            doNothing().when(mDisplayContent).layoutAndAssignWindowLayersIfNeeded();
+        }
     }
 
     @Test
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
index da1defa..0dec8ee 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
@@ -82,6 +82,8 @@
             }, new ComponentName("", ""), false, dc, true /* fillsParent */);
             mTargetSdk = Build.VERSION_CODES.CUR_DEVELOPMENT;
             mSkipOnParentChanged = skipOnParentChanged;
+            mActivityRecord = mock(ActivityRecord.class);
+            mActivityRecord.app = mock(WindowProcessController.class);
         }
 
         int getWindowsCount() {
diff --git a/services/usage/java/com/android/server/usage/AppStandbyController.java b/services/usage/java/com/android/server/usage/AppStandbyController.java
index 65ed85d..ffafb6d 100644
--- a/services/usage/java/com/android/server/usage/AppStandbyController.java
+++ b/services/usage/java/com/android/server/usage/AppStandbyController.java
@@ -35,6 +35,7 @@
 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYNC_ADAPTER;
 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYSTEM_INTERACTION;
 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYSTEM_UPDATE;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED;
 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_USER_INTERACTION;
 import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_ACTIVE;
 import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_EXEMPTED;
@@ -197,7 +198,7 @@
     static final int MSG_ONE_TIME_CHECK_IDLE_STATES = 10;
     /** Check the state of one app: arg1 = userId, arg2 = uid, obj = (String) packageName */
     static final int MSG_CHECK_PACKAGE_IDLE_STATE = 11;
-    static final int MSG_REPORT_EXEMPTED_SYNC_SCHEDULED = 12;
+    static final int MSG_REPORT_SYNC_SCHEDULED = 12;
     static final int MSG_REPORT_EXEMPTED_SYNC_START = 13;
     static final int MSG_UPDATE_STABLE_CHARGING= 14;
 
@@ -231,6 +232,10 @@
      * Maximum time an exempted sync should keep the buckets elevated, when sync is started.
      */
     long mExemptedSyncStartTimeoutMillis;
+    /**
+     * Maximum time an unexempted sync should keep the buckets elevated, when sync is scheduled
+     */
+    long mUnexemptedSyncScheduledTimeoutMillis;
     /** Maximum time a system interaction should keep the buckets elevated. */
     long mSystemInteractionTimeoutMillis;
     /** The length of time phone must be charging before considered stable enough to run jobs  */
@@ -447,6 +452,25 @@
         }
     }
 
+    void reportUnexemptedSyncScheduled(String packageName, int userId) {
+        if (!mAppIdleEnabled) return;
+
+        final long elapsedRealtime = mInjector.elapsedRealtime();
+        synchronized (mAppIdleLock) {
+            final int currentBucket =
+                    mAppIdleHistory.getAppStandbyBucket(packageName, userId, elapsedRealtime);
+            if (currentBucket == STANDBY_BUCKET_NEVER) {
+                // Bring the app out of the never bucket
+                AppUsageHistory appUsage = mAppIdleHistory.reportUsage(packageName, userId,
+                        STANDBY_BUCKET_WORKING_SET, REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED,
+                        0,
+                        elapsedRealtime + mUnexemptedSyncScheduledTimeoutMillis);
+                maybeInformListeners(packageName, userId, elapsedRealtime,
+                        appUsage.currentBucket, appUsage.bucketingReason, false);
+            }
+        }
+    }
+
     void reportExemptedSyncStart(String packageName, int userId) {
         if (!mAppIdleEnabled) return;
 
@@ -1423,8 +1447,8 @@
                 .sendToTarget();
     }
 
-    void postReportExemptedSyncScheduled(String packageName, int userId) {
-        mHandler.obtainMessage(MSG_REPORT_EXEMPTED_SYNC_SCHEDULED, userId, 0, packageName)
+    void postReportSyncScheduled(String packageName, int userId, boolean exempted) {
+        mHandler.obtainMessage(MSG_REPORT_SYNC_SCHEDULED, userId, exempted ? 1 : 0, packageName)
                 .sendToTarget();
     }
 
@@ -1492,6 +1516,9 @@
         pw.print("  mExemptedSyncStartTimeoutMillis=");
         TimeUtils.formatDuration(mExemptedSyncStartTimeoutMillis, pw);
         pw.println();
+        pw.print("  mUnexemptedSyncScheduledTimeoutMillis=");
+        TimeUtils.formatDuration(mUnexemptedSyncScheduledTimeoutMillis, pw);
+        pw.println();
 
         pw.print("  mSystemUpdateUsageTimeoutMillis=");
         TimeUtils.formatDuration(mSystemUpdateUsageTimeoutMillis, pw);
@@ -1706,8 +1733,13 @@
                             mInjector.elapsedRealtime());
                     break;
 
-                case MSG_REPORT_EXEMPTED_SYNC_SCHEDULED:
-                    reportExemptedSyncScheduled((String) msg.obj, msg.arg1);
+                case MSG_REPORT_SYNC_SCHEDULED:
+                    final boolean exempted = msg.arg1 > 0 ? true : false;
+                    if (exempted) {
+                        reportExemptedSyncScheduled((String) msg.obj, msg.arg1);
+                    } else {
+                        reportUnexemptedSyncScheduled((String) msg.obj, msg.arg1);
+                    }
                     break;
 
                 case MSG_REPORT_EXEMPTED_SYNC_START:
@@ -1799,12 +1831,14 @@
                 "system_update_usage_duration";
         private static final String KEY_PREDICTION_TIMEOUT = "prediction_timeout";
         private static final String KEY_SYNC_ADAPTER_HOLD_DURATION = "sync_adapter_duration";
-        private static final String KEY_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_HOLD_DURATION
-                = "exempted_sync_scheduled_nd_duration";
-        private static final String KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION
-                = "exempted_sync_scheduled_d_duration";
-        private static final String KEY_EXEMPTED_SYNC_START_HOLD_DURATION
-                = "exempted_sync_start_duration";
+        private static final String KEY_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_HOLD_DURATION =
+                "exempted_sync_scheduled_nd_duration";
+        private static final String KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION =
+                "exempted_sync_scheduled_d_duration";
+        private static final String KEY_EXEMPTED_SYNC_START_HOLD_DURATION =
+                "exempted_sync_start_duration";
+        private static final String KEY_UNEXEMPTED_SYNC_SCHEDULED_HOLD_DURATION =
+                "unexempted_sync_scheduled_duration";
         private static final String KEY_SYSTEM_INTERACTION_HOLD_DURATION =
                 "system_interaction_duration";
         private static final String KEY_STABLE_CHARGING_THRESHOLD = "stable_charging_threshold";
@@ -1816,6 +1850,7 @@
         public static final long DEFAULT_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_TIMEOUT = 10 * ONE_MINUTE;
         public static final long DEFAULT_EXEMPTED_SYNC_SCHEDULED_DOZE_TIMEOUT = 4 * ONE_HOUR;
         public static final long DEFAULT_EXEMPTED_SYNC_START_TIMEOUT = 10 * ONE_MINUTE;
+        public static final long DEFAULT_UNEXEMPTED_SYNC_SCHEDULED_TIMEOUT = 10 * ONE_MINUTE;
         public static final long DEFAULT_STABLE_CHARGING_THRESHOLD = 10 * ONE_MINUTE;
 
         private final KeyValueListParser mParser = new KeyValueListParser(',');
@@ -1883,42 +1918,47 @@
                         ELAPSED_TIME_THRESHOLDS);
                 mCheckIdleIntervalMillis = Math.min(mAppStandbyElapsedThresholds[1] / 4,
                         COMPRESS_TIME ? ONE_MINUTE : 4 * 60 * ONE_MINUTE); // 4 hours
-                mStrongUsageTimeoutMillis = mParser.getDurationMillis
-                        (KEY_STRONG_USAGE_HOLD_DURATION,
+                mStrongUsageTimeoutMillis = mParser.getDurationMillis(
+                        KEY_STRONG_USAGE_HOLD_DURATION,
                                 COMPRESS_TIME ? ONE_MINUTE : DEFAULT_STRONG_USAGE_TIMEOUT);
-                mNotificationSeenTimeoutMillis = mParser.getDurationMillis
-                        (KEY_NOTIFICATION_SEEN_HOLD_DURATION,
+                mNotificationSeenTimeoutMillis = mParser.getDurationMillis(
+                        KEY_NOTIFICATION_SEEN_HOLD_DURATION,
                                 COMPRESS_TIME ? 12 * ONE_MINUTE : DEFAULT_NOTIFICATION_TIMEOUT);
-                mSystemUpdateUsageTimeoutMillis = mParser.getDurationMillis
-                        (KEY_SYSTEM_UPDATE_HOLD_DURATION,
+                mSystemUpdateUsageTimeoutMillis = mParser.getDurationMillis(
+                        KEY_SYSTEM_UPDATE_HOLD_DURATION,
                                 COMPRESS_TIME ? 2 * ONE_MINUTE : DEFAULT_SYSTEM_UPDATE_TIMEOUT);
-                mPredictionTimeoutMillis = mParser.getDurationMillis
-                        (KEY_PREDICTION_TIMEOUT,
+                mPredictionTimeoutMillis = mParser.getDurationMillis(
+                        KEY_PREDICTION_TIMEOUT,
                                 COMPRESS_TIME ? 10 * ONE_MINUTE : DEFAULT_PREDICTION_TIMEOUT);
-                mSyncAdapterTimeoutMillis = mParser.getDurationMillis
-                        (KEY_SYNC_ADAPTER_HOLD_DURATION,
+                mSyncAdapterTimeoutMillis = mParser.getDurationMillis(
+                        KEY_SYNC_ADAPTER_HOLD_DURATION,
                                 COMPRESS_TIME ? ONE_MINUTE : DEFAULT_SYNC_ADAPTER_TIMEOUT);
 
-                mExemptedSyncScheduledNonDozeTimeoutMillis = mParser.getDurationMillis
-                        (KEY_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_HOLD_DURATION,
+                mExemptedSyncScheduledNonDozeTimeoutMillis = mParser.getDurationMillis(
+                        KEY_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_HOLD_DURATION,
                                 COMPRESS_TIME ? (ONE_MINUTE / 2)
                                         : DEFAULT_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_TIMEOUT);
 
-                mExemptedSyncScheduledDozeTimeoutMillis = mParser.getDurationMillis
-                        (KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION,
+                mExemptedSyncScheduledDozeTimeoutMillis = mParser.getDurationMillis(
+                        KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION,
                                 COMPRESS_TIME ? ONE_MINUTE
                                         : DEFAULT_EXEMPTED_SYNC_SCHEDULED_DOZE_TIMEOUT);
 
-                mExemptedSyncStartTimeoutMillis = mParser.getDurationMillis
-                        (KEY_EXEMPTED_SYNC_START_HOLD_DURATION,
+                mExemptedSyncStartTimeoutMillis = mParser.getDurationMillis(
+                        KEY_EXEMPTED_SYNC_START_HOLD_DURATION,
                                 COMPRESS_TIME ? ONE_MINUTE
                                         : DEFAULT_EXEMPTED_SYNC_START_TIMEOUT);
 
-                mSystemInteractionTimeoutMillis = mParser.getDurationMillis
-                        (KEY_SYSTEM_INTERACTION_HOLD_DURATION,
+                mUnexemptedSyncScheduledTimeoutMillis = mParser.getDurationMillis(
+                        KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION,
+                                COMPRESS_TIME ? ONE_MINUTE
+                                        : DEFAULT_UNEXEMPTED_SYNC_SCHEDULED_TIMEOUT); // TODO
+
+                mSystemInteractionTimeoutMillis = mParser.getDurationMillis(
+                        KEY_SYSTEM_INTERACTION_HOLD_DURATION,
                                 COMPRESS_TIME ? ONE_MINUTE : DEFAULT_SYSTEM_INTERACTION_TIMEOUT);
-                mStableChargingThresholdMillis = mParser.getDurationMillis
-                        (KEY_STABLE_CHARGING_THRESHOLD,
+                mStableChargingThresholdMillis = mParser.getDurationMillis(
+                        KEY_STABLE_CHARGING_THRESHOLD,
                                 COMPRESS_TIME ? ONE_MINUTE : DEFAULT_STABLE_CHARGING_THRESHOLD);
             }
 
diff --git a/services/usage/java/com/android/server/usage/UsageStatsService.java b/services/usage/java/com/android/server/usage/UsageStatsService.java
index ebb0210..b14d722 100644
--- a/services/usage/java/com/android/server/usage/UsageStatsService.java
+++ b/services/usage/java/com/android/server/usage/UsageStatsService.java
@@ -1751,8 +1751,8 @@
         }
 
         @Override
-        public void reportExemptedSyncScheduled(String packageName, int userId) {
-            mAppStandby.postReportExemptedSyncScheduled(packageName, userId);
+        public void reportSyncScheduled(String packageName, int userId, boolean exempted) {
+            mAppStandby.postReportSyncScheduled(packageName, userId, exempted);
         }
 
         @Override
diff --git a/telecomm/java/android/telecom/AudioState.java b/telecomm/java/android/telecom/AudioState.java
index eb202a7..4e74395 100644
--- a/telecomm/java/android/telecom/AudioState.java
+++ b/telecomm/java/android/telecom/AudioState.java
@@ -133,7 +133,7 @@
     /**
      * Responsible for creating AudioState objects for deserialized Parcels.
      */
-    public static final Parcelable.Creator<AudioState> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AudioState> CREATOR =
             new Parcelable.Creator<AudioState> () {
 
         @Override
diff --git a/telecomm/java/android/telecom/CallAudioState.java b/telecomm/java/android/telecom/CallAudioState.java
index e33ba7e..4b90985 100644
--- a/telecomm/java/android/telecom/CallAudioState.java
+++ b/telecomm/java/android/telecom/CallAudioState.java
@@ -239,7 +239,7 @@
     /**
      * Responsible for creating AudioState objects for deserialized Parcels.
      */
-    public static final Parcelable.Creator<CallAudioState> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CallAudioState> CREATOR =
             new Parcelable.Creator<CallAudioState> () {
 
         @Override
diff --git a/telecomm/java/android/telecom/CallIdentification.java b/telecomm/java/android/telecom/CallIdentification.java
index cde7f60..d15e024 100644
--- a/telecomm/java/android/telecom/CallIdentification.java
+++ b/telecomm/java/android/telecom/CallIdentification.java
@@ -281,7 +281,7 @@
     /**
      * Responsible for creating CallIdentification objects for deserialized Parcels.
      */
-    public static final Parcelable.Creator<CallIdentification> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CallIdentification> CREATOR =
             new Parcelable.Creator<CallIdentification> () {
 
                 @Override
diff --git a/telecomm/java/android/telecom/ConferenceParticipant.java b/telecomm/java/android/telecom/ConferenceParticipant.java
index 6317770..2f1505c 100644
--- a/telecomm/java/android/telecom/ConferenceParticipant.java
+++ b/telecomm/java/android/telecom/ConferenceParticipant.java
@@ -86,7 +86,7 @@
     /**
      * Responsible for creating {@code ConferenceParticipant} objects for deserialized Parcels.
      */
-    public static final Parcelable.Creator<ConferenceParticipant> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ConferenceParticipant> CREATOR =
             new Parcelable.Creator<ConferenceParticipant>() {
 
                 @Override
diff --git a/telecomm/java/android/telecom/ConnectionRequest.java b/telecomm/java/android/telecom/ConnectionRequest.java
index b6e6b0e..b428530 100644
--- a/telecomm/java/android/telecom/ConnectionRequest.java
+++ b/telecomm/java/android/telecom/ConnectionRequest.java
@@ -337,10 +337,34 @@
                 mAddress == null
                         ? Uri.EMPTY
                         : Connection.toLogSafePhoneNumber(mAddress.toString()),
-                mExtras == null ? "" : mExtras);
+                bundleToString(mExtras));
     }
 
-    public static final Creator<ConnectionRequest> CREATOR = new Creator<ConnectionRequest> () {
+    private static String bundleToString(Bundle extras){
+        if (extras == null) {
+            return "";
+        }
+        StringBuilder sb = new StringBuilder();
+        sb.append("Bundle[");
+        for (String key : extras.keySet()) {
+            sb.append(key);
+            sb.append("=");
+            switch (key) {
+                case TelecomManager.EXTRA_INCOMING_CALL_ADDRESS:
+                case TelecomManager.EXTRA_UNKNOWN_CALL_HANDLE:
+                    sb.append(Log.pii(extras.get(key)));
+                    break;
+                default:
+                    sb.append(extras.get(key));
+                    break;
+            }
+            sb.append(", ");
+        }
+        sb.append("]");
+        return sb.toString();
+    }
+
+    public static final @android.annotation.NonNull Creator<ConnectionRequest> CREATOR = new Creator<ConnectionRequest> () {
         @Override
         public ConnectionRequest createFromParcel(Parcel source) {
             return new ConnectionRequest(source);
diff --git a/telecomm/java/android/telecom/DisconnectCause.java b/telecomm/java/android/telecom/DisconnectCause.java
index 5a97c94..ae92464 100644
--- a/telecomm/java/android/telecom/DisconnectCause.java
+++ b/telecomm/java/android/telecom/DisconnectCause.java
@@ -207,7 +207,7 @@
         return mToneToPlay;
     }
 
-    public static final Creator<DisconnectCause> CREATOR = new Creator<DisconnectCause>() {
+    public static final @android.annotation.NonNull Creator<DisconnectCause> CREATOR = new Creator<DisconnectCause>() {
         @Override
         public DisconnectCause createFromParcel(Parcel source) {
             int code = source.readInt();
diff --git a/telecomm/java/android/telecom/GatewayInfo.java b/telecomm/java/android/telecom/GatewayInfo.java
index 928570e..0faa4fd 100644
--- a/telecomm/java/android/telecom/GatewayInfo.java
+++ b/telecomm/java/android/telecom/GatewayInfo.java
@@ -80,7 +80,7 @@
     /**
      * The Parcelable interface.
      * */
-    public static final Parcelable.Creator<GatewayInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<GatewayInfo> CREATOR =
             new Parcelable.Creator<GatewayInfo> () {
 
         @Override
diff --git a/telecomm/java/android/telecom/Logging/Session.java b/telecomm/java/android/telecom/Logging/Session.java
index c45bd6b..50c3cd9 100644
--- a/telecomm/java/android/telecom/Logging/Session.java
+++ b/telecomm/java/android/telecom/Logging/Session.java
@@ -69,7 +69,7 @@
         }
 
         /** Responsible for creating Info objects for deserialized Parcels. */
-        public static final Parcelable.Creator<Info> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<Info> CREATOR =
                 new Parcelable.Creator<Info> () {
                     @Override
                     public Info createFromParcel(Parcel source) {
diff --git a/telecomm/java/android/telecom/ParcelableCall.java b/telecomm/java/android/telecom/ParcelableCall.java
index f7dec83..345707e 100644
--- a/telecomm/java/android/telecom/ParcelableCall.java
+++ b/telecomm/java/android/telecom/ParcelableCall.java
@@ -331,7 +331,7 @@
 
     /** Responsible for creating ParcelableCall objects for deserialized Parcels. */
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
-    public static final Parcelable.Creator<ParcelableCall> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ParcelableCall> CREATOR =
             new Parcelable.Creator<ParcelableCall> () {
         @Override
         public ParcelableCall createFromParcel(Parcel source) {
diff --git a/telecomm/java/android/telecom/ParcelableCallAnalytics.java b/telecomm/java/android/telecom/ParcelableCallAnalytics.java
index bb066ad..2b9213b 100644
--- a/telecomm/java/android/telecom/ParcelableCallAnalytics.java
+++ b/telecomm/java/android/telecom/ParcelableCallAnalytics.java
@@ -36,7 +36,7 @@
         public static final int RECEIVE_REMOTE_SESSION_MODIFY_REQUEST = 2;
         public static final int RECEIVE_REMOTE_SESSION_MODIFY_RESPONSE = 3;
 
-        public static final Parcelable.Creator<VideoEvent> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<VideoEvent> CREATOR =
                 new Parcelable.Creator<VideoEvent> () {
 
                     @Override
@@ -135,7 +135,7 @@
         public static final int REQUEST_PULL = 500;
 
 
-        public static final Parcelable.Creator<AnalyticsEvent> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<AnalyticsEvent> CREATOR =
                 new Parcelable.Creator<AnalyticsEvent> () {
 
                     @Override
@@ -200,7 +200,7 @@
 
         public static final int INVALID = 999999;
 
-        public static final Parcelable.Creator<EventTiming> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<EventTiming> CREATOR =
                 new Parcelable.Creator<EventTiming> () {
 
                     @Override
@@ -284,7 +284,7 @@
 
     public static final int STILL_CONNECTED = -1;
 
-    public static final Parcelable.Creator<ParcelableCallAnalytics> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ParcelableCallAnalytics> CREATOR =
             new Parcelable.Creator<ParcelableCallAnalytics> () {
 
                 @Override
diff --git a/telecomm/java/android/telecom/ParcelableConference.java b/telecomm/java/android/telecom/ParcelableConference.java
index a6221d4..636e4b2 100644
--- a/telecomm/java/android/telecom/ParcelableConference.java
+++ b/telecomm/java/android/telecom/ParcelableConference.java
@@ -134,7 +134,7 @@
         return mExtras;
     }
 
-    public static final Parcelable.Creator<ParcelableConference> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ParcelableConference> CREATOR =
             new Parcelable.Creator<ParcelableConference> () {
         @Override
         public ParcelableConference createFromParcel(Parcel source) {
diff --git a/telecomm/java/android/telecom/ParcelableConnection.java b/telecomm/java/android/telecom/ParcelableConnection.java
index 61d5a12..dab1c6e 100644
--- a/telecomm/java/android/telecom/ParcelableConnection.java
+++ b/telecomm/java/android/telecom/ParcelableConnection.java
@@ -237,7 +237,7 @@
                 .toString();
     }
 
-    public static final Parcelable.Creator<ParcelableConnection> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ParcelableConnection> CREATOR =
             new Parcelable.Creator<ParcelableConnection> () {
         @Override
         public ParcelableConnection createFromParcel(Parcel source) {
diff --git a/telecomm/java/android/telecom/ParcelableRttCall.java b/telecomm/java/android/telecom/ParcelableRttCall.java
index 763e48b..fbcf486 100644
--- a/telecomm/java/android/telecom/ParcelableRttCall.java
+++ b/telecomm/java/android/telecom/ParcelableRttCall.java
@@ -50,7 +50,7 @@
         mReceiveStream = in.readParcelable(ParcelFileDescriptor.class.getClassLoader());
     }
 
-    public static final Creator<ParcelableRttCall> CREATOR = new Creator<ParcelableRttCall>() {
+    public static final @android.annotation.NonNull Creator<ParcelableRttCall> CREATOR = new Creator<ParcelableRttCall>() {
         @Override
         public ParcelableRttCall createFromParcel(Parcel in) {
             return new ParcelableRttCall(in);
diff --git a/telecomm/java/android/telecom/PhoneAccount.java b/telecomm/java/android/telecom/PhoneAccount.java
index 2ffad03..5e13400 100644
--- a/telecomm/java/android/telecom/PhoneAccount.java
+++ b/telecomm/java/android/telecom/PhoneAccount.java
@@ -914,7 +914,7 @@
         out.writeInt(mSupportedAudioRoutes);
     }
 
-    public static final Creator<PhoneAccount> CREATOR
+    public static final @android.annotation.NonNull Creator<PhoneAccount> CREATOR
             = new Creator<PhoneAccount>() {
         @Override
         public PhoneAccount createFromParcel(Parcel in) {
diff --git a/telecomm/java/android/telecom/PhoneAccountHandle.java b/telecomm/java/android/telecom/PhoneAccountHandle.java
index 5dedb04..a84ce55 100644
--- a/telecomm/java/android/telecom/PhoneAccountHandle.java
+++ b/telecomm/java/android/telecom/PhoneAccountHandle.java
@@ -156,7 +156,7 @@
         }
     }
 
-    public static final Creator<PhoneAccountHandle> CREATOR = new Creator<PhoneAccountHandle>() {
+    public static final @android.annotation.NonNull Creator<PhoneAccountHandle> CREATOR = new Creator<PhoneAccountHandle>() {
         @Override
         public PhoneAccountHandle createFromParcel(Parcel in) {
             return new PhoneAccountHandle(in);
diff --git a/telecomm/java/android/telecom/PhoneAccountSuggestion.java b/telecomm/java/android/telecom/PhoneAccountSuggestion.java
index b401bcf..05b2395 100644
--- a/telecomm/java/android/telecom/PhoneAccountSuggestion.java
+++ b/telecomm/java/android/telecom/PhoneAccountSuggestion.java
@@ -85,7 +85,7 @@
         mShouldAutoSelect = in.readByte() != 0;
     }
 
-    public static final Creator<PhoneAccountSuggestion> CREATOR =
+    public static final @android.annotation.NonNull Creator<PhoneAccountSuggestion> CREATOR =
             new Creator<PhoneAccountSuggestion>() {
                 @Override
                 public PhoneAccountSuggestion createFromParcel(Parcel in) {
diff --git a/telecomm/java/android/telecom/StatusHints.java b/telecomm/java/android/telecom/StatusHints.java
index 453f408..762c93a 100644
--- a/telecomm/java/android/telecom/StatusHints.java
+++ b/telecomm/java/android/telecom/StatusHints.java
@@ -119,7 +119,7 @@
         out.writeParcelable(mExtras, 0);
     }
 
-    public static final Creator<StatusHints> CREATOR
+    public static final @android.annotation.NonNull Creator<StatusHints> CREATOR
             = new Creator<StatusHints>() {
         public StatusHints createFromParcel(Parcel in) {
             return new StatusHints(in);
diff --git a/telecomm/java/android/telecom/TelecomAnalytics.java b/telecomm/java/android/telecom/TelecomAnalytics.java
index 6e0d02c..e88ad77 100644
--- a/telecomm/java/android/telecom/TelecomAnalytics.java
+++ b/telecomm/java/android/telecom/TelecomAnalytics.java
@@ -28,7 +28,7 @@
  */
 @SystemApi
 public final class TelecomAnalytics implements Parcelable {
-    public static final Parcelable.Creator<TelecomAnalytics> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TelecomAnalytics> CREATOR =
             new Parcelable.Creator<TelecomAnalytics> () {
 
                 @Override
@@ -43,7 +43,7 @@
             };
 
     public static final class SessionTiming extends TimedEvent<Integer> implements Parcelable {
-        public static final Parcelable.Creator<SessionTiming> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<SessionTiming> CREATOR =
                 new Parcelable.Creator<SessionTiming> () {
 
                     @Override
diff --git a/telecomm/java/android/telecom/VideoProfile.java b/telecomm/java/android/telecom/VideoProfile.java
index 157f12c..64e6ca3 100644
--- a/telecomm/java/android/telecom/VideoProfile.java
+++ b/telecomm/java/android/telecom/VideoProfile.java
@@ -170,7 +170,7 @@
     /**
      * Responsible for creating VideoProfile objects from deserialized Parcels.
      **/
-    public static final Parcelable.Creator<VideoProfile> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<VideoProfile> CREATOR =
             new Parcelable.Creator<VideoProfile> () {
                 /**
                  * Creates a MediaProfile instances from a parcel.
@@ -389,7 +389,7 @@
         /**
          * Responsible for creating CallCameraCapabilities objects from deserialized Parcels.
          **/
-        public static final Parcelable.Creator<CameraCapabilities> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<CameraCapabilities> CREATOR =
                 new Parcelable.Creator<CameraCapabilities> () {
                     /**
                      * Creates a CallCameraCapabilities instances from a parcel.
diff --git a/telecomm/java/android/telecom/Voicemail.java b/telecomm/java/android/telecom/Voicemail.java
index ca235bf..60a8a94 100644
--- a/telecomm/java/android/telecom/Voicemail.java
+++ b/telecomm/java/android/telecom/Voicemail.java
@@ -283,7 +283,7 @@
         dest.writeCharSequence(mTranscription);
     }
 
-    public static final Creator<Voicemail> CREATOR
+    public static final @android.annotation.NonNull Creator<Voicemail> CREATOR
             = new Creator<Voicemail>() {
         @Override
         public Voicemail createFromParcel(Parcel in) {
diff --git a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
index 5030f90..93eea56 100644
--- a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
+++ b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
@@ -182,6 +182,7 @@
     /**
      * @see TelecomServiceImpl#getCallState
      */
+    @UnsupportedAppUsage
     int getCallState();
 
     /**
diff --git a/telephony/java/android/provider/Telephony.java b/telephony/java/android/provider/Telephony.java
index fecdb08..79b7807 100644
--- a/telephony/java/android/provider/Telephony.java
+++ b/telephony/java/android/provider/Telephony.java
@@ -17,6 +17,7 @@
 package android.provider;
 
 import android.annotation.IntDef;
+import android.annotation.NonNull;
 import android.annotation.RequiresPermission;
 import android.annotation.SdkConstant;
 import android.annotation.SdkConstant.SdkConstantType;
@@ -4340,6 +4341,7 @@
          * @param subscriptionId the subscriptionId to receive updates on
          * @return the Uri used to observe precise carrier identity changes
          */
+        @NonNull
         public static Uri getPreciseCarrierIdUriForSubscriptionId(int subscriptionId) {
             return Uri.withAppendedPath(Uri.withAppendedPath(CONTENT_URI, "precise"),
                     String.valueOf(subscriptionId));
diff --git a/telephony/java/android/telephony/AvailableNetworkInfo.java b/telephony/java/android/telephony/AvailableNetworkInfo.java
index b407b2a..8a7153e 100644
--- a/telephony/java/android/telephony/AvailableNetworkInfo.java
+++ b/telephony/java/android/telephony/AvailableNetworkInfo.java
@@ -145,7 +145,7 @@
         return Objects.hash(mSubId, mPriority, mMccMncs);
     }
 
-    public static final Parcelable.Creator<AvailableNetworkInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<AvailableNetworkInfo> CREATOR =
             new Creator<AvailableNetworkInfo>() {
                 @Override
                 public AvailableNetworkInfo createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CallAttributes.java b/telephony/java/android/telephony/CallAttributes.java
index 0d4f09f..368f0c6 100644
--- a/telephony/java/android/telephony/CallAttributes.java
+++ b/telephony/java/android/telephony/CallAttributes.java
@@ -138,7 +138,7 @@
         dest.writeParcelable(mCallQuality, flags);
     }
 
-    public static final Parcelable.Creator<CallAttributes> CREATOR = new Parcelable.Creator() {
+    public static final @android.annotation.NonNull Parcelable.Creator<CallAttributes> CREATOR = new Parcelable.Creator() {
         public CallAttributes createFromParcel(Parcel in) {
             return new CallAttributes(in);
         }
diff --git a/telephony/java/android/telephony/CallQuality.java b/telephony/java/android/telephony/CallQuality.java
index cbe62284..10a04a9 100644
--- a/telephony/java/android/telephony/CallQuality.java
+++ b/telephony/java/android/telephony/CallQuality.java
@@ -333,7 +333,7 @@
         dest.writeInt(mCodecType);
     }
 
-    public static final Parcelable.Creator<CallQuality> CREATOR = new Parcelable.Creator() {
+    public static final @android.annotation.NonNull Parcelable.Creator<CallQuality> CREATOR = new Parcelable.Creator() {
         public CallQuality createFromParcel(Parcel in) {
             return new CallQuality(in);
         }
diff --git a/telephony/java/android/telephony/CarrierRestrictionRules.java b/telephony/java/android/telephony/CarrierRestrictionRules.java
index d47b55c..47ce632 100644
--- a/telephony/java/android/telephony/CarrierRestrictionRules.java
+++ b/telephony/java/android/telephony/CarrierRestrictionRules.java
@@ -309,7 +309,7 @@
     /**
      * {@link Parcelable.Creator}
      */
-    public static final Creator<CarrierRestrictionRules> CREATOR =
+    public static final @android.annotation.NonNull Creator<CarrierRestrictionRules> CREATOR =
             new Creator<CarrierRestrictionRules>() {
         @Override
         public CarrierRestrictionRules createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellConfigLte.java b/telephony/java/android/telephony/CellConfigLte.java
index eafbfbc..4b57d71 100644
--- a/telephony/java/android/telephony/CellConfigLte.java
+++ b/telephony/java/android/telephony/CellConfigLte.java
@@ -96,7 +96,7 @@
         mIsEndcAvailable = in.readBoolean();
     }
 
-    public static final Creator<CellConfigLte> CREATOR = new Creator<CellConfigLte>() {
+    public static final @android.annotation.NonNull Creator<CellConfigLte> CREATOR = new Creator<CellConfigLte>() {
         @Override
         public CellConfigLte createFromParcel(Parcel in) {
             return new CellConfigLte(in);
diff --git a/telephony/java/android/telephony/CellIdentity.java b/telephony/java/android/telephony/CellIdentity.java
index 7655834..6c835dc 100644
--- a/telephony/java/android/telephony/CellIdentity.java
+++ b/telephony/java/android/telephony/CellIdentity.java
@@ -186,7 +186,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<CellIdentity> CREATOR =
+    public static final @android.annotation.NonNull Creator<CellIdentity> CREATOR =
             new Creator<CellIdentity>() {
                 @Override
                 public CellIdentity createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellIdentityCdma.java b/telephony/java/android/telephony/CellIdentityCdma.java
index fa19867..daf80f5 100644
--- a/telephony/java/android/telephony/CellIdentityCdma.java
+++ b/telephony/java/android/telephony/CellIdentityCdma.java
@@ -244,7 +244,7 @@
 
     /** Implement the Parcelable interface */
     @SuppressWarnings("hiding")
-    public static final Creator<CellIdentityCdma> CREATOR =
+    public static final @android.annotation.NonNull Creator<CellIdentityCdma> CREATOR =
             new Creator<CellIdentityCdma>() {
         @Override
         public CellIdentityCdma createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellIdentityGsm.java b/telephony/java/android/telephony/CellIdentityGsm.java
index 9a24e47..6328afc 100644
--- a/telephony/java/android/telephony/CellIdentityGsm.java
+++ b/telephony/java/android/telephony/CellIdentityGsm.java
@@ -260,7 +260,7 @@
 
     /** Implement the Parcelable interface */
     @SuppressWarnings("hiding")
-    public static final Creator<CellIdentityGsm> CREATOR =
+    public static final @android.annotation.NonNull Creator<CellIdentityGsm> CREATOR =
             new Creator<CellIdentityGsm>() {
                 @Override
                 public CellIdentityGsm createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellIdentityLte.java b/telephony/java/android/telephony/CellIdentityLte.java
index 51393b9..e112004 100644
--- a/telephony/java/android/telephony/CellIdentityLte.java
+++ b/telephony/java/android/telephony/CellIdentityLte.java
@@ -294,7 +294,7 @@
 
     /** Implement the Parcelable interface */
     @SuppressWarnings("hiding")
-    public static final Creator<CellIdentityLte> CREATOR =
+    public static final @android.annotation.NonNull Creator<CellIdentityLte> CREATOR =
             new Creator<CellIdentityLte>() {
                 @Override
                 public CellIdentityLte createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellIdentityNr.java b/telephony/java/android/telephony/CellIdentityNr.java
index 856f081..b48388e 100644
--- a/telephony/java/android/telephony/CellIdentityNr.java
+++ b/telephony/java/android/telephony/CellIdentityNr.java
@@ -81,7 +81,8 @@
     /**
      * Get the NR Cell Identity.
      *
-     * @return The NR Cell Identity in range [0, 68719476735] or Long.MAX_VALUE if unknown.
+     * @return The 36-bit NR Cell Identity in range [0, 68719476735] or
+     *         {@link CellInfo#UNAVAILABLE_LONG} if unknown.
      */
     public long getNci() {
         return mNci;
@@ -160,7 +161,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<CellIdentityNr> CREATOR =
+    public static final @android.annotation.NonNull Creator<CellIdentityNr> CREATOR =
             new Creator<CellIdentityNr>() {
                 @Override
                 public CellIdentityNr createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellIdentityTdscdma.java b/telephony/java/android/telephony/CellIdentityTdscdma.java
index dba437a..10ffb80 100644
--- a/telephony/java/android/telephony/CellIdentityTdscdma.java
+++ b/telephony/java/android/telephony/CellIdentityTdscdma.java
@@ -226,7 +226,7 @@
 
     /** Implement the Parcelable interface */
     @SuppressWarnings("hiding")
-    public static final Creator<CellIdentityTdscdma> CREATOR =
+    public static final @android.annotation.NonNull Creator<CellIdentityTdscdma> CREATOR =
             new Creator<CellIdentityTdscdma>() {
                 @Override
                 public CellIdentityTdscdma createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellIdentityWcdma.java b/telephony/java/android/telephony/CellIdentityWcdma.java
index 6e09784..b1944af 100644
--- a/telephony/java/android/telephony/CellIdentityWcdma.java
+++ b/telephony/java/android/telephony/CellIdentityWcdma.java
@@ -251,7 +251,7 @@
 
     /** Implement the Parcelable interface */
     @SuppressWarnings("hiding")
-    public static final Creator<CellIdentityWcdma> CREATOR =
+    public static final @android.annotation.NonNull Creator<CellIdentityWcdma> CREATOR =
             new Creator<CellIdentityWcdma>() {
                 @Override
                 public CellIdentityWcdma createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellInfo.java b/telephony/java/android/telephony/CellInfo.java
index 8ce5c54..223f3ef 100644
--- a/telephony/java/android/telephony/CellInfo.java
+++ b/telephony/java/android/telephony/CellInfo.java
@@ -40,6 +40,11 @@
     public static final int UNAVAILABLE = Integer.MAX_VALUE;
 
     /**
+     * This value indicates that the long field is unreported.
+     */
+    public static final long UNAVAILABLE_LONG = Long.MAX_VALUE;
+
+    /**
      * Cell identity type
      * @hide
      */
@@ -284,7 +289,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<CellInfo> CREATOR = new Creator<CellInfo>() {
+    public static final @android.annotation.NonNull Creator<CellInfo> CREATOR = new Creator<CellInfo>() {
         @Override
         public CellInfo createFromParcel(Parcel in) {
                 int type = in.readInt();
diff --git a/telephony/java/android/telephony/CellInfoCdma.java b/telephony/java/android/telephony/CellInfoCdma.java
index 4440108..9c38506 100644
--- a/telephony/java/android/telephony/CellInfoCdma.java
+++ b/telephony/java/android/telephony/CellInfoCdma.java
@@ -156,7 +156,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<CellInfoCdma> CREATOR = new Creator<CellInfoCdma>() {
+    public static final @android.annotation.NonNull Creator<CellInfoCdma> CREATOR = new Creator<CellInfoCdma>() {
         @Override
         public CellInfoCdma createFromParcel(Parcel in) {
             in.readInt(); // Skip past token, we know what it is
diff --git a/telephony/java/android/telephony/CellInfoGsm.java b/telephony/java/android/telephony/CellInfoGsm.java
index 248adfc..0d91f80 100644
--- a/telephony/java/android/telephony/CellInfoGsm.java
+++ b/telephony/java/android/telephony/CellInfoGsm.java
@@ -149,7 +149,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<CellInfoGsm> CREATOR = new Creator<CellInfoGsm>() {
+    public static final @android.annotation.NonNull Creator<CellInfoGsm> CREATOR = new Creator<CellInfoGsm>() {
         @Override
         public CellInfoGsm createFromParcel(Parcel in) {
             in.readInt(); // Skip past token, we know what it is
diff --git a/telephony/java/android/telephony/CellInfoLte.java b/telephony/java/android/telephony/CellInfoLte.java
index 8e8ce8a..deae632 100644
--- a/telephony/java/android/telephony/CellInfoLte.java
+++ b/telephony/java/android/telephony/CellInfoLte.java
@@ -179,7 +179,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<CellInfoLte> CREATOR = new Creator<CellInfoLte>() {
+    public static final @android.annotation.NonNull Creator<CellInfoLte> CREATOR = new Creator<CellInfoLte>() {
         @Override
         public CellInfoLte createFromParcel(Parcel in) {
             in.readInt(); // Skip past token, we know what it is
diff --git a/telephony/java/android/telephony/CellInfoNr.java b/telephony/java/android/telephony/CellInfoNr.java
index 11857a6..fb147ce 100644
--- a/telephony/java/android/telephony/CellInfoNr.java
+++ b/telephony/java/android/telephony/CellInfoNr.java
@@ -79,7 +79,7 @@
         mCellSignalStrength.writeToParcel(dest, flags);
     }
 
-    public static final Creator<CellInfoNr> CREATOR = new Creator<CellInfoNr>() {
+    public static final @android.annotation.NonNull Creator<CellInfoNr> CREATOR = new Creator<CellInfoNr>() {
         @Override
         public CellInfoNr createFromParcel(Parcel in) {
             // Skip the type info.
diff --git a/telephony/java/android/telephony/CellInfoTdscdma.java b/telephony/java/android/telephony/CellInfoTdscdma.java
index 2ab38fb..ae43bb2 100644
--- a/telephony/java/android/telephony/CellInfoTdscdma.java
+++ b/telephony/java/android/telephony/CellInfoTdscdma.java
@@ -149,7 +149,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<CellInfoTdscdma> CREATOR = new Creator<CellInfoTdscdma>() {
+    public static final @android.annotation.NonNull Creator<CellInfoTdscdma> CREATOR = new Creator<CellInfoTdscdma>() {
         @Override
         public CellInfoTdscdma createFromParcel(Parcel in) {
             in.readInt(); // Skip past token, we know what it is
diff --git a/telephony/java/android/telephony/CellInfoWcdma.java b/telephony/java/android/telephony/CellInfoWcdma.java
index 65e0470..d2287ea 100644
--- a/telephony/java/android/telephony/CellInfoWcdma.java
+++ b/telephony/java/android/telephony/CellInfoWcdma.java
@@ -149,7 +149,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<CellInfoWcdma> CREATOR = new Creator<CellInfoWcdma>() {
+    public static final @android.annotation.NonNull Creator<CellInfoWcdma> CREATOR = new Creator<CellInfoWcdma>() {
         @Override
         public CellInfoWcdma createFromParcel(Parcel in) {
             in.readInt(); // Skip past token, we know what it is
diff --git a/telephony/java/android/telephony/CellSignalStrength.java b/telephony/java/android/telephony/CellSignalStrength.java
index e6182ed..740b970 100644
--- a/telephony/java/android/telephony/CellSignalStrength.java
+++ b/telephony/java/android/telephony/CellSignalStrength.java
@@ -119,7 +119,7 @@
     /** @hide */
     protected static final int getAsuFromRssiDbm(int dbm) {
         if (dbm == CellInfo.UNAVAILABLE) return 99;
-        return (dbm / 2) + 113;
+        return (dbm + 113) / 2;
     }
 
     // Range for RSCP in ASU (0-96, 255) as defined in TS 27.007 8.69
diff --git a/telephony/java/android/telephony/CellSignalStrengthCdma.java b/telephony/java/android/telephony/CellSignalStrengthCdma.java
index 47faf1e..5b19599 100644
--- a/telephony/java/android/telephony/CellSignalStrengthCdma.java
+++ b/telephony/java/android/telephony/CellSignalStrengthCdma.java
@@ -464,7 +464,7 @@
 
     /** Implement the Parcelable interface */
     @SuppressWarnings("hiding")
-    public static final Parcelable.Creator<CellSignalStrengthCdma> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CellSignalStrengthCdma> CREATOR =
             new Parcelable.Creator<CellSignalStrengthCdma>() {
         @Override
         public CellSignalStrengthCdma createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellSignalStrengthGsm.java b/telephony/java/android/telephony/CellSignalStrengthGsm.java
index a4207c9..3dea6f4 100644
--- a/telephony/java/android/telephony/CellSignalStrengthGsm.java
+++ b/telephony/java/android/telephony/CellSignalStrengthGsm.java
@@ -226,7 +226,7 @@
 
     /** Implement the Parcelable interface */
     @SuppressWarnings("hiding")
-    public static final Parcelable.Creator<CellSignalStrengthGsm> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CellSignalStrengthGsm> CREATOR =
             new Parcelable.Creator<CellSignalStrengthGsm>() {
         @Override
         public CellSignalStrengthGsm createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellSignalStrengthLte.java b/telephony/java/android/telephony/CellSignalStrengthLte.java
index 61c6b48..5687ada 100644
--- a/telephony/java/android/telephony/CellSignalStrengthLte.java
+++ b/telephony/java/android/telephony/CellSignalStrengthLte.java
@@ -432,7 +432,7 @@
 
     /** Implement the Parcelable interface */
     @SuppressWarnings("hiding")
-    public static final Parcelable.Creator<CellSignalStrengthLte> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CellSignalStrengthLte> CREATOR =
             new Parcelable.Creator<CellSignalStrengthLte>() {
         @Override
         public CellSignalStrengthLte createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellSignalStrengthNr.java b/telephony/java/android/telephony/CellSignalStrengthNr.java
index 6f84ec5..fff3adf 100644
--- a/telephony/java/android/telephony/CellSignalStrengthNr.java
+++ b/telephony/java/android/telephony/CellSignalStrengthNr.java
@@ -289,7 +289,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Parcelable.Creator<CellSignalStrengthNr> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CellSignalStrengthNr> CREATOR =
             new Parcelable.Creator<CellSignalStrengthNr>() {
         @Override
         public CellSignalStrengthNr createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellSignalStrengthTdscdma.java b/telephony/java/android/telephony/CellSignalStrengthTdscdma.java
index 5ae89b0..e79643f 100644
--- a/telephony/java/android/telephony/CellSignalStrengthTdscdma.java
+++ b/telephony/java/android/telephony/CellSignalStrengthTdscdma.java
@@ -237,7 +237,7 @@
 
     /** Implement the Parcelable interface */
     @SuppressWarnings("hiding")
-    public static final Parcelable.Creator<CellSignalStrengthTdscdma> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CellSignalStrengthTdscdma> CREATOR =
             new Parcelable.Creator<CellSignalStrengthTdscdma>() {
         @Override
         public CellSignalStrengthTdscdma createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/CellSignalStrengthWcdma.java b/telephony/java/android/telephony/CellSignalStrengthWcdma.java
index efa3647..d9fd7f3 100644
--- a/telephony/java/android/telephony/CellSignalStrengthWcdma.java
+++ b/telephony/java/android/telephony/CellSignalStrengthWcdma.java
@@ -333,7 +333,7 @@
 
     /** Implement the Parcelable interface */
     @SuppressWarnings("hiding")
-    public static final Parcelable.Creator<CellSignalStrengthWcdma> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<CellSignalStrengthWcdma> CREATOR =
             new Parcelable.Creator<CellSignalStrengthWcdma>() {
         @Override
         public CellSignalStrengthWcdma createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ClientRequestStats.java b/telephony/java/android/telephony/ClientRequestStats.java
index 381c847..c787893 100644
--- a/telephony/java/android/telephony/ClientRequestStats.java
+++ b/telephony/java/android/telephony/ClientRequestStats.java
@@ -29,7 +29,7 @@
  * @hide
  */
 public final class ClientRequestStats implements Parcelable {
-    public static final Parcelable.Creator<ClientRequestStats> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ClientRequestStats> CREATOR =
             new Parcelable.Creator<ClientRequestStats>() {
 
                 public ClientRequestStats createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/DataConnectionRealTimeInfo.java b/telephony/java/android/telephony/DataConnectionRealTimeInfo.java
index fc4e17a..8106f5f 100644
--- a/telephony/java/android/telephony/DataConnectionRealTimeInfo.java
+++ b/telephony/java/android/telephony/DataConnectionRealTimeInfo.java
@@ -92,7 +92,7 @@
         out.writeInt(mDcPowerState);
     }
 
-    public static final Parcelable.Creator<DataConnectionRealTimeInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<DataConnectionRealTimeInfo> CREATOR
             = new Parcelable.Creator<DataConnectionRealTimeInfo>() {
 
         @Override
diff --git a/telephony/java/android/telephony/DataSpecificRegistrationStates.java b/telephony/java/android/telephony/DataSpecificRegistrationStates.java
index d6a8065..8eb345a 100644
--- a/telephony/java/android/telephony/DataSpecificRegistrationStates.java
+++ b/telephony/java/android/telephony/DataSpecificRegistrationStates.java
@@ -1,5 +1,7 @@
 package android.telephony;
 
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 
@@ -10,14 +12,17 @@
  * Class that stores information specific to data network registration.
  * @hide
  */
-public class DataSpecificRegistrationStates implements Parcelable{
+@SystemApi
+public final class DataSpecificRegistrationStates implements Parcelable{
     /**
+     * @hide
      * The maximum number of simultaneous Data Calls that
      * must be established using setupDataCall().
      */
     public final int maxDataCalls;
 
     /**
+     * @hide
      * Indicates if the use of dual connectivity with NR is restricted.
      * Reference: 3GPP TS 24.301 v15.03 section 9.3.3.12A.
      */
@@ -25,7 +30,7 @@
 
     /**
      * Indicates if NR is supported by the selected PLMN.
-     *
+     * @hide
      * {@code true} if the bit N is in the PLMN-InfoList-r15 is true and the selected PLMN is
      * present in plmn-IdentityList at position N.
      * Reference: 3GPP TS 36.331 v15.2.2 section 6.3.1 PLMN-InfoList-r15.
@@ -34,6 +39,7 @@
     public final boolean isNrAvailable;
 
     /**
+     * @hide
      * Indicates that if E-UTRA-NR Dual Connectivity (EN-DC) is supported by the primary serving
      * cell.
      *
@@ -47,8 +53,11 @@
     /**
      * Provides network support info for LTE VoPS and LTE Emergency bearer support
      */
-    public final LteVopsSupportInfo lteVopsSupportInfo;
+    private final LteVopsSupportInfo lteVopsSupportInfo;
 
+    /**
+     * @hide
+     */
     DataSpecificRegistrationStates(
             int maxDataCalls, boolean isDcNrRestricted, boolean isNrAvailable,
             boolean isEnDcAvailable, LteVopsSupportInfo lteVops) {
@@ -114,7 +123,7 @@
                 && this.lteVopsSupportInfo.equals(other.lteVopsSupportInfo);
     }
 
-    public static final Parcelable.Creator<DataSpecificRegistrationStates> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<DataSpecificRegistrationStates> CREATOR =
             new Parcelable.Creator<DataSpecificRegistrationStates>() {
                 @Override
                 public DataSpecificRegistrationStates createFromParcel(Parcel source) {
@@ -126,4 +135,12 @@
                     return new DataSpecificRegistrationStates[size];
                 }
             };
+
+    /**
+     * @return LteVopsSupportInfo
+     */
+    @NonNull
+    public LteVopsSupportInfo getLteVopsSupportInfo() {
+        return lteVopsSupportInfo;
+    }
 }
diff --git a/telephony/java/android/telephony/DisconnectCause.java b/telephony/java/android/telephony/DisconnectCause.java
index f53cb82..6e839ab 100644
--- a/telephony/java/android/telephony/DisconnectCause.java
+++ b/telephony/java/android/telephony/DisconnectCause.java
@@ -26,7 +26,7 @@
  * @hide
  */
 @SystemApi
-public class DisconnectCause {
+public final class DisconnectCause {
 
     /** The disconnect cause is not valid (Not received a disconnect cause) */
     public static final int NOT_VALID                      = -1;
diff --git a/telephony/java/android/telephony/IccOpenLogicalChannelResponse.java b/telephony/java/android/telephony/IccOpenLogicalChannelResponse.java
index 4621f91..44ba70c 100644
--- a/telephony/java/android/telephony/IccOpenLogicalChannelResponse.java
+++ b/telephony/java/android/telephony/IccOpenLogicalChannelResponse.java
@@ -110,7 +110,7 @@
         }
     }
 
-    public static final Parcelable.Creator<IccOpenLogicalChannelResponse> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<IccOpenLogicalChannelResponse> CREATOR
              = new Parcelable.Creator<IccOpenLogicalChannelResponse>() {
 
         @Override
diff --git a/telephony/java/android/telephony/ImsiEncryptionInfo.java b/telephony/java/android/telephony/ImsiEncryptionInfo.java
index d2680ad..ef2f121 100644
--- a/telephony/java/android/telephony/ImsiEncryptionInfo.java
+++ b/telephony/java/android/telephony/ImsiEncryptionInfo.java
@@ -115,7 +115,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<ImsiEncryptionInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ImsiEncryptionInfo> CREATOR =
             new Parcelable.Creator<ImsiEncryptionInfo>() {
                 @Override
                 public ImsiEncryptionInfo createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/LteVopsSupportInfo.java b/telephony/java/android/telephony/LteVopsSupportInfo.java
index 0ae85c0..ee45f07 100644
--- a/telephony/java/android/telephony/LteVopsSupportInfo.java
+++ b/telephony/java/android/telephony/LteVopsSupportInfo.java
@@ -117,7 +117,7 @@
                 + " mEmcBearerSupport = " + mEmcBearerSupport);
     }
 
-    public static final Creator<LteVopsSupportInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<LteVopsSupportInfo> CREATOR =
             new Creator<LteVopsSupportInfo>() {
         @Override
         public LteVopsSupportInfo createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ModemActivityInfo.java b/telephony/java/android/telephony/ModemActivityInfo.java
index 521adef..a0af392 100644
--- a/telephony/java/android/telephony/ModemActivityInfo.java
+++ b/telephony/java/android/telephony/ModemActivityInfo.java
@@ -71,7 +71,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<ModemActivityInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ModemActivityInfo> CREATOR =
             new Parcelable.Creator<ModemActivityInfo>() {
         public ModemActivityInfo createFromParcel(Parcel in) {
             long timestamp = in.readLong();
diff --git a/telephony/java/android/telephony/ModemInfo.java b/telephony/java/android/telephony/ModemInfo.java
index 27a5121..c0833af 100644
--- a/telephony/java/android/telephony/ModemInfo.java
+++ b/telephony/java/android/telephony/ModemInfo.java
@@ -97,7 +97,7 @@
         dest.writeBoolean(isDataSupported);
     }
 
-    public static final Parcelable.Creator<ModemInfo> CREATOR = new Parcelable.Creator() {
+    public static final @android.annotation.NonNull Parcelable.Creator<ModemInfo> CREATOR = new Parcelable.Creator() {
         public ModemInfo createFromParcel(Parcel in) {
             return new ModemInfo(in);
         }
diff --git a/telephony/java/android/telephony/NeighboringCellInfo.java b/telephony/java/android/telephony/NeighboringCellInfo.java
index 1c615ab..023ed30 100644
--- a/telephony/java/android/telephony/NeighboringCellInfo.java
+++ b/telephony/java/android/telephony/NeighboringCellInfo.java
@@ -331,7 +331,7 @@
         dest.writeInt(mNetworkType);
     }
 
-    public static final Parcelable.Creator<NeighboringCellInfo> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<NeighboringCellInfo> CREATOR
     = new Parcelable.Creator<NeighboringCellInfo>() {
         public NeighboringCellInfo createFromParcel(Parcel in) {
             return new NeighboringCellInfo(in);
diff --git a/telephony/java/android/telephony/NetworkRegistrationState.java b/telephony/java/android/telephony/NetworkRegistrationState.java
index 6e6d59e..9614dc5 100644
--- a/telephony/java/android/telephony/NetworkRegistrationState.java
+++ b/telephony/java/android/telephony/NetworkRegistrationState.java
@@ -349,7 +349,7 @@
     }
 
     /**
-     * @hide
+     * @return Data registration related info
      */
     @Nullable
     public DataSpecificRegistrationStates getDataSpecificStates() {
@@ -509,7 +509,7 @@
         }
     }
 
-    public static final Parcelable.Creator<NetworkRegistrationState> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<NetworkRegistrationState> CREATOR =
             new Parcelable.Creator<NetworkRegistrationState>() {
         @Override
         public NetworkRegistrationState createFromParcel(Parcel source) {
diff --git a/telephony/java/android/telephony/NetworkScanRequest.java b/telephony/java/android/telephony/NetworkScanRequest.java
index 38678a3..465b6aa 100644
--- a/telephony/java/android/telephony/NetworkScanRequest.java
+++ b/telephony/java/android/telephony/NetworkScanRequest.java
@@ -267,7 +267,7 @@
                 + (mMccMncs.hashCode() * 59));
     }
 
-    public static final Creator<NetworkScanRequest> CREATOR =
+    public static final @android.annotation.NonNull Creator<NetworkScanRequest> CREATOR =
             new Creator<NetworkScanRequest>() {
                 @Override
                 public NetworkScanRequest createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/PcoData.java b/telephony/java/android/telephony/PcoData.java
index 3e735e7..bcfbcf8b 100644
--- a/telephony/java/android/telephony/PcoData.java
+++ b/telephony/java/android/telephony/PcoData.java
@@ -69,7 +69,7 @@
      *
      * @hide
      */
-    public static final Parcelable.Creator<PcoData> CREATOR = new Parcelable.Creator() {
+    public static final @android.annotation.NonNull Parcelable.Creator<PcoData> CREATOR = new Parcelable.Creator() {
         public PcoData createFromParcel(Parcel in) {
             return new PcoData(in);
         }
diff --git a/telephony/java/android/telephony/PhoneCapability.java b/telephony/java/android/telephony/PhoneCapability.java
index 21dad77..119f587 100644
--- a/telephony/java/android/telephony/PhoneCapability.java
+++ b/telephony/java/android/telephony/PhoneCapability.java
@@ -105,7 +105,7 @@
         dest.writeList(logicalModemList);
     }
 
-    public static final Parcelable.Creator<PhoneCapability> CREATOR = new Parcelable.Creator() {
+    public static final @android.annotation.NonNull Parcelable.Creator<PhoneCapability> CREATOR = new Parcelable.Creator() {
         public PhoneCapability createFromParcel(Parcel in) {
             return new PhoneCapability(in);
         }
diff --git a/telephony/java/android/telephony/PhoneNumberRange.java b/telephony/java/android/telephony/PhoneNumberRange.java
index dba803b..2c66503 100644
--- a/telephony/java/android/telephony/PhoneNumberRange.java
+++ b/telephony/java/android/telephony/PhoneNumberRange.java
@@ -43,7 +43,7 @@
  */
 @SystemApi
 public final class PhoneNumberRange implements Parcelable {
-    public static final Creator<PhoneNumberRange> CREATOR = new Creator<PhoneNumberRange>() {
+    public static final @android.annotation.NonNull Creator<PhoneNumberRange> CREATOR = new Creator<PhoneNumberRange>() {
         @Override
         public PhoneNumberRange createFromParcel(Parcel in) {
             return new PhoneNumberRange(in);
diff --git a/telephony/java/android/telephony/PhoneStateListener.java b/telephony/java/android/telephony/PhoneStateListener.java
index ffebc04..5fd36f4 100644
--- a/telephony/java/android/telephony/PhoneStateListener.java
+++ b/telephony/java/android/telephony/PhoneStateListener.java
@@ -176,26 +176,21 @@
 
     /**
      * Listen for {@link PreciseCallState.State} of ringing, background and foreground calls.
-     * {@more}
-     * Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
-     * READ_PRECISE_PHONE_STATE}
      *
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public static final int LISTEN_PRECISE_CALL_STATE                       = 0x00000800;
 
     /**
      * Listen for {@link PreciseDataConnectionState} on the data connection (cellular).
      *
-     * {@more}
-     * Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
-     * READ_PRECISE_PHONE_STATE}
-     *
      * @see #onPreciseDataConnectionStateChanged
      *
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public static final int LISTEN_PRECISE_DATA_CONNECTION_STATE            = 0x00001000;
 
@@ -331,12 +326,10 @@
     /**
      * Listen for call disconnect causes which contains {@link DisconnectCause} and
      * {@link PreciseDisconnectCause}.
-     * {@more}
-     * Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
-     * READ_PRECISE_PHONE_STATE}
      *
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public static final int LISTEN_CALL_DISCONNECT_CAUSES                  = 0x02000000;
 
@@ -356,13 +349,10 @@
      * Listen for IMS call disconnect causes which contains
      * {@link android.telephony.ims.ImsReasonInfo}
      *
-     * {@more}
-     * Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
-     * READ_PRECISE_PHONE_STATE}
-     *
      * @see #onImsCallDisconnectCauseChanged(ImsReasonInfo)
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public static final int LISTEN_IMS_CALL_DISCONNECT_CAUSES              = 0x08000000;
 
@@ -579,8 +569,9 @@
      * @param callState {@link PreciseCallState}
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
-    public void onPreciseCallStateChanged(PreciseCallState callState) {
+    public void onPreciseCallStateChanged(@NonNull PreciseCallState callState) {
         // default implementation empty
     }
 
@@ -591,6 +582,7 @@
      *
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public void onCallDisconnectCauseChanged(int disconnectCause, int preciseDisconnectCause) {
         // default implementation empty
@@ -602,6 +594,7 @@
      *
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public void onImsCallDisconnectCauseChanged(@NonNull ImsReasonInfo imsReasonInfo) {
         // default implementation empty
@@ -613,9 +606,10 @@
      *
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public void onPreciseDataConnectionStateChanged(
-            PreciseDataConnectionState dataConnectionState) {
+            @NonNull PreciseDataConnectionState dataConnectionState) {
         // default implementation empty
     }
 
diff --git a/telephony/java/android/telephony/PhysicalChannelConfig.java b/telephony/java/android/telephony/PhysicalChannelConfig.java
index 22ddb4a..e1763ab 100644
--- a/telephony/java/android/telephony/PhysicalChannelConfig.java
+++ b/telephony/java/android/telephony/PhysicalChannelConfig.java
@@ -222,7 +222,7 @@
                 mChannelNumber, mPhysicalCellId, mContextIds);
     }
 
-    public static final Parcelable.Creator<PhysicalChannelConfig> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<PhysicalChannelConfig> CREATOR =
         new Parcelable.Creator<PhysicalChannelConfig>() {
             public PhysicalChannelConfig createFromParcel(Parcel in) {
                 return new PhysicalChannelConfig(in);
diff --git a/telephony/java/android/telephony/PreciseCallState.java b/telephony/java/android/telephony/PreciseCallState.java
index 19e1931..5fb9bac 100644
--- a/telephony/java/android/telephony/PreciseCallState.java
+++ b/telephony/java/android/telephony/PreciseCallState.java
@@ -257,7 +257,7 @@
         out.writeInt(mPreciseDisconnectCause);
     }
 
-    public static final Parcelable.Creator<PreciseCallState> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<PreciseCallState> CREATOR
             = new Parcelable.Creator<PreciseCallState>() {
 
         public PreciseCallState createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/PreciseDataConnectionState.java b/telephony/java/android/telephony/PreciseDataConnectionState.java
index 57a1826..cd4fbac 100644
--- a/telephony/java/android/telephony/PreciseDataConnectionState.java
+++ b/telephony/java/android/telephony/PreciseDataConnectionState.java
@@ -16,6 +16,8 @@
 
 package android.telephony;
 
+import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.annotation.SystemApi;
 import android.annotation.UnsupportedAppUsage;
 import android.net.LinkProperties;
@@ -25,6 +27,7 @@
 
 import java.util.Objects;
 
+
 /**
  * Contains precise data connection state.
  *
@@ -119,6 +122,7 @@
     /**
      * Returns APN {@link ApnSetting} of this data connection.
      */
+    @Nullable
     public String getDataConnectionApn() {
         return mAPN;
     }
@@ -154,7 +158,7 @@
         out.writeInt(mFailCause);
     }
 
-    public static final Parcelable.Creator<PreciseDataConnectionState> CREATOR
+    public static final @android.annotation.NonNull Parcelable.Creator<PreciseDataConnectionState> CREATOR
             = new Parcelable.Creator<PreciseDataConnectionState>() {
 
         public PreciseDataConnectionState createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/PreciseDisconnectCause.java b/telephony/java/android/telephony/PreciseDisconnectCause.java
index af88748..54980a2 100644
--- a/telephony/java/android/telephony/PreciseDisconnectCause.java
+++ b/telephony/java/android/telephony/PreciseDisconnectCause.java
@@ -23,7 +23,7 @@
  * @hide
  */
 @SystemApi
-public class PreciseDisconnectCause {
+public final class PreciseDisconnectCause {
 
     /** The disconnect cause is not valid (Not received a disconnect cause).*/
     public static final int NOT_VALID                                        = -1;
diff --git a/telephony/java/android/telephony/RadioAccessFamily.java b/telephony/java/android/telephony/RadioAccessFamily.java
index c1786be..4fdfcbe0 100644
--- a/telephony/java/android/telephony/RadioAccessFamily.java
+++ b/telephony/java/android/telephony/RadioAccessFamily.java
@@ -152,7 +152,7 @@
     /**
      * Implement the Parcelable interface.
      */
-    public static final Creator<android.telephony.RadioAccessFamily> CREATOR =
+    public static final @android.annotation.NonNull Creator<android.telephony.RadioAccessFamily> CREATOR =
             new Creator<android.telephony.RadioAccessFamily>() {
 
         @Override
diff --git a/telephony/java/android/telephony/RadioAccessSpecifier.java b/telephony/java/android/telephony/RadioAccessSpecifier.java
index 81e7ed0..690e44a 100644
--- a/telephony/java/android/telephony/RadioAccessSpecifier.java
+++ b/telephony/java/android/telephony/RadioAccessSpecifier.java
@@ -109,7 +109,7 @@
         return mChannels == null ? null : mChannels.clone();
     }
 
-    public static final Parcelable.Creator<RadioAccessSpecifier> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<RadioAccessSpecifier> CREATOR =
             new Parcelable.Creator<RadioAccessSpecifier> (){
                 @Override
                 public RadioAccessSpecifier createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ServiceState.java b/telephony/java/android/telephony/ServiceState.java
index 3dc1199..03f6351 100644
--- a/telephony/java/android/telephony/ServiceState.java
+++ b/telephony/java/android/telephony/ServiceState.java
@@ -498,7 +498,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<ServiceState> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ServiceState> CREATOR =
             new Parcelable.Creator<ServiceState>() {
         public ServiceState createFromParcel(Parcel in) {
             return new ServiceState(in);
diff --git a/telephony/java/android/telephony/SignalStrength.java b/telephony/java/android/telephony/SignalStrength.java
index d2ae106..c516d97 100644
--- a/telephony/java/android/telephony/SignalStrength.java
+++ b/telephony/java/android/telephony/SignalStrength.java
@@ -215,13 +215,52 @@
      * @see android.telephony#CellSignalStrengthGsm
      */
     public @NonNull List<CellSignalStrength> getCellSignalStrengths() {
-        List<CellSignalStrength> cssList = new ArrayList<>(2); // Usually have 2 or fewer elems
-        if (mLte.isValid()) cssList.add(mLte);
-        if (mCdma.isValid()) cssList.add(mCdma);
-        if (mTdscdma.isValid()) cssList.add(mTdscdma);
-        if (mWcdma.isValid()) cssList.add(mWcdma);
-        if (mGsm.isValid()) cssList.add(mGsm);
-        if (mNr.isValid()) cssList.add(mNr);
+        return getCellSignalStrengths(CellSignalStrength.class);
+    }
+
+    /**
+     * Returns a List of CellSignalStrength Components of this SignalStrength Report.
+     *
+     * Use this API to access underlying
+     * {@link android.telephony#CellSignalStrength CellSignalStrength} objects that provide more
+     * granular information about the SignalStrength report. Only valid (non-empty)
+     * CellSignalStrengths will be returned. The order of any returned elements is not guaranteed,
+     * and the list may contain more than one instance of a CellSignalStrength type.
+     *
+     * @param clazz a class type that extends
+     *        {@link android.telephony.CellSignalStrength CellSignalStrength} to filter possible
+     *        return values.
+     * @return a List of CellSignalStrength or an empty List if there are no valid measurements.
+     *
+     * @see android.telephony#CellSignalStrength
+     * @see android.telephony#CellSignalStrengthNr
+     * @see android.telephony#CellSignalStrengthLte
+     * @see android.telephony#CellSignalStrengthTdscdma
+     * @see android.telephony#CellSignalStrengthWcdma
+     * @see android.telephony#CellSignalStrengthCdma
+     * @see android.telephony#CellSignalStrengthGsm
+     */
+    public <T extends CellSignalStrength> @NonNull List<T> getCellSignalStrengths(
+            @NonNull Class<T> clazz) {
+        List<T> cssList = new ArrayList<>(2); // Usually have 2 or fewer elems
+        if (mLte.isValid() && clazz.isAssignableFrom(CellSignalStrengthLte.class)) {
+            cssList.add((T) mLte);
+        }
+        if (mCdma.isValid() && clazz.isAssignableFrom(CellSignalStrengthCdma.class)) {
+            cssList.add((T) mCdma);
+        }
+        if (mTdscdma.isValid() && clazz.isAssignableFrom(CellSignalStrengthTdscdma.class)) {
+            cssList.add((T) mTdscdma);
+        }
+        if (mWcdma.isValid() && clazz.isAssignableFrom(CellSignalStrengthWcdma.class)) {
+            cssList.add((T) mWcdma);
+        }
+        if (mGsm.isValid() && clazz.isAssignableFrom(CellSignalStrengthGsm.class)) {
+            cssList.add((T) mGsm);
+        }
+        if (mNr.isValid() && clazz.isAssignableFrom(CellSignalStrengthNr.class)) {
+            cssList.add((T) mNr);
+        }
         return cssList;
     }
 
@@ -302,7 +341,7 @@
      * @hide
      */
     @UnsupportedAppUsage
-    public static final Parcelable.Creator<SignalStrength> CREATOR = new Parcelable.Creator() {
+    public static final @android.annotation.NonNull Parcelable.Creator<SignalStrength> CREATOR = new Parcelable.Creator() {
         public SignalStrength createFromParcel(Parcel in) {
             return new SignalStrength(in);
         }
diff --git a/telephony/java/android/telephony/SubscriptionInfo.java b/telephony/java/android/telephony/SubscriptionInfo.java
index 17acf2b..fb6f39d 100644
--- a/telephony/java/android/telephony/SubscriptionInfo.java
+++ b/telephony/java/android/telephony/SubscriptionInfo.java
@@ -467,7 +467,7 @@
      * @return group UUID a String of group UUID if it belongs to a group. Otherwise
      * it will return null.
      */
-    public String getGroupUuid() {
+    public @Nullable String getGroupUuid() {
         return mGroupUUID;
     }
 
@@ -602,7 +602,7 @@
         return mIsGroupDisabled;
     }
 
-    public static final Parcelable.Creator<SubscriptionInfo> CREATOR = new Parcelable.Creator<SubscriptionInfo>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<SubscriptionInfo> CREATOR = new Parcelable.Creator<SubscriptionInfo>() {
         @Override
         public SubscriptionInfo createFromParcel(Parcel source) {
             int id = source.readInt();
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index c28d1fb..e0b7fc4 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -63,14 +63,17 @@
 import com.android.internal.telephony.ISub;
 import com.android.internal.telephony.ITelephonyRegistry;
 import com.android.internal.telephony.PhoneConstants;
+import com.android.internal.util.Preconditions;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Locale;
+import java.util.Map;
 import java.util.concurrent.Executor;
 import java.util.concurrent.TimeUnit;
 import java.util.function.Consumer;
@@ -151,6 +154,7 @@
      * {@link Uri#withAppendedPath(Uri, String)}.
      * @hide
      */
+    @NonNull
     @SystemApi
     public static final Uri WFC_ENABLED_CONTENT_URI = Uri.withAppendedPath(CONTENT_URI, "wfc");
 
@@ -169,6 +173,7 @@
      * {@link Uri#withAppendedPath(Uri, String)}.
      * @hide
      */
+    @NonNull
     @SystemApi
     public static final Uri ADVANCED_CALLING_ENABLED_CONTENT_URI = Uri.withAppendedPath(
             CONTENT_URI, "advanced_calling");
@@ -186,6 +191,7 @@
      * {@link Uri#withAppendedPath(Uri, String)}.
      * @hide
      */
+    @NonNull
     @SystemApi
     public static final Uri WFC_MODE_CONTENT_URI = Uri.withAppendedPath(CONTENT_URI, "wfc_mode");
 
@@ -202,6 +208,7 @@
      * {@link Uri#withAppendedPath(Uri, String)}.
      * @hide
      */
+    @NonNull
     @SystemApi
     public static final Uri WFC_ROAMING_MODE_CONTENT_URI = Uri.withAppendedPath(
             CONTENT_URI, "wfc_roaming_mode");
@@ -220,6 +227,7 @@
      * {@link Uri#withAppendedPath(Uri, String)}.
      * @hide
      */
+    @NonNull
     @SystemApi
     public static final Uri VT_ENABLED_CONTENT_URI = Uri.withAppendedPath(
             CONTENT_URI, "vt_enabled");
@@ -237,6 +245,7 @@
      * {@link Uri#withAppendedPath(Uri, String)}.
      * @hide
      */
+    @NonNull
     @SystemApi
     public static final Uri WFC_ROAMING_ENABLED_CONTENT_URI = Uri.withAppendedPath(
             CONTENT_URI, "wfc_roaming_enabled");
@@ -1066,7 +1075,8 @@
      * @param listener that is to be unregistered.
      */
     public void removeOnOpportunisticSubscriptionsChangedListener(
-            OnOpportunisticSubscriptionsChangedListener listener) {
+            @NonNull OnOpportunisticSubscriptionsChangedListener listener) {
+        Preconditions.checkNotNull(listener, "listener cannot be null");
         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
         if (DBG) {
             logd("unregister OnOpportunisticSubscriptionsChangedListener pkgForDebug="
@@ -2682,7 +2692,8 @@
      *  @param callbackIntent pending intent that will be sent after operation is done.
      */
     @RequiresPermission(android.Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
-    public void switchToSubscription(int subId, PendingIntent callbackIntent) {
+    public void switchToSubscription(int subId, @NonNull PendingIntent callbackIntent) {
+        Preconditions.checkNotNull(callbackIntent, "callbackIntent cannot be null");
         EuiccManager euiccManager = new EuiccManager(mContext);
         euiccManager.switchToSubscription(subId, callbackIntent);
     }
@@ -2900,8 +2911,33 @@
         if (availableList == null) {
             return null;
         } else {
-            return availableList.stream().filter(subInfo -> !shouldHideSubscription(subInfo))
-                    .collect(Collectors.toList());
+            // Multiple subscriptions in a group should only have one representative.
+            // It should be the current active primary subscription if any, or any
+            // primary subscription.
+            List<SubscriptionInfo> selectableList = new ArrayList<>();
+            Map<String, SubscriptionInfo> groupMap = new HashMap<>();
+
+            for (SubscriptionInfo info : availableList) {
+                // Opportunistic subscriptions are considered invisible
+                // to users so they should never be returned.
+                if (isInvisibleSubscription(info)) continue;
+
+                String groupUuid = info.getGroupUuid();
+                if (groupUuid == null) {
+                    // Doesn't belong to any group. Add in the list.
+                    selectableList.add(info);
+                } else if (!groupMap.containsKey(groupUuid)
+                        || (groupMap.get(groupUuid).getSimSlotIndex() == INVALID_SIM_SLOT_INDEX
+                        && info.getSimSlotIndex() != INVALID_SIM_SLOT_INDEX)) {
+                    // If it belongs to a group that has never been recorded or it's the current
+                    // active subscription, add it in the list.
+                    selectableList.remove(groupMap.get(groupUuid));
+                    selectableList.add(info);
+                    groupMap.put(groupUuid, info);
+                }
+
+            }
+            return selectableList;
         }
     }
 
diff --git a/telephony/java/android/telephony/SubscriptionPlan.java b/telephony/java/android/telephony/SubscriptionPlan.java
index d67169c..e0838b3 100644
--- a/telephony/java/android/telephony/SubscriptionPlan.java
+++ b/telephony/java/android/telephony/SubscriptionPlan.java
@@ -145,7 +145,7 @@
         return false;
     }
 
-    public static final Parcelable.Creator<SubscriptionPlan> CREATOR = new Parcelable.Creator<SubscriptionPlan>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<SubscriptionPlan> CREATOR = new Parcelable.Creator<SubscriptionPlan>() {
         @Override
         public SubscriptionPlan createFromParcel(Parcel source) {
             return new SubscriptionPlan(source);
diff --git a/telephony/java/android/telephony/TelephonyHistogram.java b/telephony/java/android/telephony/TelephonyHistogram.java
index e1c3d7b..63bdac5 100644
--- a/telephony/java/android/telephony/TelephonyHistogram.java
+++ b/telephony/java/android/telephony/TelephonyHistogram.java
@@ -256,7 +256,7 @@
         }
     }
 
-    public static final Parcelable.Creator<TelephonyHistogram> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<TelephonyHistogram> CREATOR =
             new Parcelable.Creator<TelephonyHistogram> () {
 
                 @Override
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index f1869b0..31d8ddb 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -1366,6 +1366,26 @@
      * Intent sent when an error occurs that debug tools should log and possibly take further
      * action such as capturing vendor-specific logs.
      *
+     * A privileged application that reads these events should take appropriate vendor-specific
+     * action to record the event and collect further information to assist in analysis, debugging,
+     * and resolution of any associated issue.
+     *
+     * <p>This event should not be used for generic logging or diagnostic monitoring purposes and
+     * should generally be sent at a low rate. Instead, this mechanism should be used for the
+     * framework to notify a debugging application that an event (such as a bug) has occured
+     * within the framework if that event should trigger the collection and preservation of other
+     * more detailed device state for debugging.
+     *
+     * <p>At most one application can receive these events and should register a receiver in
+     * in the application manifest. For performance reasons, if no application to receive these
+     * events is detected at boot, then these events will not be sent.
+     *
+     * <p>Each event will include an {@link EXTRA_DEBUG_EVENT_ID} that will uniquely identify the
+     * event that has occurred. Each event will be sent to the diagnostic monitor only once per
+     * boot cycle (as another optimization).
+     *
+     * @see #EXTRA_DEBUG_EVENT_ID
+     * @see #EXTRA_DEBUG_EVENT_DESCRIPTION
      * @hide
      */
     @SystemApi
@@ -1373,21 +1393,23 @@
     public static final String ACTION_DEBUG_EVENT = "android.telephony.action.DEBUG_EVENT";
 
     /**
-     * An arbitrary ParcelUuid which should be consistent for each occurrence of the same event.
+     * An arbitrary ParcelUuid which should be consistent for each occurrence of a DebugEvent.
      *
-     * This field must be included in all events.
+     * This field must be included in all {@link ACTION_DEBUG_EVENT} events.
      *
+     * @see #ACTION_DEBUG_EVENT
      * @hide
      */
     @SystemApi
     public static final String EXTRA_DEBUG_EVENT_ID = "android.telephony.extra.DEBUG_EVENT_ID";
 
     /**
-     * A freeform string description of the event.
+     * A freeform string description of the DebugEvent.
      *
-     * This field is optional for all events and as a guideline should not exceed 80 characters
-     * and should be as short as possible to convey the essence of the event.
+     * This field is optional for all {@link ACTION_DEBUG_EVENT}s, as a guideline should not
+     * exceed 80 characters, and should be as short as possible to convey the essence of the event.
      *
+     * @see #ACTION_DEBUG_EVENT
      * @hide
      */
     @SystemApi
@@ -3227,6 +3249,7 @@
      * the caller does not have adequate permissions for that card.
      */
     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
+    @NonNull
     public List<UiccCardInfo> getUiccCardsInfo() {
         try {
             ITelephony telephony = getITelephony();
@@ -8665,24 +8688,26 @@
 
 
     /**
-     * Returns a well-formed IETF BCP 47 language tag representing the locale from the SIM, e.g,
-     * en-US. Returns {@code null} if no locale could be derived from subscriptions.
+     * Returns a locale based on the country and language from the SIM. Returns {@code null} if
+     * no locale could be derived from subscriptions.
      *
      * <p>Requires Permission:
      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
      *
      * @see Locale#toLanguageTag()
-     * @see Locale#forLanguageTag(String)
      *
      * @hide
      */
     @SystemApi
     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
-    @Nullable public String getSimLocale() {
+    @Nullable public Locale getSimLocale() {
         try {
             final ITelephony telephony = getITelephony();
             if (telephony != null) {
-                return telephony.getSimLocaleForSubscriber(getSubId());
+                String languageTag = telephony.getSimLocaleForSubscriber(getSubId());
+                if (!TextUtils.isEmpty(languageTag)) {
+                    return Locale.forLanguageTag(languageTag);
+                }
             }
         } catch (RemoteException ex) {
         }
diff --git a/telephony/java/android/telephony/UiccAccessRule.java b/telephony/java/android/telephony/UiccAccessRule.java
index d8836dc..37a4491 100644
--- a/telephony/java/android/telephony/UiccAccessRule.java
+++ b/telephony/java/android/telephony/UiccAccessRule.java
@@ -47,7 +47,7 @@
 
     private static final int ENCODING_VERSION = 1;
 
-    public static final Creator<UiccAccessRule> CREATOR = new Creator<UiccAccessRule>() {
+    public static final @android.annotation.NonNull Creator<UiccAccessRule> CREATOR = new Creator<UiccAccessRule>() {
         @Override
         public UiccAccessRule createFromParcel(Parcel in) {
             return new UiccAccessRule(in);
diff --git a/telephony/java/android/telephony/UiccCardInfo.java b/telephony/java/android/telephony/UiccCardInfo.java
index 19f357a..2c98c4d 100644
--- a/telephony/java/android/telephony/UiccCardInfo.java
+++ b/telephony/java/android/telephony/UiccCardInfo.java
@@ -15,6 +15,8 @@
  */
 package android.telephony;
 
+import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.os.Parcel;
 import android.os.Parcelable;
 
@@ -30,8 +32,9 @@
     private final String mEid;
     private final String mIccId;
     private final int mSlotIndex;
+    private final boolean mIsRemovable;
 
-    public static final Creator<UiccCardInfo> CREATOR = new Creator<UiccCardInfo>() {
+    public static final @android.annotation.NonNull Creator<UiccCardInfo> CREATOR = new Creator<UiccCardInfo>() {
         @Override
         public UiccCardInfo createFromParcel(Parcel in) {
             return new UiccCardInfo(in);
@@ -49,6 +52,7 @@
         mEid = in.readString();
         mIccId = in.readString();
         mSlotIndex = in.readInt();
+        mIsRemovable = in.readByte() != 0;
     }
 
     @Override
@@ -58,6 +62,7 @@
         dest.writeString(mEid);
         dest.writeString(mIccId);
         dest.writeInt(mSlotIndex);
+        dest.writeByte((byte) (mIsRemovable ? 1 : 0));
     }
 
     @Override
@@ -65,16 +70,21 @@
         return 0;
     }
 
-    public UiccCardInfo(boolean isEuicc, int cardId, String eid, String iccId, int slotIndex) {
+    /**
+     * @hide
+     */
+    public UiccCardInfo(boolean isEuicc, int cardId, String eid, String iccId, int slotIndex,
+            boolean isRemovable) {
         this.mIsEuicc = isEuicc;
         this.mCardId = cardId;
         this.mEid = eid;
         this.mIccId = iccId;
         this.mSlotIndex = slotIndex;
+        this.mIsRemovable = isRemovable;
     }
 
     /**
-     * Return whether the UiccCardInfo is an eUICC.
+     * Return whether the UICC is an eUICC.
      * @return true if the UICC is an eUICC.
      */
     public boolean isEuicc() {
@@ -96,6 +106,7 @@
      * Note that this field may be omitted if the caller does not have the correct permissions
      * (see {@link TelephonyManager#getUiccCardsInfo()}).
      */
+    @Nullable
     public String getEid() {
         if (!mIsEuicc) {
             return null;
@@ -109,6 +120,7 @@
      * Note that this field may be omitted if the caller does not have the correct permissions
      * (see {@link TelephonyManager#getUiccCardsInfo()}).
      */
+    @Nullable
     public String getIccId() {
         return mIccId;
     }
@@ -121,13 +133,24 @@
     }
 
     /**
-     * Returns a copy of the UiccCardinfo with the clears the EID and ICCID set to null. These
-     * values are generally private and require carrier privileges to view.
+     * Returns a copy of the UiccCardinfo with the EID and ICCID set to null. These values are
+     * generally private and require carrier privileges to view.
      *
      * @hide
      */
+    @NonNull
     public UiccCardInfo getUnprivileged() {
-        return new UiccCardInfo(mIsEuicc, mCardId, null, null, mSlotIndex);
+        return new UiccCardInfo(mIsEuicc, mCardId, null, null, mSlotIndex, mIsRemovable);
+    }
+
+    /**
+     * Return whether the UICC or eUICC is removable.
+     * <p>
+     * UICCs are generally removable, but eUICCs may be removable or built in to the device.
+     * @return true if the UICC or eUICC is removable
+     */
+    public boolean isRemovable() {
+        return mIsRemovable;
     }
 
     @Override
@@ -144,12 +167,13 @@
                 && (mCardId == that.mCardId)
                 && (Objects.equals(mEid, that.mEid))
                 && (Objects.equals(mIccId, that.mIccId))
-                && (mSlotIndex == that.mSlotIndex));
+                && (mSlotIndex == that.mSlotIndex)
+                && (mIsRemovable == that.mIsRemovable));
     }
 
     @Override
     public int hashCode() {
-        return Objects.hash(mIsEuicc, mCardId, mEid, mIccId, mSlotIndex);
+        return Objects.hash(mIsEuicc, mCardId, mEid, mIccId, mSlotIndex, mIsRemovable);
     }
 
     @Override
@@ -164,6 +188,8 @@
                 + mIccId
                 + ", mSlotIndex="
                 + mSlotIndex
+                + ", mIsRemovable="
+                + mIsRemovable
                 + ")";
     }
 }
diff --git a/telephony/java/android/telephony/UiccSlotInfo.java b/telephony/java/android/telephony/UiccSlotInfo.java
index a39992b..785d7ae 100644
--- a/telephony/java/android/telephony/UiccSlotInfo.java
+++ b/telephony/java/android/telephony/UiccSlotInfo.java
@@ -15,15 +15,15 @@
  */
 package android.telephony;
 
+import android.annotation.IntDef;
 import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
+
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.util.Objects;
 
-import android.annotation.IntDef;
-
 /**
  * Class for the information of a UICC slot.
  * @hide
@@ -61,8 +61,9 @@
     private final @CardStateInfo int mCardStateInfo;
     private final int mLogicalSlotIdx;
     private final boolean mIsExtendedApduSupported;
+    private final boolean mIsRemovable;
 
-    public static final Creator<UiccSlotInfo> CREATOR = new Creator<UiccSlotInfo>() {
+    public static final @android.annotation.NonNull Creator<UiccSlotInfo> CREATOR = new Creator<UiccSlotInfo>() {
         @Override
         public UiccSlotInfo createFromParcel(Parcel in) {
             return new UiccSlotInfo(in);
@@ -81,6 +82,7 @@
         mCardStateInfo = in.readInt();
         mLogicalSlotIdx = in.readInt();
         mIsExtendedApduSupported = in.readByte() != 0;
+        mIsRemovable = in.readByte() != 0;
     }
 
     @Override
@@ -91,6 +93,7 @@
         dest.writeInt(mCardStateInfo);
         dest.writeInt(mLogicalSlotIdx);
         dest.writeByte((byte) (mIsExtendedApduSupported ? 1 : 0));
+        dest.writeByte((byte) (mIsRemovable ? 1 : 0));
     }
 
     @Override
@@ -98,6 +101,11 @@
         return 0;
     }
 
+    /**
+     * Construct a UiccSlotInfo.
+     * @deprecated apps should not be constructing UiccSlotInfo objects
+     */
+    @Deprecated
     public UiccSlotInfo(boolean isActive, boolean isEuicc, String cardId,
             @CardStateInfo int cardStateInfo, int logicalSlotIdx, boolean isExtendedApduSupported) {
         this.mIsActive = isActive;
@@ -106,6 +114,22 @@
         this.mCardStateInfo = cardStateInfo;
         this.mLogicalSlotIdx = logicalSlotIdx;
         this.mIsExtendedApduSupported = isExtendedApduSupported;
+        this.mIsRemovable = false;
+    }
+
+    /**
+     * @hide
+     */
+    public UiccSlotInfo(boolean isActive, boolean isEuicc, String cardId,
+            @CardStateInfo int cardStateInfo, int logicalSlotIdx, boolean isExtendedApduSupported,
+            boolean isRemovable) {
+        this.mIsActive = isActive;
+        this.mIsEuicc = isEuicc;
+        this.mCardId = cardId;
+        this.mCardStateInfo = cardStateInfo;
+        this.mLogicalSlotIdx = logicalSlotIdx;
+        this.mIsExtendedApduSupported = isExtendedApduSupported;
+        this.mIsRemovable = isRemovable;
     }
 
     public boolean getIsActive() {
@@ -136,6 +160,16 @@
         return mIsExtendedApduSupported;
     }
 
+   /**
+     * Return whether the UICC slot is for a removable UICC.
+     * <p>
+     * UICCs are generally removable, but eUICCs may be removable or built in to the device.
+     * @return true if the slot is for removable UICCs
+     */
+    public boolean isRemovable() {
+        return mIsRemovable;
+    }
+
     @Override
     public boolean equals(Object obj) {
         if (this == obj) {
@@ -151,7 +185,8 @@
                 && (Objects.equals(mCardId, that.mCardId))
                 && (mCardStateInfo == that.mCardStateInfo)
                 && (mLogicalSlotIdx == that.mLogicalSlotIdx)
-                && (mIsExtendedApduSupported == that.mIsExtendedApduSupported);
+                && (mIsExtendedApduSupported == that.mIsExtendedApduSupported)
+                && (mIsRemovable == that.mIsRemovable);
     }
 
     @Override
@@ -163,6 +198,7 @@
         result = 31 * result + mCardStateInfo;
         result = 31 * result + mLogicalSlotIdx;
         result = 31 * result + (mIsExtendedApduSupported ? 1 : 0);
+        result = 31 * result + (mIsRemovable ? 1 : 0);
         return result;
     }
 
@@ -180,6 +216,8 @@
                 + mLogicalSlotIdx
                 + ", mIsExtendedApduSupported="
                 + mIsExtendedApduSupported
+                + ", mIsRemovable="
+                + mIsRemovable
                 + ")";
     }
 }
diff --git a/telephony/java/android/telephony/UssdResponse.java b/telephony/java/android/telephony/UssdResponse.java
index 5df681d..19756b5 100644
--- a/telephony/java/android/telephony/UssdResponse.java
+++ b/telephony/java/android/telephony/UssdResponse.java
@@ -63,7 +63,7 @@
         mReturnMessage = returnMessage;
     }
 
-    public static final Parcelable.Creator<UssdResponse> CREATOR = new Creator<UssdResponse>() {
+    public static final @android.annotation.NonNull Parcelable.Creator<UssdResponse> CREATOR = new Creator<UssdResponse>() {
 
         @Override
         public UssdResponse createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/VisualVoicemailSms.java b/telephony/java/android/telephony/VisualVoicemailSms.java
index 1e6ea4b..085f882 100644
--- a/telephony/java/android/telephony/VisualVoicemailSms.java
+++ b/telephony/java/android/telephony/VisualVoicemailSms.java
@@ -116,7 +116,7 @@
     }
 
 
-    public static final Creator<VisualVoicemailSms> CREATOR =
+    public static final @android.annotation.NonNull Creator<VisualVoicemailSms> CREATOR =
             new Creator<VisualVoicemailSms>() {
                 @Override
                 public VisualVoicemailSms createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/VisualVoicemailSmsFilterSettings.java b/telephony/java/android/telephony/VisualVoicemailSmsFilterSettings.java
index 7eeb1ce..e8f3f1e 100644
--- a/telephony/java/android/telephony/VisualVoicemailSmsFilterSettings.java
+++ b/telephony/java/android/telephony/VisualVoicemailSmsFilterSettings.java
@@ -162,7 +162,7 @@
         packageName = builder.mPackageName;
     }
 
-    public static final Creator<VisualVoicemailSmsFilterSettings> CREATOR =
+    public static final @android.annotation.NonNull Creator<VisualVoicemailSmsFilterSettings> CREATOR =
             new Creator<VisualVoicemailSmsFilterSettings>() {
                 @Override
                 public VisualVoicemailSmsFilterSettings createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/VoLteServiceState.java b/telephony/java/android/telephony/VoLteServiceState.java
index d0b7519..f65c7b0 100644
--- a/telephony/java/android/telephony/VoLteServiceState.java
+++ b/telephony/java/android/telephony/VoLteServiceState.java
@@ -145,7 +145,7 @@
      *
      * @hide
      */
-    public static final Parcelable.Creator<VoLteServiceState> CREATOR = new Parcelable.Creator() {
+    public static final @android.annotation.NonNull Parcelable.Creator<VoLteServiceState> CREATOR = new Parcelable.Creator() {
         public VoLteServiceState createFromParcel(Parcel in) {
             return new VoLteServiceState(in);
         }
diff --git a/telephony/java/android/telephony/VoiceSpecificRegistrationStates.java b/telephony/java/android/telephony/VoiceSpecificRegistrationStates.java
index 871ee4d..d8ce5b4 100644
--- a/telephony/java/android/telephony/VoiceSpecificRegistrationStates.java
+++ b/telephony/java/android/telephony/VoiceSpecificRegistrationStates.java
@@ -99,7 +99,7 @@
     }
 
 
-    public static final Parcelable.Creator<VoiceSpecificRegistrationStates> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<VoiceSpecificRegistrationStates> CREATOR =
             new Parcelable.Creator<VoiceSpecificRegistrationStates>() {
                 @Override
                 public VoiceSpecificRegistrationStates createFromParcel(Parcel source) {
diff --git a/telephony/java/android/telephony/data/ApnSetting.java b/telephony/java/android/telephony/data/ApnSetting.java
index 0e69530..a4ed775 100644
--- a/telephony/java/android/telephony/data/ApnSetting.java
+++ b/telephony/java/android/telephony/data/ApnSetting.java
@@ -1410,7 +1410,7 @@
             0, 0, 0, 0, mvnoType, null, apnSetId, carrierId);
     }
 
-    public static final Parcelable.Creator<ApnSetting> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ApnSetting> CREATOR =
             new Parcelable.Creator<ApnSetting>() {
                 @Override
                 public ApnSetting createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/data/DataCallResponse.java b/telephony/java/android/telephony/data/DataCallResponse.java
index 3d2fe5f..6024143 100644
--- a/telephony/java/android/telephony/data/DataCallResponse.java
+++ b/telephony/java/android/telephony/data/DataCallResponse.java
@@ -244,7 +244,7 @@
         dest.writeInt(mMtu);
     }
 
-    public static final Parcelable.Creator<DataCallResponse> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<DataCallResponse> CREATOR =
             new Parcelable.Creator<DataCallResponse>() {
                 @Override
                 public DataCallResponse createFromParcel(Parcel source) {
diff --git a/telephony/java/android/telephony/data/DataProfile.java b/telephony/java/android/telephony/data/DataProfile.java
index 1d196f9..f45954b 100644
--- a/telephony/java/android/telephony/data/DataProfile.java
+++ b/telephony/java/android/telephony/data/DataProfile.java
@@ -284,7 +284,7 @@
     }
 
     /** @hide */
-    public static final Parcelable.Creator<DataProfile> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<DataProfile> CREATOR =
             new Parcelable.Creator<DataProfile>() {
         @Override
         public DataProfile createFromParcel(Parcel source) {
diff --git a/telephony/java/android/telephony/emergency/EmergencyNumber.java b/telephony/java/android/telephony/emergency/EmergencyNumber.java
index e68256d..5373c38 100644
--- a/telephony/java/android/telephony/emergency/EmergencyNumber.java
+++ b/telephony/java/android/telephony/emergency/EmergencyNumber.java
@@ -281,7 +281,7 @@
         dest.writeInt(mEmergencyCallRouting);
     }
 
-    public static final Parcelable.Creator<EmergencyNumber> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<EmergencyNumber> CREATOR =
             new Parcelable.Creator<EmergencyNumber>() {
                 @Override
                 public EmergencyNumber createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/euicc/DownloadableSubscription.java b/telephony/java/android/telephony/euicc/DownloadableSubscription.java
index f1d5bdd..cb27f64 100644
--- a/telephony/java/android/telephony/euicc/DownloadableSubscription.java
+++ b/telephony/java/android/telephony/euicc/DownloadableSubscription.java
@@ -38,7 +38,7 @@
  */
 public final class DownloadableSubscription implements Parcelable {
 
-    public static final Creator<DownloadableSubscription> CREATOR =
+    public static final @android.annotation.NonNull Creator<DownloadableSubscription> CREATOR =
             new Creator<DownloadableSubscription>() {
                 @Override
                 public DownloadableSubscription createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/euicc/EuiccInfo.java b/telephony/java/android/telephony/euicc/EuiccInfo.java
index 28855b2..91ebb6c 100644
--- a/telephony/java/android/telephony/euicc/EuiccInfo.java
+++ b/telephony/java/android/telephony/euicc/EuiccInfo.java
@@ -30,7 +30,7 @@
 // own APIs guarded with appropriate permission checks.
 public final class EuiccInfo implements Parcelable {
 
-    public static final Creator<EuiccInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<EuiccInfo> CREATOR =
             new Creator<EuiccInfo>() {
                 @Override
                 public EuiccInfo createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/euicc/EuiccNotification.java b/telephony/java/android/telephony/euicc/EuiccNotification.java
index 43a7707..b27f775 100644
--- a/telephony/java/android/telephony/euicc/EuiccNotification.java
+++ b/telephony/java/android/telephony/euicc/EuiccNotification.java
@@ -165,7 +165,7 @@
         mData = source.createByteArray();
     }
 
-    public static final Creator<EuiccNotification> CREATOR =
+    public static final @android.annotation.NonNull Creator<EuiccNotification> CREATOR =
             new Creator<EuiccNotification>() {
                 @Override
                 public EuiccNotification createFromParcel(Parcel source) {
diff --git a/telephony/java/android/telephony/euicc/EuiccRulesAuthTable.java b/telephony/java/android/telephony/euicc/EuiccRulesAuthTable.java
index 67ae983..89842ae 100644
--- a/telephony/java/android/telephony/euicc/EuiccRulesAuthTable.java
+++ b/telephony/java/android/telephony/euicc/EuiccRulesAuthTable.java
@@ -249,7 +249,7 @@
         mPolicyRuleFlags = source.createIntArray();
     }
 
-    public static final Creator<EuiccRulesAuthTable> CREATOR =
+    public static final @android.annotation.NonNull Creator<EuiccRulesAuthTable> CREATOR =
             new Creator<EuiccRulesAuthTable>() {
                 @Override
                 public EuiccRulesAuthTable createFromParcel(Parcel source) {
diff --git a/telephony/java/android/telephony/ims/ImsCallForwardInfo.java b/telephony/java/android/telephony/ims/ImsCallForwardInfo.java
index 70daa8b..9b72d58 100644
--- a/telephony/java/android/telephony/ims/ImsCallForwardInfo.java
+++ b/telephony/java/android/telephony/ims/ImsCallForwardInfo.java
@@ -204,7 +204,7 @@
         mServiceClass = in.readInt();
     }
 
-    public static final Creator<ImsCallForwardInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<ImsCallForwardInfo> CREATOR =
             new Creator<ImsCallForwardInfo>() {
         @Override
         public ImsCallForwardInfo createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/ImsCallProfile.java b/telephony/java/android/telephony/ims/ImsCallProfile.java
index 47c8de5..793ac3c 100644
--- a/telephony/java/android/telephony/ims/ImsCallProfile.java
+++ b/telephony/java/android/telephony/ims/ImsCallProfile.java
@@ -583,7 +583,7 @@
         mHasKnownUserIntentEmergency = in.readBoolean();
     }
 
-    public static final Creator<ImsCallProfile> CREATOR = new Creator<ImsCallProfile>() {
+    public static final @android.annotation.NonNull Creator<ImsCallProfile> CREATOR = new Creator<ImsCallProfile>() {
         @Override
         public ImsCallProfile createFromParcel(Parcel in) {
             return new ImsCallProfile(in);
diff --git a/telephony/java/android/telephony/ims/ImsConferenceState.java b/telephony/java/android/telephony/ims/ImsConferenceState.java
index 66d2f8d..44595b5 100644
--- a/telephony/java/android/telephony/ims/ImsConferenceState.java
+++ b/telephony/java/android/telephony/ims/ImsConferenceState.java
@@ -16,17 +16,18 @@
 
 package android.telephony.ims;
 
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map.Entry;
-import java.util.Set;
-
 import android.annotation.SystemApi;
 import android.os.Bundle;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.telecom.Call;
 import android.telecom.Connection;
+import android.telecom.Log;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map.Entry;
+import java.util.Set;
 
 /**
  * Provides the conference information (defined in RFC 4575) for IMS conference call.
@@ -134,7 +135,7 @@
         }
     }
 
-    public static final Creator<ImsConferenceState> CREATOR =
+    public static final @android.annotation.NonNull Creator<ImsConferenceState> CREATOR =
             new Creator<ImsConferenceState>() {
         @Override
         public ImsConferenceState createFromParcel(Parcel in) {
@@ -189,7 +190,7 @@
                 sb.append("<");
                 while (iterator.hasNext()) {
                     Entry<String, Bundle> entry = iterator.next();
-                    sb.append(entry.getKey());
+                    sb.append(Log.pii(entry.getKey()));
                     sb.append(": ");
                     Bundle participantData = entry.getValue();
 
@@ -197,7 +198,7 @@
                         sb.append(key);
                         sb.append("=");
                         if (ENDPOINT.equals(key) || USER.equals(key)) {
-                            sb.append(android.telecom.Log.pii(participantData.get(key)));
+                            sb.append(Log.pii(participantData.get(key)));
                         } else {
                             sb.append(participantData.get(key));
                         }
diff --git a/telephony/java/android/telephony/ims/ImsExternalCallState.java b/telephony/java/android/telephony/ims/ImsExternalCallState.java
index f2d0cbf..a58f361 100644
--- a/telephony/java/android/telephony/ims/ImsExternalCallState.java
+++ b/telephony/java/android/telephony/ims/ImsExternalCallState.java
@@ -167,7 +167,7 @@
         Rlog.d(TAG, "ImsExternalCallState writeToParcel = " + out.toString());
     }
 
-    public static final Parcelable.Creator<ImsExternalCallState> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<ImsExternalCallState> CREATOR =
             new Parcelable.Creator<ImsExternalCallState>() {
         @Override
         public ImsExternalCallState createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/ImsMmTelManager.java b/telephony/java/android/telephony/ims/ImsMmTelManager.java
index eb99d5d..bb85be1 100644
--- a/telephony/java/android/telephony/ims/ImsMmTelManager.java
+++ b/telephony/java/android/telephony/ims/ImsMmTelManager.java
@@ -139,7 +139,7 @@
                 if (mLocalCallback == null) return;
 
                 Binder.withCleanCallingIdentity(() ->
-                        mExecutor.execute(() -> mLocalCallback.onDeregistered(info)));
+                        mExecutor.execute(() -> mLocalCallback.onUnregistered(info)));
             }
 
             @Override
@@ -199,7 +199,7 @@
          *
          * @param info the {@link ImsReasonInfo} associated with why registration was disconnected.
          */
-        public void onDeregistered(ImsReasonInfo info) {
+        public void onUnregistered(ImsReasonInfo info) {
         }
 
         /**
@@ -485,7 +485,7 @@
      * @see android.telephony.CarrierConfigManager#KEY_HIDE_ENHANCED_4G_LTE_BOOL
      * @see android.telephony.CarrierConfigManager#KEY_ENHANCED_4G_LTE_ON_BY_DEFAULT_BOOL
      * @see android.telephony.CarrierConfigManager#KEY_CARRIER_VOLTE_AVAILABLE_BOOL
-     * @see #setAdvancedCallingSetting(boolean)
+     * @see #setAdvancedCallingSettingEnabled(boolean)
      * @return true if the user's setting for advanced calling is enabled, false otherwise.
      */
     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
@@ -519,9 +519,9 @@
      * @see #isAdvancedCallingSettingEnabled()
      */
     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
-    public void setAdvancedCallingSetting(boolean isEnabled) {
+    public void setAdvancedCallingSettingEnabled(boolean isEnabled) {
         try {
-            getITelephony().setAdvancedCallingSetting(mSubId, isEnabled);
+            getITelephony().setAdvancedCallingSettingEnabled(mSubId, isEnabled);
             return;
         } catch (RemoteException e) {
             throw e.rethrowAsRuntimeException();
@@ -589,7 +589,7 @@
     /**
      * The user's setting for whether or not they have enabled the "Video Calling" setting.
      * @return true if the user’s “Video Calling” setting is currently enabled.
-     * @see #setVtSetting(boolean)
+     * @see #setVtSettingEnabled(boolean)
      */
     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
     public boolean isVtSettingEnabled() {
@@ -605,9 +605,9 @@
      * @see #isVtSettingEnabled()
      */
     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
-    public void setVtSetting(boolean isEnabled) {
+    public void setVtSettingEnabled(boolean isEnabled) {
         try {
-            getITelephony().setVtSetting(mSubId, isEnabled);
+            getITelephony().setVtSettingEnabled(mSubId, isEnabled);
             return;
         } catch (RemoteException e) {
             throw e.rethrowAsRuntimeException();
@@ -616,7 +616,7 @@
 
     /**
      * @return true if the user's setting for Voice over WiFi is enabled and false if it is not.
-     * @see #setVoWiFiSetting(boolean)
+     * @see #setVoWiFiSettingEnabled(boolean)
      */
     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
     public boolean isVoWiFiSettingEnabled() {
@@ -633,9 +633,9 @@
      * @see #isVoWiFiSettingEnabled()
      */
     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
-    public void setVoWiFiSetting(boolean isEnabled) {
+    public void setVoWiFiSettingEnabled(boolean isEnabled) {
         try {
-            getITelephony().setVoWiFiSetting(mSubId, isEnabled);
+            getITelephony().setVoWiFiSettingEnabled(mSubId, isEnabled);
             return;
         } catch (RemoteException e) {
             throw e.rethrowAsRuntimeException();
@@ -645,7 +645,7 @@
     /**
      * @return true if the user's setting for Voice over WiFi while roaming is enabled, false
      * if disabled.
-     * @see #setVoWiFiRoamingSetting(boolean)
+     * @see #setVoWiFiRoamingSettingEnabled(boolean)
      */
     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
     public boolean isVoWiFiRoamingSettingEnabled() {
@@ -663,9 +663,9 @@
      * @see #isVoWiFiRoamingSettingEnabled()
      */
     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
-    public void setVoWiFiRoamingSetting(boolean isEnabled) {
+    public void setVoWiFiRoamingSettingEnabled(boolean isEnabled) {
         try {
-            getITelephony().setVoWiFiRoamingSetting(mSubId, isEnabled);
+            getITelephony().setVoWiFiRoamingSettingEnabled(mSubId, isEnabled);
             return;
         } catch (RemoteException e) {
             throw e.rethrowAsRuntimeException();
@@ -682,7 +682,7 @@
      * - {@link #WIFI_MODE_WIFI_ONLY}
      * - {@link #WIFI_MODE_CELLULAR_PREFERRED}
      * - {@link #WIFI_MODE_WIFI_PREFERRED}
-     * @see #setVoWiFiSetting(boolean)
+     * @see #setVoWiFiSettingEnabled(boolean)
      */
     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
     public void setVoWiFiNonPersistent(boolean isCapable, int mode) {
@@ -700,7 +700,7 @@
      * - {@link #WIFI_MODE_WIFI_ONLY}
      * - {@link #WIFI_MODE_CELLULAR_PREFERRED}
      * - {@link #WIFI_MODE_WIFI_PREFERRED}
-     * @see #setVoWiFiSetting(boolean)
+     * @see #setVoWiFiSettingEnabled(boolean)
      */
     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
     public @WiFiCallingMode int getVoWiFiModeSetting() {
@@ -739,7 +739,7 @@
      *     - {@link #WIFI_MODE_WIFI_ONLY}
      *     - {@link #WIFI_MODE_CELLULAR_PREFERRED}
      *     - {@link #WIFI_MODE_WIFI_PREFERRED}
-     * @see #setVoWiFiRoamingSetting(boolean)
+     * @see #setVoWiFiRoamingSettingEnabled(boolean)
      */
     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
     public @WiFiCallingMode int getVoWiFiRoamingModeSetting() {
diff --git a/telephony/java/android/telephony/ims/ImsReasonInfo.java b/telephony/java/android/telephony/ims/ImsReasonInfo.java
index d8d2d9e..b018491 100644
--- a/telephony/java/android/telephony/ims/ImsReasonInfo.java
+++ b/telephony/java/android/telephony/ims/ImsReasonInfo.java
@@ -1181,7 +1181,7 @@
         out.writeString(mExtraMessage);
     }
 
-    public static final Creator<ImsReasonInfo> CREATOR = new Creator<ImsReasonInfo>() {
+    public static final @android.annotation.NonNull Creator<ImsReasonInfo> CREATOR = new Creator<ImsReasonInfo>() {
         @Override
         public ImsReasonInfo createFromParcel(Parcel in) {
             return new ImsReasonInfo(in);
diff --git a/telephony/java/android/telephony/ims/ImsSsData.java b/telephony/java/android/telephony/ims/ImsSsData.java
index 3a82517..10001bc 100644
--- a/telephony/java/android/telephony/ims/ImsSsData.java
+++ b/telephony/java/android/telephony/ims/ImsSsData.java
@@ -364,7 +364,7 @@
         mImsSsInfo = (ImsSsInfo[])in.readParcelableArray(this.getClass().getClassLoader());
     }
 
-    public static final Creator<ImsSsData> CREATOR = new Creator<ImsSsData>() {
+    public static final @android.annotation.NonNull Creator<ImsSsData> CREATOR = new Creator<ImsSsData>() {
         @Override
         public ImsSsData createFromParcel(Parcel in) {
             return new ImsSsData(in);
diff --git a/telephony/java/android/telephony/ims/ImsSsInfo.java b/telephony/java/android/telephony/ims/ImsSsInfo.java
index 031f9e1..303a9fe 100644
--- a/telephony/java/android/telephony/ims/ImsSsInfo.java
+++ b/telephony/java/android/telephony/ims/ImsSsInfo.java
@@ -275,7 +275,7 @@
         mProvisionStatus = in.readInt();
     }
 
-    public static final Creator<ImsSsInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<ImsSsInfo> CREATOR =
             new Creator<ImsSsInfo>() {
         @Override
         public ImsSsInfo createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/ImsStreamMediaProfile.java b/telephony/java/android/telephony/ims/ImsStreamMediaProfile.java
index 837ef54..fd75a6b 100644
--- a/telephony/java/android/telephony/ims/ImsStreamMediaProfile.java
+++ b/telephony/java/android/telephony/ims/ImsStreamMediaProfile.java
@@ -99,7 +99,7 @@
     public int mRttMode;
     // RTT Audio Speech Indicator
     /** @hide */
-    public boolean mHasRttAudioSpeech = false;
+    public boolean mIsReceivingRttAudio = false;
 
     /** @hide */
     public ImsStreamMediaProfile(Parcel in) {
@@ -201,7 +201,7 @@
                 ", videoQuality=" + mVideoQuality +
                 ", videoDirection=" + mVideoDirection +
                 ", rttMode=" + mRttMode +
-                ", hasRttAudioSpeech=" + mHasRttAudioSpeech + " }";
+                ", hasRttAudioSpeech=" + mIsReceivingRttAudio + " }";
     }
 
     @Override
@@ -216,7 +216,7 @@
         out.writeInt(mVideoQuality);
         out.writeInt(mVideoDirection);
         out.writeInt(mRttMode);
-        out.writeBoolean(mHasRttAudioSpeech);
+        out.writeBoolean(mIsReceivingRttAudio);
     }
 
     private void readFromParcel(Parcel in) {
@@ -225,10 +225,10 @@
         mVideoQuality = in.readInt();
         mVideoDirection = in.readInt();
         mRttMode = in.readInt();
-        mHasRttAudioSpeech = in.readBoolean();
+        mIsReceivingRttAudio = in.readBoolean();
     }
 
-    public static final Creator<ImsStreamMediaProfile> CREATOR =
+    public static final @android.annotation.NonNull Creator<ImsStreamMediaProfile> CREATOR =
             new Creator<ImsStreamMediaProfile>() {
         @Override
         public ImsStreamMediaProfile createFromParcel(Parcel in) {
@@ -256,8 +256,12 @@
         mRttMode = rttMode;
     }
 
-    public void setRttAudioSpeech(boolean audioOn) {
-        mHasRttAudioSpeech = audioOn;
+    /**
+     * Sets whether the remote party is transmitting audio over the RTT call.
+     * @param audioOn true if audio is being received, false otherwise.
+     */
+    public void setReceivingRttAudio(boolean audioOn) {
+        mIsReceivingRttAudio = audioOn;
     }
 
     public int getAudioQuality() {
@@ -280,7 +284,10 @@
         return mRttMode;
     }
 
-    public boolean getRttAudioSpeech() {
-        return mHasRttAudioSpeech;
+    /**
+     * @return true if remote party is transmitting audio, false otherwise.
+     */
+    public boolean isReceivingRttAudio() {
+        return mIsReceivingRttAudio;
     }
 }
diff --git a/telephony/java/android/telephony/ims/ImsSuppServiceNotification.java b/telephony/java/android/telephony/ims/ImsSuppServiceNotification.java
index efaade8..2e4288d 100644
--- a/telephony/java/android/telephony/ims/ImsSuppServiceNotification.java
+++ b/telephony/java/android/telephony/ims/ImsSuppServiceNotification.java
@@ -93,7 +93,7 @@
         out.writeStringArray(history);
     }
 
-    public static final Creator<ImsSuppServiceNotification> CREATOR =
+    public static final @android.annotation.NonNull Creator<ImsSuppServiceNotification> CREATOR =
             new Creator<ImsSuppServiceNotification>() {
         @Override
         public ImsSuppServiceNotification createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/Rcs1To1Thread.java b/telephony/java/android/telephony/ims/Rcs1To1Thread.java
index d4a78ff..0bb1b43 100644
--- a/telephony/java/android/telephony/ims/Rcs1To1Thread.java
+++ b/telephony/java/android/telephony/ims/Rcs1To1Thread.java
@@ -22,6 +22,8 @@
  * Rcs1To1Thread represents a single RCS conversation thread with a total of two
  * {@link RcsParticipant}s. Please see Section 5 (1-to-1 Messaging) - GSMA RCC.71 (RCS Universal
  * Profile Service Definition Document)
+ *
+ * @hide
  */
 public class Rcs1To1Thread extends RcsThread {
     private int mThreadId;
diff --git a/telephony/java/android/telephony/ims/RcsEvent.java b/telephony/java/android/telephony/ims/RcsEvent.java
index a547c5c0..994b27a 100644
--- a/telephony/java/android/telephony/ims/RcsEvent.java
+++ b/telephony/java/android/telephony/ims/RcsEvent.java
@@ -17,6 +17,8 @@
 
 /**
  * The base class for events that can happen on {@link RcsParticipant}s and {@link RcsThread}s.
+ *
+ * @hide
  */
 public abstract class RcsEvent {
     private final long mTimestamp;
diff --git a/telephony/java/android/telephony/ims/RcsEventQueryParams.java b/telephony/java/android/telephony/ims/RcsEventQueryParams.java
index 9dbfe43..0024cf7 100644
--- a/telephony/java/android/telephony/ims/RcsEventQueryParams.java
+++ b/telephony/java/android/telephony/ims/RcsEventQueryParams.java
@@ -37,6 +37,8 @@
  * The parameters to pass into
  * {@link RcsMessageStore#getRcsEvents(RcsEventQueryParams)} in order to select a
  * subset of {@link RcsEvent}s present in the message store.
+ *
+ * @hide
  */
 public final class RcsEventQueryParams implements Parcelable {
     /**
@@ -290,7 +292,7 @@
         mLimit = in.readInt();
     }
 
-    public static final Creator<RcsEventQueryParams> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsEventQueryParams> CREATOR =
             new Creator<RcsEventQueryParams>() {
                 @Override
                 public RcsEventQueryParams createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsEventQueryResult.java b/telephony/java/android/telephony/ims/RcsEventQueryResult.java
index 92bda81..d6347e3 100644
--- a/telephony/java/android/telephony/ims/RcsEventQueryResult.java
+++ b/telephony/java/android/telephony/ims/RcsEventQueryResult.java
@@ -22,6 +22,8 @@
  * The result of a {@link RcsMessageStore#getRcsEvents(RcsEventQueryParams)}
  * call. This class allows getting the token for querying the next batch of events in order to
  * prevent handling large amounts of data at once.
+ *
+ * @hide
  */
 public class RcsEventQueryResult {
     private RcsQueryContinuationToken mContinuationToken;
diff --git a/telephony/java/android/telephony/ims/RcsEventQueryResultDescriptor.java b/telephony/java/android/telephony/ims/RcsEventQueryResultDescriptor.java
index bba56d3..e30745b7 100644
--- a/telephony/java/android/telephony/ims/RcsEventQueryResultDescriptor.java
+++ b/telephony/java/android/telephony/ims/RcsEventQueryResultDescriptor.java
@@ -53,7 +53,7 @@
         in.readList(mEvents, null);
     }
 
-    public static final Creator<RcsEventQueryResultDescriptor> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsEventQueryResultDescriptor> CREATOR =
             new Creator<RcsEventQueryResultDescriptor>() {
         @Override
         public RcsEventQueryResultDescriptor createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsFileTransferCreationParams.java b/telephony/java/android/telephony/ims/RcsFileTransferCreationParams.java
index 14af8ea..e43552d 100644
--- a/telephony/java/android/telephony/ims/RcsFileTransferCreationParams.java
+++ b/telephony/java/android/telephony/ims/RcsFileTransferCreationParams.java
@@ -24,6 +24,8 @@
  * Pass an instance of this class to
  * {@link RcsMessage#insertFileTransfer(RcsFileTransferCreationParams)} create an
  * {@link RcsFileTransferPart} and save it into storage.
+ *
+ * @hide
  */
 public final class RcsFileTransferCreationParams implements Parcelable {
     private String mRcsFileTransferSessionId;
@@ -323,7 +325,7 @@
         mFileTransferStatus = in.readInt();
     }
 
-    public static final Creator<RcsFileTransferCreationParams> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsFileTransferCreationParams> CREATOR =
             new Creator<RcsFileTransferCreationParams>() {
                 @Override
                 public RcsFileTransferCreationParams createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsFileTransferPart.java b/telephony/java/android/telephony/ims/RcsFileTransferPart.java
index 9531c2e..3816cd4 100644
--- a/telephony/java/android/telephony/ims/RcsFileTransferPart.java
+++ b/telephony/java/android/telephony/ims/RcsFileTransferPart.java
@@ -26,6 +26,8 @@
 /**
  * A part of a composite {@link RcsMessage} that holds a file transfer. Please see Section 7
  * (File Transfer) - GSMA RCC.71 (RCS Universal Profile Service Definition Document)
+ *
+ * @hide
  */
 public class RcsFileTransferPart {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsGroupThread.java b/telephony/java/android/telephony/ims/RcsGroupThread.java
index 6e17bc2..8cd633b 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThread.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThread.java
@@ -29,6 +29,8 @@
  * RcsGroupThread represents a single RCS conversation thread where {@link RcsParticipant}s can join
  * or leave. Please see Section 6 (Group Chat) - GSMA RCC.71 (RCS Universal Profile Service
  * Definition Document)
+ *
+ * @hide
  */
 public class RcsGroupThread extends RcsThread {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadEvent.java
index 99086aa..4a6b963 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadEvent.java
@@ -19,6 +19,8 @@
 
 /**
  * An event that happened on an {@link RcsGroupThread}.
+ *
+ * @hide
  */
 public abstract class RcsGroupThreadEvent extends RcsEvent {
     private final int mRcsGroupThreadId;
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEvent.java
index cbd762d..3c6c74f 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEvent.java
@@ -22,6 +22,8 @@
 /**
  * An event that indicates an {@link RcsGroupThread}'s icon was changed. Please see R6-2-5 - GSMA
  * RCC.71 (RCS Universal Profile Service Definition Document)
+ *
+ * @hide
  */
 public final class RcsGroupThreadIconChangedEvent extends RcsGroupThreadEvent {
     private final Uri mNewIcon;
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEventDescriptor.java b/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEventDescriptor.java
index b7fe4b2..1fb8798 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEventDescriptor.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEventDescriptor.java
@@ -42,7 +42,7 @@
                 new RcsParticipant(mOriginatingParticipantId), mNewIcon);
     }
 
-    public static final Creator<RcsGroupThreadIconChangedEventDescriptor> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsGroupThreadIconChangedEventDescriptor> CREATOR =
             new Creator<RcsGroupThreadIconChangedEventDescriptor>() {
                 @Override
                 public RcsGroupThreadIconChangedEventDescriptor createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEvent.java
index a2a4fab..5403253 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEvent.java
@@ -21,6 +21,8 @@
 /**
  * An event that indicates an {@link RcsGroupThread}'s name was changed. Please see R6-2-5 - GSMA
  * RCC.71 (RCS Universal Profile Service Definition Document)
+ *
+ * @hide
  */
 public final class RcsGroupThreadNameChangedEvent extends RcsGroupThreadEvent {
     private final String mNewName;
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEventDescriptor.java b/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEventDescriptor.java
index 4ec641f..980aba2 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEventDescriptor.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEventDescriptor.java
@@ -44,7 +44,7 @@
                 mNewName);
     }
 
-    public static final Creator<RcsGroupThreadNameChangedEventDescriptor> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsGroupThreadNameChangedEventDescriptor> CREATOR =
             new Creator<RcsGroupThreadNameChangedEventDescriptor>() {
                 @Override
                 public RcsGroupThreadNameChangedEventDescriptor createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEvent.java
index 183cd9a..48be479 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEvent.java
@@ -20,6 +20,8 @@
 /**
  * An event that indicates an RCS participant has joined an {@link RcsThread}. Please see US6-3 -
  * GSMA RCC.71 (RCS Universal Profile Service Definition Document)
+ *
+ * @hide
  */
 public final class RcsGroupThreadParticipantJoinedEvent extends RcsGroupThreadEvent {
     private final RcsParticipant mJoinedParticipantId;
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEventDescriptor.java b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEventDescriptor.java
index a4218c2..e899e1c 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEventDescriptor.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEventDescriptor.java
@@ -43,7 +43,7 @@
                 new RcsParticipant(mJoinedParticipantId));
     }
 
-    public static final Creator<RcsGroupThreadParticipantJoinedEventDescriptor> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsGroupThreadParticipantJoinedEventDescriptor> CREATOR =
             new Creator<RcsGroupThreadParticipantJoinedEventDescriptor>() {
                 @Override
                 public RcsGroupThreadParticipantJoinedEventDescriptor createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEvent.java
index c12549b..b724a3f 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEvent.java
@@ -20,6 +20,8 @@
 /**
  * An event that indicates an RCS participant has left an {@link RcsThread}. Please see US6-23 -
  * GSMA RCC.71 (RCS Universal Profile Service Definition Document)
+ *
+ * @hide
  */
 public final class RcsGroupThreadParticipantLeftEvent extends RcsGroupThreadEvent {
     private RcsParticipant mLeavingParticipant;
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEventDescriptor.java b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEventDescriptor.java
index 8e91dda..8eefb4b 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEventDescriptor.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEventDescriptor.java
@@ -44,7 +44,7 @@
                 new RcsParticipant(mLeavingParticipantId));
     }
 
-    public static final Parcelable.Creator<RcsGroupThreadParticipantLeftEventDescriptor> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<RcsGroupThreadParticipantLeftEventDescriptor> CREATOR =
             new Creator<RcsGroupThreadParticipantLeftEventDescriptor>() {
                 @Override
                 public RcsGroupThreadParticipantLeftEventDescriptor createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsIncomingMessage.java b/telephony/java/android/telephony/ims/RcsIncomingMessage.java
index 61911ab..06e2a41 100644
--- a/telephony/java/android/telephony/ims/RcsIncomingMessage.java
+++ b/telephony/java/android/telephony/ims/RcsIncomingMessage.java
@@ -19,6 +19,8 @@
 
 /**
  * This is a single instance of a message received over RCS.
+ *
+ * @hide
  */
 public class RcsIncomingMessage extends RcsMessage {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsIncomingMessageCreationParams.java b/telephony/java/android/telephony/ims/RcsIncomingMessageCreationParams.java
index 61dedbc..955f263 100644
--- a/telephony/java/android/telephony/ims/RcsIncomingMessageCreationParams.java
+++ b/telephony/java/android/telephony/ims/RcsIncomingMessageCreationParams.java
@@ -24,6 +24,8 @@
  * {@link RcsIncomingMessageCreationParams} is a collection of parameters that should be passed
  * into {@link RcsThread#addIncomingMessage(RcsIncomingMessageCreationParams)} to generate an
  * {@link RcsIncomingMessage} on that {@link RcsThread}
+ *
+ * @hide
  */
 public final class RcsIncomingMessageCreationParams extends RcsMessageCreationParams implements
         Parcelable {
@@ -150,7 +152,7 @@
         return mSenderParticipantId;
     }
 
-    public static final Creator<RcsIncomingMessageCreationParams> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsIncomingMessageCreationParams> CREATOR =
             new Creator<RcsIncomingMessageCreationParams>() {
                 @Override
                 public RcsIncomingMessageCreationParams createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsManager.java b/telephony/java/android/telephony/ims/RcsManager.java
index 22e4b22..63dc1ac 100644
--- a/telephony/java/android/telephony/ims/RcsManager.java
+++ b/telephony/java/android/telephony/ims/RcsManager.java
@@ -20,6 +20,8 @@
 
 /**
  * The manager class for RCS related utilities.
+ *
+ * @hide
  */
 @SystemService(Context.TELEPHONY_RCS_SERVICE)
 public class RcsManager {
diff --git a/telephony/java/android/telephony/ims/RcsMessage.java b/telephony/java/android/telephony/ims/RcsMessage.java
index 3227413..b0d0d5a 100644
--- a/telephony/java/android/telephony/ims/RcsMessage.java
+++ b/telephony/java/android/telephony/ims/RcsMessage.java
@@ -27,6 +27,8 @@
 
 /**
  * This is a single instance of a message sent or received over RCS.
+ *
+ * @hide
  */
 public abstract class RcsMessage {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsMessageCreationParams.java b/telephony/java/android/telephony/ims/RcsMessageCreationParams.java
index c46c605..f0eea88 100644
--- a/telephony/java/android/telephony/ims/RcsMessageCreationParams.java
+++ b/telephony/java/android/telephony/ims/RcsMessageCreationParams.java
@@ -27,6 +27,8 @@
  * {@link RcsThread#addIncomingMessage(RcsIncomingMessageCreationParams)} and
  * {@link RcsThread#addOutgoingMessage(RcsOutgoingMessageCreationParams)} to create and persist
  * {@link RcsMessage}s on an {@link RcsThread}
+ *
+ * @hide
  */
 public class RcsMessageCreationParams {
     // The globally unique id of the RcsMessage to be created.
diff --git a/telephony/java/android/telephony/ims/RcsMessageQueryParams.java b/telephony/java/android/telephony/ims/RcsMessageQueryParams.java
index 535a597..9f9eafb 100644
--- a/telephony/java/android/telephony/ims/RcsMessageQueryParams.java
+++ b/telephony/java/android/telephony/ims/RcsMessageQueryParams.java
@@ -31,6 +31,8 @@
  * The parameters to pass into
  * {@link RcsMessageStore#getRcsMessages(RcsMessageQueryParams)} in order to select a
  * subset of {@link RcsMessage}s present in the message store.
+ *
+ * @hide
  */
 public final class RcsMessageQueryParams implements Parcelable {
     /**
@@ -328,7 +330,7 @@
         mThreadId = in.readInt();
     }
 
-    public static final Creator<RcsMessageQueryParams> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsMessageQueryParams> CREATOR =
             new Creator<RcsMessageQueryParams>() {
                 @Override
                 public RcsMessageQueryParams createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsMessageQueryResult.java b/telephony/java/android/telephony/ims/RcsMessageQueryResult.java
index 3514b48..5df929b 100644
--- a/telephony/java/android/telephony/ims/RcsMessageQueryResult.java
+++ b/telephony/java/android/telephony/ims/RcsMessageQueryResult.java
@@ -32,6 +32,8 @@
  * The result of a {@link RcsMessageStore#getRcsMessages(RcsMessageQueryParams)}
  * call. This class allows getting the token for querying the next batch of messages in order to
  * prevent handling large amounts of data at once.
+ *
+ * @hide
  */
 public final class RcsMessageQueryResult implements Parcelable {
     // The token to continue the query to get the next batch of results
@@ -87,7 +89,7 @@
         in.readTypedList(mMessageTypeIdPairs, RcsTypeIdPair.CREATOR);
     }
 
-    public static final Creator<RcsMessageQueryResult> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsMessageQueryResult> CREATOR =
             new Creator<RcsMessageQueryResult>() {
                 @Override
                 public RcsMessageQueryResult createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsMessageSnippet.java b/telephony/java/android/telephony/ims/RcsMessageSnippet.java
index b0b930c..8103160 100644
--- a/telephony/java/android/telephony/ims/RcsMessageSnippet.java
+++ b/telephony/java/android/telephony/ims/RcsMessageSnippet.java
@@ -23,6 +23,8 @@
 
 /**
  * An immutable summary of the latest {@link RcsMessage} on an {@link RcsThread}
+ *
+ * @hide
  */
 public final class RcsMessageSnippet implements Parcelable {
     private final String mText;
@@ -69,7 +71,7 @@
         mTimestamp = in.readLong();
     }
 
-    public static final Creator<RcsMessageSnippet> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsMessageSnippet> CREATOR =
             new Creator<RcsMessageSnippet>() {
                 @Override
                 public RcsMessageSnippet createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsMessageStore.java b/telephony/java/android/telephony/ims/RcsMessageStore.java
index 31f2983..3111652 100644
--- a/telephony/java/android/telephony/ims/RcsMessageStore.java
+++ b/telephony/java/android/telephony/ims/RcsMessageStore.java
@@ -26,6 +26,8 @@
 /**
  * RcsMessageStore is the application interface to RcsProvider and provides access methods to
  * RCS related database tables.
+ *
+ * @hide
  */
 public class RcsMessageStore {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsMessageStoreException.java b/telephony/java/android/telephony/ims/RcsMessageStoreException.java
index f25bb17..3b3fcf2 100644
--- a/telephony/java/android/telephony/ims/RcsMessageStoreException.java
+++ b/telephony/java/android/telephony/ims/RcsMessageStoreException.java
@@ -19,6 +19,8 @@
 /**
  * An exception that happened on {@link RcsMessageStore} or one of the derived storage classes in
  * {@link android.telephony.ims}
+ *
+ * @hide
  */
 public class RcsMessageStoreException extends Exception {
 
diff --git a/telephony/java/android/telephony/ims/RcsOutgoingMessage.java b/telephony/java/android/telephony/ims/RcsOutgoingMessage.java
index 06fb832..1b4bfe5 100644
--- a/telephony/java/android/telephony/ims/RcsOutgoingMessage.java
+++ b/telephony/java/android/telephony/ims/RcsOutgoingMessage.java
@@ -23,6 +23,8 @@
 
 /**
  * This is a single instance of a message sent over RCS.
+ *
+ * @hide
  */
 public class RcsOutgoingMessage extends RcsMessage {
     RcsOutgoingMessage(int id) {
diff --git a/telephony/java/android/telephony/ims/RcsOutgoingMessageCreationParams.java b/telephony/java/android/telephony/ims/RcsOutgoingMessageCreationParams.java
index 979634a..22fd8a5 100644
--- a/telephony/java/android/telephony/ims/RcsOutgoingMessageCreationParams.java
+++ b/telephony/java/android/telephony/ims/RcsOutgoingMessageCreationParams.java
@@ -23,6 +23,8 @@
  * {@link RcsOutgoingMessageCreationParams} is a collection of parameters that should be passed
  * into {@link RcsThread#addOutgoingMessage(RcsOutgoingMessageCreationParams)} to generate an
  * {@link RcsOutgoingMessage} on that {@link RcsThread}
+ *
+ * @hide
  */
 public final class RcsOutgoingMessageCreationParams extends RcsMessageCreationParams
         implements Parcelable {
@@ -62,7 +64,7 @@
         super(in);
     }
 
-    public static final Creator<RcsOutgoingMessageCreationParams> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsOutgoingMessageCreationParams> CREATOR =
             new Creator<RcsOutgoingMessageCreationParams>() {
                 @Override
                 public RcsOutgoingMessageCreationParams createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsOutgoingMessageDelivery.java b/telephony/java/android/telephony/ims/RcsOutgoingMessageDelivery.java
index 1c87b13..2db49c6 100644
--- a/telephony/java/android/telephony/ims/RcsOutgoingMessageDelivery.java
+++ b/telephony/java/android/telephony/ims/RcsOutgoingMessageDelivery.java
@@ -21,6 +21,8 @@
 /**
  * This class holds the delivery information of an {@link RcsOutgoingMessage} for each
  * {@link RcsParticipant} that the message was intended for.
+ *
+ * @hide
  */
 public class RcsOutgoingMessageDelivery {
     // The participant that this delivery is intended for
diff --git a/telephony/java/android/telephony/ims/RcsParticipant.java b/telephony/java/android/telephony/ims/RcsParticipant.java
index 7ba5d8e..bcf134a 100644
--- a/telephony/java/android/telephony/ims/RcsParticipant.java
+++ b/telephony/java/android/telephony/ims/RcsParticipant.java
@@ -20,6 +20,8 @@
 
 /**
  * RcsParticipant is an RCS capable contact that can participate in {@link RcsThread}s.
+ *
+ * @hide
  */
 public class RcsParticipant {
     // The row ID of this participant in the database
diff --git a/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEvent.java b/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEvent.java
index cc2613f..61801f3 100644
--- a/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEvent.java
+++ b/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEvent.java
@@ -21,6 +21,8 @@
 /**
  * An event that indicates an {@link RcsParticipant}'s alias was changed. Please see US18-2 - GSMA
  * RCC.71 (RCS Universal Profile Service Definition Document)
+ *
+ * @hide
  */
 public final class RcsParticipantAliasChangedEvent extends RcsEvent {
     // The participant that changed their alias
diff --git a/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEventDescriptor.java b/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEventDescriptor.java
index a32e552..aad9fb3 100644
--- a/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEventDescriptor.java
+++ b/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEventDescriptor.java
@@ -45,7 +45,7 @@
                 mTimestamp, new RcsParticipant(mParticipantId), mNewAlias);
     }
 
-    public static final Creator<RcsParticipantAliasChangedEventDescriptor> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsParticipantAliasChangedEventDescriptor> CREATOR =
             new Creator<RcsParticipantAliasChangedEventDescriptor>() {
                 @Override
                 public RcsParticipantAliasChangedEventDescriptor createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsParticipantQueryParams.java b/telephony/java/android/telephony/ims/RcsParticipantQueryParams.java
index d24d079..21107a2 100644
--- a/telephony/java/android/telephony/ims/RcsParticipantQueryParams.java
+++ b/telephony/java/android/telephony/ims/RcsParticipantQueryParams.java
@@ -30,6 +30,8 @@
  * The parameters to pass into
  * {@link RcsMessageStore#getRcsParticipants(RcsParticipantQueryParams)} in order to select a
  * subset of {@link RcsThread}s present in the message store.
+ *
+ * @hide
  */
 public final class RcsParticipantQueryParams implements Parcelable {
     /**
@@ -277,7 +279,7 @@
         mThreadId = in.readInt();
     }
 
-    public static final Creator<RcsParticipantQueryParams> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsParticipantQueryParams> CREATOR =
             new Creator<RcsParticipantQueryParams>() {
                 @Override
                 public RcsParticipantQueryParams createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsParticipantQueryResult.java b/telephony/java/android/telephony/ims/RcsParticipantQueryResult.java
index 505f1a5..3e5c231 100644
--- a/telephony/java/android/telephony/ims/RcsParticipantQueryResult.java
+++ b/telephony/java/android/telephony/ims/RcsParticipantQueryResult.java
@@ -28,6 +28,8 @@
  * The result of a {@link RcsMessageStore#getRcsParticipants(RcsParticipantQueryParams)}
  * call. This class allows getting the token for querying the next batch of participants in order to
  * prevent handling large amounts of data at once.
+ *
+ * @hide
  */
 public final class RcsParticipantQueryResult implements Parcelable {
     // A token for the caller to continue their query for the next batch of results
@@ -78,7 +80,7 @@
                 RcsQueryContinuationToken.class.getClassLoader());
     }
 
-    public static final Creator<RcsParticipantQueryResult> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsParticipantQueryResult> CREATOR =
             new Creator<RcsParticipantQueryResult>() {
                 @Override
                 public RcsParticipantQueryResult createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsQueryContinuationToken.java b/telephony/java/android/telephony/ims/RcsQueryContinuationToken.java
index 08643de..982263a 100644
--- a/telephony/java/android/telephony/ims/RcsQueryContinuationToken.java
+++ b/telephony/java/android/telephony/ims/RcsQueryContinuationToken.java
@@ -31,6 +31,8 @@
  * @see RcsMessageQueryResult#getContinuationToken()
  * @see RcsParticipantQueryResult#getContinuationToken()
  * @see RcsThreadQueryResult#getContinuationToken()
+ *
+ * @hide
  */
 public final class RcsQueryContinuationToken implements Parcelable {
     /**
@@ -127,7 +129,7 @@
         mOffset = in.readInt();
     }
 
-    public static final Creator<RcsQueryContinuationToken> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsQueryContinuationToken> CREATOR =
             new Creator<RcsQueryContinuationToken>() {
                 @Override
                 public RcsQueryContinuationToken createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsThread.java b/telephony/java/android/telephony/ims/RcsThread.java
index e015dd3..cf1dc76 100644
--- a/telephony/java/android/telephony/ims/RcsThread.java
+++ b/telephony/java/android/telephony/ims/RcsThread.java
@@ -27,6 +27,8 @@
 /**
  * RcsThread represents a single RCS conversation thread. It holds messages that were sent and
  * received and events that occurred on that thread.
+ *
+ * @hide
  */
 public abstract class RcsThread {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsThreadQueryParams.java b/telephony/java/android/telephony/ims/RcsThreadQueryParams.java
index 05a5a39..da7cdb0 100644
--- a/telephony/java/android/telephony/ims/RcsThreadQueryParams.java
+++ b/telephony/java/android/telephony/ims/RcsThreadQueryParams.java
@@ -35,6 +35,8 @@
 /**
  * The parameters to pass into {@link RcsMessageStore#getRcsThreads(RcsThreadQueryParams)} in
  * order to select a subset of {@link RcsThread}s present in the message store.
+ *
+ * @hide
  */
 public final class RcsThreadQueryParams implements Parcelable {
     /**
@@ -274,7 +276,7 @@
         mIsAscending = in.readByte() == 1;
     }
 
-    public static final Creator<RcsThreadQueryParams> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsThreadQueryParams> CREATOR =
             new Creator<RcsThreadQueryParams>() {
                 @Override
                 public RcsThreadQueryParams createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/RcsThreadQueryResult.java b/telephony/java/android/telephony/ims/RcsThreadQueryResult.java
index 1cac61d..c2c2d3a 100644
--- a/telephony/java/android/telephony/ims/RcsThreadQueryResult.java
+++ b/telephony/java/android/telephony/ims/RcsThreadQueryResult.java
@@ -32,6 +32,8 @@
  * The result of a {@link RcsMessageStore#getRcsThreads(RcsThreadQueryParams)}
  * call. This class allows getting the token for querying the next batch of threads in order to
  * prevent handling large amounts of data at once.
+ *
+ * @hide
  */
 public final class RcsThreadQueryResult implements Parcelable {
     // A token for the caller to continue their query for the next batch of results
@@ -89,7 +91,7 @@
         in.readList(mRcsThreadIds, Integer.class.getClassLoader());
     }
 
-    public static final Creator<RcsThreadQueryResult> CREATOR =
+    public static final @android.annotation.NonNull Creator<RcsThreadQueryResult> CREATOR =
             new Creator<RcsThreadQueryResult>() {
                 @Override
                 public RcsThreadQueryResult createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/feature/CapabilityChangeRequest.java b/telephony/java/android/telephony/ims/feature/CapabilityChangeRequest.java
index 1ee8563..80fc09e 100644
--- a/telephony/java/android/telephony/ims/feature/CapabilityChangeRequest.java
+++ b/telephony/java/android/telephony/ims/feature/CapabilityChangeRequest.java
@@ -187,7 +187,7 @@
         }
     }
 
-    public static final Creator<CapabilityChangeRequest> CREATOR =
+    public static final @android.annotation.NonNull Creator<CapabilityChangeRequest> CREATOR =
             new Creator<CapabilityChangeRequest>() {
                 @Override
                 public CapabilityChangeRequest createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/ims/stub/ImsFeatureConfiguration.java b/telephony/java/android/telephony/ims/stub/ImsFeatureConfiguration.java
index dfb6e2c..6ab9465 100644
--- a/telephony/java/android/telephony/ims/stub/ImsFeatureConfiguration.java
+++ b/telephony/java/android/telephony/ims/stub/ImsFeatureConfiguration.java
@@ -165,7 +165,7 @@
         }
     }
 
-    public static final Creator<ImsFeatureConfiguration> CREATOR
+    public static final @android.annotation.NonNull Creator<ImsFeatureConfiguration> CREATOR
             = new Creator<ImsFeatureConfiguration>() {
         @Override
         public ImsFeatureConfiguration createFromParcel(Parcel in) {
diff --git a/telephony/java/android/telephony/mbms/DownloadRequest.java b/telephony/java/android/telephony/mbms/DownloadRequest.java
index 9e3302b..52b51d2 100644
--- a/telephony/java/android/telephony/mbms/DownloadRequest.java
+++ b/telephony/java/android/telephony/mbms/DownloadRequest.java
@@ -330,7 +330,7 @@
         return version;
     }
 
-    public static final Parcelable.Creator<DownloadRequest> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<DownloadRequest> CREATOR =
             new Parcelable.Creator<DownloadRequest>() {
         public DownloadRequest createFromParcel(Parcel in) {
             return new DownloadRequest(in);
diff --git a/telephony/java/android/telephony/mbms/FileInfo.java b/telephony/java/android/telephony/mbms/FileInfo.java
index e064adb..ada2872 100644
--- a/telephony/java/android/telephony/mbms/FileInfo.java
+++ b/telephony/java/android/telephony/mbms/FileInfo.java
@@ -33,7 +33,7 @@
 
     private final String mimeType;
 
-    public static final Parcelable.Creator<FileInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<FileInfo> CREATOR =
             new Parcelable.Creator<FileInfo>() {
         @Override
         public FileInfo createFromParcel(Parcel source) {
diff --git a/telephony/java/android/telephony/mbms/FileServiceInfo.java b/telephony/java/android/telephony/mbms/FileServiceInfo.java
index b30a3af..8c79ab6 100644
--- a/telephony/java/android/telephony/mbms/FileServiceInfo.java
+++ b/telephony/java/android/telephony/mbms/FileServiceInfo.java
@@ -44,7 +44,7 @@
         files = new ArrayList<>(newFiles);
     }
 
-    public static final Parcelable.Creator<FileServiceInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<FileServiceInfo> CREATOR =
             new Parcelable.Creator<FileServiceInfo>() {
         @Override
         public FileServiceInfo createFromParcel(Parcel source) {
diff --git a/telephony/java/android/telephony/mbms/StreamingServiceInfo.java b/telephony/java/android/telephony/mbms/StreamingServiceInfo.java
index ef2a14a..8ad1d89 100644
--- a/telephony/java/android/telephony/mbms/StreamingServiceInfo.java
+++ b/telephony/java/android/telephony/mbms/StreamingServiceInfo.java
@@ -48,7 +48,7 @@
         super(names, className, locales, serviceId, start, end);
     }
 
-    public static final Parcelable.Creator<StreamingServiceInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<StreamingServiceInfo> CREATOR =
             new Parcelable.Creator<StreamingServiceInfo>() {
         @Override
         public StreamingServiceInfo createFromParcel(Parcel source) {
diff --git a/telephony/java/android/telephony/mbms/UriPathPair.java b/telephony/java/android/telephony/mbms/UriPathPair.java
index dd20a69..f53d7e0 100644
--- a/telephony/java/android/telephony/mbms/UriPathPair.java
+++ b/telephony/java/android/telephony/mbms/UriPathPair.java
@@ -54,7 +54,7 @@
         mContentUri = in.readParcelable(Uri.class.getClassLoader());
     }
 
-    public static final Creator<UriPathPair> CREATOR = new Creator<UriPathPair>() {
+    public static final @android.annotation.NonNull Creator<UriPathPair> CREATOR = new Creator<UriPathPair>() {
         @Override
         public UriPathPair createFromParcel(Parcel in) {
             return new UriPathPair(in);
diff --git a/telephony/java/android/telephony/mbms/vendor/IMbmsStreamingService.aidl b/telephony/java/android/telephony/mbms/vendor/IMbmsStreamingService.aidl
index c90ffc7..c1401272 100755
--- a/telephony/java/android/telephony/mbms/vendor/IMbmsStreamingService.aidl
+++ b/telephony/java/android/telephony/mbms/vendor/IMbmsStreamingService.aidl
@@ -26,13 +26,17 @@
  */
 interface IMbmsStreamingService
 {
+    @UnsupportedAppUsage
     int initialize(IMbmsStreamingSessionCallback callback, int subId);
 
+    @UnsupportedAppUsage
     int requestUpdateStreamingServices(int subId, in List<String> serviceClasses);
 
+    @UnsupportedAppUsage
     int startStreaming(int subId, String serviceId,
             IStreamingServiceCallback callback);
 
+    @UnsupportedAppUsage
     Uri getPlaybackUri(int subId, String serviceId);
 
     void stopStreaming(int subId, String serviceId);
diff --git a/telephony/java/com/android/ims/ImsConfigListener.aidl b/telephony/java/com/android/ims/ImsConfigListener.aidl
index 64a5015..4f229df 100644
--- a/telephony/java/com/android/ims/ImsConfigListener.aidl
+++ b/telephony/java/com/android/ims/ImsConfigListener.aidl
@@ -47,6 +47,7 @@
      *
      * @return void.
      */
+    @UnsupportedAppUsage
     void onSetFeatureResponse(int feature, int network, int value, int status);
 
     /**
diff --git a/telephony/java/com/android/ims/internal/IImsCallSessionListener.aidl b/telephony/java/com/android/ims/internal/IImsCallSessionListener.aidl
index 579369f..b33a9f1 100644
--- a/telephony/java/com/android/ims/internal/IImsCallSessionListener.aidl
+++ b/telephony/java/com/android/ims/internal/IImsCallSessionListener.aidl
@@ -34,33 +34,47 @@
     /**
      * Notifies the result of the basic session operation (setup / terminate).
      */
+    @UnsupportedAppUsage
     void callSessionProgressing(in IImsCallSession session, in ImsStreamMediaProfile profile);
+    @UnsupportedAppUsage
     void callSessionStarted(in IImsCallSession session, in ImsCallProfile profile);
+    @UnsupportedAppUsage
     void callSessionStartFailed(in IImsCallSession session, in ImsReasonInfo reasonInfo);
+    @UnsupportedAppUsage
     void callSessionTerminated(in IImsCallSession session, in ImsReasonInfo reasonInfo);
 
     /**
      * Notifies the result of the call hold/resume operation.
      */
+    @UnsupportedAppUsage
     void callSessionHeld(in IImsCallSession session, in ImsCallProfile profile);
+    @UnsupportedAppUsage
     void callSessionHoldFailed(in IImsCallSession session, in ImsReasonInfo reasonInfo);
+    @UnsupportedAppUsage
     void callSessionHoldReceived(in IImsCallSession session, in ImsCallProfile profile);
+    @UnsupportedAppUsage
     void callSessionResumed(in IImsCallSession session, in ImsCallProfile profile);
+    @UnsupportedAppUsage
     void callSessionResumeFailed(in IImsCallSession session, in ImsReasonInfo reasonInfo);
+    @UnsupportedAppUsage
     void callSessionResumeReceived(in IImsCallSession session, in ImsCallProfile profile);
 
     /**
      * Notifies the result of call merge operation.
      */
+    @UnsupportedAppUsage
     void callSessionMergeStarted(in IImsCallSession session,
             in IImsCallSession newSession, in ImsCallProfile profile);
+    @UnsupportedAppUsage
     void callSessionMergeComplete(in IImsCallSession session);
+    @UnsupportedAppUsage
     void callSessionMergeFailed(in IImsCallSession session,
             in ImsReasonInfo reasonInfo);
 
     /**
      * Notifies the result of call upgrade / downgrade or any other call updates.
      */
+    @UnsupportedAppUsage
     void callSessionUpdated(in IImsCallSession session,
             in ImsCallProfile profile);
     void callSessionUpdateFailed(in IImsCallSession session,
@@ -81,7 +95,9 @@
     /**
      * Notifies the result of the participant invitation / removal to/from the conference session.
      */
+    @UnsupportedAppUsage
     void callSessionInviteParticipantsRequestDelivered(in IImsCallSession session);
+    @UnsupportedAppUsage
     void callSessionInviteParticipantsRequestFailed(in IImsCallSession session,
             in ImsReasonInfo reasonInfo);
     void callSessionRemoveParticipantsRequestDelivered(in IImsCallSession session);
@@ -91,6 +107,7 @@
     /**
      * Notifies the changes of the conference info. in the conference session.
      */
+    @UnsupportedAppUsage
     void callSessionConferenceStateUpdated(in IImsCallSession session,
             in ImsConferenceState state);
 
@@ -103,8 +120,10 @@
     /**
      * Notifies of handover information for this call
      */
+    @UnsupportedAppUsage
     void callSessionHandover(in IImsCallSession session,
             in int srcAccessTech, in int targetAccessTech, in ImsReasonInfo reasonInfo);
+    @UnsupportedAppUsage
     void callSessionHandoverFailed(in IImsCallSession session,
             in int srcAccessTech, in int targetAccessTech, in ImsReasonInfo reasonInfo);
     void callSessionMayHandover(in IImsCallSession session,
@@ -118,6 +137,7 @@
      * - {@link com.android.internal.telephony.Phone#TTY_MODE_HCO}
      * - {@link com.android.internal.telephony.Phone#TTY_MODE_VCO}
      */
+    @UnsupportedAppUsage
     void callSessionTtyModeReceived(in IImsCallSession session, in int mode);
 
     /**
@@ -126,11 +146,13 @@
      * @param session The call session.
      * @param isMultiParty {@code true} if the session became multiparty, {@code false} otherwise.
      */
+    @UnsupportedAppUsage
     void callSessionMultipartyStateChanged(in IImsCallSession session, in boolean isMultiParty);
 
     /**
      * Notifies the supplementary service information for the current session.
      */
+    @UnsupportedAppUsage
     void callSessionSuppServiceReceived(in IImsCallSession session,
          in ImsSuppServiceNotification suppSrvNotification);
 
diff --git a/telephony/java/com/android/ims/internal/IImsRegistrationListener.aidl b/telephony/java/com/android/ims/internal/IImsRegistrationListener.aidl
index 2212109..a7a62a6 100644
--- a/telephony/java/com/android/ims/internal/IImsRegistrationListener.aidl
+++ b/telephony/java/com/android/ims/internal/IImsRegistrationListener.aidl
@@ -32,6 +32,7 @@
      *
      * @deprecated see {@link registrationConnectedWithRadioTech}
      */
+    @UnsupportedAppUsage
     void registrationConnected();
 
     /**
@@ -47,6 +48,7 @@
      * @param imsRadioTech the radio access technology. Valid values are {@code
      * RIL_RADIO_TECHNOLOGY_*} defined in {@link ServiceState}.
      */
+    @UnsupportedAppUsage
     void registrationConnectedWithRadioTech(int imsRadioTech);
 
     /**
@@ -55,12 +57,14 @@
      * @param imsRadioTech the radio access technology. Valid values are {@code
      * RIL_RADIO_TECHNOLOGY_*} defined in {@link ServiceState}.
      */
+    @UnsupportedAppUsage
     void registrationProgressingWithRadioTech(int imsRadioTech);
 
 
     /**
      * Notifies the application when the device is disconnected from the IMS network.
      */
+    @UnsupportedAppUsage
     void registrationDisconnected(in ImsReasonInfo imsReasonInfo);
 
     /**
@@ -94,6 +98,7 @@
      * @param enabledFeatures features enabled as defined in com.android.ims.ImsConfig#FeatureConstants.
      * @param disabledFeatures features disabled as defined in com.android.ims.ImsConfig#FeatureConstants.
      */
+    @UnsupportedAppUsage
     void registrationFeatureCapabilityChanged(int serviceClass,
             in int[] enabledFeatures, in int[] disabledFeatures);
 
@@ -101,11 +106,13 @@
      * Updates the application with the waiting voice message count.
      * @param count The number of waiting voice messages.
      */
+    @UnsupportedAppUsage
     void voiceMessageCountUpdate(int count);
 
     /**
      * Notifies the application when the list of URIs associated with IMS client is updated.
      */
+    @UnsupportedAppUsage
     void registrationAssociatedUriChanged(in Uri[] uris);
 
     /**
@@ -116,5 +123,6 @@
      *         attempted.
      * @param imsReasonInfo Reason for the failure.
      */
+    @UnsupportedAppUsage
     void registrationChangeFailed(in int targetAccessTech, in ImsReasonInfo imsReasonInfo);
 }
diff --git a/telephony/java/com/android/ims/internal/IImsUtListener.aidl b/telephony/java/com/android/ims/internal/IImsUtListener.aidl
index a603cd3..fcb9fb1 100644
--- a/telephony/java/com/android/ims/internal/IImsUtListener.aidl
+++ b/telephony/java/com/android/ims/internal/IImsUtListener.aidl
@@ -31,30 +31,37 @@
     /**
      * Notifies the result of the supplementary service configuration udpate.
      */
+    @UnsupportedAppUsage
     void utConfigurationUpdated(in IImsUt ut, int id);
+    @UnsupportedAppUsage
     void utConfigurationUpdateFailed(in IImsUt ut, int id, in ImsReasonInfo error);
 
     /**
      * Notifies the result of the supplementary service configuration query.
      */
+    @UnsupportedAppUsage
     void utConfigurationQueried(in IImsUt ut, int id, in Bundle ssInfo);
+    @UnsupportedAppUsage
     void utConfigurationQueryFailed(in IImsUt ut, int id, in ImsReasonInfo error);
 
     /**
      * Notifies the status of the call barring supplementary service.
      */
+    @UnsupportedAppUsage
     void utConfigurationCallBarringQueried(in IImsUt ut,
             int id, in ImsSsInfo[] cbInfo);
 
     /**
      * Notifies the status of the call forwarding supplementary service.
      */
+    @UnsupportedAppUsage
     void utConfigurationCallForwardQueried(in IImsUt ut,
             int id, in ImsCallForwardInfo[] cfInfo);
 
     /**
      * Notifies the status of the call waiting supplementary service.
      */
+    @UnsupportedAppUsage
     void utConfigurationCallWaitingQueried(in IImsUt ut,
             int id, in ImsSsInfo[] cwInfo);
 
diff --git a/telephony/java/com/android/ims/internal/IImsVideoCallCallback.aidl b/telephony/java/com/android/ims/internal/IImsVideoCallCallback.aidl
index 9499c9f..cf8d637 100644
--- a/telephony/java/com/android/ims/internal/IImsVideoCallCallback.aidl
+++ b/telephony/java/com/android/ims/internal/IImsVideoCallCallback.aidl
@@ -31,18 +31,25 @@
  * {@hide}
  */
 oneway interface IImsVideoCallCallback {
+    @UnsupportedAppUsage
     void receiveSessionModifyRequest(in VideoProfile videoProfile);
 
+    @UnsupportedAppUsage
     void receiveSessionModifyResponse(int status, in VideoProfile requestedProfile,
         in VideoProfile responseProfile);
 
+    @UnsupportedAppUsage
     void handleCallSessionEvent(int event);
 
+    @UnsupportedAppUsage
     void changePeerDimensions(int width, int height);
 
+    @UnsupportedAppUsage
     void changeCallDataUsage(long dataUsage);
 
+    @UnsupportedAppUsage
     void changeCameraCapabilities(in VideoProfile.CameraCapabilities cameraCapabilities);
 
+    @UnsupportedAppUsage
     void changeVideoQuality(int videoQuality);
 }
diff --git a/telephony/java/com/android/ims/internal/IImsVideoCallProvider.aidl b/telephony/java/com/android/ims/internal/IImsVideoCallProvider.aidl
index 0da27e1..4d20bd6 100644
--- a/telephony/java/com/android/ims/internal/IImsVideoCallProvider.aidl
+++ b/telephony/java/com/android/ims/internal/IImsVideoCallProvider.aidl
@@ -41,6 +41,7 @@
  * @hide
  */
 oneway interface IImsVideoCallProvider {
+    @UnsupportedAppUsage
     void setCallback(IImsVideoCallCallback callback);
 
     void setCamera(String cameraId, int uid);
diff --git a/telephony/java/com/android/ims/internal/uce/options/IOptionsListener.aidl b/telephony/java/com/android/ims/internal/uce/options/IOptionsListener.aidl
index 8cb1153..c69d5a9 100644
--- a/telephony/java/com/android/ims/internal/uce/options/IOptionsListener.aidl
+++ b/telephony/java/com/android/ims/internal/uce/options/IOptionsListener.aidl
@@ -29,6 +29,7 @@
      * @param version, version information of the service.
      * @hide
      */
+    @UnsupportedAppUsage
     void getVersionCb(in String version );
 
     /**
@@ -37,6 +38,7 @@
      * @param statusCode, UCE_SUCCESS as service availability.
      * @hide
      */
+    @UnsupportedAppUsage
     void serviceAvailable(in StatusCode statusCode);
 
     /**
@@ -45,6 +47,7 @@
      * @param statusCode, UCE_SUCCESS as service unavailability.
      * @hide
      */
+    @UnsupportedAppUsage
     void serviceUnavailable(in StatusCode statusCode);
 
     /**
@@ -55,6 +58,7 @@
      * @param capInfo, capabilities of the remote entity received.
      * @hide
      */
+    @UnsupportedAppUsage
     void sipResponseReceived( String uri,
                                 in OptionsSipResponse sipResponse, in OptionsCapInfo capInfo);
 
@@ -63,6 +67,7 @@
      * @param cmdStatus, command status of the request placed.
      * @hide
      */
+    @UnsupportedAppUsage
     void cmdStatus(in OptionsCmdStatus cmdStatus);
 
     /**
@@ -73,6 +78,7 @@
      * @param tID, transation of the request received from network.
      * @hide
      */
+    @UnsupportedAppUsage
     void incomingOptions( String uri, in OptionsCapInfo capInfo,
                                             in int tID);
 }
diff --git a/telephony/java/com/android/ims/internal/uce/options/IOptionsService.aidl b/telephony/java/com/android/ims/internal/uce/options/IOptionsService.aidl
index 839bb55..2e49082 100644
--- a/telephony/java/com/android/ims/internal/uce/options/IOptionsService.aidl
+++ b/telephony/java/com/android/ims/internal/uce/options/IOptionsService.aidl
@@ -33,6 +33,7 @@
      * @return StatusCode, status of the request placed.
      * @hide
      */
+    @UnsupportedAppUsage
     StatusCode getVersion(int optionsServiceHandle);
 
     /**
@@ -44,6 +45,7 @@
      * The service will fill UceLong.mUceLong with optionsServiceListenerHdl
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode addListener(int optionsServiceHandle, IOptionsListener optionsListener,
                            inout UceLong optionsServiceListenerHdl);
 
@@ -54,6 +56,7 @@
      * @param optionsServiceListenerHdl provided in createOptionsService() or Addlistener().
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode removeListener(int optionsServiceHandle, in UceLong optionsServiceListenerHdl);
 
     /**
@@ -66,6 +69,7 @@
      *                  with original request.
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode setMyInfo(int optionsServiceHandle , in CapInfo capInfo, int reqUserData);
 
 
@@ -78,6 +82,7 @@
      *                  with original request.
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode getMyInfo(int optionsServiceHandle , int reqUserdata);
 
     /**
@@ -90,6 +95,7 @@
      *                  with original request.
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode getContactCap(int optionsServiceHandle , String remoteURI, int reqUserData);
 
 
@@ -103,6 +109,7 @@
      *                  with original request.
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode getContactListCap(int optionsServiceHandle, in String[] remoteURIList,
                                  int reqUserData);
 
@@ -119,6 +126,7 @@
      * @param bContactInBL, true if the contact is blacklisted, else false.
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode responseIncomingOptions(int optionsServiceHandle,  int tId, int sipResponseCode,
                                        String reasonPhrase, in OptionsCapInfo capInfo,
                                        in boolean bContactInBL);
diff --git a/telephony/java/com/android/ims/internal/uce/presence/IPresenceListener.aidl b/telephony/java/com/android/ims/internal/uce/presence/IPresenceListener.aidl
index 2ae424f..65e7fc9 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/IPresenceListener.aidl
+++ b/telephony/java/com/android/ims/internal/uce/presence/IPresenceListener.aidl
@@ -36,6 +36,7 @@
      * Gets the version of the presence listener implementation.
      * @param version, version information.
      */
+    @UnsupportedAppUsage
     void getVersionCb(in String version );
 
     /**
@@ -43,6 +44,7 @@
      * availability.
      * @param statusCode, UCE_SUCCESS as service availability.
      */
+    @UnsupportedAppUsage
     void serviceAvailable(in StatusCode statusCode);
 
     /**
@@ -50,6 +52,7 @@
      * unavailability.
      * @param statusCode, UCE_SUCCESS as service unAvailability.
      */
+    @UnsupportedAppUsage
     void serviceUnAvailable(in StatusCode statusCode);
 
     /**
@@ -57,12 +60,14 @@
      * publish request.
      * @param publishTrigger, Publish trigger for the network being supported.
      */
+    @UnsupportedAppUsage
     void publishTriggering(in PresPublishTriggerType publishTrigger);
 
     /**
      * Callback function to be invoked to inform the client of the status of an asynchronous call.
      * @param cmdStatus, command status of the request placed.
      */
+    @UnsupportedAppUsage
     void cmdStatus( in PresCmdStatus cmdStatus);
 
     /**
@@ -70,6 +75,7 @@
      * such as PUBLISH or SUBSCRIBE, has been received.
      * @param sipResponse, network response received for the request placed.
      */
+    @UnsupportedAppUsage
     void sipResponseReceived(in PresSipResponse sipResponse);
 
     /**
@@ -78,6 +84,7 @@
      * @param presentityURI, URI of the remote entity the request was placed.
      * @param tupleInfo, array of capability information remote entity supports.
      */
+    @UnsupportedAppUsage
     void capInfoReceived(in String presentityURI,
                          in PresTupleInfo [] tupleInfo);
 
@@ -87,6 +94,7 @@
      * @param rlmiInfo, resource infomation received from network.
      * @param resInfo, array of capabilities received from network for the list of  remore URI.
      */
+    @UnsupportedAppUsage
     void listCapInfoReceived(in PresRlmiInfo rlmiInfo,
                              in PresResInfo [] resInfo);
 
@@ -94,6 +102,7 @@
      * Callback function to be invoked to inform the client when Unpublish message
      * is sent to network.
      */
+    @UnsupportedAppUsage
     void unpublishMessageSent();
 
 }
\ No newline at end of file
diff --git a/telephony/java/com/android/ims/internal/uce/presence/IPresenceService.aidl b/telephony/java/com/android/ims/internal/uce/presence/IPresenceService.aidl
index fdea6d3..26a3e83 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/IPresenceService.aidl
+++ b/telephony/java/com/android/ims/internal/uce/presence/IPresenceService.aidl
@@ -33,6 +33,7 @@
      * @param presenceServiceHdl returned in createPresenceService().
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode getVersion(int presenceServiceHdl);
 
     /**
@@ -45,6 +46,7 @@
      *
      * @return StatusCode, status of the request placed
      */
+    @UnsupportedAppUsage
     StatusCode addListener(int presenceServiceHdl, IPresenceListener presenceServiceListener,
                            inout UceLong presenceServiceListenerHdl);
 
@@ -54,6 +56,7 @@
      * @param presenceServiceListenerHdl provided in createPresenceService() or Addlistener().
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode removeListener(int presenceServiceHdl, in UceLong presenceServiceListenerHdl);
 
     /**
@@ -69,6 +72,7 @@
      *                  with original request.
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode reenableService(int presenceServiceHdl, int userData);
 
     /**
@@ -81,6 +85,7 @@
      *                  with original request.
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode publishMyCap(int presenceServiceHdl, in PresCapInfo myCapInfo , int userData);
 
     /**
@@ -94,6 +99,7 @@
      *                  with original request.
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode getContactCap(int presenceServiceHdl , String remoteUri, int userData);
 
     /**
@@ -107,6 +113,7 @@
      *                  with original request.
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode getContactListCap(int presenceServiceHdl, in String[] remoteUriList, int userData);
 
     /**
@@ -122,6 +129,7 @@
      *                  with original request.
      * @return StatusCode, status of the request placed.
      */
+    @UnsupportedAppUsage
     StatusCode  setNewFeatureTag(int presenceServiceHdl, String featureTag,
                                  in PresServiceInfo serviceInfo, int userData);
 
diff --git a/telephony/java/com/android/ims/internal/uce/uceservice/IUceListener.aidl b/telephony/java/com/android/ims/internal/uce/uceservice/IUceListener.aidl
index 13707a1..41abf7d 100644
--- a/telephony/java/com/android/ims/internal/uce/uceservice/IUceListener.aidl
+++ b/telephony/java/com/android/ims/internal/uce/uceservice/IUceListener.aidl
@@ -25,5 +25,6 @@
      * @param serviceStatusValue defined in ImsUceManager
      * @hide
      */
+    @UnsupportedAppUsage
     void setStatus(int serviceStatusValue);
 }
diff --git a/telephony/java/com/android/ims/internal/uce/uceservice/IUceService.aidl b/telephony/java/com/android/ims/internal/uce/uceservice/IUceService.aidl
index 1fb8513..ec45371 100644
--- a/telephony/java/com/android/ims/internal/uce/uceservice/IUceService.aidl
+++ b/telephony/java/com/android/ims/internal/uce/uceservice/IUceService.aidl
@@ -38,6 +38,7 @@
      * Service status is returned in setStatus callback in IUceListener.
      * @hide
      */
+    @UnsupportedAppUsage
     boolean startService(IUceListener uceListener);
 
     /**
@@ -45,6 +46,7 @@
      * @return boolean true if the service stop request is processed successfully, FALSE otherwise.
      * @hide
      */
+    @UnsupportedAppUsage
     boolean stopService();
 
 
@@ -54,6 +56,7 @@
      * @return boolean true if service started else false.
      * @hide
      */
+    @UnsupportedAppUsage
     boolean isServiceStarted();
 
     /**
@@ -71,6 +74,7 @@
      *
      * @deprecated This is replaced with new API createOptionsServiceForSubscription()
      */
+    @UnsupportedAppUsage
     int createOptionsService(IOptionsListener optionsListener,
                              inout UceLong optionsServiceListenerHdl);
     /**
@@ -97,6 +101,7 @@
      *        in IOptionsListener
      * @hide
      */
+    @UnsupportedAppUsage
     void destroyOptionsService(int optionsServiceHandle);
 
     /**
@@ -114,6 +119,7 @@
      *
      * @deprecated This is replaced with new API createPresenceServiceForSubscription()
      */
+    @UnsupportedAppUsage
     int createPresenceService(IPresenceListener presenceServiceListener,
                               inout UceLong presenceServiceListenerHdl);
     /**
@@ -141,6 +147,7 @@
      *
      * @hide
      */
+    @UnsupportedAppUsage
     void destroyPresenceService(int presenceServiceHdl);
 
 
@@ -152,6 +159,7 @@
      *
      * @hide
      */
+    @UnsupportedAppUsage
     boolean getServiceStatus();
 
     /**
@@ -163,6 +171,7 @@
      *
      * @deprecated use API getPresenceServiceForSubscription()
      */
+    @UnsupportedAppUsage
     IPresenceService getPresenceService();
 
     /**
@@ -185,6 +194,7 @@
      *
      * @hide
      */
+    @UnsupportedAppUsage
     IOptionsService getOptionsService();
 
     /**
diff --git a/telephony/java/com/android/internal/telephony/ICarrierConfigLoader.aidl b/telephony/java/com/android/internal/telephony/ICarrierConfigLoader.aidl
index 5cd67d9..8e50a8f 100644
--- a/telephony/java/com/android/internal/telephony/ICarrierConfigLoader.aidl
+++ b/telephony/java/com/android/internal/telephony/ICarrierConfigLoader.aidl
@@ -23,6 +23,7 @@
  */
 interface ICarrierConfigLoader {
 
+    @UnsupportedAppUsage
     PersistableBundle getConfigForSubId(int subId, String callingPackage);
 
     void overrideConfig(int subId, in PersistableBundle overrides);
diff --git a/telephony/java/com/android/internal/telephony/IPhoneSubInfo.aidl b/telephony/java/com/android/internal/telephony/IPhoneSubInfo.aidl
index abcb15a..5b509b7 100644
--- a/telephony/java/com/android/internal/telephony/IPhoneSubInfo.aidl
+++ b/telephony/java/com/android/internal/telephony/IPhoneSubInfo.aidl
@@ -60,6 +60,7 @@
     /**
      * Retrieves the unique sbuscriber ID, e.g., IMSI for GSM phones.
      */
+    @UnsupportedAppUsage
     String getSubscriberId(String callingPackage);
 
     /**
@@ -75,6 +76,7 @@
     /**
      * Retrieves the serial number of the ICC, if applicable.
      */
+    @UnsupportedAppUsage
     String getIccSerialNumber(String callingPackage);
 
     /**
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index d183837..5c5d44a 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -76,6 +76,7 @@
      * @param number the number to be dialed. If null, this
      * would display the Dialer screen with no number pre-filled.
      */
+    @UnsupportedAppUsage
     void dial(String number);
 
     /**
@@ -83,6 +84,7 @@
      * @param callingPackage The package making the call.
      * @param number the number to be called.
      */
+    @UnsupportedAppUsage
     void call(String callingPackage, String number);
 
     /**
@@ -98,6 +100,7 @@
      * @param callingPackage the name of the package making the call.
      * @return returns true if the radio is on.
      */
+    @UnsupportedAppUsage
     boolean isRadioOnForSubscriber(int subId, String callingPackage);
 
     /**
@@ -105,6 +108,7 @@
      * @param pin The pin to check.
      * @return whether the operation was a success.
      */
+    @UnsupportedAppUsage
     boolean supplyPin(String pin);
 
     /**
@@ -182,6 +186,7 @@
      * @param dialString the MMI command to be executed.
      * @return true if MMI command is executed.
      */
+    @UnsupportedAppUsage
     boolean handlePinMmi(String dialString);
 
 
@@ -202,11 +207,13 @@
      * @param subId user preferred subId.
      * @return true if MMI command is executed.
      */
+    @UnsupportedAppUsage
     boolean handlePinMmiForSubscriber(int subId, String dialString);
 
     /**
      * Toggles the radio on or off.
      */
+    @UnsupportedAppUsage
     void toggleRadioOnOff();
 
     /**
@@ -218,6 +225,7 @@
     /**
      * Set the radio to on or off
      */
+    @UnsupportedAppUsage
     boolean setRadio(boolean turnOn);
 
     /**
@@ -234,6 +242,7 @@
     /**
      * Request to update location information in service state
      */
+    @UnsupportedAppUsage
     void updateServiceLocation();
 
     /**
@@ -245,6 +254,7 @@
     /**
      * Enable location update notifications.
      */
+    @UnsupportedAppUsage
     void enableLocationUpdates();
 
     /**
@@ -256,6 +266,7 @@
     /**
      * Disable location update notifications.
      */
+    @UnsupportedAppUsage
     void disableLocationUpdates();
 
     /**
@@ -267,11 +278,13 @@
     /**
      * Allow mobile data connections.
      */
+    @UnsupportedAppUsage
     boolean enableDataConnectivity();
 
     /**
      * Disallow mobile data connections.
      */
+    @UnsupportedAppUsage
     boolean disableDataConnectivity();
 
     /**
@@ -293,6 +306,7 @@
      */
     List<NeighboringCellInfo> getNeighboringCellInfo(String callingPkg);
 
+     @UnsupportedAppUsage
      int getCallState();
 
     /**
@@ -300,7 +314,9 @@
      */
      int getCallStateForSlot(int slotIndex);
 
+     @UnsupportedAppUsage
      int getDataActivity();
+     @UnsupportedAppUsage
      int getDataState();
 
     /**
@@ -308,6 +324,7 @@
      * Returns TelephonyManager.PHONE_TYPE_CDMA if RILConstants.CDMA_PHONE
      * and TelephonyManager.PHONE_TYPE_GSM if RILConstants.GSM_PHONE
      */
+    @UnsupportedAppUsage
     int getActivePhoneType();
 
     /**
@@ -444,6 +461,7 @@
      * Returns the network type for data transmission
      * Legacy call, permission-free
      */
+    @UnsupportedAppUsage
     int getNetworkType();
 
     /**
@@ -477,6 +495,7 @@
     /**
      * Return true if an ICC card is present
      */
+    @UnsupportedAppUsage
     boolean hasIccCard();
 
     /**
@@ -557,6 +576,7 @@
      *            successful iccOpenLogicalChannel.
      * @return true if the channel was closed successfully.
      */
+    @UnsupportedAppUsage
     boolean iccCloseLogicalChannel(int subId, int channel);
 
     /**
@@ -577,6 +597,7 @@
      * @return The APDU response from the ICC card with the status appended at
      *            the end.
      */
+    @UnsupportedAppUsage
     String iccTransmitApduLogicalChannel(int subId, int channel, int cla, int instruction,
             int p1, int p2, int p3, String data);
 
@@ -829,6 +850,7 @@
      *
      * @return true on enabled
      */
+    @UnsupportedAppUsage
     boolean getDataEnabled(int subId);
 
     /**
@@ -1679,7 +1701,7 @@
     /**
      * Modify the user's setting for whether or not 4G LTE is enabled.
      */
-    void setAdvancedCallingSetting(int subId, boolean isEnabled);
+    void setAdvancedCallingSettingEnabled(int subId, boolean isEnabled);
 
     /**
      * return true if the user's setting for VT is enabled for the subscription.
@@ -1689,7 +1711,7 @@
     /**
      * Modify the user's setting for whether or not VT is available for the subscrption specified.
      */
-    void setVtSetting(int subId, boolean isEnabled);
+    void setVtSettingEnabled(int subId, boolean isEnabled);
 
     /**
      * return true if the user's setting for whether or not Voice over WiFi is currently enabled.
@@ -1699,7 +1721,7 @@
     /**
      * sets the user's setting for Voice over WiFi enabled state.
      */
-    void setVoWiFiSetting(int subId, boolean isEnabled);
+    void setVoWiFiSettingEnabled(int subId, boolean isEnabled);
 
     /**
      * return true if the user's setting for Voice over WiFi while roaming is enabled.
@@ -1710,7 +1732,7 @@
      * Sets the user's preference for whether or not Voice over WiFi is enabled for the current
      * subscription while roaming.
      */
-    void setVoWiFiRoamingSetting(int subId, boolean isEnabled);
+    void setVoWiFiRoamingSettingEnabled(int subId, boolean isEnabled);
 
     /**
      * Set the Voice over WiFi enabled state, but do not persist the setting.
diff --git a/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl b/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
index a922ab6..0610c5d 100644
--- a/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
@@ -38,9 +38,11 @@
             IOnSubscriptionsChangedListener callback);
     void removeOnSubscriptionsChangedListener(String pkg,
             IOnSubscriptionsChangedListener callback);
+    @UnsupportedAppUsage
     void listen(String pkg, IPhoneStateListener callback, int events, boolean notifyNow);
     void listenForSubscriber(in int subId, String pkg, IPhoneStateListener callback, int events,
             boolean notifyNow);
+    @UnsupportedAppUsage
     void notifyCallState(int state, String incomingNumber);
     void notifyCallStateForPhoneId(in int phoneId, in int subId, int state, String incomingNumber);
     void notifyServiceStateForPhoneId(in int phoneId, in int subId, in ServiceState state);
@@ -57,11 +59,13 @@
     void notifyDataConnectionForSubscriber(int subId, int state, boolean isDataConnectivityPossible,
             String apn, String apnType, in LinkProperties linkProperties,
             in NetworkCapabilities networkCapabilities, int networkType, boolean roaming);
+    @UnsupportedAppUsage
     void notifyDataConnectionFailed(String apnType);
     void notifyDataConnectionFailedForSubscriber(int subId, String apnType);
     void notifyCellLocation(in Bundle cellLocation);
     void notifyCellLocationForSubscriber(in int subId, in Bundle cellLocation);
     void notifyOtaspChanged(in int otaspMode);
+    @UnsupportedAppUsage
     void notifyCellInfo(in List<CellInfo> cellInfo);
     void notifyPhysicalChannelConfiguration(in List<PhysicalChannelConfig> configs);
     void notifyPhysicalChannelConfigurationForSubscriber(in int subId,
@@ -84,6 +88,6 @@
     void notifyActiveDataSubIdChanged(int activeDataSubId);
     void notifyRadioPowerStateChanged(in int state);
     void notifyEmergencyNumberList();
-    void notifyCallQualityChanged(in CallQuality callQuality, int phoneId);
+    void notifyCallQualityChanged(in CallQuality callQuality, int phoneId, int callNetworkType);
     void notifyImsDisconnectCause(int subId, in ImsReasonInfo imsReasonInfo);
 }
diff --git a/telephony/java/com/android/internal/telephony/IWapPushManager.aidl b/telephony/java/com/android/internal/telephony/IWapPushManager.aidl
index d5ecb94..1c3df65 100644
--- a/telephony/java/com/android/internal/telephony/IWapPushManager.aidl
+++ b/telephony/java/com/android/internal/telephony/IWapPushManager.aidl
@@ -30,6 +30,7 @@
      * Returns true if inserting the information is successfull. Inserting the duplicated
      * record in the application ID table is not allowed. Use update/delete method.
      */
+    @UnsupportedAppUsage
     boolean addPackage(String x_app_id, String content_type,
             String package_name, String class_name,
             int app_type, boolean need_signature, boolean further_processing);
@@ -38,6 +39,7 @@
      * Updates receiver application that is last added.
      * Returns true if updating the information is successfull.
      */
+    @UnsupportedAppUsage
     boolean updatePackage(String x_app_id, String content_type,
             String package_name, String class_name,
             int app_type, boolean need_signature, boolean further_processing);
@@ -46,6 +48,7 @@
      * Delites receiver application information.
      * Returns true if deleting is successfull.
      */
+    @UnsupportedAppUsage
     boolean deletePackage(String x_app_id, String content_type,
                             String package_name, String class_name);
 }
diff --git a/telephony/java/com/android/internal/telephony/RILConstants.java b/telephony/java/com/android/internal/telephony/RILConstants.java
index 77b7979..5205973 100644
--- a/telephony/java/com/android/internal/telephony/RILConstants.java
+++ b/telephony/java/com/android/internal/telephony/RILConstants.java
@@ -470,6 +470,7 @@
     int RIL_REQUEST_START_KEEPALIVE = 144;
     int RIL_REQUEST_STOP_KEEPALIVE = 145;
     int RIL_REQUEST_ENABLE_MODEM = 146;
+    int RIL_REQUEST_GET_MODEM_STATUS = 147;
 
     /* The following requests are not defined in RIL.h */
     int RIL_REQUEST_HAL_NON_RIL_BASE = 200;
diff --git a/test-base/Android.bp b/test-base/Android.bp
index 157609c..8aa0aaf 100644
--- a/test-base/Android.bp
+++ b/test-base/Android.bp
@@ -44,7 +44,7 @@
 // ==========================================
 // This is only intended for inclusion in the android.test.runner-minus-junit,
 // robolectric_android-all-stub and repackaged.android.test.* libraries.
-// Must not be used elewhere.
+// Must not be used elsewhere.
 java_library_static {
     name: "android.test.base_static",
     installable: false,
@@ -61,19 +61,6 @@
     sdk_version: "current",
 }
 
-// Build the legacy-test library
-// =============================
-// This contains the junit.framework and android.test classes that were in
-// Android API level 25 excluding those from android.test.runner.
-// Also contains the com.android.internal.util.Predicate[s] classes.
-java_library {
-    name: "legacy-test",
-    installable: true,
-
-    sdk_version: "current",
-    static_libs: ["android.test.base_static"],
-}
-
 // Build the repackaged.android.test.base library
 // ==============================================
 // This contains repackaged versions of the classes from
@@ -93,8 +80,8 @@
 // ===============================================
 // This contains the android.test classes from android.test.base plus
 // the com.android.internal.util.Predicate[s] classes. This is only
-// intended for inclusion in the android.test.legacy and
-// legacy-android-test static libraries and must not be used elsewhere.
+// intended for inclusion in android.test.legacy and must not be used
+// elsewhere.
 java_library_static {
     name: "android.test.base-minus-junit",
 
diff --git a/test-base/hiddenapi/Android.bp b/test-base/hiddenapi/Android.bp
new file mode 100644
index 0000000..c4e0fab
--- /dev/null
+++ b/test-base/hiddenapi/Android.bp
@@ -0,0 +1,29 @@
+//
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+// Provided solely to contribute information about which hidden parts of the android.test.base
+// library are used by apps. The source files are stubs of the actual files in ../src which use the
+// UnsupportedAppUsage annotation to tag those methods that are accessible via the hiddenapi.
+// Relies on the convention that modules with name <x>-hiddenapi provide hiddenapi information for
+// module <x> that is on the bootclasspath.
+java_library {
+    name: "android.test.base-hiddenapi",
+    compile_dex: true,
+
+    srcs: ["src/**/*.java"],
+
+    libs: ["android.test.base"],
+}
diff --git a/test-base/hiddenapi/src/android/test/AndroidTestCase.java b/test-base/hiddenapi/src/android/test/AndroidTestCase.java
new file mode 100644
index 0000000..2b9beb1
--- /dev/null
+++ b/test-base/hiddenapi/src/android/test/AndroidTestCase.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.test;
+
+import android.annotation.UnsupportedAppUsage;
+import android.content.Context;
+
+import junit.framework.TestCase;
+
+/**
+ * @deprecated Stub only
+ */
+@SuppressWarnings({ "unchecked", "deprecation", "all" })
+@Deprecated
+public class AndroidTestCase extends TestCase {
+
+    /**
+     * Stub only
+     */
+    @UnsupportedAppUsage
+    public void setTestContext(Context context) {
+        throw new RuntimeException("Stub!");
+    }
+
+    /**
+     * Stub only
+     */
+    @UnsupportedAppUsage
+    public Context getTestContext() {
+        throw new RuntimeException("Stub!");
+    }
+}
diff --git a/test-base/hiddenapi/src/android/test/InstrumentationTestCase.java b/test-base/hiddenapi/src/android/test/InstrumentationTestCase.java
new file mode 100644
index 0000000..139cd18
--- /dev/null
+++ b/test-base/hiddenapi/src/android/test/InstrumentationTestCase.java
@@ -0,0 +1,39 @@
+/*
+ * 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.test;
+
+import android.annotation.UnsupportedAppUsage;
+
+import junit.framework.TestCase;
+
+import java.lang.reflect.Method;
+
+/**
+ * @deprecated Stub only
+ */
+@SuppressWarnings({ "unchecked", "deprecation", "all" })
+@Deprecated
+public class InstrumentationTestCase extends TestCase {
+
+    /**
+     * Stub only
+     */
+    @UnsupportedAppUsage
+    private void runMethod(Method runMethod, int tolerance) throws Throwable {
+        throw new RuntimeException("Stub!");
+    }
+}
diff --git a/test-base/hiddenapi/src/junit/framework/TestCase.java b/test-base/hiddenapi/src/junit/framework/TestCase.java
new file mode 100644
index 0000000..5a54861
--- /dev/null
+++ b/test-base/hiddenapi/src/junit/framework/TestCase.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package junit.framework;
+
+import android.annotation.UnsupportedAppUsage;
+
+/**
+ * Stub only
+ */
+@SuppressWarnings({ "unchecked", "deprecation", "all" })
+public abstract class TestCase extends Assert implements Test {
+
+    /**
+     * the name of the test case
+     */
+    @UnsupportedAppUsage
+    private String fName;
+
+    /**
+     * Stub only
+     */
+    public int countTestCases() {
+        throw new RuntimeException("Stub!");
+    }
+
+    /**
+     * Stub only
+     */
+    public void run(TestResult result) {
+        throw new RuntimeException("Stub!");
+    }
+}
diff --git a/test-base/hiddenapi/src/junit/framework/TestSuite.java b/test-base/hiddenapi/src/junit/framework/TestSuite.java
new file mode 100644
index 0000000..368c661
--- /dev/null
+++ b/test-base/hiddenapi/src/junit/framework/TestSuite.java
@@ -0,0 +1,58 @@
+/*
+ * 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 junit.framework;
+
+import android.annotation.UnsupportedAppUsage;
+
+import java.lang.reflect.Method;
+
+/**
+ * Stub only
+ */
+@SuppressWarnings({ "unchecked", "deprecation", "all" })
+public class TestSuite implements Test {
+
+    /**
+     * Stub only
+     */
+    @UnsupportedAppUsage
+    private boolean isPublicTestMethod(Method m) {
+        throw new RuntimeException("Stub!");
+    }
+
+    /**
+     * Stub only
+     */
+    @UnsupportedAppUsage
+    private boolean isTestMethod(Method m) {
+        throw new RuntimeException("Stub!");
+    }
+
+    /**
+     * Stub only
+     */
+    public int countTestCases() {
+        throw new RuntimeException("Stub!");
+    }
+
+    /**
+     * Stub only
+     */
+    public void run(TestResult result) {
+        throw new RuntimeException("Stub!");
+    }
+}
diff --git a/test-legacy/Android.bp b/test-legacy/Android.bp
deleted file mode 100644
index a69f422..0000000
--- a/test-legacy/Android.bp
+++ /dev/null
@@ -1,36 +0,0 @@
-//
-// Copyright (C) 2018 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-// Build the legacy-android-test library
-// =====================================
-// This contains the android.test classes that were in Android API level 25,
-// including those from android.test.runner.
-// Also contains the com.android.internal.util.Predicate[s] classes.
-java_library_static {
-    name: "legacy-android-test",
-
-    static_libs: [
-        "android.test.base-minus-junit",
-        "android.test.runner-minus-junit",
-        "android.test.mock_static",
-    ],
-
-    no_framework_libs: true,
-    libs: [
-        "framework",
-        "junit",
-    ],
-}
diff --git a/test-legacy/Android.mk b/test-legacy/Android.mk
index da47de0..af26c5b 100644
--- a/test-legacy/Android.mk
+++ b/test-legacy/Android.mk
@@ -24,35 +24,16 @@
 # Built against the SDK so that it can be statically included in APKs
 # without breaking link type checks.
 #
-# This builds directly from the source rather than simply statically
-# including the android.test.base-minus-junit and
-# android.test.runner-minus-junit libraries because the latter library
-# cannot itself be built against the SDK. That is because it uses on
-# an internal method (setTestContext) on the AndroidTestCase class.
-# That class is provided by both the android.test.base-minus-junit and
-# the current SDK and as the latter is first on the classpath its
-# version is used. Unfortunately, it does not provide the internal
-# method and so compilation fails.
-#
-# Building from source avoids that because the compiler will use the
-# source version of AndroidTestCase instead of the one from the current
-# SDK.
-#
-# The use of the internal method does not prevent this from being
-# statically included because the class that provides the method is
-# also included in this library.
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := android.test.legacy
 
-LOCAL_SRC_FILES := \
-    $(call all-java-files-under, ../test-base/src/android) \
-    $(call all-java-files-under, ../test-base/src/com) \
-    $(call all-java-files-under, ../test-runner/src/android) \
-
 LOCAL_SDK_VERSION := current
 
 LOCAL_JAVA_LIBRARIES := junit android.test.mock.stubs
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    android.test.base-minus-junit \
+    android.test.runner-minus-junit \
 
 include $(BUILD_STATIC_JAVA_LIBRARY)
 
diff --git a/test-mock/Android.bp b/test-mock/Android.bp
index 43b765d..e1d6e01 100644
--- a/test-mock/Android.bp
+++ b/test-mock/Android.bp
@@ -30,19 +30,3 @@
     srcs_lib_whitelist_pkgs: ["android"],
     compile_dex: true,
 }
-
-// Build the android.test.mock_static library
-// ==========================================
-// This is only intended for inclusion in the legacy-android-test.
-// Must not be used elewhere.
-java_library_static {
-    name: "android.test.mock_static",
-
-    java_version: "1.8",
-    srcs: ["src/**/*.java"],
-
-    no_framework_libs: true,
-    libs: [
-        "framework",
-    ],
-}
diff --git a/test-runner/Android.bp b/test-runner/Android.bp
index db5053e..3521202 100644
--- a/test-runner/Android.bp
+++ b/test-runner/Android.bp
@@ -45,7 +45,7 @@
 
 // Build the android.test.runner-minus-junit library
 // =================================================
-// This is only intended for inclusion in the legacy-android-test static
+// This is only intended for inclusion in the android.test.legacy static
 // library and must not be used elsewhere.
 java_library {
     name: "android.test.runner-minus-junit",
diff --git a/tests/DynamicCodeLoggerIntegrationTests/src/com/android/server/pm/dex/DynamicCodeLoggerIntegrationTests.java b/tests/DynamicCodeLoggerIntegrationTests/src/com/android/server/pm/dex/DynamicCodeLoggerIntegrationTests.java
index 8ef15d8..4f9aeea 100644
--- a/tests/DynamicCodeLoggerIntegrationTests/src/com/android/server/pm/dex/DynamicCodeLoggerIntegrationTests.java
+++ b/tests/DynamicCodeLoggerIntegrationTests/src/com/android/server/pm/dex/DynamicCodeLoggerIntegrationTests.java
@@ -235,6 +235,34 @@
     }
 
     @Test
+    public void testGeneratesEvents_spoofed_validFile_untrustedApp() throws Exception {
+        File privateCopyFile = privateFile("spoofed2");
+
+        String expectedContentHash = copyAndHashResource(
+                "/DynamicCodeLoggerNativeExecutable", privateCopyFile);
+
+        EventLog.writeEvent(EventLog.getTagCode("auditd"),
+                "type=1400 avc: granted { execute_no_trans } "
+                        + "path=\"" + privateCopyFile + "\" "
+                        + "scontext=u:r:untrusted_app: "
+                        + "tcontext=u:object_r:app_data_file: "
+                        + "tclass=file ");
+
+        String expectedNameHash =
+                "3E57AA59249154C391316FDCF07C1D499C26A564E4D305833CCD9A98ED895AC9";
+
+        // Run the job to scan generated audit log entries
+        runDynamicCodeLoggingJob(AUDIT_WATCHING_JOB_ID);
+
+        // And then make sure we log events about it
+        long previousEventNanos = mostRecentEventTimeNanos();
+        runDynamicCodeLoggingJob(IDLE_LOGGING_JOB_ID);
+
+        assertDclLoggedSince(previousEventNanos, DCL_NATIVE_SUBTAG,
+                expectedNameHash, expectedContentHash);
+    }
+
+    @Test
     public void testGeneratesEvents_spoofed_pathTraversal() throws Exception {
         File privateDir = privateFile("x").getParentFile();
 
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/CustomRenderer.java b/tests/HwAccelerationTest/src/com/android/test/hwui/CustomRenderer.java
index 60bd60f..fece8ba 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/CustomRenderer.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/CustomRenderer.java
@@ -49,7 +49,7 @@
         @Override
         public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
             mContent.setLeftTopRightBottom(0, 0, width, height);
-            RecordingCanvas canvas = mContent.startRecording();
+            RecordingCanvas canvas = mContent.beginRecording();
             canvas.drawColor(Color.WHITE);
             Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
             paint.setColor(Color.BLACK);
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/MyLittleTextureView.java b/tests/HwAccelerationTest/src/com/android/test/hwui/MyLittleTextureView.java
index 8bd7d79..08d5d4f 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/MyLittleTextureView.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/MyLittleTextureView.java
@@ -60,14 +60,14 @@
         outline.setAlpha(1f);
         childNode.setOutline(outline);
         {
-            Canvas canvas = childNode.startRecording();
+            Canvas canvas = childNode.beginRecording();
             canvas.drawColor(Color.BLUE);
         }
         childNode.endRecording();
         childNode.setElevation(20f);
 
         {
-            Canvas canvas = mContent.startRecording();
+            Canvas canvas = mContent.beginRecording();
             canvas.drawColor(Color.WHITE);
             canvas.enableZ();
             canvas.drawRenderNode(childNode);
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/PositionListenerActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/PositionListenerActivity.java
index 316aad3..818d899 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/PositionListenerActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/PositionListenerActivity.java
@@ -53,7 +53,7 @@
         MyPositionReporter(Context c) {
             super(c);
             mNode = new RenderNode("positionListener");
-            mNode.requestPositionUpdates(this);
+            mNode.addPositionUpdateListener(this);
             setTextAlignment(TEXT_ALIGNMENT_VIEW_START);
         }
 
diff --git a/tests/RollbackTest/Android.mk b/tests/RollbackTest/Android.mk
index 9e5d8ce..db9376b 100644
--- a/tests/RollbackTest/Android.mk
+++ b/tests/RollbackTest/Android.mk
@@ -21,6 +21,7 @@
 LOCAL_SDK_VERSION := current
 LOCAL_SRC_FILES := $(call all-java-files-under, TestApp/src)
 LOCAL_MANIFEST_FILE := TestApp/Av1.xml
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/TestApp/res_v1
 LOCAL_PACKAGE_NAME := RollbackTestAppAv1
 include $(BUILD_PACKAGE)
 ROLLBACK_TEST_APP_AV1 := $(LOCAL_INSTALLED_MODULE)
@@ -32,6 +33,7 @@
 LOCAL_SDK_VERSION := current
 LOCAL_SRC_FILES := $(call all-java-files-under, TestApp/src)
 LOCAL_MANIFEST_FILE := TestApp/Av2.xml
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/TestApp/res_v2
 LOCAL_PACKAGE_NAME := RollbackTestAppAv2
 include $(BUILD_PACKAGE)
 ROLLBACK_TEST_APP_AV2 := $(LOCAL_INSTALLED_MODULE)
@@ -43,6 +45,7 @@
 LOCAL_SDK_VERSION := current
 LOCAL_SRC_FILES := $(call all-java-files-under, TestApp/src)
 LOCAL_MANIFEST_FILE := TestApp/ACrashingV2.xml
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/TestApp/res_v2
 LOCAL_PACKAGE_NAME := RollbackTestAppACrashingV2
 include $(BUILD_PACKAGE)
 ROLLBACK_TEST_APP_A_CRASHING_V2 := $(LOCAL_INSTALLED_MODULE)
@@ -54,6 +57,7 @@
 LOCAL_SDK_VERSION := current
 LOCAL_SRC_FILES := $(call all-java-files-under, TestApp/src)
 LOCAL_MANIFEST_FILE := TestApp/Bv1.xml
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/TestApp/res_v1
 LOCAL_PACKAGE_NAME := RollbackTestAppBv1
 include $(BUILD_PACKAGE)
 ROLLBACK_TEST_APP_BV1 := $(LOCAL_INSTALLED_MODULE)
@@ -65,10 +69,39 @@
 LOCAL_SDK_VERSION := current
 LOCAL_SRC_FILES := $(call all-java-files-under, TestApp/src)
 LOCAL_MANIFEST_FILE := TestApp/Bv2.xml
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/TestApp/res_v2
 LOCAL_PACKAGE_NAME := RollbackTestAppBv2
 include $(BUILD_PACKAGE)
 ROLLBACK_TEST_APP_BV2 := $(LOCAL_INSTALLED_MODULE)
 
+# RollbackTestAppASplitV1.apk
+include $(CLEAR_VARS)
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_SDK_VERSION := current
+LOCAL_SRC_FILES := $(call all-java-files-under, TestApp/src)
+LOCAL_MANIFEST_FILE := TestApp/Av1.xml
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/TestApp/res_v1
+LOCAL_PACKAGE_NAME := RollbackTestAppASplitV1
+LOCAL_PACKAGE_SPLITS := anydpi
+include $(BUILD_PACKAGE)
+ROLLBACK_TEST_APP_A_SPLIT_V1 := $(LOCAL_INSTALLED_MODULE)
+ROLLBACK_TEST_APP_A_SPLIT_V1_SPLIT := $(installed_apk_splits)
+
+# RollbackTestAppASplitV2.apk
+include $(CLEAR_VARS)
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_SDK_VERSION := current
+LOCAL_SRC_FILES := $(call all-java-files-under, TestApp/src)
+LOCAL_MANIFEST_FILE := TestApp/Av2.xml
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/TestApp/res_v2
+LOCAL_PACKAGE_NAME := RollbackTestAppASplitV2
+LOCAL_PACKAGE_SPLITS := anydpi
+include $(BUILD_PACKAGE)
+ROLLBACK_TEST_APP_A_SPLIT_V2 := $(LOCAL_INSTALLED_MODULE)
+ROLLBACK_TEST_APP_A_SPLIT_V2_SPLIT := $(installed_apk_splits)
+
 # RollbackTest
 include $(CLEAR_VARS)
 LOCAL_SRC_FILES := $(call all-java-files-under, RollbackTest/src)
@@ -82,6 +115,10 @@
   $(ROLLBACK_TEST_APP_A_CRASHING_V2) \
   $(ROLLBACK_TEST_APP_BV1) \
   $(ROLLBACK_TEST_APP_BV2) \
+  $(ROLLBACK_TEST_APP_A_SPLIT_V1) \
+  $(ROLLBACK_TEST_APP_A_SPLIT_V1_SPLIT) \
+  $(ROLLBACK_TEST_APP_A_SPLIT_V2) \
+  $(ROLLBACK_TEST_APP_A_SPLIT_V2_SPLIT) \
   $(ROLLBACK_TEST_APEX_V1) \
   $(ROLLBACK_TEST_APEX_V2)
 LOCAL_MANIFEST_FILE := RollbackTest/AndroidManifest.xml
@@ -103,5 +140,9 @@
 ROLLBACK_TEST_APP_AV1 :=
 ROLLBACK_TEST_APP_AV2 :=
 ROLLBACK_TEST_APP_A_CRASHING_V2 :=
+ROLLBACK_TEST_APP_A_SPLIT_V1 :=
+ROLLBACK_TEST_APP_A_SPLIT_V1_SPLIT :=
+ROLLBACK_TEST_APP_A_SPLIT_V2 :=
+ROLLBACK_TEST_APP_A_SPLIT_V2_SPLIT :=
 ROLLBACK_TEST_APP_BV1 :=
 ROLLBACK_TEST_APP_BV2 :=
diff --git a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java
index bd0881f..a6054e8 100644
--- a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java
+++ b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java
@@ -19,19 +19,18 @@
 import static com.android.tests.rollback.RollbackTestUtils.assertPackageRollbackInfoEquals;
 import static com.android.tests.rollback.RollbackTestUtils.assertRollbackInfoEquals;
 import static com.android.tests.rollback.RollbackTestUtils.getUniqueRollbackInfoForPackage;
+import static com.android.tests.rollback.RollbackTestUtils.processUserData;
 
 import android.Manifest;
 import android.app.ActivityManager;
 import android.content.BroadcastReceiver;
-import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.pm.VersionedPackage;
 import android.content.rollback.RollbackInfo;
 import android.content.rollback.RollbackManager;
-import android.os.Handler;
-import android.os.HandlerThread;
+import android.provider.DeviceConfig;
 import android.support.test.InstrumentationRegistry;
 import android.util.Log;
 
@@ -46,7 +45,6 @@
 
 import java.util.Collections;
 import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.SynchronousQueue;
 import java.util.concurrent.TimeUnit;
 
@@ -331,6 +329,64 @@
     }
 
     /**
+     * Test the scheduling aspect of rollback expiration.
+     */
+    @Test
+    public void testRollbackExpiresAfterLifetime() throws Exception {
+        long expirationTime = TimeUnit.SECONDS.toMillis(30);
+        long defaultExpirationTime = TimeUnit.HOURS.toMillis(48);
+        RollbackManager rm = RollbackTestUtils.getRollbackManager();
+
+        try {
+            RollbackTestUtils.adoptShellPermissionIdentity(
+                    Manifest.permission.INSTALL_PACKAGES,
+                    Manifest.permission.DELETE_PACKAGES,
+                    Manifest.permission.MANAGE_ROLLBACKS,
+                    Manifest.permission.WRITE_DEVICE_CONFIG);
+
+            DeviceConfig.setProperty(DeviceConfig.Rollback.BOOT_NAMESPACE,
+                    DeviceConfig.Rollback.ROLLBACK_LIFETIME_IN_MILLIS,
+                    Long.toString(expirationTime), false /* makeDefault*/);
+
+            // Pull the new expiration time from DeviceConfig
+            rm.reloadPersistedData();
+
+            // Uninstall TEST_APP_A
+            RollbackTestUtils.uninstall(TEST_APP_A);
+            assertEquals(-1, RollbackTestUtils.getInstalledVersion(TEST_APP_A));
+
+            // Install v1 of the app (without rollbacks enabled).
+            RollbackTestUtils.install("RollbackTestAppAv1.apk", false);
+            assertEquals(1, RollbackTestUtils.getInstalledVersion(TEST_APP_A));
+
+            // Upgrade from v1 to v2, with rollbacks enabled.
+            RollbackTestUtils.install("RollbackTestAppAv2.apk", true);
+            assertEquals(2, RollbackTestUtils.getInstalledVersion(TEST_APP_A));
+
+            // Check that the rollback data has not expired
+            Thread.sleep(1000);
+            RollbackInfo rollback = getUniqueRollbackInfoForPackage(
+                    rm.getAvailableRollbacks(), TEST_APP_A);
+            assertRollbackInfoEquals(TEST_APP_A, 2, 1, rollback);
+
+            // Give it a little more time, but still not the long enough to expire
+            Thread.sleep(expirationTime / 2);
+            rollback = getUniqueRollbackInfoForPackage(
+                rm.getAvailableRollbacks(), TEST_APP_A);
+            assertRollbackInfoEquals(TEST_APP_A, 2, 1, rollback);
+
+            // Check that the data has expired after the expiration time (with a buffer of 1 second)
+            Thread.sleep(expirationTime / 2);
+            assertNull(getUniqueRollbackInfoForPackage(rm.getAvailableRollbacks(), TEST_APP_A));
+        } finally {
+            DeviceConfig.setProperty(DeviceConfig.Rollback.BOOT_NAMESPACE,
+                    DeviceConfig.Rollback.ROLLBACK_LIFETIME_IN_MILLIS,
+                    Long.toString(defaultExpirationTime), false /* makeDefault*/);
+            RollbackTestUtils.dropShellPermissionIdentity();
+        }
+    }
+
+    /**
      * Test explicit expiration of rollbacks.
      * Does not test the scheduling aspects of rollback expiration.
      */
@@ -368,52 +424,6 @@
         }
     }
 
-    private static final String NO_RESPONSE = "NO RESPONSE";
-
-    // Calls into the test app to process user data.
-    // Asserts if the user data could not be processed or was version
-    // incompatible with the previously processed user data.
-    private void processUserData(String packageName) throws Exception {
-        Intent intent = new Intent();
-        intent.setComponent(new ComponentName(packageName,
-                    "com.android.tests.rollback.testapp.ProcessUserData"));
-        Context context = InstrumentationRegistry.getContext();
-
-        HandlerThread handlerThread = new HandlerThread("RollbackTestHandlerThread");
-        handlerThread.start();
-
-        // It can sometimes take a while after rollback before the app will
-        // receive this broadcast, so try a few times in a loop.
-        String result = NO_RESPONSE;
-        for (int i = 0; result.equals(NO_RESPONSE) && i < 5; ++i) {
-            BlockingQueue<String> resultQueue = new LinkedBlockingQueue<>();
-            context.sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
-                @Override
-                public void onReceive(Context context, Intent intent) {
-                    if (getResultCode() == 1) {
-                        resultQueue.add("OK");
-                    } else {
-                        // If the test app doesn't receive the broadcast or
-                        // fails to set the result data, then getResultData
-                        // here returns the initial NO_RESPONSE data passed to
-                        // the sendOrderedBroadcast call.
-                        resultQueue.add(getResultData());
-                    }
-                }
-            }, new Handler(handlerThread.getLooper()), 0, NO_RESPONSE, null);
-
-            result = resultQueue.poll(10, TimeUnit.SECONDS);
-            if (result == null) {
-                result = "ProcessUserData broadcast timed out";
-            }
-        }
-
-        handlerThread.quit();
-        if (!"OK".equals(result)) {
-            fail(result);
-        }
-    }
-
     /**
      * Test that app user data is rolled back.
      */
@@ -442,6 +452,39 @@
     }
 
     /**
+     * Test rollback of apks involving splits.
+     */
+    @Test
+    public void testRollbackWithSplits() throws Exception {
+        try {
+            RollbackTestUtils.adoptShellPermissionIdentity(
+                    Manifest.permission.INSTALL_PACKAGES,
+                    Manifest.permission.DELETE_PACKAGES,
+                    Manifest.permission.MANAGE_ROLLBACKS);
+
+            RollbackTestUtils.uninstall(TEST_APP_A);
+            RollbackTestUtils.installSplit(false,
+                    "RollbackTestAppASplitV1.apk",
+                    "RollbackTestAppASplitV1_anydpi.apk");
+            processUserData(TEST_APP_A);
+
+            RollbackTestUtils.installSplit(true,
+                    "RollbackTestAppASplitV2.apk",
+                    "RollbackTestAppASplitV2_anydpi.apk");
+            processUserData(TEST_APP_A);
+
+            RollbackManager rm = RollbackTestUtils.getRollbackManager();
+            RollbackInfo rollback = getUniqueRollbackInfoForPackage(
+                    rm.getAvailableRollbacks(), TEST_APP_A);
+            assertNotNull(rollback);
+            RollbackTestUtils.rollback(rollback.getRollbackId());
+            processUserData(TEST_APP_A);
+        } finally {
+            RollbackTestUtils.dropShellPermissionIdentity();
+        }
+    }
+
+    /**
      * Test restrictions on rollback broadcast sender.
      * A random app should not be able to send a ROLLBACK_COMMITTED broadcast.
      */
diff --git a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTestUtils.java b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTestUtils.java
index def5b8e..2f989f3 100644
--- a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTestUtils.java
+++ b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTestUtils.java
@@ -17,6 +17,7 @@
 package com.android.tests.rollback;
 
 import android.content.BroadcastReceiver;
+import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
@@ -27,12 +28,15 @@
 import android.content.rollback.PackageRollbackInfo;
 import android.content.rollback.RollbackInfo;
 import android.content.rollback.RollbackManager;
+import android.os.Handler;
+import android.os.HandlerThread;
 import android.support.test.InstrumentationRegistry;
 import android.util.Log;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
 
 import java.io.IOException;
 import java.io.InputStream;
@@ -130,6 +134,19 @@
      */
     static void install(String resourceName, boolean enableRollback)
             throws InterruptedException, IOException {
+        installSplit(enableRollback, resourceName);
+    }
+
+    /**
+     * Installs the apk with the given name and its splits.
+     *
+     * @param enableRollback if rollback should be enabled.
+     * @param resourceNames names of class loader resources for the apk and
+     *        its splits to install.
+     * @throws AssertionError if the installation fails.
+     */
+    static void installSplit(boolean enableRollback, String... resourceNames)
+            throws InterruptedException, IOException {
         Context context = InstrumentationRegistry.getContext();
         PackageInstaller.Session session = null;
         PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
@@ -142,12 +159,14 @@
         session = packageInstaller.openSession(sessionId);
 
         ClassLoader loader = RollbackTest.class.getClassLoader();
-        try (OutputStream packageInSession = session.openWrite(resourceName, 0, -1);
-             InputStream is = loader.getResourceAsStream(resourceName);) {
-            byte[] buffer = new byte[4096];
-            int n;
-            while ((n = is.read(buffer)) >= 0) {
-                packageInSession.write(buffer, 0, n);
+        for (String resourceName : resourceNames) {
+            try (OutputStream packageInSession = session.openWrite(resourceName, 0, -1);
+                    InputStream is = loader.getResourceAsStream(resourceName);) {
+                byte[] buffer = new byte[4096];
+                int n;
+                while ((n = is.read(buffer)) >= 0) {
+                    packageInSession.write(buffer, 0, n);
+                }
             }
         }
 
@@ -378,4 +397,53 @@
             throw new AssertionError(e);
         }
     }
+
+    private static final String NO_RESPONSE = "NO RESPONSE";
+
+    /**
+     * Calls into the test app to process user data.
+     * Asserts if the user data could not be processed or was version
+     * incompatible with the previously processed user data.
+     */
+    static void processUserData(String packageName) {
+        Intent intent = new Intent();
+        intent.setComponent(new ComponentName(packageName,
+                    "com.android.tests.rollback.testapp.ProcessUserData"));
+        Context context = InstrumentationRegistry.getContext();
+
+        HandlerThread handlerThread = new HandlerThread("RollbackTestHandlerThread");
+        handlerThread.start();
+
+        // It can sometimes take a while after rollback before the app will
+        // receive this broadcast, so try a few times in a loop.
+        String result = NO_RESPONSE;
+        for (int i = 0; result.equals(NO_RESPONSE) && i < 5; ++i) {
+            BlockingQueue<String> resultQueue = new LinkedBlockingQueue<>();
+            context.sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
+                @Override
+                public void onReceive(Context context, Intent intent) {
+                    if (getResultCode() == 1) {
+                        resultQueue.add("OK");
+                    } else {
+                        // If the test app doesn't receive the broadcast or
+                        // fails to set the result data, then getResultData
+                        // here returns the initial NO_RESPONSE data passed to
+                        // the sendOrderedBroadcast call.
+                        resultQueue.add(getResultData());
+                    }
+                }
+            }, new Handler(handlerThread.getLooper()), 0, NO_RESPONSE, null);
+
+            try {
+                result = resultQueue.take();
+            } catch (InterruptedException e) {
+                throw new AssertionError(e);
+            }
+        }
+
+        handlerThread.quit();
+        if (!"OK".equals(result)) {
+            fail(result);
+        }
+    }
 }
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 b65917b..59ae8d9 100644
--- a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java
+++ b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java
@@ -84,6 +84,7 @@
 
         RollbackTestUtils.install("RollbackTestAppAv1.apk", false);
         assertEquals(1, RollbackTestUtils.getInstalledVersion(TEST_APP_A));
+        RollbackTestUtils.processUserData(TEST_APP_A);
 
         RollbackTestUtils.installStaged(true, "RollbackTestAppAv2.apk");
 
@@ -98,6 +99,7 @@
     @Test
     public void testApkOnlyCommitRollback() throws Exception {
         assertEquals(2, RollbackTestUtils.getInstalledVersion(TEST_APP_A));
+        RollbackTestUtils.processUserData(TEST_APP_A);
 
         RollbackManager rm = RollbackTestUtils.getRollbackManager();
         RollbackInfo rollback = getUniqueRollbackInfoForPackage(
@@ -129,6 +131,7 @@
     @Test
     public void testApkOnlyConfirmRollback() throws Exception {
         assertEquals(1, RollbackTestUtils.getInstalledVersion(TEST_APP_A));
+        RollbackTestUtils.processUserData(TEST_APP_A);
 
         RollbackManager rm = RollbackTestUtils.getRollbackManager();
         RollbackInfo rollback = getUniqueRollbackInfoForPackage(
diff --git a/tests/RollbackTest/TestApp/ACrashingV2.xml b/tests/RollbackTest/TestApp/ACrashingV2.xml
index 5708d23..77bfd4e 100644
--- a/tests/RollbackTest/TestApp/ACrashingV2.xml
+++ b/tests/RollbackTest/TestApp/ACrashingV2.xml
@@ -23,7 +23,6 @@
     <uses-sdk android:minSdkVersion="19" />
 
     <application android:label="Rollback Test App A v2">
-        <meta-data android:name="version" android:value="2" />
         <receiver android:name="com.android.tests.rollback.testapp.ProcessUserData"
                   android:exported="true" />
         <activity android:name="com.android.tests.rollback.testapp.CrashingMainActivity">
diff --git a/tests/RollbackTest/TestApp/Av1.xml b/tests/RollbackTest/TestApp/Av1.xml
index 996d831..63729fb 100644
--- a/tests/RollbackTest/TestApp/Av1.xml
+++ b/tests/RollbackTest/TestApp/Av1.xml
@@ -23,7 +23,6 @@
     <uses-sdk android:minSdkVersion="19" />
 
     <application android:label="Rollback Test App A v1">
-        <meta-data android:name="version" android:value="1" />
         <receiver android:name="com.android.tests.rollback.testapp.ProcessUserData"
                   android:exported="true" />
         <activity android:name="com.android.tests.rollback.testapp.MainActivity">
diff --git a/tests/RollbackTest/TestApp/Av2.xml b/tests/RollbackTest/TestApp/Av2.xml
index 21c7260..f0e909f 100644
--- a/tests/RollbackTest/TestApp/Av2.xml
+++ b/tests/RollbackTest/TestApp/Av2.xml
@@ -23,7 +23,6 @@
     <uses-sdk android:minSdkVersion="19" />
 
     <application android:label="Rollback Test App A v2">
-        <meta-data android:name="version" android:value="2" />
         <receiver android:name="com.android.tests.rollback.testapp.ProcessUserData"
                   android:exported="true" />
         <activity android:name="com.android.tests.rollback.testapp.MainActivity">
diff --git a/tests/RollbackTest/TestApp/Bv1.xml b/tests/RollbackTest/TestApp/Bv1.xml
index de0fd0d..ca9c2ec 100644
--- a/tests/RollbackTest/TestApp/Bv1.xml
+++ b/tests/RollbackTest/TestApp/Bv1.xml
@@ -23,7 +23,6 @@
     <uses-sdk android:minSdkVersion="19" />
 
     <application android:label="Rollback Test App B v1">
-        <meta-data android:name="version" android:value="1" />
         <receiver android:name="com.android.tests.rollback.testapp.ProcessUserData"
                   android:exported="true" />
         <activity android:name="com.android.tests.rollback.testapp.MainActivity">
diff --git a/tests/RollbackTest/TestApp/Bv2.xml b/tests/RollbackTest/TestApp/Bv2.xml
index 6c2e66a..bd3e613 100644
--- a/tests/RollbackTest/TestApp/Bv2.xml
+++ b/tests/RollbackTest/TestApp/Bv2.xml
@@ -23,7 +23,6 @@
     <uses-sdk android:minSdkVersion="19" />
 
     <application android:label="Rollback Test App B v2">
-        <meta-data android:name="version" android:value="2" />
         <receiver android:name="com.android.tests.rollback.testapp.ProcessUserData"
                   android:exported="true" />
         <activity android:name="com.android.tests.rollback.testapp.MainActivity">
diff --git a/tests/RollbackTest/TestApp/res_v1/values-anydpi/values.xml b/tests/RollbackTest/TestApp/res_v1/values-anydpi/values.xml
new file mode 100644
index 0000000..90d3da2
--- /dev/null
+++ b/tests/RollbackTest/TestApp/res_v1/values-anydpi/values.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<resources>
+    <integer name="split_version">1</integer>
+</resources>
diff --git a/tests/RollbackTest/TestApp/res_v1/values/values.xml b/tests/RollbackTest/TestApp/res_v1/values/values.xml
new file mode 100644
index 0000000..0447c74
--- /dev/null
+++ b/tests/RollbackTest/TestApp/res_v1/values/values.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<resources>
+    <integer name="app_version">1</integer>
+    <integer name="split_version">0</integer>
+</resources>
diff --git a/tests/RollbackTest/TestApp/res_v2/values-anydpi/values.xml b/tests/RollbackTest/TestApp/res_v2/values-anydpi/values.xml
new file mode 100644
index 0000000..9a1aa7f
--- /dev/null
+++ b/tests/RollbackTest/TestApp/res_v2/values-anydpi/values.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<resources>
+    <integer name="split_version">2</integer>
+</resources>
diff --git a/tests/RollbackTest/TestApp/res_v2/values/values.xml b/tests/RollbackTest/TestApp/res_v2/values/values.xml
new file mode 100644
index 0000000..fd988f5
--- /dev/null
+++ b/tests/RollbackTest/TestApp/res_v2/values/values.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<resources>
+    <integer name="app_version">2</integer>
+    <integer name="split_version">0</integer>
+</resources>
diff --git a/tests/RollbackTest/TestApp/src/com/android/tests/rollback/testapp/ProcessUserData.java b/tests/RollbackTest/TestApp/src/com/android/tests/rollback/testapp/ProcessUserData.java
index fde6a83..38c658e 100644
--- a/tests/RollbackTest/TestApp/src/com/android/tests/rollback/testapp/ProcessUserData.java
+++ b/tests/RollbackTest/TestApp/src/com/android/tests/rollback/testapp/ProcessUserData.java
@@ -19,9 +19,7 @@
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import android.os.Bundle;
+import android.content.res.Resources;
 
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -35,6 +33,8 @@
  */
 public class ProcessUserData extends BroadcastReceiver {
 
+    private static final String TAG = "RollbackTestApp";
+
     /**
      * Exception thrown in case of issue with user data.
      */
@@ -66,14 +66,19 @@
      * @throws UserDataException in case of problems with app user data.
      */
     public void processUserData(Context context) throws UserDataException {
-        int appVersion = 0;
-        try {
-            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
-                    context.getPackageName(), PackageManager.GET_META_DATA);
-            Bundle bundle = appInfo.metaData;
-            appVersion = bundle.getInt("version");
-        } catch (PackageManager.NameNotFoundException e) {
-            throw new UserDataException("Unable to get app version info", e);
+        Resources res = context.getResources();
+        String packageName = context.getPackageName();
+
+        int appVersionId = res.getIdentifier("app_version", "integer", packageName);
+        int appVersion = res.getInteger(appVersionId);
+
+        int splitVersionId = res.getIdentifier("split_version", "integer", packageName);
+        int splitVersion = res.getInteger(splitVersionId);
+
+        // Make sure the app version and split versions are compatible.
+        if (appVersion != splitVersion) {
+            throw new UserDataException("Split version " + splitVersion
+                    + " does not match app version " + appVersion);
         }
 
         // Read the version of the app's user data and ensure it is compatible
diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java
index ed524f6..1a0e8fa 100644
--- a/tests/net/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java
@@ -17,10 +17,10 @@
 package com.android.server;
 
 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
+import static android.net.ConnectivityManager.NETID_UNSET;
 import static android.net.ConnectivityManager.PRIVATE_DNS_MODE_OFF;
 import static android.net.ConnectivityManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
 import static android.net.ConnectivityManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME;
-import static android.net.ConnectivityManager.NETID_UNSET;
 import static android.net.ConnectivityManager.TYPE_ETHERNET;
 import static android.net.ConnectivityManager.TYPE_MOBILE;
 import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
@@ -125,6 +125,7 @@
 import android.net.NetworkRequest;
 import android.net.NetworkSpecifier;
 import android.net.NetworkStackClient;
+import android.net.NetworkState;
 import android.net.NetworkUtils;
 import android.net.ProxyInfo;
 import android.net.RouteInfo;
@@ -157,6 +158,7 @@
 import android.util.SparseArray;
 
 import com.android.internal.net.VpnConfig;
+import com.android.internal.net.VpnInfo;
 import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.WakeupMessage;
 import com.android.internal.util.test.BroadcastInterceptingContext;
@@ -1828,6 +1830,12 @@
                     fn.test((NetworkCapabilities) cbi.arg));
         }
 
+        void expectLinkPropertiesLike(Predicate<LinkProperties> fn, MockNetworkAgent agent) {
+            CallbackInfo cbi = expectCallback(CallbackState.LINK_PROPERTIES, agent);
+            assertTrue("Received LinkProperties don't match expectations : " + cbi.arg,
+                    fn.test((LinkProperties) cbi.arg));
+        }
+
         void expectBlockedStatusCallback(boolean expectBlocked, MockNetworkAgent agent) {
             CallbackInfo cbi = expectCallback(CallbackState.BLOCKED_STATUS, agent);
             boolean actualBlocked = (boolean) cbi.arg;
@@ -4356,48 +4364,91 @@
         mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
         mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
 
-        Network[] onlyCell = new Network[]{mCellNetworkAgent.getNetwork()};
-        Network[] onlyWifi = new Network[]{mWiFiNetworkAgent.getNetwork()};
+        Network[] onlyCell = new Network[] {mCellNetworkAgent.getNetwork()};
+        Network[] onlyWifi = new Network[] {mWiFiNetworkAgent.getNetwork()};
+
+        LinkProperties cellLp = new LinkProperties();
+        cellLp.setInterfaceName(MOBILE_IFNAME);
+        LinkProperties wifiLp = new LinkProperties();
+        wifiLp.setInterfaceName(WIFI_IFNAME);
 
         // Simple connection should have updated ifaces
         mCellNetworkAgent.connect(false);
+        mCellNetworkAgent.sendLinkProperties(cellLp);
         waitForIdle();
-        verify(mStatsService, atLeastOnce()).forceUpdateIfaces(onlyCell);
+        verify(mStatsService, atLeastOnce())
+                .forceUpdateIfaces(
+                        eq(onlyCell),
+                        eq(new VpnInfo[0]),
+                        any(NetworkState[].class),
+                        eq(MOBILE_IFNAME));
         reset(mStatsService);
 
         // Default network switch should update ifaces.
         mWiFiNetworkAgent.connect(false);
+        mWiFiNetworkAgent.sendLinkProperties(wifiLp);
         waitForIdle();
-        verify(mStatsService, atLeastOnce()).forceUpdateIfaces(onlyWifi);
+        assertEquals(wifiLp, mService.getActiveLinkProperties());
+        verify(mStatsService, atLeastOnce())
+                .forceUpdateIfaces(
+                        eq(onlyWifi),
+                        eq(new VpnInfo[0]),
+                        any(NetworkState[].class),
+                        eq(WIFI_IFNAME));
         reset(mStatsService);
 
         // Disconnect should update ifaces.
         mWiFiNetworkAgent.disconnect();
         waitForIdle();
-        verify(mStatsService, atLeastOnce()).forceUpdateIfaces(onlyCell);
+        verify(mStatsService, atLeastOnce())
+                .forceUpdateIfaces(
+                        eq(onlyCell),
+                        eq(new VpnInfo[0]),
+                        any(NetworkState[].class),
+                        eq(MOBILE_IFNAME));
         reset(mStatsService);
 
         // Metered change should update ifaces
         mCellNetworkAgent.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
         waitForIdle();
-        verify(mStatsService, atLeastOnce()).forceUpdateIfaces(onlyCell);
+        verify(mStatsService, atLeastOnce())
+                .forceUpdateIfaces(
+                        eq(onlyCell),
+                        eq(new VpnInfo[0]),
+                        any(NetworkState[].class),
+                        eq(MOBILE_IFNAME));
         reset(mStatsService);
 
         mCellNetworkAgent.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
         waitForIdle();
-        verify(mStatsService, atLeastOnce()).forceUpdateIfaces(onlyCell);
+        verify(mStatsService, atLeastOnce())
+                .forceUpdateIfaces(
+                        eq(onlyCell),
+                        eq(new VpnInfo[0]),
+                        any(NetworkState[].class),
+                        eq(MOBILE_IFNAME));
         reset(mStatsService);
 
         // Captive portal change shouldn't update ifaces
         mCellNetworkAgent.addCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL);
         waitForIdle();
-        verify(mStatsService, never()).forceUpdateIfaces(onlyCell);
+        verify(mStatsService, never())
+                .forceUpdateIfaces(
+                        eq(onlyCell),
+                        eq(new VpnInfo[0]),
+                        any(NetworkState[].class),
+                        eq(MOBILE_IFNAME));
         reset(mStatsService);
 
         // Roaming change should update ifaces
         mCellNetworkAgent.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
         waitForIdle();
-        verify(mStatsService, atLeastOnce()).forceUpdateIfaces(onlyCell);
+        verify(mStatsService, atLeastOnce())
+                .forceUpdateIfaces(
+                        eq(onlyCell),
+                        eq(new VpnInfo[0]),
+                        any(NetworkState[].class),
+                        eq(MOBILE_IFNAME));
         reset(mStatsService);
     }
 
@@ -5176,6 +5227,9 @@
     public void testStackedLinkProperties() throws UnknownHostException, RemoteException {
         final LinkAddress myIpv4 = new LinkAddress("1.2.3.4/24");
         final LinkAddress myIpv6 = new LinkAddress("2001:db8:1::1/64");
+        final String kNat64PrefixString = "2001:db8:64:64:64:64::";
+        final IpPrefix kNat64Prefix = new IpPrefix(InetAddress.getByName(kNat64PrefixString), 96);
+
         final NetworkRequest networkRequest = new NetworkRequest.Builder()
                 .addTransportType(TRANSPORT_CELLULAR)
                 .addCapability(NET_CAPABILITY_INTERNET)
@@ -5183,8 +5237,9 @@
         final TestNetworkCallback networkCallback = new TestNetworkCallback();
         mCm.registerNetworkCallback(networkRequest, networkCallback);
 
-        // Prepare ipv6 only link properties and connect.
+        // Prepare ipv6 only link properties.
         mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
+        final int cellNetId = mCellNetworkAgent.getNetwork().netId;
         final LinkProperties cellLp = new LinkProperties();
         cellLp.setInterfaceName(MOBILE_IFNAME);
         cellLp.addLinkAddress(myIpv6);
@@ -5194,15 +5249,44 @@
         when(mNetworkManagementService.getInterfaceConfig(CLAT_PREFIX + MOBILE_IFNAME))
                 .thenReturn(getClatInterfaceConfig(myIpv4));
 
-        // Connect with ipv6 link properties, then expect clat setup ipv4 and update link
-        // properties properly.
+        // Connect with ipv6 link properties. Expect prefix discovery to be started.
         mCellNetworkAgent.sendLinkProperties(cellLp);
         mCellNetworkAgent.connect(true);
         networkCallback.expectAvailableThenValidatedCallbacks(mCellNetworkAgent);
-        verify(mMockNetd, times(1)).clatdStart(MOBILE_IFNAME);
-        Nat464Xlat clat = mService.getNat464Xlat(mCellNetworkAgent);
+        verify(mMockNetd, times(1)).resolverStartPrefix64Discovery(cellNetId);
 
-        // Clat iface up, expect stack link updated.
+        // Switching default network updates TCP buffer sizes.
+        verifyTcpBufferSizeChange(ConnectivityService.DEFAULT_TCP_BUFFER_SIZES);
+
+        // Add an IPv4 address. Expect prefix discovery to be stopped. Netd doesn't tell us that
+        // the NAT64 prefix was removed because one was never discovered.
+        cellLp.addLinkAddress(myIpv4);
+        mCellNetworkAgent.sendLinkProperties(cellLp);
+        networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
+        verify(mMockNetd, times(1)).resolverStopPrefix64Discovery(cellNetId);
+
+        verifyNoMoreInteractions(mMockNetd);
+        reset(mMockNetd);
+
+        // Remove IPv4 address. Expect prefix discovery to be started again.
+        cellLp.removeLinkAddress(myIpv4);
+        cellLp.removeRoute(new RouteInfo(myIpv4, null, MOBILE_IFNAME));
+        mCellNetworkAgent.sendLinkProperties(cellLp);
+        networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
+        verify(mMockNetd, times(1)).resolverStartPrefix64Discovery(cellNetId);
+
+        // When NAT64 prefix discovery succeeds, LinkProperties are updated and clatd is started.
+        Nat464Xlat clat = mService.getNat464Xlat(mCellNetworkAgent);
+        assertNull(mCm.getLinkProperties(mCellNetworkAgent.getNetwork()).getNat64Prefix());
+        mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, true /* added */,
+                kNat64PrefixString, 96);
+        LinkProperties lpBeforeClat = (LinkProperties) networkCallback.expectCallback(
+                CallbackState.LINK_PROPERTIES, mCellNetworkAgent).arg;
+        assertEquals(0, lpBeforeClat.getStackedLinks().size());
+        assertEquals(kNat64Prefix, lpBeforeClat.getNat64Prefix());
+        verify(mMockNetd, times(1)).clatdStart(MOBILE_IFNAME, kNat64Prefix.toString());
+
+        // Clat iface comes up. Expect stacked link to be added.
         clat.interfaceLinkStateChanged(CLAT_PREFIX + MOBILE_IFNAME, true);
         networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
         List<LinkProperties> stackedLps = mCm.getLinkProperties(mCellNetworkAgent.getNetwork())
@@ -5219,20 +5303,66 @@
         assertNotEquals(stackedLpsAfterChange, Collections.EMPTY_LIST);
         assertEquals(makeClatLinkProperties(myIpv4), stackedLpsAfterChange.get(0));
 
-        // Add ipv4 address, expect stacked linkproperties be cleaned up
+        // Add ipv4 address, expect that clatd and prefix discovery are stopped and stacked
+        // linkproperties are cleaned up.
         cellLp.addLinkAddress(myIpv4);
         cellLp.addRoute(new RouteInfo(myIpv4, null, MOBILE_IFNAME));
         mCellNetworkAgent.sendLinkProperties(cellLp);
         networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
         verify(mMockNetd, times(1)).clatdStop(MOBILE_IFNAME);
+        verify(mMockNetd, times(1)).resolverStopPrefix64Discovery(cellNetId);
 
-        // Clat iface removed, expect linkproperties revert to original one
-        clat.interfaceRemoved(CLAT_PREFIX + MOBILE_IFNAME);
+        // As soon as stop is called, the linkproperties lose the stacked interface.
         networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
         LinkProperties actualLpAfterIpv4 = mCm.getLinkProperties(mCellNetworkAgent.getNetwork());
-        assertEquals(cellLp, actualLpAfterIpv4);
+        LinkProperties expected = new LinkProperties(cellLp);
+        expected.setNat64Prefix(kNat64Prefix);
+        assertEquals(expected, actualLpAfterIpv4);
+        assertEquals(0, actualLpAfterIpv4.getStackedLinks().size());
 
-        // Clean up
+        // The interface removed callback happens but has no effect after stop is called.
+        clat.interfaceRemoved(CLAT_PREFIX + MOBILE_IFNAME);
+        networkCallback.assertNoCallback();
+
+        verifyNoMoreInteractions(mMockNetd);
+        reset(mMockNetd);
+
+        // Stopping prefix discovery causes netd to tell us that the NAT64 prefix is gone.
+        mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, false /* added */,
+                kNat64PrefixString, 96);
+        networkCallback.expectLinkPropertiesLike((lp) -> lp.getNat64Prefix() == null,
+                mCellNetworkAgent);
+
+        // Remove IPv4 address and expect prefix discovery and clatd to be started again.
+        cellLp.removeLinkAddress(myIpv4);
+        cellLp.removeRoute(new RouteInfo(myIpv4, null, MOBILE_IFNAME));
+        cellLp.removeDnsServer(InetAddress.getByName("8.8.8.8"));
+        mCellNetworkAgent.sendLinkProperties(cellLp);
+        networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
+        verify(mMockNetd, times(1)).resolverStartPrefix64Discovery(cellNetId);
+        mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, true /* added */,
+                kNat64PrefixString, 96);
+        networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
+        verify(mMockNetd, times(1)).clatdStart(MOBILE_IFNAME, kNat64Prefix.toString());
+
+
+        // Clat iface comes up. Expect stacked link to be added.
+        clat.interfaceLinkStateChanged(CLAT_PREFIX + MOBILE_IFNAME, true);
+        networkCallback.expectLinkPropertiesLike(
+                (lp) -> lp.getStackedLinks().size() == 1 && lp.getNat64Prefix() != null,
+                mCellNetworkAgent);
+
+        // NAT64 prefix is removed. Expect that clat is stopped.
+        mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, false /* added */,
+                kNat64PrefixString, 96);
+        networkCallback.expectLinkPropertiesLike(
+                (lp) -> lp.getStackedLinks().size() == 0 && lp.getNat64Prefix() == null,
+                mCellNetworkAgent);
+        verify(mMockNetd, times(1)).clatdStop(MOBILE_IFNAME);
+        networkCallback.expectLinkPropertiesLike((lp) -> lp.getStackedLinks().size() == 0,
+                mCellNetworkAgent);
+
+        // Clean up.
         mCellNetworkAgent.disconnect();
         networkCallback.expectCallback(CallbackState.LOST, mCellNetworkAgent);
         networkCallback.assertNoCallback();
@@ -5313,30 +5443,34 @@
         mCm.unregisterNetworkCallback(networkCallback);
     }
 
-    private static final String TEST_TCP_BUFFER_SIZES = "1,2,3,4,5,6";
-
-    private void verifyTcpBufferSizeChange(String tcpBufferSizes) throws Exception {
+    private void verifyTcpBufferSizeChange(String tcpBufferSizes) {
         String[] values = tcpBufferSizes.split(",");
         String rmemValues = String.join(" ", values[0], values[1], values[2]);
         String wmemValues = String.join(" ", values[3], values[4], values[5]);
         waitForIdle();
-        verify(mMockNetd, atLeastOnce()).setTcpRWmemorySize(rmemValues, wmemValues);
+        try {
+            verify(mMockNetd, atLeastOnce()).setTcpRWmemorySize(rmemValues, wmemValues);
+        } catch (RemoteException e) {
+            fail("mMockNetd should never throw RemoteException");
+        }
         reset(mMockNetd);
     }
 
     @Test
-    public void testTcpBufferReset() throws Exception {
+    public void testTcpBufferReset() {
+        final String testTcpBufferSizes = "1,2,3,4,5,6";
+
         mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
         reset(mMockNetd);
-        // Simple connection should have updated tcp buffer size.
+        // Switching default network updates TCP buffer sizes.
         mCellNetworkAgent.connect(false);
         verifyTcpBufferSizeChange(ConnectivityService.DEFAULT_TCP_BUFFER_SIZES);
 
         // Change link Properties should have updated tcp buffer size.
         LinkProperties lp = new LinkProperties();
-        lp.setTcpBufferSizes(TEST_TCP_BUFFER_SIZES);
+        lp.setTcpBufferSizes(testTcpBufferSizes);
         mCellNetworkAgent.sendLinkProperties(lp);
-        verifyTcpBufferSizeChange(TEST_TCP_BUFFER_SIZES);
+        verifyTcpBufferSizeChange(testTcpBufferSizes);
     }
 
     @Test
diff --git a/tests/net/java/com/android/server/connectivity/Nat464XlatTest.java b/tests/net/java/com/android/server/connectivity/Nat464XlatTest.java
index 07b1d05..37c0df8 100644
--- a/tests/net/java/com/android/server/connectivity/Nat464XlatTest.java
+++ b/tests/net/java/com/android/server/connectivity/Nat464XlatTest.java
@@ -16,9 +16,11 @@
 
 package com.android.server.connectivity;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.inOrder;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoMoreInteractions;
@@ -27,6 +29,7 @@
 import android.net.ConnectivityManager;
 import android.net.INetd;
 import android.net.InterfaceConfiguration;
+import android.net.IpPrefix;
 import android.net.LinkAddress;
 import android.net.LinkProperties;
 import android.net.NetworkInfo;
@@ -43,6 +46,7 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
+import org.mockito.InOrder;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
@@ -53,6 +57,8 @@
     static final String BASE_IFACE = "test0";
     static final String STACKED_IFACE = "v4-test0";
     static final LinkAddress ADDR = new LinkAddress("192.0.2.5/29");
+    static final String NAT64_PREFIX = "64:ff9b::/96";
+    static final int NETID = 42;
 
     @Mock ConnectivityService mConnectivity;
     @Mock NetworkMisc mMisc;
@@ -65,7 +71,11 @@
     Handler mHandler;
 
     Nat464Xlat makeNat464Xlat() {
-        return new Nat464Xlat(mNai, mNetd, mNms);
+        return new Nat464Xlat(mNai, mNetd, mNms) {
+            @Override protected int getNetId() {
+                return NETID;
+            }
+        };
     }
 
     @Before
@@ -87,6 +97,24 @@
         when(mConfig.getLinkAddress()).thenReturn(ADDR);
     }
 
+    private void assertRequiresClat(boolean expected, NetworkAgentInfo nai) {
+        String msg = String.format("requiresClat expected %b for type=%d state=%s skip=%b "
+                + "nat64Prefix=%s addresses=%s", expected, nai.networkInfo.getType(),
+                nai.networkInfo.getDetailedState(),
+                mMisc.skip464xlat, nai.linkProperties.getNat64Prefix(),
+                nai.linkProperties.getLinkAddresses());
+        assertEquals(msg, expected, Nat464Xlat.requiresClat(nai));
+    }
+
+    private void assertShouldStartClat(boolean expected, NetworkAgentInfo nai) {
+        String msg = String.format("shouldStartClat expected %b for type=%d state=%s skip=%b "
+                + "nat64Prefix=%s addresses=%s", expected, nai.networkInfo.getType(),
+                nai.networkInfo.getDetailedState(),
+                mMisc.skip464xlat, nai.linkProperties.getNat64Prefix(),
+                nai.linkProperties.getLinkAddresses());
+        assertEquals(msg, expected, Nat464Xlat.shouldStartClat(nai));
+    }
+
     @Test
     public void testRequiresClat() throws Exception {
         final int[] supportedTypes = {
@@ -102,20 +130,45 @@
             NetworkInfo.DetailedState.SUSPENDED,
         };
 
+        LinkProperties oldLp = new LinkProperties(mNai.linkProperties);
         for (int type : supportedTypes) {
             mNai.networkInfo.setType(type);
             for (NetworkInfo.DetailedState state : supportedDetailedStates) {
                 mNai.networkInfo.setDetailedState(state, "reason", "extraInfo");
-                String msg = String.format("requiresClat expected for type=%d state=%s",
-                        type, state);
+
+                mNai.linkProperties.setNat64Prefix(new IpPrefix("2001:db8:0:64::/96"));
+                assertRequiresClat(false, mNai);
+                assertShouldStartClat(false, mNai);
+
+                mNai.linkProperties.addLinkAddress(new LinkAddress("fc00::1/64"));
+                assertRequiresClat(false, mNai);
+                assertShouldStartClat(false, mNai);
+
+                mNai.linkProperties.addLinkAddress(new LinkAddress("2001:db8::1/64"));
+                assertRequiresClat(true, mNai);
+                assertShouldStartClat(true, mNai);
 
                 mMisc.skip464xlat = true;
-                String errorMsg = msg + String.format(" skip464xlat=%b", mMisc.skip464xlat);
-                assertFalse(errorMsg, Nat464Xlat.requiresClat(mNai));
+                assertRequiresClat(false, mNai);
+                assertShouldStartClat(false, mNai);
 
                 mMisc.skip464xlat = false;
-                errorMsg = msg + String.format(" skip464xlat=%b", mMisc.skip464xlat);
-                assertTrue(errorMsg, Nat464Xlat.requiresClat(mNai));
+                assertRequiresClat(true, mNai);
+                assertShouldStartClat(true, mNai);
+
+                mNai.linkProperties.addLinkAddress(new LinkAddress("192.0.2.2/24"));
+                assertRequiresClat(false, mNai);
+                assertShouldStartClat(false, mNai);
+
+                mNai.linkProperties.removeLinkAddress(new LinkAddress("192.0.2.2/24"));
+                assertRequiresClat(true, mNai);
+                assertShouldStartClat(true, mNai);
+
+                mNai.linkProperties.setNat64Prefix(null);
+                assertRequiresClat(true, mNai);
+                assertShouldStartClat(false, mNai);
+
+                mNai.linkProperties = new LinkProperties(oldLp);
             }
         }
     }
@@ -125,11 +178,13 @@
         Nat464Xlat nat = makeNat464Xlat();
         ArgumentCaptor<LinkProperties> c = ArgumentCaptor.forClass(LinkProperties.class);
 
-        // ConnectivityService starts clat.
+        nat.setNat64Prefix(new IpPrefix(NAT64_PREFIX));
+
+        // Start clat.
         nat.start();
 
         verify(mNms).registerObserver(eq(nat));
-        verify(mNetd).clatdStart(eq(BASE_IFACE));
+        verify(mNetd).clatdStart(eq(BASE_IFACE), eq(NAT64_PREFIX));
 
         // Stacked interface up notification arrives.
         nat.interfaceLinkStateChanged(STACKED_IFACE, true);
@@ -141,22 +196,109 @@
         assertTrue(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
         assertRunning(nat);
 
-        // ConnectivityService stops clat (Network disconnects, IPv4 addr appears, ...).
+        // Stop clat (Network disconnects, IPv4 addr appears, ...).
         nat.stop();
 
         verify(mNetd).clatdStop(eq(BASE_IFACE));
+        verify(mConnectivity, times(2)).handleUpdateLinkProperties(eq(mNai), c.capture());
+        verify(mNms).unregisterObserver(eq(nat));
+        assertTrue(c.getValue().getStackedLinks().isEmpty());
+        assertFalse(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
+        verify(mNetd).resolverStopPrefix64Discovery(eq(NETID));
+        assertIdle(nat);
 
-        // Stacked interface removed notification arrives.
+        // Stacked interface removed notification arrives and is ignored.
         nat.interfaceRemoved(STACKED_IFACE);
         mLooper.dispatchNext();
 
-        verify(mNms).unregisterObserver(eq(nat));
-        verify(mConnectivity, times(2)).handleUpdateLinkProperties(eq(mNai), c.capture());
+        verifyNoMoreInteractions(mNetd, mNms, mConnectivity);
+    }
+
+    private void checkStartStopStart(boolean interfaceRemovedFirst) throws Exception {
+        Nat464Xlat nat = makeNat464Xlat();
+        ArgumentCaptor<LinkProperties> c = ArgumentCaptor.forClass(LinkProperties.class);
+        InOrder inOrder = inOrder(mNetd, mConnectivity);
+
+        nat.setNat64Prefix(new IpPrefix(NAT64_PREFIX));
+
+        nat.start();
+
+        inOrder.verify(mNetd).clatdStart(eq(BASE_IFACE), eq(NAT64_PREFIX));
+
+        // Stacked interface up notification arrives.
+        nat.interfaceLinkStateChanged(STACKED_IFACE, true);
+        mLooper.dispatchNext();
+
+        inOrder.verify(mConnectivity).handleUpdateLinkProperties(eq(mNai), c.capture());
+        assertFalse(c.getValue().getStackedLinks().isEmpty());
+        assertTrue(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
+        assertRunning(nat);
+
+        // ConnectivityService stops clat (Network disconnects, IPv4 addr appears, ...).
+        nat.stop();
+
+        inOrder.verify(mNetd).clatdStop(eq(BASE_IFACE));
+
+        inOrder.verify(mConnectivity, times(1)).handleUpdateLinkProperties(eq(mNai), c.capture());
         assertTrue(c.getValue().getStackedLinks().isEmpty());
         assertFalse(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
         assertIdle(nat);
 
-        verifyNoMoreInteractions(mNetd, mNms, mConnectivity);
+        if (interfaceRemovedFirst) {
+            // Stacked interface removed notification arrives and is ignored.
+            nat.interfaceRemoved(STACKED_IFACE);
+            mLooper.dispatchNext();
+            nat.interfaceLinkStateChanged(STACKED_IFACE, false);
+            mLooper.dispatchNext();
+        }
+
+        assertTrue(c.getValue().getStackedLinks().isEmpty());
+        assertFalse(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
+        assertIdle(nat);
+        inOrder.verifyNoMoreInteractions();
+
+        nat.start();
+
+        inOrder.verify(mNetd).clatdStart(eq(BASE_IFACE), eq(NAT64_PREFIX));
+
+        if (!interfaceRemovedFirst) {
+            // Stacked interface removed notification arrives and is ignored.
+            nat.interfaceRemoved(STACKED_IFACE);
+            mLooper.dispatchNext();
+            nat.interfaceLinkStateChanged(STACKED_IFACE, false);
+            mLooper.dispatchNext();
+        }
+
+        // Stacked interface up notification arrives.
+        nat.interfaceLinkStateChanged(STACKED_IFACE, true);
+        mLooper.dispatchNext();
+
+        inOrder.verify(mConnectivity).handleUpdateLinkProperties(eq(mNai), c.capture());
+        assertFalse(c.getValue().getStackedLinks().isEmpty());
+        assertTrue(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
+        assertRunning(nat);
+
+        // ConnectivityService stops clat again.
+        nat.stop();
+
+        inOrder.verify(mNetd).clatdStop(eq(BASE_IFACE));
+
+        inOrder.verify(mConnectivity, times(1)).handleUpdateLinkProperties(eq(mNai), c.capture());
+        assertTrue(c.getValue().getStackedLinks().isEmpty());
+        assertFalse(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
+        assertIdle(nat);
+
+        inOrder.verifyNoMoreInteractions();
+    }
+
+    @Test
+    public void testStartStopStart() throws Exception {
+        checkStartStopStart(true);
+    }
+
+    @Test
+    public void testStartStopStartBeforeInterfaceRemoved() throws Exception {
+        checkStartStopStart(false);
     }
 
     @Test
@@ -164,11 +306,12 @@
         Nat464Xlat nat = makeNat464Xlat();
         ArgumentCaptor<LinkProperties> c = ArgumentCaptor.forClass(LinkProperties.class);
 
-        // ConnectivityService starts clat.
+        nat.setNat64Prefix(new IpPrefix(NAT64_PREFIX));
+
         nat.start();
 
         verify(mNms).registerObserver(eq(nat));
-        verify(mNetd).clatdStart(eq(BASE_IFACE));
+        verify(mNetd).clatdStart(eq(BASE_IFACE), eq(NAT64_PREFIX));
 
         // Stacked interface up notification arrives.
         nat.interfaceLinkStateChanged(STACKED_IFACE, true);
@@ -184,9 +327,10 @@
         nat.interfaceRemoved(STACKED_IFACE);
         mLooper.dispatchNext();
 
-        verify(mNms).unregisterObserver(eq(nat));
         verify(mNetd).clatdStop(eq(BASE_IFACE));
         verify(mConnectivity, times(2)).handleUpdateLinkProperties(eq(mNai), c.capture());
+        verify(mNms).unregisterObserver(eq(nat));
+        verify(mNetd).resolverStopPrefix64Discovery(eq(NETID));
         assertTrue(c.getValue().getStackedLinks().isEmpty());
         assertFalse(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
         assertIdle(nat);
@@ -201,24 +345,25 @@
     public void testStopBeforeClatdStarts() throws Exception {
         Nat464Xlat nat = makeNat464Xlat();
 
-        // ConnectivityService starts clat.
+        nat.setNat64Prefix(new IpPrefix(NAT64_PREFIX));
+
         nat.start();
 
         verify(mNms).registerObserver(eq(nat));
-        verify(mNetd).clatdStart(eq(BASE_IFACE));
+        verify(mNetd).clatdStart(eq(BASE_IFACE), eq(NAT64_PREFIX));
 
         // ConnectivityService immediately stops clat (Network disconnects, IPv4 addr appears, ...)
         nat.stop();
 
-        verify(mNms).unregisterObserver(eq(nat));
         verify(mNetd).clatdStop(eq(BASE_IFACE));
+        verify(mNms).unregisterObserver(eq(nat));
+        verify(mNetd).resolverStopPrefix64Discovery(eq(NETID));
         assertIdle(nat);
 
         // In-flight interface up notification arrives: no-op
         nat.interfaceLinkStateChanged(STACKED_IFACE, true);
         mLooper.dispatchNext();
 
-
         // Interface removed notification arrives after stopClatd() takes effect: no-op.
         nat.interfaceRemoved(STACKED_IFACE);
         mLooper.dispatchNext();
@@ -232,17 +377,19 @@
     public void testStopAndClatdNeverStarts() throws Exception {
         Nat464Xlat nat = makeNat464Xlat();
 
-        // ConnectivityService starts clat.
+        nat.setNat64Prefix(new IpPrefix(NAT64_PREFIX));
+
         nat.start();
 
         verify(mNms).registerObserver(eq(nat));
-        verify(mNetd).clatdStart(eq(BASE_IFACE));
+        verify(mNetd).clatdStart(eq(BASE_IFACE), eq(NAT64_PREFIX));
 
         // ConnectivityService immediately stops clat (Network disconnects, IPv4 addr appears, ...)
         nat.stop();
 
-        verify(mNms).unregisterObserver(eq(nat));
         verify(mNetd).clatdStop(eq(BASE_IFACE));
+        verify(mNms).unregisterObserver(eq(nat));
+        verify(mNetd).resolverStopPrefix64Discovery(eq(NETID));
         assertIdle(nat);
 
         verifyNoMoreInteractions(mNetd, mNms, mConnectivity);
diff --git a/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java b/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
index f89f303..d91d3eb 100644
--- a/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
+++ b/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
@@ -70,7 +70,6 @@
 import android.content.Context;
 import android.content.Intent;
 import android.net.DataUsageRequest;
-import android.net.IConnectivityManager;
 import android.net.INetworkManagementEventObserver;
 import android.net.INetworkStatsSession;
 import android.net.LinkProperties;
@@ -163,7 +162,6 @@
 
     private @Mock INetworkManagementService mNetManager;
     private @Mock NetworkStatsSettings mSettings;
-    private @Mock IConnectivityManager mConnManager;
     private @Mock IBinder mBinder;
     private @Mock AlarmManager mAlarmManager;
     private HandlerThread mHandlerThread;
@@ -205,7 +203,6 @@
         Handler.Callback callback = new NetworkStatsService.HandlerCallback(mService);
         mHandler = new Handler(mHandlerThread.getLooper(), callback);
         mService.setHandler(mHandler, callback);
-        mService.bindConnectivityManager(mConnManager);
 
         mElapsedRealtime = 0L;
 
@@ -234,7 +231,6 @@
 
         mNetManager = null;
         mSettings = null;
-        mConnManager = null;
 
         mSession.close();
         mService = null;
@@ -245,12 +241,12 @@
         // pretend that wifi network comes online; service should ask about full
         // network state, and poll any existing interfaces before updating.
         expectDefaultSettings();
-        expectNetworkState(buildWifiState());
+        NetworkState[] states = new NetworkState[] {buildWifiState()};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_WIFI);
+        mService.forceUpdateIfaces(NETWORKS_WIFI, new VpnInfo[0], states, getActiveIface(states));
 
         // verify service has empty history for wifi
         assertNetworkTotal(sTemplateWifi, 0L, 0L, 0L, 0L, 0);
@@ -289,12 +285,12 @@
         // pretend that wifi network comes online; service should ask about full
         // network state, and poll any existing interfaces before updating.
         expectDefaultSettings();
-        expectNetworkState(buildWifiState());
+        NetworkState[] states = new NetworkState[] {buildWifiState()};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_WIFI);
+        mService.forceUpdateIfaces(NETWORKS_WIFI, new VpnInfo[0], states, getActiveIface(states));
 
         // verify service has empty history for wifi
         assertNetworkTotal(sTemplateWifi, 0L, 0L, 0L, 0L, 0);
@@ -363,12 +359,12 @@
         // pretend that wifi network comes online; service should ask about full
         // network state, and poll any existing interfaces before updating.
         expectSettings(0L, HOUR_IN_MILLIS, WEEK_IN_MILLIS);
-        expectNetworkState(buildWifiState());
+        NetworkState[] states = new NetworkState[] {buildWifiState()};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_WIFI);
+        mService.forceUpdateIfaces(NETWORKS_WIFI, new VpnInfo[0], states, getActiveIface(states));
 
 
         // modify some number on wifi, and trigger poll event
@@ -405,12 +401,12 @@
     public void testUidStatsAcrossNetworks() throws Exception {
         // pretend first mobile network comes online
         expectDefaultSettings();
-        expectNetworkState(buildMobile3gState(IMSI_1));
+        NetworkState[] states = new NetworkState[] {buildMobile3gState(IMSI_1)};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_MOBILE);
+        mService.forceUpdateIfaces(NETWORKS_MOBILE, new VpnInfo[0], states, getActiveIface(states));
 
 
         // create some traffic on first network
@@ -437,7 +433,7 @@
         // disappearing, to verify we don't count backwards.
         incrementCurrentTime(HOUR_IN_MILLIS);
         expectDefaultSettings();
-        expectNetworkState(buildMobile3gState(IMSI_2));
+        states = new NetworkState[] {buildMobile3gState(IMSI_2)};
         expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1)
                 .addIfaceValues(TEST_IFACE, 2048L, 16L, 512L, 4L));
         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 3)
@@ -446,7 +442,7 @@
                 .addValues(TEST_IFACE, UID_BLUE, SET_DEFAULT, TAG_NONE, 512L, 4L, 0L, 0L, 0L));
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_MOBILE);
+        mService.forceUpdateIfaces(NETWORKS_MOBILE, new VpnInfo[0], states, getActiveIface(states));
         forcePollAndWaitForIdle();
 
 
@@ -481,12 +477,12 @@
     public void testUidRemovedIsMoved() throws Exception {
         // pretend that network comes online
         expectDefaultSettings();
-        expectNetworkState(buildWifiState());
+        NetworkState[] states = new NetworkState[] {buildWifiState()};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_WIFI);
+        mService.forceUpdateIfaces(NETWORKS_WIFI, new VpnInfo[0], states, getActiveIface(states));
 
 
         // create some traffic
@@ -540,12 +536,12 @@
     public void testUid3g4gCombinedByTemplate() throws Exception {
         // pretend that network comes online
         expectDefaultSettings();
-        expectNetworkState(buildMobile3gState(IMSI_1));
+        NetworkState[] states = new NetworkState[] {buildMobile3gState(IMSI_1)};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_MOBILE);
+        mService.forceUpdateIfaces(NETWORKS_MOBILE, new VpnInfo[0], states, getActiveIface(states));
 
 
         // create some traffic
@@ -566,14 +562,14 @@
         // now switch over to 4g network
         incrementCurrentTime(HOUR_IN_MILLIS);
         expectDefaultSettings();
-        expectNetworkState(buildMobile4gState(TEST_IFACE2));
+        states = new NetworkState[] {buildMobile4gState(TEST_IFACE2)};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 1)
                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 1024L, 8L, 1024L, 8L, 0L)
                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 512L, 4L, 512L, 4L, 0L));
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_MOBILE);
+        mService.forceUpdateIfaces(NETWORKS_MOBILE, new VpnInfo[0], states, getActiveIface(states));
         forcePollAndWaitForIdle();
 
 
@@ -598,12 +594,12 @@
     public void testSummaryForAllUid() throws Exception {
         // pretend that network comes online
         expectDefaultSettings();
-        expectNetworkState(buildWifiState());
+        NetworkState[] states = new NetworkState[] {buildWifiState()};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_WIFI);
+        mService.forceUpdateIfaces(NETWORKS_WIFI, new VpnInfo[0], states, getActiveIface(states));
 
 
         // create some traffic for two apps
@@ -657,12 +653,12 @@
     public void testDetailedUidStats() throws Exception {
         // pretend that network comes online
         expectDefaultSettings();
-        expectNetworkState(buildWifiState());
+        NetworkState[] states = new NetworkState[] {buildWifiState()};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_WIFI);
+        mService.forceUpdateIfaces(NETWORKS_WIFI, new VpnInfo[0], states, getActiveIface(states));
 
         NetworkStats.Entry entry1 = new NetworkStats.Entry(
                 TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 50L, 5L, 50L, 5L, 0L);
@@ -700,13 +696,13 @@
         stackedProp.setInterfaceName(stackedIface);
         final NetworkState wifiState = buildWifiState();
         wifiState.linkProperties.addStackedLink(stackedProp);
-        expectNetworkState(wifiState);
+        NetworkState[] states = new NetworkState[] {wifiState};
 
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_WIFI);
+        mService.forceUpdateIfaces(NETWORKS_WIFI, new VpnInfo[0], states, getActiveIface(states));
 
         NetworkStats.Entry uidStats = new NetworkStats.Entry(
                 TEST_IFACE, UID_BLUE, SET_DEFAULT, 0xF00D, 1024L, 8L, 512L, 4L, 0L);
@@ -745,12 +741,12 @@
     public void testForegroundBackground() throws Exception {
         // pretend that network comes online
         expectDefaultSettings();
-        expectNetworkState(buildWifiState());
+        NetworkState[] states = new NetworkState[] {buildWifiState()};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_WIFI);
+        mService.forceUpdateIfaces(NETWORKS_WIFI, new VpnInfo[0], states, getActiveIface(states));
 
 
         // create some initial traffic
@@ -803,12 +799,12 @@
     public void testMetered() throws Exception {
         // pretend that network comes online
         expectDefaultSettings();
-        expectNetworkState(buildWifiState(true /* isMetered */));
+        NetworkState[] states = new NetworkState[] {buildWifiState(true /* isMetered */)};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_WIFI);
+        mService.forceUpdateIfaces(NETWORKS_WIFI, new VpnInfo[0], states, getActiveIface(states));
 
 
         // create some initial traffic
@@ -843,12 +839,13 @@
     public void testRoaming() throws Exception {
         // pretend that network comes online
         expectDefaultSettings();
-        expectNetworkState(buildMobile3gState(IMSI_1, true /* isRoaming */));
+        NetworkState[] states =
+            new NetworkState[] {buildMobile3gState(IMSI_1, true /* isRoaming */)};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_MOBILE);
+        mService.forceUpdateIfaces(NETWORKS_MOBILE, new VpnInfo[0], states, getActiveIface(states));
 
 
         // Create some traffic
@@ -882,12 +879,12 @@
     public void testTethering() throws Exception {
         // pretend first mobile network comes online
         expectDefaultSettings();
-        expectNetworkState(buildMobile3gState(IMSI_1));
+        NetworkState[] states = new NetworkState[] {buildMobile3gState(IMSI_1)};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_MOBILE);
+        mService.forceUpdateIfaces(NETWORKS_MOBILE, new VpnInfo[0], states, getActiveIface(states));
 
 
         // create some tethering traffic
@@ -925,12 +922,12 @@
         // pretend that wifi network comes online; service should ask about full
         // network state, and poll any existing interfaces before updating.
         expectDefaultSettings();
-        expectNetworkState(buildWifiState());
+        NetworkState[] states = new NetworkState[] {buildWifiState()};
         expectNetworkStatsSummary(buildEmptyStats());
         expectNetworkStatsUidDetail(buildEmptyStats());
         expectBandwidthControlCheck();
 
-        mService.forceUpdateIfaces(NETWORKS_WIFI);
+        mService.forceUpdateIfaces(NETWORKS_WIFI, new VpnInfo[0], states, getActiveIface(states));
 
         // verify service has empty history for wifi
         assertNetworkTotal(sTemplateWifi, 0L, 0L, 0L, 0L, 0);
@@ -1077,11 +1074,11 @@
         expectBandwidthControlCheck();
     }
 
-    private void expectNetworkState(NetworkState... state) throws Exception {
-        when(mConnManager.getAllNetworkState()).thenReturn(state);
-
-        final LinkProperties linkProp = state.length > 0 ? state[0].linkProperties : null;
-        when(mConnManager.getActiveLinkProperties()).thenReturn(linkProp);
+    private String getActiveIface(NetworkState... states) throws Exception {
+        if (states == null || states.length == 0 || states[0].linkProperties == null) {
+            return null;
+        }
+        return states[0].linkProperties.getInterfaceName();
     }
 
     private void expectNetworkStatsSummary(NetworkStats summary) throws Exception {
@@ -1090,8 +1087,6 @@
 
     private void expectNetworkStatsSummary(NetworkStats summary, NetworkStats tetherStats)
             throws Exception {
-        when(mConnManager.getAllVpnInfo()).thenReturn(new VpnInfo[0]);
-
         expectNetworkStatsTethering(STATS_PER_IFACE, tetherStats);
         expectNetworkStatsSummaryDev(summary.clone());
         expectNetworkStatsSummaryXt(summary.clone());
diff --git a/tests/testables/Android.bp b/tests/testables/Android.bp
index f07f09d..0bad7a4 100644
--- a/tests/testables/Android.bp
+++ b/tests/testables/Android.bp
@@ -25,7 +25,7 @@
     libs: [
         "android.test.runner",
         "android.test.mock",
-        "android-support-test",
+        "androidx.test.rules",
         "mockito-target-inline-minus-junit4",
     ],
 
diff --git a/tests/testables/src/android/testing/AndroidTestingRunner.java b/tests/testables/src/android/testing/AndroidTestingRunner.java
index cf5d4cf..0375220 100644
--- a/tests/testables/src/android/testing/AndroidTestingRunner.java
+++ b/tests/testables/src/android/testing/AndroidTestingRunner.java
@@ -14,13 +14,13 @@
 
 package android.testing;
 
-import android.support.test.internal.runner.junit4.statement.RunAfters;
-import android.support.test.internal.runner.junit4.statement.RunBefores;
-import android.support.test.internal.runner.junit4.statement.UiThreadStatement;
-
 import android.testing.TestableLooper.LooperFrameworkMethod;
 import android.testing.TestableLooper.RunWithLooper;
 
+import androidx.test.internal.runner.junit4.statement.RunAfters;
+import androidx.test.internal.runner.junit4.statement.RunBefores;
+import androidx.test.internal.runner.junit4.statement.UiThreadStatement;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
diff --git a/tests/testables/src/android/testing/BaseFragmentTest.java b/tests/testables/src/android/testing/BaseFragmentTest.java
index d18c126..9f60cce 100644
--- a/tests/testables/src/android/testing/BaseFragmentTest.java
+++ b/tests/testables/src/android/testing/BaseFragmentTest.java
@@ -26,13 +26,14 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Parcelable;
-import android.support.test.InstrumentationRegistry;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.WindowManager;
 import android.view.WindowManager.LayoutParams;
 import android.widget.FrameLayout;
 
+import androidx.test.InstrumentationRegistry;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
diff --git a/tests/testables/src/android/testing/TestableInstrumentation.java b/tests/testables/src/android/testing/TestableInstrumentation.java
index c35dc68..ed867c1 100644
--- a/tests/testables/src/android/testing/TestableInstrumentation.java
+++ b/tests/testables/src/android/testing/TestableInstrumentation.java
@@ -19,9 +19,10 @@
 import android.os.Looper;
 import android.os.Message;
 import android.os.TestLooperManager;
-import android.support.test.runner.AndroidJUnitRunner;
 import android.util.Log;
 
+import androidx.test.runner.AndroidJUnitRunner;
+
 import java.util.ArrayList;
 
 /**
diff --git a/tests/testables/src/android/testing/TestableLooper.java b/tests/testables/src/android/testing/TestableLooper.java
index 8b4cba1..8d99ac7 100644
--- a/tests/testables/src/android/testing/TestableLooper.java
+++ b/tests/testables/src/android/testing/TestableLooper.java
@@ -20,9 +20,10 @@
 import android.os.Message;
 import android.os.MessageQueue;
 import android.os.TestLooperManager;
-import android.support.test.InstrumentationRegistry;
 import android.util.ArrayMap;
 
+import androidx.test.InstrumentationRegistry;
+
 import org.junit.runners.model.FrameworkMethod;
 
 import java.lang.annotation.ElementType;
diff --git a/tests/testables/src/android/testing/ViewUtils.java b/tests/testables/src/android/testing/ViewUtils.java
index 1c6016e..80c2e8d 100644
--- a/tests/testables/src/android/testing/ViewUtils.java
+++ b/tests/testables/src/android/testing/ViewUtils.java
@@ -16,7 +16,6 @@
 
 import android.content.pm.ApplicationInfo;
 import android.graphics.PixelFormat;
-import android.support.test.InstrumentationRegistry;
 import android.view.View;
 import android.view.WindowManager;
 import android.view.WindowManager.LayoutParams;
diff --git a/tests/testables/tests/Android.mk b/tests/testables/tests/Android.mk
index 79469e3..16fbb18 100644
--- a/tests/testables/tests/Android.mk
+++ b/tests/testables/tests/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
-    android-support-test \
+    androidx.test.rules hamcrest-library \
     mockito-target-inline-minus-junit4 \
 	testables
 
diff --git a/tests/testables/tests/AndroidManifest.xml b/tests/testables/tests/AndroidManifest.xml
index 61f0be6..2bfb04f 100644
--- a/tests/testables/tests/AndroidManifest.xml
+++ b/tests/testables/tests/AndroidManifest.xml
@@ -25,7 +25,7 @@
         <uses-library android:name="android.test.runner" />
     </application>
 
-    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
         android:targetPackage="com.android.testables"
         android:label="Tests for Testables">
     </instrumentation>
diff --git a/tests/testables/tests/src/android/testing/DexmakerShareClassLoaderRuleTest.java b/tests/testables/tests/src/android/testing/DexmakerShareClassLoaderRuleTest.java
index 2528d09..13addb1 100644
--- a/tests/testables/tests/src/android/testing/DexmakerShareClassLoaderRuleTest.java
+++ b/tests/testables/tests/src/android/testing/DexmakerShareClassLoaderRuleTest.java
@@ -22,8 +22,8 @@
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.fail;
 
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
diff --git a/tests/testables/tests/src/android/testing/TestableContentResolverTest.java b/tests/testables/tests/src/android/testing/TestableContentResolverTest.java
index 71afda0..f531369 100644
--- a/tests/testables/tests/src/android/testing/TestableContentResolverTest.java
+++ b/tests/testables/tests/src/android/testing/TestableContentResolverTest.java
@@ -2,8 +2,9 @@
 
 import android.content.ContentProvider;
 import android.content.IContentProvider;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.filters.SmallTest;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
 
 import org.junit.Assert;
 import org.junit.Before;
diff --git a/tests/testables/tests/src/android/testing/TestablePermissionsTest.java b/tests/testables/tests/src/android/testing/TestablePermissionsTest.java
index c56146e..4626de7 100644
--- a/tests/testables/tests/src/android/testing/TestablePermissionsTest.java
+++ b/tests/testables/tests/src/android/testing/TestablePermissionsTest.java
@@ -20,11 +20,10 @@
 import static org.junit.Assert.assertEquals;
 
 import android.Manifest.permission;
-import android.content.pm.PackageManager;
 import android.net.Uri;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.filters.SmallTest;
-import android.testing.TestableLooper.RunWithLooper;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
 
 import org.junit.Rule;
 import org.junit.Test;
diff --git a/tests/testables/tests/src/android/testing/TestableResourcesTest.java b/tests/testables/tests/src/android/testing/TestableResourcesTest.java
index dc7cf95..dd4325c 100644
--- a/tests/testables/tests/src/android/testing/TestableResourcesTest.java
+++ b/tests/testables/tests/src/android/testing/TestableResourcesTest.java
@@ -21,9 +21,10 @@
 import static org.junit.Assert.fail;
 
 import android.content.res.Resources;
-import android.support.test.InstrumentationRegistry;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.InstrumentationRegistry;
+
 import com.android.testables.R;
 
 import org.junit.Rule;
diff --git a/tests/testables/tests/src/android/testing/TestableSettingsProviderTest.java b/tests/testables/tests/src/android/testing/TestableSettingsProviderTest.java
index ac61deb..0333d51 100644
--- a/tests/testables/tests/src/android/testing/TestableSettingsProviderTest.java
+++ b/tests/testables/tests/src/android/testing/TestableSettingsProviderTest.java
@@ -14,20 +14,22 @@
 
 package android.testing;
 
+import static org.junit.Assert.*;
+
 import android.content.ContentResolver;
 import android.provider.Settings;
 import android.provider.Settings.Global;
 import android.provider.Settings.Secure;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import static org.junit.Assert.*;
-
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class TestableSettingsProviderTest {
diff --git a/tools/aapt2/ResourceUtils.cpp b/tools/aapt2/ResourceUtils.cpp
index 0032960..ffc1a92 100644
--- a/tools/aapt2/ResourceUtils.cpp
+++ b/tools/aapt2/ResourceUtils.cpp
@@ -44,6 +44,7 @@
 
 Maybe<ResourceName> ToResourceName(
     const android::ResTable::resource_name& name_in) {
+  // TODO: Remove this when ResTable and AssetManager(1) are removed from AAPT2
   ResourceName name_out;
   if (!name_in.package) {
     return {};
@@ -79,6 +80,41 @@
   return name_out;
 }
 
+Maybe<ResourceName> ToResourceName(const android::AssetManager2::ResourceName& name_in) {
+  ResourceName name_out;
+  if (!name_in.package) {
+    return {};
+  }
+
+  name_out.package = std::string(name_in.package, name_in.package_len);
+
+  const ResourceType* type;
+  if (name_in.type16) {
+    type = ParseResourceType(
+        util::Utf16ToUtf8(StringPiece16(name_in.type16, name_in.type_len)));
+  } else if (name_in.type) {
+    type = ParseResourceType(StringPiece(name_in.type, name_in.type_len));
+  } else {
+    return {};
+  }
+
+  if (!type) {
+    return {};
+  }
+
+  name_out.type = *type;
+
+  if (name_in.entry16) {
+    name_out.entry =
+        util::Utf16ToUtf8(StringPiece16(name_in.entry16, name_in.entry_len));
+  } else if (name_in.entry) {
+    name_out.entry = std::string(name_in.entry, name_in.entry_len);
+  } else {
+    return {};
+  }
+  return name_out;
+}
+
 bool ParseResourceName(const StringPiece& str, ResourceNameRef* out_ref,
                        bool* out_private) {
   if (str.empty()) {
diff --git a/tools/aapt2/ResourceUtils.h b/tools/aapt2/ResourceUtils.h
index e282fd58..a8a3120 100644
--- a/tools/aapt2/ResourceUtils.h
+++ b/tools/aapt2/ResourceUtils.h
@@ -20,6 +20,7 @@
 #include <functional>
 #include <memory>
 
+#include "androidfw/AssetManager2.h"
 #include "androidfw/ConfigDescription.h"
 #include "androidfw/ResourceTypes.h"
 #include "androidfw/StringPiece.h"
@@ -78,6 +79,12 @@
     const android::ResTable::resource_name& name);
 
 /**
+ * Convert an android::AssetManager2::ResourceName to an aapt::ResourceName struct.
+ */
+Maybe<ResourceName> ToResourceName(
+    const android::AssetManager2::ResourceName& name_in);
+
+/**
  * Returns a boolean value if the string is equal to TRUE, true, True, FALSE,
  * false, or False.
  */
diff --git a/tools/aapt2/cmd/Compile.cpp b/tools/aapt2/cmd/Compile.cpp
index 0512bdc..bec6c69 100644
--- a/tools/aapt2/cmd/Compile.cpp
+++ b/tools/aapt2/cmd/Compile.cpp
@@ -769,7 +769,10 @@
     auto collection = util::make_unique<io::FileCollection>();
 
     // Collect data from the path for each input file.
-    for (const std::string& arg : args) {
+    std::vector<std::string> sorted_args = args;
+    std::sort(sorted_args.begin(), sorted_args.end());
+
+    for (const std::string& arg : sorted_args) {
       collection->InsertFile(arg);
     }
 
diff --git a/tools/aapt2/cmd/Link.cpp b/tools/aapt2/cmd/Link.cpp
index 22edd2f..a7b8d25 100644
--- a/tools/aapt2/cmd/Link.cpp
+++ b/tools/aapt2/cmd/Link.cpp
@@ -717,28 +717,20 @@
   return true;
 }
 
-static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
+static android::ApkAssetsCookie FindFrameworkAssetManagerCookie(
+    const android::AssetManager2& assets) {
   using namespace android;
 
   // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
   // we're looking for the first attribute resource in the system package.
-  const ResTable& table = assets.getResources(true);
-  Res_value val;
-  ssize_t idx = table.getResource(0x01010000, &val, true);
-  if (idx != NO_ERROR) {
-    // Try as a bag.
-    const ResTable::bag_entry* entry;
-    ssize_t cnt = table.lockBag(0x01010000, &entry);
-    if (cnt >= 0) {
-      idx = entry->stringBlock;
-    }
-    table.unlockBag(entry);
-  }
+  Res_value val{};
+  ResTable_config config{};
+  uint32_t type_spec_flags;
+  ApkAssetsCookie idx = assets.GetResource(0x01010000, true /** may_be_bag */,
+                                           0 /** density_override */, &val, &config,
+                                           &type_spec_flags);
 
-  if (idx < 0) {
-    return 0;
-  }
-  return table.getTableCookie(idx);
+  return idx;
 }
 
 class Linker {
@@ -750,17 +742,17 @@
         file_collection_(util::make_unique<io::FileCollection>()) {
   }
 
-  void ExtractCompileSdkVersions(android::AssetManager* assets) {
+  void ExtractCompileSdkVersions(android::AssetManager2* assets) {
     using namespace android;
 
-    int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
-    if (cookie == 0) {
+    android::ApkAssetsCookie cookie = FindFrameworkAssetManagerCookie(*assets);
+    if (cookie == android::kInvalidCookie) {
       // No Framework assets loaded. Not a failure.
       return;
     }
 
     std::unique_ptr<Asset> manifest(
-        assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
+        assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
     if (manifest == nullptr) {
       // No errors.
       return;
diff --git a/tools/aapt2/io/FileSystem.cpp b/tools/aapt2/io/FileSystem.cpp
index 51cc903..e15f935 100644
--- a/tools/aapt2/io/FileSystem.cpp
+++ b/tools/aapt2/io/FileSystem.cpp
@@ -79,6 +79,7 @@
     return nullptr;
   }
 
+  std::vector<std::string> sorted_files;
   while (struct dirent *entry = readdir(d.get())) {
     std::string prefix_path = root.to_string();
     file::AppendPath(&prefix_path, entry->d_name);
@@ -105,10 +106,15 @@
         continue;
       }
 
-      collection->InsertFile(full_path);
+      sorted_files.push_back(full_path);
     }
   }
 
+  std::sort(sorted_files.begin(), sorted_files.end());
+  for (const std::string& full_path : sorted_files) {
+    collection->InsertFile(full_path);
+  }
+
   return collection;
 }
 
diff --git a/tools/aapt2/process/SymbolTable.cpp b/tools/aapt2/process/SymbolTable.cpp
index a844a43..78e0074 100644
--- a/tools/aapt2/process/SymbolTable.cpp
+++ b/tools/aapt2/process/SymbolTable.cpp
@@ -20,9 +20,11 @@
 
 #include "android-base/logging.h"
 #include "android-base/stringprintf.h"
-#include "androidfw/AssetManager.h"
+#include "androidfw/Asset.h"
+#include "androidfw/AssetManager2.h"
 #include "androidfw/ConfigDescription.h"
 #include "androidfw/ResourceTypes.h"
+#include "androidfw/ResourceUtils.h"
 
 #include "NameMangler.h"
 #include "Resource.h"
@@ -30,6 +32,7 @@
 #include "ValueVisitor.h"
 #include "util/Util.h"
 
+using ::android::ApkAssets;
 using ::android::ConfigDescription;
 using ::android::StringPiece;
 using ::android::StringPiece16;
@@ -214,51 +217,75 @@
 }
 
 bool AssetManagerSymbolSource::AddAssetPath(const StringPiece& path) {
-  int32_t cookie = 0;
-  return assets_.addAssetPath(android::String8(path.data(), path.size()), &cookie);
+  if (std::unique_ptr<const ApkAssets> apk = ApkAssets::Load(path.data())) {
+    apk_assets_.push_back(std::move(apk));
+
+    std::vector<const ApkAssets*> apk_assets;
+    for (const std::unique_ptr<const ApkAssets>& apk_asset : apk_assets_) {
+      apk_assets.push_back(apk_asset.get());
+    }
+
+    asset_manager_.SetApkAssets(apk_assets, true /* invalidate_caches */,
+                                false /* filter_incompatible_configs */);
+    return true;
+  }
+  return false;
 }
 
 std::map<size_t, std::string> AssetManagerSymbolSource::GetAssignedPackageIds() const {
   std::map<size_t, std::string> package_map;
-  const android::ResTable& table = assets_.getResources(false);
-  const size_t package_count = table.getBasePackageCount();
-  for (size_t i = 0; i < package_count; i++) {
-    package_map[table.getBasePackageId(i)] =
-        util::Utf16ToUtf8(android::StringPiece16(table.getBasePackageName(i).string()));
-  }
+  asset_manager_.ForEachPackage([&package_map](const std::string& name, uint8_t id) -> bool {
+    package_map.insert(std::make_pair(id, name));
+    return true;
+  });
+
   return package_map;
 }
 
 bool AssetManagerSymbolSource::IsPackageDynamic(uint32_t packageId) const {
-  return assets_.getResources(false).isPackageDynamic(packageId);
+  if (packageId == 0) {
+    return true;
+  }
+
+  for (const std::unique_ptr<const ApkAssets>& assets : apk_assets_) {
+    for (const std::unique_ptr<const android::LoadedPackage>& loaded_package
+         : assets->GetLoadedArsc()->GetPackages()) {
+      if (packageId == loaded_package->GetPackageId() && loaded_package->IsDynamic()) {
+        return true;
+      }
+    }
+  }
+
+  return false;
 }
 
 static std::unique_ptr<SymbolTable::Symbol> LookupAttributeInTable(
-    const android::ResTable& table, ResourceId id) {
-  // Try as a bag.
-  const android::ResTable::bag_entry* entry;
-  ssize_t count = table.lockBag(id.id, &entry);
-  if (count < 0) {
-    table.unlockBag(entry);
+    android::AssetManager2& am, ResourceId id) {
+  if (am.GetApkAssets().empty()) {
+    return {};
+  }
+
+  const android::ResolvedBag* bag = am.GetBag(id.id);
+  if (bag == nullptr) {
     return nullptr;
   }
 
   // We found a resource.
   std::unique_ptr<SymbolTable::Symbol> s = util::make_unique<SymbolTable::Symbol>(id);
 
-  // Check to see if it is an attribute.
-  for (size_t i = 0; i < (size_t)count; i++) {
-    if (entry[i].map.name.ident == android::ResTable_map::ATTR_TYPE) {
-      s->attribute = std::make_shared<Attribute>(entry[i].map.value.data);
+  const size_t count = bag->entry_count;
+  for (uint32_t i = 0; i < count; i++) {
+    if (bag->entries[i].key == android::ResTable_map::ATTR_TYPE) {
+      s->attribute = std::make_shared<Attribute>(bag->entries[i].value.data);
       break;
     }
   }
 
   if (s->attribute) {
-    for (size_t i = 0; i < (size_t)count; i++) {
-      const android::ResTable_map& map_entry = entry[i].map;
-      if (Res_INTERNALID(map_entry.name.ident)) {
-        switch (map_entry.name.ident) {
+    for (size_t i = 0; i < count; i++) {
+      const android::ResolvedBag::Entry& map_entry = bag->entries[i];
+      if (Res_INTERNALID(map_entry.key)) {
+        switch (map_entry.key) {
           case android::ResTable_map::ATTR_MIN:
             s->attribute->min_int = static_cast<int32_t>(map_entry.value.data);
             break;
@@ -269,74 +296,65 @@
         continue;
       }
 
-      android::ResTable::resource_name entry_name;
-      if (!table.getResourceName(map_entry.name.ident, false, &entry_name)) {
-        table.unlockBag(entry);
+      android::AssetManager2::ResourceName name;
+      if (!am.GetResourceName(map_entry.key, &name)) {
         return nullptr;
       }
 
-      Maybe<ResourceName> parsed_name = ResourceUtils::ToResourceName(entry_name);
+      Maybe<ResourceName> parsed_name = ResourceUtils::ToResourceName(name);
       if (!parsed_name) {
         return nullptr;
       }
 
       Attribute::Symbol symbol;
       symbol.symbol.name = parsed_name.value();
-      symbol.symbol.id = ResourceId(map_entry.name.ident);
+      symbol.symbol.id = ResourceId(map_entry.key);
       symbol.value = map_entry.value.data;
       s->attribute->symbols.push_back(std::move(symbol));
     }
   }
-  table.unlockBag(entry);
+
   return s;
 }
 
 std::unique_ptr<SymbolTable::Symbol> AssetManagerSymbolSource::FindByName(
     const ResourceName& name) {
-  const android::ResTable& table = assets_.getResources(false);
+  const std::string mangled_entry = NameMangler::MangleEntry(name.package, name.entry);
 
-  const std::u16string package16 = util::Utf8ToUtf16(name.package);
-  const std::u16string type16 = util::Utf8ToUtf16(to_string(name.type));
-  const std::u16string entry16 = util::Utf8ToUtf16(name.entry);
-  const std::u16string mangled_entry16 =
-      util::Utf8ToUtf16(NameMangler::MangleEntry(name.package, name.entry));
-
+  bool found = false;
+  ResourceId res_id = 0;
   uint32_t type_spec_flags;
-  ResourceId res_id;
 
   // There can be mangled resources embedded within other packages. Here we will
   // look into each package and look-up the mangled name until we find the resource.
-  const size_t count = table.getBasePackageCount();
-  for (size_t i = 0; i < count; i++) {
-    const android::String16 package_name = table.getBasePackageName(i);
-    StringPiece16 real_package16 = package16;
-    StringPiece16 real_entry16 = entry16;
-    std::u16string scratch_entry16;
-    if (StringPiece16(package_name) != package16) {
-      real_entry16 = mangled_entry16;
-      real_package16 = package_name.string();
+  asset_manager_.ForEachPackage([&](const std::string& package_name, uint8_t id) -> bool {
+    ResourceName real_name(name.package, name.type, name.entry);
+
+    if (package_name != name.package) {
+      real_name.entry = mangled_entry;
+      real_name.package = package_name;
     }
 
-    type_spec_flags = 0;
-    res_id = table.identifierForName(real_entry16.data(), real_entry16.size(), type16.data(),
-                                     type16.size(), real_package16.data(), real_package16.size(),
-                                     &type_spec_flags);
-    if (res_id.is_valid()) {
-      break;
+    res_id = asset_manager_.GetResourceId(real_name.to_string());
+    if (res_id.is_valid() && asset_manager_.GetResourceFlags(res_id.id, &type_spec_flags)) {
+      found = true;
+      return false;
     }
-  }
 
-  if (!res_id.is_valid()) {
+    return true;
+  });
+
+  if (!found) {
     return {};
   }
 
   std::unique_ptr<SymbolTable::Symbol> s;
   if (name.type == ResourceType::kAttr) {
-    s = LookupAttributeInTable(table, res_id);
+    s = LookupAttributeInTable(asset_manager_, res_id);
   } else {
     s = util::make_unique<SymbolTable::Symbol>();
     s->id = res_id;
-    s->is_dynamic = table.isResourceDynamic(res_id.id);
+    s->is_dynamic = IsPackageDynamic(ResourceId(res_id).package_id());
   }
 
   if (s) {
@@ -346,13 +364,13 @@
   return {};
 }
 
-static Maybe<ResourceName> GetResourceName(const android::ResTable& table,
+static Maybe<ResourceName> GetResourceName(android::AssetManager2& am,
                                            ResourceId id) {
-  android::ResTable::resource_name res_name = {};
-  if (!table.getResourceName(id.id, true, &res_name)) {
+  android::AssetManager2::ResourceName name;
+  if (!am.GetResourceName(id.id, &name)) {
     return {};
   }
-  return ResourceUtils::ToResourceName(res_name);
+  return ResourceUtils::ToResourceName(name);
 }
 
 std::unique_ptr<SymbolTable::Symbol> AssetManagerSymbolSource::FindById(
@@ -361,22 +379,30 @@
     // Exit early and avoid the error logs from AssetManager.
     return {};
   }
-  const android::ResTable& table = assets_.getResources(false);
-  Maybe<ResourceName> maybe_name = GetResourceName(table, id);
+
+  if (apk_assets_.empty()) {
+    return {};
+  }
+
+  Maybe<ResourceName> maybe_name = GetResourceName(asset_manager_, id);
   if (!maybe_name) {
     return {};
   }
 
-  uint32_t type_spec_flags = 0;
-  table.getResourceFlags(id.id, &type_spec_flags);
 
+  uint32_t type_spec_flags = 0;
+  if (!asset_manager_.GetResourceFlags(id.id, &type_spec_flags)) {
+    return {};
+  }
+
+  ResourceName& name = maybe_name.value();
   std::unique_ptr<SymbolTable::Symbol> s;
-  if (maybe_name.value().type == ResourceType::kAttr) {
-    s = LookupAttributeInTable(table, id);
+  if (name.type == ResourceType::kAttr) {
+    s = LookupAttributeInTable(asset_manager_, id);
   } else {
     s = util::make_unique<SymbolTable::Symbol>();
     s->id = id;
-    s->is_dynamic = table.isResourceDynamic(id.id);
+    s->is_dynamic = IsPackageDynamic(ResourceId(id).package_id());
   }
 
   if (s) {
diff --git a/tools/aapt2/process/SymbolTable.h b/tools/aapt2/process/SymbolTable.h
index 2d8bd02..6997cd6 100644
--- a/tools/aapt2/process/SymbolTable.h
+++ b/tools/aapt2/process/SymbolTable.h
@@ -22,7 +22,8 @@
 #include <vector>
 
 #include "android-base/macros.h"
-#include "androidfw/AssetManager.h"
+#include "androidfw/Asset.h"
+#include "androidfw/AssetManager2.h"
 #include "utils/JenkinsHash.h"
 #include "utils/LruCache.h"
 
@@ -201,12 +202,13 @@
   std::unique_ptr<SymbolTable::Symbol> FindByReference(
       const Reference& ref) override;
 
-  android::AssetManager* GetAssetManager() {
-    return &assets_;
+  android::AssetManager2* GetAssetManager() {
+    return &asset_manager_;
   }
 
  private:
-  android::AssetManager assets_;
+  android::AssetManager2 asset_manager_;
+  std::vector<std::unique_ptr<const android::ApkAssets>> apk_assets_;
 
   DISALLOW_COPY_AND_ASSIGN(AssetManagerSymbolSource);
 };
diff --git a/tools/aapt2/process/SymbolTable_test.cpp b/tools/aapt2/process/SymbolTable_test.cpp
index 1f59d70..ddc2101 100644
--- a/tools/aapt2/process/SymbolTable_test.cpp
+++ b/tools/aapt2/process/SymbolTable_test.cpp
@@ -76,40 +76,54 @@
   EXPECT_THAT(symbol_table.FindByName(test::ParseNameOrDie("com.android.lib:id/foo")), NotNull());
 }
 
-TEST(SymbolTableTest, FindByNameWhenSymbolIsMangledInResTable) {
+using SymbolTableTestFixture = CommandTestFixture;
+TEST_F(SymbolTableTestFixture, FindByNameWhenSymbolIsMangledInResTable) {
   using namespace android;
+  StdErrDiagnostics diag;
 
-  std::unique_ptr<IAaptContext> context =
-      test::ContextBuilder()
-          .SetCompilationPackage("com.android.app")
-          .SetPackageId(0x7f)
-          .SetPackageType(PackageType::kApp)
-          .SetMinSdkVersion(SDK_LOLLIPOP_MR1)
-          .SetNameManglerPolicy(NameManglerPolicy{"com.android.app"})
-          .Build();
+  // Create a static library.
+  const std::string static_lib_compiled_files_dir = GetTestPath("static-lib-compiled");
+  ASSERT_TRUE(CompileFile(GetTestPath("res/values/values.xml"),
+         R"(<?xml version="1.0" encoding="utf-8"?>
+         <resources>
+             <item type="id" name="foo"/>
+        </resources>)",
+         static_lib_compiled_files_dir, &diag));
 
-  // Create a ResourceTable with a mangled resource, simulating a static library being merged into
-  // the main application package.
-  std::unique_ptr<ResourceTable> table =
-      test::ResourceTableBuilder()
-          .AddSimple("com.android.app:id/" + NameMangler::MangleEntry("com.android.lib", "foo"),
-                     ResourceId(0x7f020000))
-          .AddSimple("com.android.app:id/bar", ResourceId(0x7f020001))
-          .Build();
+  const std::string static_lib_apk = GetTestPath("static_lib.apk");
+  std::vector<std::string> link_args = {
+      "--manifest", GetDefaultManifest("com.android.lib"),
+      "--min-sdk-version", "22",
+      "--static-lib",
+      "-o", static_lib_apk,
+  };
+  ASSERT_TRUE(Link(link_args, static_lib_compiled_files_dir, &diag));
 
-  BigBuffer buffer(1024u);
-  TableFlattener flattener({}, &buffer);
-  ASSERT_TRUE(flattener.Consume(context.get(), table.get()));
+  // Merge the static library into the main application package. The static library resources will
+  // be mangled with the library package name.
+  const std::string app_compiled_files_dir = GetTestPath("app-compiled");
+  ASSERT_TRUE(CompileFile(GetTestPath("res/values/values.xml"),
+      R"(<?xml version="1.0" encoding="utf-8"?>
+         <resources>
+             <item type="id" name="bar"/>
+        </resources>)",
+        app_compiled_files_dir, &diag));
 
-  std::unique_ptr<uint8_t[]> data = util::Copy(buffer);
+  const std::string out_apk = GetTestPath("out.apk");
+  link_args = {
+      "--manifest", GetDefaultManifest("com.android.app"),
+      "--min-sdk-version", "22",
+      "-o", out_apk,
+      static_lib_apk
+  };
+  ASSERT_TRUE(Link(link_args, app_compiled_files_dir, &diag));
 
   // Construct the test AssetManager.
   auto asset_manager_source = util::make_unique<AssetManagerSymbolSource>();
-  ResTable& res_table = const_cast<ResTable&>(
-      asset_manager_source->GetAssetManager()->getResources(false /*required*/));
-  ASSERT_THAT(res_table.add(data.get(), buffer.size()), Eq(NO_ERROR));
+  asset_manager_source->AddAssetPath(out_apk);
 
-  SymbolTable symbol_table(context->GetNameMangler());
+  NameMangler name_mangler(NameManglerPolicy{"com.android.app"});
+  SymbolTable symbol_table(&name_mangler);
   symbol_table.AppendSource(std::move(asset_manager_source));
 
   EXPECT_THAT(symbol_table.FindByName(test::ParseNameOrDie("com.android.lib:id/foo")), NotNull());
diff --git a/tools/aapt2/test/Fixture.cpp b/tools/aapt2/test/Fixture.cpp
index 3fcdfb7..a51b4a4 100644
--- a/tools/aapt2/test/Fixture.cpp
+++ b/tools/aapt2/test/Fixture.cpp
@@ -37,6 +37,8 @@
 
 namespace aapt {
 
+const char* CommandTestFixture::kDefaultPackageName = "com.aapt.command.test";
+
 void ClearDirectory(const android::StringPiece& path) {
   const std::string root_dir = path.to_string();
   std::unique_ptr<DIR, decltype(closedir)*> dir(opendir(root_dir.data()), closedir);
@@ -124,12 +126,12 @@
   return LinkCommand(diag).Execute(link_args, &std::cerr) == 0;
 }
 
-std::string CommandTestFixture::GetDefaultManifest() {
+std::string CommandTestFixture::GetDefaultManifest(const char* package_name) {
   const std::string manifest_file = GetTestPath("AndroidManifest.xml");
-  CHECK(WriteFile(manifest_file, R"(
+  CHECK(WriteFile(manifest_file, android::base::StringPrintf(R"(
       <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          package="com.aapt.command.test">
-      </manifest>)"));
+          package="%s">
+      </manifest>)", package_name)));
   return manifest_file;
 }
 
diff --git a/tools/aapt2/test/Fixture.h b/tools/aapt2/test/Fixture.h
index 3079c75..fce2aeb 100644
--- a/tools/aapt2/test/Fixture.h
+++ b/tools/aapt2/test/Fixture.h
@@ -81,7 +81,7 @@
             IDiagnostics* diag);
 
   // Creates a minimal android manifest within the test directory and returns the file path.
-  std::string GetDefaultManifest();
+  std::string GetDefaultManifest(const char* package_name = kDefaultPackageName);
 
   // Returns pointer to data inside APK files
   std::unique_ptr<io::IData> OpenFileAsData(LoadedApk* apk,
@@ -91,6 +91,7 @@
   void AssertLoadXml(LoadedApk* apk, const io::IData* data,
                      android::ResXMLTree* out_tree);
 
+  static const char* kDefaultPackageName;
  private:
   DISALLOW_COPY_AND_ASSIGN(CommandTestFixture);
 };
diff --git a/tools/aapt2/util/Files.cpp b/tools/aapt2/util/Files.cpp
index 604b257..5d57de6 100644
--- a/tools/aapt2/util/Files.cpp
+++ b/tools/aapt2/util/Files.cpp
@@ -102,12 +102,21 @@
 #endif
 
 bool mkdirs(const std::string& path) {
-  #ifdef _WIN32
-  // Start after the drive path if present. Calling mkdir with only the drive will cause an error.
-  size_t current_pos = 1u;
-  if (path.size() >= 3 && path[1] == ':' &&
-        (path[2] == '\\' || path[2] == '/')) {
-    current_pos = 3u;
+ #ifdef _WIN32
+  // Start after the long path prefix if present.
+  bool require_drive = false;
+  size_t current_pos = 0u;
+  if (util::StartsWith(path, R"(\\?\)")) {
+    require_drive = true;
+    current_pos = 4u;
+  }
+
+  // Start after the drive path if present.
+  if (path.size() >= 3 && path[current_pos + 1] == ':' &&
+       (path[current_pos + 2] == '\\' || path[current_pos + 2] == '/')) {
+    current_pos += 3u;
+  } else if (require_drive) {
+    return false;
   }
  #else
   // Start after the first character so that we don't consume the root '/'.
diff --git a/tools/aapt2/util/Files_test.cpp b/tools/aapt2/util/Files_test.cpp
index 202cc26..6c38080 100644
--- a/tools/aapt2/util/Files_test.cpp
+++ b/tools/aapt2/util/Files_test.cpp
@@ -19,6 +19,7 @@
 #include <sstream>
 
 #include "android-base/stringprintf.h"
+#include "android-base/utf8.h"
 
 #include "test/Test.h"
 
@@ -65,5 +66,40 @@
   EXPECT_EQ(expected_path_, base);
 }
 
+#ifdef _WIN32
+TEST_F(FilesTest, WindowsMkdirsLongPath) {
+  // Creating directory paths longer than the Windows maximum path length (260 charatcers) should
+  // succeed.
+  const std::string kDirName = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+  const size_t kRecursiveDepth = 10u;
+
+  // Recursively create the test file path and clean up the created directories after the files have
+  // been created.
+  std::function<void(std::string, size_t)> CreateResursiveDirs =
+      [&kDirName, &CreateResursiveDirs](std::string current_path, const size_t n) -> void {
+    AppendPath(&current_path, kDirName);
+
+    if (n == 0) {
+      ASSERT_TRUE(file::mkdirs(current_path)) << "Failed to create path " << current_path;
+    } else {
+      CreateResursiveDirs(current_path, n - 1);
+    }
+
+    // Clean up the created directories.
+    _rmdir(current_path.data());
+  };
+
+  CreateResursiveDirs(
+      android::base::StringPrintf(R"(\\?\%s)", android::base::GetExecutableDirectory().data()),
+      kRecursiveDepth);
+}
+
+TEST_F(FilesTest, WindowsMkdirsLongPathMissingDrive) {
+  ASSERT_FALSE(file::mkdirs(R"(\\?\local\path\to\file)"));
+  ASSERT_FALSE(file::mkdirs(R"(\\?\:local\path\to\file)"));
+  ASSERT_FALSE(file::mkdirs(R"(\\?\\local\path\to\file)"));
+}
+#endif
+
 }  // namespace files
 }  // namespace aapt
diff --git a/tools/apilint/apilint.py b/tools/apilint/apilint.py
index 59e89f5..295e3de 100644
--- a/tools/apilint/apilint.py
+++ b/tools/apilint/apilint.py
@@ -79,6 +79,7 @@
                 self.value = raw[3].strip(';"')
             else:
                 self.value = None
+            self.annotations = []
 
         self.ident = "-".join((self.typ, self.name, self.value or ""))
 
@@ -88,6 +89,18 @@
     def __repr__(self):
         return self.raw
 
+
+class Argument(object):
+
+    __slots__ = ["type", "annotations", "name", "default"]
+
+    def __init__(self, type):
+        self.type = type
+        self.annotations = []
+        self.name = None
+        self.default = None
+
+
 class Method():
     def __init__(self, clazz, line, raw, blame, sig_format = 1):
         self.clazz = clazz
@@ -118,21 +131,24 @@
             self.name = raw[1]
 
             # parse args
-            self.args = []
+            self.detailed_args = []
             for arg in re.split(",\s*", raw_args):
                 arg = re.split("\s", arg)
                 # ignore annotations for now
                 arg = [ a for a in arg if not a.startswith("@") ]
                 if len(arg[0]) > 0:
-                    self.args.append(arg[0])
+                    self.detailed_args.append(Argument(arg[0]))
 
             # parse throws
             self.throws = []
             for throw in re.split(",\s*", raw_throws):
                 self.throws.append(throw)
+
+            self.annotations = []
         else:
             raise ValueError("Unknown signature format: " + sig_format)
 
+        self.args = map(lambda a: a.type, self.detailed_args)
         self.ident = "-".join((self.typ, self.name, "-".join(self.args)))
 
     def sig_matches(self, typ, name, args):
@@ -208,13 +224,14 @@
 
 
 class Package():
+    NAME = re.compile("package(?: .*)? ([A-Za-z.]+)")
+
     def __init__(self, line, raw, blame):
         self.line = line
         self.raw = raw.strip(" {;")
         self.blame = blame
 
-        raw = raw.split()
-        self.name = raw[raw.index("package")+1]
+        self.name = Package.NAME.match(raw).group(1)
         self.name_path = self.name.split(".")
 
     def __repr__(self):
@@ -311,10 +328,10 @@
         method.split = []
         kind = self.parse_one_of("ctor", "method")
         method.split.append(kind)
-        annotations = self.parse_annotations()
+        method.annotations = self.parse_annotations()
         method.split.extend(self.parse_modifiers())
         self.parse_matching_paren("<", ">")
-        if "@Deprecated" in annotations:
+        if "@Deprecated" in method.annotations:
             method.split.append("deprecated")
         if kind == "ctor":
             method.typ = "ctor"
@@ -324,7 +341,7 @@
         method.name = self.parse_name()
         method.split.append(method.name)
         self.parse_token("(")
-        method.args = self.parse_args()
+        method.detailed_args = self.parse_args()
         self.parse_token(")")
         method.throws = self.parse_throws()
         if "@interface" in method.clazz.split:
@@ -359,8 +376,8 @@
     def parse_into_field(self, field):
         kind = self.parse_one_of(*V2LineParser.FIELD_KINDS)
         field.split = [kind]
-        annotations = self.parse_annotations()
-        if "@Deprecated" in annotations:
+        field.annotations = self.parse_annotations()
+        if "@Deprecated" in field.annotations:
             field.split.append("deprecated")
         field.split.extend(self.parse_modifiers())
         field.typ = self.parse_type()
@@ -487,15 +504,16 @@
 
     def parse_arg(self):
         self.parse_if("vararg")  # kotlin vararg
-        self.parse_annotations()
-        type = self.parse_arg_type()
+        annotations = self.parse_annotations()
+        arg = Argument(self.parse_arg_type())
+        arg.annotations = annotations
         l = self.lookahead()
         if l != "," and l != ")":
             if self.lookahead() != '=':
-                self.parse_token()  # kotlin argument name
+                arg.name = self.parse_token()  # kotlin argument name
             if self.parse_if('='): # kotlin default value
-                self.parse_expression()
-        return type
+                arg.default = self.parse_expression()
+        return arg
 
     def parse_expression(self):
         while not self.lookahead() in [')', ',', ';']:
@@ -592,7 +610,7 @@
     blame = None
     sig_format = 1
 
-    re_blame = re.compile("^([a-z0-9]{7,}) \(<([^>]+)>.+?\) (.+?)$")
+    re_blame = re.compile(r"^(\^?[a-z0-9]{7,}) \(<([^>]+)>.+?\) (.+?)$")
 
     field_prefixes = map(lambda kind: "    %s" % (kind,), V2LineParser.FIELD_KINDS)
     def startsWithFieldPrefix(raw):
@@ -607,11 +625,13 @@
         match = re_blame.match(raw)
         if match is not None:
             blame = match.groups()[0:2]
+            if blame[0].startswith("^"):  # Outside of blame range
+              blame = None
             raw = match.groups()[2]
         else:
             blame = None
 
-        if line == 1 and raw.startswith("// Signature format: "):
+        if line == 1 and V2Tokenizer.SIGNATURE_PREFIX in raw:
             sig_format_string = raw[len(V2Tokenizer.SIGNATURE_PREFIX):]
             if sig_format_string in ["2.0", "3.0"]:
                 sig_format = 2
@@ -1108,6 +1128,9 @@
     if not has_build:
         warn(clazz, None, None, "Missing build() method")
 
+    if "final" not in clazz.split:
+        error(clazz, None, None, "Builder should be final")
+
 
 def verify_aidl(clazz):
     """Catch people exposing raw AIDL."""
@@ -1867,6 +1890,35 @@
             if arg in discouraged:
                 warn(clazz, m, "FW12", "Should avoid odd sized primitives; use int instead")
 
+PRIMITIVES = {"void", "int", "float", "boolean", "short", "char", "byte", "long", "double"}
+
+def verify_nullability(clazz):
+    """Catches missing nullability annotations"""
+
+    for f in clazz.fields:
+        if f.value is not None and 'static' in f.split and 'final' in f.split:
+            continue  # Nullability of constants can be inferred.
+        if f.typ not in PRIMITIVES and not has_nullability(f.annotations):
+            error(clazz, f, "M12", "Field must be marked either @NonNull or @Nullable")
+
+    for c in clazz.ctors:
+        verify_nullability_args(clazz, c)
+
+    for m in clazz.methods:
+        if m.name == "writeToParcel" or m.name == "onReceive":
+            continue  # Parcelable.writeToParcel() and BroadcastReceiver.onReceive() are not yet annotated
+
+        if m.typ not in PRIMITIVES and not has_nullability(m.annotations):
+            error(clazz, m, "M12", "Return value must be marked either @NonNull or @Nullable")
+        verify_nullability_args(clazz, m)
+
+def verify_nullability_args(clazz, m):
+    for i, arg in enumerate(m.detailed_args):
+        if arg.type not in PRIMITIVES and not has_nullability(arg.annotations):
+            error(clazz, m, "M12", "Argument %d must be marked either @NonNull or @Nullable" % (i+1,))
+
+def has_nullability(annotations):
+    return "@NonNull" in annotations or "@Nullable" in annotations
 
 def verify_singleton(clazz):
     """Catch singleton objects with constructors."""
@@ -1955,6 +2007,7 @@
     verify_pfd(clazz)
     verify_numbers(clazz)
     verify_singleton(clazz)
+    verify_nullability(clazz)
 
 
 def examine_stream(stream, base_stream=None, in_classes_with_base=[], out_classes_with_base=None):
diff --git a/tools/apilint/apilint_test.py b/tools/apilint/apilint_test.py
index 3716bf9..f34492d 100644
--- a/tools/apilint/apilint_test.py
+++ b/tools/apilint/apilint_test.py
@@ -88,20 +88,22 @@
 
 
 faulty_current_txt = """
+// Signature format: 2.0
 package android.app {
   public final class Activity {
   }
 
   public final class WallpaperColors implements android.os.Parcelable {
-    ctor public WallpaperColors(android.os.Parcel);
+    ctor public WallpaperColors(@NonNull android.os.Parcel);
     method public int describeContents();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.WallpaperColors> CREATOR;
+    method public void writeToParcel(@NonNull android.os.Parcel, int);
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.WallpaperColors> CREATOR;
   }
 }
-""".split('\n')
+""".strip().split('\n')
 
 ok_current_txt = """
+// Signature format: 2.0
 package android.app {
   public final class Activity {
   }
@@ -109,19 +111,20 @@
   public final class WallpaperColors implements android.os.Parcelable {
     ctor public WallpaperColors();
     method public int describeContents();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.app.WallpaperColors> CREATOR;
+    method public void writeToParcel(@NonNull android.os.Parcel, int);
+    field @NonNull public static final android.os.Parcelable.Creator<android.app.WallpaperColors> CREATOR;
   }
 }
-""".split('\n')
+""".strip().split('\n')
 
 system_current_txt = """
+// Signature format: 2.0
 package android.app {
   public final class WallpaperColors implements android.os.Parcelable {
     method public int getSomething();
   }
 }
-""".split('\n')
+""".strip().split('\n')
 
 
 
@@ -369,5 +372,21 @@
         m = self._method('method @NonNull public @NonNull String @NonNull [] split(@NonNull String, int);')
         self.assertEquals('java.lang.String[]', m.typ)
 
+class PackageTests(unittest.TestCase):
+    def _package(self, raw):
+        return apilint.Package(123, raw, "blame")
+
+    def test_regular_package(self):
+        p = self._package("package an.pref.int {")
+        self.assertEquals('an.pref.int', p.name)
+
+    def test_annotation_package(self):
+        p = self._package("package @RestrictTo(a.b.C) an.pref.int {")
+        self.assertEquals('an.pref.int', p.name)
+
+    def test_multi_annotation_package(self):
+        p = self._package("package @Rt(a.b.L_G_P) @RestrictTo(a.b.C) an.pref.int {")
+        self.assertEquals('an.pref.int', p.name)
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/tools/bit/main.cpp b/tools/bit/main.cpp
index 860094ae..082ccf3 100644
--- a/tools/bit/main.cpp
+++ b/tools/bit/main.cpp
@@ -33,6 +33,8 @@
 
 using namespace std;
 
+#define NATIVE_TESTS "NATIVE_TESTS"
+
 /**
  * An entry from the command line for something that will be built, installed,
  * and/or tested.
@@ -132,6 +134,32 @@
 {
 }
 
+struct PushedFile
+{
+    TrackedFile file;
+    string dest;
+
+    PushedFile();
+    PushedFile(const PushedFile& that);
+    PushedFile(const string& filename, const string& dest);
+    ~PushedFile() {};
+};
+
+PushedFile::PushedFile()
+{
+}
+
+PushedFile::PushedFile(const PushedFile& that)
+    :file(that.file),
+     dest(that.dest)
+{
+}
+
+PushedFile::PushedFile(const string& f, const string& d)
+    :file(f),
+     dest(d)
+{
+}
 
 /**
  * Record for an test that is going to be launched.
@@ -658,12 +686,14 @@
     }
 
     // Figure out whether we need to sync the system and which apks to install
-    string systemPath = buildOut + "/target/product/" + buildDevice + "/system/";
-    string dataPath = buildOut + "/target/product/" + buildDevice + "/data/";
+    string deviceTargetPath = buildOut + "/target/product/" + buildDevice;
+    string systemPath = deviceTargetPath + "/system/";
+    string dataPath = deviceTargetPath + "/data/";
     bool syncSystem = false;
     bool alwaysSyncSystem = false;
     vector<string> systemFiles;
     vector<InstallApk> installApks;
+    vector<PushedFile> pushedFiles;
     for (size_t i=0; i<targets.size(); i++) {
         Target* target = targets[i];
         if (target->install) {
@@ -687,6 +717,11 @@
                     installApks.push_back(InstallApk(file, !target->build));
                     continue;
                 }
+                // If it's a native test module, push it.
+                if (target->module.HasClass(NATIVE_TESTS) && starts_with(file, dataPath)) {
+                    string installedPath(file.c_str() + deviceTargetPath.length());
+                    pushedFiles.push_back(PushedFile(file, installedPath));
+                }
             }
         }
     }
@@ -701,6 +736,13 @@
             printf("  %s\n", systemFiles[i].c_str());
         }
     }
+    if (pushedFiles.size() > 0){
+        print_info("Files to push:");
+        for (size_t i=0; i<pushedFiles.size(); i++) {
+            printf("  %s\n", pushedFiles[i].file.filename.c_str());
+            printf("    --> %s\n", pushedFiles[i].dest.c_str());
+        }
+    }
     if (installApks.size() > 0){
         print_info("APKs to install:");
         for (size_t i=0; i<installApks.size(); i++) {
@@ -784,6 +826,25 @@
         }
     }
 
+    // Push files
+    if (pushedFiles.size() > 0) {
+        print_status("Pushing files");
+        for (size_t i=0; i<pushedFiles.size(); i++) {
+            const PushedFile& pushed = pushedFiles[i];
+            string dir = dirname(pushed.dest);
+            if (dir.length() == 0 || dir == "/") {
+                // This isn't really a file inside the data directory. Just skip it.
+                continue;
+            }
+            // TODO: if (!apk.file.fileInfo.exists || apk.file.HasChanged())
+            err = run_adb("shell", "mkdir", "-p", dir.c_str(), NULL);
+            check_error(err);
+            err = run_adb("push", pushed.file.filename.c_str(), pushed.dest.c_str());
+            check_error(err);
+            // pushed.installed = true;
+        }
+    }
+
     // Install APKs
     if (installApks.size() > 0) {
         print_status("Installing APKs");
@@ -804,6 +865,74 @@
     // Actions
     //
 
+    // Whether there have been any tests run, so we can print a summary.
+    bool testsRun = false;
+
+    // Run the native tests.
+    // TODO: We don't have a good way of running these and capturing the output of
+    // them live.  It'll take some work.  On the other hand, if they're gtest tests,
+    // the output of gtest is not completely insane like the text output of the
+    // instrumentation tests.  So for now, we'll just live with that.
+    for (size_t i=0; i<targets.size(); i++) {
+        Target* target = targets[i];
+        if (target->test && target->module.HasClass(NATIVE_TESTS)) {
+            // We don't have a clear signal from the build system which of the installed
+            // files is actually the test, so we guess by looking for one with the same
+            // leaf name as the module that is executable.
+            for (size_t j=0; j<target->module.installed.size(); j++) {
+                string filename = target->module.installed[j];
+                if (!starts_with(filename, dataPath)) {
+                    // Native tests go into the data directory.
+                    continue;
+                }
+                if (leafname(filename) != target->module.name) {
+                    // This isn't the test executable.
+                    continue;
+                }
+                if (!is_executable(filename)) {
+                    continue;
+                }
+                string installedPath(filename.c_str() + deviceTargetPath.length());
+                printf("the magic one is: %s\n", filename.c_str());
+                printf("  and it's installed at: %s\n", installedPath.c_str());
+
+                // Convert bit-style actions to gtest test filter arguments
+                if (target->actions.size() > 0) {
+                    testsRun = true;
+                    target->testActionCount++;
+                    bool runAll = false;
+                    string filterArg("--gtest_filter=");
+                    for (size_t k=0; k<target->actions.size(); k++) {
+                        string actionString = target->actions[k];
+                        if (actionString == "*") {
+                            runAll = true;
+                        } else {
+                            filterArg += actionString;
+                            if (k != target->actions.size()-1) {
+                                // We would otherwise have to worry about this condition
+                                // being true, and appending an extra ':', but we know that
+                                // if the extra action is "*", then we'll just run all and
+                                // won't use filterArg anyway, so just keep this condition
+                                // simple.
+                                filterArg += ':';
+                            }
+                        }
+                    }
+                    if (runAll) {
+                        err = run_adb("shell", installedPath.c_str(), NULL);
+                    } else {
+                        err = run_adb("shell", installedPath.c_str(), filterArg.c_str(), NULL);
+                    }
+                    if (err == 0) {
+                        target->testPassCount++;
+                    } else {
+                        target->testFailCount++;
+                    }
+                }
+            }
+        }
+    }
+
     // Inspect the apks, and figure out what is an activity and what needs a test runner
     bool printedInspecting = false;
     vector<TestAction> testActions;
@@ -872,6 +1001,7 @@
     TestResults testResults;
     if (testActions.size() > 0) {
         print_status("Running tests");
+        testsRun = true;
         for (size_t i=0; i<testActions.size(); i++) {
             TestAction& action = testActions[i];
             testResults.SetCurrentAction(&action);
@@ -969,7 +1099,7 @@
 
     // Tests
     bool hasErrors = false;
-    if (testActions.size() > 0) {
+    if (testsRun) {
         printf("%sRan tests:%s\n", g_escapeBold, g_escapeEndColor);
         size_t maxNameLength = 0;
         for (size_t i=0; i<targets.size(); i++) {
diff --git a/tools/bit/make.cpp b/tools/bit/make.cpp
index 6270913..df64a80 100644
--- a/tools/bit/make.cpp
+++ b/tools/bit/make.cpp
@@ -51,6 +51,18 @@
     return filename + "/.bit_cache";
 }
 
+bool
+Module::HasClass(const string& cl)
+{
+    for (vector<string>::const_iterator c = classes.begin(); c != classes.end(); c++) {
+        if (*c == cl) {
+            return true;
+        }
+    }
+    return false;
+}
+
+
 BuildVars::BuildVars(const string& outDir, const string& buildProduct,
         const string& buildVariant, const string& buildType)
     :m_filename(),
diff --git a/tools/bit/make.h b/tools/bit/make.h
index db0b69f..785912a 100644
--- a/tools/bit/make.h
+++ b/tools/bit/make.h
@@ -29,6 +29,8 @@
     vector<string> classes;
     vector<string> paths;
     vector<string> installed;
+
+    bool HasClass(const string& cl);
 };
 
 /**
diff --git a/tools/bit/util.cpp b/tools/bit/util.cpp
index a502a9d..63399d6 100644
--- a/tools/bit/util.cpp
+++ b/tools/bit/util.cpp
@@ -254,4 +254,42 @@
     return result;
 }
 
+bool
+is_executable(const string& filename)
+{
+    int err;
+    struct stat st;
 
+    err = stat(filename.c_str(), &st);
+    if (err != 0) {
+        return false;
+    }
+
+    return (st.st_mode & S_IXUSR) != 0;
+}
+
+string
+dirname(const string& filename)
+{
+    size_t slash = filename.rfind('/');
+    if (slash == string::npos) {
+        return "";
+    } else if (slash == 0) {
+        return "/";
+    } else {
+        return string(filename, 0, slash);
+    }
+}
+
+string
+leafname(const string& filename)
+{
+    size_t slash = filename.rfind('/');
+    if (slash == string::npos) {
+        return filename;
+    } else if (slash == filename.length() - 1) {
+        return "";
+    } else {
+        return string(filename, slash + 1);
+    }
+}
diff --git a/tools/bit/util.h b/tools/bit/util.h
index 718f147..7ccdab1 100644
--- a/tools/bit/util.h
+++ b/tools/bit/util.h
@@ -79,5 +79,10 @@
 
 string read_file(const string& filename);
 
+bool is_executable(const string& filename);
+
+string dirname(const string& filename);
+string leafname(const string& filename);
+
 #endif // UTIL_H
 
diff --git a/tools/hiddenapi/exclude.sh b/tools/hiddenapi/exclude.sh
index 4ffcf68..18c4054 100755
--- a/tools/hiddenapi/exclude.sh
+++ b/tools/hiddenapi/exclude.sh
@@ -9,6 +9,7 @@
 LIBCORE_PACKAGES="\
   android.icu \
   android.system \
+  android.test \
   com.android.bouncycastle \
   com.android.conscrypt \
   com.android.i18n.phonenumbers \
@@ -17,6 +18,7 @@
   dalvik \
   java \
   javax \
+  junit \
   libcore \
   org.apache.harmony \
   org.json \
diff --git a/wifi/java/android/net/wifi/BatchedScanResult.java b/wifi/java/android/net/wifi/BatchedScanResult.java
index c06543e..ed8845dd 100644
--- a/wifi/java/android/net/wifi/BatchedScanResult.java
+++ b/wifi/java/android/net/wifi/BatchedScanResult.java
@@ -78,7 +78,7 @@
     }
 
     /** Implement the Parcelable interface {@hide} */
-    public static final Creator<BatchedScanResult> CREATOR =
+    public static final @android.annotation.NonNull Creator<BatchedScanResult> CREATOR =
         new Creator<BatchedScanResult>() {
             public BatchedScanResult createFromParcel(Parcel in) {
                 BatchedScanResult result = new BatchedScanResult();
diff --git a/wifi/java/android/net/wifi/IWifiManager.aidl b/wifi/java/android/net/wifi/IWifiManager.aidl
index d549799..17948e7 100644
--- a/wifi/java/android/net/wifi/IWifiManager.aidl
+++ b/wifi/java/android/net/wifi/IWifiManager.aidl
@@ -147,8 +147,10 @@
 
     void stopWatchLocalOnlyHotspot();
 
+    @UnsupportedAppUsage
     int getWifiApEnabledState();
 
+    @UnsupportedAppUsage
     WifiConfiguration getWifiApConfiguration();
 
     boolean setWifiApConfiguration(in WifiConfiguration wifiConfig, String packageName);
@@ -173,6 +175,7 @@
 
     void factoryReset(String packageName);
 
+    @UnsupportedAppUsage
     Network getCurrentNetwork();
 
     byte[] retrieveBackupData();
diff --git a/wifi/java/android/net/wifi/PasspointManagementObjectDefinition.java b/wifi/java/android/net/wifi/PasspointManagementObjectDefinition.java
index 9fc1706..70577b9 100644
--- a/wifi/java/android/net/wifi/PasspointManagementObjectDefinition.java
+++ b/wifi/java/android/net/wifi/PasspointManagementObjectDefinition.java
@@ -63,7 +63,7 @@
     /**
      * Implement the Parcelable interface {@hide}
      */
-    public static final Creator<PasspointManagementObjectDefinition> CREATOR =
+    public static final @android.annotation.NonNull Creator<PasspointManagementObjectDefinition> CREATOR =
             new Creator<PasspointManagementObjectDefinition>() {
                 public PasspointManagementObjectDefinition createFromParcel(Parcel in) {
                     return new PasspointManagementObjectDefinition(
diff --git a/wifi/java/android/net/wifi/RssiPacketCountInfo.java b/wifi/java/android/net/wifi/RssiPacketCountInfo.java
index 0de2033..4301165 100644
--- a/wifi/java/android/net/wifi/RssiPacketCountInfo.java
+++ b/wifi/java/android/net/wifi/RssiPacketCountInfo.java
@@ -60,7 +60,7 @@
         return 0;
     }
 
-    public static final Parcelable.Creator<RssiPacketCountInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<RssiPacketCountInfo> CREATOR =
             new Parcelable.Creator<RssiPacketCountInfo>() {
         @Override
         public RssiPacketCountInfo createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/RttManager.java b/wifi/java/android/net/wifi/RttManager.java
index 9ab374a..6ce2121 100644
--- a/wifi/java/android/net/wifi/RttManager.java
+++ b/wifi/java/android/net/wifi/RttManager.java
@@ -292,7 +292,7 @@
         }
 
         /** Implement the Parcelable interface {@hide} */
-        public static final Creator<RttCapabilities> CREATOR =
+        public static final @android.annotation.NonNull Creator<RttCapabilities> CREATOR =
             new Creator<RttCapabilities>() {
             @Override
             public RttCapabilities createFromParcel(Parcel in) {
@@ -556,7 +556,7 @@
         }
 
         /** Implement the Parcelable interface {@hide} */
-        public static final Creator<ParcelableRttParams> CREATOR =
+        public static final @android.annotation.NonNull Creator<ParcelableRttParams> CREATOR =
                 new Creator<ParcelableRttParams>() {
                     @Override
                     public ParcelableRttParams createFromParcel(Parcel in) {
@@ -859,7 +859,7 @@
         }
 
         /** Implement the Parcelable interface {@hide} */
-        public static final Creator<ParcelableRttResults> CREATOR =
+        public static final @android.annotation.NonNull Creator<ParcelableRttResults> CREATOR =
                 new Creator<ParcelableRttResults>() {
                     @Override
                     public ParcelableRttResults createFromParcel(Parcel in) {
@@ -1158,7 +1158,7 @@
         }
 
         /** Implement {@link Parcelable} interface */
-        public static final Parcelable.Creator<ResponderConfig> CREATOR =
+        public static final @android.annotation.NonNull Parcelable.Creator<ResponderConfig> CREATOR =
                 new Parcelable.Creator<ResponderConfig>() {
             @Override
             public ResponderConfig createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/ScanResult.java b/wifi/java/android/net/wifi/ScanResult.java
index 9b9247d..21fe22e 100644
--- a/wifi/java/android/net/wifi/ScanResult.java
+++ b/wifi/java/android/net/wifi/ScanResult.java
@@ -751,7 +751,7 @@
 
     /** Implement the Parcelable interface {@hide} */
     @UnsupportedAppUsage
-    public static final Creator<ScanResult> CREATOR =
+    public static final @android.annotation.NonNull Creator<ScanResult> CREATOR =
         new Creator<ScanResult>() {
             public ScanResult createFromParcel(Parcel in) {
                 WifiSsid wifiSsid = null;
diff --git a/wifi/java/android/net/wifi/SupplicantState.java b/wifi/java/android/net/wifi/SupplicantState.java
index 369d3a8..de7e2b5 100644
--- a/wifi/java/android/net/wifi/SupplicantState.java
+++ b/wifi/java/android/net/wifi/SupplicantState.java
@@ -251,7 +251,7 @@
     }
 
     /** Implement the Parcelable interface {@hide} */
-    public static final Creator<SupplicantState> CREATOR =
+    public static final @android.annotation.NonNull Creator<SupplicantState> CREATOR =
         new Creator<SupplicantState>() {
             public SupplicantState createFromParcel(Parcel in) {
                 return SupplicantState.valueOf(in.readString());
diff --git a/wifi/java/android/net/wifi/WifiActivityEnergyInfo.java b/wifi/java/android/net/wifi/WifiActivityEnergyInfo.java
index 03c9fbe..0f7fc2d 100644
--- a/wifi/java/android/net/wifi/WifiActivityEnergyInfo.java
+++ b/wifi/java/android/net/wifi/WifiActivityEnergyInfo.java
@@ -100,7 +100,7 @@
             + " }";
     }
 
-    public static final Parcelable.Creator<WifiActivityEnergyInfo> CREATOR =
+    public static final @android.annotation.NonNull Parcelable.Creator<WifiActivityEnergyInfo> CREATOR =
             new Parcelable.Creator<WifiActivityEnergyInfo>() {
         public WifiActivityEnergyInfo createFromParcel(Parcel in) {
             long timestamp = in.readLong();
diff --git a/wifi/java/android/net/wifi/WifiConfiguration.java b/wifi/java/android/net/wifi/WifiConfiguration.java
index 3881e9e..c59ad65 100644
--- a/wifi/java/android/net/wifi/WifiConfiguration.java
+++ b/wifi/java/android/net/wifi/WifiConfiguration.java
@@ -16,6 +16,7 @@
 
 package android.net.wifi;
 
+import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.SystemApi;
 import android.annotation.UnsupportedAppUsage;
@@ -41,6 +42,8 @@
 import java.io.DataInputStream;
 import java.io.DataOutputStream;
 import java.io.IOException;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
 import java.util.Arrays;
 import java.util.BitSet;
 import java.util.HashMap;
@@ -339,6 +342,90 @@
         public static final String[] strings = { "current", "disabled", "enabled" };
     }
 
+    /**
+     * Security types we support.
+     */
+    /** @hide */
+    public static final int SECURITY_TYPE_OPEN = 0;
+    /** @hide */
+    public static final int SECURITY_TYPE_WEP = 1;
+    /** @hide */
+    public static final int SECURITY_TYPE_PSK = 2;
+    /** @hide */
+    public static final int SECURITY_TYPE_EAP = 3;
+    /** @hide */
+    public static final int SECURITY_TYPE_SAE = 4;
+    /** @hide */
+    public static final int SECURITY_TYPE_EAP_SUITE_B = 5;
+    /** @hide */
+    public static final int SECURITY_TYPE_OWE = 6;
+
+    /** @hide */
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef(prefix = { "SECURITY_TYPE_" }, value = {
+            SECURITY_TYPE_OPEN,
+            SECURITY_TYPE_WEP,
+            SECURITY_TYPE_PSK,
+            SECURITY_TYPE_EAP,
+            SECURITY_TYPE_SAE,
+            SECURITY_TYPE_EAP_SUITE_B,
+            SECURITY_TYPE_OWE
+    })
+    public @interface SecurityType {}
+
+    /**
+     * @hide
+     * Set security params (sets the various bitsets exposed in WifiConfiguration).
+     *
+     * @param securityType One of the security types from {@link SecurityType}.
+     */
+    public void setSecurityParams(@SecurityType int securityType) {
+        // Clear all the bitsets.
+        allowedKeyManagement.clear();
+        allowedProtocols.clear();
+        allowedAuthAlgorithms.clear();
+        allowedPairwiseCiphers.clear();
+        allowedGroupCiphers.clear();
+        allowedGroupManagementCiphers.clear();
+        allowedSuiteBCiphers.clear();
+
+        switch (securityType) {
+            case SECURITY_TYPE_OPEN:
+                allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
+                break;
+            case SECURITY_TYPE_WEP:
+                allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
+                allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
+                allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
+                break;
+            case SECURITY_TYPE_PSK:
+                allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
+                break;
+            case SECURITY_TYPE_EAP:
+                allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
+                allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
+                break;
+            case SECURITY_TYPE_SAE:
+                allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SAE);
+                requirePMF = true;
+                break;
+            case SECURITY_TYPE_EAP_SUITE_B:
+                allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SUITE_B_192);
+                allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
+                allowedGroupManagementCiphers.set(WifiConfiguration.GroupMgmtCipher.BIP_GMAC_256);
+                allowedSuiteBCiphers.set(WifiConfiguration.SuiteBCipher.ECDHE_ECDSA);
+                allowedSuiteBCiphers.set(WifiConfiguration.SuiteBCipher.ECDHE_RSA);
+                requirePMF = true;
+                break;
+            case SECURITY_TYPE_OWE:
+                allowedKeyManagement.set(WifiConfiguration.KeyMgmt.OWE);
+                requirePMF = true;
+                break;
+            default:
+                throw new IllegalArgumentException("unknown security type " + securityType);
+        }
+    }
+
     /** @hide */
     public static final int UNKNOWN_UID = -1;
 
@@ -2399,7 +2486,7 @@
 
     /** Implement the Parcelable interface {@hide} */
     @UnsupportedAppUsage
-    public static final Creator<WifiConfiguration> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiConfiguration> CREATOR =
         new Creator<WifiConfiguration>() {
             public WifiConfiguration createFromParcel(Parcel in) {
                 WifiConfiguration config = new WifiConfiguration();
diff --git a/wifi/java/android/net/wifi/WifiEnterpriseConfig.java b/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
index 145e269..7a505a2 100644
--- a/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
+++ b/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
@@ -226,7 +226,7 @@
         ParcelUtil.writeCertificates(dest, mClientCertificateChain);
     }
 
-    public static final Creator<WifiEnterpriseConfig> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiEnterpriseConfig> CREATOR =
             new Creator<WifiEnterpriseConfig>() {
                 @Override
                 public WifiEnterpriseConfig createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/WifiInfo.java b/wifi/java/android/net/wifi/WifiInfo.java
index 089b59a..ee60408 100644
--- a/wifi/java/android/net/wifi/WifiInfo.java
+++ b/wifi/java/android/net/wifi/WifiInfo.java
@@ -16,6 +16,7 @@
 
 package android.net.wifi;
 
+import android.annotation.IntRange;
 import android.annotation.Nullable;
 import android.annotation.SystemApi;
 import android.annotation.UnsupportedAppUsage;
@@ -101,6 +102,11 @@
     private int mLinkSpeed;
 
     /**
+     * Constant for unknown link speed.
+     */
+    public static final int LINK_SPEED_UNKNOWN = -1;
+
+    /**
      * Tx(transmit) Link speed in Mbps
      */
     private int mTxLinkSpeed;
@@ -214,7 +220,7 @@
         mNetworkId = -1;
         mSupplicantState = SupplicantState.UNINITIALIZED;
         mRssi = INVALID_RSSI;
-        mLinkSpeed = -1;
+        mLinkSpeed = LINK_SPEED_UNKNOWN;
         mFrequency = -1;
     }
 
@@ -225,9 +231,9 @@
         setSSID(null);
         setNetworkId(-1);
         setRssi(INVALID_RSSI);
-        setLinkSpeed(-1);
-        setTxLinkSpeedMbps(-1);
-        setRxLinkSpeedMbps(-1);
+        setLinkSpeed(LINK_SPEED_UNKNOWN);
+        setTxLinkSpeedMbps(LINK_SPEED_UNKNOWN);
+        setRxLinkSpeedMbps(LINK_SPEED_UNKNOWN);
         setFrequency(-1);
         setMeteredHint(false);
         setEphemeral(false);
@@ -369,8 +375,9 @@
 
     /**
      * Returns the current link speed in {@link #LINK_SPEED_UNITS}.
-     * @return the link speed or -1 if there is no valid value.
+     * @return the link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is unknown.
      * @see #LINK_SPEED_UNITS
+     * @see #LINK_SPEED_UNKNOWN
      */
     public int getLinkSpeed() {
         return mLinkSpeed;
@@ -384,8 +391,10 @@
 
     /**
      * Returns the current transmit link speed in Mbps.
-     * @return the Tx link speed or -1 if there is no valid value.
+     * @return the Tx link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is unknown.
+     * @see #LINK_SPEED_UNKNOWN
      */
+    @IntRange(from = -1)
     public int getTxLinkSpeedMbps() {
         return mTxLinkSpeed;
     }
@@ -400,8 +409,10 @@
 
     /**
      * Returns the current receive link speed in Mbps.
-     * @return the Rx link speed or -1 if there is no valid value.
+     * @return the Rx link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is unknown.
+     * @see #LINK_SPEED_UNKNOWN
      */
+    @IntRange(from = -1)
     public int getRxLinkSpeedMbps() {
         return mRxLinkSpeed;
     }
@@ -725,7 +736,7 @@
 
     /** Implement the Parcelable interface {@hide} */
     @UnsupportedAppUsage
-    public static final Creator<WifiInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiInfo> CREATOR =
         new Creator<WifiInfo>() {
             public WifiInfo createFromParcel(Parcel in) {
                 WifiInfo info = new WifiInfo();
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
index 6792003..d4a5b46 100644
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ b/wifi/java/android/net/wifi/WifiManager.java
@@ -4575,7 +4575,8 @@
     public static final int DEVICE_MOBILITY_STATE_UNKNOWN = 0;
 
     /**
-     * High movement device mobility state
+     * High movement device mobility state.
+     * e.g. on a bike, in a motor vehicle
      *
      * @see #setDeviceMobilityState(int)
      *
@@ -4585,7 +4586,8 @@
     public static final int DEVICE_MOBILITY_STATE_HIGH_MVMT = 1;
 
     /**
-     * Low movement device mobility state
+     * Low movement device mobility state.
+     * e.g. walking, running
      *
      * @see #setDeviceMobilityState(int)
      *
@@ -4607,6 +4609,8 @@
     /**
      * Updates the device mobility state. Wifi uses this information to adjust the interval between
      * Wifi scans in order to balance power consumption with scan accuracy.
+     * The default mobility state when the device boots is {@link #DEVICE_MOBILITY_STATE_UNKNOWN}.
+     * This API should be called whenever there is a change in the mobility state.
      * @param state the updated device mobility state
      * @hide
      */
diff --git a/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java b/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
index 9d87466..24aa23a 100644
--- a/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
+++ b/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
@@ -74,7 +74,7 @@
     /**
      * @hide
      */
-    public static final Creator<WifiNetworkAgentSpecifier> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiNetworkAgentSpecifier> CREATOR =
             new Creator<WifiNetworkAgentSpecifier>() {
                 @Override
                 public WifiNetworkAgentSpecifier createFromParcel(@NonNull Parcel in) {
diff --git a/wifi/java/android/net/wifi/WifiNetworkConnectionStatistics.java b/wifi/java/android/net/wifi/WifiNetworkConnectionStatistics.java
index 9b2fdc8..8262a7a 100644
--- a/wifi/java/android/net/wifi/WifiNetworkConnectionStatistics.java
+++ b/wifi/java/android/net/wifi/WifiNetworkConnectionStatistics.java
@@ -68,7 +68,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<WifiNetworkConnectionStatistics> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiNetworkConnectionStatistics> CREATOR =
         new Creator<WifiNetworkConnectionStatistics>() {
             public WifiNetworkConnectionStatistics createFromParcel(Parcel in) {
                 int numConnection = in.readInt();
diff --git a/wifi/java/android/net/wifi/WifiNetworkSpecifier.java b/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
index 333b82c..358bf31 100644
--- a/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
+++ b/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
@@ -45,7 +45,7 @@
     /**
      * Builder used to create {@link WifiNetworkSpecifier} objects.
      */
-    public static class Builder {
+    public static final class Builder {
         private static final String MATCH_ALL_SSID_PATTERN_PATH = ".*";
         private static final String MATCH_EMPTY_SSID_PATTERN_PATH = "";
         private static final Pair<MacAddress, MacAddress> MATCH_NO_BSSID_PATTERN1 =
@@ -115,7 +115,7 @@
          *                    string pattern to use for matching the network's SSID.
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setSsidPattern(@NonNull PatternMatcher ssidPattern) {
+        public @NonNull Builder setSsidPattern(@NonNull PatternMatcher ssidPattern) {
             checkNotNull(ssidPattern);
             mSsidPatternMatcher = ssidPattern;
             return this;
@@ -133,7 +133,7 @@
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          * @throws IllegalArgumentException if the SSID is not valid unicode.
          */
-        public Builder setSsid(@NonNull String ssid) {
+        public @NonNull Builder setSsid(@NonNull String ssid) {
             checkNotNull(ssid);
             final CharsetEncoder unicodeEncoder = StandardCharsets.UTF_8.newEncoder();
             if (!unicodeEncoder.canEncode(ssid)) {
@@ -155,7 +155,7 @@
          * @param mask Mask for BSSID pattern.
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setBssidPattern(
+        public @NonNull Builder setBssidPattern(
                 @NonNull MacAddress baseAddress, @NonNull MacAddress mask) {
             checkNotNull(baseAddress, mask);
             mBssidPatternMatcher = Pair.create(baseAddress, mask);
@@ -174,7 +174,7 @@
          * @param bssid BSSID of the network.
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setBssid(@NonNull MacAddress bssid) {
+        public @NonNull Builder setBssid(@NonNull MacAddress bssid) {
             checkNotNull(bssid);
             mBssidPatternMatcher = Pair.create(bssid, MATCH_EXACT_BSSID_PATTERN_MASK);
             return this;
@@ -185,7 +185,7 @@
          *
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setIsEnhancedOpen() {
+        public @NonNull Builder setIsEnhancedOpen() {
             mIsEnhancedOpen = true;
             return this;
         }
@@ -198,7 +198,7 @@
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
          */
-        public Builder setWpa2Passphrase(@NonNull String passphrase) {
+        public @NonNull Builder setWpa2Passphrase(@NonNull String passphrase) {
             checkNotNull(passphrase);
             final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
             if (!asciiEncoder.canEncode(passphrase)) {
@@ -216,7 +216,7 @@
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
          */
-        public Builder setWpa3Passphrase(@NonNull String passphrase) {
+        public @NonNull Builder setWpa3Passphrase(@NonNull String passphrase) {
             checkNotNull(passphrase);
             final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
             if (!asciiEncoder.canEncode(passphrase)) {
@@ -233,7 +233,7 @@
          * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setWpa2EnterpriseConfig(
+        public @NonNull Builder setWpa2EnterpriseConfig(
                 @NonNull WifiEnterpriseConfig enterpriseConfig) {
             checkNotNull(enterpriseConfig);
             mWpa2EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
@@ -247,7 +247,7 @@
          * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setWpa3EnterpriseConfig(
+        public @NonNull Builder setWpa3EnterpriseConfig(
                 @NonNull WifiEnterpriseConfig enterpriseConfig) {
             checkNotNull(enterpriseConfig);
             mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
@@ -263,64 +263,31 @@
          *
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setIsHiddenSsid() {
+        public @NonNull Builder setIsHiddenSsid() {
             mIsHiddenSSID = true;
             return this;
         }
 
-
-        /**
-         * Set defaults for the various low level credential type fields in the newly created
-         * WifiConfiguration object.
-         *
-         * See {@link com.android.server.wifi.WifiConfigManager#setDefaultsInWifiConfiguration(
-         * WifiConfiguration)}.
-         *
-         * @param configuration provided WifiConfiguration object.
-         */
-        private static void setDefaultsInWifiConfiguration(
-                @NonNull WifiConfiguration configuration) {
-            configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
-            configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
-            configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
-            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
-            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
-        }
-
         private void setSecurityParamsInWifiConfiguration(
                 @NonNull WifiConfiguration configuration) {
             if (!TextUtils.isEmpty(mWpa2PskPassphrase)) { // WPA-PSK network.
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
+                configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_PSK);
                 // WifiConfiguration.preSharedKey needs quotes around ASCII password.
                 configuration.preSharedKey = "\"" + mWpa2PskPassphrase + "\"";
             } else if (!TextUtils.isEmpty(mWpa3SaePassphrase)) { // WPA3-SAE network.
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SAE);
-                // PMF mandatory for SAE.
-                configuration.requirePMF = true;
+                configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_SAE);
                 // WifiConfiguration.preSharedKey needs quotes around ASCII password.
                 configuration.preSharedKey = "\"" + mWpa3SaePassphrase + "\"";
             } else if (mWpa2EnterpriseConfig != null) { // WPA-EAP network
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
+                configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP);
                 configuration.enterpriseConfig = mWpa2EnterpriseConfig;
             } else if (mWpa3EnterpriseConfig != null) { // WPA3-SuiteB network
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SUITE_B_192);
-                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
-                // TODO (b/113878056): Verify these params once we verify SuiteB configuration.
-                configuration.allowedGroupManagementCiphers.set(
-                        WifiConfiguration.GroupMgmtCipher.BIP_GMAC_256);
-                configuration.allowedSuiteBCiphers.set(
-                        WifiConfiguration.SuiteBCipher.ECDHE_ECDSA);
-                configuration.allowedSuiteBCiphers.set(
-                        WifiConfiguration.SuiteBCipher.ECDHE_RSA);
-                configuration.requirePMF = true;
+                configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP_SUITE_B);
                 configuration.enterpriseConfig = mWpa3EnterpriseConfig;
             } else if (mIsEnhancedOpen) { // OWE network
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.OWE);
-                // PMF mandatory.
-                configuration.requirePMF = true;
+                configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OWE);
             } else { // Open network
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
+                configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OPEN);
             }
         }
 
@@ -330,7 +297,6 @@
          */
         private WifiConfiguration buildWifiConfiguration() {
             final WifiConfiguration wifiConfiguration = new WifiConfiguration();
-            setDefaultsInWifiConfiguration(wifiConfiguration);
             // WifiConfiguration.SSID needs quotes around unicode SSID.
             if (mSsidPatternMatcher.getType() == PatternMatcher.PATTERN_LITERAL) {
                 wifiConfiguration.SSID = "\"" + mSsidPatternMatcher.getPath() + "\"";
@@ -442,7 +408,7 @@
          * @return Instance of {@link NetworkSpecifier}.
          * @throws IllegalStateException on invalid params set.
          */
-        public NetworkSpecifier build() {
+        public @NonNull NetworkSpecifier build() {
             if (!hasSetAnyPattern()) {
                 throw new IllegalStateException("one of setSsidPattern/setSsid/setBssidPattern/"
                         + "setBssid should be invoked for specifier");
@@ -529,7 +495,7 @@
         this.requestorPackageName = requestorPackageName;
     }
 
-    public static final Creator<WifiNetworkSpecifier> CREATOR =
+    public static final @NonNull Creator<WifiNetworkSpecifier> CREATOR =
             new Creator<WifiNetworkSpecifier>() {
                 @Override
                 public WifiNetworkSpecifier createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java b/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
index 233fa2c..3742b83 100644
--- a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
+++ b/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
@@ -45,7 +45,7 @@
     /**
      * Builder used to create {@link WifiNetworkSuggestion} objects.
      */
-    public static class Builder {
+    public static final class Builder {
         private static final int UNASSIGNED_PRIORITY = -1;
 
         /**
@@ -125,7 +125,7 @@
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          * @throws IllegalArgumentException if the SSID is not valid unicode.
          */
-        public Builder setSsid(@NonNull String ssid) {
+        public @NonNull Builder setSsid(@NonNull String ssid) {
             checkNotNull(ssid);
             final CharsetEncoder unicodeEncoder = StandardCharsets.UTF_8.newEncoder();
             if (!unicodeEncoder.canEncode(ssid)) {
@@ -150,7 +150,7 @@
          * @param bssid BSSID of the network.
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setBssid(@NonNull MacAddress bssid) {
+        public @NonNull Builder setBssid(@NonNull MacAddress bssid) {
             checkNotNull(bssid);
             mBssid = MacAddress.fromBytes(bssid.toByteArray());
             return this;
@@ -161,7 +161,7 @@
          *
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setIsEnhancedOpen() {
+        public @NonNull Builder setIsEnhancedOpen() {
             mIsEnhancedOpen = true;
             return this;
         }
@@ -174,7 +174,7 @@
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
          */
-        public Builder setWpa2Passphrase(@NonNull String passphrase) {
+        public @NonNull Builder setWpa2Passphrase(@NonNull String passphrase) {
             checkNotNull(passphrase);
             final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
             if (!asciiEncoder.canEncode(passphrase)) {
@@ -192,7 +192,7 @@
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
          */
-        public Builder setWpa3Passphrase(@NonNull String passphrase) {
+        public @NonNull Builder setWpa3Passphrase(@NonNull String passphrase) {
             checkNotNull(passphrase);
             final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
             if (!asciiEncoder.canEncode(passphrase)) {
@@ -209,7 +209,7 @@
          * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setWpa2EnterpriseConfig(
+        public @NonNull Builder setWpa2EnterpriseConfig(
                 @NonNull WifiEnterpriseConfig enterpriseConfig) {
             checkNotNull(enterpriseConfig);
             mWpa2EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
@@ -223,7 +223,7 @@
          * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setWpa3EnterpriseConfig(
+        public @NonNull Builder setWpa3EnterpriseConfig(
                 @NonNull WifiEnterpriseConfig enterpriseConfig) {
             checkNotNull(enterpriseConfig);
             mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
@@ -237,7 +237,7 @@
          *
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setIsHiddenSsid() {
+        public @NonNull Builder setIsHiddenSsid() {
             mIsHiddenSSID = true;
             return this;
         }
@@ -255,7 +255,7 @@
          *
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setIsAppInteractionRequired() {
+        public @NonNull Builder setIsAppInteractionRequired() {
             mIsAppInteractionRequired = true;
             return this;
         }
@@ -267,7 +267,7 @@
          *
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setIsUserInteractionRequired() {
+        public @NonNull Builder setIsUserInteractionRequired() {
             mIsUserInteractionRequired = true;
             return this;
         }
@@ -283,7 +283,7 @@
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          * @throws IllegalArgumentException if the priority value is negative.
          */
-        public Builder setPriority(int priority) {
+        public @NonNull Builder setPriority(int priority) {
             if (priority < 0) {
                 throw new IllegalArgumentException("Invalid priority value " + priority);
             }
@@ -298,63 +298,31 @@
          *
          * @return Instance of {@link Builder} to enable chaining of the builder method.
          */
-        public Builder setIsMetered() {
+        public @NonNull Builder setIsMetered() {
             mIsMetered = true;
             return this;
         }
 
-        /**
-         * Set defaults for the various low level credential type fields in the newly created
-         * WifiConfiguration object.
-         *
-         * See {@link com.android.server.wifi.WifiConfigManager#setDefaultsInWifiConfiguration(
-         * WifiConfiguration)}.
-         *
-         * @param configuration provided WifiConfiguration object.
-         */
-        private static void setDefaultsInWifiConfiguration(
-                @NonNull WifiConfiguration configuration) {
-            configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
-            configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
-            configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
-            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
-            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
-        }
-
         private void setSecurityParamsInWifiConfiguration(
                 @NonNull WifiConfiguration configuration) {
             if (!TextUtils.isEmpty(mWpa2PskPassphrase)) { // WPA-PSK network.
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
+                configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_PSK);
                 // WifiConfiguration.preSharedKey needs quotes around ASCII password.
                 configuration.preSharedKey = "\"" + mWpa2PskPassphrase + "\"";
             } else if (!TextUtils.isEmpty(mWpa3SaePassphrase)) { // WPA3-SAE network.
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SAE);
-                // PMF mandatory for SAE.
-                configuration.requirePMF = true;
+                configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_SAE);
                 // WifiConfiguration.preSharedKey needs quotes around ASCII password.
                 configuration.preSharedKey = "\"" + mWpa3SaePassphrase + "\"";
             } else if (mWpa2EnterpriseConfig != null) { // WPA-EAP network
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
+                configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP);
                 configuration.enterpriseConfig = mWpa2EnterpriseConfig;
             } else if (mWpa3EnterpriseConfig != null) { // WPA3-SuiteB network
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SUITE_B_192);
-                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
-                // TODO (b/113878056): Verify these params once we verify SuiteB configuration.
-                configuration.allowedGroupManagementCiphers.set(
-                        WifiConfiguration.GroupMgmtCipher.BIP_GMAC_256);
-                configuration.allowedSuiteBCiphers.set(
-                        WifiConfiguration.SuiteBCipher.ECDHE_ECDSA);
-                configuration.allowedSuiteBCiphers.set(
-                        WifiConfiguration.SuiteBCipher.ECDHE_RSA);
-                configuration.requirePMF = true;
+                configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP_SUITE_B);
                 configuration.enterpriseConfig = mWpa3EnterpriseConfig;
             } else if (mIsEnhancedOpen) { // OWE network
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.OWE);
-                // PMF mandatory.
-                configuration.requirePMF = true;
+                configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OWE);
             } else { // Open network
-                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
+                configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OPEN);
             }
         }
 
@@ -364,7 +332,6 @@
          */
         private WifiConfiguration buildWifiConfiguration() {
             final WifiConfiguration wifiConfiguration = new WifiConfiguration();
-            setDefaultsInWifiConfiguration(wifiConfiguration);
             // WifiConfiguration.SSID needs quotes around unicode SSID.
             wifiConfiguration.SSID = "\"" + mSsid + "\"";
             if (mBssid != null) {
@@ -439,7 +406,7 @@
          * @return Instance of {@link WifiNetworkSuggestion}.
          * @throws IllegalStateException on invalid params set.
          */
-        public WifiNetworkSuggestion build() {
+        public @NonNull WifiNetworkSuggestion build() {
             if (mSsid == null) {
                 throw new IllegalStateException("setSsid should be invoked for suggestion");
             }
@@ -516,7 +483,7 @@
         this.suggestorPackageName = suggestorPackageName;
     }
 
-    public static final Creator<WifiNetworkSuggestion> CREATOR =
+    public static final @NonNull Creator<WifiNetworkSuggestion> CREATOR =
             new Creator<WifiNetworkSuggestion>() {
                 @Override
                 public WifiNetworkSuggestion createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/WifiScanner.java b/wifi/java/android/net/wifi/WifiScanner.java
index acc0518..66dc992 100644
--- a/wifi/java/android/net/wifi/WifiScanner.java
+++ b/wifi/java/android/net/wifi/WifiScanner.java
@@ -259,8 +259,17 @@
          * {@hide}
          */
         @SystemApi
-        @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
         public boolean ignoreLocationSettings;
+        /**
+         * This scan request will be hidden from app-ops noting for location information. This
+         * should only be used by FLP/NLP module on the device which is using the scan results to
+         * compute results for behalf on their clients. FLP/NLP module using this flag should ensure
+         * that they note in app-ops the eventual delivery of location information computed using
+         * these results to their client .
+         * {@hide}
+         */
+        @SystemApi
+        public boolean hideFromAppOps;
 
         /** Implement the Parcelable interface {@hide} */
         public int describeContents() {
@@ -279,6 +288,7 @@
             dest.writeInt(isPnoScan ? 1 : 0);
             dest.writeInt(type);
             dest.writeInt(ignoreLocationSettings ? 1 : 0);
+            dest.writeInt(hideFromAppOps ? 1 : 0);
             if (channels != null) {
                 dest.writeInt(channels.length);
                 for (int i = 0; i < channels.length; i++) {
@@ -300,7 +310,7 @@
         }
 
         /** Implement the Parcelable interface {@hide} */
-        public static final Creator<ScanSettings> CREATOR =
+        public static final @android.annotation.NonNull Creator<ScanSettings> CREATOR =
                 new Creator<ScanSettings>() {
                     public ScanSettings createFromParcel(Parcel in) {
                         ScanSettings settings = new ScanSettings();
@@ -314,6 +324,7 @@
                         settings.isPnoScan = in.readInt() == 1;
                         settings.type = in.readInt();
                         settings.ignoreLocationSettings = in.readInt() == 1;
+                        settings.hideFromAppOps = in.readInt() == 1;
                         int num_channels = in.readInt();
                         settings.channels = new ChannelSpec[num_channels];
                         for (int i = 0; i < num_channels; i++) {
@@ -442,7 +453,7 @@
         }
 
         /** Implement the Parcelable interface {@hide} */
-        public static final Creator<ScanData> CREATOR =
+        public static final @android.annotation.NonNull Creator<ScanData> CREATOR =
                 new Creator<ScanData>() {
                     public ScanData createFromParcel(Parcel in) {
                         int id = in.readInt();
@@ -494,7 +505,7 @@
         }
 
         /** Implement the Parcelable interface {@hide} */
-        public static final Creator<ParcelableScanData> CREATOR =
+        public static final @android.annotation.NonNull Creator<ParcelableScanData> CREATOR =
                 new Creator<ParcelableScanData>() {
                     public ParcelableScanData createFromParcel(Parcel in) {
                         int n = in.readInt();
@@ -542,7 +553,7 @@
         }
 
         /** Implement the Parcelable interface {@hide} */
-        public static final Creator<ParcelableScanResults> CREATOR =
+        public static final @android.annotation.NonNull Creator<ParcelableScanResults> CREATOR =
                 new Creator<ParcelableScanResults>() {
                     public ParcelableScanResults createFromParcel(Parcel in) {
                         int n = in.readInt();
@@ -673,7 +684,7 @@
         }
 
         /** Implement the Parcelable interface {@hide} */
-        public static final Creator<PnoSettings> CREATOR =
+        public static final @android.annotation.NonNull Creator<PnoSettings> CREATOR =
                 new Creator<PnoSettings>() {
                     public PnoSettings createFromParcel(Parcel in) {
                         PnoSettings settings = new PnoSettings();
@@ -1018,7 +1029,7 @@
         }
 
         /** Implement the Parcelable interface {@hide} */
-        public static final Creator<WifiChangeSettings> CREATOR =
+        public static final @android.annotation.NonNull Creator<WifiChangeSettings> CREATOR =
                 new Creator<WifiChangeSettings>() {
                     public WifiChangeSettings createFromParcel(Parcel in) {
                         return new WifiChangeSettings();
@@ -1129,7 +1140,7 @@
         }
 
         /** Implement the Parcelable interface {@hide} */
-        public static final Creator<HotlistSettings> CREATOR =
+        public static final @android.annotation.NonNull Creator<HotlistSettings> CREATOR =
                 new Creator<HotlistSettings>() {
                     public HotlistSettings createFromParcel(Parcel in) {
                         HotlistSettings settings = new HotlistSettings();
@@ -1362,7 +1373,7 @@
         }
 
         /** Implement the Parcelable interface {@hide} */
-        public static final Creator<OperationResult> CREATOR =
+        public static final @android.annotation.NonNull Creator<OperationResult> CREATOR =
                 new Creator<OperationResult>() {
                     public OperationResult createFromParcel(Parcel in) {
                         int reason = in.readInt();
diff --git a/wifi/java/android/net/wifi/WifiSsid.java b/wifi/java/android/net/wifi/WifiSsid.java
index 9acbc14..fd59390 100644
--- a/wifi/java/android/net/wifi/WifiSsid.java
+++ b/wifi/java/android/net/wifi/WifiSsid.java
@@ -252,7 +252,7 @@
 
     /** Implement the Parcelable interface {@hide} */
     @UnsupportedAppUsage
-    public static final Creator<WifiSsid> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiSsid> CREATOR =
         new Creator<WifiSsid>() {
             public WifiSsid createFromParcel(Parcel in) {
                 WifiSsid ssid = new WifiSsid();
diff --git a/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java b/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
index c43818d..2dee971 100644
--- a/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
+++ b/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
@@ -167,7 +167,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<WifiUsabilityStatsEntry> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiUsabilityStatsEntry> CREATOR =
             new Creator<WifiUsabilityStatsEntry>() {
         public WifiUsabilityStatsEntry createFromParcel(Parcel in) {
             return new WifiUsabilityStatsEntry(
diff --git a/wifi/java/android/net/wifi/WpsInfo.java b/wifi/java/android/net/wifi/WpsInfo.java
index ae3104b..00cb243 100644
--- a/wifi/java/android/net/wifi/WpsInfo.java
+++ b/wifi/java/android/net/wifi/WpsInfo.java
@@ -85,7 +85,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<WpsInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<WpsInfo> CREATOR =
         new Creator<WpsInfo>() {
             public WpsInfo createFromParcel(Parcel in) {
                 WpsInfo config = new WpsInfo();
diff --git a/wifi/java/android/net/wifi/WpsResult.java b/wifi/java/android/net/wifi/WpsResult.java
index d4fd3e2..f2ffb6f 100644
--- a/wifi/java/android/net/wifi/WpsResult.java
+++ b/wifi/java/android/net/wifi/WpsResult.java
@@ -74,7 +74,7 @@
     }
 
     /** Implement the Parcelable interface {@hide} */
-    public static final Creator<WpsResult> CREATOR =
+    public static final @android.annotation.NonNull Creator<WpsResult> CREATOR =
         new Creator<WpsResult>() {
             public WpsResult createFromParcel(Parcel in) {
                 WpsResult result = new WpsResult();
diff --git a/wifi/java/android/net/wifi/aware/Characteristics.java b/wifi/java/android/net/wifi/aware/Characteristics.java
index 70474fd..e2cf4dc 100644
--- a/wifi/java/android/net/wifi/aware/Characteristics.java
+++ b/wifi/java/android/net/wifi/aware/Characteristics.java
@@ -87,7 +87,7 @@
         return 0;
     }
 
-    public static final Creator<Characteristics> CREATOR =
+    public static final @android.annotation.NonNull Creator<Characteristics> CREATOR =
             new Creator<Characteristics>() {
                 @Override
                 public Characteristics createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/aware/ConfigRequest.java b/wifi/java/android/net/wifi/aware/ConfigRequest.java
index cc14ab2..1e46d1b 100644
--- a/wifi/java/android/net/wifi/aware/ConfigRequest.java
+++ b/wifi/java/android/net/wifi/aware/ConfigRequest.java
@@ -112,7 +112,7 @@
         dest.writeIntArray(mDiscoveryWindowInterval);
     }
 
-    public static final Creator<ConfigRequest> CREATOR = new Creator<ConfigRequest>() {
+    public static final @android.annotation.NonNull Creator<ConfigRequest> CREATOR = new Creator<ConfigRequest>() {
         @Override
         public ConfigRequest[] newArray(int size) {
             return new ConfigRequest[size];
diff --git a/wifi/java/android/net/wifi/aware/ParcelablePeerHandle.java b/wifi/java/android/net/wifi/aware/ParcelablePeerHandle.java
index 4ddf872..ce67abf 100644
--- a/wifi/java/android/net/wifi/aware/ParcelablePeerHandle.java
+++ b/wifi/java/android/net/wifi/aware/ParcelablePeerHandle.java
@@ -43,7 +43,7 @@
         dest.writeInt(peerId);
     }
 
-    public static final Creator<ParcelablePeerHandle> CREATOR =
+    public static final @android.annotation.NonNull Creator<ParcelablePeerHandle> CREATOR =
             new Creator<ParcelablePeerHandle>() {
                 @Override
                 public ParcelablePeerHandle[] newArray(int size) {
diff --git a/wifi/java/android/net/wifi/aware/PublishConfig.java b/wifi/java/android/net/wifi/aware/PublishConfig.java
index d43f727..f0c7967 100644
--- a/wifi/java/android/net/wifi/aware/PublishConfig.java
+++ b/wifi/java/android/net/wifi/aware/PublishConfig.java
@@ -129,7 +129,7 @@
         dest.writeInt(mEnableRanging ? 1 : 0);
     }
 
-    public static final Creator<PublishConfig> CREATOR = new Creator<PublishConfig>() {
+    public static final @android.annotation.NonNull Creator<PublishConfig> CREATOR = new Creator<PublishConfig>() {
         @Override
         public PublishConfig[] newArray(int size) {
             return new PublishConfig[size];
diff --git a/wifi/java/android/net/wifi/aware/SubscribeConfig.java b/wifi/java/android/net/wifi/aware/SubscribeConfig.java
index 51353c6..f477490 100644
--- a/wifi/java/android/net/wifi/aware/SubscribeConfig.java
+++ b/wifi/java/android/net/wifi/aware/SubscribeConfig.java
@@ -146,7 +146,7 @@
         dest.writeInt(mMaxDistanceMmSet ? 1 : 0);
     }
 
-    public static final Creator<SubscribeConfig> CREATOR = new Creator<SubscribeConfig>() {
+    public static final @android.annotation.NonNull Creator<SubscribeConfig> CREATOR = new Creator<SubscribeConfig>() {
         @Override
         public SubscribeConfig[] newArray(int size) {
             return new SubscribeConfig[size];
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareAgentNetworkSpecifier.java b/wifi/java/android/net/wifi/aware/WifiAwareAgentNetworkSpecifier.java
index 4bee837..9164d04 100644
--- a/wifi/java/android/net/wifi/aware/WifiAwareAgentNetworkSpecifier.java
+++ b/wifi/java/android/net/wifi/aware/WifiAwareAgentNetworkSpecifier.java
@@ -77,7 +77,7 @@
         dest.writeArray(mNetworkSpecifiers.toArray());
     }
 
-    public static final Creator<WifiAwareAgentNetworkSpecifier> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiAwareAgentNetworkSpecifier> CREATOR =
             new Creator<WifiAwareAgentNetworkSpecifier>() {
                 @Override
                 public WifiAwareAgentNetworkSpecifier createFromParcel(Parcel in) {
@@ -210,7 +210,7 @@
             dest.writeBlob(mData);
         }
 
-        public static final Creator<ByteArrayWrapper> CREATOR =
+        public static final @android.annotation.NonNull Creator<ByteArrayWrapper> CREATOR =
                 new Creator<ByteArrayWrapper>() {
                     @Override
                     public ByteArrayWrapper createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareNetworkInfo.java b/wifi/java/android/net/wifi/aware/WifiAwareNetworkInfo.java
index b258906..020cb56 100644
--- a/wifi/java/android/net/wifi/aware/WifiAwareNetworkInfo.java
+++ b/wifi/java/android/net/wifi/aware/WifiAwareNetworkInfo.java
@@ -116,7 +116,7 @@
         dest.writeInt(mTransportProtocol);
     }
 
-    public static final Creator<WifiAwareNetworkInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiAwareNetworkInfo> CREATOR =
             new Creator<WifiAwareNetworkInfo>() {
                 @Override
                 public WifiAwareNetworkInfo createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareNetworkSpecifier.java b/wifi/java/android/net/wifi/aware/WifiAwareNetworkSpecifier.java
index a93a6d5..59f534a 100644
--- a/wifi/java/android/net/wifi/aware/WifiAwareNetworkSpecifier.java
+++ b/wifi/java/android/net/wifi/aware/WifiAwareNetworkSpecifier.java
@@ -167,7 +167,7 @@
         this.requestorUid = requestorUid;
     }
 
-    public static final Creator<WifiAwareNetworkSpecifier> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiAwareNetworkSpecifier> CREATOR =
             new Creator<WifiAwareNetworkSpecifier>() {
                 @Override
                 public WifiAwareNetworkSpecifier createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/hotspot2/OsuProvider.java b/wifi/java/android/net/wifi/hotspot2/OsuProvider.java
index f91790f..a1684d6 100644
--- a/wifi/java/android/net/wifi/hotspot2/OsuProvider.java
+++ b/wifi/java/android/net/wifi/hotspot2/OsuProvider.java
@@ -256,7 +256,7 @@
                 + " mIcon=" + mIcon;
     }
 
-    public static final Creator<OsuProvider> CREATOR =
+    public static final @android.annotation.NonNull Creator<OsuProvider> CREATOR =
             new Creator<OsuProvider>() {
                 @Override
                 public OsuProvider createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/hotspot2/PasspointConfiguration.java b/wifi/java/android/net/wifi/hotspot2/PasspointConfiguration.java
index f09d864..9095b5d 100644
--- a/wifi/java/android/net/wifi/hotspot2/PasspointConfiguration.java
+++ b/wifi/java/android/net/wifi/hotspot2/PasspointConfiguration.java
@@ -600,7 +600,7 @@
         return true;
     }
 
-    public static final Creator<PasspointConfiguration> CREATOR =
+    public static final @android.annotation.NonNull Creator<PasspointConfiguration> CREATOR =
         new Creator<PasspointConfiguration>() {
             @Override
             public PasspointConfiguration createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/hotspot2/pps/Credential.java b/wifi/java/android/net/wifi/hotspot2/pps/Credential.java
index 28165e15..9409c03 100644
--- a/wifi/java/android/net/wifi/hotspot2/pps/Credential.java
+++ b/wifi/java/android/net/wifi/hotspot2/pps/Credential.java
@@ -428,7 +428,7 @@
             return true;
         }
 
-        public static final Creator<UserCredential> CREATOR =
+        public static final @android.annotation.NonNull Creator<UserCredential> CREATOR =
             new Creator<UserCredential>() {
                 @Override
                 public UserCredential createFromParcel(Parcel in) {
@@ -599,7 +599,7 @@
             return true;
         }
 
-        public static final Creator<CertificateCredential> CREATOR =
+        public static final @android.annotation.NonNull Creator<CertificateCredential> CREATOR =
             new Creator<CertificateCredential>() {
                 @Override
                 public CertificateCredential createFromParcel(Parcel in) {
@@ -770,7 +770,7 @@
             return true;
         }
 
-        public static final Creator<SimCredential> CREATOR =
+        public static final @android.annotation.NonNull Creator<SimCredential> CREATOR =
             new Creator<SimCredential>() {
                 @Override
                 public SimCredential createFromParcel(Parcel in) {
@@ -1086,7 +1086,7 @@
         return true;
     }
 
-    public static final Creator<Credential> CREATOR =
+    public static final @android.annotation.NonNull Creator<Credential> CREATOR =
         new Creator<Credential>() {
             @Override
             public Credential createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/hotspot2/pps/HomeSp.java b/wifi/java/android/net/wifi/hotspot2/pps/HomeSp.java
index d829ea8..49a76c3 100644
--- a/wifi/java/android/net/wifi/hotspot2/pps/HomeSp.java
+++ b/wifi/java/android/net/wifi/hotspot2/pps/HomeSp.java
@@ -345,7 +345,7 @@
         return true;
     }
 
-    public static final Creator<HomeSp> CREATOR =
+    public static final @android.annotation.NonNull Creator<HomeSp> CREATOR =
         new Creator<HomeSp>() {
             @Override
             public HomeSp createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/hotspot2/pps/Policy.java b/wifi/java/android/net/wifi/hotspot2/pps/Policy.java
index ee0894b..b0a2cc3 100644
--- a/wifi/java/android/net/wifi/hotspot2/pps/Policy.java
+++ b/wifi/java/android/net/wifi/hotspot2/pps/Policy.java
@@ -279,7 +279,7 @@
             return true;
         }
 
-        public static final Creator<RoamingPartner> CREATOR =
+        public static final @android.annotation.NonNull Creator<RoamingPartner> CREATOR =
             new Creator<RoamingPartner>() {
                 @Override
                 public RoamingPartner createFromParcel(Parcel in) {
@@ -475,7 +475,7 @@
         return true;
     }
 
-    public static final Creator<Policy> CREATOR =
+    public static final @android.annotation.NonNull Creator<Policy> CREATOR =
         new Creator<Policy>() {
             @Override
             public Policy createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java b/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java
index 8d30ff1..4a8aa36 100644
--- a/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java
+++ b/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java
@@ -378,7 +378,7 @@
         return true;
     }
 
-    public static final Creator<UpdateParameter> CREATOR =
+    public static final @android.annotation.NonNull Creator<UpdateParameter> CREATOR =
         new Creator<UpdateParameter>() {
             @Override
             public UpdateParameter createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pConfig.java b/wifi/java/android/net/wifi/p2p/WifiP2pConfig.java
index f931ad2..5e1f569 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pConfig.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pConfig.java
@@ -26,6 +26,7 @@
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
+import java.util.regex.PatternSyntaxException;
 
 /**
  * A class representing a Wi-Fi P2p configuration for setting up a connection
@@ -192,7 +193,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<WifiP2pConfig> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiP2pConfig> CREATOR =
         new Creator<WifiP2pConfig>() {
             public WifiP2pConfig createFromParcel(Parcel in) {
                 WifiP2pConfig config = new WifiP2pConfig();
@@ -252,7 +253,12 @@
          * Specify the network name, a.k.a. group name,
          * for creating or joining a group.
          * <p>
-         *     Must be called - an empty network name is not valid.
+         * A network name shall begin with "DIRECT-xy". x and y are selected
+         * from the following character set: upper case letters, lower case
+         * letters and numbers.
+         * <p>
+         *     Must be called - an empty network name or an network name
+         *     not conforming to the P2P Group ID naming rule is not valid.
          *
          * @param networkName network name of a group.
          * @return The builder to facilitate chaining
@@ -263,6 +269,14 @@
                 throw new IllegalArgumentException(
                         "network name must be non-empty.");
             }
+            try {
+                if (!networkName.matches("^DIRECT-[a-zA-Z0-9]{2}.*")) {
+                    throw new IllegalArgumentException(
+                            "network name must starts with the prefix DIRECT-xy.");
+                }
+            } catch (PatternSyntaxException e) {
+                // can never happen (fixed pattern)
+            }
             mNetworkName = networkName;
             return this;
         }
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pDevice.java b/wifi/java/android/net/wifi/p2p/WifiP2pDevice.java
index ab7bb68..c5318a9 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pDevice.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pDevice.java
@@ -385,7 +385,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<WifiP2pDevice> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiP2pDevice> CREATOR =
         new Creator<WifiP2pDevice>() {
             @Override
             public WifiP2pDevice createFromParcel(Parcel in) {
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pDeviceList.java b/wifi/java/android/net/wifi/p2p/WifiP2pDeviceList.java
index 72edd56..acf06fb 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pDeviceList.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pDeviceList.java
@@ -200,7 +200,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<WifiP2pDeviceList> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiP2pDeviceList> CREATOR =
         new Creator<WifiP2pDeviceList>() {
             public WifiP2pDeviceList createFromParcel(Parcel in) {
                 WifiP2pDeviceList deviceList = new WifiP2pDeviceList();
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pGroup.java b/wifi/java/android/net/wifi/p2p/WifiP2pGroup.java
index 8a1b21c..4866bd4 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pGroup.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pGroup.java
@@ -332,7 +332,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<WifiP2pGroup> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiP2pGroup> CREATOR =
         new Creator<WifiP2pGroup>() {
             public WifiP2pGroup createFromParcel(Parcel in) {
                 WifiP2pGroup group = new WifiP2pGroup();
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pGroupList.java b/wifi/java/android/net/wifi/p2p/WifiP2pGroupList.java
index 8d92253..62524d9 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pGroupList.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pGroupList.java
@@ -231,7 +231,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<WifiP2pGroupList> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiP2pGroupList> CREATOR =
         new Creator<WifiP2pGroupList>() {
             public WifiP2pGroupList createFromParcel(Parcel in) {
                 WifiP2pGroupList grpList = new WifiP2pGroupList();
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pInfo.java b/wifi/java/android/net/wifi/p2p/WifiP2pInfo.java
index 8972b7e..33bc37e 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pInfo.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pInfo.java
@@ -77,7 +77,7 @@
     }
 
     /** Implement the Parcelable interface */
-    public static final Creator<WifiP2pInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiP2pInfo> CREATOR =
         new Creator<WifiP2pInfo>() {
             public WifiP2pInfo createFromParcel(Parcel in) {
                 WifiP2pInfo info = new WifiP2pInfo();
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pWfdInfo.java b/wifi/java/android/net/wifi/p2p/WifiP2pWfdInfo.java
index f9ef08f..3caa280 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pWfdInfo.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pWfdInfo.java
@@ -195,7 +195,7 @@
 
     /** Implement the Parcelable interface */
     @UnsupportedAppUsage
-    public static final Creator<WifiP2pWfdInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiP2pWfdInfo> CREATOR =
         new Creator<WifiP2pWfdInfo>() {
             public WifiP2pWfdInfo createFromParcel(Parcel in) {
                 WifiP2pWfdInfo device = new WifiP2pWfdInfo();
diff --git a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceInfo.java b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceInfo.java
index e9ee7bb..db0bdb8 100644
--- a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceInfo.java
+++ b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceInfo.java
@@ -171,7 +171,7 @@
 
     /** Implement the Parcelable interface {@hide} */
     @UnsupportedAppUsage
-    public static final Creator<WifiP2pServiceInfo> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiP2pServiceInfo> CREATOR =
         new Creator<WifiP2pServiceInfo>() {
             public WifiP2pServiceInfo createFromParcel(Parcel in) {
 
diff --git a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceRequest.java b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceRequest.java
index f1f2262..87528c4 100644
--- a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceRequest.java
+++ b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceRequest.java
@@ -266,7 +266,7 @@
 
     /** Implement the Parcelable interface {@hide} */
     @UnsupportedAppUsage
-    public static final Creator<WifiP2pServiceRequest> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiP2pServiceRequest> CREATOR =
         new Creator<WifiP2pServiceRequest>() {
             public WifiP2pServiceRequest createFromParcel(Parcel in) {
                 int servType = in.readInt();
diff --git a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceResponse.java b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceResponse.java
index 1020fd2..1b9c080 100644
--- a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceResponse.java
+++ b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceResponse.java
@@ -350,7 +350,7 @@
     }
 
     /** Implement the Parcelable interface {@hide} */
-    public static final Creator<WifiP2pServiceResponse> CREATOR =
+    public static final @android.annotation.NonNull Creator<WifiP2pServiceResponse> CREATOR =
         new Creator<WifiP2pServiceResponse>() {
             public WifiP2pServiceResponse createFromParcel(Parcel in) {
 
diff --git a/wifi/java/android/net/wifi/rtt/CivicLocation.java b/wifi/java/android/net/wifi/rtt/CivicLocation.java
index a669d77..b438a69 100644
--- a/wifi/java/android/net/wifi/rtt/CivicLocation.java
+++ b/wifi/java/android/net/wifi/rtt/CivicLocation.java
@@ -91,7 +91,7 @@
         mCivicAddressElements = in.readSparseArray(this.getClass().getClassLoader());
     }
 
-    public static final Creator<CivicLocation> CREATOR = new Creator<CivicLocation>() {
+    public static final @android.annotation.NonNull Creator<CivicLocation> CREATOR = new Creator<CivicLocation>() {
         @Override
         public CivicLocation createFromParcel(Parcel in) {
             return new CivicLocation(in);
diff --git a/wifi/java/android/net/wifi/rtt/RangingRequest.java b/wifi/java/android/net/wifi/rtt/RangingRequest.java
index 339233b..70af03e 100644
--- a/wifi/java/android/net/wifi/rtt/RangingRequest.java
+++ b/wifi/java/android/net/wifi/rtt/RangingRequest.java
@@ -76,7 +76,7 @@
         dest.writeList(mRttPeers);
     }
 
-    public static final Creator<RangingRequest> CREATOR = new Creator<RangingRequest>() {
+    public static final @android.annotation.NonNull Creator<RangingRequest> CREATOR = new Creator<RangingRequest>() {
         @Override
         public RangingRequest[] newArray(int size) {
             return new RangingRequest[size];
diff --git a/wifi/java/android/net/wifi/rtt/RangingResult.java b/wifi/java/android/net/wifi/rtt/RangingResult.java
index b53b35c..7c29ff4 100644
--- a/wifi/java/android/net/wifi/rtt/RangingResult.java
+++ b/wifi/java/android/net/wifi/rtt/RangingResult.java
@@ -349,7 +349,7 @@
         dest.writeLong(mTimestamp);
     }
 
-    public static final Creator<RangingResult> CREATOR = new Creator<RangingResult>() {
+    public static final @android.annotation.NonNull Creator<RangingResult> CREATOR = new Creator<RangingResult>() {
         @Override
         public RangingResult[] newArray(int size) {
             return new RangingResult[size];
diff --git a/wifi/java/android/net/wifi/rtt/ResponderConfig.java b/wifi/java/android/net/wifi/rtt/ResponderConfig.java
index 166af6c..e6ae483 100644
--- a/wifi/java/android/net/wifi/rtt/ResponderConfig.java
+++ b/wifi/java/android/net/wifi/rtt/ResponderConfig.java
@@ -406,7 +406,7 @@
         dest.writeInt(preamble);
     }
 
-    public static final Creator<ResponderConfig> CREATOR = new Creator<ResponderConfig>() {
+    public static final @android.annotation.NonNull Creator<ResponderConfig> CREATOR = new Creator<ResponderConfig>() {
         @Override
         public ResponderConfig[] newArray(int size) {
             return new ResponderConfig[size];
diff --git a/wifi/java/android/net/wifi/rtt/ResponderLocation.java b/wifi/java/android/net/wifi/rtt/ResponderLocation.java
index 2912a67..7b25eed 100644
--- a/wifi/java/android/net/wifi/rtt/ResponderLocation.java
+++ b/wifi/java/android/net/wifi/rtt/ResponderLocation.java
@@ -439,7 +439,7 @@
         }
     }
 
-    public static final Creator<ResponderLocation> CREATOR = new Creator<ResponderLocation>() {
+    public static final @android.annotation.NonNull Creator<ResponderLocation> CREATOR = new Creator<ResponderLocation>() {
         @Override
         public ResponderLocation createFromParcel(Parcel in) {
             return new ResponderLocation(in);
diff --git a/wifi/tests/src/android/net/wifi/WifiNetworkSpecifierTest.java b/wifi/tests/src/android/net/wifi/WifiNetworkSpecifierTest.java
index bef33b7..feac0e5 100644
--- a/wifi/tests/src/android/net/wifi/WifiNetworkSpecifierTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiNetworkSpecifierTest.java
@@ -69,16 +69,6 @@
         assertEquals(MacAddress.ALL_ZEROS_ADDRESS, wifiNetworkSpecifier.bssidPatternMatcher.second);
         assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedKeyManagement
                 .get(WifiConfiguration.KeyMgmt.NONE));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedProtocols
-                .get(WifiConfiguration.Protocol.RSN));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedAuthAlgorithms
-                .get(WifiConfiguration.AuthAlgorithm.OPEN));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedPairwiseCiphers
-                .get(WifiConfiguration.PairwiseCipher.CCMP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.CCMP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.TKIP));
     }
 
     /**
@@ -105,16 +95,6 @@
                 wifiNetworkSpecifier.bssidPatternMatcher.second);
         assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedKeyManagement
                 .get(WifiConfiguration.KeyMgmt.WPA_PSK));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedProtocols
-                .get(WifiConfiguration.Protocol.RSN));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedAuthAlgorithms
-                .get(WifiConfiguration.AuthAlgorithm.OPEN));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedPairwiseCiphers
-                .get(WifiConfiguration.PairwiseCipher.CCMP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.CCMP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.TKIP));
         assertEquals("\"" + TEST_PRESHARED_KEY + "\"",
                 wifiNetworkSpecifier.wifiConfiguration.preSharedKey);
     }
@@ -150,16 +130,6 @@
                 .get(WifiConfiguration.KeyMgmt.WPA_EAP));
         assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedKeyManagement
                 .get(WifiConfiguration.KeyMgmt.IEEE8021X));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedProtocols
-                .get(WifiConfiguration.Protocol.RSN));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedAuthAlgorithms
-                .get(WifiConfiguration.AuthAlgorithm.OPEN));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedPairwiseCiphers
-                .get(WifiConfiguration.PairwiseCipher.CCMP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.CCMP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.TKIP));
         assertTrue(wifiNetworkSpecifier.wifiConfiguration.hiddenSSID);
         assertEquals(enterpriseConfig.getEapMethod(),
                 wifiNetworkSpecifier.wifiConfiguration.enterpriseConfig.getEapMethod());
diff --git a/wifi/tests/src/android/net/wifi/p2p/WifiP2pConfigTest.java b/wifi/tests/src/android/net/wifi/p2p/WifiP2pConfigTest.java
new file mode 100644
index 0000000..560c88e
--- /dev/null
+++ b/wifi/tests/src/android/net/wifi/p2p/WifiP2pConfigTest.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.wifi.p2p;
+
+import static org.junit.Assert.fail;
+
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+
+/**
+ * Unit test harness for {@link android.net.wifi.p2p.WifiP2pConfig}
+ */
+@SmallTest
+public class WifiP2pConfigTest {
+    /**
+     * Check network name setter
+     */
+    @Test
+    public void testBuilderInvalidNetworkName() throws Exception {
+        WifiP2pConfig.Builder b = new WifiP2pConfig.Builder();
+
+        // sunny case
+        try {
+            b.setNetworkName("DIRECT-ab-Hello");
+        } catch (IllegalArgumentException e) {
+            fail("Unexpected IllegalArgumentException");
+        }
+
+        // sunny case, no trailing string
+        try {
+            b.setNetworkName("DIRECT-WR");
+        } catch (IllegalArgumentException e) {
+            fail("Unexpected IllegalArgumentException");
+        }
+
+        // less than 9 characters.
+        try {
+            b.setNetworkName("DIRECT-z");
+            fail("expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) { }
+
+        // not starts with DIRECT-xy.
+        try {
+            b.setNetworkName("ABCDEFGHIJK");
+            fail("expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) { }
+
+        // not starts with uppercase DIRECT-xy
+        try {
+            b.setNetworkName("direct-ab");
+            fail("expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) { }
+
+        // x and y are not selected from upper case letters, lower case letters or
+        // numbers.
+        try {
+            b.setNetworkName("direct-a?");
+            fail("expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) { }
+    }
+}