Merge "Add log before doRestoreFinished is called on BackupAgent." into oc-dev
diff --git a/api/current.txt b/api/current.txt
index 35726f1..698c9b6 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -766,6 +766,7 @@
     field public static final int itemIconDisabledAlpha = 16843057; // 0x1010131
     field public static final int itemPadding = 16843565; // 0x101032d
     field public static final int itemTextAppearance = 16843052; // 0x101012c
+    field public static final int justificationMode = 16844138; // 0x101056a
     field public static final int keepScreenOn = 16843286; // 0x1010216
     field public static final int key = 16843240; // 0x10101e8
     field public static final int keyBackground = 16843315; // 0x1010233
@@ -6892,15 +6893,15 @@
   public abstract class JobServiceEngine {
     ctor public JobServiceEngine(android.app.Service);
     method public final android.os.IBinder getBinder();
-    method public final void jobFinished(android.app.job.JobParameters, boolean);
+    method public void jobFinished(android.app.job.JobParameters, boolean);
     method public abstract boolean onStartJob(android.app.job.JobParameters);
     method public abstract boolean onStopJob(android.app.job.JobParameters);
   }
 
   public final class JobWorkItem implements android.os.Parcelable {
     ctor public JobWorkItem(android.content.Intent);
-    ctor public JobWorkItem(android.os.Parcel);
     method public int describeContents();
+    method public int getDeliveryCount();
     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;
@@ -6925,6 +6926,7 @@
 
   public final class ExternalStorageStats implements android.os.Parcelable {
     method public int describeContents();
+    method public long getAppBytes();
     method public long getAudioBytes();
     method public long getImageBytes();
     method public long getTotalBytes();
@@ -14752,16 +14754,16 @@
     method public float getZ();
   }
 
-  public final class HardwareBuffer implements android.os.Parcelable {
+  public final class HardwareBuffer implements java.lang.AutoCloseable android.os.Parcelable {
+    method public void close();
     method public static android.hardware.HardwareBuffer create(int, int, int, int, long);
     method public int describeContents();
-    method public void destroy();
     method public int getFormat();
     method public int getHeight();
     method public int getLayers();
     method public long getUsage();
     method public int getWidth();
-    method public boolean isDestroyed();
+    method public boolean isClosed();
     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;
@@ -22779,7 +22781,7 @@
     method public void releaseDrm() throws android.media.MediaPlayer.NoDrmSchemeException;
     method public void reset();
     method public void restoreKeys(byte[]) throws android.media.MediaPlayer.NoDrmSchemeException;
-    method public void seekTo(int, int) throws java.lang.IllegalStateException;
+    method public void seekTo(long, int);
     method public void seekTo(int) throws java.lang.IllegalStateException;
     method public void selectTrack(int) throws java.lang.IllegalStateException;
     method public void setAudioAttributes(android.media.AudioAttributes) throws java.lang.IllegalArgumentException;
@@ -34929,7 +34931,7 @@
     field public static final java.lang.String ACTION_MANAGE_APPLICATIONS_SETTINGS = "android.settings.MANAGE_APPLICATIONS_SETTINGS";
     field public static final java.lang.String ACTION_MANAGE_DEFAULT_APPS_SETTINGS = "android.settings.MANAGE_DEFAULT_APPS_SETTINGS";
     field public static final java.lang.String ACTION_MANAGE_OVERLAY_PERMISSION = "android.settings.action.MANAGE_OVERLAY_PERMISSION";
-    field public static final java.lang.String ACTION_MANAGE_UNKNOWN_APP_SOURCES = "android.settings.action.MANAGE_UNKNOWN_APP_SOURCES";
+    field public static final java.lang.String ACTION_MANAGE_UNKNOWN_APP_SOURCES = "android.settings.MANAGE_UNKNOWN_APP_SOURCES";
     field public static final java.lang.String ACTION_MANAGE_WRITE_SETTINGS = "android.settings.action.MANAGE_WRITE_SETTINGS";
     field public static final java.lang.String ACTION_MEMORY_CARD_SETTINGS = "android.settings.MEMORY_CARD_SETTINGS";
     field public static final java.lang.String ACTION_NETWORK_OPERATOR_SETTINGS = "android.settings.NETWORK_OPERATOR_SETTINGS";
diff --git a/api/removed.txt b/api/removed.txt
index 189536d..dc9c54e 100644
--- a/api/removed.txt
+++ b/api/removed.txt
@@ -126,6 +126,11 @@
 
 package android.hardware {
 
+  public final class HardwareBuffer implements java.lang.AutoCloseable android.os.Parcelable {
+    method public deprecated void destroy();
+    method public deprecated boolean isDestroyed();
+  }
+
   public final class SensorDirectChannel implements java.nio.channels.Channel {
     method public deprecated boolean isValid();
   }
diff --git a/api/system-current.txt b/api/system-current.txt
index b9125bf..b89964d 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -884,6 +884,7 @@
     field public static final int itemIconDisabledAlpha = 16843057; // 0x1010131
     field public static final int itemPadding = 16843565; // 0x101032d
     field public static final int itemTextAppearance = 16843052; // 0x101012c
+    field public static final int justificationMode = 16844138; // 0x101056a
     field public static final int keepScreenOn = 16843286; // 0x1010216
     field public static final int key = 16843240; // 0x10101e8
     field public static final int keyBackground = 16843315; // 0x1010233
@@ -7328,15 +7329,15 @@
   public abstract class JobServiceEngine {
     ctor public JobServiceEngine(android.app.Service);
     method public final android.os.IBinder getBinder();
-    method public final void jobFinished(android.app.job.JobParameters, boolean);
+    method public void jobFinished(android.app.job.JobParameters, boolean);
     method public abstract boolean onStartJob(android.app.job.JobParameters);
     method public abstract boolean onStopJob(android.app.job.JobParameters);
   }
 
   public final class JobWorkItem implements android.os.Parcelable {
     ctor public JobWorkItem(android.content.Intent);
-    ctor public JobWorkItem(android.os.Parcel);
     method public int describeContents();
+    method public int getDeliveryCount();
     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;
@@ -7390,6 +7391,7 @@
 
   public final class ExternalStorageStats implements android.os.Parcelable {
     method public int describeContents();
+    method public long getAppBytes();
     method public long getAudioBytes();
     method public long getImageBytes();
     method public long getTotalBytes();
@@ -15526,16 +15528,16 @@
     method public float getZ();
   }
 
-  public final class HardwareBuffer implements android.os.Parcelable {
+  public final class HardwareBuffer implements java.lang.AutoCloseable android.os.Parcelable {
+    method public void close();
     method public static android.hardware.HardwareBuffer create(int, int, int, int, long);
     method public int describeContents();
-    method public void destroy();
     method public int getFormat();
     method public int getHeight();
     method public int getLayers();
     method public long getUsage();
     method public int getWidth();
-    method public boolean isDestroyed();
+    method public boolean isClosed();
     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;
@@ -24615,7 +24617,7 @@
     method public void releaseDrm() throws android.media.MediaPlayer.NoDrmSchemeException;
     method public void reset();
     method public void restoreKeys(byte[]) throws android.media.MediaPlayer.NoDrmSchemeException;
-    method public void seekTo(int, int) throws java.lang.IllegalStateException;
+    method public void seekTo(long, int);
     method public void seekTo(int) throws java.lang.IllegalStateException;
     method public void selectTrack(int) throws java.lang.IllegalStateException;
     method public void setAudioAttributes(android.media.AudioAttributes) throws java.lang.IllegalArgumentException;
@@ -38021,7 +38023,7 @@
     field public static final java.lang.String ACTION_MANAGE_APPLICATIONS_SETTINGS = "android.settings.MANAGE_APPLICATIONS_SETTINGS";
     field public static final java.lang.String ACTION_MANAGE_DEFAULT_APPS_SETTINGS = "android.settings.MANAGE_DEFAULT_APPS_SETTINGS";
     field public static final java.lang.String ACTION_MANAGE_OVERLAY_PERMISSION = "android.settings.action.MANAGE_OVERLAY_PERMISSION";
-    field public static final java.lang.String ACTION_MANAGE_UNKNOWN_APP_SOURCES = "android.settings.action.MANAGE_UNKNOWN_APP_SOURCES";
+    field public static final java.lang.String ACTION_MANAGE_UNKNOWN_APP_SOURCES = "android.settings.MANAGE_UNKNOWN_APP_SOURCES";
     field public static final java.lang.String ACTION_MANAGE_WRITE_SETTINGS = "android.settings.action.MANAGE_WRITE_SETTINGS";
     field public static final java.lang.String ACTION_MEMORY_CARD_SETTINGS = "android.settings.MEMORY_CARD_SETTINGS";
     field public static final java.lang.String ACTION_NETWORK_OPERATOR_SETTINGS = "android.settings.NETWORK_OPERATOR_SETTINGS";
diff --git a/api/system-removed.txt b/api/system-removed.txt
index 559ce12..4862bb7 100644
--- a/api/system-removed.txt
+++ b/api/system-removed.txt
@@ -124,6 +124,11 @@
 
 package android.hardware {
 
+  public final class HardwareBuffer implements java.lang.AutoCloseable android.os.Parcelable {
+    method public deprecated void destroy();
+    method public deprecated boolean isDestroyed();
+  }
+
   public final class SensorDirectChannel implements java.nio.channels.Channel {
     method public deprecated boolean isValid();
   }
diff --git a/api/test-current.txt b/api/test-current.txt
index 3675bd8..4cafde5 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -766,6 +766,7 @@
     field public static final int itemIconDisabledAlpha = 16843057; // 0x1010131
     field public static final int itemPadding = 16843565; // 0x101032d
     field public static final int itemTextAppearance = 16843052; // 0x101012c
+    field public static final int justificationMode = 16844138; // 0x101056a
     field public static final int keepScreenOn = 16843286; // 0x1010216
     field public static final int key = 16843240; // 0x10101e8
     field public static final int keyBackground = 16843315; // 0x1010233
@@ -6922,15 +6923,15 @@
   public abstract class JobServiceEngine {
     ctor public JobServiceEngine(android.app.Service);
     method public final android.os.IBinder getBinder();
-    method public final void jobFinished(android.app.job.JobParameters, boolean);
+    method public void jobFinished(android.app.job.JobParameters, boolean);
     method public abstract boolean onStartJob(android.app.job.JobParameters);
     method public abstract boolean onStopJob(android.app.job.JobParameters);
   }
 
   public final class JobWorkItem implements android.os.Parcelable {
     ctor public JobWorkItem(android.content.Intent);
-    ctor public JobWorkItem(android.os.Parcel);
     method public int describeContents();
+    method public int getDeliveryCount();
     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;
@@ -6955,6 +6956,7 @@
 
   public final class ExternalStorageStats implements android.os.Parcelable {
     method public int describeContents();
+    method public long getAppBytes();
     method public long getAudioBytes();
     method public long getImageBytes();
     method public long getTotalBytes();
@@ -13997,6 +13999,7 @@
     method public void draw(android.graphics.Canvas);
     method public int getColor();
     method public int getOpacity();
+    method public android.graphics.Xfermode getXfermode();
     method public void setAlpha(int);
     method public void setColor(int);
     method public void setColorFilter(android.graphics.ColorFilter);
@@ -14797,16 +14800,16 @@
     method public float getZ();
   }
 
-  public final class HardwareBuffer implements android.os.Parcelable {
+  public final class HardwareBuffer implements java.lang.AutoCloseable android.os.Parcelable {
+    method public void close();
     method public static android.hardware.HardwareBuffer create(int, int, int, int, long);
     method public int describeContents();
-    method public void destroy();
     method public int getFormat();
     method public int getHeight();
     method public int getLayers();
     method public long getUsage();
     method public int getWidth();
-    method public boolean isDestroyed();
+    method public boolean isClosed();
     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;
@@ -22886,7 +22889,7 @@
     method public void releaseDrm() throws android.media.MediaPlayer.NoDrmSchemeException;
     method public void reset();
     method public void restoreKeys(byte[]) throws android.media.MediaPlayer.NoDrmSchemeException;
-    method public void seekTo(int, int) throws java.lang.IllegalStateException;
+    method public void seekTo(long, int);
     method public void seekTo(int) throws java.lang.IllegalStateException;
     method public void selectTrack(int) throws java.lang.IllegalStateException;
     method public void setAudioAttributes(android.media.AudioAttributes) throws java.lang.IllegalArgumentException;
@@ -35065,7 +35068,7 @@
     field public static final java.lang.String ACTION_MANAGE_APPLICATIONS_SETTINGS = "android.settings.MANAGE_APPLICATIONS_SETTINGS";
     field public static final java.lang.String ACTION_MANAGE_DEFAULT_APPS_SETTINGS = "android.settings.MANAGE_DEFAULT_APPS_SETTINGS";
     field public static final java.lang.String ACTION_MANAGE_OVERLAY_PERMISSION = "android.settings.action.MANAGE_OVERLAY_PERMISSION";
-    field public static final java.lang.String ACTION_MANAGE_UNKNOWN_APP_SOURCES = "android.settings.action.MANAGE_UNKNOWN_APP_SOURCES";
+    field public static final java.lang.String ACTION_MANAGE_UNKNOWN_APP_SOURCES = "android.settings.MANAGE_UNKNOWN_APP_SOURCES";
     field public static final java.lang.String ACTION_MANAGE_WRITE_SETTINGS = "android.settings.action.MANAGE_WRITE_SETTINGS";
     field public static final java.lang.String ACTION_MEMORY_CARD_SETTINGS = "android.settings.MEMORY_CARD_SETTINGS";
     field public static final java.lang.String ACTION_NETWORK_OPERATOR_SETTINGS = "android.settings.NETWORK_OPERATOR_SETTINGS";
diff --git a/api/test-removed.txt b/api/test-removed.txt
index 189536d..dc9c54e 100644
--- a/api/test-removed.txt
+++ b/api/test-removed.txt
@@ -126,6 +126,11 @@
 
 package android.hardware {
 
+  public final class HardwareBuffer implements java.lang.AutoCloseable android.os.Parcelable {
+    method public deprecated void destroy();
+    method public deprecated boolean isDestroyed();
+  }
+
   public final class SensorDirectChannel implements java.nio.channels.Channel {
     method public deprecated boolean isValid();
   }
diff --git a/core/java/android/animation/AnimatorSet.java b/core/java/android/animation/AnimatorSet.java
index fe496e3..cdeca13 100644
--- a/core/java/android/animation/AnimatorSet.java
+++ b/core/java/android/animation/AnimatorSet.java
@@ -1092,6 +1092,14 @@
                 AnimationEvent event = mEvents.get(i);
                 Node node = event.mNode;
                 if (event.mEvent == AnimationEvent.ANIMATION_END) {
+                    if (node.mAnimation.isStarted()) {
+                        // If the animation has already been started before its due time (i.e.
+                        // the child animator is being manipulated outside of the AnimatorSet), we
+                        // need to cancel the animation to reset the internal state (e.g. frame
+                        // time tracking) and remove the self pulsing callbacks
+                        node.mAnimation.cancel();
+                    }
+                    node.mEnded = false;
                     mPlayingSet.add(event.mNode);
                     node.mAnimation.startWithoutPulsing(true);
                     pulseFrame(node, 0);
@@ -1106,6 +1114,14 @@
                 Node node = event.mNode;
                 if (event.mEvent == AnimationEvent.ANIMATION_START) {
                     mPlayingSet.add(event.mNode);
+                    if (node.mAnimation.isStarted()) {
+                        // If the animation has already been started before its due time (i.e.
+                        // the child animator is being manipulated outside of the AnimatorSet), we
+                        // need to cancel the animation to reset the internal state (e.g. frame
+                        // time tracking) and remove the self pulsing callbacks
+                        node.mAnimation.cancel();
+                    }
+                    node.mEnded = false;
                     node.mAnimation.startWithoutPulsing(false);
                     pulseFrame(node, 0);
                 } else if (event.mEvent == AnimationEvent.ANIMATION_END && !node.mEnded) {
diff --git a/core/java/android/annotation/AnyThread.java b/core/java/android/annotation/AnyThread.java
index c101548c..e173bd1 100644
--- a/core/java/android/annotation/AnyThread.java
+++ b/core/java/android/annotation/AnyThread.java
@@ -15,30 +15,34 @@
  */
 package android.annotation;
 
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
 import static java.lang.annotation.ElementType.CONSTRUCTOR;
 import static java.lang.annotation.ElementType.METHOD;
 import static java.lang.annotation.ElementType.TYPE;
 import static java.lang.annotation.RetentionPolicy.SOURCE;
 
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
 /**
- * Denotes that the annotated method can be called from any thread (e.g. it is "thread safe".)
- * If the annotated element is a class, then all methods in the class can be called
- * from any thread.
+ * Denotes that the annotated method can be called from any thread (e.g. it is
+ * "thread safe".) If the annotated element is a class, then all methods in the
+ * class can be called from any thread.
  * <p>
- * The main purpose of this method is to indicate that you believe a method can be called
- * from any thread; static tools can then check that nothing you call from within this method
- * or class have more strict threading requirements.
+ * The main purpose of this method is to indicate that you believe a method can
+ * be called from any thread; static tools can then check that nothing you call
+ * from within this method or class have more strict threading requirements.
  * <p>
  * Example:
- * <pre><code>
+ *
+ * <pre>
+ * <code>
  *  &#64;AnyThread
  *  public void deliverResult(D data) { ... }
- * </code></pre>
+ * </code>
+ * </pre>
  *
- * {@hide}
+ * @memberDoc This method is safe to call from any thread.
+ * @hide
  */
 @Retention(SOURCE)
 @Target({METHOD,CONSTRUCTOR,TYPE})
diff --git a/core/java/android/annotation/CallSuper.java b/core/java/android/annotation/CallSuper.java
index b10a28a..c16b511 100644
--- a/core/java/android/annotation/CallSuper.java
+++ b/core/java/android/annotation/CallSuper.java
@@ -15,24 +15,29 @@
  */
 package android.annotation;
 
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
 import static java.lang.annotation.ElementType.METHOD;
 import static java.lang.annotation.RetentionPolicy.SOURCE;
 
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
 /**
  * Denotes that any overriding methods should invoke this method as well.
  * <p>
  * Example:
- * <pre><code>
+ *
+ * <pre>
+ * <code>
  *  &#64;CallSuper
  *  public abstract void onFocusLost();
- * </code></pre>
+ * </code>
+ * </pre>
  *
+ * @memberDoc If you override this method you <em>must</em> call through to the
+ *            superclass implementation.
  * @hide
  */
 @Retention(SOURCE)
 @Target({METHOD})
 public @interface CallSuper {
-}
\ No newline at end of file
+}
diff --git a/core/java/android/annotation/MainThread.java b/core/java/android/annotation/MainThread.java
index c6ac30c..d15cfcd 100644
--- a/core/java/android/annotation/MainThread.java
+++ b/core/java/android/annotation/MainThread.java
@@ -15,9 +15,6 @@
  */
 package android.annotation;
 
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
 import static java.lang.annotation.ElementType.CONSTRUCTOR;
 import static java.lang.annotation.ElementType.METHOD;
 import static java.lang.annotation.ElementType.TYPE;
@@ -25,6 +22,9 @@
 
 import android.os.Looper;
 
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
 /**
  * Denotes that the annotated method should only be called on the main thread.
  * If the annotated element is a class, then all methods in the class should be
diff --git a/core/java/android/annotation/SuppressAutoDoc.java b/core/java/android/annotation/SuppressAutoDoc.java
index 0f8fa6c..e34e03b 100644
--- a/core/java/android/annotation/SuppressAutoDoc.java
+++ b/core/java/android/annotation/SuppressAutoDoc.java
@@ -16,14 +16,17 @@
 
 package android.annotation;
 
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
 import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
 import static java.lang.annotation.ElementType.METHOD;
 import static java.lang.annotation.ElementType.PARAMETER;
+import static java.lang.annotation.ElementType.TYPE;
 import static java.lang.annotation.RetentionPolicy.SOURCE;
 
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
 /**
  * Denotes that any automatically generated documentation should be suppressed
  * for the annotated method, parameter, or field.
@@ -31,6 +34,6 @@
  * @hide
  */
 @Retention(SOURCE)
-@Target({METHOD, PARAMETER, FIELD})
+@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
 public @interface SuppressAutoDoc {
 }
diff --git a/core/java/android/annotation/UiThread.java b/core/java/android/annotation/UiThread.java
index 53121e7..b277896 100644
--- a/core/java/android/annotation/UiThread.java
+++ b/core/java/android/annotation/UiThread.java
@@ -15,28 +15,36 @@
  */
 package android.annotation;
 
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
 import static java.lang.annotation.ElementType.CONSTRUCTOR;
 import static java.lang.annotation.ElementType.METHOD;
 import static java.lang.annotation.ElementType.TYPE;
 import static java.lang.annotation.RetentionPolicy.SOURCE;
 
+import android.os.Looper;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
 /**
- * Denotes that the annotated method or constructor should only be called on the UI thread.
- * If the annotated element is a class, then all methods in the class should be called
- * on the UI thread.
+ * Denotes that the annotated method or constructor should only be called on the
+ * UI thread. If the annotated element is a class, then all methods in the class
+ * should be called on the UI thread.
  * <p>
  * Example:
- * <pre><code>
+ *
+ * <pre>
+ * <code>
  *  &#64;UiThread
  *  public abstract void setText(@NonNull String text) { ... }
- * </code></pre>
+ * </code>
+ * </pre>
  *
- * {@hide}
+ * @memberDoc This method must be called on the thread that originally created
+ *            this UI element. This is typically the
+ *            {@linkplain Looper#getMainLooper() main thread} of your app.
+ * @hide
  */
 @Retention(SOURCE)
 @Target({METHOD,CONSTRUCTOR,TYPE})
 public @interface UiThread {
-}
\ No newline at end of file
+}
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index 44c275f..62f2144 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -3081,6 +3081,21 @@
          */
         public int lastTrimLevel;
 
+        /** @hide */
+        @IntDef(prefix = { "IMPORTANCE_" }, value = {
+                IMPORTANCE_FOREGROUND,
+                IMPORTANCE_FOREGROUND_SERVICE,
+                IMPORTANCE_TOP_SLEEPING,
+                IMPORTANCE_VISIBLE,
+                IMPORTANCE_PERCEPTIBLE,
+                IMPORTANCE_CANT_SAVE_STATE,
+                IMPORTANCE_SERVICE,
+                IMPORTANCE_CACHED,
+                IMPORTANCE_GONE,
+        })
+        @Retention(RetentionPolicy.SOURCE)
+        public @interface Importance {}
+
         /**
          * Constant for {@link #importance}: This process is running the
          * foreground UI; that is, it is the thing currently at the top of the screen
@@ -3190,7 +3205,7 @@
          * will be passed to a client, use {@link #procStateToImportanceForClient}.
          * @hide
          */
-        public static int procStateToImportance(int procState) {
+        public static @Importance int procStateToImportance(int procState) {
             if (procState == PROCESS_STATE_NONEXISTENT) {
                 return IMPORTANCE_GONE;
             } else if (procState >= PROCESS_STATE_HOME) {
@@ -3219,7 +3234,8 @@
          * client's target SDK < {@link VERSION_CODES#O}.
          * @hide
          */
-        public static int procStateToImportanceForClient(int procState, Context clientContext) {
+        public static @Importance int procStateToImportanceForClient(int procState,
+                Context clientContext) {
             final int importance = procStateToImportance(procState);
 
             // For pre O apps, convert to the old, wrong values.
@@ -3235,7 +3251,7 @@
         }
 
         /** @hide */
-        public static int importanceToProcState(int importance) {
+        public static int importanceToProcState(@Importance int importance) {
             if (importance == IMPORTANCE_GONE) {
                 return PROCESS_STATE_NONEXISTENT;
             } else if (importance >= IMPORTANCE_CACHED) {
@@ -3258,14 +3274,11 @@
         }
 
         /**
-         * The relative importance level that the system places on this
-         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
-         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE}, or
-         * {@link #IMPORTANCE_CACHED}.  These
-         * constants are numbered so that "more important" values are always
-         * smaller than "less important" values.
+         * The relative importance level that the system places on this process.
+         * These constants are numbered so that "more important" values are
+         * always smaller than "less important" values.
          */
-        public int importance;
+        public @Importance int importance;
 
         /**
          * An additional ordering within a particular {@link #importance}
@@ -3459,7 +3472,7 @@
      */
     @SystemApi @TestApi
     @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
-    public int getPackageImportance(String packageName) {
+    public @RunningAppProcessInfo.Importance int getPackageImportance(String packageName) {
         try {
             int procState = getService().getPackageProcessState(packageName,
                     mContext.getOpPackageName());
@@ -3479,7 +3492,7 @@
      */
     @SystemApi @TestApi
     @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
-    public int getUidImportance(int uid) {
+    public @RunningAppProcessInfo.Importance int getUidImportance(int uid) {
         try {
             int procState = getService().getUidProcessState(uid,
                     mContext.getOpPackageName());
@@ -3505,7 +3518,7 @@
          * @param uid The uid whose importance has changed.
          * @param importance The new importance value as per {@link RunningAppProcessInfo}.
          */
-        void onUidImportance(int uid, int importance);
+        void onUidImportance(int uid, @RunningAppProcessInfo.Importance int importance);
     }
 
     /**
@@ -3527,7 +3540,7 @@
      */
     @SystemApi @TestApi
     public void addOnUidImportanceListener(OnUidImportanceListener listener,
-            int importanceCutpoint) {
+            @RunningAppProcessInfo.Importance int importanceCutpoint) {
         synchronized (this) {
             if (mImportanceListeners.containsKey(listener)) {
                 throw new IllegalArgumentException("Listener already registered: " + listener);
@@ -4263,8 +4276,7 @@
 
     /**
      * Enable more aggressive scheduling for latency-sensitive low-runtime VR threads that persist
-     * beyond a single process. It requires holding the
-     * {@link android.Manifest.permission#RESTRICTED_VR_ACCESS} permission. Only one thread can be a
+     * beyond a single process. Only one thread can be a
      * persistent VR thread at a time, and that thread may be subject to restrictions on the amount
      * of time it can run. Calling this method will disable aggressive scheduling for non-persistent
      * VR threads set via {@link #setVrThread}. If persistent VR mode is disabled then the
diff --git a/core/java/android/app/INotificationManager.aidl b/core/java/android/app/INotificationManager.aidl
index cd9c095..cc7e0fd 100644
--- a/core/java/android/app/INotificationManager.aidl
+++ b/core/java/android/app/INotificationManager.aidl
@@ -46,7 +46,7 @@
     void enqueueToast(String pkg, ITransientNotification callback, int duration);
     void cancelToast(String pkg, ITransientNotification callback);
     void enqueueNotificationWithTag(String pkg, String opPkg, String tag, int id,
-            in Notification notification, inout int[] idReceived, int userId);
+            in Notification notification, int userId);
     void cancelNotificationWithTag(String pkg, String tag, int id, int userId);
 
     void setShowBadge(String pkg, int uid, boolean showBadge);
diff --git a/core/java/android/app/ITaskStackListener.aidl b/core/java/android/app/ITaskStackListener.aidl
index 47817a7..f369955 100644
--- a/core/java/android/app/ITaskStackListener.aidl
+++ b/core/java/android/app/ITaskStackListener.aidl
@@ -21,6 +21,11 @@
 
 /** @hide */
 oneway interface ITaskStackListener {
+    /** Activity was resized to be displayed in split-screen. */
+    const int FORCED_RESIZEABLE_REASON_SPLIT_SCREEN = 1;
+    /** Activity was resized to be displayed on a secondary display. */
+    const int FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY = 2;
+
     /** Called whenever there are changes to the state of tasks in a stack. */
     void onTaskStackChanged();
 
@@ -49,15 +54,26 @@
 
     /**
      * Called when we launched an activity that we forced to be resizable.
+     *
+     * @param packageName Package name of the top activity in the task.
+     * @param taskId Id of the task.
+     * @param reason {@link #FORCED_RESIZEABLE_REASON_SPLIT_SCREEN} or
+      *              {@link #FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY}.
      */
-    void onActivityForcedResizable(String packageName, int taskId);
+    void onActivityForcedResizable(String packageName, int taskId, int reason);
 
     /**
-     * Callen when we launched an activity that is dismissed the docked stack.
+     * Called when we launched an activity that dismissed the docked stack.
      */
     void onActivityDismissingDockedStack();
 
     /**
+     * Called when an activity was requested to be launched on a secondary display but was not
+     * allowed there.
+     */
+    void onActivityLaunchOnSecondaryDisplayFailed();
+
+    /**
      * Called when a task is added.
      *
      * @param taskId id of the task.
diff --git a/core/java/android/app/KeyguardManager.java b/core/java/android/app/KeyguardManager.java
index c0bf0c4..b8a5f57 100644
--- a/core/java/android/app/KeyguardManager.java
+++ b/core/java/android/app/KeyguardManager.java
@@ -169,9 +169,6 @@
          * Note: This call has no effect while any {@link android.app.admin.DevicePolicyManager}
          * is enabled that requires a password.
          *
-         * <p>This method requires the caller to hold the permission
-         * {@link android.Manifest.permission#DISABLE_KEYGUARD}.
-         *
          * @see #reenableKeyguard()
          */
         @RequiresPermission(Manifest.permission.DISABLE_KEYGUARD)
@@ -191,9 +188,6 @@
          * Note: This call has no effect while any {@link android.app.admin.DevicePolicyManager}
          * is enabled that requires a password.
          *
-         * <p>This method requires the caller to hold the permission
-         * {@link android.Manifest.permission#DISABLE_KEYGUARD}.
-         *
          * @see #disableKeyguard()
          */
         @RequiresPermission(Manifest.permission.DISABLE_KEYGUARD)
@@ -431,9 +425,6 @@
      * This will, if the keyguard is secure, bring up the unlock screen of
      * the keyguard.
      *
-     * <p>This method requires the caller to hold the permission
-     * {@link android.Manifest.permission#DISABLE_KEYGUARD}.
-     *
      * @param callback Let's you know whether the operation was succesful and
      *   it is safe to launch anything that would normally be considered safe
      *   once the user has gotten past the keyguard.
diff --git a/core/java/android/app/NotificationManager.java b/core/java/android/app/NotificationManager.java
index 58ed587..7c361b9 100644
--- a/core/java/android/app/NotificationManager.java
+++ b/core/java/android/app/NotificationManager.java
@@ -298,7 +298,6 @@
      */
     public void notifyAsUser(String tag, int id, Notification notification, UserHandle user)
     {
-        int[] idOut = new int[1];
         INotificationManager service = getService();
         String pkg = mContext.getPackageName();
         // Fix the notification as best we can.
@@ -320,10 +319,7 @@
         final Notification copy = Builder.maybeCloneStrippedForDelivery(notification);
         try {
             service.enqueueNotificationWithTag(pkg, mContext.getOpPackageName(), tag, id,
-                    copy, idOut, user.getIdentifier());
-            if (localLOGV && id != idOut[0]) {
-                Log.v(TAG, "notify: id corrupted: sent " + id + ", got back " + idOut[0]);
-            }
+                    copy, user.getIdentifier());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
diff --git a/core/java/android/app/TaskStackListener.java b/core/java/android/app/TaskStackListener.java
index 57fc874..307fc91 100644
--- a/core/java/android/app/TaskStackListener.java
+++ b/core/java/android/app/TaskStackListener.java
@@ -51,7 +51,8 @@
     }
 
     @Override
-    public void onActivityForcedResizable(String packageName, int taskId) throws RemoteException {
+    public void onActivityForcedResizable(String packageName, int taskId, int reason)
+            throws RemoteException {
     }
 
     @Override
@@ -59,6 +60,10 @@
     }
 
     @Override
+    public void onActivityLaunchOnSecondaryDisplayFailed() throws RemoteException {
+    }
+
+    @Override
     public void onTaskCreated(int taskId, ComponentName componentName) throws RemoteException {
     }
 
diff --git a/core/java/android/app/assist/AssistStructure.java b/core/java/android/app/assist/AssistStructure.java
index 9e5c9e7..ca74d54 100644
--- a/core/java/android/app/assist/AssistStructure.java
+++ b/core/java/android/app/assist/AssistStructure.java
@@ -34,8 +34,18 @@
 import java.util.Arrays;
 
 /**
- * Assist data automatically created by the platform's implementation
- * of {@link android.app.Activity#onProvideAssistData}.
+ * Assist data automatically created by the platform's implementation of Assist and Autofill.
+ *
+ * <p>The structure is used for Assist purposes when created by
+ * {@link android.app.Activity#onProvideAssistData}, {@link View#onProvideStructure(ViewStructure)},
+ * or {@link View#onProvideVirtualStructure(ViewStructure)}.
+ *
+ * <p>The structure is used for Autofill purposes when created by
+ * {@link View#onProvideAutofillStructure(ViewStructure, int)},
+ * or {@link View#onProvideAutofillVirtualStructure(ViewStructure, int)}.
+ *
+ * <p>For performance reasons, some properties of the Assist data might be available just for Assist
+ * or Autofill purposes; in those case, the property availability will be document in its javadoc.
  */
 public class AssistStructure implements Parcelable {
     static final String TAG = "AssistStructure";
@@ -592,7 +602,7 @@
         // TODO(b/33197203): once we have more flags, it might be better to store the individual
         // fields (viewId and childId) of the field.
         AutofillId mAutofillId;
-        @View.AutofillType int mAutofillType;
+        @View.AutofillType int mAutofillType = View.AUTOFILL_TYPE_NONE;
         @Nullable String[] mAutofillHints;
         AutofillValue mAutofillValue;
         CharSequence[] mAutofillOptions;
@@ -938,18 +948,22 @@
         /**
          * Gets the id that can be used to autofill the view contents.
          *
-         * <p>It's only set when the {@link AssistStructure} is used for autofilling purposes, not
-         * for assist.
+         * <p>It's relevant set when the {@link AssistStructure} is used for Autofill purposes.
+         *
+         * @return id that can be used to autofill the view contents, or {@code null} if the
+         * structure was created for Assist purposes.
          */
-        public AutofillId getAutofillId() {
+        @Nullable public AutofillId getAutofillId() {
             return mAutofillId;
         }
 
         /**
          * Gets the the type of value that can be used to autofill the view contents.
          *
-         * <p>It's only set when the {@link AssistStructure} is used for autofilling purposes, not
-         * for assist.
+         * <p>It's only relevant when the {@link AssistStructure} is used for Autofill purposes.
+         *
+         * @return autofill type as defined by {@link View#getAutofillType()},
+         * or {@link View#AUTOFILL_TYPE_NONE} if the structure was created for Assist purposes.
          */
         public @View.AutofillType int getAutofillType() {
             return mAutofillType;
@@ -959,32 +973,26 @@
          * Describes the content of a view so that a autofill service can fill in the appropriate
          * data.
          *
-         * <p>It's only set when the {@link AssistStructure} is used for autofilling purposes, not
-         * for assist.</p>
+         * <p>It's only relevant when the {@link AssistStructure} is used for Autofill purposes,
+         * not for Assist - see {@link View#getAutofillHints()} for more info.
          *
-         * @return The hints for this view
+         * @return The autofill hints for this view, or {@code null} if the structure was created
+         * for Assist purposes.
          */
         @Nullable public String[] getAutofillHints() {
             return mAutofillHints;
         }
 
         /**
-         * @hide
-         * @deprecated use getAutofillHints() instead.
-         */
-        // TODO(b/33197203): remove once clients don't use it anymore...
-        @Deprecated
-        @Nullable public String[] getAutoFillHints() {
-            return mAutofillHints;
-        }
-
-        /**
          * Gets the the value of this view.
          *
-         * <p>It's only set when the {@link AssistStructure} is used for autofilling purposes, not
-         * for assist.
+         * <p>It's only relevant when the {@link AssistStructure} is used for Autofill purposes,
+         * not for Assist purposes.
+         *
+         * @return the autofill value of this view, or {@code null} if the structure was created
+         * for Assist purposes.
          */
-        public AutofillValue getAutofillValue() {
+        @Nullable public AutofillValue getAutofillValue() {
             return mAutofillValue;
         }
 
@@ -994,15 +1002,18 @@
         }
 
         /**
-         * Gets the options that can be used to autofill this structure.
+         * Gets the options that can be used to autofill this view.
          *
          * <p>Typically used by nodes whose {@link View#getAutofillType()} is a list to indicate
          * the meaning of each possible value in the list.
          *
-         * <p>It's only set when the {@link AssistStructure} is used for autofilling purposes, not
-         * for assist.
+         * <p>It's relevant when the {@link AssistStructure} is used for Autofill purposes, not
+         * for Assist purposes.
+         *
+         * @return the options that can be used to autofill this view, or {@code null} if the
+         * structure was created for Assist purposes.
          */
-        public CharSequence[] getAutofillOptions() {
+        @Nullable public CharSequence[] getAutofillOptions() {
             return mAutofillOptions;
         }
 
@@ -1226,33 +1237,36 @@
         }
 
         /**
-         * Returns the URL represented by this node.
+         * Returns the URL represented by this view.
          *
-         * <p>Typically used when the view associated with the node is a container for an HTML
+         * <p>Typically used when the view associated with the view is a container for an HTML
          * document.
          *
          * <strong>WARNING:</strong> a {@link android.service.autofill.AutofillService} should only
-         * use this URL for autofill purposes when it trusts the app generating it (i.e., the app
+         * use this URL for Autofill purposes when it trusts the app generating it (i.e., the app
          * defined by {@link AssistStructure#getActivityComponent()}).
          */
-        public String getUrl() {
+        @Nullable public String getUrl() {
             return mUrl;
         }
 
         /**
-         * Returns the HTML properties associated with this node.
+         * Returns the HTML properties associated with this view.
          *
-         * <p>It's only set when the {@link AssistStructure} is used for autofilling purposes, not
-         * for assist.
+         * <p>It's only relevant when the {@link AssistStructure} is used for Autofill purposes,
+         * not for Assist purposes.
+         *
+         * @return the HTML properties associated with this view, or {@code null} if the
+         * structure was created for Assist purposes.
          */
-        public HtmlInfo getHtmlInfo() {
+        @Nullable public HtmlInfo getHtmlInfo() {
             return mHtmlInfo;
         }
 
         /**
-         * Returns the the list of locales associated with this node.
+         * Returns the the list of locales associated with this view.
          */
-        public LocaleList getLocaleList() {
+        @Nullable public LocaleList getLocaleList() {
             return mLocaleList;
         }
 
@@ -1965,7 +1979,7 @@
                     + ", type=" + node.getAutofillType()
                     + ", options=" + Arrays.toString(node.getAutofillOptions())
                     + ", inputType=" + node.getInputType()
-                    + ", hints=" + Arrays.toString(node.getAutoFillHints())
+                    + ", hints=" + Arrays.toString(node.getAutofillHints())
                     + ", value=" + node.getAutofillValue()
                     + ", sanitized=" + node.isSanitized());
         }
diff --git a/core/java/android/app/job/JobInfo.java b/core/java/android/app/job/JobInfo.java
index 23baa17..3538256 100644
--- a/core/java/android/app/job/JobInfo.java
+++ b/core/java/android/app/job/JobInfo.java
@@ -244,7 +244,7 @@
     /**
      * Bundle of extras which are returned to your application at execution time.
      */
-    public PersistableBundle getExtras() {
+    public @NonNull PersistableBundle getExtras() {
         return extras;
     }
 
@@ -252,7 +252,7 @@
      * Bundle of transient extras which are returned to your application at execution time,
      * but not persisted by the system.
      */
-    public Bundle getTransientExtras() {
+    public @NonNull Bundle getTransientExtras() {
         return transientExtras;
     }
 
@@ -260,7 +260,7 @@
      * ClipData of information that is returned to your application at execution time,
      * but not persisted by the system.
      */
-    public ClipData getClipData() {
+    public @Nullable ClipData getClipData() {
         return clipData;
     }
 
@@ -274,7 +274,7 @@
     /**
      * Name of the service endpoint that will be called back into by the JobScheduler.
      */
-    public ComponentName getService() {
+    public @NonNull ComponentName getService() {
         return service;
     }
 
@@ -327,8 +327,7 @@
      * Which content: URIs must change for the job to be scheduled.  Returns null
      * if there are none required.
      */
-    @Nullable
-    public TriggerContentUri[] getTriggerContentUris() {
+    public @Nullable TriggerContentUri[] getTriggerContentUris() {
         return triggerContentUris;
     }
 
@@ -811,7 +810,7 @@
          * @param jobService The endpoint that you implement that will receive the callback from the
          * JobScheduler.
          */
-        public Builder(int jobId, ComponentName jobService) {
+        public Builder(int jobId, @NonNull ComponentName jobService) {
             mJobService = jobService;
             mJobId = jobId;
         }
@@ -832,17 +831,21 @@
          * Set optional extras. This is persisted, so we only allow primitive types.
          * @param extras Bundle containing extras you want the scheduler to hold on to for you.
          */
-        public Builder setExtras(PersistableBundle extras) {
+        public Builder setExtras(@NonNull PersistableBundle extras) {
             mExtras = extras;
             return this;
         }
 
         /**
-         * Set optional transient extras. This is incompatible with jobs that are also
-         * persisted with {@link #setPersisted(boolean)}; mixing the two is not allowed.
+         * Set optional transient extras.
+         *
+         * <p>Because setting this property is not compatible with persisted
+         * jobs, doing so will throw an {@link java.lang.IllegalArgumentException} when
+         * {@link android.app.job.JobInfo.Builder#build()} is called.</p>
+         *
          * @param extras Bundle containing extras you want the scheduler to hold on to for you.
          */
-        public Builder setTransientExtras(Bundle extras) {
+        public Builder setTransientExtras(@NonNull Bundle extras) {
             mTransientExtras = extras;
             return this;
         }
@@ -869,7 +872,7 @@
          * {@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION}, and
          * {@link android.content.Intent#FLAG_GRANT_PREFIX_URI_PERMISSION}.
          */
-        public Builder setClipData(ClipData clip, int grantFlags) {
+        public Builder setClipData(@Nullable ClipData clip, int grantFlags) {
             mClipData = clip;
             mClipGrantFlags = grantFlags;
             return this;
diff --git a/core/java/android/app/job/JobParameters.java b/core/java/android/app/job/JobParameters.java
index 673d1b8..98bdde8 100644
--- a/core/java/android/app/job/JobParameters.java
+++ b/core/java/android/app/job/JobParameters.java
@@ -16,6 +16,8 @@
 
 package android.app.job;
 
+import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.app.job.IJobCallback;
 import android.content.ClipData;
 import android.net.Uri;
@@ -91,7 +93,7 @@
      * {@link android.app.job.JobInfo.Builder#setExtras(android.os.PersistableBundle)}. This will
      * never be null. If you did not set any extras this will be an empty bundle.
      */
-    public PersistableBundle getExtras() {
+    public @NonNull PersistableBundle getExtras() {
         return extras;
     }
 
@@ -100,7 +102,7 @@
      * {@link android.app.job.JobInfo.Builder#setTransientExtras(android.os.Bundle)}. This will
      * never be null. If you did not set any extras this will be an empty bundle.
      */
-    public Bundle getTransientExtras() {
+    public @NonNull Bundle getTransientExtras() {
         return transientExtras;
     }
 
@@ -109,7 +111,7 @@
      * {@link android.app.job.JobInfo.Builder#setClipData(ClipData, int)}. Will be null
      * if it was not set.
      */
-    public ClipData getClipData() {
+    public @Nullable ClipData getClipData() {
         return clipData;
     }
 
@@ -140,7 +142,7 @@
      * always use {@link #getTriggeredContentAuthorities()} to determine whether the job was
      * triggered due to any content changes and the authorities they are associated with.
      */
-    public Uri[] getTriggeredContentUris() {
+    public @Nullable Uri[] getTriggeredContentUris() {
         return mTriggeredContentUris;
     }
 
@@ -152,7 +154,7 @@
      * to retrieve the details of which URIs changed (as long as that has not exceeded the maximum
      * number it can reported).
      */
-    public String[] getTriggeredContentAuthorities() {
+    public @Nullable String[] getTriggeredContentAuthorities() {
         return mTriggeredContentAuthorities;
     }
 
@@ -178,12 +180,18 @@
      * doing so any pending as well as remaining uncompleted work will be re-queued
      * for the next time the job runs.</p>
      *
+     * <p>This example shows how to construct a JobService that will serially dequeue and
+     * process work that is available for it:</p>
+     *
+     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/JobWorkService.java
+     *      service}
+     *
      * @return Returns a new {@link JobWorkItem} if there is one pending, otherwise null.
      * If null is returned, the system will also stop the job if all work has also been completed.
      * (This means that for correct operation, you must always call dequeueWork() after you have
      * completed other work, to check either for more work or allow the system to stop the job.)
      */
-    public JobWorkItem dequeueWork() {
+    public @Nullable JobWorkItem dequeueWork() {
         try {
             return getCallback().dequeueWork(getJobId());
         } catch (RemoteException e) {
@@ -207,7 +215,7 @@
      * @param work The work you have completed processing, as previously returned by
      * {@link #dequeueWork()}
      */
-    public void completeWork(JobWorkItem work) {
+    public void completeWork(@NonNull JobWorkItem work) {
         try {
             if (!getCallback().completeWork(getJobId(), work.getWorkId())) {
                 throw new IllegalArgumentException("Given work is not active: " + work);
diff --git a/core/java/android/app/job/JobScheduler.java b/core/java/android/app/job/JobScheduler.java
index e0afe03..23f9eea 100644
--- a/core/java/android/app/job/JobScheduler.java
+++ b/core/java/android/app/job/JobScheduler.java
@@ -72,24 +72,25 @@
      * you can schedule.
      * @return An int representing ({@link #RESULT_SUCCESS} or {@link #RESULT_FAILURE}).
      */
-    public abstract int schedule(JobInfo job);
+    public abstract int schedule(@NonNull JobInfo job);
 
     /**
-     * Similar to {@link #schedule}, but allows you to enqueue work for an existing job.  If a job
-     * with the same ID is already scheduled, it will be replaced with the new {@link JobInfo}, but
-     * any previously enqueued work will remain and be dispatched the next time it runs.  If a job
-     * with the same ID is already running, the new work will be enqueued for it.
+     * Similar to {@link #schedule}, but allows you to enqueue work for a new <em>or existing</em>
+     * job.  If a job with the same ID is already scheduled, it will be replaced with the
+     * new {@link JobInfo}, but any previously enqueued work will remain and be dispatched the
+     * next time it runs.  If a job with the same ID is already running, the new work will be
+     * enqueued for it.
      *
      * <p>The work you enqueue is later retrieved through
-     * {@link JobParameters#dequeueWork() JobParameters.dequeueWork()}.  Be sure to see there
+     * {@link JobParameters#dequeueWork() JobParameters.dequeueWork}.  Be sure to see there
      * about how to process work; the act of enqueueing work changes how you should handle the
      * overall lifecycle of an executing job.</p>
      *
      * <p>It is strongly encouraged that you use the same {@link JobInfo} for all work you
-     * enqueue.  This will allow the system to optimal schedule work along with any pending
+     * enqueue.  This will allow the system to optimally schedule work along with any pending
      * and/or currently running work.  If the JobInfo changes from the last time the job was
      * enqueued, the system will need to update the associated JobInfo, which can cause a disruption
-     * in exection.  In particular, this can result in any currently running job that is processing
+     * in execution.  In particular, this can result in any currently running job that is processing
      * previous work to be stopped and restarted with the new JobInfo.</p>
      *
      * <p>It is recommended that you avoid using
@@ -100,7 +101,7 @@
      * (That said, you should be relatively safe with a simple set of consistent data in these
      * fields.)  You should never use {@link JobInfo.Builder#setClipData(ClipData, int)} with
      * work you are enqueue, since currently this will always be treated as a different JobInfo,
-     * even if the ClipData contents is exactly the same.</p>
+     * even if the ClipData contents are exactly the same.</p>
      *
      * @param job The job you wish to enqueue work for. See
      * {@link android.app.job.JobInfo.Builder JobInfo.Builder} for more detail on the sorts of jobs
@@ -108,7 +109,7 @@
      * @param work New work to enqueue.  This will be available later when the job starts running.
      * @return An int representing ({@link #RESULT_SUCCESS} or {@link #RESULT_FAILURE}).
      */
-    public abstract int enqueue(JobInfo job, JobWorkItem work);
+    public abstract int enqueue(@NonNull JobInfo job, @NonNull JobWorkItem work);
 
     /**
      *
@@ -121,7 +122,8 @@
      * @hide
      */
     @SystemApi
-    public abstract int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag);
+    public abstract int scheduleAsPackage(@NonNull JobInfo job, @NonNull String packageName,
+            int userId, String tag);
 
     /**
      * Cancel a job that is pending in the JobScheduler.
diff --git a/core/java/android/app/job/JobServiceEngine.java b/core/java/android/app/job/JobServiceEngine.java
index a628619..b7d759b 100644
--- a/core/java/android/app/job/JobServiceEngine.java
+++ b/core/java/android/app/job/JobServiceEngine.java
@@ -32,7 +32,11 @@
 
 /**
  * Helper for implementing a {@link android.app.Service} that interacts with
- * {@link JobScheduler}.
+ * {@link JobScheduler}.  This is not intended for use by regular applications, but
+ * allows frameworks built on top of the platform to create their own
+ * {@link android.app.Service} that interact with {@link JobScheduler} as well as
+ * add in additional functionality.  If you just want to execute jobs normally, you
+ * should instead be looking at {@link JobService}.
  */
 public abstract class JobServiceEngine {
     private static final String TAG = "JobServiceEngine";
@@ -215,7 +219,7 @@
      * {@link JobService#jobFinished(JobParameters, boolean)}  JobService.jobFinished} for more
      * information.
      */
-    public final void jobFinished(JobParameters params, boolean needsReschedule) {
+    public void jobFinished(JobParameters params, boolean needsReschedule) {
         Message m = Message.obtain(mHandler, MSG_JOB_FINISHED, params);
         m.arg2 = needsReschedule ? 1 : 0;
         m.sendToTarget();
diff --git a/core/java/android/app/job/JobWorkItem.java b/core/java/android/app/job/JobWorkItem.java
index 05687ee..0eb0450 100644
--- a/core/java/android/app/job/JobWorkItem.java
+++ b/core/java/android/app/job/JobWorkItem.java
@@ -22,15 +22,19 @@
 
 /**
  * A unit of work that can be enqueued for a job using
- * {@link JobScheduler#enqueue JobScheduler.enqueue}.
+ * {@link JobScheduler#enqueue JobScheduler.enqueue}.  See
+ * {@link JobParameters#dequeueWork() JobParameters.dequeueWork} for more details.
  */
 final public class JobWorkItem implements Parcelable {
     final Intent mIntent;
+    int mDeliveryCount;
     int mWorkId;
     Object mGrants;
 
     /**
-     * Create a new piece of work.
+     * Create a new piece of work, which can be submitted to
+     * {@link JobScheduler#enqueue JobScheduler.enqueue}.
+     *
      * @param intent The general Intent describing this work.
      */
     public JobWorkItem(Intent intent) {
@@ -45,6 +49,23 @@
     }
 
     /**
+     * Return the count of the number of times this work item has been delivered
+     * to the job.  The value will be > 1 if it has been redelivered because the job
+     * was stopped or crashed while it had previously been delivered but before the
+     * job had called {@link JobParameters#completeWork JobParameters.completeWork} for it.
+     */
+    public int getDeliveryCount() {
+        return mDeliveryCount;
+    }
+
+    /**
+     * @hide
+     */
+    public void bumpDeliveryCount() {
+        mDeliveryCount++;
+    }
+
+    /**
      * @hide
      */
     public void setWorkId(int id) {
@@ -73,7 +94,17 @@
     }
 
     public String toString() {
-        return "JobWorkItem{id=" + mWorkId + " intent=" + mIntent + "}";
+        StringBuilder sb = new StringBuilder(64);
+        sb.append("JobWorkItem{id=");
+        sb.append(mWorkId);
+        sb.append(" intent=");
+        sb.append(mIntent);
+        if (mDeliveryCount != 0) {
+            sb.append(" dcount=");
+            sb.append(mDeliveryCount);
+        }
+        sb.append("}");
+        return sb.toString();
     }
 
     public int describeContents() {
@@ -87,6 +118,7 @@
         } else {
             out.writeInt(0);
         }
+        out.writeInt(mDeliveryCount);
         out.writeInt(mWorkId);
     }
 
@@ -101,12 +133,13 @@
         }
     };
 
-    public JobWorkItem(Parcel in) {
+    JobWorkItem(Parcel in) {
         if (in.readInt() != 0) {
             mIntent = Intent.CREATOR.createFromParcel(in);
         } else {
             mIntent = null;
         }
+        mDeliveryCount = in.readInt();
         mWorkId = in.readInt();
     }
 }
diff --git a/core/java/android/app/trust/TrustManager.java b/core/java/android/app/trust/TrustManager.java
index a64a023..06b0aac 100644
--- a/core/java/android/app/trust/TrustManager.java
+++ b/core/java/android/app/trust/TrustManager.java
@@ -51,8 +51,6 @@
      * Changes the lock status for the given user. This is only applicable to Managed Profiles,
      * other users should be handled by Keyguard.
      *
-     * Requires the {@link android.Manifest.permission#ACCESS_KEYGUARD_SECURE_STORAGE} permission.
-     *
      * @param userId The id for the user to be locked/unlocked.
      * @param locked The value for that user's locked state.
      */
diff --git a/core/java/android/app/usage/ExternalStorageStats.java b/core/java/android/app/usage/ExternalStorageStats.java
index 1166df0..10c9b5f 100644
--- a/core/java/android/app/usage/ExternalStorageStats.java
+++ b/core/java/android/app/usage/ExternalStorageStats.java
@@ -31,6 +31,7 @@
     /** {@hide} */ public long audioBytes;
     /** {@hide} */ public long videoBytes;
     /** {@hide} */ public long imageBytes;
+    /** {@hide} */ public long appBytes;
 
     /**
      * Return the total bytes used by all files in the shared/external storage
@@ -64,6 +65,17 @@
         return imageBytes;
     }
 
+    /**
+     * Return the total bytes used by app files in the shared/external storage
+     * hosted on this volume.
+     * <p>
+     * This data is already accounted against individual apps as returned
+     * through {@link StorageStats}.
+     */
+    public long getAppBytes() {
+        return appBytes;
+    }
+
     /** {@hide} */
     public ExternalStorageStats() {
     }
@@ -74,6 +86,7 @@
         this.audioBytes = in.readLong();
         this.videoBytes = in.readLong();
         this.imageBytes = in.readLong();
+        this.appBytes = in.readLong();
     }
 
     @Override
@@ -87,6 +100,7 @@
         dest.writeLong(audioBytes);
         dest.writeLong(videoBytes);
         dest.writeLong(imageBytes);
+        dest.writeLong(appBytes);
     }
 
     public static final Creator<ExternalStorageStats> CREATOR = new Creator<ExternalStorageStats>() {
diff --git a/core/java/android/app/usage/StorageStats.java b/core/java/android/app/usage/StorageStats.java
index b3104f6..26c702c0 100644
--- a/core/java/android/app/usage/StorageStats.java
+++ b/core/java/android/app/usage/StorageStats.java
@@ -22,12 +22,8 @@
 import android.os.UserHandle;
 
 /**
- * Storage statistics for a UID or {@link UserHandle} on a single storage
- * volume.
- * <p class="note">
- * Note: multiple packages using the same {@code sharedUserId} in their manifest
- * will be merged into a single UID.
- * </p>
+ * Storage statistics for a UID, package, or {@link UserHandle} on a single
+ * storage volume.
  *
  * @see StorageStatsManager
  */
@@ -40,6 +36,9 @@
      * Return the size of all code. This includes {@code APK} files and
      * optimized compiler output.
      * <p>
+     * If the primary external/shared storage is hosted on this storage device,
+     * then this includes files stored under {@link Context#getObbDir()}.
+     * <p>
      * Code is shared between all users on a multiuser device.
      */
     public long getCodeBytes() {
@@ -51,6 +50,12 @@
      * {@link Context#getDataDir()}, {@link Context#getCacheDir()},
      * {@link Context#getCodeCacheDir()}.
      * <p>
+     * If the primary external/shared storage is hosted on this storage device,
+     * then this includes files stored under
+     * {@link Context#getExternalFilesDir(String)},
+     * {@link Context#getExternalCacheDir()}, and
+     * {@link Context#getExternalMediaDirs()}.
+     * <p>
      * Data is isolated for each user on a multiuser device.
      */
     public long getDataBytes() {
@@ -61,6 +66,10 @@
      * Return the size of all cached data. This includes files stored under
      * {@link Context#getCacheDir()} and {@link Context#getCodeCacheDir()}.
      * <p>
+     * If the primary external/shared storage is hosted on this storage device,
+     * then this includes files stored under
+     * {@link Context#getExternalCacheDir()}.
+     * <p>
      * Cached data is isolated for each user on a multiuser device.
      */
     public long getCacheBytes() {
diff --git a/core/java/android/app/usage/StorageStatsManager.java b/core/java/android/app/usage/StorageStatsManager.java
index 4b6479a..5497d57 100644
--- a/core/java/android/app/usage/StorageStatsManager.java
+++ b/core/java/android/app/usage/StorageStatsManager.java
@@ -73,7 +73,8 @@
     }
 
     /**
-     * Return the total size of the media hosting this storage volume.
+     * Return the total size of the underlying media that is hosting this
+     * storage volume.
      * <p>
      * To reduce end user confusion, this value matches the total storage size
      * advertised in a retail environment, which is typically larger than the
diff --git a/core/java/android/bluetooth/BluetoothA2dp.java b/core/java/android/bluetooth/BluetoothA2dp.java
index 1ca2be5..d1ad8de 100644
--- a/core/java/android/bluetooth/BluetoothA2dp.java
+++ b/core/java/android/bluetooth/BluetoothA2dp.java
@@ -422,8 +422,6 @@
      * {@link #PRIORITY_AUTO_CONNECT}, {@link #PRIORITY_OFF},
      * {@link #PRIORITY_ON}, {@link #PRIORITY_UNDEFINED}
      *
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
-     *
      * @param device Bluetooth device
      * @return priority of the device
      * @hide
diff --git a/core/java/android/bluetooth/BluetoothAdapter.java b/core/java/android/bluetooth/BluetoothAdapter.java
index 845a47d..d60d4db 100644
--- a/core/java/android/bluetooth/BluetoothAdapter.java
+++ b/core/java/android/bluetooth/BluetoothAdapter.java
@@ -466,6 +466,30 @@
         "android.bluetooth.adapter.action.BLE_STATE_CHANGED";
 
     /**
+     * Intent used to broadcast the change in the Bluetooth address
+     * of the local Bluetooth adapter.
+     * <p>Always contains the extra field {@link
+     * #EXTRA_BLUETOOTH_ADDRESS} containing the Bluetooth address.
+     *
+     * Note: only system level processes are allowed to send this
+     * defined broadcast.
+     *
+     * @hide
+     */
+    public static final String ACTION_BLUETOOTH_ADDRESS_CHANGED =
+        "android.bluetooth.adapter.action.BLUETOOTH_ADDRESS_CHANGED";
+
+    /**
+     * Used as a String extra field in {@link
+     * #ACTION_BLUETOOTH_ADDRESS_CHANGED} intent to store the local
+     * Bluetooth address.
+     *
+     * @hide
+     */
+    public static final String EXTRA_BLUETOOTH_ADDRESS =
+          "android.bluetooth.adapter.extra.BLUETOOTH_ADDRESS";
+
+    /**
      * Broadcast Action: The notifys Bluetooth ACL connected event. This will be
      * by BLE Always on enabled application to know the ACL_CONNECTED event
      * when Bluetooth state in STATE_BLE_ON. This denotes GATT connection
@@ -673,7 +697,6 @@
      * Return true if Bluetooth is currently enabled and ready for use.
      * <p>Equivalent to:
      * <code>getBluetoothState() == STATE_ON</code>
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
      *
      * @return true if the local adapter is turned on
      */
@@ -811,7 +834,6 @@
      * {@link #STATE_TURNING_ON},
      * {@link #STATE_ON},
      * {@link #STATE_TURNING_OFF}.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
      *
      * @return current state of Bluetooth adapter
      */
@@ -854,7 +876,6 @@
      * {@link #STATE_ON},
      * {@link #STATE_TURNING_OFF},
      * {@link #STATE_BLE_TURNING_OFF}.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
      *
      * @return current state of Bluetooth adapter
      * @hide
@@ -910,8 +931,6 @@
      * #STATE_ON}. If this call returns false then there was an
      * immediate problem that will prevent the adapter from being turned on -
      * such as Airplane mode, or the adapter is already turned on.
-     * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
-     * permission
      *
      * @return true to indicate adapter startup has begun, or false on
      *         immediate error
@@ -946,8 +965,6 @@
      * #STATE_ON}. If this call returns false then there was an
      * immediate problem that will prevent the adapter from being turned off -
      * such as the adapter already being turned off.
-     * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
-     * permission
      *
      * @return true to indicate adapter shutdown has begun, or false on
      *         immediate error
@@ -981,7 +998,6 @@
     /**
      * Returns the hardware address of the local Bluetooth adapter.
      * <p>For example, "00:11:22:AA:BB:CC".
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
      *
      * @return Bluetooth hardware address as string
      */
@@ -1085,7 +1101,6 @@
      * will return false. After turning on Bluetooth,
      * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
      * to get the updated value.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
      *
      * @param name a valid Bluetooth name
      * @return     true if the name was set, false otherwise
@@ -1116,7 +1131,6 @@
      * will return {@link #SCAN_MODE_NONE}. After turning on Bluetooth,
      * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
      * to get the updated value.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
      *
      * @return scan mode
      */
@@ -1255,7 +1269,6 @@
      * will return false. After turning on Bluetooth,
      * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
      * to get the updated value.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
      *
      * @return true on success, false on error
      */
@@ -1275,7 +1288,6 @@
 
     /**
      * Cancel the current device discovery process.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
      * <p>Because discovery is a heavyweight procedure for the Bluetooth
      * adapter, this method should always be called before attempting to connect
      * to a remote device with {@link
@@ -1319,7 +1331,6 @@
      * will return false. After turning on Bluetooth,
      * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
      * to get the updated value.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
      *
      * @return true if discovering
      */
@@ -1484,8 +1495,8 @@
     }
 
     /**
-     * Return the maximum LE advertising data length,
-     * if LE Extended Advertising feature is supported.
+     * Return the maximum LE advertising data length in bytes,
+     * if LE Extended Advertising feature is supported, 0 otherwise.
      *
      * @return the maximum LE advertising data length.
      */
@@ -1586,7 +1597,6 @@
      * will return an empty set. After turning on Bluetooth,
      * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
      * to get the updated value.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
      *
      * @return unmodifiable set of {@link BluetoothDevice}, or null on error
      */
@@ -1671,8 +1681,6 @@
      * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET},
      * {@link BluetoothProfile#A2DP}.
      *
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
-     *
      * <p> Return value can be one of
      * {@link BluetoothProfile#STATE_DISCONNECTED},
      * {@link BluetoothProfile#STATE_CONNECTING},
@@ -1762,7 +1770,6 @@
      * closed, or if this application closes unexpectedly.
      * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
      * connect to this socket from another device using the same {@link UUID}.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
      * @param name service name for SDP record
      * @param uuid uuid for SDP record
      * @return a listening RFCOMM BluetoothServerSocket
@@ -1794,7 +1801,6 @@
      * closed, or if this application closes unexpectedly.
      * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
      * connect to this socket from another device using the same {@link UUID}.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
      * @param name service name for SDP record
      * @param uuid uuid for SDP record
      * @return a listening RFCOMM BluetoothServerSocket
@@ -2386,8 +2392,6 @@
      * <p>Results of the scan are reported using the
      * {@link LeScanCallback#onLeScan} callback.
      *
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
-     *
      * @param callback the callback LE scan results are delivered
      * @return true, if the scan was started successfully
      * @deprecated use {@link BluetoothLeScanner#startScan(List, ScanSettings, ScanCallback)}
@@ -2406,8 +2410,6 @@
      * <p>Devices which advertise all specified services are reported using the
      * {@link LeScanCallback#onLeScan} callback.
      *
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
-     *
      * @param serviceUuids Array of services to look for
      * @param callback the callback LE scan results are delivered
      * @return true, if the scan was started successfully
@@ -2495,8 +2497,6 @@
     /**
      * Stops an ongoing Bluetooth LE device scan.
      *
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
-     *
      * @param callback used to identify which scan to stop
      *        must be the same handle used to start the scan
      * @deprecated Use {@link BluetoothLeScanner#stopScan(ScanCallback)} instead.
diff --git a/core/java/android/bluetooth/BluetoothDevice.java b/core/java/android/bluetooth/BluetoothDevice.java
index e6cebc0..639e056 100644
--- a/core/java/android/bluetooth/BluetoothDevice.java
+++ b/core/java/android/bluetooth/BluetoothDevice.java
@@ -762,7 +762,6 @@
      * <p>The local adapter will automatically retrieve remote names when
      * performing a device scan, and will cache them. This method just returns
      * the name for this device from the cache.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
      *
      * @return the Bluetooth name, or null if there was a problem.
      */
@@ -781,8 +780,6 @@
     /**
      * Get the Bluetooth device type of the remote device.
      *
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
-     *
      * @return the device type {@link #DEVICE_TYPE_CLASSIC}, {@link #DEVICE_TYPE_LE}
      *                         {@link #DEVICE_TYPE_DUAL}.
      *         {@link #DEVICE_TYPE_UNKNOWN} if it's not available
@@ -862,7 +859,6 @@
      * the bonding process completes, and its result.
      * <p>Android system services will handle the necessary user interactions
      * to confirm and complete the bonding process.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
      *
      * @return false on immediate error, true if bonding will begin
      */
@@ -1022,7 +1018,6 @@
      * {@link #BOND_NONE},
      * {@link #BOND_BONDING},
      * {@link #BOND_BONDED}.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
      *
      * @return the bond state
      */
@@ -1089,7 +1084,6 @@
 
     /**
      * Get the Bluetooth class of the remote device.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
      *
      * @return Bluetooth class object, or null on error
      */
@@ -1114,7 +1108,6 @@
      * from the remote device. Instead, the local cached copy of the service
      * UUIDs are returned.
      * <p>Use {@link #fetchUuidsWithSdp} if fresh UUIDs are desired.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
      *
      * @return the supported features (UUIDs) of the remote device,
      *         or null on error
@@ -1140,7 +1133,6 @@
       * {@link #ACTION_UUID} intent is sent with the UUIDs that is currently
       * present in the cache. Clients should use the {@link #getUuids} to get UUIDs
       * if service discovery is not to be performed.
-      * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
       *
       * @return False if the sanity check fails, True if the process
       *               of initiating an ACL connection to the remote device
@@ -1221,7 +1213,6 @@
 
     /**
      * Confirm passkey for {@link #PAIRING_VARIANT_PASSKEY_CONFIRMATION} pairing.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}.
      *
      * @return true confirmation has been sent out
      *         false for error
@@ -1502,7 +1493,6 @@
      * using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB.
      * However if you are connecting to an Android peer then please generate
      * your own unique UUID.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
      *
      * @param uuid service record uuid to lookup RFCOMM channel
      * @return a RFCOMM BluetoothServerSocket ready for an outgoing connection
@@ -1541,7 +1531,6 @@
      * using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB.
      * However if you are connecting to an Android peer then please generate
      * your own unique UUID.
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
      *
      * @param uuid service record uuid to lookup RFCOMM channel
      * @return a RFCOMM BluetoothServerSocket ready for an outgoing connection
diff --git a/core/java/android/bluetooth/BluetoothManager.java b/core/java/android/bluetooth/BluetoothManager.java
index 29283e7..c7191ba 100644
--- a/core/java/android/bluetooth/BluetoothManager.java
+++ b/core/java/android/bluetooth/BluetoothManager.java
@@ -85,8 +85,6 @@
      * This can be used by applications like status bar which would just like
      * to know the state of Bluetooth.
      *
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
-     *
      * @param device Remote bluetooth device.
      * @param profile GATT or GATT_SERVER
      * @return State of the profile connection. One of
@@ -118,8 +116,6 @@
      * This can be used by applications like status bar which would just like
      * to know the state of Bluetooth.
      *
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
-     *
      * @param profile GATT or GATT_SERVER
      * @return List of devices. The list will be empty on error.
      */
@@ -159,8 +155,6 @@
      * This can be used by applications like status bar which would just like
      * to know the state of the local adapter.
      *
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
-     *
      * @param profile GATT or GATT_SERVER
      * @param states Array of states. States can be one of
      *        {@link BluetoothProfile#STATE_CONNECTED}, {@link BluetoothProfile#STATE_CONNECTING},
diff --git a/core/java/android/bluetooth/BluetoothProfile.java b/core/java/android/bluetooth/BluetoothProfile.java
index 2f64c71..c5b58e9 100644
--- a/core/java/android/bluetooth/BluetoothProfile.java
+++ b/core/java/android/bluetooth/BluetoothProfile.java
@@ -187,8 +187,6 @@
      *
      * <p> Return the set of devices which are in state {@link #STATE_CONNECTED}
      *
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
-     *
      * @return List of devices. The list will be empty on error.
      */
     @RequiresPermission(Manifest.permission.BLUETOOTH)
@@ -201,8 +199,6 @@
      * <p> If none of the devices match any of the given states,
      * an empty list will be returned.
      *
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
-     *
      * @param states Array of states. States can be one of
      *              {@link #STATE_CONNECTED}, {@link #STATE_CONNECTING},
      *              {@link #STATE_DISCONNECTED}, {@link #STATE_DISCONNECTING},
@@ -214,8 +210,6 @@
     /**
      * Get the current connection state of the profile
      *
-     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
-     *
      * @param device Remote bluetooth device.
      * @return State of the profile connection. One of
      *               {@link #STATE_CONNECTED}, {@link #STATE_CONNECTING},
diff --git a/core/java/android/bluetooth/le/BluetoothLeScanner.java b/core/java/android/bluetooth/le/BluetoothLeScanner.java
index b65a7ad..8d2c3ec 100644
--- a/core/java/android/bluetooth/le/BluetoothLeScanner.java
+++ b/core/java/android/bluetooth/le/BluetoothLeScanner.java
@@ -100,7 +100,6 @@
      * Start Bluetooth LE scan with default parameters and no filters. The scan results will be
      * delivered through {@code callback}.
      * <p>
-     * Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
      * An app must hold
      * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION ACCESS_COARSE_LOCATION} or
      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission
@@ -117,7 +116,6 @@
     /**
      * Start Bluetooth LE scan. The scan results will be delivered through {@code callback}.
      * <p>
-     * Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
      * An app must hold
      * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION ACCESS_COARSE_LOCATION} or
      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission
@@ -243,8 +241,6 @@
 
     /**
      * Stops an ongoing Bluetooth LE scan.
-     * <p>
-     * Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
      *
      * @param callback
      */
@@ -263,8 +259,6 @@
 
     /**
      * Stops an ongoing Bluetooth LE scan started using a PendingIntent.
-     * <p>
-     * Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
      *
      * @param callbackIntent The PendingIntent that was used to start the scan.
      * @see #startScan(List, ScanSettings, PendingIntent)
diff --git a/core/java/android/content/ClipDescription.java b/core/java/android/content/ClipDescription.java
index d8ff222..8e30fd6 100644
--- a/core/java/android/content/ClipDescription.java
+++ b/core/java/android/content/ClipDescription.java
@@ -148,7 +148,7 @@
      * Used for setting the timestamp at which the associated {@link ClipData} is copied to
      * global clipboard.
      *
-     * @param timeStamp at which the associated {@link ClipData} is copeid to clipboard in
+     * @param timeStamp at which the associated {@link ClipData} is copied to clipboard in
      *                  {@link System#currentTimeMillis()} time base.
      * @hide
      */
diff --git a/core/java/android/content/ComponentCallbacks2.java b/core/java/android/content/ComponentCallbacks2.java
index b78548b..6576c0f 100644
--- a/core/java/android/content/ComponentCallbacks2.java
+++ b/core/java/android/content/ComponentCallbacks2.java
@@ -16,6 +16,11 @@
 
 package android.content;
 
+import android.annotation.IntDef;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
 /**
  * Extended {@link ComponentCallbacks} interface with a new callback for
  * finer-grained memory management. This interface is available in all application components
@@ -83,6 +88,19 @@
  */
 public interface ComponentCallbacks2 extends ComponentCallbacks {
 
+    /** @hide */
+    @IntDef(prefix = { "TRIM_MEMORY_" }, value = {
+            TRIM_MEMORY_COMPLETE,
+            TRIM_MEMORY_MODERATE,
+            TRIM_MEMORY_BACKGROUND,
+            TRIM_MEMORY_UI_HIDDEN,
+            TRIM_MEMORY_RUNNING_CRITICAL,
+            TRIM_MEMORY_RUNNING_LOW,
+            TRIM_MEMORY_RUNNING_MODERATE,
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface TrimMemoryLevel {}
+
     /**
      * Level for {@link #onTrimMemory(int)}: the process is nearing the end
      * of the background LRU list, and if more memory isn't found soon it will
@@ -132,7 +150,6 @@
      */
     static final int TRIM_MEMORY_RUNNING_LOW = 10;
 
-
     /**
      * Level for {@link #onTrimMemory(int)}: the process is not an expendable
      * background process, but the device is running moderately low on memory.
@@ -155,11 +172,7 @@
      * ActivityManager.getMyMemoryState(RunningAppProcessInfo)}.
      *
      * @param level The context of the trim, giving a hint of the amount of
-     * trimming the application may like to perform.  May be
-     * {@link #TRIM_MEMORY_COMPLETE}, {@link #TRIM_MEMORY_MODERATE},
-     * {@link #TRIM_MEMORY_BACKGROUND}, {@link #TRIM_MEMORY_UI_HIDDEN},
-     * {@link #TRIM_MEMORY_RUNNING_CRITICAL}, {@link #TRIM_MEMORY_RUNNING_LOW},
-     * or {@link #TRIM_MEMORY_RUNNING_MODERATE}.
+     * trimming the application may like to perform.
      */
-    void onTrimMemory(int level);
+    void onTrimMemory(@TrimMemoryLevel int level);
 }
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index 13d7362..b6f9ac9 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -4307,34 +4307,34 @@
      * learned in advance, e.g., when creating or saving content, to avoid increasing latency to
      * start {@link #ACTION_CHOOSER}. Performance on customized annotations can suffer, if they are
      * rarely used for {@link #ACTION_CHOOSER} in the past 14 days. Therefore, it is recommended to
-     * use the following annotations when applicable:</p>
+     * use the following annotations when applicable.</p>
      * <ul>
-     *     <li>"product": represents that the topic of the content is mainly about products, e.g.,
+     *     <li>"product" represents that the topic of the content is mainly about products, e.g.,
      *     health & beauty, and office supplies.</li>
-     *     <li>"emotion": represents that the topic of the content is mainly about emotions, e.g.,
+     *     <li>"emotion" represents that the topic of the content is mainly about emotions, e.g.,
      *     happy, and sad.</li>
-     *     <li>"person": represents that the topic of the content is mainly about persons, e.g.,
+     *     <li>"person" represents that the topic of the content is mainly about persons, e.g.,
      *     face, finger, standing, and walking.</li>
-     *     <li>"child": represents that the topic of the content is mainly about children, e.g.,
+     *     <li>"child" represents that the topic of the content is mainly about children, e.g.,
      *     child, and baby.</li>
-     *     <li>"selfie": represents that the topic of the content is mainly about selfies.</li>
-     *     <li>"crowd": represents that the topic of the content is mainly about crowds.</li>
-     *     <li>"party": represents that the topic of the content is mainly about parties.</li>
-     *     <li>"animal": represent that the topic of the content is mainly about animals.</li>
-     *     <li>"plant": represents that the topic of the content is mainly about plants, e.g.,
+     *     <li>"selfie" represents that the topic of the content is mainly about selfies.</li>
+     *     <li>"crowd" represents that the topic of the content is mainly about crowds.</li>
+     *     <li>"party" represents that the topic of the content is mainly about parties.</li>
+     *     <li>"animal" represent that the topic of the content is mainly about animals.</li>
+     *     <li>"plant" represents that the topic of the content is mainly about plants, e.g.,
      *     flowers.</li>
-     *     <li>"vacation": represents that the topic of the content is mainly about vacations.</li>
-     *     <li>"fashion": represents that the topic of the content is mainly about fashion, e.g.
+     *     <li>"vacation" represents that the topic of the content is mainly about vacations.</li>
+     *     <li>"fashion" represents that the topic of the content is mainly about fashion, e.g.
      *     sunglasses, jewelry, handbags and clothing.</li>
-     *     <li>"material": represents that the topic of the content is mainly about materials, e.g.,
+     *     <li>"material" represents that the topic of the content is mainly about materials, e.g.,
      *     paper, and silk.</li>
-     *     <li>"vehicle": represents that the topic of the content is mainly about vehicles, like
+     *     <li>"vehicle" represents that the topic of the content is mainly about vehicles, like
      *     cars, and boats.</li>
-     *     <li>"document": represents that the topic of the content is mainly about documents, e.g.
+     *     <li>"document" represents that the topic of the content is mainly about documents, e.g.
      *     posters.</li>
-     *     <li>"design": represents that the topic of the content is mainly about design, e.g. arts
+     *     <li>"design" represents that the topic of the content is mainly about design, e.g. arts
      *     and designs of houses.</li>
-     *     <li>"holiday": represents that the topic of the content is mainly about holidays, e.g.,
+     *     <li>"holiday" represents that the topic of the content is mainly about holidays, e.g.,
      *     Christmas and Thanksgiving.</li>
      * </ul>
      */
diff --git a/core/java/android/content/pm/ApplicationInfo.java b/core/java/android/content/pm/ApplicationInfo.java
index b0f8aa7..6c5d26a 100644
--- a/core/java/android/content/pm/ApplicationInfo.java
+++ b/core/java/android/content/pm/ApplicationInfo.java
@@ -891,7 +891,7 @@
     public @Category int category = CATEGORY_UNDEFINED;
 
     /** {@hide} */
-    @IntDef({
+    @IntDef(prefix = { "CATEGORY_" }, value = {
             CATEGORY_UNDEFINED,
             CATEGORY_GAME,
             CATEGORY_AUDIO,
diff --git a/core/java/android/content/pm/PackageInstaller.java b/core/java/android/content/pm/PackageInstaller.java
index 9e4a86d..aaaff0c 100644
--- a/core/java/android/content/pm/PackageInstaller.java
+++ b/core/java/android/content/pm/PackageInstaller.java
@@ -1084,8 +1084,6 @@
 
         /**
          * Sets which runtime permissions to be granted to the package at installation.
-         * Using this API requires holding {@link android.Manifest.permission
-         * #INSTALL_GRANT_RUNTIME_PERMISSIONS}
          *
          * @param permissions The permissions to grant or null to grant all runtime
          *     permissions.
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index b8c87e6..47d79cf 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -119,7 +119,7 @@
      */
 
     /** @hide */
-    @IntDef(flag = true, value = {
+    @IntDef(flag = true, prefix = { "GET_", "MATCH_" }, value = {
             GET_ACTIVITIES,
             GET_CONFIGURATIONS,
             GET_GIDS,
@@ -148,7 +148,7 @@
     public @interface PackageInfoFlags {}
 
     /** @hide */
-    @IntDef(flag = true, value = {
+    @IntDef(flag = true, prefix = { "GET_", "MATCH_" }, value = {
             GET_META_DATA,
             GET_SHARED_LIBRARY_FILES,
             MATCH_UNINSTALLED_PACKAGES,
@@ -164,7 +164,7 @@
     public @interface ApplicationInfoFlags {}
 
     /** @hide */
-    @IntDef(flag = true, value = {
+    @IntDef(flag = true, prefix = { "GET_", "MATCH_" }, value = {
             GET_META_DATA,
             GET_SHARED_LIBRARY_FILES,
             MATCH_ALL,
@@ -185,7 +185,7 @@
     public @interface ComponentInfoFlags {}
 
     /** @hide */
-    @IntDef(flag = true, value = {
+    @IntDef(flag = true, prefix = { "GET_", "MATCH_" }, value = {
             GET_META_DATA,
             GET_RESOLVED_FILTER,
             GET_SHARED_LIBRARY_FILES,
@@ -207,21 +207,21 @@
     public @interface ResolveInfoFlags {}
 
     /** @hide */
-    @IntDef(flag = true, value = {
+    @IntDef(flag = true, prefix = { "GET_", "MATCH_" }, value = {
             GET_META_DATA,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface PermissionInfoFlags {}
 
     /** @hide */
-    @IntDef(flag = true, value = {
+    @IntDef(flag = true, prefix = { "GET_", "MATCH_" }, value = {
             GET_META_DATA,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface PermissionGroupInfoFlags {}
 
     /** @hide */
-    @IntDef(flag = true, value = {
+    @IntDef(flag = true, prefix = { "GET_", "MATCH_" }, value = {
             GET_META_DATA,
     })
     @Retention(RetentionPolicy.SOURCE)
@@ -503,7 +503,10 @@
     public static final int ONLY_IF_NO_MATCH_FOUND = 0x00000004;
 
     /** @hide */
-    @IntDef({PERMISSION_GRANTED, PERMISSION_DENIED})
+    @IntDef(prefix = { "PERMISSION_" }, value = {
+            PERMISSION_GRANTED,
+            PERMISSION_DENIED
+    })
     @Retention(RetentionPolicy.SOURCE)
     public @interface PermissionResult {}
 
@@ -603,7 +606,7 @@
     public static final int COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED = 4;
 
     /** @hide */
-    @IntDef(flag = true, value = {
+    @IntDef(flag = true, prefix = { "INSTALL_" }, value = {
             INSTALL_FORWARD_LOCK,
             INSTALL_REPLACE_EXISTING,
             INSTALL_ALLOW_TEST,
@@ -770,8 +773,13 @@
     public static final int DONT_KILL_APP = 0x00000001;
 
     /** @hide */
-    @IntDef({INSTALL_REASON_UNKNOWN, INSTALL_REASON_POLICY, INSTALL_REASON_DEVICE_RESTORE,
-            INSTALL_REASON_DEVICE_SETUP, INSTALL_REASON_USER})
+    @IntDef(prefix = { "INSTALL_REASON_" }, value = {
+            INSTALL_REASON_UNKNOWN,
+            INSTALL_REASON_POLICY,
+            INSTALL_REASON_DEVICE_RESTORE,
+            INSTALL_REASON_DEVICE_SETUP,
+            INSTALL_REASON_USER
+    })
     @Retention(RetentionPolicy.SOURCE)
     public @interface InstallReason {}
 
@@ -1247,7 +1255,7 @@
     public static final int INSTALL_FAILED_INSTANT_APP_INVALID = -116;
 
     /** @hide */
-    @IntDef(flag = true, value = {
+    @IntDef(flag = true, prefix = { "DELETE_" }, value = {
             DELETE_KEEP_DATA,
             DELETE_ALL_USERS,
             DELETE_SYSTEM_APP,
@@ -2768,44 +2776,17 @@
      * installed on the system.
      *
      * @param packageName The full name (i.e. com.google.apps.contacts) of the
-     *         desired package.
-     * @param flags Additional option flags. Use any combination of
-     *         {@link #GET_ACTIVITIES}, {@link #GET_CONFIGURATIONS},
-     *         {@link #GET_GIDS}, {@link #GET_INSTRUMENTATION},
-     *         {@link #GET_INTENT_FILTERS}, {@link #GET_META_DATA},
-     *         {@link #GET_PERMISSIONS}, {@link #GET_PROVIDERS},
-     *         {@link #GET_RECEIVERS}, {@link #GET_SERVICES},
-     *         {@link #GET_SHARED_LIBRARY_FILES}, {@link #GET_SIGNATURES},
-     *         {@link #GET_URI_PERMISSION_PATTERNS}, {@link #GET_UNINSTALLED_PACKAGES},
-     *         {@link #MATCH_DISABLED_COMPONENTS}, {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *         {@link #MATCH_UNINSTALLED_PACKAGES}
-     *         to modify the data returned.
-     *
-     * @return A PackageInfo object containing information about the
-     *         package. If flag {@code MATCH_UNINSTALLED_PACKAGES} is set and if the
-     *         package is not found in the list of installed applications, the
-     *         package information is retrieved from the list of uninstalled
+     *            desired package.
+     * @param flags Additional option flags to modify the data returned.
+     * @return A PackageInfo object containing information about the package. If
+     *         flag {@code MATCH_UNINSTALLED_PACKAGES} is set and if the package
+     *         is not found in the list of installed applications, the package
+     *         information is retrieved from the list of uninstalled
      *         applications (which includes installed applications as well as
      *         applications with data directory i.e. applications which had been
      *         deleted with {@code DONT_DELETE_DATA} flag set).
      * @throws NameNotFoundException if a package with the given name cannot be
      *             found on the system.
-     * @see #GET_ACTIVITIES
-     * @see #GET_CONFIGURATIONS
-     * @see #GET_GIDS
-     * @see #GET_INSTRUMENTATION
-     * @see #GET_INTENT_FILTERS
-     * @see #GET_META_DATA
-     * @see #GET_PERMISSIONS
-     * @see #GET_PROVIDERS
-     * @see #GET_RECEIVERS
-     * @see #GET_SERVICES
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #GET_SIGNATURES
-     * @see #GET_URI_PERMISSION_PATTERNS
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract PackageInfo getPackageInfo(String packageName, @PackageInfoFlags int flags)
             throws NameNotFoundException;
@@ -2813,51 +2794,24 @@
     /**
      * Retrieve overall information about an application package that is
      * installed on the system. This method can be used for retrieving
-     * information about packages for which multiple versions can be
-     * installed at the time. Currently only packages hosting static shared
-     * libraries can have multiple installed versions. The method can also
-     * be used to get info for a package that has a single version installed
-     * by passing {@link #VERSION_CODE_HIGHEST} in the {@link VersionedPackage}
+     * information about packages for which multiple versions can be installed
+     * at the time. Currently only packages hosting static shared libraries can
+     * have multiple installed versions. The method can also be used to get info
+     * for a package that has a single version installed by passing
+     * {@link #VERSION_CODE_HIGHEST} in the {@link VersionedPackage}
      * constructor.
      *
      * @param versionedPackage The versioned package for which to query.
-     * @param flags Additional option flags. Use any combination of
-     *         {@link #GET_ACTIVITIES}, {@link #GET_CONFIGURATIONS},
-     *         {@link #GET_GIDS}, {@link #GET_INSTRUMENTATION},
-     *         {@link #GET_INTENT_FILTERS}, {@link #GET_META_DATA},
-     *         {@link #GET_PERMISSIONS}, {@link #GET_PROVIDERS},
-     *         {@link #GET_RECEIVERS}, {@link #GET_SERVICES},
-     *         {@link #GET_SHARED_LIBRARY_FILES}, {@link #GET_SIGNATURES},
-     *         {@link #GET_URI_PERMISSION_PATTERNS}, {@link #GET_UNINSTALLED_PACKAGES},
-     *         {@link #MATCH_DISABLED_COMPONENTS}, {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *         {@link #MATCH_UNINSTALLED_PACKAGES}
-     *         to modify the data returned.
-     *
-     * @return A PackageInfo object containing information about the
-     *         package. If flag {@code MATCH_UNINSTALLED_PACKAGES} is set and if the
-     *         package is not found in the list of installed applications, the
-     *         package information is retrieved from the list of uninstalled
+     * @param flags Additional option flags to modify the data returned.
+     * @return A PackageInfo object containing information about the package. If
+     *         flag {@code MATCH_UNINSTALLED_PACKAGES} is set and if the package
+     *         is not found in the list of installed applications, the package
+     *         information is retrieved from the list of uninstalled
      *         applications (which includes installed applications as well as
      *         applications with data directory i.e. applications which had been
      *         deleted with {@code DONT_DELETE_DATA} flag set).
      * @throws NameNotFoundException if a package with the given name cannot be
      *             found on the system.
-     * @see #GET_ACTIVITIES
-     * @see #GET_CONFIGURATIONS
-     * @see #GET_GIDS
-     * @see #GET_INSTRUMENTATION
-     * @see #GET_INTENT_FILTERS
-     * @see #GET_META_DATA
-     * @see #GET_PERMISSIONS
-     * @see #GET_PROVIDERS
-     * @see #GET_RECEIVERS
-     * @see #GET_SERVICES
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #GET_SIGNATURES
-     * @see #GET_URI_PERMISSION_PATTERNS
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract PackageInfo getPackageInfo(VersionedPackage versionedPackage,
             @PackageInfoFlags int flags) throws NameNotFoundException;
@@ -2867,46 +2821,18 @@
      * installed on the system.
      *
      * @param packageName The full name (i.e. com.google.apps.contacts) of the
-     *         desired package.
-     * @param flags Additional option flags. Use any combination of
-     *         {@link #GET_ACTIVITIES}, {@link #GET_CONFIGURATIONS},
-     *         {@link #GET_GIDS}, {@link #GET_INSTRUMENTATION},
-     *         {@link #GET_INTENT_FILTERS}, {@link #GET_META_DATA},
-     *         {@link #GET_PERMISSIONS}, {@link #GET_PROVIDERS},
-     *         {@link #GET_RECEIVERS}, {@link #GET_SERVICES},
-     *         {@link #GET_SHARED_LIBRARY_FILES}, {@link #GET_SIGNATURES},
-     *         {@link #GET_URI_PERMISSION_PATTERNS}, {@link #GET_UNINSTALLED_PACKAGES},
-     *         {@link #MATCH_DISABLED_COMPONENTS}, {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *         {@link #MATCH_UNINSTALLED_PACKAGES}
-     *         to modify the data returned.
+     *            desired package.
+     * @param flags Additional option flags to modify the data returned.
      * @param userId The user id.
-     *
-     * @return A PackageInfo object containing information about the
-     *         package. If flag {@code MATCH_UNINSTALLED_PACKAGES} is set and if the
-     *         package is not found in the list of installed applications, the
-     *         package information is retrieved from the list of uninstalled
+     * @return A PackageInfo object containing information about the package. If
+     *         flag {@code MATCH_UNINSTALLED_PACKAGES} is set and if the package
+     *         is not found in the list of installed applications, the package
+     *         information is retrieved from the list of uninstalled
      *         applications (which includes installed applications as well as
      *         applications with data directory i.e. applications which had been
      *         deleted with {@code DONT_DELETE_DATA} flag set).
      * @throws NameNotFoundException if a package with the given name cannot be
      *             found on the system.
-     * @see #GET_ACTIVITIES
-     * @see #GET_CONFIGURATIONS
-     * @see #GET_GIDS
-     * @see #GET_INSTRUMENTATION
-     * @see #GET_INTENT_FILTERS
-     * @see #GET_META_DATA
-     * @see #GET_PERMISSIONS
-     * @see #GET_PROVIDERS
-     * @see #GET_RECEIVERS
-     * @see #GET_SERVICES
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #GET_SIGNATURES
-     * @see #GET_URI_PERMISSION_PATTERNS
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_UNINSTALLED_PACKAGES
-     *
      * @hide
      */
     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
@@ -3048,16 +2974,12 @@
      * Retrieve all of the information we know about a particular permission.
      *
      * @param name The fully qualified name (i.e. com.google.permission.LOGIN)
-     *         of the permission you are interested in.
-     * @param flags Additional option flags.  Use {@link #GET_META_DATA} to
-     *         retrieve any meta-data associated with the permission.
-     *
+     *            of the permission you are interested in.
+     * @param flags Additional option flags to modify the data returned.
      * @return Returns a {@link PermissionInfo} containing information about the
      *         permission.
      * @throws NameNotFoundException if a package with the given name cannot be
      *             found on the system.
-     *
-     * @see #GET_META_DATA
      */
     public abstract PermissionInfo getPermissionInfo(String name, @PermissionInfoFlags int flags)
             throws NameNotFoundException;
@@ -3066,17 +2988,13 @@
      * Query for all of the permissions associated with a particular group.
      *
      * @param group The fully qualified name (i.e. com.google.permission.LOGIN)
-     *         of the permission group you are interested in.  Use null to
-     *         find all of the permissions not associated with a group.
-     * @param flags Additional option flags.  Use {@link #GET_META_DATA} to
-     *         retrieve any meta-data associated with the permissions.
-     *
+     *            of the permission group you are interested in. Use null to
+     *            find all of the permissions not associated with a group.
+     * @param flags Additional option flags to modify the data returned.
      * @return Returns a list of {@link PermissionInfo} containing information
-     *             about all of the permissions in the given group.
+     *         about all of the permissions in the given group.
      * @throws NameNotFoundException if a package with the given name cannot be
      *             found on the system.
-     *
-     * @see #GET_META_DATA
      */
     public abstract List<PermissionInfo> queryPermissionsByGroup(String group,
             @PermissionInfoFlags int flags) throws NameNotFoundException;
@@ -3093,17 +3011,14 @@
      * Retrieve all of the information we know about a particular group of
      * permissions.
      *
-     * @param name The fully qualified name (i.e. com.google.permission_group.APPS)
-     *         of the permission you are interested in.
-     * @param flags Additional option flags.  Use {@link #GET_META_DATA} to
-     *         retrieve any meta-data associated with the permission group.
-     *
+     * @param name The fully qualified name (i.e.
+     *            com.google.permission_group.APPS) of the permission you are
+     *            interested in.
+     * @param flags Additional option flags to modify the data returned.
      * @return Returns a {@link PermissionGroupInfo} containing information
      *         about the permission.
      * @throws NameNotFoundException if a package with the given name cannot be
      *             found on the system.
-     *
-     * @see #GET_META_DATA
      */
     public abstract PermissionGroupInfo getPermissionGroupInfo(String name,
             @PermissionGroupInfoFlags int flags) throws NameNotFoundException;
@@ -3111,13 +3026,9 @@
     /**
      * Retrieve all of the known permission groups in the system.
      *
-     * @param flags Additional option flags.  Use {@link #GET_META_DATA} to
-     *         retrieve any meta-data associated with the permission group.
-     *
+     * @param flags Additional option flags to modify the data returned.
      * @return Returns a list of {@link PermissionGroupInfo} containing
      *         information about all of the known permission groups.
-     *
-     * @see #GET_META_DATA
      */
     public abstract List<PermissionGroupInfo> getAllPermissionGroups(
             @PermissionGroupInfoFlags int flags);
@@ -3127,27 +3038,17 @@
      * package/application.
      *
      * @param packageName The full name (i.e. com.google.apps.contacts) of an
-     *         application.
-     * @param flags Additional option flags. Use any combination of
-     *         {@link #GET_META_DATA}, {@link #GET_SHARED_LIBRARY_FILES},
-     *         {@link #MATCH_SYSTEM_ONLY}, {@link #MATCH_UNINSTALLED_PACKAGES}
-     *         to modify the data returned.
-     *
+     *            application.
+     * @param flags Additional option flags to modify the data returned.
      * @return An {@link ApplicationInfo} containing information about the
-     *         package. If flag {@code MATCH_UNINSTALLED_PACKAGES} is set and if the
-     *         package is not found in the list of installed applications, the
-     *         application information is retrieved from the list of uninstalled
-     *         applications (which includes installed applications as well as
-     *         applications with data directory i.e. applications which had been
-     *         deleted with {@code DONT_DELETE_DATA} flag set).
+     *         package. If flag {@code MATCH_UNINSTALLED_PACKAGES} is set and if
+     *         the package is not found in the list of installed applications,
+     *         the application information is retrieved from the list of
+     *         uninstalled applications (which includes installed applications
+     *         as well as applications with data directory i.e. applications
+     *         which had been deleted with {@code DONT_DELETE_DATA} flag set).
      * @throws NameNotFoundException if a package with the given name cannot be
      *             found on the system.
-     *
-     * @see #GET_META_DATA
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract ApplicationInfo getApplicationInfo(String packageName,
             @ApplicationInfoFlags int flags) throws NameNotFoundException;
@@ -3163,30 +3064,11 @@
      * @param component The full component name (i.e.
      *            com.google.apps.contacts/com.google.apps.contacts.
      *            ContactsList) of an Activity class.
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_SHARED_LIBRARY_FILES},
-     *            {@link #MATCH_ALL}, {@link #MATCH_DEFAULT_ONLY},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @return An {@link ActivityInfo} containing information about the
      *         activity.
      * @throws NameNotFoundException if a package with the given name cannot be
      *             found on the system.
-     * @see #GET_META_DATA
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DEBUG_TRIAGED_MISSING
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract ActivityInfo getActivityInfo(ComponentName component,
             @ComponentInfoFlags int flags) throws NameNotFoundException;
@@ -3198,30 +3080,11 @@
      * @param component The full component name (i.e.
      *            com.google.apps.calendar/com.google.apps.calendar.
      *            CalendarAlarm) of a Receiver class.
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_SHARED_LIBRARY_FILES},
-     *            {@link #MATCH_ALL}, {@link #MATCH_DEFAULT_ONLY},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @return An {@link ActivityInfo} containing information about the
      *         receiver.
      * @throws NameNotFoundException if a package with the given name cannot be
      *             found on the system.
-     * @see #GET_META_DATA
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DEBUG_TRIAGED_MISSING
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract ActivityInfo getReceiverInfo(ComponentName component,
             @ComponentInfoFlags int flags) throws NameNotFoundException;
@@ -3232,30 +3095,11 @@
      * @param component The full component name (i.e.
      *            com.google.apps.media/com.google.apps.media.
      *            BackgroundPlayback) of a Service class.
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_SHARED_LIBRARY_FILES},
-     *            {@link #MATCH_ALL}, {@link #MATCH_DEFAULT_ONLY},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @return A {@link ServiceInfo} object containing information about the
      *         service.
      * @throws NameNotFoundException if a package with the given name cannot be
      *             found on the system.
-     * @see #GET_META_DATA
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DEBUG_TRIAGED_MISSING
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract ServiceInfo getServiceInfo(ComponentName component,
             @ComponentInfoFlags int flags) throws NameNotFoundException;
@@ -3267,168 +3111,63 @@
      * @param component The full component name (i.e.
      *            com.google.providers.media/com.google.providers.media.
      *            MediaProvider) of a ContentProvider class.
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_SHARED_LIBRARY_FILES},
-     *            {@link #MATCH_ALL}, {@link #MATCH_DEFAULT_ONLY},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @return A {@link ProviderInfo} object containing information about the
      *         provider.
      * @throws NameNotFoundException if a package with the given name cannot be
      *             found on the system.
-     * @see #GET_META_DATA
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DEBUG_TRIAGED_MISSING
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract ProviderInfo getProviderInfo(ComponentName component,
             @ComponentInfoFlags int flags) throws NameNotFoundException;
 
     /**
-     * Return a List of all packages that are installed
-     * on the device.
+     * Return a List of all packages that are installed on the device.
      *
-     * @param flags Additional option flags. Use any combination of
-     *         {@link #GET_ACTIVITIES}, {@link #GET_CONFIGURATIONS},
-     *         {@link #GET_GIDS}, {@link #GET_INSTRUMENTATION},
-     *         {@link #GET_INTENT_FILTERS}, {@link #GET_META_DATA},
-     *         {@link #GET_PERMISSIONS}, {@link #GET_PROVIDERS},
-     *         {@link #GET_RECEIVERS}, {@link #GET_SERVICES},
-     *         {@link #GET_SHARED_LIBRARY_FILES}, {@link #GET_SIGNATURES},
-     *         {@link #GET_URI_PERMISSION_PATTERNS}, {@link #GET_UNINSTALLED_PACKAGES},
-     *         {@link #MATCH_DISABLED_COMPONENTS}, {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *         {@link #MATCH_UNINSTALLED_PACKAGES}
-     *         to modify the data returned.
-     *
+     * @param flags Additional option flags to modify the data returned.
      * @return A List of PackageInfo objects, one for each installed package,
-     *         containing information about the package.  In the unlikely case
+     *         containing information about the package. In the unlikely case
      *         there are no installed packages, an empty list is returned. If
      *         flag {@code MATCH_UNINSTALLED_PACKAGES} is set, the package
      *         information is retrieved from the list of uninstalled
      *         applications (which includes installed applications as well as
      *         applications with data directory i.e. applications which had been
      *         deleted with {@code DONT_DELETE_DATA} flag set).
-     *
-     * @see #GET_ACTIVITIES
-     * @see #GET_CONFIGURATIONS
-     * @see #GET_GIDS
-     * @see #GET_INSTRUMENTATION
-     * @see #GET_INTENT_FILTERS
-     * @see #GET_META_DATA
-     * @see #GET_PERMISSIONS
-     * @see #GET_PROVIDERS
-     * @see #GET_RECEIVERS
-     * @see #GET_SERVICES
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #GET_SIGNATURES
-     * @see #GET_URI_PERMISSION_PATTERNS
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract List<PackageInfo> getInstalledPackages(@PackageInfoFlags int flags);
 
     /**
-     * Return a List of all installed packages that are currently
-     * holding any of the given permissions.
+     * Return a List of all installed packages that are currently holding any of
+     * the given permissions.
      *
-     * @param flags Additional option flags. Use any combination of
-     *         {@link #GET_ACTIVITIES}, {@link #GET_CONFIGURATIONS},
-     *         {@link #GET_GIDS}, {@link #GET_INSTRUMENTATION},
-     *         {@link #GET_INTENT_FILTERS}, {@link #GET_META_DATA},
-     *         {@link #GET_PERMISSIONS}, {@link #GET_PROVIDERS},
-     *         {@link #GET_RECEIVERS}, {@link #GET_SERVICES},
-     *         {@link #GET_SHARED_LIBRARY_FILES}, {@link #GET_SIGNATURES},
-     *         {@link #GET_URI_PERMISSION_PATTERNS}, {@link #GET_UNINSTALLED_PACKAGES},
-     *         {@link #MATCH_DISABLED_COMPONENTS}, {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *         {@link #MATCH_UNINSTALLED_PACKAGES}
-     *         to modify the data returned.
-     *
+     * @param flags Additional option flags to modify the data returned.
      * @return A List of PackageInfo objects, one for each installed package
      *         that holds any of the permissions that were provided, containing
      *         information about the package. If no installed packages hold any
      *         of the permissions, an empty list is returned. If flag
-     *         {@code MATCH_UNINSTALLED_PACKAGES} is set, the package information
-     *         is retrieved from the list of uninstalled applications (which
-     *         includes installed applications as well as applications with data
-     *         directory i.e. applications which had been deleted with
-     *         {@code DONT_DELETE_DATA} flag set).
-     *
-     * @see #GET_ACTIVITIES
-     * @see #GET_CONFIGURATIONS
-     * @see #GET_GIDS
-     * @see #GET_INSTRUMENTATION
-     * @see #GET_INTENT_FILTERS
-     * @see #GET_META_DATA
-     * @see #GET_PERMISSIONS
-     * @see #GET_PROVIDERS
-     * @see #GET_RECEIVERS
-     * @see #GET_SERVICES
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #GET_SIGNATURES
-     * @see #GET_URI_PERMISSION_PATTERNS
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_UNINSTALLED_PACKAGES
+     *         {@code MATCH_UNINSTALLED_PACKAGES} is set, the package
+     *         information is retrieved from the list of uninstalled
+     *         applications (which includes installed applications as well as
+     *         applications with data directory i.e. applications which had been
+     *         deleted with {@code DONT_DELETE_DATA} flag set).
      */
     public abstract List<PackageInfo> getPackagesHoldingPermissions(
             String[] permissions, @PackageInfoFlags int flags);
 
     /**
-     * Return a List of all packages that are installed on the device, for a specific user.
-     * Requesting a list of installed packages for another user
+     * Return a List of all packages that are installed on the device, for a
+     * specific user. Requesting a list of installed packages for another user
      * will require the permission INTERACT_ACROSS_USERS_FULL.
      *
-     * @param flags Additional option flags. Use any combination of
-     *         {@link #GET_ACTIVITIES}, {@link #GET_CONFIGURATIONS},
-     *         {@link #GET_GIDS}, {@link #GET_INSTRUMENTATION},
-     *         {@link #GET_INTENT_FILTERS}, {@link #GET_META_DATA},
-     *         {@link #GET_PERMISSIONS}, {@link #GET_PROVIDERS},
-     *         {@link #GET_RECEIVERS}, {@link #GET_SERVICES},
-     *         {@link #GET_SHARED_LIBRARY_FILES}, {@link #GET_SIGNATURES},
-     *         {@link #GET_URI_PERMISSION_PATTERNS}, {@link #GET_UNINSTALLED_PACKAGES},
-     *         {@link #MATCH_DISABLED_COMPONENTS}, {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *         {@link #MATCH_UNINSTALLED_PACKAGES}
-     *         to modify the data returned.
+     * @param flags Additional option flags to modify the data returned.
      * @param userId The user for whom the installed packages are to be listed
-     *
      * @return A List of PackageInfo objects, one for each installed package,
-     *         containing information about the package.  In the unlikely case
+     *         containing information about the package. In the unlikely case
      *         there are no installed packages, an empty list is returned. If
      *         flag {@code MATCH_UNINSTALLED_PACKAGES} is set, the package
      *         information is retrieved from the list of uninstalled
      *         applications (which includes installed applications as well as
      *         applications with data directory i.e. applications which had been
      *         deleted with {@code DONT_DELETE_DATA} flag set).
-     *
-     * @see #GET_ACTIVITIES
-     * @see #GET_CONFIGURATIONS
-     * @see #GET_GIDS
-     * @see #GET_INSTRUMENTATION
-     * @see #GET_INTENT_FILTERS
-     * @see #GET_META_DATA
-     * @see #GET_PERMISSIONS
-     * @see #GET_PROVIDERS
-     * @see #GET_RECEIVERS
-     * @see #GET_SERVICES
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #GET_SIGNATURES
-     * @see #GET_URI_PERMISSION_PATTERNS
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_UNINSTALLED_PACKAGES
-     *
      * @hide
      */
     @SystemApi
@@ -3541,12 +3280,14 @@
      * @hide
      */
     @SystemApi
-    @IntDef({FLAG_PERMISSION_USER_SET,
+    @IntDef(prefix = { "FLAG_PERMISSION_" }, value = {
+            FLAG_PERMISSION_USER_SET,
             FLAG_PERMISSION_USER_FIXED,
             FLAG_PERMISSION_POLICY_FIXED,
             FLAG_PERMISSION_REVOKE_ON_UPGRADE,
             FLAG_PERMISSION_SYSTEM_FIXED,
-            FLAG_PERMISSION_GRANTED_BY_DEFAULT})
+            FLAG_PERMISSION_GRANTED_BY_DEFAULT
+    })
     @Retention(RetentionPolicy.SOURCE)
     public @interface PermissionFlags {}
 
@@ -3627,7 +3368,7 @@
      */
     @SystemApi
     public abstract void updatePermissionFlags(String permissionName,
-            String packageName, @PermissionFlags int flagMask, int flagValues,
+            String packageName, @PermissionFlags int flagMask, @PermissionFlags int flagValues,
             @NonNull UserHandle user);
 
     /**
@@ -3755,67 +3496,46 @@
     /**
      * Return a List of all application packages that are installed on the
      * device. If flag GET_UNINSTALLED_PACKAGES has been set, a list of all
-     * applications including those deleted with {@code DONT_DELETE_DATA} (partially
-     * installed apps with data directory) will be returned.
+     * applications including those deleted with {@code DONT_DELETE_DATA}
+     * (partially installed apps with data directory) will be returned.
      *
-     * @param flags Additional option flags. Use any combination of
-     * {@link #GET_META_DATA}, {@link #GET_SHARED_LIBRARY_FILES},
-     * {@link #MATCH_DISABLED_COMPONENTS}, {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS}
-     * {@link #MATCH_SYSTEM_ONLY}, {@link #MATCH_UNINSTALLED_PACKAGES}
-     * to modify the data returned.
-     *
-     * @return A List of ApplicationInfo objects, one for each installed application.
-     *         In the unlikely case there are no installed packages, an empty list
-     *         is returned. If flag {@code MATCH_UNINSTALLED_PACKAGES} is set, the
-     *         application information is retrieved from the list of uninstalled
+     * @param flags Additional option flags to modify the data returned.
+     * @return A List of ApplicationInfo objects, one for each installed
+     *         application. In the unlikely case there are no installed
+     *         packages, an empty list is returned. If flag
+     *         {@code MATCH_UNINSTALLED_PACKAGES} is set, the application
+     *         information is retrieved from the list of uninstalled
      *         applications (which includes installed applications as well as
      *         applications with data directory i.e. applications which had been
      *         deleted with {@code DONT_DELETE_DATA} flag set).
-     *
-     * @see #GET_META_DATA
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract List<ApplicationInfo> getInstalledApplications(@ApplicationInfoFlags int flags);
 
     /**
-     * Return a List of all application packages that are installed on the device, for a specific
-     * user. If flag GET_UNINSTALLED_PACKAGES has been set, a list of all applications including
-     * those deleted with {@code DONT_DELETE_DATA} (partially installed apps with data directory)
+     * Return a List of all application packages that are installed on the
+     * device, for a specific user. If flag GET_UNINSTALLED_PACKAGES has been
+     * set, a list of all applications including those deleted with
+     * {@code DONT_DELETE_DATA} (partially installed apps with data directory)
      * will be returned.
      *
-     * @param flags Additional option flags. Use any combination of
-     * {@link #GET_META_DATA}, {@link #GET_SHARED_LIBRARY_FILES},
-     * {@link #MATCH_DISABLED_COMPONENTS}, {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS}
-     * {@link #MATCH_SYSTEM_ONLY}, {@link #MATCH_UNINSTALLED_PACKAGES}
-     * to modify the data returned.
-     * @param userId The user for whom the installed applications are to be listed
-     *
-     * @return A List of ApplicationInfo objects, one for each installed application.
-     *         In the unlikely case there are no installed packages, an empty list
-     *         is returned. If flag {@code MATCH_UNINSTALLED_PACKAGES} is set, the
-     *         application information is retrieved from the list of uninstalled
+     * @param flags Additional option flags to modify the data returned.
+     * @param userId The user for whom the installed applications are to be
+     *            listed
+     * @return A List of ApplicationInfo objects, one for each installed
+     *         application. In the unlikely case there are no installed
+     *         packages, an empty list is returned. If flag
+     *         {@code MATCH_UNINSTALLED_PACKAGES} is set, the application
+     *         information is retrieved from the list of uninstalled
      *         applications (which includes installed applications as well as
      *         applications with data directory i.e. applications which had been
      *         deleted with {@code DONT_DELETE_DATA} flag set).
      * @hide
-     *
-     * @see #GET_META_DATA
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract List<ApplicationInfo> getInstalledApplicationsAsUser(
             @ApplicationInfoFlags int flags, @UserIdInt int userId);
 
     /**
-     * Gets the instant applications the user recently used. Requires
-     * holding "android.permission.ACCESS_INSTANT_APPS".
+     * Gets the instant applications the user recently used.
      *
      * @return The instant app list.
      *
@@ -4055,33 +3775,15 @@
      *
      * @param intent An intent containing all of the desired specification
      *            (action, data, type, category, and/or component).
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_RESOLVED_FILTER},
-     *            {@link #GET_SHARED_LIBRARY_FILES}, {@link #MATCH_ALL},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DEFAULT_ONLY}, {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned. The most important is {@link #MATCH_DEFAULT_ONLY},
-     *            to limit the resolution to only those activities that support
-     *            the {@link android.content.Intent#CATEGORY_DEFAULT}.
+     * @param flags Additional option flags to modify the data returned. The
+     *            most important is {@link #MATCH_DEFAULT_ONLY}, to limit the
+     *            resolution to only those activities that support the
+     *            {@link android.content.Intent#CATEGORY_DEFAULT}.
      * @return Returns a ResolveInfo object containing the final activity intent
      *         that was determined to be the best action. Returns null if no
      *         matching activity was found. If multiple matching activities are
      *         found and there is no default set, returns a ResolveInfo object
      *         containing something else, such as the activity resolver.
-     * @see #GET_META_DATA
-     * @see #GET_RESOLVED_FILTER
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract ResolveInfo resolveActivity(Intent intent, @ResolveInfoFlags int flags);
 
@@ -4101,34 +3803,16 @@
      *
      * @param intent An intent containing all of the desired specification
      *            (action, data, type, category, and/or component).
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_RESOLVED_FILTER},
-     *            {@link #GET_SHARED_LIBRARY_FILES}, {@link #MATCH_ALL},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DEFAULT_ONLY}, {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned. The most important is {@link #MATCH_DEFAULT_ONLY},
-     *            to limit the resolution to only those activities that support
-     *            the {@link android.content.Intent#CATEGORY_DEFAULT}.
+     * @param flags Additional option flags to modify the data returned. The
+     *            most important is {@link #MATCH_DEFAULT_ONLY}, to limit the
+     *            resolution to only those activities that support the
+     *            {@link android.content.Intent#CATEGORY_DEFAULT}.
      * @param userId The user id.
      * @return Returns a ResolveInfo object containing the final activity intent
      *         that was determined to be the best action. Returns null if no
      *         matching activity was found. If multiple matching activities are
      *         found and there is no default set, returns a ResolveInfo object
      *         containing something else, such as the activity resolver.
-     * @see #GET_META_DATA
-     * @see #GET_RESOLVED_FILTER
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      * @hide
      */
     public abstract ResolveInfo resolveActivityAsUser(Intent intent, @ResolveInfoFlags int flags,
@@ -4138,34 +3822,16 @@
      * Retrieve all activities that can be performed for the given intent.
      *
      * @param intent The desired intent as per resolveActivity().
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_RESOLVED_FILTER},
-     *            {@link #GET_SHARED_LIBRARY_FILES}, {@link #MATCH_ALL},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DEFAULT_ONLY}, {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned. The most important is {@link #MATCH_DEFAULT_ONLY},
-     *            to limit the resolution to only those activities that support
-     *            the {@link android.content.Intent#CATEGORY_DEFAULT}. Or, set
+     * @param flags Additional option flags to modify the data returned. The
+     *            most important is {@link #MATCH_DEFAULT_ONLY}, to limit the
+     *            resolution to only those activities that support the
+     *            {@link android.content.Intent#CATEGORY_DEFAULT}. Or, set
      *            {@link #MATCH_ALL} to prevent any filtering of the results.
      * @return Returns a List of ResolveInfo objects containing one entry for
      *         each matching activity, ordered from best to worst. In other
      *         words, the first item is what would be returned by
      *         {@link #resolveActivity}. If there are no matching activities, an
      *         empty list is returned.
-     * @see #GET_META_DATA
-     * @see #GET_RESOLVED_FILTER
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract List<ResolveInfo> queryIntentActivities(Intent intent,
             @ResolveInfoFlags int flags);
@@ -4175,34 +3841,16 @@
      * specific user.
      *
      * @param intent The desired intent as per resolveActivity().
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_RESOLVED_FILTER},
-     *            {@link #GET_SHARED_LIBRARY_FILES}, {@link #MATCH_ALL},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DEFAULT_ONLY}, {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned. The most important is {@link #MATCH_DEFAULT_ONLY},
-     *            to limit the resolution to only those activities that support
-     *            the {@link android.content.Intent#CATEGORY_DEFAULT}. Or, set
+     * @param flags Additional option flags to modify the data returned. The
+     *            most important is {@link #MATCH_DEFAULT_ONLY}, to limit the
+     *            resolution to only those activities that support the
+     *            {@link android.content.Intent#CATEGORY_DEFAULT}. Or, set
      *            {@link #MATCH_ALL} to prevent any filtering of the results.
      * @return Returns a List of ResolveInfo objects containing one entry for
      *         each matching activity, ordered from best to worst. In other
      *         words, the first item is what would be returned by
      *         {@link #resolveActivity}. If there are no matching activities, an
      *         empty list is returned.
-     * @see #GET_META_DATA
-     * @see #GET_RESOLVED_FILTER
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      * @hide
      */
     public abstract List<ResolveInfo> queryIntentActivitiesAsUser(Intent intent,
@@ -4222,34 +3870,16 @@
      * @param specifics An array of Intents that should be resolved to the first
      *            specific results. Can be null.
      * @param intent The desired intent as per resolveActivity().
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_RESOLVED_FILTER},
-     *            {@link #GET_SHARED_LIBRARY_FILES}, {@link #MATCH_ALL},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DEFAULT_ONLY}, {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned. The most important is {@link #MATCH_DEFAULT_ONLY},
-     *            to limit the resolution to only those activities that support
-     *            the {@link android.content.Intent#CATEGORY_DEFAULT}.
+     * @param flags Additional option flags to modify the data returned. The
+     *            most important is {@link #MATCH_DEFAULT_ONLY}, to limit the
+     *            resolution to only those activities that support the
+     *            {@link android.content.Intent#CATEGORY_DEFAULT}.
      * @return Returns a List of ResolveInfo objects containing one entry for
      *         each matching activity. The list is ordered first by all of the
      *         intents resolved in <var>specifics</var> and then any additional
      *         activities that can handle <var>intent</var> but did not get
      *         included by one of the <var>specifics</var> intents. If there are
      *         no matching activities, an empty list is returned.
-     * @see #GET_META_DATA
-     * @see #GET_RESOLVED_FILTER
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract List<ResolveInfo> queryIntentActivityOptions(
             ComponentName caller, Intent[] specifics, Intent intent, @ResolveInfoFlags int flags);
@@ -4258,29 +3888,10 @@
      * Retrieve all receivers that can handle a broadcast of the given intent.
      *
      * @param intent The desired intent as per resolveActivity().
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_RESOLVED_FILTER},
-     *            {@link #GET_SHARED_LIBRARY_FILES}, {@link #MATCH_ALL},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DEFAULT_ONLY}, {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @return Returns a List of ResolveInfo objects containing one entry for
      *         each matching receiver, ordered from best to worst. If there are
      *         no matching receivers, an empty list or null is returned.
-     * @see #GET_META_DATA
-     * @see #GET_RESOLVED_FILTER
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract List<ResolveInfo> queryBroadcastReceivers(Intent intent,
             @ResolveInfoFlags int flags);
@@ -4290,30 +3901,11 @@
      * for a specific user.
      *
      * @param intent The desired intent as per resolveActivity().
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_RESOLVED_FILTER},
-     *            {@link #GET_SHARED_LIBRARY_FILES}, {@link #MATCH_ALL},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DEFAULT_ONLY}, {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @param userHandle UserHandle of the user being queried.
      * @return Returns a List of ResolveInfo objects containing one entry for
      *         each matching receiver, ordered from best to worst. If there are
      *         no matching receivers, an empty list or null is returned.
-     * @see #GET_META_DATA
-     * @see #GET_RESOLVED_FILTER
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      * @hide
      */
     @SystemApi
@@ -4348,29 +3940,10 @@
      *
      * @param intent An intent containing all of the desired specification
      *            (action, data, type, category, and/or component).
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_RESOLVED_FILTER},
-     *            {@link #GET_SHARED_LIBRARY_FILES}, {@link #MATCH_ALL},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DEFAULT_ONLY}, {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @return Returns a ResolveInfo object containing the final service intent
      *         that was determined to be the best action. Returns null if no
      *         matching service was found.
-     * @see #GET_META_DATA
-     * @see #GET_RESOLVED_FILTER
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract ResolveInfo resolveService(Intent intent, @ResolveInfoFlags int flags);
 
@@ -4378,31 +3951,12 @@
      * Retrieve all services that can match the given intent.
      *
      * @param intent The desired intent as per resolveService().
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_RESOLVED_FILTER},
-     *            {@link #GET_SHARED_LIBRARY_FILES}, {@link #MATCH_ALL},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DEFAULT_ONLY}, {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @return Returns a List of ResolveInfo objects containing one entry for
      *         each matching service, ordered from best to worst. In other
      *         words, the first item is what would be returned by
      *         {@link #resolveService}. If there are no matching services, an
      *         empty list or null is returned.
-     * @see #GET_META_DATA
-     * @see #GET_RESOLVED_FILTER
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract List<ResolveInfo> queryIntentServices(Intent intent,
             @ResolveInfoFlags int flags);
@@ -4411,32 +3965,13 @@
      * Retrieve all services that can match the given intent for a given user.
      *
      * @param intent The desired intent as per resolveService().
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_RESOLVED_FILTER},
-     *            {@link #GET_SHARED_LIBRARY_FILES}, {@link #MATCH_ALL},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DEFAULT_ONLY}, {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @param userId The user id.
      * @return Returns a List of ResolveInfo objects containing one entry for
      *         each matching service, ordered from best to worst. In other
      *         words, the first item is what would be returned by
      *         {@link #resolveService}. If there are no matching services, an
      *         empty list or null is returned.
-     * @see #GET_META_DATA
-     * @see #GET_RESOLVED_FILTER
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      * @hide
      */
     public abstract List<ResolveInfo> queryIntentServicesAsUser(Intent intent,
@@ -4447,30 +3982,11 @@
      *
      * @param intent An intent containing all of the desired specification
      *            (action, data, type, category, and/or component).
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_RESOLVED_FILTER},
-     *            {@link #GET_SHARED_LIBRARY_FILES}, {@link #MATCH_ALL},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DEFAULT_ONLY}, {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @param userId The user id.
      * @return Returns a List of ResolveInfo objects containing one entry for
      *         each matching provider, ordered from best to worst. If there are
      *         no matching services, an empty list or null is returned.
-     * @see #GET_META_DATA
-     * @see #GET_RESOLVED_FILTER
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      * @hide
      */
     public abstract List<ResolveInfo> queryIntentContentProvidersAsUser(
@@ -4481,29 +3997,10 @@
      *
      * @param intent An intent containing all of the desired specification
      *            (action, data, type, category, and/or component).
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_RESOLVED_FILTER},
-     *            {@link #GET_SHARED_LIBRARY_FILES}, {@link #MATCH_ALL},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DEFAULT_ONLY}, {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @return Returns a List of ResolveInfo objects containing one entry for
      *         each matching provider, ordered from best to worst. If there are
      *         no matching services, an empty list or null is returned.
-     * @see #GET_META_DATA
-     * @see #GET_RESOLVED_FILTER
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract List<ResolveInfo> queryIntentContentProviders(Intent intent,
             @ResolveInfoFlags int flags);
@@ -4512,28 +4009,9 @@
      * Find a single content provider by its base path name.
      *
      * @param name The name of the provider to find.
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_SHARED_LIBRARY_FILES},
-     *            {@link #MATCH_ALL}, {@link #MATCH_DEFAULT_ONLY},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @return A {@link ProviderInfo} object containing information about the
      *         provider. If a provider was not found, returns null.
-     * @see #GET_META_DATA
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DEBUG_TRIAGED_MISSING
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract ProviderInfo resolveContentProvider(String name,
             @ComponentInfoFlags int flags);
@@ -4542,29 +4020,10 @@
      * Find a single content provider by its base path name.
      *
      * @param name The name of the provider to find.
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_SHARED_LIBRARY_FILES},
-     *            {@link #MATCH_ALL}, {@link #MATCH_DEFAULT_ONLY},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @param userId The user id.
      * @return A {@link ProviderInfo} object containing information about the
      *         provider. If a provider was not found, returns null.
-     * @see #GET_META_DATA
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DEBUG_TRIAGED_MISSING
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      * @hide
      */
     public abstract ProviderInfo resolveContentProviderAsUser(String name,
@@ -4581,30 +4040,11 @@
      *            content providers are returned.
      * @param uid If <var>processName</var> is non-null, this is the required
      *            uid owning the requested content providers.
-     * @param flags Additional option flags. Use any combination of
-     *            {@link #GET_META_DATA}, {@link #GET_SHARED_LIBRARY_FILES},
-     *            {@link #MATCH_ALL}, {@link #MATCH_DEFAULT_ONLY},
-     *            {@link #MATCH_DISABLED_COMPONENTS},
-     *            {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *            {@link #MATCH_DIRECT_BOOT_AWARE},
-     *            {@link #MATCH_DIRECT_BOOT_UNAWARE}, {@link #MATCH_SYSTEM_ONLY}
-     *            or {@link #MATCH_UNINSTALLED_PACKAGES} to modify the data
-     *            returned.
+     * @param flags Additional option flags to modify the data returned.
      * @return A list of {@link ProviderInfo} objects containing one entry for
      *         each provider either matching <var>processName</var> or, if
      *         <var>processName</var> is null, all known content providers.
      *         <em>If there are no matching providers, null is returned.</em>
-     * @see #GET_META_DATA
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #MATCH_ALL
-     * @see #MATCH_DEBUG_TRIAGED_MISSING
-     * @see #MATCH_DEFAULT_ONLY
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_DIRECT_BOOT_AWARE
-     * @see #MATCH_DIRECT_BOOT_UNAWARE
-     * @see #MATCH_SYSTEM_ONLY
-     * @see #MATCH_UNINSTALLED_PACKAGES
      */
     public abstract List<ProviderInfo> queryContentProviders(
             String processName, int uid, @ComponentInfoFlags int flags);
@@ -4635,39 +4075,28 @@
      * instrumentation class.
      *
      * @param className The full name (i.e.
-     *                  com.google.apps.contacts.InstrumentList) of an
-     *                  Instrumentation class.
-     * @param flags Additional option flags. Use any combination of
-     *         {@link #GET_META_DATA}
-     *         to modify the data returned.
-     *
-     * @return An {@link InstrumentationInfo} object containing information about the
-     *         instrumentation.
+     *            com.google.apps.contacts.InstrumentList) of an Instrumentation
+     *            class.
+     * @param flags Additional option flags to modify the data returned.
+     * @return An {@link InstrumentationInfo} object containing information
+     *         about the instrumentation.
      * @throws NameNotFoundException if a package with the given name cannot be
      *             found on the system.
-     *
-     * @see #GET_META_DATA
      */
     public abstract InstrumentationInfo getInstrumentationInfo(ComponentName className,
             @InstrumentationInfoFlags int flags) throws NameNotFoundException;
 
     /**
-     * Retrieve information about available instrumentation code.  May be used
-     * to retrieve either all instrumentation code, or only the code targeting
-     * a particular package.
+     * Retrieve information about available instrumentation code. May be used to
+     * retrieve either all instrumentation code, or only the code targeting a
+     * particular package.
      *
      * @param targetPackage If null, all instrumentation is returned; only the
-     *                      instrumentation targeting this package name is
-     *                      returned.
-     * @param flags Additional option flags. Use any combination of
-     *         {@link #GET_META_DATA}
-     *         to modify the data returned.
-     *
+     *            instrumentation targeting this package name is returned.
+     * @param flags Additional option flags to modify the data returned.
      * @return A list of {@link InstrumentationInfo} objects containing one
      *         entry for each matching instrumentation. If there are no
      *         instrumentation available, returns an empty list.
-     *
-     * @see #GET_META_DATA
      */
     public abstract List<InstrumentationInfo> queryInstrumentation(String targetPackage,
             @InstrumentationInfoFlags int flags);
@@ -5091,43 +4520,13 @@
             @UserIdInt int userId) throws NameNotFoundException;
 
     /**
-     * Retrieve overall information about an application package defined
-     * in a package archive file
+     * Retrieve overall information about an application package defined in a
+     * package archive file
      *
      * @param archiveFilePath The path to the archive file
-     * @param flags Additional option flags. Use any combination of
-     *         {@link #GET_ACTIVITIES}, {@link #GET_CONFIGURATIONS},
-     *         {@link #GET_GIDS}, {@link #GET_INSTRUMENTATION},
-     *         {@link #GET_INTENT_FILTERS}, {@link #GET_META_DATA},
-     *         {@link #GET_PERMISSIONS}, {@link #GET_PROVIDERS},
-     *         {@link #GET_RECEIVERS}, {@link #GET_SERVICES},
-     *         {@link #GET_SHARED_LIBRARY_FILES}, {@link #GET_SIGNATURES},
-     *         {@link #GET_URI_PERMISSION_PATTERNS}, {@link #GET_UNINSTALLED_PACKAGES},
-     *         {@link #MATCH_DISABLED_COMPONENTS}, {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *         {@link #MATCH_UNINSTALLED_PACKAGES}
-     *         to modify the data returned.
-     *
-     * @return A PackageInfo object containing information about the
-     *         package archive. If the package could not be parsed,
-     *         returns null.
-     *
-     * @see #GET_ACTIVITIES
-     * @see #GET_CONFIGURATIONS
-     * @see #GET_GIDS
-     * @see #GET_INSTRUMENTATION
-     * @see #GET_INTENT_FILTERS
-     * @see #GET_META_DATA
-     * @see #GET_PERMISSIONS
-     * @see #GET_PROVIDERS
-     * @see #GET_RECEIVERS
-     * @see #GET_SERVICES
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #GET_SIGNATURES
-     * @see #GET_URI_PERMISSION_PATTERNS
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_UNINSTALLED_PACKAGES
-     *
+     * @param flags Additional option flags to modify the data returned.
+     * @return A PackageInfo object containing information about the package
+     *         archive. If the package could not be parsed, returns null.
      */
     public PackageInfo getPackageArchiveInfo(String archiveFilePath, @PackageInfoFlags int flags) {
         final PackageParser parser = new PackageParser();
@@ -5615,41 +5014,13 @@
     public abstract void removePackageFromPreferred(String packageName);
 
     /**
-     * Retrieve the list of all currently configured preferred packages.  The
-     * first package on the list is the most preferred, the last is the
-     * least preferred.
+     * Retrieve the list of all currently configured preferred packages. The
+     * first package on the list is the most preferred, the last is the least
+     * preferred.
      *
-     * @param flags Additional option flags. Use any combination of
-     *         {@link #GET_ACTIVITIES}, {@link #GET_CONFIGURATIONS},
-     *         {@link #GET_GIDS}, {@link #GET_INSTRUMENTATION},
-     *         {@link #GET_INTENT_FILTERS}, {@link #GET_META_DATA},
-     *         {@link #GET_PERMISSIONS}, {@link #GET_PROVIDERS},
-     *         {@link #GET_RECEIVERS}, {@link #GET_SERVICES},
-     *         {@link #GET_SHARED_LIBRARY_FILES}, {@link #GET_SIGNATURES},
-     *         {@link #GET_URI_PERMISSION_PATTERNS}, {@link #GET_UNINSTALLED_PACKAGES},
-     *         {@link #MATCH_DISABLED_COMPONENTS}, {@link #MATCH_DISABLED_UNTIL_USED_COMPONENTS},
-     *         {@link #MATCH_UNINSTALLED_PACKAGES}
-     *         to modify the data returned.
-     *
-     * @return A List of PackageInfo objects, one for each preferred application,
-     *         in order of preference.
-     *
-     * @see #GET_ACTIVITIES
-     * @see #GET_CONFIGURATIONS
-     * @see #GET_GIDS
-     * @see #GET_INSTRUMENTATION
-     * @see #GET_INTENT_FILTERS
-     * @see #GET_META_DATA
-     * @see #GET_PERMISSIONS
-     * @see #GET_PROVIDERS
-     * @see #GET_RECEIVERS
-     * @see #GET_SERVICES
-     * @see #GET_SHARED_LIBRARY_FILES
-     * @see #GET_SIGNATURES
-     * @see #GET_URI_PERMISSION_PATTERNS
-     * @see #MATCH_DISABLED_COMPONENTS
-     * @see #MATCH_DISABLED_UNTIL_USED_COMPONENTS
-     * @see #MATCH_UNINSTALLED_PACKAGES
+     * @param flags Additional option flags to modify the data returned.
+     * @return A List of PackageInfo objects, one for each preferred
+     *         application, in order of preference.
      */
     public abstract List<PackageInfo> getPreferredPackages(@PackageInfoFlags int flags);
 
@@ -5961,16 +5332,7 @@
      * determined by {@link #getInstallerPackageName(String)}.
      *
      * @param packageName the package to change the category hint for.
-     * @param categoryHint the category hint to set; one of
-     *            {@link ApplicationInfo#CATEGORY_AUDIO},
-     *            {@link ApplicationInfo#CATEGORY_GAME},
-     *            {@link ApplicationInfo#CATEGORY_IMAGE},
-     *            {@link ApplicationInfo#CATEGORY_MAPS},
-     *            {@link ApplicationInfo#CATEGORY_NEWS},
-     *            {@link ApplicationInfo#CATEGORY_PRODUCTIVITY},
-     *            {@link ApplicationInfo#CATEGORY_SOCIAL},
-     *            {@link ApplicationInfo#CATEGORY_UNDEFINED}, or
-     *            {@link ApplicationInfo#CATEGORY_VIDEO}.
+     * @param categoryHint the category hint to set.
      */
     public abstract void setApplicationCategoryHint(@NonNull String packageName,
             @ApplicationInfo.Category int categoryHint);
@@ -6265,23 +5627,14 @@
     }
 
     /**
-     * Return the install reason that was recorded when a package was first installed for a specific
-     * user. Requesting the install reason for another user will require the permission
-     * INTERACT_ACROSS_USERS_FULL.
+     * Return the install reason that was recorded when a package was first
+     * installed for a specific user. Requesting the install reason for another
+     * user will require the permission INTERACT_ACROSS_USERS_FULL.
      *
      * @param packageName The package for which to retrieve the install reason
      * @param user The user for whom to retrieve the install reason
-     *
-     * @return The install reason, currently one of {@code INSTALL_REASON_UNKNOWN} and
-     *         {@code INSTALL_REASON_POLICY}. If the package is not installed for the given user,
-     *         {@code INSTALL_REASON_UNKNOWN} is returned.
-     *
-     * @see #INSTALL_REASON_UNKNOWN
-     * @see #INSTALL_REASON_POLICY
-     * @see #INSTALL_REASON_DEVICE_RESTORE
-     * @see #INSTALL_REASON_DEVICE_SETUP
-     * @see #INSTALL_REASON_USER
-     *
+     * @return The install reason. If the package is not installed for the given
+     *         user, {@code INSTALL_REASON_UNKNOWN} is returned.
      * @hide
      */
     @TestApi
diff --git a/core/java/android/content/res/Resources.java b/core/java/android/content/res/Resources.java
index 408bee8..b559604 100644
--- a/core/java/android/content/res/Resources.java
+++ b/core/java/android/content/res/Resources.java
@@ -815,14 +815,7 @@
      */
     public Drawable getDrawable(@DrawableRes int id, @Nullable Theme theme)
             throws NotFoundException {
-        final TypedValue value = obtainTempTypedValue();
-        try {
-            final ResourcesImpl impl = mResourcesImpl;
-            impl.getValue(id, value, true);
-            return impl.loadDrawable(this, value, id, theme, true);
-        } finally {
-            releaseTempTypedValue(value);
-        }
+        return getDrawableForDensity(id, 0, theme);
     }
 
     /**
@@ -844,7 +837,9 @@
      *            This integer encodes the package, type, and resource entry.
      *            The value 0 is an invalid identifier.
      * @param density the desired screen density indicated by the resource as
-     *            found in {@link DisplayMetrics}.
+     *            found in {@link DisplayMetrics}. A value of 0 means to use the
+     *            density returned from {@link #getConfiguration()}.
+     *            This is equivalent to calling {@link #getDrawable(int)}.
      * @return Drawable An object that can be used to draw this resource.
      * @throws NotFoundException Throws NotFoundException if the given ID does
      *             not exist.
@@ -865,7 +860,9 @@
      *            This integer encodes the package, type, and resource entry.
      *            The value 0 is an invalid identifier.
      * @param density The desired screen density indicated by the resource as
-     *            found in {@link DisplayMetrics}.
+     *            found in {@link DisplayMetrics}. A value of 0 means to use the
+     *            density returned from {@link #getConfiguration()}.
+     *            This is equivalent to calling {@link #getDrawable(int, Theme)}.
      * @param theme The theme used to style the drawable attributes, may be {@code null}.
      * @return Drawable An object that can be used to draw this resource.
      * @throws NotFoundException Throws NotFoundException if the given ID does
@@ -876,37 +873,16 @@
         try {
             final ResourcesImpl impl = mResourcesImpl;
             impl.getValueForDensity(id, density, value, true);
-
-            // If the drawable's XML lives in our current density qualifier,
-            // it's okay to use a scaled version from the cache. Otherwise, we
-            // need to actually load the drawable from XML.
-            final DisplayMetrics metrics = impl.getDisplayMetrics();
-            final boolean useCache = value.density == metrics.densityDpi;
-
-            /*
-             * Pretend the requested density is actually the display density. If
-             * the drawable returned is not the requested density, then force it
-             * to be scaled later by dividing its density by the ratio of
-             * requested density to actual device density. Drawables that have
-             * undefined density or no density don't need to be handled here.
-             */
-            if (value.density > 0 && value.density != TypedValue.DENSITY_NONE) {
-                if (value.density == density) {
-                    value.density = metrics.densityDpi;
-                } else {
-                    value.density = (value.density * metrics.densityDpi) / density;
-                }
-            }
-            return impl.loadDrawable(this, value, id, theme, useCache);
+            return impl.loadDrawable(this, value, id, density, theme);
         } finally {
             releaseTempTypedValue(value);
         }
     }
 
     @NonNull
-    Drawable loadDrawable(@NonNull TypedValue value, int id, @Nullable Theme theme)
+    Drawable loadDrawable(@NonNull TypedValue value, int id, int density, @Nullable Theme theme)
             throws NotFoundException {
-        return mResourcesImpl.loadDrawable(this, value, id, theme, true);
+        return mResourcesImpl.loadDrawable(this, value, id, density, theme);
     }
 
     /**
@@ -1221,8 +1197,7 @@
      * used to open drawable, sound, and raw resources; it will fail on string
      * and color resources.
      * 
-     * @param id The resource identifier to open, as generated by the appt
-     *           tool.
+     * @param id The resource identifier to open, as generated by the aapt tool.
      * 
      * @return InputStream Access to the resource data.
      *
@@ -1278,7 +1253,7 @@
      * used to open drawable, sound, and raw resources; it will fail on string
      * and color resources.
      *
-     * @param id The resource identifier to open, as generated by the appt tool.
+     * @param id The resource identifier to open, as generated by the aapt tool.
      * @param value The TypedValue object to hold the resource information.
      *
      * @return InputStream Access to the resource data.
@@ -1300,8 +1275,7 @@
      * as uncompressed data, which typically includes things like mp3 files
      * and png images.
      * 
-     * @param id The resource identifier to open, as generated by the appt
-     *           tool.
+     * @param id The resource identifier to open, as generated by the aapt tool.
      * 
      * @return AssetFileDescriptor A new file descriptor you can use to read
      * the resource.  This includes the file descriptor itself, as well as the
diff --git a/core/java/android/content/res/ResourcesImpl.java b/core/java/android/content/res/ResourcesImpl.java
index f9acab9..02ddc89 100644
--- a/core/java/android/content/res/ResourcesImpl.java
+++ b/core/java/android/content/res/ResourcesImpl.java
@@ -523,8 +523,27 @@
     }
 
     @Nullable
-    Drawable loadDrawable(Resources wrapper, TypedValue value, int id, Resources.Theme theme,
-            boolean useCache) throws NotFoundException {
+    Drawable loadDrawable(@NonNull Resources wrapper, @NonNull TypedValue value, int id,
+            int density, @Nullable Resources.Theme theme)
+            throws NotFoundException {
+        // If the drawable's XML lives in our current density qualifier,
+        // it's okay to use a scaled version from the cache. Otherwise, we
+        // need to actually load the drawable from XML.
+        final boolean useCache = density == 0 || value.density == mMetrics.densityDpi;
+
+        // Pretend the requested density is actually the display density. If
+        // the drawable returned is not the requested density, then force it
+        // to be scaled later by dividing its density by the ratio of
+        // requested density to actual device density. Drawables that have
+        // undefined density or no density don't need to be handled here.
+        if (density > 0 && value.density > 0 && value.density != TypedValue.DENSITY_NONE) {
+            if (value.density == density) {
+                value.density = mMetrics.densityDpi;
+            } else {
+                value.density = (value.density * mMetrics.densityDpi) / density;
+            }
+        }
+
         try {
             if (TRACE_FOR_PRELOAD) {
                 // Log only framework resources
@@ -576,7 +595,7 @@
             } else if (isColorDrawable) {
                 dr = new ColorDrawable(value.data);
             } else {
-                dr = loadDrawableForCookie(wrapper, value, id, null);
+                dr = loadDrawableForCookie(wrapper, value, id, density, null);
             }
 
             // Determine if the drawable has unresolved theme attributes. If it
@@ -691,8 +710,8 @@
     /**
      * Loads a drawable from XML or resources stream.
      */
-    private Drawable loadDrawableForCookie(Resources wrapper, TypedValue value, int id,
-            Resources.Theme theme) {
+    private Drawable loadDrawableForCookie(@NonNull Resources wrapper, @NonNull TypedValue value,
+            int id, int density, @Nullable Resources.Theme theme) {
         if (value.string == null) {
             throw new NotFoundException("Resource \"" + getResourceName(id) + "\" ("
                     + Integer.toHexString(id) + ") is not a Drawable (color or path): " + value);
@@ -722,7 +741,7 @@
             if (file.endsWith(".xml")) {
                 final XmlResourceParser rp = loadXmlResourceParser(
                         file, id, value.assetCookie, "drawable");
-                dr = Drawable.createFromXml(wrapper, rp, theme);
+                dr = Drawable.createFromXmlForDensity(wrapper, rp, density, theme);
                 rp.close();
             } else {
                 final InputStream is = mAssets.openNonAsset(
diff --git a/core/java/android/content/res/TypedArray.java b/core/java/android/content/res/TypedArray.java
index 88bb1a4..0b0f048 100644
--- a/core/java/android/content/res/TypedArray.java
+++ b/core/java/android/content/res/TypedArray.java
@@ -923,6 +923,15 @@
      */
     @Nullable
     public Drawable getDrawable(@StyleableRes int index) {
+        return getDrawableForDensity(index, 0);
+    }
+
+    /**
+     * Version of {@link #getDrawable(int)} that accepts an override density.
+     * @hide
+     */
+    @Nullable
+    public Drawable getDrawableForDensity(@StyleableRes int index, int density) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -933,7 +942,13 @@
                 throw new UnsupportedOperationException(
                         "Failed to resolve attribute at index " + index + ": " + value);
             }
-            return mResources.loadDrawable(value, value.resourceId, mTheme);
+
+            if (density > 0) {
+                // If the density is overridden, the value in the TypedArray will not reflect this.
+                // Do a separate lookup of the resourceId with the density override.
+                mResources.getValueForDensity(value.resourceId, density, value, true);
+            }
+            return mResources.loadDrawable(value, value.resourceId, density, mTheme);
         }
         return null;
     }
diff --git a/core/java/android/hardware/HardwareBuffer.java b/core/java/android/hardware/HardwareBuffer.java
index 7b09e26..9d217d3 100644
--- a/core/java/android/hardware/HardwareBuffer.java
+++ b/core/java/android/hardware/HardwareBuffer.java
@@ -22,6 +22,7 @@
 import android.os.Parcelable;
 
 import dalvik.annotation.optimization.FastNative;
+import dalvik.system.CloseGuard;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -37,7 +38,7 @@
  *
  * For more information, see the NDK documentation for <code>AHardwareBuffer</code>.
  */
-public final class HardwareBuffer implements Parcelable {
+public final class HardwareBuffer implements Parcelable, AutoCloseable {
     /** @hide */
     @Retention(RetentionPolicy.SOURCE)
     @IntDef({RGBA_8888, RGBA_FP16, RGBA_1010102, RGBX_8888, RGB_888, RGB_565, BLOB})
@@ -65,6 +66,8 @@
     // Invoked on destruction
     private Runnable mCleaner;
 
+    private final CloseGuard mCloseGuard = CloseGuard.get();
+
     /** @hide */
     @Retention(RetentionPolicy.SOURCE)
     @IntDef(flag = true, value = {USAGE0_CPU_READ, USAGE0_CPU_READ_OFTEN, USAGE0_CPU_WRITE,
@@ -163,14 +166,25 @@
         NativeAllocationRegistry registry = new NativeAllocationRegistry(
                 loader, nGetNativeFinalizer(), NATIVE_HARDWARE_BUFFER_SIZE);
         mCleaner = registry.registerNativeAllocation(this, mNativeObject);
+        mCloseGuard.open("close");
+    }
+
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            mCloseGuard.warnIfOpen();
+            close();
+        } finally {
+            super.finalize();
+        }
     }
 
     /**
      * Returns the width of this buffer in pixels.
      */
     public int getWidth() {
-        if (mNativeObject == 0) {
-            throw new IllegalStateException("This HardwareBuffer has been destroyed and its width "
+        if (isClosed()) {
+            throw new IllegalStateException("This HardwareBuffer has been closed and its width "
                     + "cannot be obtained.");
         }
         return nGetWidth(mNativeObject);
@@ -180,8 +194,8 @@
      * Returns the height of this buffer in pixels.
      */
     public int getHeight() {
-        if (mNativeObject == 0) {
-            throw new IllegalStateException("This HardwareBuffer has been destroyed and its height "
+        if (isClosed()) {
+            throw new IllegalStateException("This HardwareBuffer has been closed and its height "
                     + "cannot be obtained.");
         }
         return nGetHeight(mNativeObject);
@@ -193,8 +207,8 @@
      */
     @Format
     public int getFormat() {
-        if (mNativeObject == 0) {
-            throw new IllegalStateException("This HardwareBuffer has been destroyed and its format "
+        if (isClosed()) {
+            throw new IllegalStateException("This HardwareBuffer has been closed and its format "
                     + "cannot be obtained.");
         }
         return nGetFormat(mNativeObject);
@@ -204,8 +218,8 @@
      * Returns the number of layers in this buffer.
      */
     public int getLayers() {
-        if (mNativeObject == 0) {
-            throw new IllegalStateException("This HardwareBuffer has been destroyed and its layer "
+        if (isClosed()) {
+            throw new IllegalStateException("This HardwareBuffer has been closed and its layer "
                     + "count cannot be obtained.");
         }
         return nGetLayers(mNativeObject);
@@ -215,22 +229,36 @@
      * Returns the usage flags of the usage hints set on this buffer.
      */
     public long getUsage() {
-        if (mNativeObject == 0) {
-            throw new IllegalStateException("This HardwareBuffer has been destroyed and its usage "
+        if (isClosed()) {
+            throw new IllegalStateException("This HardwareBuffer has been closed and its usage "
                     + "cannot be obtained.");
         }
         return nGetUsage(mNativeObject);
     }
 
+    /** @removed replaced by {@link #close()} */
+    @Deprecated
+    public void destroy() {
+        close();
+    }
+
+    /** @removed replaced by {@link #isClosed()} */
+    @Deprecated
+    public boolean isDestroyed() {
+        return isClosed();
+    }
+
     /**
      * Destroys this buffer immediately. Calling this method frees up any
      * underlying native resources. After calling this method, this buffer
      * must not be used in any way.
      *
-     * @see #isDestroyed()
+     * @see #isClosed()
      */
-    public void destroy() {
-        if (mNativeObject != 0) {
+    @Override
+    public void close() {
+        if (!isClosed()) {
+            mCloseGuard.close();
             mNativeObject = 0;
             mCleaner.run();
             mCleaner = null;
@@ -238,15 +266,15 @@
     }
 
     /**
-     * Indicates whether this buffer has been destroyed. A destroyed buffer
-     * cannot be used in any way: the buffer cannot be written to a parcel, etc.
+     * Indicates whether this buffer has been closed. A closed buffer cannot
+     * be used in any way: the buffer cannot be written to a parcel, etc.
      *
-     * @return True if this <code>HardwareBuffer</code> is in a destroyed state,
+     * @return True if this <code>HardwareBuffer</code> is in a closed state,
      *         false otherwise.
      *
-     * @see #destroy()
+     * @see #close()
      */
-    public boolean isDestroyed() {
+    public boolean isClosed() {
         return mNativeObject == 0;
     }
 
@@ -259,7 +287,7 @@
      * Flatten this object in to a Parcel.
      *
      * <p>Calling this method will throw an <code>IllegalStateException</code> if
-     * {@link #destroy()} has been previously called.</p>
+     * {@link #close()} has been previously called.</p>
      *
      * @param dest The Parcel in which the object should be written.
      * @param flags Additional flags about how the object should be written.
@@ -267,8 +295,8 @@
      */
     @Override
     public void writeToParcel(Parcel dest, int flags) {
-        if (mNativeObject == 0) {
-            throw new IllegalStateException("This HardwareBuffer has been destroyed and cannot be "
+        if (isClosed()) {
+            throw new IllegalStateException("This HardwareBuffer has been closed and cannot be "
                     + "written to a parcel.");
         }
         nWriteHardwareBufferToParcel(mNativeObject, dest);
diff --git a/core/java/android/os/Build.java b/core/java/android/os/Build.java
index 0610499..86fcfc8 100644
--- a/core/java/android/os/Build.java
+++ b/core/java/android/os/Build.java
@@ -115,8 +115,7 @@
     public static final String SERIAL = getString("no.such.thing");
 
     /**
-     * Gets the hardware serial, if available. Requires holding the {@link
-     * android.Manifest.permission#READ_PHONE_STATE} permission.
+     * Gets the hardware serial, if available.
      * @return The serial if specified.
      */
     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
diff --git a/core/java/android/os/storage/StorageManager.java b/core/java/android/os/storage/StorageManager.java
index 1c15004..baa29b0 100644
--- a/core/java/android/os/storage/StorageManager.java
+++ b/core/java/android/os/storage/StorageManager.java
@@ -730,7 +730,7 @@
      */
     public @NonNull UUID getUuidForPath(@NonNull File path) throws IOException {
         Preconditions.checkNotNull(path);
-        final String pathString = path.getAbsolutePath();
+        final String pathString = path.getCanonicalPath();
         if (FileUtils.contains(Environment.getDataDirectory().getAbsolutePath(), pathString)) {
             return UUID_DEFAULT;
         }
diff --git a/core/java/android/provider/FontsContract.java b/core/java/android/provider/FontsContract.java
index 3fa92b8..068628a 100644
--- a/core/java/android/provider/FontsContract.java
+++ b/core/java/android/provider/FontsContract.java
@@ -44,6 +44,7 @@
 import android.os.Process;
 import android.os.ResultReceiver;
 import android.util.Log;
+import android.util.LruCache;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
@@ -181,6 +182,8 @@
     @GuardedBy("mLock")
     private HandlerThread mThread;
 
+    private static final LruCache<String, Typeface> sTypefaceCache = new LruCache<>(16);
+
     /** @hide */
     public FontsContract(Context context) {
         mContext = context.getApplicationContext();
@@ -476,6 +479,11 @@
      * therefore the result is delivered to the given callback. See {@link FontRequest}.
      * Only one of the methods in callback will be invoked, depending on whether the request
      * succeeds or fails. These calls will happen on the caller thread.
+     *
+     * Note that the result Typeface may be cached internally and the same instance will be returned
+     * the next time you call this method with the same request. If you want to bypass this cache,
+     * use {@link #fetchFonts} and {@link #buildTypeface} instead.
+     *
      * @param context A context to be used for fetching from font provider.
      * @param request A {@link FontRequest} object that identifies the provider and query for the
      *                request. May not be null.
@@ -486,8 +494,13 @@
             @NonNull FontRequestCallback callback, @NonNull Handler handler) {
 
         final Handler callerThreadHandler = new Handler();
+        final Typeface cachedTypeface = sTypefaceCache.get(request.getIdentifier());
+        if (cachedTypeface != null) {
+            callerThreadHandler.post(() -> callback.onTypefaceRetrieved(cachedTypeface));
+            return;
+        }
+
         handler.post(() -> {
-            // TODO: Cache the result.
             FontFamilyResult result;
             try {
                 result = fetchFonts(context, null /* cancellation signal */, request);
@@ -497,6 +510,13 @@
                 return;
             }
 
+            // Same request might be dispatched during fetchFonts. Check the cache again.
+            final Typeface anotherCachedTypeface = sTypefaceCache.get(request.getIdentifier());
+            if (anotherCachedTypeface != null) {
+                callerThreadHandler.post(() -> callback.onTypefaceRetrieved(anotherCachedTypeface));
+                return;
+            }
+
             if (result.getStatusCode() != FontFamilyResult.STATUS_OK) {
                 switch (result.getStatusCode()) {
                     case FontFamilyResult.STATUS_WRONG_CERTIFICATES:
@@ -547,6 +567,7 @@
                 return;
             }
 
+            sTypefaceCache.put(request.getIdentifier(), typeface);
             callerThreadHandler.post(() -> callback.onTypefaceRetrieved(typeface));
         });
     }
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index f9d81da..0884480 100755
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -303,7 +303,7 @@
      */
     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
     public static final String ACTION_MANAGE_UNKNOWN_APP_SOURCES =
-            "android.settings.action.MANAGE_UNKNOWN_APP_SOURCES";
+            "android.settings.MANAGE_UNKNOWN_APP_SOURCES";
 
     /**
      * Activity Action: Show trusted credentials settings, opening to the user tab,
diff --git a/core/java/android/service/autofill/SaveInfo.java b/core/java/android/service/autofill/SaveInfo.java
index f796444..3a1529f 100644
--- a/core/java/android/service/autofill/SaveInfo.java
+++ b/core/java/android/service/autofill/SaveInfo.java
@@ -21,9 +21,7 @@
 import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.app.assist.AssistStructure;
 import android.content.IntentSender;
-import android.os.Bundle;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.util.DebugUtils;
@@ -154,7 +152,7 @@
     @interface SaveDataType{}
 
     /**
-     * Usually {@link AutofillService#onSaveRequest(AssistStructure, Bundle, SaveCallback)}
+     * Usually {@link AutofillService#onSaveRequest(SaveRequest, SaveCallback)}
      * is called once the activity finishes. If this flag is set it is called once all saved views
      * become invisible.
      */
@@ -228,8 +226,7 @@
         private final @SaveDataType int mType;
         private CharSequence mNegativeActionTitle;
         private IntentSender mNegativeActionListener;
-        // TODO(b/33197203): make mRequiredIds final once addSavableIds() is gone
-        private AutofillId[] mRequiredIds;
+        private final AutofillId[] mRequiredIds;
         private AutofillId[] mOptionalIds;
         private CharSequence mDescription;
         private boolean mDestroyed;
@@ -251,37 +248,13 @@
          * @throws IllegalArgumentException if {@code requiredIds} is {@code null} or empty.
          */
         public Builder(@SaveDataType int type, @NonNull AutofillId[] requiredIds) {
-            if (false) {// TODO(b/33197203): re-move when clients use it
             Preconditions.checkArgument(requiredIds != null && requiredIds.length > 0,
                     "must have at least one required id: " + Arrays.toString(requiredIds));
-            }
             mType = type;
             mRequiredIds = requiredIds;
         }
 
         /**
-         * @hide
-         * @deprecated
-         * // TODO(b/33197203): make sure is removed when clients migrated
-         */
-        @Deprecated
-        public Builder(@SaveDataType int type) {
-            this(type, null);
-        }
-
-        /**
-         * @hide
-         * @deprecated
-         * // TODO(b/33197203): make sure is removed when clients migrated
-         */
-        @Deprecated
-        public @NonNull Builder addSavableIds(@Nullable AutofillId... ids) {
-            throwIfDestroyed();
-            mRequiredIds = ids;
-            return this;
-        }
-
-        /**
          * Set flags changing the save behavior.
          *
          * @param flags {@link #FLAG_SAVE_ON_ALL_VIEWS_INVISIBLE} or 0.
diff --git a/core/java/android/widget/ImageView.java b/core/java/android/widget/ImageView.java
index 7e6f2e4..57818e2 100644
--- a/core/java/android/widget/ImageView.java
+++ b/core/java/android/widget/ImageView.java
@@ -55,11 +55,31 @@
 import java.io.InputStream;
 
 /**
- * Displays an arbitrary image, such as an icon.  The ImageView class
- * can load images from various sources (such as resources or content
- * providers), takes care of computing its measurement from the image so that
- * it can be used in any layout manager, and provides various display options
- * such as scaling and tinting.
+ * Displays image resources, for example {@link android.graphics.Bitmap}
+ * or {@link android.graphics.drawable.Drawable} resources.
+ * ImageView is also commonly used to {@link #setImageTintMode(PorterDuff.Mode)
+ * apply tints to an image} and handle {@link #setScaleType(ScaleType) image scaling}.
+ *
+ * <p>
+ * The following XML snippet is a common example of using an ImageView to display an image resource:
+ * </p>
+ * <pre>
+ * &lt;LinearLayout
+ *     xmlns:android="http://schemas.android.com/apk/res/android"
+ *     android:layout_width="match_parent"
+ *     android:layout_height="match_parent"&gt;
+ *     &lt;ImageView
+ *         android:layout_width="wrap_content"
+ *         android:layout_height="wrap_content"
+ *         android:src="@mipmap/ic_launcher"
+ *         /&gt;
+ * &lt;/LinearLayout&gt;
+ * </pre>
+ *
+ * <p>
+ * To learn more about Drawables, see: <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.
+ * To learn more about working with Bitmaps, see: <a href="{@docRoot}topic/performance/graphics/index.htm">Handling Bitmaps</a>.
+ * </p>
  *
  * @attr ref android.R.styleable#ImageView_adjustViewBounds
  * @attr ref android.R.styleable#ImageView_src
@@ -395,9 +415,13 @@
         mMaxHeight = maxHeight;
     }
 
-    /** Return the view's drawable, or null if no drawable has been
-        assigned.
-    */
+    /**
+     * Gets the current Drawable, or null if no Drawable has been
+     * assigned.
+     *
+     * @return the view's drawable, or null if no drawable has been
+     * assigned.
+     */
     public Drawable getDrawable() {
         if (mDrawable == mRecycleableBitmapDrawable) {
             // Consider our cached version dirty since app code now has a reference to it
@@ -428,7 +452,6 @@
 
     /**
      * Sets a drawable as the content of this ImageView.
-     *
      * <p class="note">This does Bitmap reading and decoding on the UI
      * thread, which can cause a latency hiccup.  If that's a concern,
      * consider using {@link #setImageDrawable(android.graphics.drawable.Drawable)} or
@@ -474,7 +497,10 @@
 
     /**
      * Sets the content of this ImageView to the specified Uri.
-     *
+     * Note that you use this method to load images from a local Uri only.
+     * <p/>
+     * To learn how to display images from a remote Uri see: <a href="https://developer.android.com/topic/performance/graphics/index.html">Handling Bitmaps</a>
+     * <p/>
      * <p class="note">This does Bitmap reading and decoding on the UI
      * thread, which can cause a latency hiccup.  If that's a concern,
      * consider using {@link #setImageDrawable(Drawable)} or
@@ -598,6 +624,9 @@
     }
 
     /**
+     * Get the current {@link android.content.res.ColorStateList} used to tint the image Drawable,
+     * or null if no tint is applied.
+     *
      * @return the tint applied to the image drawable
      * @attr ref android.R.styleable#ImageView_tint
      * @see #setImageTintList(ColorStateList)
@@ -626,7 +655,8 @@
     }
 
     /**
-     * @return the blending mode used to apply the tint to the image drawable
+     * Gets the blending mode used to apply the tint to the image Drawable
+     * @return the blending mode used to apply the tint to the image Drawable
      * @attr ref android.R.styleable#ImageView_tintMode
      * @see #setImageTintMode(PorterDuff.Mode)
      */
@@ -673,6 +703,13 @@
         setImageDrawable(mRecycleableBitmapDrawable);
     }
 
+    /**
+     * Set the state of the current {@link android.graphics.drawable.StateListDrawable}.
+     * For more information about State List Drawables, see: <a href="https://developer.android.com/guide/topics/resources/drawable-resource.html#StateList">the Drawable Resource Guide</a>.
+     *
+     * @param state the state to set for the StateListDrawable
+     * @param merge if true, merges the state values for the state you specify into the current state
+     */
     public void setImageState(int[] state, boolean merge) {
         mState = state;
         mMergeState = merge;
@@ -786,17 +823,16 @@
     }
 
     /**
-     * Return the current scale type in use by this ImageView.
-     *
+     * Returns the current ScaleType that is used to scale the bounds of an image to the bounds of the ImageView.
+     * @return The ScaleType used to scale the image.
      * @see ImageView.ScaleType
-     *
      * @attr ref android.R.styleable#ImageView_scaleType
      */
     public ScaleType getScaleType() {
         return mScaleType;
     }
 
-    /** Return the view's optional matrix. This is applied to the
+    /** Returns the view's optional matrix. This is applied to the
         view's drawable when it is drawn. If there is no matrix,
         this method will return an identity matrix.
         Do not change this matrix in place but make a copy.
@@ -815,7 +851,7 @@
      * to the view's drawable when it is drawn.  Allows custom scaling,
      * translation, and perspective distortion.
      *
-     * @param matrix the transformation parameters in matrix form
+     * @param matrix The transformation parameters in matrix form.
      */
     public void setImageMatrix(Matrix matrix) {
         // collapse null and identity to just null
@@ -1367,11 +1403,10 @@
     }
 
     /**
-     * Set whether to set the baseline of this view to the bottom of the view.
+     * Sets whether the baseline of this view to the bottom of the view.
      * Setting this value overrides any calls to setBaseline.
      *
-     * @param aligned If true, the image view will be baseline aligned with
-     *      based on its bottom edge.
+     * @param aligned If true, the image view will be baseline aligned by its bottom edge.
      *
      * @attr ref android.R.styleable#ImageView_baselineAlignBottom
      */
@@ -1383,8 +1418,9 @@
     }
 
     /**
-     * Return whether this view's baseline will be considered the bottom of the view.
+     * Checks whether this view's baseline is considered the bottom of the view.
      *
+     * @return True if the ImageView's baseline is considered the bottom of the view, false if otherwise.
      * @see #setBaselineAlignBottom(boolean)
      */
     public boolean getBaselineAlignBottom() {
@@ -1392,7 +1428,7 @@
     }
 
     /**
-     * Set a tinting option for the image.
+     * Sets a tinting option for the image.
      *
      * @param color Color tint to apply.
      * @param mode How to apply the color.  The standard mode is
@@ -1416,6 +1452,12 @@
         setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
     }
 
+    /**
+     * Removes the image's {@link android.graphics.ColorFilter}.
+     *
+     * @see #setColorFilter(int)
+     * @see #getColorFilter()
+     */
     public final void clearColorFilter() {
         setColorFilter(null);
     }
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 16a31f1..f42d6c8 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -178,18 +178,43 @@
 import java.util.Locale;
 
 /**
- * Displays text to the user and optionally allows them to edit it.  A TextView
- * is a complete text editor, however the basic class is configured to not
- * allow editing; see {@link EditText} for a subclass that configures the text
- * view for editing.
- *
+ * A user interface element that displays text to the user.
+ * To provide user-editable text, see {@link EditText}.
  * <p>
- * To allow users to copy some or all of the TextView's value and paste it somewhere else, set the
- * XML attribute {@link android.R.styleable#TextView_textIsSelectable
- * android:textIsSelectable} to "true" or call
- * {@link #setTextIsSelectable setTextIsSelectable(true)}. The {@code textIsSelectable} flag
- * allows users to make selection gestures in the TextView, which in turn triggers the system's
- * built-in copy/paste controls.
+ * The following code sample shows a typical use, with an XML layout
+ * and code to modify the contents of the text view:
+ * </p>
+
+ * <pre>
+ * &lt;LinearLayout
+       xmlns:android="http://schemas.android.com/apk/res/android"
+       android:layout_width="match_parent"
+       android:layout_height="match_parent"&gt;
+ *    &lt;TextView
+ *        android:id="@+id/text_view_id"
+ *        android:layout_height="wrap_content"
+ *        android:layout_width="wrap_content"
+ *        android:text="@string/hello" /&gt;
+ * &lt;/LinearLayout&gt;
+ * </pre>
+ * <p>
+ * This code sample demonstrates how to modify the contents of the text view
+ * defined in the previous XML layout:
+ * </p>
+ * <pre>
+ * public class MainActivity extends Activity {
+ *
+ *    protected void onCreate(Bundle savedInstanceState) {
+ *         super.onCreate(savedInstanceState);
+ *         setContentView(R.layout.activity_main);
+ *         final TextView helloTextView = (TextView) findViewById(R.id.text_view_id);
+ *         helloTextView.setText(R.string.user_greeting);
+ *     }
+ * }
+ * </pre>
+ * <p>
+ * To customize the appearance of TextView, see <a href="https://developer.android.com/guide/topics/ui/themes.html">Styles and Themes</a>.
+ * </p>
  * <p>
  * <b>XML attributes</b>
  * <p>
@@ -674,7 +699,7 @@
     int mTextEditSuggestionHighlightStyle;
 
     /**
-     * EditText specific data, created on demand when one of the Editor fields is used.
+     * {@link EditText} specific data, created on demand when one of the Editor fields is used.
      * See {@link #createEditorIfNeeded()}.
      */
     private Editor mEditor;
@@ -1346,6 +1371,9 @@
                         autoSizePresetTextSizes.recycle();
                     }
                     break;
+                case com.android.internal.R.styleable.TextView_justificationMode:
+                    mJustificationMode = a.getInt(attr, Layout.JUSTIFICATION_MODE_NONE);
+                    break;
             }
         }
 
@@ -2172,10 +2200,11 @@
      * with an argument of {@link android.widget.TextView.BufferType#SPANNABLE BufferType.SPANNABLE}
      * or {@link android.widget.TextView.BufferType#EDITABLE BufferType.EDITABLE}, you can cast
      * the return value from this method to Spannable or Editable, respectively.
-     * <p/>
-     * The content of the return value should not be modified. If you want a modifiable one, you
-     * should make your own copy first.
      *
+     * <p>The content of the return value should not be modified. If you want a modifiable one, you
+     * should make your own copy first.</p>
+     *
+     * @return The text displayed by the text view.
      * @attr ref android.R.styleable#TextView_text
      */
     @ViewDebug.CapturedViewProperty
@@ -2185,6 +2214,7 @@
 
     /**
      * Returns the length, in characters, of the text managed by this TextView
+     * @return The length of the text managed by the TextView in characters.
      */
     public int length() {
         return mText.length();
@@ -2201,26 +2231,28 @@
     }
 
     /**
-     * @return the height of one standard line in pixels.  Note that markup
-     * within the text can cause individual lines to be taller or shorter
-     * than this height, and the layout may contain additional first-
-     * or last-line padding.
+     * Gets the vertical distance between lines of text, in pixels.
+     * Note that markup within the text can cause individual lines
+     * to be taller or shorter than this height, and the layout may
+     * contain additional first-or last-line padding.
+     * @return The height of one standard line in pixels.
      */
     public int getLineHeight() {
         return FastMath.round(mTextPaint.getFontMetricsInt(null) * mSpacingMult + mSpacingAdd);
     }
 
     /**
-     * @return the Layout that is currently being used to display the text.
-     * This can be null if the text or width has recently changes.
+     * Gets the {@link android.text.Layout} that is currently being used to display the text.
+     * This value can be null if the text or width has recently changed.
+     * @return The Layout that is currently being used to display the text.
      */
     public final Layout getLayout() {
         return mLayout;
     }
 
     /**
-     * @return the Layout that is currently being used to display the hint text.
-     * This can be null.
+     * @return the {@link android.text.Layout} that is currently being used to
+     * display the hint text. This can be null.
      */
     final Layout getHintLayout() {
         return mHintLayout;
@@ -2272,8 +2304,9 @@
     }
 
     /**
-     * @return the current key listener for this TextView.
+     * Gets the current {@link KeyListener} for the TextView.
      * This will frequently be null for non-EditText TextViews.
+     * @return the current key listener for this TextView.
      *
      * @attr ref android.R.styleable#TextView_numeric
      * @attr ref android.R.styleable#TextView_digits
@@ -2350,17 +2383,20 @@
     }
 
     /**
-     * @return the movement method being used for this TextView.
+     * Gets the {@link android.text.method.MovementMethod} being used for this TextView,
+     * which provides positioning, scrolling, and text selection functionality.
      * This will frequently be null for non-EditText TextViews.
+     * @return the movement method being used for this TextView.
+     * @see android.text.method.MovementMethod
      */
     public final MovementMethod getMovementMethod() {
         return mMovement;
     }
 
     /**
-     * Sets the movement method (arrow key handler) to be used for
-     * this TextView.  This can be null to disallow using the arrow keys
-     * to move the cursor or scroll the view.
+     * Sets the {@link android.text.method.MovementMethod} for handling arrow key movement
+     * for this TextView. This can be null to disallow using the arrow keys to move the
+     * cursor or scroll the view.
      * <p>
      * Be warned that if you want a TextView with a key listener or movement
      * method not to be focusable, or if you want a TextView without a
@@ -2397,9 +2433,9 @@
     }
 
     /**
+     * Gets the current {@link android.text.method.TransformationMethod} for the TextView.
+     * This is frequently null, except for single-line and password fields.
      * @return the current transformation method for this TextView.
-     * This will frequently be null except for single-line and password
-     * fields.
      *
      * @attr ref android.R.styleable#TextView_password
      * @attr ref android.R.styleable#TextView_singleLine
@@ -3432,8 +3468,8 @@
     }
 
     /**
-     * Set the default {@link LocaleList} of the text in this TextView to a one-member list
-     * containing just the given value.
+     * Set the default {@link Locale} of the text in this TextView to a one-member
+     * {@link LocaleList} containing just the given Locale.
      *
      * @param locale the {@link Locale} for drawing text, must not be null.
      *
@@ -3492,7 +3528,7 @@
     }
 
     /**
-     * @return the size (in scaled pixels) of thee default text size in this TextView.
+     * @return the size (in scaled pixels) of the default text size in this TextView.
      * @hide
      */
     @ViewDebug.ExportedProperty(category = "text")
@@ -3574,16 +3610,19 @@
     }
 
     /**
-     * @return the extent by which text is currently being stretched
-     * horizontally.  This will usually be 1.
+     * Gets the extent by which text should be stretched horizontally.
+     * This will usually be 1.0.
+     * @return The horizontal scale factor.
      */
     public float getTextScaleX() {
         return mTextPaint.getTextScaleX();
     }
 
     /**
-     * Sets the extent by which text should be stretched horizontally.
-     *
+     * Sets the horizontal scale factor for text. The default value
+     * is 1.0. Values greater than 1.0 stretch the text wider.
+     * Values less than 1.0 make the text narrower. By default, this value is 1.0.
+     * @param size The horizontal scale factor.
      * @attr ref android.R.styleable#TextView_textScaleX
      */
     @android.view.RemotableViewMethod
@@ -3626,8 +3665,8 @@
     }
 
     /**
-     * @return the current typeface and style in which the text is being
-     * displayed.
+     * Gets the current {@link Typeface} that is used to style the text.
+     * @return The current Typeface.
      *
      * @see #setTypeface(Typeface)
      *
@@ -3660,8 +3699,9 @@
     }
 
     /**
-     * @return the extent by which text is currently being letter-spaced.
-     * This will normally be 0.
+     * Gets the text letter-space value, which determines the spacing between characters.
+     * The value returned is in ems. Normally, this value is 0.0.
+     * @return The text letter-space value in ems.
      *
      * @see #setLetterSpacing(float)
      * @see Paint#setLetterSpacing
@@ -3671,12 +3711,13 @@
     }
 
     /**
-     * Sets text letter-spacing.  The value is in 'EM' units.  Typical values
+     * Sets text letter-spacing in em units.  Typical values
      * for slight expansion will be around 0.05.  Negative values tighten text.
      *
      * @see #getLetterSpacing()
      * @see Paint#getLetterSpacing
      *
+     * @param letterSpacing A text letter-space value in ems.
      * @attr ref android.R.styleable#TextView_letterSpacing
      */
     @android.view.RemotableViewMethod
@@ -3741,7 +3782,8 @@
     }
 
     /**
-     * @return the currently set break strategy.
+     * Gets the current strategy for breaking paragraphs into lines.
+     * @return the current strategy for breaking paragraphs into lines.
      *
      * @attr ref android.R.styleable#TextView_breakStrategy
      * @see #setBreakStrategy(int)
@@ -3752,9 +3794,12 @@
     }
 
     /**
-     * Sets the hyphenation frequency. The default value for both TextView and EditText, which is
-     * set from the theme, is {@link Layout#HYPHENATION_FREQUENCY_NORMAL}.
+     * Sets the frequency of automatic hyphenation to use when determining word breaks.
+     * The default value for both TextView and {@link EditText} is
+     * {@link Layout#HYPHENATION_FREQUENCY_NORMAL}.
+     * Note that the default hyphenation frequency value is set from the theme.
      *
+     * @param hyphenationFrequency The hyphenation frequency to use.
      * @attr ref android.R.styleable#TextView_hyphenationFrequency
      * @see #getHyphenationFrequency()
      */
@@ -3768,7 +3813,9 @@
     }
 
     /**
-     * @return the currently set hyphenation frequency.
+     * Gets the current frequency of automatic hyphenation to be used when determining word breaks.
+     * @return the current frequency of automatic hyphenation to be used when determining word
+     * breaks.
      *
      * @attr ref android.R.styleable#TextView_hyphenationFrequency
      * @see #setHyphenationFrequency(int)
@@ -3927,7 +3974,7 @@
     }
 
     /**
-     * <p>Return the current color selected for normal text.</p>
+     * Return the current color selected for normal text.
      *
      * @return Returns the current text color.
      */
@@ -4037,7 +4084,8 @@
     }
 
     /**
-     * @return the vertical offset of the shadow layer
+     * Gets the vertical offset of the shadow layer.
+     * @return The vertical offset of the shadow layer.
      *
      * @see #setShadowLayer(float, float, float, int)
      *
@@ -4048,6 +4096,7 @@
     }
 
     /**
+     * Gets the color of the shadow layer.
      * @return the color of the shadow layer
      *
      * @see #setShadowLayer(float, float, float, int)
@@ -4060,8 +4109,9 @@
     }
 
     /**
-     * @return the base paint used for the text.  Please use this only to
-     * consult the Paint's properties and not to change them.
+     * Gets the {@link TextPaint} used for the text.
+     * Use this only to consult the Paint's properties and not to change them.
+     * @return The base paint used for the text.
      */
     public TextPaint getPaint() {
         return mTextPaint;
@@ -4105,7 +4155,7 @@
     }
 
     /**
-     * Returns the list of URLSpans attached to the text
+     * Returns the list of {@link android.text.style.URLSpan URLSpans} attached to the text
      * (by {@link Linkify} or otherwise) if any.  You can call
      * {@link URLSpan#getURL} on them to find where they link to
      * or use {@link Spanned#getSpanStart} and {@link Spanned#getSpanEnd}
@@ -4266,7 +4316,8 @@
     }
 
     /**
-     * @return the flags on the Paint being used to display the text.
+     * Gets the flags on the Paint being used to display the text.
+     * @return The flags on the Paint being used to display the text.
      * @see Paint#getFlags
      */
     public int getPaintFlags() {
@@ -5691,8 +5742,8 @@
 
     /**
      * Change the editor type integer associated with the text view, which
-     * will be reported to an IME with {@link EditorInfo#imeOptions} when it
-     * has focus.
+     * is reported to an Input Method Editor (IME) with {@link EditorInfo#imeOptions}
+     * when it has focus.
      * @see #getImeOptions
      * @see android.view.inputmethod.EditorInfo
      * @attr ref android.R.styleable#TextView_imeOptions
@@ -5704,8 +5755,8 @@
     }
 
     /**
-     * Get the type of the IME editor.
-     *
+     * Get the type of the Input Method Editor (IME).
+     * @return the type of the IME
      * @see #setImeOptions(int)
      * @see android.view.inputmethod.EditorInfo
      */
@@ -7532,7 +7583,7 @@
 
     /**
      * Called by the framework in response to a text auto-correction (such as fixing a typo using a
-     * a dictionary) from the current input method, provided by it calling
+     * dictionary) from the current input method, provided by it calling
      * {@link InputConnection#commitCorrection(CorrectionInfo) InputConnection.commitCorrection()}.
      * The default implementation flashes the background of the corrected word to provide
      * feedback to the user.
@@ -9636,6 +9687,11 @@
         return super.onTrackballEvent(event);
     }
 
+    /**
+     * Sets the Scroller used for producing a scrolling animation
+     *
+     * @param s A Scroller instance
+     */
     public void setScroller(Scroller s) {
         mScroller = s;
     }
@@ -10581,6 +10637,7 @@
     /**
      * Returns whether this text view is a current input method target.  The
      * default implementation just checks with {@link InputMethodManager}.
+     * @return True if the TextView is a current input method target; false otherwise.
      */
     public boolean isInputMethodTarget() {
         InputMethodManager imm = InputMethodManager.peekInstance();
diff --git a/core/java/com/android/internal/policy/DividerSnapAlgorithm.java b/core/java/com/android/internal/policy/DividerSnapAlgorithm.java
index 11e7102..fb6b8b0 100644
--- a/core/java/com/android/internal/policy/DividerSnapAlgorithm.java
+++ b/core/java/com/android/internal/policy/DividerSnapAlgorithm.java
@@ -332,8 +332,12 @@
     }
 
     private void addMinimizedTarget(boolean isHorizontalDivision) {
-        int position = mTaskHeightInMinimizedMode;
-        position += isHorizontalDivision ? mInsets.top : mInsets.left;
+        // In portrait offset the position by the statusbar height, in landscape add the statusbar
+        // height as well to match portrait offset
+        int position = mTaskHeightInMinimizedMode + mInsets.top;
+        if (!isHorizontalDivision) {
+            position += mInsets.left;
+        }
         mTargets.add(new SnapTarget(position, position, SnapTarget.FLAG_NONE));
     }
 
diff --git a/core/jni/android_view_TextureView.cpp b/core/jni/android_view_TextureView.cpp
index 18a1360..2921b37 100644
--- a/core/jni/android_view_TextureView.cpp
+++ b/core/jni/android_view_TextureView.cpp
@@ -83,7 +83,7 @@
             colorType = kN32_SkColorType;
             alphaType = kOpaque_SkAlphaType;
             break;
-        case AHARDWAREBUFFER_FORMAT_R16G16B16A16_SFLOAT:
+        case AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT:
             colorType = kRGBA_F16_SkColorType;
             alphaType = kPremul_SkAlphaType;
             break;
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 155a939..1777f24 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -126,6 +126,7 @@
     <protected-broadcast android:name="android.bluetooth.adapter.action.DISCOVERY_STARTED" />
     <protected-broadcast android:name="android.bluetooth.adapter.action.DISCOVERY_FINISHED" />
     <protected-broadcast android:name="android.bluetooth.adapter.action.LOCAL_NAME_CHANGED" />
+    <protected-broadcast android:name="android.bluetooth.adapter.action.BLUETOOTH_ADDRESS_CHANGED" />
     <protected-broadcast android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
     <protected-broadcast android:name="android.bluetooth.device.action.UUID" />
     <protected-broadcast android:name="android.bluetooth.device.action.MAS_INSTANCE" />
diff --git a/core/res/res/layout/autofill_save.xml b/core/res/res/layout/autofill_save.xml
index a6892c6..2f7ad3a 100644
--- a/core/res/res/layout/autofill_save.xml
+++ b/core/res/res/layout/autofill_save.xml
@@ -16,85 +16,88 @@
 
 <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/autofill_save"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
-    android:paddingStart="16dip"
-    android:paddingEnd="16dip"
-    android:paddingTop="16dip"
-    android:paddingBottom="16dip"
-    android:elevation="16dp"
-    android:background="?android:attr/colorBackground"
     android:orientation="vertical">
 
     <LinearLayout
+        android:id="@+id/autofill_save"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
-        android:orientation="horizontal">
+        android:layout_marginTop="32dp"
+        android:padding="16dp"
+        android:elevation="32dp"
+        android:background="?android:attr/colorBackground"
+        android:orientation="vertical">
+
+        <LinearLayout
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:orientation="horizontal">
+
+            <TextView
+                android:id="@+id/autofill_save_title"
+                android:layout_width="0dp"
+                android:layout_height="wrap_content"
+                android:text="@string/autofill_save_title"
+                android:textSize="16sp"
+                android:textColor="?android:attr/textColorPrimary"
+                android:layout_weight="1">
+            </TextView>
+
+            <ImageView
+                android:id="@+id/autofill_save_close"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_marginLeft="16dp"
+                android:src="@android:drawable/ic_close"
+                android:alpha="0.54"
+                android:background="?android:attr/selectableItemBackgroundBorderless">
+            </ImageView>
+
+        </LinearLayout>
 
         <TextView
-            android:id="@+id/autofill_save_title"
-            android:layout_width="wrap_content"
+            android:id="@+id/autofill_save_subtitle"
+            android:layout_width="fill_parent"
             android:layout_height="wrap_content"
-            android:text="@string/autofill_save_title"
-            android:singleLine="true">
+            android:layout_marginTop="4dp"
+            android:visibility="gone">
         </TextView>
 
-        <Space
-            android:layout_width="0dp"
-            android:layout_height="0dp"
-            android:layout_weight="1"
-            android:visibility="invisible" >
-        </Space>
-
-        <ImageView
-            android:id="@+id/autofill_save_close"
+        <com.android.internal.widget.ButtonBarLayout
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:src="@android:drawable/ic_close"
-            android:background="?android:attr/selectableItemBackgroundBorderless">
-        </ImageView>
+            android:layout_gravity="end"
+            android:layout_marginTop="16dp"
+            android:layout_weight="1"
+            android:orientation="horizontal">
+
+            <Space
+                android:layout_width="0dp"
+                android:layout_height="0dp"
+                android:layout_weight="1"
+                android:visibility="invisible">
+            </Space>
+
+            <Button
+                android:id="@+id/autofill_save_no"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                style="?android:attr/buttonBarButtonStyle"
+                android:text="@string/autofill_save_no">
+            </Button>
+
+            <Button
+                android:id="@+id/autofill_save_yes"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                style="@style/Widget.Material.Button.Colored"
+                android:text="@string/autofill_save_yes">
+            </Button>
+
+        </com.android.internal.widget.ButtonBarLayout>
 
     </LinearLayout>
 
-    <TextView
-        android:id="@+id/autofill_save_subtitle"
-        android:layout_width="fill_parent"
-        android:layout_height="wrap_content"
-        android:visibility="invisible" >
-    </TextView>
-
-    <com.android.internal.widget.ButtonBarLayout
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="end"
-        android:layout_marginTop="16dp"
-        android:layout_weight="1"
-        android:orientation="horizontal">
-
-        <Space
-            android:layout_width="0dp"
-            android:layout_height="0dp"
-            android:layout_weight="1"
-            android:visibility="invisible" >
-        </Space>
-
-        <Button
-            android:id="@+id/autofill_save_no"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            style="?android:attr/buttonBarButtonStyle"
-            android:text="@string/autofill_save_no" >
-        </Button>
-
-        <Button
-            android:id="@+id/autofill_save_yes"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            style="?android:attr/buttonBarButtonStyle"
-            android:text="@string/autofill_save_yes" >
-        </Button>
-
-   </com.android.internal.widget.ButtonBarLayout>
-
 </LinearLayout>
diff --git a/core/res/res/values-b+sr+Latn/strings.xml b/core/res/res/values-b+sr+Latn/strings.xml
index 86bb518..b66167e 100644
--- a/core/res/res/values-b+sr+Latn/strings.xml
+++ b/core/res/res/values-b+sr+Latn/strings.xml
@@ -837,7 +837,7 @@
     <string name="permlab_addVoicemail" msgid="5525660026090959044">"dodavanje govorne pošte"</string>
     <string name="permdesc_addVoicemail" msgid="6604508651428252437">"Dozvoljava aplikaciji da dodaje poruke u prijemno sanduče govorne pošte."</string>
     <string name="permlab_writeGeolocationPermissions" msgid="5962224158955273932">"izmena dozvola za geografske lokacije Pregledača"</string>
-    <string name="permdesc_writeGeolocationPermissions" msgid="1083743234522638747">"Dozvoljava aplikaciji da izmeni dozvole Pregledača za utvrđivanje geografske lokacije. Zlonamerne aplikacije to mogu da zloupotrebe i iskoriste za slanje informacija o lokaciji nasumičnim veb sajtovima."</string>
+    <string name="permdesc_writeGeolocationPermissions" msgid="1083743234522638747">"Dozvoljava aplikaciji da izmeni dozvole Pregledača za utvrđivanje geografske lokacije. Zlonamerne aplikacije to mogu da zloupotrebe i iskoriste za slanje informacija o lokaciji nasumičnim veb-sajtovima."</string>
     <string name="save_password_message" msgid="767344687139195790">"Želite li da pregledač zapamti ovu lozinku?"</string>
     <string name="save_password_notnow" msgid="6389675316706699758">"Ne sada"</string>
     <string name="save_password_remember" msgid="6491879678996749466">"Zapamti"</string>
diff --git a/core/res/res/values-bn/strings.xml b/core/res/res/values-bn/strings.xml
index 83db42c..754e04f 100644
--- a/core/res/res/values-bn/strings.xml
+++ b/core/res/res/values-bn/strings.xml
@@ -1736,10 +1736,8 @@
     <string name="autofill_error_cannot_autofill" msgid="7402758580060110371">"বিষয়বস্তুগুলি অটো-ফিল করা যাবে না"</string>
     <string name="autofill_save_title" msgid="7081244500504163245">"<xliff:g id="LABEL">%1$s</xliff:g> এ সংরক্ষণ করবেন?"</string>
     <string name="autofill_save_title_with_type" msgid="4977385733042555659">"<xliff:g id="LABEL">%2$s</xliff:g> এ <xliff:g id="TYPE">%1$s</xliff:g> সংরক্ষণ করবেন?"</string>
-    <!-- no translation found for autofill_save_title_with_2types (8875796560521962098) -->
-    <skip />
-    <!-- no translation found for autofill_save_title_with_3types (6889899028382843493) -->
-    <skip />
+    <string name="autofill_save_title_with_2types" msgid="8875796560521962098">"<xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g> <xliff:g id="LABEL">%3$s</xliff:g> এ সংরক্ষণ করবেন?"</string>
+    <string name="autofill_save_title_with_3types" msgid="6889899028382843493">"<xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g>, <xliff:g id="TYPE_2">%3$s</xliff:g> <xliff:g id="LABEL">%4$s</xliff:g> এ সংরক্ষণ করবেন?"</string>
     <string name="autofill_save_yes" msgid="6398026094049005921">"সংরক্ষণ করুন"</string>
     <string name="autofill_save_no" msgid="2625132258725581787">"না থাক"</string>
     <string name="autofill_save_type_password" msgid="5288448918465971568">"পাসওয়ার্ড"</string>
diff --git a/core/res/res/values-ca/strings.xml b/core/res/res/values-ca/strings.xml
index 0a63cdf..b0ea791 100644
--- a/core/res/res/values-ca/strings.xml
+++ b/core/res/res/values-ca/strings.xml
@@ -1735,8 +1735,8 @@
     <string name="autofill_error_cannot_autofill" msgid="7402758580060110371">"El contingut no es pot emplenar automàticament"</string>
     <string name="autofill_save_title" msgid="7081244500504163245">"Vols desar-ho a <xliff:g id="LABEL">%1$s</xliff:g>?"</string>
     <string name="autofill_save_title_with_type" msgid="4977385733042555659">"Vols desar la informació del camp <xliff:g id="TYPE">%1$s</xliff:g> a <xliff:g id="LABEL">%2$s</xliff:g>?"</string>
-    <string name="autofill_save_title_with_2types" msgid="8875796560521962098">"Vols desar la informació dels camps <xliff:g id="TYPE_0">%1$s</xliff:g> i <xliff:g id="TYPE_1">%2$s</xliff:g> a <xliff:g id="LABEL">%3$s</xliff:g>?"</string>
-    <string name="autofill_save_title_with_3types" msgid="6889899028382843493">"Vols desar la informació dels camps <xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g> i <xliff:g id="TYPE_2">%3$s</xliff:g> a <xliff:g id="LABEL">%4$s</xliff:g>?"</string>
+    <string name="autofill_save_title_with_2types" msgid="8875796560521962098">"Vols desar <xliff:g id="TYPE_0">%1$s</xliff:g> i <xliff:g id="TYPE_1">%2$s</xliff:g> a <xliff:g id="LABEL">%3$s</xliff:g>?"</string>
+    <string name="autofill_save_title_with_3types" msgid="6889899028382843493">"Vols desar <xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g> i <xliff:g id="TYPE_2">%3$s</xliff:g> a <xliff:g id="LABEL">%4$s</xliff:g>?"</string>
     <string name="autofill_save_yes" msgid="6398026094049005921">"Desa"</string>
     <string name="autofill_save_no" msgid="2625132258725581787">"No, gràcies"</string>
     <string name="autofill_save_type_password" msgid="5288448918465971568">"contrasenya"</string>
diff --git a/core/res/res/values-de/strings.xml b/core/res/res/values-de/strings.xml
index 6e930ff..e283c3d 100644
--- a/core/res/res/values-de/strings.xml
+++ b/core/res/res/values-de/strings.xml
@@ -391,7 +391,7 @@
     <string name="permlab_modifyAudioSettings" msgid="6095859937069146086">"Audio-Einstellungen ändern"</string>
     <string name="permdesc_modifyAudioSettings" msgid="3522565366806248517">"Ermöglicht der App, globale Audio-Einstellungen zu ändern, etwa die Lautstärke und den Lautsprecher für die Ausgabe."</string>
     <string name="permlab_recordAudio" msgid="3876049771427466323">"Audio aufnehmen"</string>
-    <string name="permdesc_recordAudio" msgid="4245930455135321433">"Diese App kann jederzeit Ton über das Mikrofon aufnehmen."</string>
+    <string name="permdesc_recordAudio" msgid="4245930455135321433">"Diese App kann jederzeit Audio über das Mikrofon aufnehmen."</string>
     <string name="permlab_sim_communication" msgid="2935852302216852065">"Befehle an die SIM senden"</string>
     <string name="permdesc_sim_communication" msgid="5725159654279639498">"Ermöglicht der App das Senden von Befehlen an die SIM-Karte. Dies ist äußerst risikoreich."</string>
     <string name="permlab_camera" msgid="3616391919559751192">"Bilder und Videos aufnehmen"</string>
diff --git a/core/res/res/values-es/strings.xml b/core/res/res/values-es/strings.xml
index c46146d..08bff7d 100644
--- a/core/res/res/values-es/strings.xml
+++ b/core/res/res/values-es/strings.xml
@@ -495,7 +495,7 @@
     <string name="permlab_sdcardRead" product="default" msgid="2188156462934977940">"consultar el contenido de la tarjeta SD"</string>
     <string name="permdesc_sdcardRead" product="nosdcard" msgid="3446988712598386079">"Permite que la aplicación lea el contenido del almacenamiento USB."</string>
     <string name="permdesc_sdcardRead" product="default" msgid="2607362473654975411">"Permite que la aplicación lea el contenido de la tarjeta SD."</string>
-    <string name="permlab_sdcardWrite" product="nosdcard" msgid="8485979062254666748">"editar o borrar contenido de USB"</string>
+    <string name="permlab_sdcardWrite" product="nosdcard" msgid="8485979062254666748">"editar o borrar contenido de almacenamiento USB"</string>
     <string name="permlab_sdcardWrite" product="default" msgid="8805693630050458763">"modificar o eliminar el contenido de la tarjeta SD"</string>
     <string name="permdesc_sdcardWrite" product="nosdcard" msgid="6175406299445710888">"Permite escribir en el almacenamiento USB."</string>
     <string name="permdesc_sdcardWrite" product="default" msgid="4337417790936632090">"Permite que la aplicación escriba en la tarjeta SD."</string>
diff --git a/core/res/res/values-fa/strings.xml b/core/res/res/values-fa/strings.xml
index 7312fa6..25bdc11 100644
--- a/core/res/res/values-fa/strings.xml
+++ b/core/res/res/values-fa/strings.xml
@@ -346,7 +346,7 @@
     <string name="permdesc_persistentActivity" product="default" msgid="4384760047508278272">"به برنامه امکان می‌دهد قسمت‌هایی از خود را در حافظه دائمی کند. این کار حافظه موجود را برای سایر برنامه‌ها محدود کرده و باعث کندی تلفن می‌شود."</string>
     <string name="permlab_getPackageSize" msgid="7472921768357981986">"اندازه گیری فضای حافظه برنامه"</string>
     <string name="permdesc_getPackageSize" msgid="3921068154420738296">"‏به برنامه اجازه می‎دهد تا کدها، داده‎ها و اندازه‎های حافظهٔ پنهان خود را بازیابی کند"</string>
-    <string name="permlab_writeSettings" msgid="2226195290955224730">"اصلاح تنظیمات سیستم"</string>
+    <string name="permlab_writeSettings" msgid="2226195290955224730">"تغییر تنظیمات سیستم"</string>
     <string name="permdesc_writeSettings" msgid="7775723441558907181">"‏به برنامه اجازه می‎دهد تا داده‎های تنظیم سیستم را تغییر دهد. برنامه‎های مخرب می‎توانند پیکربندی سیستم شما را خراب کنند."</string>
     <string name="permlab_receiveBootCompleted" msgid="5312965565987800025">"اجرا شدن در هنگام راه‌اندازی"</string>
     <string name="permdesc_receiveBootCompleted" product="tablet" msgid="7390304664116880704">"به برنامه اجازه می‌دهد که به محض پایان راه‌اندازی سیستم، راه‌اندازی شود. این ویژگی ممکن است باعث شود راه‌اندازی دستگاه مدت زمان بیشتری طول بکشد و به برنامه اجازه می‌دهد با همیشه درحال اجرا بودنش باعث کاهش سرعت کلی دستگاه شود."</string>
@@ -360,7 +360,7 @@
     <string name="permdesc_readContacts" product="tablet" msgid="5294866856941149639">"به برنامه اجازه می‌دهد داده‌های مربوط به مخاطبین ذخیره شده در رایانهٔ لوحی شما را بخواند از جمله، تعداد دفعات تماس‌هایی که برقرار کرده‌اید، ایمیل‌هایی که ارسال کرده‌اید یا به روش‌های دیگری به افراد خاصی ارتباط برقرار کرده‌اید. این با برنامه‌ها امکان می‌دهد داده‌های مخاطب شما را ذخیره کنند و برنامه‌های مخرب ممکن است داده‌های مخاطب را بدون اطلاع شما به اشتراک بگذارند."</string>
     <string name="permdesc_readContacts" product="tv" msgid="1839238344654834087">"به برنامه اجازه می‌دهد داده‌های مربوط به مخاطبین ذخیره شده در تلویزیون شما را از جمله تعداد تماس‌‌هایی که برقرار کرده‌اید، ایمیل‌هایی که ارسال کرده‌اید یا ارتباطاتی را که به هر شکل با مخاطبین خاصی برقرار کردید تغییر دهد. این مجوز به برنامه اجازه می‌دهد تا داده‌های مخاطب را ذخیره کند و شاید برنامه‌های مخرب داده‌های مخاطب را بدون اطلاع شما به اشتراک بگذارند."</string>
     <string name="permdesc_readContacts" product="default" msgid="8440654152457300662">"به برنامه اجازه می‌دهد داده‌های مربوط به مخاطبین ذخیره شده در تلفن شما را بخواند از جمله، تعداد دفعات تماس‌هایی که برقرار کرده‌اید، ایمیل‌هایی که ارسال کرده‌اید یا به روش‌های دیگری با افراد خاصی ارتباط برقرار کرده‌اید. این به برنامه‌ها امکان می‌دهد داده‌های مخاطب شما را ذخیره کنند و برنامه‌های مخرب ممکن است داده‌های مخاطب را بدون اطلاع شما به اشتراک بگذارند."</string>
-    <string name="permlab_writeContacts" msgid="5107492086416793544">"اصلاح مخاطبین شما"</string>
+    <string name="permlab_writeContacts" msgid="5107492086416793544">"تغییر مخاطبین"</string>
     <string name="permdesc_writeContacts" product="tablet" msgid="897243932521953602">"به برنامه اجازه می‌دهد داده‌های مربوط به مخاطبین ذخیره شده در رایانهٔ لوحی شما را از جمله تعداد تماس‌‌هایی که برقرار کرده‌اید، ایمیل‌هایی که ارسال کرده‌اید یا ارتباطاتی را که به هر شکل با مخاطبین خاصی برقرار کردید تغییر دهد. این مجوز به برنامه اجازه می‌دهد داده‌های مخاطب را حذف نماید."</string>
     <string name="permdesc_writeContacts" product="tv" msgid="5438230957000018959">"به برنامه اجازه می‌دهد داده‌های مربوط به مخاطبین ذخیره شده در تلویزیون شما را از جمله تعداد تماس‌‌هایی که برقرار کرده‌اید، ایمیل‌هایی که ارسال کرده‌اید یا ارتباطاتی را که به هر شکل با مخاطبین خاصی برقرار کردید تغییر دهد. این مجوز به برنامه اجازه می‌دهد داده‌های مخاطب را حذف نماید."</string>
     <string name="permdesc_writeContacts" product="default" msgid="589869224625163558">"به برنامه اجازه می‌دهد داده‌های مربوط به مخاطبین ذخیره شده در تلفن شما را از جمله تعداد تماس‌‌هایی که برقرار کرده‌اید، ایمیل‌هایی که ارسال کرده‌اید یا ارتباطاتی را که به هر شکل با مخاطبین خاصی برقرار کردید تغییر دهد. این مجوز به برنامه اجازه می‌دهد داده‌های مخاطب را حذف نماید."</string>
@@ -389,7 +389,7 @@
     <string name="permdesc_accessCoarseLocation" product="tv" msgid="1884022719818788511">"‏این برنامه می‌تواند براساس منابع شبکه مانند دکل‌های مخابراتی و شبکه‌های Wi-Fi، مکان شما را تشخیص دهد. این خدمات مکان باید روشن و در تلویزیون شما دردسترس باشند تا برنامه بتواند از آن‌ها استفاده کند."</string>
     <string name="permdesc_accessCoarseLocation" product="default" msgid="7788009094906196995">"‏این برنامه می‌تواند براساس منابع شبکه مانند دکل‌های مخابراتی و شبکه‌های Wi-Fi، مکان شما را تشخیص دهد. این خدمات مکان باید روشن و در تلفن شما دردسترس باشند تا برنامه بتواند از آن‌ها استفاده کند."</string>
     <string name="permlab_modifyAudioSettings" msgid="6095859937069146086">"تغییر تنظیمات صوتی"</string>
-    <string name="permdesc_modifyAudioSettings" msgid="3522565366806248517">"به برنامه امکان می‌دهد تنظیمات صوتی کلی مانند میزان صدا و بلندگوی مورد استفاده برای پخش صدا را اصلاح کند."</string>
+    <string name="permdesc_modifyAudioSettings" msgid="3522565366806248517">"به برنامه امکان می‌دهد تنظیمات صوتی کلی مانند میزان صدا و بلندگوی مورد استفاده برای پخش صدا را تغییر دهد."</string>
     <string name="permlab_recordAudio" msgid="3876049771427466323">"ضبط صدا"</string>
     <string name="permdesc_recordAudio" msgid="4245930455135321433">"این برنامه می‌تواند در هرزمانی با استفاده از میکروفون صدا ضبط کند."</string>
     <string name="permlab_sim_communication" msgid="2935852302216852065">"ارسال فرمان به سیم کارت"</string>
@@ -488,15 +488,15 @@
     <string name="permlab_readSyncSettings" msgid="6201810008230503052">"خواندن تنظیمات همگام‌سازی"</string>
     <string name="permdesc_readSyncSettings" msgid="2706745674569678644">"به برنامه اجازه می‌دهد تنظیمات را برای یک حساب بخواند. به‌عنوان مثال، این ویژگی می‌تواند تعیین کند آیا حساب «افراد» شما با یک حساب همگام‌سازی شده است."</string>
     <string name="permlab_writeSyncSettings" msgid="5408694875793945314">"تغییر وضعیت همگام‌سازی بین فعال و غیرفعال"</string>
-    <string name="permdesc_writeSyncSettings" msgid="8956262591306369868">"به یک برنامه اجازه می‌دهد تنظیمات همگام‌سازی را برای یک حساب اصلاح کند. به‌عنوان مثال، از این ویژگی می‌توان برای فعال کردن همگام‌سازی برنامه «افراد» با یک حساب استفاده کرد."</string>
+    <string name="permdesc_writeSyncSettings" msgid="8956262591306369868">"به برنامه اجازه می‌دهد تنظیمات همگام‌سازی را برای حساب تغییر دهد. به‌عنوان مثال، از این ویژگی می‌توان برای فعال کردن همگام‌سازی برنامه «افراد» با یک حساب استفاده کرد."</string>
     <string name="permlab_readSyncStats" msgid="7396577451360202448">"خواندن اطلاعات آماری همگام‌سازی"</string>
     <string name="permdesc_readSyncStats" msgid="1510143761757606156">"به یک برنامه اجازه می‌دهد وضعیت همگام‌سازی یک حساب را بخواند، از جمله سابقه رویدادهای همگام‌سازی و میزان داده‌های همگام‌سازی شده."</string>
     <string name="permlab_sdcardRead" product="nosdcard" msgid="367275095159405468">"‏خواندن محتویات حافظهٔ USB شما"</string>
     <string name="permlab_sdcardRead" product="default" msgid="2188156462934977940">"‏خواندن محتویات کارت SD شما"</string>
     <string name="permdesc_sdcardRead" product="nosdcard" msgid="3446988712598386079">"‏به برنامه اجازه می‌دهد محتواهای فضای ذخیره USB را بخواند."</string>
     <string name="permdesc_sdcardRead" product="default" msgid="2607362473654975411">"‏به برنامه اجازه می‌دهد محتواهای کارت SD شما را بخواند."</string>
-    <string name="permlab_sdcardWrite" product="nosdcard" msgid="8485979062254666748">"‏اصلاح یا حذف محتویات حافظهٔ USB شما"</string>
-    <string name="permlab_sdcardWrite" product="default" msgid="8805693630050458763">"‏محتوای کارت SD شما را اصلاح کرده یا تغییر دهد"</string>
+    <string name="permlab_sdcardWrite" product="nosdcard" msgid="8485979062254666748">"‏تغییر یا حذف محتویات حافظه USB"</string>
+    <string name="permlab_sdcardWrite" product="default" msgid="8805693630050458763">"‏تغییر یا حذف محتوای کارت SD"</string>
     <string name="permdesc_sdcardWrite" product="nosdcard" msgid="6175406299445710888">"‏به برنامه اجازه می‎دهد تا در حافظهٔ USB بنویسد."</string>
     <string name="permdesc_sdcardWrite" product="default" msgid="4337417790936632090">"‏به برنامه اجازه می‎دهد تا در کارت SD بنویسد."</string>
     <string name="permlab_use_sip" msgid="2052499390128979920">"‏تماس گرفتن/دریافت تماس از طریق SIP"</string>
@@ -517,7 +517,7 @@
     <string name="permdesc_readNetworkUsageHistory" msgid="7689060749819126472">"‏به برنامه اجازه می‎دهد تا کاربرد شبکه را در طول زمان برای برنامه‎ها و شبکه‎های خاص بخواند."</string>
     <string name="permlab_manageNetworkPolicy" msgid="2562053592339859990">"مدیریت خط‌مشی شبکه"</string>
     <string name="permdesc_manageNetworkPolicy" msgid="7537586771559370668">"‏به برنامه اجازه می‎دهد تا خط‌مشی‎های شبکه را مدیریت کند و قوانین خاص برنامه را تعیین کند."</string>
-    <string name="permlab_modifyNetworkAccounting" msgid="5088217309088729650">"اصلاح محاسبه استفاده از شبکه"</string>
+    <string name="permlab_modifyNetworkAccounting" msgid="5088217309088729650">"تغییر محاسبه استفاده از شبکه"</string>
     <string name="permdesc_modifyNetworkAccounting" msgid="5443412866746198123">"‏به برنامه اجازه می‎دهد تا نحوه محاسبه کاربرد شبکه در برنامه را تغییر دهد. برای استفاده برنامه‎های عادی نیست."</string>
     <string name="permlab_accessNotifications" msgid="7673416487873432268">"اعلان‌های دسترسی"</string>
     <string name="permdesc_accessNotifications" msgid="458457742683431387">"به برنامه اجازه می‌دهد به بازیابی، بررسی و پاک کردن اعلان‌ها از جمله موارد پست شده توسط سایر برنامه‌ها بپردازد."</string>
@@ -826,9 +826,9 @@
     <string name="permlab_readHistoryBookmarks" msgid="3775265775405106983">"خواندن سابقه و نشانک‌های وب شما"</string>
     <string name="permdesc_readHistoryBookmarks" msgid="8462378226600439658">"به برنامه اجازه می‌دهد سابقه نشانی‌های وب را که مرورگر بازدید کرده است و همه نشانک‌های مرورگر را بخواند. توجه: این مجوز توسط مرورگرهای شخص ثالث یا سایر برنامه‌های دارای قابلیت مرور وب قابل اجرا نیست."</string>
     <string name="permlab_writeHistoryBookmarks" msgid="3714785165273314490">"نوشتن نشانک‌های وب و سابقه"</string>
-    <string name="permdesc_writeHistoryBookmarks" product="tablet" msgid="6825527469145760922">"به برنامه اجازه می‌دهد سابقه مرورگر یا نشانک‌های ذخیره شده در رایانهٔ لوحی شما را اصلاح کند. این ویژگی ممکن است به برنامه اجازه دهد داده‌های مرورگر را حذف یا اصلاح کند. توجه: این مجوز ممکن است توسط مرورگرهای شخص ثالث یا سایر برنامه‌های دارای قابلیت مرور وب قابل اجرا نباشد."</string>
+    <string name="permdesc_writeHistoryBookmarks" product="tablet" msgid="6825527469145760922">"به برنامه اجازه می‌دهد سابقه مرورگر یا نشانک‌های ذخیره‌شده در رایانهٔ لوحی شما را تغییر دهد. این ممکن است به برنامه اجازه دهد داده‌های مرورگر را حذف کند یا تغییر دهد. توجه: این مجوز ممکن است توسط مرورگرهای شخص ثالث یا سایر برنامه‌های دارای قابلیت مرور وب قابل اجرا نباشد."</string>
     <string name="permdesc_writeHistoryBookmarks" product="tv" msgid="7007393823197766548">"به برنامه اجازه می‌دهد تا سابقه یا نشانک‌های ذخیره شده مرورگر در تلویزیون شما را تغییر دهد. شاید به برنامه اجازه دهد تا داده‌های «مرورگر» را پاک کند یا تغییر دهد. توجه: این مجوز شاید توسط مرورگرهای شخص ثالث یا سایر برنامه‌ها با قابلیت‌های مرور وب اجرا شود."</string>
-    <string name="permdesc_writeHistoryBookmarks" product="default" msgid="8497389531014185509">"به برنامه اجازه می‌دهد سابقه مرورگر یا نشانک‌های ذخیره شده در تلفن شما را اصلاح کند. این ویژگی ممکن است به برنامه اجازه دهد داده‌های مرورگر را حذف یا اصلاح کند. توجه: این مجوز ممکن است توسط مرورگرهای شخص ثالث یا سایر برنامه‌های دارای قابلیت مرور وب قابل اجرا نباشد."</string>
+    <string name="permdesc_writeHistoryBookmarks" product="default" msgid="8497389531014185509">"به برنامه اجازه می‌دهد سابقه مرورگر یا نشانک‌های ذخیره‌شده در تلفن شما را تغییر دهد. این ممکن است به برنامه اجازه دهد داده‌های مرورگر را حذف کند یا تغییر دهد. توجه: این مجوز ممکن است توسط مرورگرهای شخص ثالث یا سایر برنامه‌های دارای قابلیت مرور وب قابل اجرا نباشد."</string>
     <string name="permlab_setAlarm" msgid="1379294556362091814">"تنظیم یک هشدار"</string>
     <string name="permdesc_setAlarm" msgid="316392039157473848">"‏به برنامه اجازه می‎دهد تا هشداری را در برنامه ساعت زنگدار نصب شده تنظیم کند. برخی از برنامه‎های ساعت زنگدار نمی‌‎توانند این ویژگی را اعمال کنند."</string>
     <string name="permlab_addVoicemail" msgid="5525660026090959044">"افزودن پست صوتی"</string>
diff --git a/core/res/res/values-fr/strings.xml b/core/res/res/values-fr/strings.xml
index fdea62a..5b7b377 100644
--- a/core/res/res/values-fr/strings.xml
+++ b/core/res/res/values-fr/strings.xml
@@ -1641,7 +1641,7 @@
     </plurals>
     <string name="zen_mode_until" msgid="7336308492289875088">"Jusqu\'à <xliff:g id="FORMATTEDTIME">%1$s</xliff:g>"</string>
     <string name="zen_mode_alarm" msgid="9128205721301330797">"Jusqu\'à <xliff:g id="FORMATTEDTIME">%1$s</xliff:g> (alarme suivante)"</string>
-    <string name="zen_mode_forever" msgid="1916263162129197274">"Jusqu\'à ce que vous désactiviez le mode Ne pas déranger"</string>
+    <string name="zen_mode_forever" msgid="1916263162129197274">"Jusqu\'à ce que vous désactiviez ce mode"</string>
     <string name="zen_mode_forever_dnd" msgid="3792132696572189081">"Jusqu\'à ce que vous désactiviez la fonctionnalité \"Ne pas déranger\""</string>
     <string name="zen_mode_rule_name_combination" msgid="191109939968076477">"<xliff:g id="FIRST">%1$s</xliff:g>/<xliff:g id="REST">%2$s</xliff:g>"</string>
     <string name="toolbar_collapse_description" msgid="2821479483960330739">"Réduire"</string>
diff --git a/core/res/res/values-gu/strings.xml b/core/res/res/values-gu/strings.xml
index 82481d5..58adbca 100644
--- a/core/res/res/values-gu/strings.xml
+++ b/core/res/res/values-gu/strings.xml
@@ -1736,10 +1736,8 @@
     <string name="autofill_error_cannot_autofill" msgid="7402758580060110371">"કન્ટેન્ટ સ્વતઃ ભરી શકાતું નથી"</string>
     <string name="autofill_save_title" msgid="7081244500504163245">"<xliff:g id="LABEL">%1$s</xliff:g> માં સાચવીએ?"</string>
     <string name="autofill_save_title_with_type" msgid="4977385733042555659">"<xliff:g id="TYPE">%1$s</xliff:g> ને <xliff:g id="LABEL">%2$s</xliff:g> માં સાચવીએ?"</string>
-    <!-- no translation found for autofill_save_title_with_2types (8875796560521962098) -->
-    <skip />
-    <!-- no translation found for autofill_save_title_with_3types (6889899028382843493) -->
-    <skip />
+    <string name="autofill_save_title_with_2types" msgid="8875796560521962098">"<xliff:g id="LABEL">%3$s</xliff:g>માં <xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g> સાચવીએ?"</string>
+    <string name="autofill_save_title_with_3types" msgid="6889899028382843493">"<xliff:g id="LABEL">%4$s</xliff:g>માં <xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g>, <xliff:g id="TYPE_2">%3$s</xliff:g> સાચવીએ?"</string>
     <string name="autofill_save_yes" msgid="6398026094049005921">"સાચવો"</string>
     <string name="autofill_save_no" msgid="2625132258725581787">"નહીં આભાર"</string>
     <string name="autofill_save_type_password" msgid="5288448918465971568">"પાસવર્ડ"</string>
diff --git a/core/res/res/values-mr/strings.xml b/core/res/res/values-mr/strings.xml
index 4769676..43c18da7 100644
--- a/core/res/res/values-mr/strings.xml
+++ b/core/res/res/values-mr/strings.xml
@@ -1736,10 +1736,8 @@
     <string name="autofill_error_cannot_autofill" msgid="7402758580060110371">"सामग्रींची स्‍वयं-भरणा करता येणार नाही"</string>
     <string name="autofill_save_title" msgid="7081244500504163245">"<xliff:g id="LABEL">%1$s</xliff:g> वर जतन करायचे?"</string>
     <string name="autofill_save_title_with_type" msgid="4977385733042555659">"<xliff:g id="LABEL">%2$s</xliff:g> वर <xliff:g id="TYPE">%1$s</xliff:g> जतन करायचे?"</string>
-    <!-- no translation found for autofill_save_title_with_2types (8875796560521962098) -->
-    <skip />
-    <!-- no translation found for autofill_save_title_with_3types (6889899028382843493) -->
-    <skip />
+    <string name="autofill_save_title_with_2types" msgid="8875796560521962098">"<xliff:g id="LABEL">%3$s</xliff:g> वर <xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g> जतन करायचे का?"</string>
+    <string name="autofill_save_title_with_3types" msgid="6889899028382843493">"<xliff:g id="LABEL">%4$s</xliff:g> वर <xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g>, <xliff:g id="TYPE_2">%3$s</xliff:g> जतन करायचे का?"</string>
     <string name="autofill_save_yes" msgid="6398026094049005921">"जतन करा"</string>
     <string name="autofill_save_no" msgid="2625132258725581787">"नाही धन्यवाद"</string>
     <string name="autofill_save_type_password" msgid="5288448918465971568">"संकेतशब्द"</string>
diff --git a/core/res/res/values-my/strings.xml b/core/res/res/values-my/strings.xml
index 5252422..dd71d43 100644
--- a/core/res/res/values-my/strings.xml
+++ b/core/res/res/values-my/strings.xml
@@ -1737,7 +1737,7 @@
     <string name="autofill_save_title" msgid="7081244500504163245">"<xliff:g id="LABEL">%1$s</xliff:g> သို့ သိမ်းဆည်းလိုပါသလား။"</string>
     <string name="autofill_save_title_with_type" msgid="4977385733042555659">"<xliff:g id="TYPE">%1$s</xliff:g> ကို <xliff:g id="LABEL">%2$s</xliff:g> သို့ သိမ်းဆည်းလိုပါသလား။"</string>
     <string name="autofill_save_title_with_2types" msgid="8875796560521962098">"<xliff:g id="TYPE_0">%1$s</xliff:g>၊ <xliff:g id="TYPE_1">%2$s</xliff:g> ကို <xliff:g id="LABEL">%3$s</xliff:g> သို့ သိမ်းဆည်းလိုပါသလား။"</string>
-    <string name="autofill_save_title_with_3types" msgid="6889899028382843493">"<xliff:g id="TYPE_0">%1$s</xliff:g>၊ <xliff:g id="TYPE_1">%2$s</xliff:g>၊ <xliff:g id="TYPE_2">%3$s</xliff:g> ကို <xliff:g id="LABEL">%4$s</xliff:g>သို့ သိမ်းဆည်းလိုပါသလား။"</string>
+    <string name="autofill_save_title_with_3types" msgid="6889899028382843493">"<xliff:g id="TYPE_0">%1$s</xliff:g>၊ <xliff:g id="TYPE_1">%2$s</xliff:g>၊ <xliff:g id="TYPE_2">%3$s</xliff:g> ကို <xliff:g id="LABEL">%4$s</xliff:g> သို့ သိမ်းဆည်းလိုပါသလား။"</string>
     <string name="autofill_save_yes" msgid="6398026094049005921">"သိမ်းရန်"</string>
     <string name="autofill_save_no" msgid="2625132258725581787">"မလိုပါ"</string>
     <string name="autofill_save_type_password" msgid="5288448918465971568">"စကားဝှက်"</string>
diff --git a/core/res/res/values-pa/strings.xml b/core/res/res/values-pa/strings.xml
index 71fd285..702e2fb 100644
--- a/core/res/res/values-pa/strings.xml
+++ b/core/res/res/values-pa/strings.xml
@@ -1733,7 +1733,7 @@
     <string name="time_picker_text_input_mode_description" msgid="4148166758173708199">"ਸਮਾਂ ਇਨਪੁੱਟ ਕਰਨ ਲਈ ਲਿਖਤ ਇਨਪੁੱਟ ਮੋਡ \'ਤੇ ਬਦਲੀ ਕਰੋ।"</string>
     <string name="time_picker_radial_mode_description" msgid="4953403779779557198">"ਸਮਾਂ ਇਨਪੁੱਟ ਕਰਨ ਲਈ ਘੜੀ ਮੋਡ \'ਤੇ ਬਦਲੀ ਕਰੋ।"</string>
     <string name="autofill_picker_accessibility_title" msgid="8469043291648711535">"ਆਟੋਫਿਲ ਵਿਕਲਪ"</string>
-    <string name="autofill_error_cannot_autofill" msgid="7402758580060110371">"ਸਮੱਗਰੀਆਂ ਆਟੋਫਿਲ ਨਹੀਂ ਕੀਤਾ ਜਾ ਸਕਦਾ"</string>
+    <string name="autofill_error_cannot_autofill" msgid="7402758580060110371">"ਸਮੱਗਰੀਆਂ ਨੂੰ ਆਟੋਫਿਲ ਨਹੀਂ ਕੀਤਾ ਜਾ ਸਕਦਾ"</string>
     <string name="autofill_save_title" msgid="7081244500504163245">"<xliff:g id="LABEL">%1$s</xliff:g> ਵਿੱਚ ਰੱਖਿਅਤ ਕਰੀਏ?"</string>
     <string name="autofill_save_title_with_type" msgid="4977385733042555659">"<xliff:g id="TYPE">%1$s</xliff:g> ਨੂੰ <xliff:g id="LABEL">%2$s</xliff:g> ਵਿੱਚ ਰੱਖਿਅਤ ਕਰੀਏ?"</string>
     <string name="autofill_save_title_with_2types" msgid="8875796560521962098">"<xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g> ਨੂੰ <xliff:g id="LABEL">%3$s</xliff:g> ਵਿੱਚ ਰੱਖਿਅਤ ਕਰੀਏ?"</string>
diff --git a/core/res/res/values-ru/strings.xml b/core/res/res/values-ru/strings.xml
index 3ac621a..e32823f 100644
--- a/core/res/res/values-ru/strings.xml
+++ b/core/res/res/values-ru/strings.xml
@@ -322,7 +322,7 @@
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Приложение получит доступ к сообщениям широковещательных SMS-служб, которые в некоторых странах используются для информирования населения об экстренных ситуациях. Вредоносные программы могут помешать работе устройства, на которое поступают такие сообщения."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"Просмотр фидов пользователя"</string>
     <string name="permdesc_subscribedFeedsRead" msgid="5557058907906144505">"Приложение сможет получать сведения о синхронизируемых в настоящее время фидах."</string>
-    <string name="permlab_sendSms" msgid="7544599214260982981">"отправка и просмотр SMS-сообщений"</string>
+    <string name="permlab_sendSms" msgid="7544599214260982981">"Отправка и просмотр SMS-сообщений"</string>
     <string name="permdesc_sendSms" msgid="7094729298204937667">"Приложение сможет отправлять SMS. Учтите, что вредоносные программы смогут отправлять сообщения без уведомления, что может привести к непредвиденным расходам."</string>
     <string name="permlab_readSms" msgid="8745086572213270480">"Просмотр SMS и MMS"</string>
     <string name="permdesc_readSms" product="tablet" msgid="4741697454888074891">"Приложение может считывать SMS-сообщения на планшете."</string>
@@ -378,7 +378,7 @@
     <string name="permdesc_writeCallLog" product="default" msgid="683941736352787842">"Приложение сможет вносить изменения в список вызовов телефона и данные о входящих и исходящих звонках. Вредоносные приложения смогут воспользоваться этим для удаления или изменения информации о звонках."</string>
     <string name="permlab_bodySensors" msgid="4683341291818520277">"Датчики (например, пульсометр)"</string>
     <string name="permdesc_bodySensors" product="default" msgid="4380015021754180431">"Приложение сможет получить доступ к данным датчиков, размещенных на теле, например измеряющих частоту сердцебиения."</string>
-    <string name="permlab_readCalendar" msgid="6716116972752441641">"Просмотр мероприятий и других данных календаря"</string>
+    <string name="permlab_readCalendar" msgid="6716116972752441641">"Чтение мероприятий и данных"</string>
     <string name="permdesc_readCalendar" product="tablet" msgid="4993979255403945892">"Приложение может считывать, отправлять и сохранять информацию о мероприятиях в календаре планшета."</string>
     <string name="permdesc_readCalendar" product="tv" msgid="8837931557573064315">"Приложение может считывать, отправлять и сохранять информацию о мероприятиях в календаре телевизора."</string>
     <string name="permdesc_readCalendar" product="default" msgid="4373978642145196715">"Приложение может считывать, отправлять и сохранять информацию о мероприятиях в календаре телефона."</string>
@@ -467,7 +467,7 @@
     <string name="permdesc_bluetooth" product="tv" msgid="3974124940101104206">"Доступ к настройкам Bluetooth на телевизоре, установка соединений с сопряженными устройствами и принятие запросов на подключение."</string>
     <string name="permdesc_bluetooth" product="default" msgid="3207106324452312739">"Приложение сможет просматривать конфигурацию Bluetooth на телефоне, а также запрашивать и подтверждать соединение с другими устройствами."</string>
     <string name="permlab_nfc" msgid="4423351274757876953">"Управление NFC-модулем"</string>
-    <string name="permdesc_nfc" msgid="7120611819401789907">"Приложение сможет обмениваться данными с NFC-метками, картами и устройствами считывания, используя связь малого радиуса действия."</string>
+    <string name="permdesc_nfc" msgid="7120611819401789907">"Приложение сможет обмениваться данными с NFC-метками, картами и устройствами считывания, используя NFC."</string>
     <string name="permlab_disableKeyguard" msgid="3598496301486439258">"Отключение функции блокировки экрана"</string>
     <string name="permdesc_disableKeyguard" msgid="6034203065077122992">"Приложение сможет отключать блокировку экрана и другие функции защиты. Например, блокировка экрана будет отключаться при получении входящего вызова и включаться после завершения разговора."</string>
     <string name="permlab_manageFingerprint" msgid="5640858826254575638">"управление сканером отпечатков"</string>
diff --git a/core/res/res/values-sr/strings.xml b/core/res/res/values-sr/strings.xml
index 6e13582..6dc7761 100644
--- a/core/res/res/values-sr/strings.xml
+++ b/core/res/res/values-sr/strings.xml
@@ -837,7 +837,7 @@
     <string name="permlab_addVoicemail" msgid="5525660026090959044">"додавање говорне поште"</string>
     <string name="permdesc_addVoicemail" msgid="6604508651428252437">"Дозвољава апликацији да додаје поруке у пријемно сандуче говорне поште."</string>
     <string name="permlab_writeGeolocationPermissions" msgid="5962224158955273932">"измена дозвола за географске локације Прегледача"</string>
-    <string name="permdesc_writeGeolocationPermissions" msgid="1083743234522638747">"Дозвољава апликацији да измени дозволе Прегледача за утврђивање географске локације. Злонамерне апликације то могу да злоупотребе и искористе за слање информација о локацији насумичним веб сајтовима."</string>
+    <string name="permdesc_writeGeolocationPermissions" msgid="1083743234522638747">"Дозвољава апликацији да измени дозволе Прегледача за утврђивање географске локације. Злонамерне апликације то могу да злоупотребе и искористе за слање информација о локацији насумичним веб-сајтовима."</string>
     <string name="save_password_message" msgid="767344687139195790">"Желите ли да прегледач запамти ову лозинку?"</string>
     <string name="save_password_notnow" msgid="6389675316706699758">"Не сада"</string>
     <string name="save_password_remember" msgid="6491879678996749466">"Запамти"</string>
diff --git a/core/res/res/values-sw/strings.xml b/core/res/res/values-sw/strings.xml
index 664a038..d104bb7 100644
--- a/core/res/res/values-sw/strings.xml
+++ b/core/res/res/values-sw/strings.xml
@@ -181,7 +181,7 @@
     <string name="work_profile_deleted_details" msgid="6307630639269092360">"Programu ya msimamizi wa wasifu wa kazini imepotea au ina hitilafu. Kwa sababu hiyo, wasifu wako wa kazini na data husika imefutwa. Wasiliana na msimamizi wako kwa usaidizi."</string>
     <string name="work_profile_deleted_description_dpm_wipe" msgid="8823792115612348820">"Wasifu wako wa kazini haupatikani tena kwenye kifaa hiki"</string>
     <string name="network_logging_notification_title" msgid="6399790108123704477">"Kifaa kinadhibitiwa"</string>
-    <string name="network_logging_notification_text" msgid="7930089249949354026">"Shirika lako linadhibiti kifaa hiki na huenda likafuatilia trafiki ya mtandao. Gonga ili upate maelezo zaidi."</string>
+    <string name="network_logging_notification_text" msgid="7930089249949354026">"Shirika lako linadhibiti kifaa hiki na huenda likafuatilia shughuli kwenye mtandao. Gonga ili upate maelezo zaidi."</string>
     <string name="factory_reset_warning" msgid="5423253125642394387">"Data iliyomo kwenye kifaa chako itafutwa"</string>
     <string name="factory_reset_message" msgid="7972496262232832457">"Huwezi kutumia programu ya msimamizi. Sasa data iliyo kwenye kifaa chako itafutwa.\n\nIkiwa una maswali yoyote, wasiliana na msimamizi wa shirika lako."</string>
     <string name="me" msgid="6545696007631404292">"Mimi"</string>
@@ -277,7 +277,7 @@
     <string name="permgrouplab_phone" msgid="5229115638567440675">"Simu"</string>
     <string name="permgroupdesc_phone" msgid="6234224354060641055">"piga na udhibiti simu"</string>
     <string name="permgrouplab_sensors" msgid="416037179223226722">"Vihisi vya Mwili"</string>
-    <string name="permgroupdesc_sensors" msgid="7147968539346634043">"fikia data ya kihisi kuhusu alama zako muhimu"</string>
+    <string name="permgroupdesc_sensors" msgid="7147968539346634043">"fikia data ya kitambuzi kuhusu alama zako muhimu"</string>
     <string name="capability_title_canRetrieveWindowContent" msgid="3901717936930170320">"Rejesha maudhui ya dirisha"</string>
     <string name="capability_desc_canRetrieveWindowContent" msgid="3772225008605310672">"Chunguza maudhui ya dirisha unaloingiliana nalo."</string>
     <string name="capability_title_canRequestTouchExploration" msgid="3108723364676667320">"Washa Chunguza kwa Mguso"</string>
@@ -466,9 +466,9 @@
     <string name="permdesc_manageFingerprint" msgid="178208705828055464">"Huruhusu programu kuomba njia za kuongeza na kufuta violezo vya kitambulisho kwa matumizi."</string>
     <string name="permlab_useFingerprint" msgid="3150478619915124905">"tumia maunzi ya kitambulisho"</string>
     <string name="permdesc_useFingerprint" msgid="9165097460730684114">"Huruhusu programu kutumia maunzi ya kitambulisho kwa uthibitisho"</string>
-    <string name="fingerprint_acquired_partial" msgid="735082772341716043">"Kihisi kimegundua sehemu ya kitambulisho. Tafadhali jaribu tena."</string>
+    <string name="fingerprint_acquired_partial" msgid="735082772341716043">"Kitambuzi kimegundua sehemu ya kitambulisho. Tafadhali jaribu tena."</string>
     <string name="fingerprint_acquired_insufficient" msgid="4596546021310923214">"Haikuweza kuchakata kitambulisho. Tafadhali jaribu tena."</string>
-    <string name="fingerprint_acquired_imager_dirty" msgid="1087209702421076105">"Kihisi kitambulisho ni kichafu. Tafadhali kisafishe na ujaribu tena."</string>
+    <string name="fingerprint_acquired_imager_dirty" msgid="1087209702421076105">"Kitambuzi alama ya kidole ni kichafu. Tafadhali kisafishe na ujaribu tena."</string>
     <string name="fingerprint_acquired_too_fast" msgid="6470642383109155969">"Ulisogeza kidole kwa kasi mno. Tafadhali jaribu tena."</string>
     <string name="fingerprint_acquired_too_slow" msgid="59250885689661653">"Kidole kilisogezwa polepole zaidi. Tafadhali jaribu tena."</string>
   <string-array name="fingerprint_acquired_vendor">
diff --git a/core/res/res/values-uz/strings.xml b/core/res/res/values-uz/strings.xml
index ee2438f..35e4455 100644
--- a/core/res/res/values-uz/strings.xml
+++ b/core/res/res/values-uz/strings.xml
@@ -1733,11 +1733,11 @@
     <string name="time_picker_text_input_mode_description" msgid="4148166758173708199">"Vaqtni kiritish uchun matn kiritish rejimiga o‘ting."</string>
     <string name="time_picker_radial_mode_description" msgid="4953403779779557198">"Vaqtni kiritish uchun soat rejimiga o‘ting."</string>
     <string name="autofill_picker_accessibility_title" msgid="8469043291648711535">"Avtomatik to‘ldirish parametrlari"</string>
-    <string name="autofill_error_cannot_autofill" msgid="7402758580060110371">"Kontentlarni avtomatik to‘ldirib bo‘lmaydi"</string>
+    <string name="autofill_error_cannot_autofill" msgid="7402758580060110371">"Avtomatik to‘ldirib bo‘lmaydi"</string>
     <string name="autofill_save_title" msgid="7081244500504163245">"<xliff:g id="LABEL">%1$s</xliff:g> xizmatiga saqlansinmi?"</string>
     <string name="autofill_save_title_with_type" msgid="4977385733042555659">"<xliff:g id="TYPE">%1$s</xliff:g> <xliff:g id="LABEL">%2$s</xliff:g> xizmatiga saqlansinmi?"</string>
-    <string name="autofill_save_title_with_2types" msgid="8875796560521962098">"<xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g> ma’lumotlari <xliff:g id="LABEL">%3$s</xliff:g> yorlig‘iga saqlansinmi?"</string>
-    <string name="autofill_save_title_with_3types" msgid="6889899028382843493">"<xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g>, <xliff:g id="TYPE_2">%3$s</xliff:g> ma’lumotlari <xliff:g id="LABEL">%4$s</xliff:g> yorlig‘iga saqlansinmi?"</string>
+    <string name="autofill_save_title_with_2types" msgid="8875796560521962098">"<xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g> ma’lumotlari <xliff:g id="LABEL">%3$s</xliff:g> ichiga saqlansinmi?"</string>
+    <string name="autofill_save_title_with_3types" msgid="6889899028382843493">"<xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g>, <xliff:g id="TYPE_2">%3$s</xliff:g> ma’lumotlari <xliff:g id="LABEL">%4$s</xliff:g> ichiga saqlansinmi?"</string>
     <string name="autofill_save_yes" msgid="6398026094049005921">"Saqlash"</string>
     <string name="autofill_save_no" msgid="2625132258725581787">"Yo‘q, kerak emas"</string>
     <string name="autofill_save_type_password" msgid="5288448918465971568">"parol"</string>
diff --git a/core/res/res/values-zh-rCN/strings.xml b/core/res/res/values-zh-rCN/strings.xml
index 1daecdd..2d1a20b 100644
--- a/core/res/res/values-zh-rCN/strings.xml
+++ b/core/res/res/values-zh-rCN/strings.xml
@@ -285,7 +285,7 @@
     <string name="capability_title_canRequestTouchExploration" msgid="3108723364676667320">"启用触摸浏览"</string>
     <string name="capability_desc_canRequestTouchExploration" msgid="7543249041581408313">"设备将大声读出您点按的内容,同时您可以通过手势来浏览屏幕。"</string>
     <string name="capability_title_canRequestEnhancedWebAccessibility" msgid="1739881766522594073">"启用网页无障碍增强功能"</string>
-    <string name="capability_desc_canRequestEnhancedWebAccessibility" msgid="7881063961507511765">"安装脚本以方便访问应用的内容。"</string>
+    <string name="capability_desc_canRequestEnhancedWebAccessibility" msgid="7881063961507511765">"可能会安装程序以便访问应用的内容。"</string>
     <string name="capability_title_canRequestFilterKeyEvents" msgid="2103440391902412174">"监测您输入的文字"</string>
     <string name="capability_desc_canRequestFilterKeyEvents" msgid="7463135292204152818">"包含个人数据,例如信用卡号和密码。"</string>
     <string name="capability_title_canControlMagnification" msgid="3593493281059424855">"控制显示内容放大功能"</string>
@@ -832,7 +832,7 @@
     <string name="permlab_setAlarm" msgid="1379294556362091814">"设置闹钟"</string>
     <string name="permdesc_setAlarm" msgid="316392039157473848">"允许应用在已安装的闹钟应用中设置闹钟。有些闹钟应用可能无法实现此功能。"</string>
     <string name="permlab_addVoicemail" msgid="5525660026090959044">"添加语音邮件"</string>
-    <string name="permdesc_addVoicemail" msgid="6604508651428252437">"允许应用向您的语音信箱收件箱添加邮件。"</string>
+    <string name="permdesc_addVoicemail" msgid="6604508651428252437">"允许应用在您的语音信箱中留言。"</string>
     <string name="permlab_writeGeolocationPermissions" msgid="5962224158955273932">"修改“浏览器”地理位置的权限"</string>
     <string name="permdesc_writeGeolocationPermissions" msgid="1083743234522638747">"允许应用修改“浏览器”的地理位置权限。恶意应用可能借此向任意网站发送位置信息。"</string>
     <string name="save_password_message" msgid="767344687139195790">"是否希望浏览器记住此密码?"</string>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 8682d7d..6e790a7 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -4776,6 +4776,13 @@
         <attr name="autoSizeMinTextSize" format="dimension" />
         <!-- The maximum text size constraint to be used when auto-sizing text. -->
         <attr name="autoSizeMaxTextSize" format="dimension" />
+        <!-- Mode for justification. -->
+        <attr name="justificationMode">
+            <!-- No justification. -->
+            <enum name="none" value="0" />
+            <!-- Justification by stretching word spacing. -->
+            <enum name="inter_word" value = "1" />
+        </attr>
     </declare-styleable>
     <declare-styleable name="TextViewAppearance">
         <!-- Base text color, typeface, size, and style. -->
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 27a4d5c..0fa1fdb 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -2833,4 +2833,34 @@
 
     <!-- Whether the device uses the default focus highlight when focus state isn't specified. -->
     <bool name="config_useDefaultFocusHighlight">true</bool>
+
+    <!-- Configuration for automotive -->
+    <bool name="enable_pbap_pce_profile">false</bool>
+
+    <!-- Default data warning level in mb -->
+    <integer name="default_data_warning_level_mb">2048</integer>
+
+    <!-- Whether to send a custom package name with the PSD.-->
+    <bool name="config_sendPackageName">false</bool>
+
+    <!-- Name for the set of keys associating package names -->
+    <string name="config_helpPackageNameKey" translatable="false"></string>
+
+    <!-- Name for the set of values of package names -->
+    <string name="config_helpPackageNameValue" translatable="false"></string>
+
+    <!-- Intent key for the package name keys -->
+    <string name="config_helpIntentExtraKey" translatable="false"></string>
+
+    <!-- Intent key for package name values -->
+    <string name="config_helpIntentNameKey" translatable="false"></string>
+
+    <!-- Intent key for the package name keys -->
+    <string name="config_feedbackIntentExtraKey" translatable="false"></string>
+
+    <!-- Intent key for package name values -->
+    <string name="config_feedbackIntentNameKey" translatable="false"></string>
+
+    <!-- The apps that need to be hidden when they are disabled -->
+    <string-array name="config_hideWhenDisabled_packageNames"></string-array>
 </resources>
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 89c912fd..e13026b 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -2821,6 +2821,7 @@
         <public name="requiredSystemPropertyName" />
         <!-- @hide @SystemApi -->
         <public name="requiredSystemPropertyValue" />
+        <public name="justificationMode" />
     </public-group>
 
     <public-group type="style" first-id="0x010302e0">
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index bd35073..a5181fe 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -212,6 +212,21 @@
     <!-- Displayed to tell the user that they should switch their network preference. -->
     <string name="NetworkPreferenceSwitchSummary">To improve reception, try changing the type selected at System &gt; Network &amp; Internet &gt; Mobile networks &gt; Preferred network type."</string>
 
+    <!-- Telephony notification channel name for a channel containing network alert notifications. -->
+    <string name="notification_channel_network_alert">Alerts</string>
+    <!-- Telephony notification channel name for a channel containing call forwarding notifications. -->
+    <string name="notification_channel_call_forward">Call forwarding</string>
+    <!-- Telephony notification channel name for a channel containing emergency callback mode notifications. -->
+    <string name="notification_channel_emergency_callback">Emergency callback mode</string>
+    <!-- Telephony notification channel name for a channel containing mobile data alert notifications. -->
+    <string name="notification_channel_mobile_data_alert">Mobile data alerts</string>
+    <!-- Telephony notification channel name for a channel containing sms notifications. -->
+    <string name="notification_channel_sms">SMS messages</string>
+    <!-- Telephony notification channel name for a channel containing voice mail notifications. -->
+    <string name="notification_channel_voice_mail">Voicemail messages</string>
+    <!-- Telephony notification channel name for a channel containing wifi calling status notifications. -->
+    <string name="notification_channel_wfc">Wi-Fi calling</string>
+
     <!-- Displayed to tell the user that peer changed TTY mode -->
     <string name="peerTtyModeFull">Peer requested TTY Mode FULL</string>
     <string name="peerTtyModeHco">Peer requested TTY Mode HCO</string>
@@ -4587,23 +4602,26 @@
     <!-- Accessibility title for the autofill dialog used to select a list of options to autofill an activity. [CHAR LIMIT=NONE] -->
     <string name="autofill_picker_accessibility_title">Autofill options</string>
 
+    <!-- Accessibility title for the autofill dialog used to ask user to save the information on the screen by sending it to an Autofill Service. [CHAR LIMIT=NONE] -->
+    <string name="autofill_save_accessibility_title">Save for Autofill</string>
+
     <!-- Toast message shown when user manually request autofill but service could not figure out the data that would autofill the screen contents. [CHAR LIMIT=NONE] -->
     <string name="autofill_error_cannot_autofill">Contents can\u2019t be autofilled</string>
 
     <!-- Title for the autofill save dialog shown when the the contents of the activity can be saved
          by an autofill service, but the service does not know what the activity represents [CHAR LIMIT=NONE] -->
-    <string name="autofill_save_title">Save to <xliff:g id="label" example="MyPass">%1$s</xliff:g>?</string>
+    <string name="autofill_save_title">Save to &lt;b><xliff:g id="label" example="MyPass">%1$s</xliff:g>&lt;/b>?</string>
     <!-- Title for the autofill save dialog shown when the the contents of the activity can be saved
          by an autofill service, and the service does knows what the activity represents (for example, credit card info) [CHAR LIMIT=NONE] -->
-    <string name="autofill_save_title_with_type">Save <xliff:g id="type" example="Credit Card">%1$s</xliff:g> to <xliff:g id="label" example="MyPass">%2$s</xliff:g>?</string>
+    <string name="autofill_save_title_with_type">Save <xliff:g id="type" example="Credit Card">%1$s</xliff:g> to &lt;b><xliff:g id="label" example="MyPass">%2$s</xliff:g>&lt;/b>?</string>
     <!-- Title for the autofill save dialog shown when the the contents of the activity can be saved
          by an autofill service, and the service does knows what the activity represents, and it represents 2 types of
          data (for example, password and credit card info) [CHAR LIMIT=NONE] -->
-    <string name="autofill_save_title_with_2types">Save <xliff:g id="type" example="Password">%1$s</xliff:g>, <xliff:g id="type" example="Credit Card">%2$s</xliff:g> to <xliff:g id="label" example="MyPass">%3$s</xliff:g>?</string>
+    <string name="autofill_save_title_with_2types">Save <xliff:g id="type" example="Password">%1$s</xliff:g> and <xliff:g id="type" example="Credit Card">%2$s</xliff:g> to &lt;b><xliff:g id="label" example="MyPass">%3$s</xliff:g>&lt;/b>?</string>
     <!-- Title for the autofill save dialog shown when the the contents of the activity can be saved
          by an autofill service, and the service does knows what the activity represents, and it represents 3 types of
          data (for example, username, password and credit card info) [CHAR LIMIT=NONE] -->
-    <string name="autofill_save_title_with_3types">Save <xliff:g id="type" example="Username">%1$s</xliff:g>, <xliff:g id="type" example="Password">%2$s</xliff:g>, <xliff:g id="type" example="Credit Card">%3$s</xliff:g> to <xliff:g id="label" example="MyPass">%4$s</xliff:g>?</string>
+    <string name="autofill_save_title_with_3types">Save <xliff:g id="type" example="Username">%1$s</xliff:g>, <xliff:g id="type" example="Password">%2$s</xliff:g>, and <xliff:g id="type" example="Credit Card">%3$s</xliff:g> to &lt;b><xliff:g id="label" example="MyPass">%4$s</xliff:g>&lt;/b>?</string>
     <!-- Label for the autofill save button [CHAR LIMIT=NONE] -->
     <string name="autofill_save_yes">Save</string>
     <!-- Label for the autofill cancel button [CHAR LIMIT=NONE] -->
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 1dd8227..63a5cfd7 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -523,6 +523,13 @@
   <java-symbol type="string" name="RestrictedOnDataContent" />
   <java-symbol type="string" name="RestrictedOnEmergencyContent" />
   <java-symbol type="string" name="RestrictedOnNormalContent" />
+  <java-symbol type="string" name="notification_channel_network_alert" />
+  <java-symbol type="string" name="notification_channel_call_forward" />
+  <java-symbol type="string" name="notification_channel_emergency_callback" />
+  <java-symbol type="string" name="notification_channel_mobile_data_alert" />
+  <java-symbol type="string" name="notification_channel_sms" />
+  <java-symbol type="string" name="notification_channel_voice_mail" />
+  <java-symbol type="string" name="notification_channel_wfc" />
   <java-symbol type="string" name="SetupCallDefault" />
   <java-symbol type="string" name="accept" />
   <java-symbol type="string" name="activity_chooser_view_see_all" />
@@ -2886,6 +2893,7 @@
   <java-symbol type="string" name="autofill_error_cannot_autofill" />
   <java-symbol type="string" name="autofill" />
   <java-symbol type="string" name="autofill_picker_accessibility_title " />
+  <java-symbol type="string" name="autofill_save_accessibility_title " />
   <java-symbol type="string" name="autofill_save_title" />
   <java-symbol type="string" name="autofill_save_title_with_type" />
   <java-symbol type="string" name="autofill_save_title_with_2types" />
@@ -2976,4 +2984,18 @@
   <java-symbol type="bool" name="config_quickSettingsSupported" />
 
   <java-symbol type="style" name="Theme.DeviceDefault.QuickSettings" />
+
+  <java-symbol type="bool" name="enable_pbap_pce_profile" />
+
+  <java-symbol type="integer" name="default_data_warning_level_mb" />
+
+  <java-symbol type="bool" name="config_sendPackageName" />
+  <java-symbol type="string" name="config_helpPackageNameKey" />
+  <java-symbol type="string" name="config_helpPackageNameValue" />
+  <java-symbol type="string" name="config_helpIntentExtraKey" />
+  <java-symbol type="string" name="config_helpIntentNameKey" />
+  <java-symbol type="string" name="config_feedbackIntentExtraKey" />
+  <java-symbol type="string" name="config_feedbackIntentNameKey" />
+
+  <java-symbol type="array" name="config_hideWhenDisabled_packageNames" />
 </resources>
diff --git a/core/tests/coretests/AndroidManifest.xml b/core/tests/coretests/AndroidManifest.xml
index 5669189..94a515b 100644
--- a/core/tests/coretests/AndroidManifest.xml
+++ b/core/tests/coretests/AndroidManifest.xml
@@ -1266,6 +1266,11 @@
             <meta-data android:name="com.android.frameworks.coretests.reference" android:resource="@xml/metadata" />
         </provider>
 
+        <provider android:name="android.provider.MockFontProvider"
+                  android:authorities="android.provider.fonts.font"
+                  android:exported="false"
+                  android:multiprocess="true" />
+
         <!-- Application components used for content tests -->
         <provider android:name="android.content.MemoryFileProvider"
                 android:authorities="android.content.MemoryFileProvider"
diff --git a/core/tests/coretests/assets/fonts/samplefont1.ttf b/core/tests/coretests/assets/fonts/samplefont1.ttf
new file mode 100644
index 0000000..020436a
--- /dev/null
+++ b/core/tests/coretests/assets/fonts/samplefont1.ttf
Binary files differ
diff --git a/core/tests/coretests/assets/fonts/samplefont1.ttx b/core/tests/coretests/assets/fonts/samplefont1.ttx
new file mode 100644
index 0000000..40fa268
--- /dev/null
+++ b/core/tests/coretests/assets/fonts/samplefont1.ttx
@@ -0,0 +1,177 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- 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.
+-->
+<ttFont sfntVersion="\x00\x01\x00\x00" ttLibVersion="3.0">
+
+  <GlyphOrder>
+    <GlyphID id="0" name=".notdef"/>
+    <GlyphID id="1" name="a"/>
+  </GlyphOrder>
+
+  <head>
+    <tableVersion value="1.0"/>
+    <fontRevision value="1.0"/>
+    <checkSumAdjustment value="0x640cdb2f"/>
+    <magicNumber value="0x5f0f3cf5"/>
+    <flags value="00000000 00000011"/>
+    <unitsPerEm value="1000"/>
+    <created value="Fri Mar 17 07:26:00 2017"/>
+    <macStyle value="00000000 00000000"/>
+    <lowestRecPPEM value="7"/>
+    <fontDirectionHint value="2"/>
+    <glyphDataFormat value="0"/>
+  </head>
+
+  <hhea>
+    <tableVersion value="1.0"/>
+    <ascent value="1000"/>
+    <descent value="-200"/>
+    <lineGap value="0"/>
+    <caretSlopeRise value="1"/>
+    <caretSlopeRun value="0"/>
+    <caretOffset value="0"/>
+    <reserved0 value="0"/>
+    <reserved1 value="0"/>
+    <reserved2 value="0"/>
+    <reserved3 value="0"/>
+    <metricDataFormat value="0"/>
+  </hhea>
+
+  <maxp>
+    <tableVersion value="0x10000"/>
+    <maxZones value="0"/>
+    <maxTwilightPoints value="0"/>
+    <maxStorage value="0"/>
+    <maxFunctionDefs value="0"/>
+    <maxInstructionDefs value="0"/>
+    <maxStackElements value="0"/>
+    <maxSizeOfInstructions value="0"/>
+    <maxComponentElements value="0"/>
+  </maxp>
+
+  <OS_2>
+    <!-- The fields 'usFirstCharIndex' and 'usLastCharIndex'
+         will be recalculated by the compiler -->
+    <version value="3"/>
+    <xAvgCharWidth value="594"/>
+    <usWeightClass value="400"/>
+    <usWidthClass value="5"/>
+    <fsType value="00000000 00001000"/>
+    <ySubscriptXSize value="650"/>
+    <ySubscriptYSize value="600"/>
+    <ySubscriptXOffset value="0"/>
+    <ySubscriptYOffset value="75"/>
+    <ySuperscriptXSize value="650"/>
+    <ySuperscriptYSize value="600"/>
+    <ySuperscriptXOffset value="0"/>
+    <ySuperscriptYOffset value="350"/>
+    <yStrikeoutSize value="50"/>
+    <yStrikeoutPosition value="300"/>
+    <sFamilyClass value="0"/>
+    <panose>
+      <bFamilyType value="0"/>
+      <bSerifStyle value="0"/>
+      <bWeight value="5"/>
+      <bProportion value="0"/>
+      <bContrast value="0"/>
+      <bStrokeVariation value="0"/>
+      <bArmStyle value="0"/>
+      <bLetterForm value="0"/>
+      <bMidline value="0"/>
+      <bXHeight value="0"/>
+    </panose>
+    <ulUnicodeRange1 value="00000000 00000000 00000000 00000001"/>
+    <ulUnicodeRange2 value="00000000 00000000 00000000 00000000"/>
+    <ulUnicodeRange3 value="00000000 00000000 00000000 00000000"/>
+    <ulUnicodeRange4 value="00000000 00000000 00000000 00000000"/>
+    <achVendID value="UKWN"/>
+    <fsSelection value="00000000 01000000"/>
+    <usFirstCharIndex value="32"/>
+    <usLastCharIndex value="122"/>
+    <sTypoAscender value="800"/>
+    <sTypoDescender value="-200"/>
+    <sTypoLineGap value="200"/>
+    <usWinAscent value="1000"/>
+    <usWinDescent value="200"/>
+    <ulCodePageRange1 value="00000000 00000000 00000000 00000001"/>
+    <ulCodePageRange2 value="00000000 00000000 00000000 00000000"/>
+    <sxHeight value="500"/>
+    <sCapHeight value="700"/>
+    <usDefaultChar value="0"/>
+    <usBreakChar value="32"/>
+    <usMaxContext value="0"/>
+  </OS_2>
+
+  <hmtx>
+    <mtx name=".notdef" width="500" lsb="93"/>
+    <mtx name="a" width="500" lsb="93"/>
+  </hmtx>
+
+  <cmap>
+    <tableVersion version="0"/>
+    <cmap_format_4 platformID="3" platEncID="10" language="0">
+      <map code="0x0061" name="a" />
+    </cmap_format_4>
+  </cmap>
+
+  <loca>
+    <!-- The 'loca' table will be calculated by the compiler -->
+  </loca>
+
+  <glyf>
+    <TTGlyph name=".notdef" xMin="0" yMin="0" xMax="0" yMax="0" />
+    <TTGlyph name="a" xMin="0" yMin="0" xMax="0" yMax="0" />
+  </glyf>
+
+  <name>
+    <namerecord nameID="1" platformID="1" platEncID="0" langID="0x0" unicode="True">
+      Sample Font
+    </namerecord>
+    <namerecord nameID="2" platformID="1" platEncID="0" langID="0x0" unicode="True">
+      Regular
+    </namerecord>
+    <namerecord nameID="4" platformID="1" platEncID="0" langID="0x0" unicode="True">
+      Sample Font
+    </namerecord>
+    <namerecord nameID="6" platformID="1" platEncID="0" langID="0x0" unicode="True">
+      SampleFont-Regular
+    </namerecord>
+    <namerecord nameID="1" platformID="3" platEncID="1" langID="0x409">
+      Sample Font
+    </namerecord>
+    <namerecord nameID="2" platformID="3" platEncID="1" langID="0x409">
+      Regular
+    </namerecord>
+    <namerecord nameID="4" platformID="3" platEncID="1" langID="0x409">
+      Sample Font
+    </namerecord>
+    <namerecord nameID="6" platformID="3" platEncID="1" langID="0x409">
+      SampleFont-Regular
+    </namerecord>
+  </name>
+
+  <post>
+    <formatType value="3.0"/>
+    <italicAngle value="0.0"/>
+    <underlinePosition value="-75"/>
+    <underlineThickness value="50"/>
+    <isFixedPitch value="0"/>
+    <minMemType42 value="0"/>
+    <maxMemType42 value="0"/>
+    <minMemType1 value="0"/>
+    <maxMemType1 value="0"/>
+  </post>
+
+</ttFont>
diff --git a/core/tests/coretests/src/android/provider/FontsContractE2ETest.java b/core/tests/coretests/src/android/provider/FontsContractE2ETest.java
new file mode 100644
index 0000000..479f6dd
--- /dev/null
+++ b/core/tests/coretests/src/android/provider/FontsContractE2ETest.java
@@ -0,0 +1,175 @@
+/*
+ * 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.
+ */
+
+package android.provider;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertNotSame;
+
+import android.app.Instrumentation;
+import android.content.pm.Signature;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.PackageInfo;
+import android.content.Context;
+import android.graphics.Typeface;
+import android.graphics.fonts.FontRequest;
+import android.provider.FontsContract;
+import android.provider.FontsContract.FontFamilyResult;
+import android.provider.FontsContract.FontInfo;
+import android.provider.FontsContract.Columns;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.os.Handler;
+import java.util.List;
+import java.util.ArrayList;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class FontsContractE2ETest {
+    private static final String AUTHORITY = "android.provider.fonts.font";
+    private static final String PACKAGE = "com.android.frameworks.coretests";
+
+    // Signature to be used for authentication to access content provider.
+    // In this test case, the content provider and consumer live in the same package, self package's
+    // signature works.
+    private static List<List<byte[]>> SIGNATURE;
+    static {
+        final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        try {
+            PackageManager manager = context.getPackageManager();
+            PackageInfo info = manager.getPackageInfo(
+                    context.getPackageName(), PackageManager.GET_SIGNATURES);
+            ArrayList<byte[]> out = new ArrayList<>();
+            for (Signature sig : info.signatures) {
+                out.add(sig.toByteArray());
+            }
+            SIGNATURE = new ArrayList<>();
+            SIGNATURE.add(out);
+        } catch (PackageManager.NameNotFoundException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Before
+    public void setUp() {
+        MockFontProvider.prepareFontFiles(
+                InstrumentationRegistry.getInstrumentation().getTargetContext());
+    }
+
+    @After
+    public void tearDown() {
+        MockFontProvider.cleanUpFontFiles(
+                InstrumentationRegistry.getInstrumentation().getTargetContext());
+    }
+
+    private static class TestCallback extends FontsContract.FontRequestCallback {
+        private Typeface mTypeface;
+
+        private int mSuccessCallCount;
+        private int mFailedCallCount;
+
+        public void onTypefaceRetrieved(Typeface typeface) {
+            mTypeface = typeface;
+            mSuccessCallCount++;
+        }
+
+        public void onTypefaceRequestFailed(int reason) {
+            mFailedCallCount++;
+        }
+
+        public Typeface getTypeface() {
+            return mTypeface;
+        }
+
+        public int getSuccessCallCount() {
+            return mSuccessCallCount;
+        }
+
+        public int getFailedCallCount() {
+            return mFailedCallCount;
+        }
+    }
+
+    @Test
+    public void typefaceCacheTest() throws NameNotFoundException {
+        Instrumentation inst = InstrumentationRegistry.getInstrumentation();
+        Context ctx = inst.getTargetContext();
+
+        final TestCallback callback = new TestCallback();
+        inst.runOnMainSync(() -> {
+            FontRequest request = new FontRequest(
+                    AUTHORITY, PACKAGE, "singleFontFamily", SIGNATURE);
+            FontsContract.requestFont(ctx, request, callback, new Handler());
+        });
+        inst.waitForIdleSync();
+        assertEquals(1, callback.getSuccessCallCount());
+        assertEquals(0, callback.getFailedCallCount());
+        assertNotNull(callback.getTypeface());
+
+        final TestCallback callback2 = new TestCallback();
+        inst.runOnMainSync(() -> {
+            FontRequest request = new FontRequest(
+                    AUTHORITY, PACKAGE, "singleFontFamily", SIGNATURE);
+            FontsContract.requestFont(ctx, request, callback2, new Handler());
+        });
+        inst.waitForIdleSync();
+        assertEquals(1, callback2.getSuccessCallCount());
+        assertEquals(0, callback2.getFailedCallCount());
+        assertSame(callback.getTypeface(), callback2.getTypeface());
+
+        final TestCallback callback3 = new TestCallback();
+        inst.runOnMainSync(() -> {
+            FontRequest request = new FontRequest(
+                    AUTHORITY, PACKAGE, "singleFontFamily2", SIGNATURE);
+            FontsContract.requestFont(ctx, request, callback3, new Handler());
+        });
+        inst.waitForIdleSync();
+        assertEquals(1, callback3.getSuccessCallCount());
+        assertEquals(0, callback3.getFailedCallCount());
+        assertNotSame(callback.getTypeface(), callback3.getTypeface());
+    }
+
+    @Test
+    public void typefaceNotCacheTest() throws NameNotFoundException {
+        Instrumentation inst = InstrumentationRegistry.getInstrumentation();
+        Context ctx = inst.getTargetContext();
+
+        FontRequest request = new FontRequest(
+                AUTHORITY, PACKAGE, "singleFontFamily", SIGNATURE);
+        FontFamilyResult result = FontsContract.fetchFonts(
+                ctx, null /* cancellation signal */, request);
+        assertEquals(FontFamilyResult.STATUS_OK, result.getStatusCode());
+        Typeface typeface = FontsContract.buildTypeface(
+                ctx, null /* cancellation signal */, result.getFonts());
+
+        FontFamilyResult result2 = FontsContract.fetchFonts(
+                ctx, null /* cancellation signal */, request);
+        assertEquals(FontFamilyResult.STATUS_OK, result2.getStatusCode());
+        Typeface typeface2 = FontsContract.buildTypeface(
+                ctx, null /* cancellation signal */, result2.getFonts());
+
+        // Neighter fetchFonts nor buildTypeface should cache the Typeface.
+        assertNotSame(typeface, typeface2);
+    }
+}
diff --git a/core/tests/coretests/src/android/provider/MockFontProvider.java b/core/tests/coretests/src/android/provider/MockFontProvider.java
new file mode 100644
index 0000000..339d5c3
--- /dev/null
+++ b/core/tests/coretests/src/android/provider/MockFontProvider.java
@@ -0,0 +1,202 @@
+/*
+ * 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.
+ */
+package android.provider;
+
+import static android.provider.FontsContract.Columns;
+
+import android.content.ContentProvider;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.res.AssetFileDescriptor;
+import android.content.res.AssetManager;
+import android.database.Cursor;
+import android.database.MatrixCursor;
+import android.graphics.fonts.FontVariationAxis;
+import android.net.Uri;
+import android.os.CancellationSignal;
+import android.os.ParcelFileDescriptor;
+import android.util.SparseArray;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.io.File;
+import java.nio.file.Files;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.FileNotFoundException;
+import java.nio.file.StandardCopyOption;
+
+public class MockFontProvider extends ContentProvider {
+    final static String AUTHORITY = "android.provider.fonts.font";
+
+    final static String[] FONT_FILES = {
+        "samplefont1.ttf",
+    };
+    private static final int SAMPLE_FONT_FILE_0_ID = 0;
+    private static final int SAMPLE_FONT_FILE_1_ID = 1;
+
+    static class Font {
+        public Font(int id, int fileId, int ttcIndex, String varSettings, int weight, int italic,
+                int resultCode) {
+            mId = id;
+            mFileId = fileId;
+            mTtcIndex = ttcIndex;
+            mVarSettings = varSettings;
+            mWeight = weight;
+            mItalic = italic;
+            mResultCode = resultCode;
+        }
+
+        public int getId() {
+            return mId;
+        }
+
+        public int getTtcIndex() {
+            return mTtcIndex;
+        }
+
+        public String getVarSettings() {
+            return mVarSettings;
+        }
+
+        public int getWeight() {
+            return mWeight;
+        }
+
+        public int getItalic() {
+            return mItalic;
+        }
+
+        public int getResultCode() {
+            return mResultCode;
+        }
+
+        public int getFileId() {
+            return mFileId;
+        }
+
+        private int mId;
+        private int mFileId;
+        private int mTtcIndex;
+        private String mVarSettings;
+        private int mWeight;
+        private int mItalic;
+        private int mResultCode;
+    };
+
+    private static Map<String, Font[]> QUERY_MAP;
+    static {
+        HashMap<String, Font[]> map = new HashMap<>();
+        int id = 0;
+
+        map.put("singleFontFamily", new Font[] {
+            new Font(id++, SAMPLE_FONT_FILE_0_ID, 0, null, 400, 0, Columns.RESULT_CODE_OK),
+        });
+
+        map.put("singleFontFamily2", new Font[] {
+            new Font(id++, SAMPLE_FONT_FILE_0_ID, 0, null, 700, 0, Columns.RESULT_CODE_OK),
+        });
+
+        QUERY_MAP = Collections.unmodifiableMap(map);
+    }
+
+    private static Cursor buildCursor(Font[] in) {
+        MatrixCursor cursor = new MatrixCursor(new String[] {
+                Columns._ID, Columns.TTC_INDEX, Columns.VARIATION_SETTINGS, Columns.WEIGHT,
+                Columns.ITALIC, Columns.RESULT_CODE, Columns.FILE_ID});
+        for (Font font : in) {
+            MatrixCursor.RowBuilder builder = cursor.newRow();
+            builder.add(Columns._ID, font.getId());
+            builder.add(Columns.FILE_ID, font.getFileId());
+            builder.add(Columns.TTC_INDEX, font.getTtcIndex());
+            builder.add(Columns.VARIATION_SETTINGS, font.getVarSettings());
+            builder.add(Columns.WEIGHT, font.getWeight());
+            builder.add(Columns.ITALIC, font.getItalic());
+            builder.add(Columns.RESULT_CODE, font.getResultCode());
+        }
+        return cursor;
+    }
+
+    public MockFontProvider() {
+    }
+
+    public static void prepareFontFiles(Context context) {
+        final AssetManager mgr = context.getAssets();
+        for (String file : FONT_FILES) {
+            try (InputStream is = mgr.open("fonts/" + file)) {
+                Files.copy(is, getCopiedFile(context, file).toPath(),
+                        StandardCopyOption.REPLACE_EXISTING);
+            } catch (IOException e) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
+
+    public static void cleanUpFontFiles(Context context) {
+        for (String file : FONT_FILES) {
+            getCopiedFile(context, file).delete();
+        }
+    }
+
+    public static File getCopiedFile(Context context, String path) {
+        return new File(context.getFilesDir(), path);
+    }
+
+    @Override
+    public ParcelFileDescriptor openFile(Uri uri, String mode) {
+        final int id = (int)ContentUris.parseId(uri);
+        final File targetFile = getCopiedFile(getContext(), FONT_FILES[id]);
+        try {
+            return ParcelFileDescriptor.open(targetFile, ParcelFileDescriptor.MODE_READ_ONLY);
+        } catch (FileNotFoundException e) {
+            throw new RuntimeException(
+                    "Failed to found font file. You might forget call prepareFontFiles in setUp");
+        }
+    }
+
+    @Override
+    public boolean onCreate() {
+        return true;
+    }
+
+    @Override
+    public String getType(Uri uri) {
+        return "vnd.android.cursor.dir/vnd.android.provider.font";
+    }
+
+    @Override
+    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
+            String sortOrder) {
+        return buildCursor(QUERY_MAP.get(selectionArgs[0]));
+    }
+
+    @Override
+    public Uri insert(Uri uri, ContentValues values) {
+        throw new UnsupportedOperationException("insert is not supported.");
+    }
+
+    @Override
+    public int delete(Uri uri, String selection, String[] selectionArgs) {
+        throw new UnsupportedOperationException("delete is not supported.");
+    }
+
+    @Override
+    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+        throw new UnsupportedOperationException("update is not supported.");
+    }
+}
diff --git a/graphics/java/android/graphics/Color.java b/graphics/java/android/graphics/Color.java
index 8cbf921..bdd828f 100644
--- a/graphics/java/android/graphics/Color.java
+++ b/graphics/java/android/graphics/Color.java
@@ -24,7 +24,7 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.Size;
-
+import android.annotation.SuppressAutoDoc;
 import android.util.Half;
 import com.android.internal.util.XmlUtils;
 
@@ -289,6 +289,7 @@
  * and <code>(1.0, 0.0, 0.0, 0.5)</code>.</p>
  */
 @AnyThread
+@SuppressAutoDoc
 public class Color {
     @ColorInt public static final int BLACK       = 0xFF000000;
     @ColorInt public static final int DKGRAY      = 0xFF444444;
diff --git a/graphics/java/android/graphics/ColorSpace.java b/graphics/java/android/graphics/ColorSpace.java
index f2957a3..5814df5 100644
--- a/graphics/java/android/graphics/ColorSpace.java
+++ b/graphics/java/android/graphics/ColorSpace.java
@@ -22,6 +22,7 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.Size;
+import android.annotation.SuppressAutoDoc;
 import android.util.Pair;
 
 import java.util.ArrayList;
@@ -131,6 +132,7 @@
  */
 @AnyThread
 @SuppressWarnings("StaticInitializerReferencesSubClass")
+@SuppressAutoDoc
 public abstract class ColorSpace {
     /**
      * Standard CIE 1931 2° illuminant A, encoded in xyY.
diff --git a/graphics/java/android/graphics/SurfaceTexture.java b/graphics/java/android/graphics/SurfaceTexture.java
index 90bdd81..24fb673 100644
--- a/graphics/java/android/graphics/SurfaceTexture.java
+++ b/graphics/java/android/graphics/SurfaceTexture.java
@@ -107,7 +107,7 @@
      *
      * @param texName the OpenGL texture object name (e.g. generated via glGenTextures)
      *
-     * @throws Surface.OutOfResourcesException If the SurfaceTexture cannot be created.
+     * @throws android.view.Surface.OutOfResourcesException If the SurfaceTexture cannot be created.
      */
     public SurfaceTexture(int texName) {
         this(texName, false);
@@ -128,7 +128,7 @@
      * @param texName the OpenGL texture object name (e.g. generated via glGenTextures)
      * @param singleBufferMode whether the SurfaceTexture will be in single buffered mode.
      *
-     * @throws Surface.OutOfResourcesException If the SurfaceTexture cannot be created.
+     * @throws android.view.Surface.OutOfResourcesException If the SurfaceTexture cannot be created.
      */
     public SurfaceTexture(int texName, boolean singleBufferMode) {
         mCreatorLooper = Looper.myLooper();
@@ -155,7 +155,7 @@
      *
      * @param singleBufferMode whether the SurfaceTexture will be in single buffered mode.
      *
-     * @throws Surface.OutOfResourcesException If the SurfaceTexture cannot be created.
+     * @throws android.view.Surface.OutOfResourcesException If the SurfaceTexture cannot be created.
      */
     public SurfaceTexture(boolean singleBufferMode) {
         mCreatorLooper = Looper.myLooper();
diff --git a/graphics/java/android/graphics/drawable/AdaptiveIconDrawable.java b/graphics/java/android/graphics/drawable/AdaptiveIconDrawable.java
index 283a3e2..ffadad9 100644
--- a/graphics/java/android/graphics/drawable/AdaptiveIconDrawable.java
+++ b/graphics/java/android/graphics/drawable/AdaptiveIconDrawable.java
@@ -16,8 +16,6 @@
 
 package android.graphics.drawable;
 
-import static android.graphics.drawable.Drawable.obtainAttributes;
-
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.TestApi;
@@ -218,14 +216,16 @@
 
         // The density may have changed since the last update. This will
         // apply scaling to any existing constant state properties.
-        final int density = Drawable.resolveDensity(r, 0);
-        state.setDensity(density);
+        final int deviceDensity = Drawable.resolveDensity(r, 0);
+        state.setDensity(deviceDensity);
+        state.mSrcDensityOverride = mSrcDensityOverride;
 
         final ChildDrawable[] array = state.mChildren;
         for (int i = 0; i < state.mChildren.length; i++) {
             final ChildDrawable layer = array[i];
-            layer.setDensity(density);
+            layer.setDensity(deviceDensity);
         }
+
         inflateLayers(r, parser, attrs, theme);
     }
 
@@ -444,7 +444,7 @@
     /**
      * Inflates child layers using the specified parser.
      */
-    void inflateLayers(@NonNull Resources r, @NonNull XmlPullParser parser,
+    private void inflateLayers(@NonNull Resources r, @NonNull XmlPullParser parser,
             @NonNull AttributeSet attrs, @Nullable Theme theme)
             throws XmlPullParserException, IOException {
         final LayerState state = mLayerState;
@@ -491,7 +491,8 @@
                 }
 
                 // We found a child drawable. Take ownership.
-                layer.mDrawable = Drawable.createFromXmlInner(r, parser, attrs, theme);
+                layer.mDrawable = Drawable.createFromXmlInnerForDensity(r, parser, attrs,
+                        mLayerState.mSrcDensityOverride, theme);
                 layer.mDrawable.setCallback(this);
                 state.mChildrenChangingConfigurations |=
                         layer.mDrawable.getChangingConfigurations();
@@ -509,7 +510,8 @@
         // Extract the theme attributes, if any.
         layer.mThemeAttrs = a.extractThemeAttrs();
 
-        Drawable dr = a.getDrawable(R.styleable.AdaptiveIconDrawableLayer_drawable);
+        Drawable dr = a.getDrawableForDensity(R.styleable.AdaptiveIconDrawableLayer_drawable,
+                state.mSrcDensityOverride);
         if (dr != null) {
             if (layer.mDrawable != null) {
                 // It's possible that a drawable was already set, in which case
@@ -951,7 +953,13 @@
         final static int N_CHILDREN = 2;
         ChildDrawable[] mChildren;
 
+        // The density at which to render the drawable and its children.
         int mDensity;
+
+        // The density to use when inflating/looking up the children drawables. A value of 0 means
+        // use the system's density.
+        int mSrcDensityOverride = 0;
+
         int mOpacityOverride = PixelFormat.UNKNOWN;
 
         @Config int mChangingConfigurations;
@@ -986,6 +994,7 @@
                 mAutoMirrored = orig.mAutoMirrored;
                 mThemeAttrs = orig.mThemeAttrs;
                 mOpacityOverride = orig.mOpacityOverride;
+                mSrcDensityOverride = orig.mSrcDensityOverride;
             } else {
                 for (int i = 0; i < N_CHILDREN; i++) {
                     mChildren[i] = new ChildDrawable(mDensity);
diff --git a/graphics/java/android/graphics/drawable/BitmapDrawable.java b/graphics/java/android/graphics/drawable/BitmapDrawable.java
index 5004667..e3740e3 100644
--- a/graphics/java/android/graphics/drawable/BitmapDrawable.java
+++ b/graphics/java/android/graphics/drawable/BitmapDrawable.java
@@ -41,6 +41,7 @@
 import android.util.AttributeSet;
 import android.util.DisplayMetrics;
 import android.util.LayoutDirection;
+import android.util.TypedValue;
 import android.view.Gravity;
 
 import com.android.internal.R;
@@ -49,6 +50,7 @@
 import org.xmlpull.v1.XmlPullParserException;
 
 import java.io.IOException;
+import java.io.InputStream;
 
 /**
  * A Drawable that wraps a bitmap and can be tiled, stretched, or aligned. You can create a
@@ -749,7 +751,7 @@
         super.inflate(r, parser, attrs, theme);
 
         final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.BitmapDrawable);
-        updateStateFromTypedArray(a);
+        updateStateFromTypedArray(a, mSrcDensityOverride);
         verifyRequiredAttributes(a);
         a.recycle();
 
@@ -775,7 +777,8 @@
     /**
      * Updates the constant state from the values in the typed array.
      */
-    private void updateStateFromTypedArray(TypedArray a) throws XmlPullParserException {
+    private void updateStateFromTypedArray(TypedArray a, int srcDensityOverride)
+            throws XmlPullParserException {
         final Resources r = a.getResources();
         final BitmapState state = mBitmapState;
 
@@ -785,9 +788,37 @@
         // Extract the theme attributes, if any.
         state.mThemeAttrs = a.extractThemeAttrs();
 
+        state.mSrcDensityOverride = srcDensityOverride;
+
+        state.mTargetDensity = Drawable.resolveDensity(r, 0);
+
         final int srcResId = a.getResourceId(R.styleable.BitmapDrawable_src, 0);
         if (srcResId != 0) {
-            final Bitmap bitmap = BitmapFactory.decodeResource(r, srcResId);
+            final TypedValue value = new TypedValue();
+            r.getValueForDensity(srcResId, srcDensityOverride, value, true);
+
+            // Pretend the requested density is actually the display density. If
+            // the drawable returned is not the requested density, then force it
+            // to be scaled later by dividing its density by the ratio of
+            // requested density to actual device density. Drawables that have
+            // undefined density or no density don't need to be handled here.
+            if (srcDensityOverride > 0 && value.density > 0
+                    && value.density != TypedValue.DENSITY_NONE) {
+                if (value.density == srcDensityOverride) {
+                    value.density = r.getDisplayMetrics().densityDpi;
+                } else {
+                    value.density =
+                            (value.density * r.getDisplayMetrics().densityDpi) / srcDensityOverride;
+                }
+            }
+
+            Bitmap bitmap = null;
+            try (InputStream is = r.openRawResource(srcResId, value)) {
+                bitmap = BitmapFactory.decodeResourceStream(r, value, is, null, null);
+            } catch (Exception e) {
+                // Do nothing and pick up the error below.
+            }
+
             if (bitmap == null) {
                 throw new XmlPullParserException(a.getPositionDescription() +
                         ": <bitmap> requires a valid 'src' attribute");
@@ -796,8 +827,6 @@
             state.mBitmap = bitmap;
         }
 
-        state.mTargetDensity = r.getDisplayMetrics().densityDpi;
-
         final boolean defMipMap = state.mBitmap != null ? state.mBitmap.hasMipMap() : false;
         setMipMap(a.getBoolean(R.styleable.BitmapDrawable_mipMap, defMipMap));
 
@@ -839,8 +868,6 @@
         if (tileModeY != TILE_MODE_UNDEFINED) {
             setTileModeY(parseTileMode(tileModeY));
         }
-
-        state.mTargetDensity = Drawable.resolveDensity(r, 0);
     }
 
     @Override
@@ -855,7 +882,7 @@
         if (state.mThemeAttrs != null) {
             final TypedArray a = t.resolveAttributes(state.mThemeAttrs, R.styleable.BitmapDrawable);
             try {
-                updateStateFromTypedArray(a);
+                updateStateFromTypedArray(a, state.mSrcDensityOverride);
             } catch (XmlPullParserException e) {
                 rethrowAsRuntimeException(e);
             } finally {
@@ -929,7 +956,14 @@
         float mBaseAlpha = 1.0f;
         Shader.TileMode mTileModeX = null;
         Shader.TileMode mTileModeY = null;
+
+        // The density to use when looking up the bitmap in Resources. A value of 0 means use
+        // the system's density.
+        int mSrcDensityOverride = 0;
+
+        // The density at which to render the bitmap.
         int mTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
+
         boolean mAutoMirrored = false;
 
         @Config int mChangingConfigurations;
@@ -949,6 +983,7 @@
             mGravity = bitmapState.mGravity;
             mTileModeX = bitmapState.mTileModeX;
             mTileModeY = bitmapState.mTileModeY;
+            mSrcDensityOverride = bitmapState.mSrcDensityOverride;
             mTargetDensity = bitmapState.mTargetDensity;
             mBaseAlpha = bitmapState.mBaseAlpha;
             mPaint = new Paint(bitmapState.mPaint);
diff --git a/graphics/java/android/graphics/drawable/ColorDrawable.java b/graphics/java/android/graphics/drawable/ColorDrawable.java
index 559e3d3..9ae747d 100644
--- a/graphics/java/android/graphics/drawable/ColorDrawable.java
+++ b/graphics/java/android/graphics/drawable/ColorDrawable.java
@@ -18,6 +18,8 @@
 
 import android.annotation.ColorInt;
 import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.TestApi;
 import android.content.pm.ActivityInfo.Config;
 import android.graphics.*;
 import android.graphics.PorterDuff.Mode;
@@ -213,6 +215,25 @@
         return mColorState.mTint != null && mColorState.mTint.hasFocusStateSpecified();
     }
 
+    /**
+     * @hide
+     * @param mode new transfer mode
+     */
+    @Override
+    public void setXfermode(@Nullable Xfermode mode) {
+        mPaint.setXfermode(mode);
+        invalidateSelf();
+    }
+
+    /**
+     * @hide
+     * @return current transfer mode
+     */
+    @TestApi
+    public Xfermode getXfermode() {
+        return mPaint.getXfermode();
+    }
+
     @Override
     public int getOpacity() {
         if (mTintFilter != null || mPaint.getColorFilter() != null) {
diff --git a/graphics/java/android/graphics/drawable/Drawable.java b/graphics/java/android/graphics/drawable/Drawable.java
index 44fb1c7..f17cd76 100644
--- a/graphics/java/android/graphics/drawable/Drawable.java
+++ b/graphics/java/android/graphics/drawable/Drawable.java
@@ -189,6 +189,21 @@
     private int mLayoutDirection;
 
     /**
+     * The source density to use when looking up resources using
+     * {@link Resources#getDrawableForDensity(int, int, Theme)}. A value of 0 means there is no
+     * override and the system density will be used.
+     *
+     * NOTE(adamlesinski): This is transient state used to get around the public API that does not
+     * account for source density overrides. Custom drawables implemented by developers do not need
+     * to be aware of the source density override, as it is only used by Launcher to load higher
+     * resolution icons from external Resources packages, which do not execute custom code.
+     * This is all to support the {@link Resources#getDrawableForDensity(int, int, Theme)} API.
+     *
+     * @hide
+     */
+    protected int mSrcDensityOverride = 0;
+
+    /**
      * Draw in its bounds (set via setBounds) respecting optional effects such
      * as alpha (set via setAlpha) and color filter (set via setColorFilter).
      *
@@ -1197,7 +1212,8 @@
      * create resources in XML, see
      * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.
      */
-    public static Drawable createFromXml(Resources r, XmlPullParser parser)
+    @NonNull
+    public static Drawable createFromXml(@NonNull Resources r, @NonNull XmlPullParser parser)
             throws XmlPullParserException, IOException {
         return createFromXml(r, parser, null);
     }
@@ -1207,7 +1223,20 @@
      * For more information on how to create resources in XML, see
      * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.
      */
-    public static Drawable createFromXml(Resources r, XmlPullParser parser, Theme theme)
+    @NonNull
+    public static Drawable createFromXml(@NonNull Resources r, @NonNull XmlPullParser parser,
+            @Nullable Theme theme) throws XmlPullParserException, IOException {
+        return createFromXmlForDensity(r, parser, 0, theme);
+    }
+
+    /**
+     * Version of {@link #createFromXml(Resources, XmlPullParser, Theme)} that accepts a density
+     * override.
+     * @hide
+     */
+    @NonNull
+    public static Drawable createFromXmlForDensity(@NonNull Resources r,
+            @NonNull XmlPullParser parser, int density, @Nullable Theme theme)
             throws XmlPullParserException, IOException {
         AttributeSet attrs = Xml.asAttributeSet(parser);
 
@@ -1222,7 +1251,7 @@
             throw new XmlPullParserException("No start tag found");
         }
 
-        Drawable drawable = createFromXmlInner(r, parser, attrs, theme);
+        Drawable drawable = createFromXmlInnerForDensity(r, parser, attrs, density, theme);
 
         if (drawable == null) {
             throw new RuntimeException("Unknown initial tag: " + parser.getName());
@@ -1236,8 +1265,9 @@
      * a tag in an XML document, tries to create a Drawable from that tag.
      * Returns null if the tag is not a valid drawable.
      */
-    public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs)
-            throws XmlPullParserException, IOException {
+    @NonNull
+    public static Drawable createFromXmlInner(@NonNull Resources r, @NonNull XmlPullParser parser,
+            @NonNull AttributeSet attrs) throws XmlPullParserException, IOException {
         return createFromXmlInner(r, parser, attrs, null);
     }
 
@@ -1247,14 +1277,29 @@
      * document, tries to create a Drawable from that tag. Returns {@code null}
      * if the tag is not a valid drawable.
      */
-    public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs,
-            Theme theme) throws XmlPullParserException, IOException {
-        return r.getDrawableInflater().inflateFromXml(parser.getName(), parser, attrs, theme);
+    @NonNull
+    public static Drawable createFromXmlInner(@NonNull Resources r, @NonNull XmlPullParser parser,
+            @NonNull AttributeSet attrs, @Nullable Theme theme)
+            throws XmlPullParserException, IOException {
+        return createFromXmlInnerForDensity(r, parser, attrs, 0, theme);
+    }
+
+    /**
+     * Version of {@link #createFromXmlInner(Resources, XmlPullParser, AttributeSet, Theme)} that
+     * accepts an override density.
+     */
+    @NonNull
+    static Drawable createFromXmlInnerForDensity(@NonNull Resources r,
+            @NonNull XmlPullParser parser, @NonNull AttributeSet attrs, int density,
+            @Nullable Theme theme) throws XmlPullParserException, IOException {
+        return r.getDrawableInflater().inflateFromXmlForDensity(parser.getName(), parser, attrs,
+                density, theme);
     }
 
     /**
      * Create a drawable from file path name.
      */
+    @Nullable
     public static Drawable createFromPath(String pathName) {
         if (pathName == null) {
             return null;
@@ -1316,6 +1361,16 @@
     }
 
     /**
+     * Sets the source override density for this Drawable. If non-zero, this density is to be used
+     * for any calls to {@link Resources#getDrawableForDensity(int, int, Theme)} or
+     * {@link Resources#getValueForDensity(int, int, TypedValue, boolean)}.
+     * @hide
+     */
+    final void setSrcDensityOverride(int density) {
+        mSrcDensityOverride = density;
+    }
+
+    /**
      * This abstract class is used by {@link Drawable}s to store shared constant state and data
      * between Drawables. {@link BitmapDrawable}s created from the same resource will for instance
      * share a unique bitmap stored in their ConstantState.
diff --git a/graphics/java/android/graphics/drawable/DrawableInflater.java b/graphics/java/android/graphics/drawable/DrawableInflater.java
index 3404d8c..eea7048 100644
--- a/graphics/java/android/graphics/drawable/DrawableInflater.java
+++ b/graphics/java/android/graphics/drawable/DrawableInflater.java
@@ -112,6 +112,17 @@
     public Drawable inflateFromXml(@NonNull String name, @NonNull XmlPullParser parser,
             @NonNull AttributeSet attrs, @Nullable Theme theme)
             throws XmlPullParserException, IOException {
+        return inflateFromXmlForDensity(name, parser, attrs, 0, theme);
+    }
+
+    /**
+     * Version of {@link #inflateFromXml(String, XmlPullParser, AttributeSet, Theme)} that accepts
+     * an override density.
+     */
+    @NonNull
+    Drawable inflateFromXmlForDensity(@NonNull String name, @NonNull XmlPullParser parser,
+            @NonNull AttributeSet attrs, int density, @Nullable Theme theme)
+            throws XmlPullParserException, IOException {
         // Inner classes must be referenced as Outer$Inner, but XML tag names
         // can't contain $, so the <drawable> tag allows developers to specify
         // the class in an attribute. We'll still run it through inflateFromTag
@@ -127,6 +138,7 @@
         if (drawable == null) {
             drawable = inflateFromClass(name);
         }
+        drawable.setSrcDensityOverride(density);
         drawable.inflate(mRes, parser, attrs, theme);
         return drawable;
     }
diff --git a/graphics/java/android/graphics/drawable/DrawableWrapper.java b/graphics/java/android/graphics/drawable/DrawableWrapper.java
index 431b63b..cf821bb 100644
--- a/graphics/java/android/graphics/drawable/DrawableWrapper.java
+++ b/graphics/java/android/graphics/drawable/DrawableWrapper.java
@@ -131,6 +131,7 @@
         final int densityDpi = r.getDisplayMetrics().densityDpi;
         final int targetDensity = densityDpi == 0 ? DisplayMetrics.DENSITY_DEFAULT : densityDpi;
         state.setDensity(targetDensity);
+        state.mSrcDensityOverride = mSrcDensityOverride;
 
         final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.DrawableWrapper);
         updateStateFromTypedArray(a);
@@ -437,7 +438,8 @@
         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
             if (type == XmlPullParser.START_TAG) {
-                dr = Drawable.createFromXmlInner(r, parser, attrs, theme);
+                dr = Drawable.createFromXmlInnerForDensity(r, parser, attrs,
+                        mState.mSrcDensityOverride, theme);
             }
         }
 
@@ -452,6 +454,14 @@
         @Config int mChangingConfigurations;
         int mDensity = DisplayMetrics.DENSITY_DEFAULT;
 
+        /**
+         * The density to use when looking up resources from
+         * {@link Resources#getDrawableForDensity(int, int, Theme)}.
+         * A value of 0 means there is no override and the system density will be used.
+         * @hide
+         */
+        int mSrcDensityOverride = 0;
+
         Drawable.ConstantState mDrawableState;
 
         DrawableWrapperState(@Nullable DrawableWrapperState orig, @Nullable Resources res) {
@@ -459,6 +469,7 @@
                 mThemeAttrs = orig.mThemeAttrs;
                 mChangingConfigurations = orig.mChangingConfigurations;
                 mDrawableState = orig.mDrawableState;
+                mSrcDensityOverride = orig.mSrcDensityOverride;
             }
 
             final int density;
diff --git a/graphics/java/android/graphics/fonts/FontRequest.java b/graphics/java/android/graphics/fonts/FontRequest.java
index c7a5830..df3951c 100644
--- a/graphics/java/android/graphics/fonts/FontRequest.java
+++ b/graphics/java/android/graphics/fonts/FontRequest.java
@@ -35,6 +35,9 @@
     private final String mQuery;
     private final List<List<byte[]>> mCertificates;
 
+    // Used for key of the cache.
+    private final String mIdentifier;
+
     /**
      * @param providerAuthority The authority of the Font Provider to be used for the request. This
      *         should be a system installed app.
@@ -49,6 +52,8 @@
         mQuery = Preconditions.checkNotNull(query);
         mProviderPackage = Preconditions.checkNotNull(providerPackage);
         mCertificates = Collections.emptyList();
+        mIdentifier = new StringBuilder(mProviderAuthority).append("-").append(mProviderPackage)
+                .append("-").append(mQuery).toString();
     }
 
     /**
@@ -68,6 +73,8 @@
         mProviderPackage = Preconditions.checkNotNull(providerPackage);
         mQuery = Preconditions.checkNotNull(query);
         mCertificates = Preconditions.checkNotNull(certificates);
+        mIdentifier = new StringBuilder(mProviderAuthority).append("-").append(mProviderPackage)
+                .append("-").append(mQuery).toString();
     }
 
     /**
@@ -102,6 +109,11 @@
         return mCertificates;
     }
 
+    /** @hide */
+    public String getIdentifier() {
+        return mIdentifier;
+    }
+
     @Override
     public int describeContents() {
         return 0;
@@ -121,6 +133,8 @@
         mQuery = in.readString();
         mCertificates = new ArrayList<>();
         in.readList(mCertificates, null);
+        mIdentifier = new StringBuilder(mProviderAuthority).append("-").append(mProviderPackage)
+                .append("-").append(mQuery).toString();
     }
 
     public static final Parcelable.Creator<FontRequest> CREATOR =
diff --git a/keystore/java/android/security/keystore/AttestationUtils.java b/keystore/java/android/security/keystore/AttestationUtils.java
index 2ec8d33..0f98392 100644
--- a/keystore/java/android/security/keystore/AttestationUtils.java
+++ b/keystore/java/android/security/keystore/AttestationUtils.java
@@ -95,9 +95,6 @@
      * For privacy reasons, you cannot distinguish between (1) and (2). If attestation is
      * unsuccessful, the device may not support it in general or the user may have permanently
      * disabled it.
-     * <p>
-     * The caller must hold {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
-     * permission.
      *
      * @param context the context to use for retrieving device identifiers.
      * @param idTypes the types of device identifiers to attest.
diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java
index 293ceea..5cbccea 100644
--- a/media/java/android/media/MediaPlayer.java
+++ b/media/java/android/media/MediaPlayer.java
@@ -140,7 +140,7 @@
  *         {@link #getVideoWidth()}, {@link #setAudioAttributes(AudioAttributes)},
  *         {@link #setLooping(boolean)},
  *         {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()},
- *         {@link #stop()}, {@link #seekTo(int, int)}, {@link #prepare()} or
+ *         {@link #stop()}, {@link #seekTo(long, int)}, {@link #prepare()} or
  *         {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these
  *         methods is called right after a MediaPlayer object is constructed,
  *         the user supplied callback method OnErrorListener.onError() won't be
@@ -286,9 +286,9 @@
  *         </ul>
  *         </li>
  *     <li>The playback position can be adjusted with a call to
- *         {@link #seekTo(int, int)}.
+ *         {@link #seekTo(long, int)}.
  *         <ul>
- *         <li>Although the asynchronuous {@link #seekTo(int, int)}
+ *         <li>Although the asynchronuous {@link #seekTo(long, int)}
  *         call returns right away, the actual seek operation may take a while to
  *         finish, especially for audio/video being streamed. When the actual
  *         seek operation completes, the internal player engine calls a user
@@ -296,9 +296,9 @@
  *         has been registered beforehand via
  *         {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li>
  *         <li>Please
- *         note that {@link #seekTo(int, int)} can also be called in the other states,
+ *         note that {@link #seekTo(long, int)} can also be called in the other states,
  *         such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
- *         </em> state. When {@link #seekTo(int, int)} is called in those states,
+ *         </em> state. When {@link #seekTo(long, int)} is called in those states,
  *         one video frame will be displayed if the stream has video and the requested
  *         position is valid.
  *         </li>
@@ -1704,42 +1704,42 @@
     public native SyncParams getSyncParams();
 
     /**
-     * Seek modes used in method seekTo(int, int) to move media position
+     * Seek modes used in method seekTo(long, int) to move media position
      * to a specified location.
      *
      * Do not change these mode values without updating their counterparts
      * in include/media/IMediaSource.h!
      */
     /**
-     * This mode is used with {@link #seekTo(int, int)} to move media position to
+     * This mode is used with {@link #seekTo(long, int)} to move media position to
      * a sync (or key) frame associated with a data source that is located
      * right before or at the given time.
      *
-     * @see #seekTo(int, int)
+     * @see #seekTo(long, int)
      */
     public static final int SEEK_PREVIOUS_SYNC    = 0x00;
     /**
-     * This mode is used with {@link #seekTo(int, int)} to move media position to
+     * This mode is used with {@link #seekTo(long, int)} to move media position to
      * a sync (or key) frame associated with a data source that is located
      * right after or at the given time.
      *
-     * @see #seekTo(int, int)
+     * @see #seekTo(long, int)
      */
     public static final int SEEK_NEXT_SYNC        = 0x01;
     /**
-     * This mode is used with {@link #seekTo(int, int)} to move media position to
+     * This mode is used with {@link #seekTo(long, int)} to move media position to
      * a sync (or key) frame associated with a data source that is located
      * closest to (in time) or at the given time.
      *
-     * @see #seekTo(int, int)
+     * @see #seekTo(long, int)
      */
     public static final int SEEK_CLOSEST_SYNC     = 0x02;
     /**
-     * This mode is used with {@link #seekTo(int, int)} to move media position to
+     * This mode is used with {@link #seekTo(long, int)} to move media position to
      * a frame (not necessarily a key frame) associated with a data source that
      * is located closest to or at the given time.
      *
-     * @see #seekTo(int, int)
+     * @see #seekTo(long, int)
      */
     public static final int SEEK_CLOSEST          = 0x03;
 
@@ -1754,7 +1754,7 @@
     @Retention(RetentionPolicy.SOURCE)
     public @interface SeekMode {}
 
-    private native final void _seekTo(int msec, int mode);
+    private native final void _seekTo(long msec, int mode);
 
     /**
      * Moves the media to specified time position by considering the given mode.
@@ -1786,17 +1786,25 @@
      * initialized
      * @throws IllegalArgumentException if the mode is invalid.
      */
-    public void seekTo(int msec, @SeekMode int mode) throws IllegalStateException {
+    public void seekTo(long msec, @SeekMode int mode) {
         if (mode < SEEK_PREVIOUS_SYNC || mode > SEEK_CLOSEST) {
             final String msg = "Illegal seek mode: " + mode;
             throw new IllegalArgumentException(msg);
         }
+        // TODO: pass long to native, instead of truncating here.
+        if (msec > Integer.MAX_VALUE) {
+            Log.w(TAG, "seekTo offset " + msec + " is too large, cap to " + Integer.MAX_VALUE);
+            msec = Integer.MAX_VALUE;
+        } else if (msec < Integer.MIN_VALUE) {
+            Log.w(TAG, "seekTo offset " + msec + " is too small, cap to " + Integer.MIN_VALUE);
+            msec = Integer.MIN_VALUE;
+        }
         _seekTo(msec, mode);
     }
 
     /**
      * Seeks to specified time position.
-     * Same as {@link #seekTo(int, int)} with {@code mode = SEEK_PREVIOUS_SYNC}.
+     * Same as {@link #seekTo(long, int)} with {@code mode = SEEK_PREVIOUS_SYNC}.
      *
      * @param msec the offset in milliseconds from the start to seek to
      * @throws IllegalStateException if the internal player engine has not been
diff --git a/media/jni/android_media_MediaPlayer.cpp b/media/jni/android_media_MediaPlayer.cpp
index 2fc4afd..3711462 100644
--- a/media/jni/android_media_MediaPlayer.cpp
+++ b/media/jni/android_media_MediaPlayer.cpp
@@ -662,15 +662,15 @@
 }
 
 static void
-android_media_MediaPlayer_seekTo(JNIEnv *env, jobject thiz, jint msec, jint mode)
+android_media_MediaPlayer_seekTo(JNIEnv *env, jobject thiz, jlong msec, jint mode)
 {
     sp<MediaPlayer> mp = getMediaPlayer(env, thiz);
     if (mp == NULL ) {
         jniThrowException(env, "java/lang/IllegalStateException", NULL);
         return;
     }
-    ALOGV("seekTo: %d(msec), mode=%d", msec, mode);
-    process_media_player_call( env, thiz, mp->seekTo(msec, (MediaPlayerSeekMode)mode), NULL, NULL );
+    ALOGV("seekTo: %lld(msec), mode=%d", (long long)msec, mode);
+    process_media_player_call( env, thiz, mp->seekTo((int)msec, (MediaPlayerSeekMode)mode), NULL, NULL );
 }
 
 static jint
@@ -1398,7 +1398,7 @@
     {"getPlaybackParams", "()Landroid/media/PlaybackParams;", (void *)android_media_MediaPlayer_getPlaybackParams},
     {"setSyncParams",     "(Landroid/media/SyncParams;)V",  (void *)android_media_MediaPlayer_setSyncParams},
     {"getSyncParams",     "()Landroid/media/SyncParams;",   (void *)android_media_MediaPlayer_getSyncParams},
-    {"_seekTo",             "(II)V",                            (void *)android_media_MediaPlayer_seekTo},
+    {"_seekTo",             "(JI)V",                            (void *)android_media_MediaPlayer_seekTo},
     {"_pause",              "()V",                              (void *)android_media_MediaPlayer_pause},
     {"isPlaying",           "()Z",                              (void *)android_media_MediaPlayer_isPlaying},
     {"getCurrentPosition",  "()I",                              (void *)android_media_MediaPlayer_getCurrentPosition},
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/CodecTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/CodecTest.java
index 9e50490..48b2878 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/CodecTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/CodecTest.java
@@ -789,11 +789,12 @@
     };
 
     public static boolean playMediaSamples(String filePath) throws Exception {
-        return playMediaSamples(filePath, 2000);
+        return playMediaSamples(filePath, 2000, false /* streamingTest */);
     }
 
     // For each media file, forward twice and backward once, then play to the end
-    public static boolean playMediaSamples(String filePath, int buffertime) throws Exception {
+    public static boolean playMediaSamples(String filePath, int buffertime, boolean streamingTest)
+            throws Exception {
         int duration = 0;
         int curPosition = 0;
         int nextPosition = 0;
@@ -808,27 +809,32 @@
         mFailedToCompleteWithNoError = true;
         String testResult;
 
-        final MediaCodecList list = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
-        final MediaExtractor extractor = new MediaExtractor();
         boolean hasSupportedVideo = false;
 
-        try {
-            extractor.setDataSource(filePath);
+        if (!streamingTest) {
+            final MediaCodecList list = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
+            final MediaExtractor extractor = new MediaExtractor();
 
-            for (int index = 0; index < extractor.getTrackCount(); ++index) {
-                MediaFormat format = extractor.getTrackFormat(index);
-                String mime = format.getString(MediaFormat.KEY_MIME);
-                if (!mime.startsWith("video/")) {
-                    continue;
-                }
+            try {
+                extractor.setDataSource(filePath);
 
-                if (list.findDecoderForFormat(format) != null) {
-                    hasSupportedVideo = true;
-                    break;
+                for (int index = 0; index < extractor.getTrackCount(); ++index) {
+                    MediaFormat format = extractor.getTrackFormat(index);
+                    String mime = format.getString(MediaFormat.KEY_MIME);
+                    if (!mime.startsWith("video/")) {
+                        continue;
+                    }
+
+                    if (list.findDecoderForFormat(format) != null) {
+                        hasSupportedVideo = true;
+                        break;
+                    }
                 }
+            } finally {
+                extractor.release();
             }
-        } finally {
-            extractor.release();
+        } else { // streamingTest
+            hasSupportedVideo = true;
         }
 
         initializeMessageLooper();
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/stress/MediaPlayerStreamingStressTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/stress/MediaPlayerStreamingStressTest.java
index d92c857..6a820ec 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/stress/MediaPlayerStreamingStressTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/stress/MediaPlayerStreamingStressTest.java
@@ -144,7 +144,7 @@
                 //Get url
                 String filename = urls.get(i);
                 onCompleteSuccess =
-                    CodecTest.playMediaSamples(filename, 60000);
+                    CodecTest.playMediaSamples(filename, 60000, true /* streamingTest */);
                 if (!onCompleteSuccess){
                     //Don't fail the test right away, print out the failure file.
                     fileWithError += filename + '\n';
diff --git a/opengl/java/android/opengl/GLSurfaceView.java b/opengl/java/android/opengl/GLSurfaceView.java
index 329514c..0f0a7e9d 100644
--- a/opengl/java/android/opengl/GLSurfaceView.java
+++ b/opengl/java/android/opengl/GLSurfaceView.java
@@ -1469,6 +1469,13 @@
                                     }
                                     break;
                                 }
+                            } else {
+                                if (finishDrawingRunnable != null) {
+                                    Log.w(TAG, "Warning, !readyToDraw() but waiting for " +
+                                            "draw finished! Early reporting draw finished.");
+                                    finishDrawingRunnable.run();
+                                    finishDrawingRunnable = null;
+                                }
                             }
                             // By design, this is the only place in a GLThread thread where we wait().
                             if (LOG_THREADS) {
diff --git a/packages/PrintSpooler/res/drawable/ic_pdf_printer.xml b/packages/PrintSpooler/res/drawable/ic_pdf_printer.xml
new file mode 100644
index 0000000..8196650
--- /dev/null
+++ b/packages/PrintSpooler/res/drawable/ic_pdf_printer.xml
@@ -0,0 +1,25 @@
+<!--
+    Copyright (C) 2017 The Android Open Source Project
+
+    Licensed under the Apache License, Version 2.0 (the "License");
+    you may not use this file except in compliance with the License.
+    You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="36dp"
+    android:height="36dp"
+    android:viewportWidth="48.0"
+    android:viewportHeight="48.0"
+    android:tint="@color/pdf_printer_color">
+    <path
+        android:pathData="M40,4L16,4c-2.21,0 -4,1.79 -4,4v24c0,2.21 1.79,4 4,4h24c2.21,0 4,-1.79 4,-4L44,8c0,-2.21 -1.79,-4 -4,-4zM23,19c0,1.66 -1.34,3 -3,3h-2v4h-3L15,14h5c1.66,0 3,1.34 3,3v2zM33,23c0,1.66 -1.34,3 -3,3h-5L25,14h5c1.66,0 3,1.34 3,3v6zM41,17h-3v2h3v3h-3v4h-3L35,14h6v3zM18,19h2v-2h-2v2zM8,12L4,12v28c0,2.21 1.79,4 4,4h28v-4L8,40L8,12zM28,23h2v-6h-2v6z"
+        android:fillColor="@android:color/black"/>
+</vector>
\ No newline at end of file
diff --git a/packages/PrintSpooler/res/values/colors.xml b/packages/PrintSpooler/res/values/colors.xml
index d83d364..a15fff5 100644
--- a/packages/PrintSpooler/res/values/colors.xml
+++ b/packages/PrintSpooler/res/values/colors.xml
@@ -24,4 +24,5 @@
 
     <color name="material_grey_500">#ffa3a3a3</color>
 
+    <color name="pdf_printer_color">#009688</color>
 </resources>
diff --git a/packages/PrintSpooler/src/com/android/printspooler/ui/PrintActivity.java b/packages/PrintSpooler/src/com/android/printspooler/ui/PrintActivity.java
index ccdec62..601491a 100644
--- a/packages/PrintSpooler/src/com/android/printspooler/ui/PrintActivity.java
+++ b/packages/PrintSpooler/src/com/android/printspooler/ui/PrintActivity.java
@@ -2442,7 +2442,7 @@
                 if (position == 0 && getPdfPrinter() != null) {
                     PrinterHolder printerHolder = (PrinterHolder) getItem(position);
                     title = printerHolder.printer.getName();
-                    icon = getResources().getDrawable(R.drawable.ic_menu_savetopdf, null);
+                    icon = getResources().getDrawable(R.drawable.ic_pdf_printer, null);
                 } else if (position == 1) {
                     title = getMoreItemTitle();
                 }
@@ -2450,7 +2450,7 @@
                 if (position == 1 && getPdfPrinter() != null) {
                     PrinterHolder printerHolder = (PrinterHolder) getItem(position);
                     title = printerHolder.printer.getName();
-                    icon = getResources().getDrawable(R.drawable.ic_menu_savetopdf, null);
+                    icon = getResources().getDrawable(R.drawable.ic_pdf_printer, null);
                 } else if (position == getCount() - 1) {
                     title = getMoreItemTitle();
                 } else {
diff --git a/packages/SettingsLib/res/values/config.xml b/packages/SettingsLib/res/values/config.xml
deleted file mode 100755
index 64f21b5..0000000
--- a/packages/SettingsLib/res/values/config.xml
+++ /dev/null
@@ -1,49 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2016, 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>
-    <!-- Configuration for automotive -->
-    <bool name="enable_pbap_pce_profile">false</bool>
-
-    <!-- Default data warning level in mb -->
-    <integer name="default_data_warning_level_mb">2048</integer>
-
-    <!-- Whether to send a custom package name with the PSD.-->
-    <bool name="config_sendPackageName">false</bool>
-
-    <!-- Name for the set of keys associating package names -->
-    <string name="config_helpPackageNameKey" translatable="false"></string>
-
-    <!-- Name for the set of values of package names -->
-    <string name="config_helpPackageNameValue" translatable="false"></string>
-
-    <!-- Intent key for the package name keys -->
-    <string name="config_helpIntentExtraKey" translatable="false"></string>
-
-    <!-- Intent key for package name values -->
-    <string name="config_helpIntentNameKey" translatable="false"></string>
-
-    <!-- Intent key for the package name keys -->
-    <string name="config_feedbackIntentExtraKey" translatable="false"></string>
-
-    <!-- Intent key for package name values -->
-    <string name="config_feedbackIntentNameKey" translatable="false"></string>
-
-    <!-- The apps that need to be hided when they are disabled -->
-    <string-array name="config_hideWhenDisabled_packageNames"></string-array>
-</resources>
\ No newline at end of file
diff --git a/packages/SettingsLib/src/com/android/settingslib/HelpUtils.java b/packages/SettingsLib/src/com/android/settingslib/HelpUtils.java
index 58047bb..2c26410 100644
--- a/packages/SettingsLib/src/com/android/settingslib/HelpUtils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/HelpUtils.java
@@ -180,21 +180,24 @@
         }
 
         Resources resources = context.getResources();
-        boolean includePackageName = resources.getBoolean(R.bool.config_sendPackageName);
+        boolean includePackageName =
+                resources.getBoolean(com.android.internal.R.bool.config_sendPackageName);
 
         if (sendPackageName && includePackageName) {
             String[] packageNameKey =
-                    {resources.getString(R.string.config_helpPackageNameKey)};
+                    {resources.getString(com.android.internal.R.string.config_helpPackageNameKey)};
             String[] packageNameValue =
-                    {resources.getString(R.string.config_helpPackageNameValue)};
+                    {resources.getString(
+                            com.android.internal.R.string.config_helpPackageNameValue)};
             String helpIntentExtraKey =
-                    resources.getString(R.string.config_helpIntentExtraKey);
+                    resources.getString(com.android.internal.R.string.config_helpIntentExtraKey);
             String helpIntentNameKey =
-                    resources.getString(R.string.config_helpIntentNameKey);
+                    resources.getString(com.android.internal.R.string.config_helpIntentNameKey);
             String feedbackIntentExtraKey =
-                    resources.getString(R.string.config_feedbackIntentExtraKey);
+                    resources.getString(
+                            com.android.internal.R.string.config_feedbackIntentExtraKey);
             String feedbackIntentNameKey =
-                    resources.getString(R.string.config_feedbackIntentNameKey);
+                    resources.getString(com.android.internal.R.string.config_feedbackIntentNameKey);
             intent.putExtra(helpIntentExtraKey, packageNameKey);
             intent.putExtra(helpIntentNameKey, packageNameValue);
             intent.putExtra(feedbackIntentExtraKey, packageNameKey);
diff --git a/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java b/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java
index c109704..66dfecd 100644
--- a/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java
+++ b/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java
@@ -50,8 +50,8 @@
 import android.util.Log;
 import android.util.SparseArray;
 
+import com.android.internal.R;
 import com.android.internal.util.ArrayUtils;
-import com.android.settingslib.R;
 
 import java.io.File;
 import java.io.IOException;
@@ -1276,8 +1276,7 @@
                     return true;
                 } else {
                     this.mounted = false;
-                    this.icon = context.getDrawable(
-                            com.android.internal.R.drawable.sym_app_on_sd_unavailable_icon);
+                    this.icon = context.getDrawable(R.drawable.sym_app_on_sd_unavailable_icon);
                 }
             } else if (!this.mounted) {
                 // If the app wasn't mounted but is now mounted, reload
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothProfileManager.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothProfileManager.java
index 1ea592d..5a9a749 100755
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothProfileManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothProfileManager.java
@@ -32,7 +32,7 @@
 import android.content.Intent;
 import android.os.ParcelUuid;
 import android.util.Log;
-import com.android.settingslib.R;
+import com.android.internal.R;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
diff --git a/packages/SettingsLib/src/com/android/settingslib/net/DataUsageController.java b/packages/SettingsLib/src/com/android/settingslib/net/DataUsageController.java
index 994ea88..b69232c 100644
--- a/packages/SettingsLib/src/com/android/settingslib/net/DataUsageController.java
+++ b/packages/SettingsLib/src/com/android/settingslib/net/DataUsageController.java
@@ -32,7 +32,7 @@
 import android.text.format.Time;
 import android.util.Log;
 
-import com.android.settingslib.R;
+import com.android.internal.R;
 
 import java.util.Date;
 import java.util.Locale;
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/HelpUtilsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/HelpUtilsTest.java
index 56891f6..fdc42bf 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/HelpUtilsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/HelpUtilsTest.java
@@ -27,6 +27,7 @@
 import android.content.res.TypedArray;
 import android.provider.Settings;
 import android.view.MenuItem;
+import com.android.internal.R;
 
 import org.junit.Before;
 import org.junit.Test;
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index b70597f..9e88578 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -1811,10 +1811,14 @@
     <string name="report_rejected_touch" translatable="false">Report rejected touch</string>
 
     <!-- Multi-Window strings -->
-    <!-- Text that gets shown on top of current activity to inform the user that the system force-resized the current activity and that things might crash/not work properly [CHAR LIMIT=NONE] -->
+    <!-- Text that gets shown on top of current activity to inform the user that the system force-resized the current activity to be displayed in split-screen and that things might crash/not work properly [CHAR LIMIT=NONE] -->
     <string name="dock_forced_resizable">App may not work with split-screen.</string>
-    <!-- Warning message when we try to dock a non-resizeble tasks and launch it in fullscreen instead. -->
+    <!-- Warning message when we try to dock a non-resizeable task and launch it in fullscreen instead. -->
     <string name="dock_non_resizeble_failed_to_dock_text">App does not support split-screen.</string>
+    <!-- Text that gets shown on top of current activity to inform the user that the system force-resized the current activity to be displayed on a secondary display and that things might crash/not work properly [CHAR LIMIT=NONE] -->
+    <string name="forced_resizable_secondary_display">App may not work on a secondary display.</string>
+    <!-- Warning message when we try to launch a non-resizeable activity on a secondary display and launch it on the primary instead. -->
+    <string name="activity_launch_on_secondary_display_failed_text">App does not support launch on secondary displays.</string>
 
     <!-- accessibility label for button to open settings [CHAR LIMIT=NONE] -->
     <string name="accessibility_quick_settings_settings">Open settings.</string>
diff --git a/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java b/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java
index 429ace6..2f12282 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java
@@ -156,8 +156,9 @@
         public void onPinnedActivityRestartAttempt() { }
         public void onPinnedStackAnimationStarted() { }
         public void onPinnedStackAnimationEnded() { }
-        public void onActivityForcedResizable(String packageName, int taskId) { }
+        public void onActivityForcedResizable(String packageName, int taskId, int reason) { }
         public void onActivityDismissingDockedStack() { }
+        public void onActivityLaunchOnSecondaryDisplayFailed() { }
         public void onTaskProfileLocked(int taskId, int userId) { }
 
         /**
@@ -224,9 +225,9 @@
         }
 
         @Override
-        public void onActivityForcedResizable(String packageName, int taskId)
+        public void onActivityForcedResizable(String packageName, int taskId, int reason)
                 throws RemoteException {
-            mHandler.obtainMessage(H.ON_ACTIVITY_FORCED_RESIZABLE, taskId, 0, packageName)
+            mHandler.obtainMessage(H.ON_ACTIVITY_FORCED_RESIZABLE, taskId, reason, packageName)
                     .sendToTarget();
         }
 
@@ -236,6 +237,11 @@
         }
 
         @Override
+        public void onActivityLaunchOnSecondaryDisplayFailed() throws RemoteException {
+            mHandler.sendEmptyMessage(H.ON_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_FAILED);
+        }
+
+        @Override
         public void onTaskProfileLocked(int taskId, int userId) {
             mHandler.obtainMessage(H.ON_TASK_PROFILE_LOCKED, taskId, userId).sendToTarget();
         }
@@ -1235,6 +1241,7 @@
         private static final int ON_TASK_PROFILE_LOCKED = 8;
         private static final int ON_PINNED_STACK_ANIMATION_STARTED = 9;
         private static final int ON_ACTIVITY_UNPINNED = 10;
+        private static final int ON_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_FAILED = 11;
 
         @Override
         public void handleMessage(Message msg) {
@@ -1285,7 +1292,7 @@
                 case ON_ACTIVITY_FORCED_RESIZABLE: {
                     for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) {
                         mTaskStackListeners.get(i).onActivityForcedResizable(
-                                (String) msg.obj, msg.arg1);
+                                (String) msg.obj, msg.arg1, msg.arg2);
                     }
                     break;
                 }
@@ -1295,6 +1302,12 @@
                     }
                     break;
                 }
+                case ON_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_FAILED: {
+                    for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) {
+                        mTaskStackListeners.get(i).onActivityLaunchOnSecondaryDisplayFailed();
+                    }
+                    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/systemui/stackdivider/ForcedResizableInfoActivity.java b/packages/SystemUI/src/com/android/systemui/stackdivider/ForcedResizableInfoActivity.java
index 30bf060..4415bd7 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/ForcedResizableInfoActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/ForcedResizableInfoActivity.java
@@ -16,6 +16,9 @@
 
 package com.android.systemui.stackdivider;
 
+import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY;
+import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
+
 import android.annotation.Nullable;
 import android.app.Activity;
 import android.app.ActivityManager;
@@ -34,6 +37,8 @@
  */
 public class ForcedResizableInfoActivity extends Activity implements OnTouchListener {
 
+    public static final String EXTRA_FORCED_RESIZEABLE_REASON = "extra_forced_resizeable_reason";
+
     private static final long DISMISS_DELAY = 2500;
 
     private final Runnable mFinishRunnable = new Runnable() {
@@ -48,8 +53,21 @@
         super.onCreate(savedInstanceState);
         setContentView(R.layout.forced_resizable_activity);
         TextView tv = (TextView) findViewById(com.android.internal.R.id.message);
-        tv.setText(R.string.dock_forced_resizable);
-        getWindow().setTitle(getString(R.string.dock_forced_resizable));
+        int reason = getIntent().getIntExtra(EXTRA_FORCED_RESIZEABLE_REASON, -1);
+        String text;
+        switch (reason) {
+            case FORCED_RESIZEABLE_REASON_SPLIT_SCREEN:
+                text = getString(R.string.dock_forced_resizable);
+                break;
+            case FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY:
+                text = getString(R.string.forced_resizable_secondary_display);
+                break;
+            default:
+                throw new IllegalArgumentException("Unexpected forced resizeable reason: "
+                        + reason);
+        }
+        tv.setText(text);
+        getWindow().setTitle(text);
         getWindow().getDecorView().setOnTouchListener(this);
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/ForcedResizableInfoActivityController.java b/packages/SystemUI/src/com/android/systemui/stackdivider/ForcedResizableInfoActivityController.java
index 17b494e..a2c782e 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/ForcedResizableInfoActivityController.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/ForcedResizableInfoActivityController.java
@@ -16,6 +16,9 @@
 
 package com.android.systemui.stackdivider;
 
+import static com.android.systemui.stackdivider.ForcedResizableInfoActivity
+        .EXTRA_FORCED_RESIZEABLE_REASON;
+
 import android.app.ActivityOptions;
 import android.content.Context;
 import android.content.Intent;
@@ -43,7 +46,7 @@
     private static final int TIMEOUT = 1000;
     private final Context mContext;
     private final Handler mHandler = new Handler();
-    private final ArraySet<Integer> mPendingTaskIds = new ArraySet<>();
+    private final ArraySet<PendingTaskRecord> mPendingTasks = new ArraySet<>();
     private final ArraySet<String> mPackagesShownInSession = new ArraySet<>();
     private boolean mDividerDraging;
 
@@ -54,20 +57,41 @@
         }
     };
 
+    /** Record of force resized task that's pending to be handled. */
+    private class PendingTaskRecord {
+        int taskId;
+        /**
+         * {@link android.app.ITaskStackListener#FORCED_RESIZEABLE_REASON_SPLIT_SCREEN} or
+         * {@link android.app.ITaskStackListener#FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY}
+         */
+        int reason;
+
+        PendingTaskRecord(int taskId, int reason) {
+            this.taskId = taskId;
+            this.reason = reason;
+        }
+    }
+
     public ForcedResizableInfoActivityController(Context context) {
         mContext = context;
         EventBus.getDefault().register(this);
         SystemServicesProxy.getInstance(context).registerTaskStackListener(
                 new TaskStackListener() {
                     @Override
-                    public void onActivityForcedResizable(String packageName, int taskId) {
-                        activityForcedResizable(packageName, taskId);
+                    public void onActivityForcedResizable(String packageName, int taskId,
+                            int reason) {
+                        activityForcedResizable(packageName, taskId, reason);
                     }
 
                     @Override
                     public void onActivityDismissingDockedStack() {
                         activityDismissingDockedStack();
                     }
+
+                    @Override
+                    public void onActivityLaunchOnSecondaryDisplayFailed() {
+                        activityLaunchOnSecondaryDisplayFailed();
+                    }
                 });
     }
 
@@ -93,11 +117,11 @@
         showPending();
     }
 
-    private void activityForcedResizable(String packageName, int taskId) {
+    private void activityForcedResizable(String packageName, int taskId, int reason) {
         if (debounce(packageName)) {
             return;
         }
-        mPendingTaskIds.add(taskId);
+        mPendingTasks.add(new PendingTaskRecord(taskId, reason));
         postTimeout();
     }
 
@@ -106,16 +130,23 @@
                 R.string.dock_non_resizeble_failed_to_dock_text, Toast.LENGTH_SHORT));
     }
 
+    private void activityLaunchOnSecondaryDisplayFailed() {
+        EventBus.getDefault().send(new ShowUserToastEvent(
+                R.string.activity_launch_on_secondary_display_failed_text, Toast.LENGTH_SHORT));
+    }
+
     private void showPending() {
         mHandler.removeCallbacks(mTimeoutRunnable);
-        for (int i = mPendingTaskIds.size() - 1; i >= 0; i--) {
+        for (int i = mPendingTasks.size() - 1; i >= 0; i--) {
+            PendingTaskRecord pendingRecord = mPendingTasks.valueAt(i);
             Intent intent = new Intent(mContext, ForcedResizableInfoActivity.class);
             ActivityOptions options = ActivityOptions.makeBasic();
-            options.setLaunchTaskId(mPendingTaskIds.valueAt(i));
+            options.setLaunchTaskId(pendingRecord.taskId);
             options.setTaskOverlay(true, false /* canResume */);
+            intent.putExtra(EXTRA_FORCED_RESIZEABLE_REASON, pendingRecord.reason);
             mContext.startActivityAsUser(intent, options.toBundle(), UserHandle.CURRENT);
         }
-        mPendingTaskIds.clear();
+        mPendingTasks.clear();
     }
 
     private void postTimeout() {
diff --git a/services/autofill/java/com/android/server/autofill/ui/SaveUi.java b/services/autofill/java/com/android/server/autofill/ui/SaveUi.java
index f94d456..9bba1ad 100644
--- a/services/autofill/java/com/android/server/autofill/ui/SaveUi.java
+++ b/services/autofill/java/com/android/server/autofill/ui/SaveUi.java
@@ -24,6 +24,7 @@
 import android.content.IntentSender;
 import android.os.Handler;
 import android.service.autofill.SaveInfo;
+import android.text.Html;
 import android.util.ArraySet;
 import android.util.Slog;
 import android.view.Gravity;
@@ -125,23 +126,24 @@
             types.add(context.getString(R.string.autofill_save_type_email_address));
         }
 
-        final String title;
+        final CharSequence title;
         switch (types.size()) {
             case 1:
-                title = context.getString(R.string.autofill_save_title_with_type,
-                        types.valueAt(0), providerLabel);
+                title = Html.fromHtml(context.getString(R.string.autofill_save_title_with_type,
+                        types.valueAt(0), providerLabel), 0);
                 break;
             case 2:
-                title = context.getString(R.string.autofill_save_title_with_2types,
-                        types.valueAt(0), types.valueAt(1), providerLabel);
+                title = Html.fromHtml(context.getString(R.string.autofill_save_title_with_2types,
+                        types.valueAt(0), types.valueAt(1), providerLabel), 0);
                 break;
             case 3:
-                title = context.getString(R.string.autofill_save_title_with_3types,
-                        types.valueAt(0), types.valueAt(1), types.valueAt(2), providerLabel);
+                title = Html.fromHtml(context.getString(R.string.autofill_save_title_with_3types,
+                        types.valueAt(0), types.valueAt(1), types.valueAt(2), providerLabel), 0);
                 break;
             default:
                 // Use generic if more than 3 or invalid type (size 0).
-                title = context.getString(R.string.autofill_save_title, providerLabel);
+                title = Html.fromHtml(
+                        context.getString(R.string.autofill_save_title, providerLabel), 0);
         }
 
         titleView.setText(title);
@@ -183,7 +185,9 @@
         window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
         window.setGravity(Gravity.BOTTOM | Gravity.CENTER);
         window.setCloseOnTouchOutside(true);
-        window.getAttributes().width = WindowManager.LayoutParams.MATCH_PARENT;
+        final WindowManager.LayoutParams params = window.getAttributes();
+        params.width = WindowManager.LayoutParams.MATCH_PARENT;
+        params.accessibilityTitle = context.getString(R.string.autofill_save_accessibility_title);
 
         mDialog.show();
     }
diff --git a/services/core/java/com/android/server/AlarmManagerService.java b/services/core/java/com/android/server/AlarmManagerService.java
index 21dae4f..05ffcf0 100644
--- a/services/core/java/com/android/server/AlarmManagerService.java
+++ b/services/core/java/com/android/server/AlarmManagerService.java
@@ -1239,6 +1239,11 @@
                     mAllowWhileIdleDispatches.add(ent);
                 }
             }
+            if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
+                Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
+                        + " to " + a);
+            }
+
             mPendingIdleUntil = a;
             mConstants.updateAllowWhileIdleMinTimeLocked();
             needRebatch = true;
diff --git a/services/core/java/com/android/server/BluetoothManagerService.java b/services/core/java/com/android/server/BluetoothManagerService.java
index 6c4895c..6c18b26 100644
--- a/services/core/java/com/android/server/BluetoothManagerService.java
+++ b/services/core/java/com/android/server/BluetoothManagerService.java
@@ -308,6 +308,14 @@
                 if (newName != null) {
                     storeNameAndAddress(newName, null);
                 }
+            } else if (BluetoothAdapter.ACTION_BLUETOOTH_ADDRESS_CHANGED.equals(action)) {
+                String newAddress = intent.getStringExtra(BluetoothAdapter.EXTRA_BLUETOOTH_ADDRESS);
+                if (newAddress != null) {
+                    if (DBG) Slog.d(TAG, "Bluetooth Adapter address changed to " + newAddress);
+                    storeNameAndAddress(null, newAddress);
+                } else {
+                    if (DBG) Slog.e(TAG, "No Bluetooth Adapter address parameter found");
+                }
             }
         }
     };
@@ -343,6 +351,9 @@
         IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
         mContext.registerReceiver(mReceiver, filter);
+        filter = new IntentFilter(BluetoothAdapter.ACTION_BLUETOOTH_ADDRESS_CHANGED);
+        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
+        mContext.registerReceiver(mReceiver, filter);
         loadStoredNameAndAddress();
         if (isBluetoothPersistedStateOn()) {
             if (DBG) Slog.d(TAG, "Startup: Bluetooth persisted state is ON.");
diff --git a/services/core/java/com/android/server/LockSettingsService.java b/services/core/java/com/android/server/LockSettingsService.java
index 3a24091..a184d70 100644
--- a/services/core/java/com/android/server/LockSettingsService.java
+++ b/services/core/java/com/android/server/LockSettingsService.java
@@ -961,8 +961,7 @@
                     if (pi.isManagedProfile()
                             && !mLockPatternUtils.isSeparateProfileChallengeEnabled(pi.id)
                             && mStorage.hasChildProfileLock(pi.id)
-                            && mUserManager.isUserRunning(pi.id)
-                            && !mUserManager.isUserUnlocked(pi.id)) {
+                            && mUserManager.isUserRunning(pi.id)) {
                         unlockChildProfile(pi.id);
                     }
                 }
diff --git a/services/core/java/com/android/server/Watchdog.java b/services/core/java/com/android/server/Watchdog.java
index 80f89fc..feb9ce4 100644
--- a/services/core/java/com/android/server/Watchdog.java
+++ b/services/core/java/com/android/server/Watchdog.java
@@ -83,6 +83,7 @@
         "android.hardware.audio@2.0::IDevicesFactory",
         "android.hardware.bluetooth@1.0::IBluetoothHci",
         "android.hardware.camera.provider@2.4::ICameraProvider",
+        "android.hardware.graphics.composer@2.1::IComposer",
         "android.hardware.vr@1.0::IVr",
         "android.hardware.media.omx@1.0::IOmx"
     );
diff --git a/services/core/java/com/android/server/accounts/AccountManagerService.java b/services/core/java/com/android/server/accounts/AccountManagerService.java
index eb58e4c..adb55b9 100644
--- a/services/core/java/com/android/server/accounts/AccountManagerService.java
+++ b/services/core/java/com/android/server/accounts/AccountManagerService.java
@@ -5006,7 +5006,7 @@
             INotificationManager notificationManager = mInjector.getNotificationManager();
             try {
                 notificationManager.enqueueNotificationWithTag(packageName, packageName,
-                        id.mTag, id.mId, notification, new int[1], userId);
+                        id.mTag, id.mId, notification, userId);
             } catch (RemoteException e) {
                 /* ignore - local call */
             }
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index 3fe8a1e..c6e44e0 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -1728,7 +1728,7 @@
             return null;
         }
 
-        if (!whileRestarting && r.restartDelay > 0) {
+        if (!whileRestarting && mRestartingServices.contains(r)) {
             // If waiting for a restart, then do nothing.
             return null;
         }
@@ -1740,7 +1740,6 @@
         // We are now bringing the service up, so no longer in the
         // restarting state.
         if (mRestartingServices.remove(r)) {
-            r.resetRestartCounter();
             clearRestartingIfNeededLocked(r);
         }
 
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 98b31c0..d99601c 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -358,6 +358,7 @@
 import android.view.View;
 import android.view.WindowManager;
 
+import com.android.server.job.JobSchedulerInternal;
 import com.google.android.collect.Lists;
 import com.google.android.collect.Maps;
 
@@ -2114,10 +2115,9 @@
                                     new UserHandle(root.userId)))
                             .build();
                     try {
-                        int[] outId = new int[1];
                         inm.enqueueNotificationWithTag("android", "android", null,
                                 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION,
-                                notification, outId, root.userId);
+                                notification, root.userId);
                     } catch (RuntimeException e) {
                         Slog.w(ActivityManagerService.TAG,
                                 "Error showing notification for heavy-weight app", e);
@@ -2369,10 +2369,9 @@
                         .build();
 
                 try {
-                    int[] outId = new int[1];
                     inm.enqueueNotificationWithTag("android", "android", null,
                             SystemMessage.NOTE_DUMP_HEAP_NOTIFICATION,
-                            notification, outId, userId);
+                            notification, userId);
                 } catch (RuntimeException e) {
                     Slog.w(ActivityManagerService.TAG,
                             "Error showing notification for dump heap", e);
@@ -18181,6 +18180,9 @@
             return false;
         }
 
+        int oldBackupUid;
+        int newBackupUid;
+
         synchronized(this) {
             // !!! TODO: currently no check here that we're already bound
             BatteryStatsImpl.Uid.Pkg.Serv ss = null;
@@ -18221,6 +18223,8 @@
                 proc.inFullBackup = true;
             }
             r.app = proc;
+            oldBackupUid = mBackupTarget != null ? mBackupTarget.appInfo.uid : -1;
+            newBackupUid = proc.inFullBackup ? r.appInfo.uid : -1;
             mBackupTarget = r;
             mBackupAppName = app.packageName;
 
@@ -18246,6 +18250,14 @@
             // know that it's scheduled for a backup-agent operation.
         }
 
+        JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
+        if (oldBackupUid != -1) {
+            js.removeBackingUpUid(oldBackupUid);
+        }
+        if (newBackupUid != -1) {
+            js.addBackingUpUid(newBackupUid);
+        }
+
         return true;
     }
 
@@ -18258,6 +18270,9 @@
             mBackupTarget = null;
             mBackupAppName = null;
         }
+
+        JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
+        js.clearAllBackingUpUids();
     }
 
     // A backup agent has just come up
@@ -18295,6 +18310,8 @@
             return;
         }
 
+        int oldBackupUid;
+
         synchronized(this) {
             try {
                 if (mBackupAppName == null) {
@@ -18312,6 +18329,8 @@
                 updateOomAdjLocked(proc);
                 proc.inFullBackup = false;
 
+                oldBackupUid = mBackupTarget != null ? mBackupTarget.appInfo.uid : -1;
+
                 // If the app crashed during backup, 'thread' will be null here
                 if (proc.thread != null) {
                     try {
@@ -18327,7 +18346,13 @@
                 mBackupAppName = null;
             }
         }
+
+        if (oldBackupUid != -1) {
+            JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
+            js.removeBackingUpUid(oldBackupUid);
+        }
     }
+
     // =========================================================
     // BROADCASTS
     // =========================================================
diff --git a/services/core/java/com/android/server/am/ActivityRecord.java b/services/core/java/com/android/server/am/ActivityRecord.java
index 43904d6..6e84ed6 100644
--- a/services/core/java/com/android/server/am/ActivityRecord.java
+++ b/services/core/java/com/android/server/am/ActivityRecord.java
@@ -68,6 +68,7 @@
 import static android.os.Build.VERSION_CODES.O;
 import static android.os.Process.SYSTEM_UID;
 import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
+
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONFIGURATION;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SAVED_STATE;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SCREENSHOTS;
@@ -1163,6 +1164,17 @@
     }
 
     /**
+     * Check whether this activity can be launched on the specified display.
+     * @param displayId Target display id.
+     * @return {@code true} if either it is the default display or this activity is resizeable and
+     *         can be put a secondary screen.
+     */
+    boolean canBeLaunchedOnDisplay(int displayId) {
+        return service.mStackSupervisor.canPlaceEntityOnDisplay(displayId,
+                supportsResizeableMultiWindow());
+    }
+
+    /**
      * @param beforeStopping Whether this check is for an auto-enter-pip operation, that is to say
      *         the activity has requested to enter PiP when it would otherwise be stopped.
      *
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index ab70340..6010bef 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -33,6 +33,8 @@
 import static android.app.ActivityManager.StackId.LAST_STATIC_STACK_ID;
 import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
 import static android.app.ActivityManager.StackId.RECENTS_STACK_ID;
+import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY;
+import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
 import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
@@ -108,6 +110,7 @@
 import android.app.ActivityOptions;
 import android.app.AppOpsManager;
 import android.app.IActivityContainerCallback;
+import android.app.ITaskStackListener;
 import android.app.ProfilerInfo;
 import android.app.ResultInfo;
 import android.app.StatusBarManager;
@@ -485,6 +488,33 @@
         activityDisplay.onOverrideConfigurationChanged(overrideConfiguration);
     }
 
+    /** Check if placing task or activity on specified display is allowed. */
+    boolean canPlaceEntityOnDisplay(int displayId, boolean resizeable) {
+        return displayId == DEFAULT_DISPLAY || (mService.mSupportsMultiDisplay
+                && (resizeable || displayConfigMatchesGlobal(displayId)));
+    }
+
+    /**
+     * Check if configuration of specified display matches current global config.
+     * Used to check if we can put a non-resizeable activity on a secondary display and it will get
+     * the same config as on the default display.
+     * @param displayId Id of the display to check.
+     * @return {@code true} if configuration matches.
+     */
+    private boolean displayConfigMatchesGlobal(int displayId) {
+        if (displayId == DEFAULT_DISPLAY) {
+            return true;
+        }
+        if (displayId == INVALID_DISPLAY) {
+            return false;
+        }
+        final ActivityDisplay targetDisplay = mActivityDisplays.get(displayId);
+        if (targetDisplay == null) {
+            throw new IllegalArgumentException("No display found with id: " + displayId);
+        }
+        return getConfiguration().equals(targetDisplay.getConfiguration());
+    }
+
     static class FindTaskResult {
         ActivityRecord r;
         boolean matchedByRootAffinity;
@@ -2104,8 +2134,8 @@
         if (DEBUG_STACK) Slog.d(TAG_STACK,
                 "findTaskToMoveToFront: moved to front of stack=" + currentStack);
 
-        handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, currentStack.mStackId,
-                forceNonResizeable);
+        handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
+                currentStack.mStackId, forceNonResizeable);
     }
 
     boolean canUseActivityOptionsLaunchBounds(ActivityOptions options, int launchStackId) {
@@ -2156,7 +2186,7 @@
         // Return the topmost valid stack on the display.
         for (int i = activityDisplay.mStacks.size() - 1; i >= 0; --i) {
             final ActivityStack stack = activityDisplay.mStacks.get(i);
-            if (mService.mActivityStarter.isValidLaunchStackId(stack.mStackId, r)) {
+            if (mService.mActivityStarter.isValidLaunchStackId(stack.mStackId, displayId, r)) {
                 return stack;
             }
         }
@@ -2164,7 +2194,7 @@
         // If there is no valid stack on the external display - check if new dynamic stack will do.
         if (displayId != Display.DEFAULT_DISPLAY) {
             final int newDynamicStackId = getNextStackId();
-            if (mService.mActivityStarter.isValidLaunchStackId(newDynamicStackId, r)) {
+            if (mService.mActivityStarter.isValidLaunchStackId(newDynamicStackId, displayId, r)) {
                 return createStackOnDisplay(newDynamicStackId, displayId, true /*onTop*/);
             }
         }
@@ -3987,31 +4017,68 @@
         }
     }
 
-    void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId, int actualStackId) {
-        handleNonResizableTaskIfNeeded(task, preferredStackId, actualStackId,
+    void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
+            int preferredDisplayId, int actualStackId) {
+        handleNonResizableTaskIfNeeded(task, preferredStackId, preferredDisplayId, actualStackId,
                 false /* forceNonResizable */);
     }
 
-    void handleNonResizableTaskIfNeeded(
-            TaskRecord task, int preferredStackId, int actualStackId, boolean forceNonResizable) {
-        if ((!isStackDockedInEffect(actualStackId) && preferredStackId != DOCKED_STACK_ID)
-                || task.isHomeTask()) {
+    private void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
+            int preferredDisplayId, int actualStackId, boolean forceNonResizable) {
+        final boolean isSecondaryDisplayPreferred =
+                (preferredDisplayId != DEFAULT_DISPLAY && preferredDisplayId != INVALID_DISPLAY)
+                || StackId.isDynamicStack(preferredStackId);
+        if (((!isStackDockedInEffect(actualStackId) && preferredStackId != DOCKED_STACK_ID)
+                && !isSecondaryDisplayPreferred) || task.isHomeTask()) {
             return;
         }
 
+        // Handle incorrect launch/move to secondary display if needed.
+        final boolean launchOnSecondaryDisplayFailed;
+        if (isSecondaryDisplayPreferred) {
+            final int actualDisplayId = task.getStack().mDisplayId;
+            if (!task.canBeLaunchedOnDisplay(actualDisplayId)) {
+                // The task landed on an inappropriate display somehow, move it to the default
+                // display.
+                // TODO(multi-display): Find proper stack for the task on the default display.
+                mService.moveTaskToStack(task.taskId, FULLSCREEN_WORKSPACE_STACK_ID,
+                        true /* toTop */);
+                launchOnSecondaryDisplayFailed = true;
+            } else {
+                // The task might have landed on a display different from requested.
+                launchOnSecondaryDisplayFailed = actualDisplayId == DEFAULT_DISPLAY
+                        || (preferredDisplayId != INVALID_DISPLAY
+                            && preferredDisplayId != actualDisplayId);
+            }
+        } else {
+            // The task wasn't requested to be on a secondary display.
+            launchOnSecondaryDisplayFailed = false;
+        }
+
         final ActivityRecord topActivity = task.getTopActivity();
-        if (!task.supportsSplitScreen() || forceNonResizable) {
-            // Display a warning toast that we tried to put a non-dockable task in the docked stack.
-            mService.mTaskChangeNotificationController.notifyActivityDismissingDockedStack();
+        if (launchOnSecondaryDisplayFailed || !task.supportsSplitScreen() || forceNonResizable) {
+            if (launchOnSecondaryDisplayFailed) {
+                // Display a warning toast that we tried to put a non-resizeable task on a secondary
+                // display with config different from global config.
+                mService.mTaskChangeNotificationController
+                        .notifyActivityLaunchOnSecondaryDisplayFailed();
+            } else {
+                // Display a warning toast that we tried to put a non-dockable task in the docked
+                // stack.
+                mService.mTaskChangeNotificationController.notifyActivityDismissingDockedStack();
+            }
 
             // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
             // we need to move it to top of fullscreen stack, otherwise it will be covered.
             moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, actualStackId == DOCKED_STACK_ID);
         } else if (topActivity != null && topActivity.isNonResizableOrForcedResizable()
                 && !topActivity.noDisplay) {
-            String packageName = topActivity.appInfo.packageName;
+            final String packageName = topActivity.appInfo.packageName;
+            final int reason = isSecondaryDisplayPreferred
+                    ? FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY
+                    : FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
             mService.mTaskChangeNotificationController.notifyActivityForcedResizable(
-                    task.taskId, packageName);
+                    task.taskId, reason, packageName);
         }
     }
 
@@ -4084,8 +4151,8 @@
             resumeFocusedStackTopActivityLocked();
             mWindowManager.executeAppTransition();
         } else if (lockTaskModeState != LOCK_TASK_MODE_NONE) {
-            handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, task.getStackId(),
-                    true /* forceNonResizable */);
+            handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
+                    task.getStackId(), true /* forceNonResizable */);
         }
     }
 
diff --git a/services/core/java/com/android/server/am/ActivityStarter.java b/services/core/java/com/android/server/am/ActivityStarter.java
index 56594d3..1f4b21b1 100644
--- a/services/core/java/com/android/server/am/ActivityStarter.java
+++ b/services/core/java/com/android/server/am/ActivityStarter.java
@@ -979,6 +979,8 @@
 
         final int preferredLaunchStackId =
                 (mOptions != null) ? mOptions.getLaunchStackId() : INVALID_STACK_ID;
+        final int preferredLaunchDisplayId =
+                (mOptions != null) ? mOptions.getLaunchDisplayId() : DEFAULT_DISPLAY;
 
         if (reusedActivity != null) {
             // When the flags NEW_TASK and CLEAR_TASK are set, then the task gets reused but
@@ -1100,8 +1102,8 @@
 
             // Don't use mStartActivity.task to show the toast. We're not starting a new activity
             // but reusing 'top'. Fields in mStartActivity may not be fully initialized.
-            mSupervisor.handleNonResizableTaskIfNeeded(
-                    top.getTask(), preferredLaunchStackId, topStack.mStackId);
+            mSupervisor.handleNonResizableTaskIfNeeded(top.getTask(), preferredLaunchStackId,
+                    preferredLaunchDisplayId, topStack.mStackId);
 
             return START_DELIVERED_TO_TOP;
         }
@@ -1183,8 +1185,8 @@
         }
         mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);
 
-        mSupervisor.handleNonResizableTaskIfNeeded(
-                mStartActivity.getTask(), preferredLaunchStackId, mTargetStack.mStackId);
+        mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(), preferredLaunchStackId,
+                preferredLaunchDisplayId, mTargetStack.mStackId);
 
         return START_SUCCESS;
     }
@@ -1580,7 +1582,7 @@
         }
 
         mSupervisor.handleNonResizableTaskIfNeeded(intentActivity.getTask(), INVALID_STACK_ID,
-                mTargetStack.mStackId);
+                DEFAULT_DISPLAY, mTargetStack.mStackId);
 
         // If the caller has requested that the target task be reset, then do so.
         if ((mLaunchFlags & FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
@@ -2033,16 +2035,19 @@
                 canUseFocusedStack = r.isAssistantActivity();
                 break;
             case DOCKED_STACK_ID:
-                // Any activty which supports split screen can go in the docked stack.
+                // Any activity which supports split screen can go in the docked stack.
                 canUseFocusedStack = r.supportsSplitScreen();
                 break;
             case FREEFORM_WORKSPACE_STACK_ID:
-                // Any activty which supports freeform can go in the freeform stack.
+                // Any activity which supports freeform can go in the freeform stack.
                 canUseFocusedStack = r.supportsFreeform();
                 break;
             default:
-                // Dynamic stacks behave similarly to the fullscreen stack and can contain any task.
-                canUseFocusedStack = isDynamicStack(focusedStackId);
+                // Dynamic stacks behave similarly to the fullscreen stack and can contain any
+                // resizeable task.
+                // TODO: Check ActivityView after fixing b/35349678.
+                canUseFocusedStack = isDynamicStack(focusedStackId)
+                        && r.canBeLaunchedOnDisplay(focusedStack.mDisplayId);
         }
 
         return canUseFocusedStack
@@ -2082,7 +2087,7 @@
                     "Stack and display id can't be set at the same time.");
         }
 
-        if (isValidLaunchStackId(launchStackId, r)) {
+        if (isValidLaunchStackId(launchStackId, launchDisplayId, r)) {
             return mSupervisor.getStack(launchStackId, CREATE_IF_NEEDED, ON_TOP);
         }
         if (launchStackId == DOCKED_STACK_ID) {
@@ -2148,7 +2153,7 @@
         }
     }
 
-    boolean isValidLaunchStackId(int stackId, ActivityRecord r) {
+    boolean isValidLaunchStackId(int stackId, int displayId, ActivityRecord r) {
         switch (stackId) {
             case INVALID_STACK_ID:
             case HOME_STACK_ID:
@@ -2167,8 +2172,8 @@
                 return r.isAssistantActivity();
             default:
                 // TODO: Check ActivityView after fixing b/35349678.
-                if (StackId.isDynamicStack(stackId) && mService.mSupportsMultiDisplay) {
-                    return true;
+                if (StackId.isDynamicStack(stackId)) {
+                    return r.canBeLaunchedOnDisplay(displayId);
                 }
                 Slog.e(TAG, "isValidLaunchStackId: Unexpected stackId=" + stackId);
                 return false;
diff --git a/services/core/java/com/android/server/am/ServiceRecord.java b/services/core/java/com/android/server/am/ServiceRecord.java
index b57f6c3..cffa475 100644
--- a/services/core/java/com/android/server/am/ServiceRecord.java
+++ b/services/core/java/com/android/server/am/ServiceRecord.java
@@ -524,10 +524,9 @@
                             throw new RuntimeException("invalid service notification: "
                                     + foregroundNoti);
                         }
-                        int[] outId = new int[1];
                         nm.enqueueNotification(localPackageName, localPackageName,
                                 appUid, appPid, null, localForegroundId, localForegroundNoti,
-                                outId, userId);
+                                userId);
 
                         foregroundNoti = localForegroundNoti; // save it for amending next time
                     } catch (RuntimeException e) {
diff --git a/services/core/java/com/android/server/am/TaskChangeNotificationController.java b/services/core/java/com/android/server/am/TaskChangeNotificationController.java
index 94cf092..7d2bc5b 100644
--- a/services/core/java/com/android/server/am/TaskChangeNotificationController.java
+++ b/services/core/java/com/android/server/am/TaskChangeNotificationController.java
@@ -48,6 +48,7 @@
     static final int NOTIFY_TASK_SNAPSHOT_CHANGED_LISTENERS_MSG = 15;
     static final int NOTIFY_PINNED_STACK_ANIMATION_STARTED_LISTENERS_MSG = 16;
     static final int NOTIFY_ACTIVITY_UNPINNED_LISTENERS_MSG = 17;
+    static final int NOTIFY_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_FAILED_MSG = 18;
 
     // Delay in notifying task stack change listeners (in millis)
     static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_DELAY = 100;
@@ -115,13 +116,17 @@
     };
 
     private final TaskStackConsumer mNotifyActivityForcedResizable = (l, m) -> {
-        l.onActivityForcedResizable((String) m.obj, m.arg1);
+        l.onActivityForcedResizable((String) m.obj, m.arg1, m.arg2);
     };
 
     private final TaskStackConsumer mNotifyActivityDismissingDockedStack = (l, m) -> {
         l.onActivityDismissingDockedStack();
     };
 
+    private final TaskStackConsumer mNotifyActivityLaunchOnSecondaryDisplayFailed = (l, m) -> {
+        l.onActivityLaunchOnSecondaryDisplayFailed();
+    };
+
     private final TaskStackConsumer mNotifyTaskProfileLocked = (l, m) -> {
         l.onTaskProfileLocked(m.arg1, m.arg2);
     };
@@ -191,6 +196,9 @@
                 case NOTIFY_ACTIVITY_DISMISSING_DOCKED_STACK_MSG:
                     forAllRemoteListeners(mNotifyActivityDismissingDockedStack, msg);
                     break;
+                case NOTIFY_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_FAILED_MSG:
+                    forAllRemoteListeners(mNotifyActivityLaunchOnSecondaryDisplayFailed, msg);
+                    break;
                 case NOTIFY_TASK_PROFILE_LOCKED_LISTENERS_MSG:
                     forAllRemoteListeners(mNotifyTaskProfileLocked, msg);
                     break;
@@ -324,14 +332,22 @@
         forAllLocalListeners(mNotifyActivityDismissingDockedStack, message);
     }
 
-    void notifyActivityForcedResizable(int taskId, String packageName) {
+    void notifyActivityForcedResizable(int taskId, int reason, String packageName) {
         mHandler.removeMessages(NOTIFY_FORCED_RESIZABLE_MSG);
-        final Message msg = mHandler.obtainMessage(NOTIFY_FORCED_RESIZABLE_MSG, taskId,
-                0 /* unused */, packageName);
+        final Message msg = mHandler.obtainMessage(NOTIFY_FORCED_RESIZABLE_MSG, taskId, reason,
+                packageName);
         forAllLocalListeners(mNotifyActivityForcedResizable, msg);
         msg.sendToTarget();
     }
 
+    void notifyActivityLaunchOnSecondaryDisplayFailed() {
+        mHandler.removeMessages(NOTIFY_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_FAILED_MSG);
+        final Message msg = mHandler.obtainMessage(
+                NOTIFY_ACTIVITY_LAUNCH_ON_SECONDARY_DISPLAY_FAILED_MSG);
+        forAllLocalListeners(mNotifyActivityLaunchOnSecondaryDisplayFailed, 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/am/TaskRecord.java b/services/core/java/com/android/server/am/TaskRecord.java
index d42b6a7..dc636e5 100644
--- a/services/core/java/com/android/server/am/TaskRecord.java
+++ b/services/core/java/com/android/server/am/TaskRecord.java
@@ -97,6 +97,8 @@
 import static android.content.pm.ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
 import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
 import static android.provider.Settings.Secure.USER_SETUP_COMPLETE;
+import static android.view.Display.DEFAULT_DISPLAY;
+
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ADD_REMOVE;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
@@ -748,7 +750,8 @@
             supervisor.resumeFocusedStackTopActivityLocked();
         }
 
-        supervisor.handleNonResizableTaskIfNeeded(this, preferredStackId, stackId);
+        // TODO: Handle incorrect request to move before the actual move, not after.
+        supervisor.handleNonResizableTaskIfNeeded(this, preferredStackId, DEFAULT_DISPLAY, stackId);
 
         boolean successful = (preferredStackId == stackId);
         if (successful && stackId == DOCKED_STACK_ID) {
@@ -1561,6 +1564,17 @@
     }
 
     /**
+     * Check whether this task can be launched on the specified display.
+     * @param displayId Target display id.
+     * @return {@code true} if either it is the default display or this activity is resizeable and
+     *         can be put a secondary screen.
+     */
+    boolean canBeLaunchedOnDisplay(int displayId) {
+        return mService.mStackSupervisor.canPlaceEntityOnDisplay(displayId,
+                isResizeable(false /* checkSupportsPip */));
+    }
+
+    /**
      * Check that a given bounds matches the application requested orientation.
      *
      * @param bounds The bounds to be tested.
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index d2d69cb..eea5473 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -5189,7 +5189,9 @@
     }
 
     // Devices which removal triggers intent ACTION_AUDIO_BECOMING_NOISY. The intent is only
-    // sent if none of these devices is connected.
+    // sent if:
+    // - none of these devices are connected anymore after one is disconnected AND
+    // - the device being disconnected is actually used for music.
     // Access synchronized on mConnectedDevices
     int mBecomingNoisyIntentDevices =
             AudioSystem.DEVICE_OUT_WIRED_HEADSET | AudioSystem.DEVICE_OUT_WIRED_HEADPHONE |
@@ -5210,7 +5212,8 @@
                     devices |= dev;
                 }
             }
-            if (devices == device) {
+            int musicDevice = getDeviceForStream(AudioSystem.STREAM_MUSIC);
+            if ((device == musicDevice) && (device == devices)) {
                 sendMsg(mAudioHandler,
                         MSG_BROADCAST_AUDIO_BECOMING_NOISY,
                         SENDMSG_REPLACE,
@@ -5829,25 +5832,9 @@
 
     // Must be called synchronized on mConnectedDevices
     private void setForceUseInt_SyncDevices(int usage, int config) {
-        switch (usage) {
-            case AudioSystem.FOR_MEDIA:
-                if (config == AudioSystem.FORCE_NO_BT_A2DP) {
-                    mBecomingNoisyIntentDevices &= ~AudioSystem.DEVICE_OUT_ALL_A2DP;
-                } else { // config == AudioSystem.FORCE_NONE
-                    mBecomingNoisyIntentDevices |= AudioSystem.DEVICE_OUT_ALL_A2DP;
-                }
-                sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
-                        SENDMSG_NOOP, 0, 0, null, 0);
-                break;
-            case AudioSystem.FOR_DOCK:
-                if (config == AudioSystem.FORCE_ANALOG_DOCK) {
-                    mBecomingNoisyIntentDevices |= AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
-                } else { // config == AudioSystem.FORCE_NONE
-                    mBecomingNoisyIntentDevices &= ~AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
-                }
-                break;
-            default:
-                // usage doesn't affect the broadcast of ACTION_AUDIO_BECOMING_NOISY
+        if (usage == AudioSystem.FOR_MEDIA) {
+            sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
+                    SENDMSG_NOOP, 0, 0, null, 0);
         }
         AudioSystem.setForceUse(usage, config);
     }
diff --git a/services/core/java/com/android/server/connectivity/Tethering.java b/services/core/java/com/android/server/connectivity/Tethering.java
index 9d8b3d4..ac5fb43 100644
--- a/services/core/java/com/android/server/connectivity/Tethering.java
+++ b/services/core/java/com/android/server/connectivity/Tethering.java
@@ -138,7 +138,7 @@
         public boolean isCurrentlyServing() {
             switch (lastState) {
                 case IControlsTethering.STATE_TETHERED:
-                case IControlsTethering.STATE_LOCAL_HOTSPOT:
+                case IControlsTethering.STATE_LOCAL_ONLY:
                     return true;
                 default:
                     return false;
@@ -617,7 +617,7 @@
                     erroredList.add(iface);
                 } else if (tetherState.lastState == IControlsTethering.STATE_AVAILABLE) {
                     availableList.add(iface);
-                } else if (tetherState.lastState == IControlsTethering.STATE_LOCAL_HOTSPOT) {
+                } else if (tetherState.lastState == IControlsTethering.STATE_LOCAL_ONLY) {
                     localOnlyList.add(iface);
                 } else if (tetherState.lastState == IControlsTethering.STATE_TETHERED) {
                     if (cfg.isUsb(iface)) {
@@ -795,7 +795,7 @@
                         // Otherwise, assume it's a local-only hotspot request.
                         final int state = mWifiTetherRequested
                                 ? IControlsTethering.STATE_TETHERED
-                                : IControlsTethering.STATE_LOCAL_HOTSPOT;
+                                : IControlsTethering.STATE_LOCAL_ONLY;
                         tetherMatchingInterfaces(state, ConnectivityManager.TETHERING_WIFI);
                         break;
                     case WifiManager.WIFI_AP_STATE_DISABLED:
@@ -865,7 +865,7 @@
                 result = untether(chosenIface);
                 break;
             case IControlsTethering.STATE_TETHERED:
-            case IControlsTethering.STATE_LOCAL_HOTSPOT:
+            case IControlsTethering.STATE_LOCAL_ONLY:
                 result = tether(chosenIface, requestedState);
                 break;
             default:
@@ -1723,7 +1723,7 @@
                     case IControlsTethering.STATE_TETHERED:
                         pw.print("TetheredState");
                         break;
-                    case IControlsTethering.STATE_LOCAL_HOTSPOT:
+                    case IControlsTethering.STATE_LOCAL_ONLY:
                         pw.print("LocalHotspotState");
                         break;
                     default:
@@ -1778,7 +1778,7 @@
                 which = TetherMasterSM.EVENT_IFACE_SERVING_STATE_INACTIVE;
                 break;
             case IControlsTethering.STATE_TETHERED:
-            case IControlsTethering.STATE_LOCAL_HOTSPOT:
+            case IControlsTethering.STATE_LOCAL_ONLY:
                 which = TetherMasterSM.EVENT_IFACE_SERVING_STATE_ACTIVE;
                 break;
             default:
diff --git a/services/core/java/com/android/server/connectivity/tethering/IControlsTethering.java b/services/core/java/com/android/server/connectivity/tethering/IControlsTethering.java
index f3914b7..c5c86bd 100644
--- a/services/core/java/com/android/server/connectivity/tethering/IControlsTethering.java
+++ b/services/core/java/com/android/server/connectivity/tethering/IControlsTethering.java
@@ -23,9 +23,9 @@
  */
 public interface IControlsTethering {
     public final int STATE_UNAVAILABLE = 0;
-    public final int STATE_AVAILABLE = 1;
-    public final int STATE_TETHERED = 2;
-    public final int STATE_LOCAL_HOTSPOT = 3;
+    public final int STATE_AVAILABLE   = 1;
+    public final int STATE_TETHERED    = 2;
+    public final int STATE_LOCAL_ONLY  = 3;
 
     /**
      * Notify that |who| has changed its tethering state.  This may be called from any thread.
diff --git a/services/core/java/com/android/server/connectivity/tethering/IPv6TetheringCoordinator.java b/services/core/java/com/android/server/connectivity/tethering/IPv6TetheringCoordinator.java
index 5f496ca..2485654 100644
--- a/services/core/java/com/android/server/connectivity/tethering/IPv6TetheringCoordinator.java
+++ b/services/core/java/com/android/server/connectivity/tethering/IPv6TetheringCoordinator.java
@@ -172,7 +172,7 @@
         final Downstream ds = findDownstream(sm);
         if (ds == null) return null;
 
-        if (ds.mode == IControlsTethering.STATE_LOCAL_HOTSPOT) {
+        if (ds.mode == IControlsTethering.STATE_LOCAL_ONLY) {
             // Build a Unique Locally-assigned Prefix configuration.
             return getUniqueLocalConfig(mUniqueLocalPrefix, ds.subnetId);
         }
diff --git a/services/core/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachine.java b/services/core/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachine.java
index 601ed01..e21349a 100644
--- a/services/core/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachine.java
+++ b/services/core/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachine.java
@@ -194,7 +194,7 @@
                 case CMD_TETHER_REQUESTED:
                     mLastError = ConnectivityManager.TETHER_ERROR_NO_ERROR;
                     switch (message.arg1) {
-                        case IControlsTethering.STATE_LOCAL_HOTSPOT:
+                        case IControlsTethering.STATE_LOCAL_ONLY:
                             transitionTo(mLocalHotspotState);
                             break;
                         case IControlsTethering.STATE_TETHERED:
@@ -304,7 +304,7 @@
             }
 
             if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
-            sendInterfaceState(IControlsTethering.STATE_LOCAL_HOTSPOT);
+            sendInterfaceState(IControlsTethering.STATE_LOCAL_ONLY);
         }
 
         @Override
diff --git a/services/core/java/com/android/server/job/JobSchedulerInternal.java b/services/core/java/com/android/server/job/JobSchedulerInternal.java
index 75170ec..bc6bd50 100644
--- a/services/core/java/com/android/server/job/JobSchedulerInternal.java
+++ b/services/core/java/com/android/server/job/JobSchedulerInternal.java
@@ -30,4 +30,11 @@
      * Returns a list of pending jobs scheduled by the system service.
      */
     List<JobInfo> getSystemScheduledPendingJobs();
+
+    /**
+     * These are for activity manager to communicate to use what is currently performing backups.
+     */
+    void addBackingUpUid(int uid);
+    void removeBackingUpUid(int uid);
+    void clearAllBackingUpUids();
 }
diff --git a/services/core/java/com/android/server/job/JobSchedulerService.java b/services/core/java/com/android/server/job/JobSchedulerService.java
index c8bfa34..abb2b55 100644
--- a/services/core/java/com/android/server/job/JobSchedulerService.java
+++ b/services/core/java/com/android/server/job/JobSchedulerService.java
@@ -174,6 +174,11 @@
      */
     final SparseIntArray mUidPriorityOverride = new SparseIntArray();
 
+    /**
+     * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
+     */
+    final SparseIntArray mBackingUpUids = new SparseIntArray();
+
     // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
 
     /**
@@ -621,14 +626,30 @@
             jobStatus.prepareLocked(ActivityManager.getService());
 
             if (toCancel != null) {
-                cancelJobImpl(toCancel, jobStatus);
+                cancelJobImplLocked(toCancel, jobStatus);
             }
             if (work != null) {
                 // If work has been supplied, enqueue it into the new job.
                 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
             }
             startTrackingJobLocked(jobStatus, toCancel);
-            mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
+
+            // If the job is immediately ready to run, then we can just immediately
+            // put it in the pending list and try to schedule it.  This is especially
+            // important for jobs with a 0 deadline constraint, since they will happen a fair
+            // amount, we want to handle them as quickly as possible, and semantically we want to
+            // make sure we have started holding the wake lock for the job before returning to
+            // the caller.
+            // If the job is not yet ready to run, there is nothing more to do -- we are
+            // now just waiting for one of its controllers to change state and schedule
+            // the job appropriately.
+            if (isReadyToBeExecutedLocked(jobStatus)) {
+                // This is a new job, we can just immediately put it on the pending
+                // list and try to run it.
+                mJobPackageTracker.notePending(jobStatus);
+                mPendingJobs.add(jobStatus);
+                maybeRunPendingJobsLocked();
+            }
         }
         return JobScheduler.RESULT_SUCCESS;
     }
@@ -659,25 +680,23 @@
     }
 
     void cancelJobsForUser(int userHandle) {
-        List<JobStatus> jobsForUser;
         synchronized (mLock) {
-            jobsForUser = mJobs.getJobsByUser(userHandle);
-        }
-        for (int i=0; i<jobsForUser.size(); i++) {
-            JobStatus toRemove = jobsForUser.get(i);
-            cancelJobImpl(toRemove, null);
+            final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
+            for (int i=0; i<jobsForUser.size(); i++) {
+                JobStatus toRemove = jobsForUser.get(i);
+                cancelJobImplLocked(toRemove, null);
+            }
         }
     }
 
     void cancelJobsForPackageAndUid(String pkgName, int uid) {
-        List<JobStatus> jobsForUid;
         synchronized (mLock) {
-            jobsForUid = mJobs.getJobsByUid(uid);
-        }
-        for (int i = jobsForUid.size() - 1; i >= 0; i--) {
-            final JobStatus job = jobsForUid.get(i);
-            if (job.getSourcePackageName().equals(pkgName)) {
-                cancelJobImpl(job, null);
+            final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
+            for (int i = jobsForUid.size() - 1; i >= 0; i--) {
+                final JobStatus job = jobsForUid.get(i);
+                if (job.getSourcePackageName().equals(pkgName)) {
+                    cancelJobImplLocked(job, null);
+                }
             }
         }
     }
@@ -690,13 +709,12 @@
      *
      */
     public void cancelJobsForUid(int uid) {
-        List<JobStatus> jobsForUid;
         synchronized (mLock) {
-            jobsForUid = mJobs.getJobsByUid(uid);
-        }
-        for (int i=0; i<jobsForUid.size(); i++) {
-            JobStatus toRemove = jobsForUid.get(i);
-            cancelJobImpl(toRemove, null);
+            final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
+            for (int i=0; i<jobsForUid.size(); i++) {
+                JobStatus toRemove = jobsForUid.get(i);
+                cancelJobImplLocked(toRemove, null);
+            }
         }
     }
 
@@ -711,25 +729,23 @@
         JobStatus toCancel;
         synchronized (mLock) {
             toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
-        }
-        if (toCancel != null) {
-            cancelJobImpl(toCancel, null);
+            if (toCancel != null) {
+                cancelJobImplLocked(toCancel, null);
+            }
         }
     }
 
-    private void cancelJobImpl(JobStatus cancelled, JobStatus incomingJob) {
-        synchronized (mLock) {
-            if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
-            cancelled.unprepareLocked(ActivityManager.getService());
-            stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
-            // Remove from pending queue.
-            if (mPendingJobs.remove(cancelled)) {
-                mJobPackageTracker.noteNonpending(cancelled);
-            }
-            // Cancel if running.
-            stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED);
-            reportActiveLocked();
+    private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob) {
+        if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
+        cancelled.unprepareLocked(ActivityManager.getService());
+        stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
+        // Remove from pending queue.
+        if (mPendingJobs.remove(cancelled)) {
+            mJobPackageTracker.noteNonpending(cancelled);
         }
+        // Cancel if running.
+        stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED);
+        reportActiveLocked();
     }
 
     void updateUidState(int uid, int procState) {
@@ -770,8 +786,8 @@
                             mLocalDeviceIdleController.setJobsActive(true);
                         }
                     }
+                    mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
                 }
-                mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
             }
         }
     }
@@ -990,7 +1006,7 @@
      * @return A newly instantiated JobStatus with the same constraints as the last job except
      * with adjusted timing constraints.
      *
-     * @see JobHandler#maybeQueueReadyJobsForExecutionLockedH
+     * @see #maybeQueueReadyJobsForExecutionLocked
      */
     private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
         final long elapsedNowMillis = SystemClock.elapsedRealtime();
@@ -1128,7 +1144,7 @@
         mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
     }
 
-    private class JobHandler extends Handler {
+    final private class JobHandler extends Handler {
 
         public JobHandler(Looper looper) {
             super(looper);
@@ -1140,283 +1156,300 @@
                 if (!mReadyToRock) {
                     return;
                 }
-            }
-            switch (message.what) {
-                case MSG_JOB_EXPIRED:
-                    synchronized (mLock) {
+                switch (message.what) {
+                    case MSG_JOB_EXPIRED: {
                         JobStatus runNow = (JobStatus) message.obj;
                         // runNow can be null, which is a controller's way of indicating that its
                         // state is such that all ready jobs should be run immediately.
                         if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
                             mJobPackageTracker.notePending(runNow);
                             mPendingJobs.add(runNow);
+                        } else {
+                            queueReadyJobsForExecutionLocked();
                         }
-                        queueReadyJobsForExecutionLockedH();
-                    }
-                    break;
-                case MSG_CHECK_JOB:
-                    synchronized (mLock) {
+                    } break;
+                    case MSG_CHECK_JOB:
                         if (mReportedActive) {
                             // if jobs are currently being run, queue all ready jobs for execution.
-                            queueReadyJobsForExecutionLockedH();
+                            queueReadyJobsForExecutionLocked();
                         } else {
                             // Check the list of jobs and run some of them if we feel inclined.
-                            maybeQueueReadyJobsForExecutionLockedH();
+                            maybeQueueReadyJobsForExecutionLocked();
                         }
-                    }
-                    break;
-                case MSG_CHECK_JOB_GREEDY:
-                    synchronized (mLock) {
-                        queueReadyJobsForExecutionLockedH();
-                    }
-                    break;
-                case MSG_STOP_JOB:
-                    cancelJobImpl((JobStatus)message.obj, null);
-                    break;
-            }
-            maybeRunPendingJobsH();
-            // Don't remove JOB_EXPIRED in case one came along while processing the queue.
-            removeMessages(MSG_CHECK_JOB);
-        }
-
-        /**
-         * Run through list of jobs and execute all possible - at least one is expired so we do
-         * as many as we can.
-         */
-        private void queueReadyJobsForExecutionLockedH() {
-            if (DEBUG) {
-                Slog.d(TAG, "queuing all ready jobs for execution:");
-            }
-            noteJobsNonpending(mPendingJobs);
-            mPendingJobs.clear();
-            mJobs.forEachJob(mReadyQueueFunctor);
-            mReadyQueueFunctor.postProcess();
-
-            if (DEBUG) {
-                final int queuedJobs = mPendingJobs.size();
-                if (queuedJobs == 0) {
-                    Slog.d(TAG, "No jobs pending.");
-                } else {
-                    Slog.d(TAG, queuedJobs + " jobs queued.");
+                        break;
+                    case MSG_CHECK_JOB_GREEDY:
+                        queueReadyJobsForExecutionLocked();
+                        break;
+                    case MSG_STOP_JOB:
+                        cancelJobImplLocked((JobStatus) message.obj, null);
+                        break;
                 }
+                maybeRunPendingJobsLocked();
+                // Don't remove JOB_EXPIRED in case one came along while processing the queue.
+                removeMessages(MSG_CHECK_JOB);
             }
         }
+    }
 
-        class ReadyJobQueueFunctor implements JobStatusFunctor {
-            ArrayList<JobStatus> newReadyJobs;
+    /**
+     * Run through list of jobs and execute all possible - at least one is expired so we do
+     * as many as we can.
+     */
+    private void queueReadyJobsForExecutionLocked() {
+        if (DEBUG) {
+            Slog.d(TAG, "queuing all ready jobs for execution:");
+        }
+        noteJobsNonpending(mPendingJobs);
+        mPendingJobs.clear();
+        mJobs.forEachJob(mReadyQueueFunctor);
+        mReadyQueueFunctor.postProcess();
 
-            @Override
-            public void process(JobStatus job) {
-                if (isReadyToBeExecutedLocked(job)) {
-                    if (DEBUG) {
-                        Slog.d(TAG, "    queued " + job.toShortString());
-                    }
-                    if (newReadyJobs == null) {
-                        newReadyJobs = new ArrayList<JobStatus>();
-                    }
-                    newReadyJobs.add(job);
-                } else if (areJobConstraintsNotSatisfiedLocked(job)) {
-                    stopJobOnServiceContextLocked(job,
-                            JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
-                }
-            }
-
-            public void postProcess() {
-                if (newReadyJobs != null) {
-                    noteJobsPending(newReadyJobs);
-                    mPendingJobs.addAll(newReadyJobs);
-                }
-                newReadyJobs = null;
+        if (DEBUG) {
+            final int queuedJobs = mPendingJobs.size();
+            if (queuedJobs == 0) {
+                Slog.d(TAG, "No jobs pending.");
+            } else {
+                Slog.d(TAG, queuedJobs + " jobs queued.");
             }
         }
-        private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
+    }
 
-        /**
-         * The state of at least one job has changed. Here is where we could enforce various
-         * policies on when we want to execute jobs.
-         * Right now the policy is such:
-         * If >1 of the ready jobs is idle mode we send all of them off
-         * if more than 2 network connectivity jobs are ready we send them all off.
-         * If more than 4 jobs total are ready we send them all off.
-         * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
-         */
-        class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
-            int chargingCount;
-            int batteryNotLowCount;
-            int storageNotLowCount;
-            int idleCount;
-            int backoffCount;
-            int connectivityCount;
-            int contentCount;
-            List<JobStatus> runnableJobs;
+    final class ReadyJobQueueFunctor implements JobStatusFunctor {
+        ArrayList<JobStatus> newReadyJobs;
 
-            public MaybeReadyJobQueueFunctor() {
-                reset();
-            }
-
-            // Functor method invoked for each job via JobStore.forEachJob()
-            @Override
-            public void process(JobStatus job) {
-                if (isReadyToBeExecutedLocked(job)) {
-                    try {
-                        if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
-                                job.getJob().getService().getPackageName())) {
-                            Slog.w(TAG, "Aborting job " + job.getUid() + ":"
-                                    + job.getJob().toString() + " -- package not allowed to start");
-                            mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
-                            return;
-                        }
-                    } catch (RemoteException e) {
-                    }
-                    if (job.getNumFailures() > 0) {
-                        backoffCount++;
-                    }
-                    if (job.hasIdleConstraint()) {
-                        idleCount++;
-                    }
-                    if (job.hasConnectivityConstraint()) {
-                        connectivityCount++;
-                    }
-                    if (job.hasChargingConstraint()) {
-                        chargingCount++;
-                    }
-                    if (job.hasBatteryNotLowConstraint()) {
-                        batteryNotLowCount++;
-                    }
-                    if (job.hasStorageNotLowConstraint()) {
-                        storageNotLowCount++;
-                    }
-                    if (job.hasContentTriggerConstraint()) {
-                        contentCount++;
-                    }
-                    if (runnableJobs == null) {
-                        runnableJobs = new ArrayList<>();
-                    }
-                    runnableJobs.add(job);
-                } else if (areJobConstraintsNotSatisfiedLocked(job)) {
-                    stopJobOnServiceContextLocked(job,
-                            JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
-                }
-            }
-
-            public void postProcess() {
-                if (backoffCount > 0 ||
-                        idleCount >= mConstants.MIN_IDLE_COUNT ||
-                        connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
-                        chargingCount >= mConstants.MIN_CHARGING_COUNT ||
-                        batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
-                        storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
-                        contentCount >= mConstants.MIN_CONTENT_COUNT ||
-                        (runnableJobs != null
-                                && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
-                    if (DEBUG) {
-                        Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Running jobs.");
-                    }
-                    noteJobsPending(runnableJobs);
-                    mPendingJobs.addAll(runnableJobs);
-                } else {
-                    if (DEBUG) {
-                        Slog.d(TAG, "maybeQueueReadyJobsForExecutionLockedH: Not running anything.");
-                    }
-                }
-
-                // Be ready for next time
-                reset();
-            }
-
-            private void reset() {
-                chargingCount = 0;
-                idleCount =  0;
-                backoffCount = 0;
-                connectivityCount = 0;
-                batteryNotLowCount = 0;
-                storageNotLowCount = 0;
-                contentCount = 0;
-                runnableJobs = null;
-            }
-        }
-        private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
-
-        private void maybeQueueReadyJobsForExecutionLockedH() {
-            if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
-
-            noteJobsNonpending(mPendingJobs);
-            mPendingJobs.clear();
-            mJobs.forEachJob(mMaybeQueueFunctor);
-            mMaybeQueueFunctor.postProcess();
-        }
-
-        /**
-         * Criteria for moving a job into the pending queue:
-         *      - It's ready.
-         *      - It's not pending.
-         *      - It's not already running on a JSC.
-         *      - The user that requested the job is running.
-         *      - The component is enabled and runnable.
-         */
-        private boolean isReadyToBeExecutedLocked(JobStatus job) {
-            final boolean jobExists = mJobs.containsJob(job);
-            final boolean jobReady = job.isReady();
-            final boolean jobPending = mPendingJobs.contains(job);
-            final boolean jobActive = isCurrentlyActiveLocked(job);
-
-            final int userId = job.getUserId();
-            final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
-
-            if (DEBUG) {
-                Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
-                        + " exists=" + jobExists
-                        + " ready=" + jobReady + " pending=" + jobPending
-                        + " active=" + jobActive + " userStarted=" + userStarted);
-            }
-
-            // Short circuit: don't do the expensive PM check unless we really think
-            // we might need to run this job now.
-            if (!jobExists || !userStarted || !jobReady || jobPending || jobActive) {
-                return false;
-            }
-
-            final boolean componentPresent;
-            try {
-                componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
-                        job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
-                        userId) != null);
-            } catch (RemoteException e) {
-                throw e.rethrowAsRuntimeException();
-            }
-
-            if (DEBUG) {
-                Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
-                        + " componentPresent=" + componentPresent);
-            }
-
-            // Everything else checked out so far, so this is the final yes/no check
-            return componentPresent;
-        }
-
-        /**
-         * Criteria for cancelling an active job:
-         *      - It's not ready
-         *      - It's running on a JSC.
-         */
-        private boolean areJobConstraintsNotSatisfiedLocked(JobStatus job) {
-            return !job.isReady() && isCurrentlyActiveLocked(job);
-        }
-
-        /**
-         * Reconcile jobs in the pending queue against available execution contexts.
-         * A controller can force a job into the pending queue even if it's already running, but
-         * here is where we decide whether to actually execute it.
-         */
-        private void maybeRunPendingJobsH() {
-            synchronized (mLock) {
+        @Override
+        public void process(JobStatus job) {
+            if (isReadyToBeExecutedLocked(job)) {
                 if (DEBUG) {
-                    Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
+                    Slog.d(TAG, "    queued " + job.toShortString());
                 }
-                assignJobsToContextsLocked();
-                reportActiveLocked();
+                if (newReadyJobs == null) {
+                    newReadyJobs = new ArrayList<JobStatus>();
+                }
+                newReadyJobs.add(job);
+            } else if (areJobConstraintsNotSatisfiedLocked(job)) {
+                stopJobOnServiceContextLocked(job,
+                        JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
             }
         }
+
+        public void postProcess() {
+            if (newReadyJobs != null) {
+                noteJobsPending(newReadyJobs);
+                mPendingJobs.addAll(newReadyJobs);
+            }
+            newReadyJobs = null;
+        }
+    }
+    private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
+
+    /**
+     * The state of at least one job has changed. Here is where we could enforce various
+     * policies on when we want to execute jobs.
+     * Right now the policy is such:
+     * If >1 of the ready jobs is idle mode we send all of them off
+     * if more than 2 network connectivity jobs are ready we send them all off.
+     * If more than 4 jobs total are ready we send them all off.
+     * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
+     */
+    final class MaybeReadyJobQueueFunctor implements JobStatusFunctor {
+        int chargingCount;
+        int batteryNotLowCount;
+        int storageNotLowCount;
+        int idleCount;
+        int backoffCount;
+        int connectivityCount;
+        int contentCount;
+        List<JobStatus> runnableJobs;
+
+        public MaybeReadyJobQueueFunctor() {
+            reset();
+        }
+
+        // Functor method invoked for each job via JobStore.forEachJob()
+        @Override
+        public void process(JobStatus job) {
+            if (isReadyToBeExecutedLocked(job)) {
+                try {
+                    if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
+                            job.getJob().getService().getPackageName())) {
+                        Slog.w(TAG, "Aborting job " + job.getUid() + ":"
+                                + job.getJob().toString() + " -- package not allowed to start");
+                        mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
+                        return;
+                    }
+                } catch (RemoteException e) {
+                }
+                if (job.getNumFailures() > 0) {
+                    backoffCount++;
+                }
+                if (job.hasIdleConstraint()) {
+                    idleCount++;
+                }
+                if (job.hasConnectivityConstraint()) {
+                    connectivityCount++;
+                }
+                if (job.hasChargingConstraint()) {
+                    chargingCount++;
+                }
+                if (job.hasBatteryNotLowConstraint()) {
+                    batteryNotLowCount++;
+                }
+                if (job.hasStorageNotLowConstraint()) {
+                    storageNotLowCount++;
+                }
+                if (job.hasContentTriggerConstraint()) {
+                    contentCount++;
+                }
+                if (runnableJobs == null) {
+                    runnableJobs = new ArrayList<>();
+                }
+                runnableJobs.add(job);
+            } else if (areJobConstraintsNotSatisfiedLocked(job)) {
+                stopJobOnServiceContextLocked(job,
+                        JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED);
+            }
+        }
+
+        public void postProcess() {
+            if (backoffCount > 0 ||
+                    idleCount >= mConstants.MIN_IDLE_COUNT ||
+                    connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
+                    chargingCount >= mConstants.MIN_CHARGING_COUNT ||
+                    batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
+                    storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
+                    contentCount >= mConstants.MIN_CONTENT_COUNT ||
+                    (runnableJobs != null
+                            && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
+                if (DEBUG) {
+                    Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
+                }
+                noteJobsPending(runnableJobs);
+                mPendingJobs.addAll(runnableJobs);
+            } else {
+                if (DEBUG) {
+                    Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
+                }
+            }
+
+            // Be ready for next time
+            reset();
+        }
+
+        private void reset() {
+            chargingCount = 0;
+            idleCount =  0;
+            backoffCount = 0;
+            connectivityCount = 0;
+            batteryNotLowCount = 0;
+            storageNotLowCount = 0;
+            contentCount = 0;
+            runnableJobs = null;
+        }
+    }
+    private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
+
+    private void maybeQueueReadyJobsForExecutionLocked() {
+        if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
+
+        noteJobsNonpending(mPendingJobs);
+        mPendingJobs.clear();
+        mJobs.forEachJob(mMaybeQueueFunctor);
+        mMaybeQueueFunctor.postProcess();
+    }
+
+    /**
+     * Criteria for moving a job into the pending queue:
+     *      - It's ready.
+     *      - It's not pending.
+     *      - It's not already running on a JSC.
+     *      - The user that requested the job is running.
+     *      - The component is enabled and runnable.
+     */
+    private boolean isReadyToBeExecutedLocked(JobStatus job) {
+        final boolean jobReady = job.isReady();
+
+        if (DEBUG) {
+            Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
+                    + " ready=" + jobReady);
+        }
+
+        // This is a condition that is very likely to be false (most jobs that are
+        // scheduled are sitting there, not ready yet) and very cheap to check (just
+        // a few conditions on data in JobStatus).
+        if (!jobReady) {
+            return false;
+        }
+
+        final boolean jobExists = mJobs.containsJob(job);
+
+        final int userId = job.getUserId();
+        final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
+
+        if (DEBUG) {
+            Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
+                    + " exists=" + jobExists + " userStarted=" + userStarted);
+        }
+
+        // These are also fairly cheap to check, though they typically will not
+        // be conditions we fail.
+        if (!jobExists || !userStarted) {
+            return false;
+        }
+
+        final boolean jobPending = mPendingJobs.contains(job);
+        final boolean jobActive = isCurrentlyActiveLocked(job);
+
+        if (DEBUG) {
+            Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
+                    + " pending=" + jobPending + " active=" + jobActive);
+        }
+
+        // These can be a little more expensive (especially jobActive, since we need to
+        // go through the array of all potentially active jobs), so we are doing them
+        // later...  but still before checking with the package manager!
+        if (jobPending || jobActive) {
+            return false;
+        }
+
+        final boolean componentPresent;
+        try {
+            componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
+                    job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
+                    userId) != null);
+        } catch (RemoteException e) {
+            throw e.rethrowAsRuntimeException();
+        }
+
+        if (DEBUG) {
+            Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
+                    + " componentPresent=" + componentPresent);
+        }
+
+        // Everything else checked out so far, so this is the final yes/no check
+        return componentPresent;
+    }
+
+    /**
+     * Criteria for cancelling an active job:
+     *      - It's not ready
+     *      - It's running on a JSC.
+     */
+    private boolean areJobConstraintsNotSatisfiedLocked(JobStatus job) {
+        return !job.isReady() && isCurrentlyActiveLocked(job);
+    }
+
+    /**
+     * Reconcile jobs in the pending queue against available execution contexts.
+     * A controller can force a job into the pending queue even if it's already running, but
+     * here is where we decide whether to actually execute it.
+     */
+    private void maybeRunPendingJobsLocked() {
+        if (DEBUG) {
+            Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
+        }
+        assignJobsToContextsLocked();
+        reportActiveLocked();
     }
 
     private int adjustJobPriority(int curPriority, JobStatus job) {
@@ -1619,6 +1652,38 @@
                 return pendingJobs;
             }
         }
+
+        @Override
+        public void addBackingUpUid(int uid) {
+            synchronized (mLock) {
+                // No need to actually do anything here, since for a full backup the
+                // activity manager will kill the process which will kill the job (and
+                // cause it to restart, but now it can't run).
+                mBackingUpUids.put(uid, uid);
+            }
+        }
+
+        @Override
+        public void removeBackingUpUid(int uid) {
+            synchronized (mLock) {
+                mBackingUpUids.delete(uid);
+                // If there are any jobs for this uid, we need to rebuild the pending list
+                // in case they are now ready to run.
+                if (mJobs.countJobsForUid(uid) > 0) {
+                    mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
+                }
+            }
+        }
+
+        @Override
+        public void clearAllBackingUpUids() {
+            synchronized (mLock) {
+                if (mBackingUpUids.size() > 0) {
+                    mBackingUpUids.clear();
+                    mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
+                }
+            }
+        }
     }
 
     /**
@@ -1868,7 +1933,8 @@
                     return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
                 }
 
-                mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
+                queueReadyJobsForExecutionLocked();
+                maybeRunPendingJobsLocked();
             }
         } catch (RemoteException e) {
             // can't happen
@@ -2015,7 +2081,7 @@
 
                     job.dump(pw, "    ", true);
                     pw.print("    Ready: ");
-                    pw.print(mHandler.isReadyToBeExecutedLocked(job));
+                    pw.print(isReadyToBeExecutedLocked(job));
                     pw.print(" (job=");
                     pw.print(job.isReady());
                     pw.print(" user=");
@@ -2024,6 +2090,8 @@
                     pw.print(!mPendingJobs.contains(job));
                     pw.print(" !active=");
                     pw.print(!isCurrentlyActiveLocked(job));
+                    pw.print(" !backingup=");
+                    pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
                     pw.print(" comp=");
                     boolean componentPresent = false;
                     try {
@@ -2052,6 +2120,24 @@
                     pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
                 }
             }
+            if (mBackingUpUids.size() > 0) {
+                pw.println();
+                pw.println("Backing up uids:");
+                boolean first = true;
+                for (int i = 0; i < mBackingUpUids.size(); i++) {
+                    int uid = mBackingUpUids.keyAt(i);
+                    if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
+                        if (first) {
+                            pw.print("  ");
+                            first = false;
+                        } else {
+                            pw.print(", ");
+                        }
+                        pw.print(UserHandle.formatUid(uid));
+                    }
+                }
+                pw.println();
+            }
             pw.println();
             mJobPackageTracker.dump(pw, "", filterUidFinal);
             pw.println();
diff --git a/services/core/java/com/android/server/job/controllers/AppIdleController.java b/services/core/java/com/android/server/job/controllers/AppIdleController.java
index 2dbecbd..68dd00f 100644
--- a/services/core/java/com/android/server/job/controllers/AppIdleController.java
+++ b/services/core/java/com/android/server/job/controllers/AppIdleController.java
@@ -123,7 +123,8 @@
     }
 
     @Override
-    public void maybeStopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob, boolean forUpdate) {
+    public void maybeStopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
+            boolean forUpdate) {
     }
 
     @Override
diff --git a/services/core/java/com/android/server/job/controllers/BatteryController.java b/services/core/java/com/android/server/job/controllers/BatteryController.java
index 91a962d..b1f8f6b 100644
--- a/services/core/java/com/android/server/job/controllers/BatteryController.java
+++ b/services/core/java/com/android/server/job/controllers/BatteryController.java
@@ -24,6 +24,7 @@
 import android.os.BatteryManagerInternal;
 import android.os.SystemClock;
 import android.os.UserHandle;
+import android.util.ArraySet;
 import android.util.Slog;
 
 import com.android.internal.annotations.VisibleForTesting;
@@ -32,9 +33,6 @@
 import com.android.server.job.StateChangedListener;
 
 import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
 
 /**
  * Simple controller that tracks whether the phone is charging or not. The phone is considered to
@@ -47,7 +45,7 @@
     private static final Object sCreationLock = new Object();
     private static volatile BatteryController sController;
 
-    private List<JobStatus> mTrackedTasks = new ArrayList<JobStatus>();
+    private final ArraySet<JobStatus> mTrackedTasks = new ArraySet<>();
     private ChargingTracker mChargeTracker;
 
     public static BatteryController get(JobSchedulerService taskManagerService) {
@@ -82,6 +80,7 @@
     public void maybeStartTrackingJobLocked(JobStatus taskStatus, JobStatus lastJob) {
         if (taskStatus.hasPowerConstraint()) {
             mTrackedTasks.add(taskStatus);
+            taskStatus.setTrackingController(JobStatus.TRACKING_BATTERY);
             taskStatus.setChargingConstraintSatisfied(mChargeTracker.isOnStablePower());
             taskStatus.setBatteryNotLowConstraintSatisfied(mChargeTracker.isBatteryNotLow());
         }
@@ -89,7 +88,7 @@
 
     @Override
     public void maybeStopTrackingJobLocked(JobStatus taskStatus, JobStatus incomingJob, boolean forUpdate) {
-        if (taskStatus.hasPowerConstraint()) {
+        if (taskStatus.clearTrackingController(JobStatus.TRACKING_BATTERY)) {
             mTrackedTasks.remove(taskStatus);
         }
     }
@@ -103,7 +102,7 @@
         boolean reportChange = false;
         synchronized (mLock) {
             for (int i = mTrackedTasks.size() - 1; i >= 0; i--) {
-                final JobStatus ts = mTrackedTasks.get(i);
+                final JobStatus ts = mTrackedTasks.valueAt(i);
                 boolean previous = ts.setChargingConstraintSatisfied(stablePower);
                 if (previous != stablePower) {
                     reportChange = true;
@@ -251,7 +250,7 @@
         pw.print(mTrackedTasks.size());
         pw.println(":");
         for (int i = 0; i < mTrackedTasks.size(); i++) {
-            final JobStatus js = mTrackedTasks.get(i);
+            final JobStatus js = mTrackedTasks.valueAt(i);
             if (!js.shouldDump(filterUid)) {
                 continue;
             }
diff --git a/services/core/java/com/android/server/job/controllers/ConnectivityController.java b/services/core/java/com/android/server/job/controllers/ConnectivityController.java
index 5ebcc93..f426818 100644
--- a/services/core/java/com/android/server/job/controllers/ConnectivityController.java
+++ b/services/core/java/com/android/server/job/controllers/ConnectivityController.java
@@ -27,6 +27,7 @@
 import android.net.NetworkPolicyManager;
 import android.os.Process;
 import android.os.UserHandle;
+import android.util.ArraySet;
 import android.util.Slog;
 
 import com.android.internal.annotations.GuardedBy;
@@ -34,7 +35,6 @@
 import com.android.server.job.StateChangedListener;
 
 import java.io.PrintWriter;
-import java.util.ArrayList;
 
 /**
  * Handles changes in connectivity.
@@ -54,7 +54,7 @@
     private boolean mValidated;
 
     @GuardedBy("mLock")
-    private final ArrayList<JobStatus> mTrackedJobs = new ArrayList<JobStatus>();
+    private final ArraySet<JobStatus> mTrackedJobs = new ArraySet<>();
 
     /** Singleton. */
     private static ConnectivityController mSingleton;
@@ -87,13 +87,14 @@
         if (jobStatus.hasConnectivityConstraint()) {
             updateConstraintsSatisfied(jobStatus, null);
             mTrackedJobs.add(jobStatus);
+            jobStatus.setTrackingController(JobStatus.TRACKING_CONNECTIVITY);
         }
     }
 
     @Override
     public void maybeStopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
             boolean forUpdate) {
-        if (jobStatus.hasConnectivityConstraint()) {
+        if (jobStatus.clearTrackingController(JobStatus.TRACKING_CONNECTIVITY)) {
             mTrackedJobs.remove(jobStatus);
         }
     }
@@ -150,8 +151,8 @@
     private void updateTrackedJobs(int uid, NetworkCapabilities capabilities) {
         synchronized (mLock) {
             boolean changed = false;
-            for (int i = 0; i < mTrackedJobs.size(); i++) {
-                final JobStatus js = mTrackedJobs.get(i);
+            for (int i = mTrackedJobs.size()-1; i >= 0; i--) {
+                final JobStatus js = mTrackedJobs.valueAt(i);
                 if (uid == -1 || uid == js.getSourceUid()) {
                     changed |= updateConstraintsSatisfied(js, capabilities);
                 }
@@ -168,8 +169,8 @@
     @Override
     public void onNetworkActive() {
         synchronized (mLock) {
-            for (int i = 0; i < mTrackedJobs.size(); i++) {
-                final JobStatus js = mTrackedJobs.get(i);
+            for (int i = mTrackedJobs.size()-1; i >= 0; i--) {
+                final JobStatus js = mTrackedJobs.valueAt(i);
                 if (js.isReady()) {
                     if (DEBUG) {
                         Slog.d(TAG, "Running " + js + " due to network activity.");
@@ -239,7 +240,7 @@
         pw.print(mTrackedJobs.size());
         pw.println(":");
         for (int i = 0; i < mTrackedJobs.size(); i++) {
-            final JobStatus js = mTrackedJobs.get(i);
+            final JobStatus js = mTrackedJobs.valueAt(i);
             if (js.shouldDump(filterUid)) {
                 pw.print("  #");
                 js.printUniqueId(pw);
diff --git a/services/core/java/com/android/server/job/controllers/ContentObserverController.java b/services/core/java/com/android/server/job/controllers/ContentObserverController.java
index 29f0e2c..cfafc38 100644
--- a/services/core/java/com/android/server/job/controllers/ContentObserverController.java
+++ b/services/core/java/com/android/server/job/controllers/ContentObserverController.java
@@ -35,9 +35,6 @@
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Objects;
 
 /**
  * Controller for monitoring changes to content URIs through a ContentObserver.
@@ -61,11 +58,11 @@
     private static final Object sCreationLock = new Object();
     private static volatile ContentObserverController sController;
 
-    final private List<JobStatus> mTrackedTasks = new ArrayList<JobStatus>();
+    final private ArraySet<JobStatus> mTrackedTasks = new ArraySet<>();
     /**
      * Per-userid {@link JobInfo.TriggerContentUri} keyed ContentObserver cache.
      */
-    SparseArray<ArrayMap<JobInfo.TriggerContentUri, ObserverInstance>> mObservers =
+    final SparseArray<ArrayMap<JobInfo.TriggerContentUri, ObserverInstance>> mObservers =
             new SparseArray<>();
     final Handler mHandler;
 
@@ -101,6 +98,7 @@
                 Slog.i(TAG, "Tracking content-trigger job " + taskStatus);
             }
             mTrackedTasks.add(taskStatus);
+            taskStatus.setTrackingController(JobStatus.TRACKING_CONTENT);
             boolean havePendingUris = false;
             // If there is a previous job associated with the new job, propagate over
             // any pending content URI trigger reports.
@@ -156,7 +154,8 @@
     @Override
     public void maybeStopTrackingJobLocked(JobStatus taskStatus, JobStatus incomingJob,
             boolean forUpdate) {
-        if (taskStatus.hasContentTriggerConstraint()) {
+        if (taskStatus.clearTrackingController(JobStatus.TRACKING_CONTENT)) {
+            mTrackedTasks.remove(taskStatus);
             if (taskStatus.contentObserverJobInstance != null) {
                 taskStatus.contentObserverJobInstance.unscheduleLocked();
                 if (incomingJob != null) {
@@ -190,7 +189,6 @@
             if (DEBUG) {
                 Slog.i(TAG, "No longer tracking job " + taskStatus);
             }
-            mTrackedTasks.remove(taskStatus);
         }
     }
 
@@ -374,9 +372,8 @@
     @Override
     public void dumpControllerStateLocked(PrintWriter pw, int filterUid) {
         pw.println("Content:");
-        Iterator<JobStatus> it = mTrackedTasks.iterator();
-        while (it.hasNext()) {
-            JobStatus js = it.next();
+        for (int i = 0; i < mTrackedTasks.size(); i++) {
+            JobStatus js = mTrackedTasks.valueAt(i);
             if (!js.shouldDump(filterUid)) {
                 continue;
             }
diff --git a/services/core/java/com/android/server/job/controllers/DeviceIdleJobsController.java b/services/core/java/com/android/server/job/controllers/DeviceIdleJobsController.java
index f7706d7..5ccf812 100644
--- a/services/core/java/com/android/server/job/controllers/DeviceIdleJobsController.java
+++ b/services/core/java/com/android/server/job/controllers/DeviceIdleJobsController.java
@@ -164,13 +164,12 @@
 
     @Override
     public void maybeStartTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
-        synchronized (mLock) {
-            updateTaskStateLocked(jobStatus);
-        }
+        updateTaskStateLocked(jobStatus);
     }
 
     @Override
-    public void maybeStopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob, boolean forUpdate) {
+    public void maybeStopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
+            boolean forUpdate) {
     }
 
     @Override
diff --git a/services/core/java/com/android/server/job/controllers/IdleController.java b/services/core/java/com/android/server/job/controllers/IdleController.java
index 0e04d24..7e92293 100644
--- a/services/core/java/com/android/server/job/controllers/IdleController.java
+++ b/services/core/java/com/android/server/job/controllers/IdleController.java
@@ -17,7 +17,6 @@
 package com.android.server.job.controllers;
 
 import java.io.PrintWriter;
-import java.util.ArrayList;
 
 import android.app.AlarmManager;
 import android.app.PendingIntent;
@@ -27,6 +26,7 @@
 import android.content.IntentFilter;
 import android.os.SystemClock;
 import android.os.UserHandle;
+import android.util.ArraySet;
 import android.util.Slog;
 
 import com.android.server.am.ActivityManagerService;
@@ -40,7 +40,7 @@
     // screen off or dreaming for at least this long
     private long mInactivityIdleThreshold;
     private long mIdleWindowSlop;
-    final ArrayList<JobStatus> mTrackedTasks = new ArrayList<JobStatus>();
+    final ArraySet<JobStatus> mTrackedTasks = new ArraySet<>();
     IdlenessTracker mIdleTracker;
 
     // Singleton factory
@@ -69,13 +69,17 @@
     public void maybeStartTrackingJobLocked(JobStatus taskStatus, JobStatus lastJob) {
         if (taskStatus.hasIdleConstraint()) {
             mTrackedTasks.add(taskStatus);
+            taskStatus.setTrackingController(JobStatus.TRACKING_IDLE);
             taskStatus.setIdleConstraintSatisfied(mIdleTracker.isIdle());
         }
     }
 
     @Override
-    public void maybeStopTrackingJobLocked(JobStatus taskStatus, JobStatus incomingJob, boolean forUpdate) {
-        mTrackedTasks.remove(taskStatus);
+    public void maybeStopTrackingJobLocked(JobStatus taskStatus, JobStatus incomingJob,
+            boolean forUpdate) {
+        if (taskStatus.clearTrackingController(JobStatus.TRACKING_IDLE)) {
+            mTrackedTasks.remove(taskStatus);
+        }
     }
 
     /**
@@ -83,8 +87,8 @@
      */
     void reportNewIdleState(boolean isIdle) {
         synchronized (mLock) {
-            for (JobStatus task : mTrackedTasks) {
-                task.setIdleConstraintSatisfied(isIdle);
+            for (int i = mTrackedTasks.size()-1; i >= 0; i--) {
+                mTrackedTasks.valueAt(i).setIdleConstraintSatisfied(isIdle);
             }
         }
         mStateChangedListener.onControllerStateChanged();
@@ -200,7 +204,7 @@
         pw.print(mTrackedTasks.size());
         pw.println(":");
         for (int i = 0; i < mTrackedTasks.size(); i++) {
-            final JobStatus js = mTrackedTasks.get(i);
+            final JobStatus js = mTrackedTasks.valueAt(i);
             if (!js.shouldDump(filterUid)) {
                 continue;
             }
diff --git a/services/core/java/com/android/server/job/controllers/JobStatus.java b/services/core/java/com/android/server/job/controllers/JobStatus.java
index 1ab66b9..7fdb08a 100644
--- a/services/core/java/com/android/server/job/controllers/JobStatus.java
+++ b/services/core/java/com/android/server/job/controllers/JobStatus.java
@@ -128,6 +128,38 @@
     // Set to true if doze constraint was satisfied due to app being whitelisted.
     public boolean dozeWhitelisted;
 
+    /**
+     * Flag for {@link #trackingControllers}: the battery controller is currently tracking this job.
+     */
+    public static final int TRACKING_BATTERY = 1<<0;
+    /**
+     * Flag for {@link #trackingControllers}: the network connectivity controller is currently
+     * tracking this job.
+     */
+    public static final int TRACKING_CONNECTIVITY = 1<<1;
+    /**
+     * Flag for {@link #trackingControllers}: the content observer controller is currently
+     * tracking this job.
+     */
+    public static final int TRACKING_CONTENT = 1<<2;
+    /**
+     * Flag for {@link #trackingControllers}: the idle controller is currently tracking this job.
+     */
+    public static final int TRACKING_IDLE = 1<<3;
+    /**
+     * Flag for {@link #trackingControllers}: the storage controller is currently tracking this job.
+     */
+    public static final int TRACKING_STORAGE = 1<<4;
+    /**
+     * Flag for {@link #trackingControllers}: the time controller is currently tracking this job.
+     */
+    public static final int TRACKING_TIME = 1<<5;
+
+    /**
+     * Bit mask of controllers that are currently tracking the job.
+     */
+    private int trackingControllers;
+
     // These are filled in by controllers when preparing for execution.
     public ArraySet<Uri> changedUris;
     public ArraySet<String> changedAuthorities;
@@ -307,6 +339,7 @@
                     executingWork = new ArrayList<>();
                 }
                 executingWork.add(work);
+                work.bumpDeliveryCount();
             }
             return work;
         }
@@ -609,6 +642,18 @@
         return (satisfiedConstraints&constraint) != 0;
     }
 
+    boolean clearTrackingController(int which) {
+        if ((trackingControllers&which) != 0) {
+            trackingControllers &= ~which;
+            return true;
+        }
+        return false;
+    }
+
+    void setTrackingController(int which) {
+        trackingControllers |= which;
+    }
+
     public boolean shouldDump(int filterUid) {
         return filterUid == -1 || UserHandle.getAppId(getUid()) == filterUid
                 || UserHandle.getAppId(getSourceUid()) == filterUid;
@@ -617,6 +662,9 @@
     /**
      * @return Whether or not this job is ready to run, based on its requirements. This is true if
      * the constraints are satisfied <strong>or</strong> the deadline on the job has expired.
+     * TODO: This function is called a *lot*.  We should probably just have it check an
+     * already-computed boolean, which we updated whenever we see one of the states it depends
+     * on here change.
      */
     public boolean isReady() {
         // Deadline constraint trumps other constraints (except for periodic jobs where deadline
@@ -812,7 +860,8 @@
 
     private void dumpJobWorkItem(PrintWriter pw, String prefix, JobWorkItem work, int index) {
         pw.print(prefix); pw.print("  #"); pw.print(index); pw.print(": #");
-        pw.print(work.getWorkId()); pw.print(" "); pw.println(work.getIntent());
+        pw.print(work.getWorkId()); pw.print(" "); pw.print(work.getDeliveryCount());
+        pw.print("x "); pw.println(work.getIntent());
         if (work.getGrants() != null) {
             pw.print(prefix); pw.println("  URI grants:");
             ((GrantedUriPermissions)work.getGrants()).dump(pw, prefix + "    ");
@@ -925,6 +974,16 @@
                 pw.print(prefix); pw.println("Doze whitelisted: true");
             }
         }
+        if (trackingControllers != 0) {
+            pw.print(prefix); pw.print("Tracking:");
+            if ((trackingControllers&TRACKING_BATTERY) != 0) pw.print(" BATTERY");
+            if ((trackingControllers&TRACKING_CONNECTIVITY) != 0) pw.print(" CONNECTIVITY");
+            if ((trackingControllers&TRACKING_CONTENT) != 0) pw.print(" CONTENT");
+            if ((trackingControllers&TRACKING_IDLE) != 0) pw.print(" IDLE");
+            if ((trackingControllers&TRACKING_STORAGE) != 0) pw.print(" STORAGE");
+            if ((trackingControllers&TRACKING_TIME) != 0) pw.print(" TIME");
+            pw.println();
+        }
         if (changedAuthorities != null) {
             pw.print(prefix); pw.println("Changed authorities:");
             for (int i=0; i<changedAuthorities.size(); i++) {
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 60ae5a7..4fe8eca 100644
--- a/services/core/java/com/android/server/job/controllers/StorageController.java
+++ b/services/core/java/com/android/server/job/controllers/StorageController.java
@@ -20,9 +20,9 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.os.BatteryManager;
 import android.os.SystemClock;
 import android.os.UserHandle;
+import android.util.ArraySet;
 import android.util.Slog;
 
 import com.android.internal.annotations.VisibleForTesting;
@@ -31,8 +31,6 @@
 import com.android.server.storage.DeviceStorageMonitorService;
 
 import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.List;
 
 /**
  * Simple controller that tracks the status of the device's storage.
@@ -43,7 +41,7 @@
     private static final Object sCreationLock = new Object();
     private static volatile StorageController sController;
 
-    private List<JobStatus> mTrackedTasks = new ArrayList<JobStatus>();
+    private final ArraySet<JobStatus> mTrackedTasks = new ArraySet<JobStatus>();
     private StorageTracker mStorageTracker;
 
     public static StorageController get(JobSchedulerService taskManagerService) {
@@ -78,13 +76,15 @@
     public void maybeStartTrackingJobLocked(JobStatus taskStatus, JobStatus lastJob) {
         if (taskStatus.hasStorageNotLowConstraint()) {
             mTrackedTasks.add(taskStatus);
+            taskStatus.setTrackingController(JobStatus.TRACKING_STORAGE);
             taskStatus.setStorageNotLowConstraintSatisfied(mStorageTracker.isStorageNotLow());
         }
     }
 
     @Override
-    public void maybeStopTrackingJobLocked(JobStatus taskStatus, JobStatus incomingJob, boolean forUpdate) {
-        if (taskStatus.hasPowerConstraint()) {
+    public void maybeStopTrackingJobLocked(JobStatus taskStatus, JobStatus incomingJob,
+            boolean forUpdate) {
+        if (taskStatus.clearTrackingController(JobStatus.TRACKING_STORAGE)) {
             mTrackedTasks.remove(taskStatus);
         }
     }
@@ -94,7 +94,7 @@
         boolean reportChange = false;
         synchronized (mLock) {
             for (int i = mTrackedTasks.size() - 1; i >= 0; i--) {
-                final JobStatus ts = mTrackedTasks.get(i);
+                final JobStatus ts = mTrackedTasks.valueAt(i);
                 boolean previous = ts.setStorageNotLowConstraintSatisfied(storageNotLow);
                 if (previous != storageNotLow) {
                     reportChange = true;
@@ -178,7 +178,7 @@
         pw.print(mTrackedTasks.size());
         pw.println(":");
         for (int i = 0; i < mTrackedTasks.size(); i++) {
-            final JobStatus js = mTrackedTasks.get(i);
+            final JobStatus js = mTrackedTasks.valueAt(i);
             if (!js.shouldDump(filterUid)) {
                 continue;
             }
diff --git a/services/core/java/com/android/server/job/controllers/TimeController.java b/services/core/java/com/android/server/job/controllers/TimeController.java
index 0b3b00f..01c841e 100644
--- a/services/core/java/com/android/server/job/controllers/TimeController.java
+++ b/services/core/java/com/android/server/job/controllers/TimeController.java
@@ -51,7 +51,7 @@
 
     private AlarmManager mAlarmService = null;
     /** List of tracked jobs, sorted asc. by deadline */
-    private final List<JobStatus> mTrackedJobs = new LinkedList<JobStatus>();
+    private final List<JobStatus> mTrackedJobs = new LinkedList<>();
     /** Singleton. */
     private static TimeController mSingleton;
 
@@ -78,6 +78,20 @@
     public void maybeStartTrackingJobLocked(JobStatus job, JobStatus lastJob) {
         if (job.hasTimingDelayConstraint() || job.hasDeadlineConstraint()) {
             maybeStopTrackingJobLocked(job, null, false);
+
+            // First: check the constraints now, because if they are already satisfied
+            // then there is no need to track it.  This gives us a fast path for a common
+            // pattern of having a job with a 0 deadline constraint ("run immediately").
+            // Unlike most controllers, once one of our constraints has been satisfied, it
+            // will never be unsatisfied (our time base can not go backwards).
+            final long nowElapsedMillis = SystemClock.elapsedRealtime();
+            if (job.hasDeadlineConstraint() && evaluateDeadlineConstraint(job, nowElapsedMillis)) {
+                return;
+            } else if (job.hasTimingDelayConstraint() && evaluateTimingDelayConstraint(job,
+                    nowElapsedMillis)) {
+                return;
+            }
+
             boolean isInsert = false;
             ListIterator<JobStatus> it = mTrackedJobs.listIterator(mTrackedJobs.size());
             while (it.hasPrevious()) {
@@ -92,6 +106,7 @@
                 it.next();
             }
             it.add(job);
+            job.setTrackingController(JobStatus.TRACKING_TIME);
             maybeUpdateAlarmsLocked(
                     job.hasTimingDelayConstraint() ? job.getEarliestRunTime() : Long.MAX_VALUE,
                     job.hasDeadlineConstraint() ? job.getLatestRunTimeElapsed() : Long.MAX_VALUE,
@@ -102,13 +117,15 @@
     /**
      * When we stop tracking a job, we only need to update our alarms if the job we're no longer
      * tracking was the one our alarms were based off of.
-     * Really an == comparison should be enough, but why play with fate? We'll do <=.
      */
     @Override
-    public void maybeStopTrackingJobLocked(JobStatus job, JobStatus incomingJob, boolean forUpdate) {
-        if (mTrackedJobs.remove(job)) {
-            checkExpiredDelaysAndResetAlarm();
-            checkExpiredDeadlinesAndResetAlarm();
+    public void maybeStopTrackingJobLocked(JobStatus job, JobStatus incomingJob,
+            boolean forUpdate) {
+        if (job.clearTrackingController(JobStatus.TRACKING_TIME)) {
+            if (mTrackedJobs.remove(job)) {
+                checkExpiredDelaysAndResetAlarm();
+                checkExpiredDeadlinesAndResetAlarm();
+            }
         }
     }
 
@@ -147,17 +164,12 @@
                 if (!job.hasDeadlineConstraint()) {
                     continue;
                 }
-                final long jobDeadline = job.getLatestRunTimeElapsed();
 
-                if (jobDeadline <= nowElapsedMillis) {
-                    if (job.hasTimingDelayConstraint()) {
-                        job.setTimingDelayConstraintSatisfied(true);
-                    }
-                    job.setDeadlineConstraintSatisfied(true);
+                if (evaluateDeadlineConstraint(job, nowElapsedMillis)) {
                     mStateChangedListener.onRunJobNow(job);
                     it.remove();
                 } else {  // Sorted by expiry time, so take the next one and stop.
-                    nextExpiryTime = jobDeadline;
+                    nextExpiryTime = job.getLatestRunTimeElapsed();
                     nextExpiryUid = job.getSourceUid();
                     break;
                 }
@@ -166,6 +178,19 @@
         }
     }
 
+    private boolean evaluateDeadlineConstraint(JobStatus job, long nowElapsedMillis) {
+        final long jobDeadline = job.getLatestRunTimeElapsed();
+
+        if (jobDeadline <= nowElapsedMillis) {
+            if (job.hasTimingDelayConstraint()) {
+                job.setTimingDelayConstraintSatisfied(true);
+            }
+            job.setDeadlineConstraintSatisfied(true);
+            return true;
+        }
+        return false;
+    }
+
     /**
      * Handles alarm that notifies us that a job's delay has expired. Iterates through the list of
      * tracked jobs and marks them as ready as appropriate.
@@ -182,9 +207,7 @@
                 if (!job.hasTimingDelayConstraint()) {
                     continue;
                 }
-                final long jobDelayTime = job.getEarliestRunTime();
-                if (jobDelayTime <= nowElapsedMillis) {
-                    job.setTimingDelayConstraintSatisfied(true);
+                if (evaluateTimingDelayConstraint(job, nowElapsedMillis)) {
                     if (canStopTrackingJobLocked(job)) {
                         it.remove();
                     }
@@ -194,6 +217,7 @@
                 } else if (!job.isConstraintSatisfied(JobStatus.CONSTRAINT_TIMING_DELAY)) {
                     // If this job still doesn't have its delay constraint satisfied,
                     // then see if it is the next upcoming delay time for the alarm.
+                    final long jobDelayTime = job.getEarliestRunTime();
                     if (nextDelayTime > jobDelayTime) {
                         nextDelayTime = jobDelayTime;
                         nextDelayUid = job.getSourceUid();
@@ -207,6 +231,15 @@
         }
     }
 
+    private boolean evaluateTimingDelayConstraint(JobStatus job, long nowElapsedMillis) {
+        final long jobDelayTime = job.getEarliestRunTime();
+        if (jobDelayTime <= nowElapsedMillis) {
+            job.setTimingDelayConstraintSatisfied(true);
+            return true;
+        }
+        return false;
+    }
+
     private void maybeUpdateAlarmsLocked(long delayExpiredElapsed, long deadlineExpiredElapsed,
             int uid) {
         if (delayExpiredElapsed < mNextDelayExpiredElapsedMillis) {
diff --git a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
index 9157c4e..39585a1 100644
--- a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
+++ b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
@@ -1254,14 +1254,13 @@
         // TODO: move to NotificationManager once we can mock it
         try {
             final String packageName = mContext.getPackageName();
-            final int[] idReceived = new int[1];
             if (!TextUtils.isEmpty(body)) {
                 builder.setStyle(new Notification.BigTextStyle()
                         .bigText(body));
             }
             mNotifManager.enqueueNotificationWithTag(
                     packageName, packageName, notificationId.getTag(), notificationId.getId(),
-                    builder.build(), idReceived, UserHandle.USER_ALL);
+                    builder.build(), UserHandle.USER_ALL);
             mActiveNotifs.add(notificationId);
         } catch (RemoteException e) {
             // ignored; service lives in system_server
diff --git a/services/core/java/com/android/server/notification/NotificationManagerInternal.java b/services/core/java/com/android/server/notification/NotificationManagerInternal.java
index c6b0d36..4923b06 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerInternal.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerInternal.java
@@ -20,7 +20,7 @@
 
 public interface NotificationManagerInternal {
     void enqueueNotification(String pkg, String basePkg, int callingUid, int callingPid,
-            String tag, int id, Notification notification, int[] idReceived, int userId);
+            String tag, int id, Notification notification, int userId);
 
     void removeForegroundServiceFlagFromNotification(String pkg, int notificationId, int userId);
 }
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index 81a8e68b3..9f693df 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -1080,7 +1080,7 @@
                     }
                     enqueueNotificationInternal(r.sbn.getPackageName(), r.sbn.getOpPkg(),
                             r.sbn.getUid(), r.sbn.getInitialPid(), r.sbn.getTag(), r.sbn.getId(),
-                            r.sbn.getNotification(), new int[1], userId);
+                            r.sbn.getNotification(), userId);
                 } catch (Exception e) {
                     Slog.e(TAG, "Cannot un-snooze notification", e);
                 }
@@ -1558,9 +1558,9 @@
 
         @Override
         public void enqueueNotificationWithTag(String pkg, String opPkg, String tag, int id,
-                Notification notification, int[] idOut, int userId) throws RemoteException {
+                Notification notification, int userId) throws RemoteException {
             enqueueNotificationInternal(pkg, opPkg, Binder.getCallingUid(),
-                    Binder.getCallingPid(), tag, id, notification, idOut, userId);
+                    Binder.getCallingPid(), tag, id, notification, userId);
         }
 
         @Override
@@ -3095,9 +3095,9 @@
     private final NotificationManagerInternal mInternalService = new NotificationManagerInternal() {
         @Override
         public void enqueueNotification(String pkg, String opPkg, int callingUid, int callingPid,
-                String tag, int id, Notification notification, int[] idReceived, int userId) {
+                String tag, int id, Notification notification, int userId) {
             enqueueNotificationInternal(pkg, opPkg, callingUid, callingPid, tag, id, notification,
-                    idReceived, userId);
+                    userId);
         }
 
         @Override
@@ -3139,7 +3139,7 @@
 
     void enqueueNotificationInternal(final String pkg, final String opPkg, final int callingUid,
             final int callingPid, final String tag, final int id, final Notification notification,
-            int[] idOut, int incomingUserId) {
+            int incomingUserId) {
         if (DBG) {
             Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id
                     + " notification=" + notification);
@@ -3236,8 +3236,6 @@
         }
 
         mHandler.post(new EnqueueNotificationRunnable(userId, r));
-
-        idOut[0] = id;
     }
 
     private void doDebugOnlyToast(CharSequence toastText) {
diff --git a/services/core/java/com/android/server/pm/Installer.java b/services/core/java/com/android/server/pm/Installer.java
index 1e2b743..c5cefc8 100644
--- a/services/core/java/com/android/server/pm/Installer.java
+++ b/services/core/java/com/android/server/pm/Installer.java
@@ -258,10 +258,11 @@
         }
     }
 
-    public long[] getExternalSize(String uuid, int userId, int flags) throws InstallerException {
+    public long[] getExternalSize(String uuid, int userId, int flags, int[] appIds)
+            throws InstallerException {
         if (!checkBeforeRemote()) return new long[4];
         try {
-            return mInstalld.getExternalSize(uuid, userId, flags);
+            return mInstalld.getExternalSize(uuid, userId, flags, appIds);
         } catch (Exception e) {
             throw InstallerException.from(e);
         }
diff --git a/services/core/java/com/android/server/wm/DimLayerController.java b/services/core/java/com/android/server/wm/DimLayerController.java
index 3a6e328..4100446 100644
--- a/services/core/java/com/android/server/wm/DimLayerController.java
+++ b/services/core/java/com/android/server/wm/DimLayerController.java
@@ -200,8 +200,9 @@
                 // TODO: This is a work around for b/34395537 as the dim user should have cleaned-up
                 // it self when it was detached from the display. Need to investigate how the dim
                 // user is leaking...
-                Slog.wtfStack(TAG_WM, "Leaked dim user=" + user.toShortString()
-                        + " state=" + state);
+                //Slog.wtfStack(TAG_WM, "Leaked dim user=" + user.toShortString()
+                //        + " state=" + state);
+                Slog.w(TAG_WM, "Leaked dim user=" + user.toShortString() + " state=" + state);
                 removeDimLayerUser(user);
                 continue;
             }
diff --git a/services/tests/notification/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/notification/src/com/android/server/notification/NotificationManagerServiceTest.java
index 57ee928..92534a1 100644
--- a/services/tests/notification/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/notification/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -280,7 +280,7 @@
     @UiThreadTest
     public void testEnqueueNotificationWithTag_PopulatesGetActiveNotifications() throws Exception {
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", "tag", 0,
-                generateNotificationRecord(null).getNotification(), new int[1], 0);
+                generateNotificationRecord(null).getNotification(), 0);
         waitForIdle();
         StatusBarNotification[] notifs =
                 mBinderService.getActiveNotifications(PKG);
@@ -291,7 +291,7 @@
     @UiThreadTest
     public void testCancelNotificationImmediatelyAfterEnqueue() throws Exception {
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", "tag", 0,
-                generateNotificationRecord(null).getNotification(), new int[1], 0);
+                generateNotificationRecord(null).getNotification(), 0);
         mBinderService.cancelNotificationWithTag(PKG, "tag", 0, 0);
         waitForIdle();
         StatusBarNotification[] notifs =
@@ -303,10 +303,10 @@
     @UiThreadTest
     public void testCancelNotificationWhilePostedAndEnqueued() throws Exception {
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", "tag", 0,
-                generateNotificationRecord(null).getNotification(), new int[1], 0);
+                generateNotificationRecord(null).getNotification(), 0);
         waitForIdle();
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", "tag", 0,
-                generateNotificationRecord(null).getNotification(), new int[1], 0);
+                generateNotificationRecord(null).getNotification(), 0);
         mBinderService.cancelNotificationWithTag(PKG, "tag", 0, 0);
         waitForIdle();
         StatusBarNotification[] notifs =
@@ -319,7 +319,7 @@
     public void testCancelNotificationsFromListenerImmediatelyAfterEnqueue() throws Exception {
         final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", "tag",
-                sbn.getId(), sbn.getNotification(), new int[1], sbn.getUserId());
+                sbn.getId(), sbn.getNotification(), sbn.getUserId());
         mBinderService.cancelNotificationsFromListener(null, null);
         waitForIdle();
         StatusBarNotification[] notifs =
@@ -332,7 +332,7 @@
     public void testCancelAllNotificationsImmediatelyAfterEnqueue() throws Exception {
         final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", "tag",
-                sbn.getId(), sbn.getNotification(), new int[1], sbn.getUserId());
+                sbn.getId(), sbn.getNotification(), sbn.getUserId());
         mBinderService.cancelAllNotifications(PKG, sbn.getUserId());
         waitForIdle();
         StatusBarNotification[] notifs =
@@ -346,7 +346,7 @@
         final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
         sbn.getNotification().flags |= Notification.FLAG_FOREGROUND_SERVICE;
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", "tag",
-                sbn.getId(), sbn.getNotification(), new int[1], sbn.getUserId());
+                sbn.getId(), sbn.getNotification(), sbn.getUserId());
         mBinderService.cancelAllNotifications(PKG, sbn.getUserId());
         waitForIdle();
         StatusBarNotification[] notifs =
@@ -360,7 +360,7 @@
         final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
         sbn.getNotification().flags |= Notification.FLAG_FOREGROUND_SERVICE;
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", "tag",
-                sbn.getId(), sbn.getNotification(), new int[1], sbn.getUserId());
+                sbn.getId(), sbn.getNotification(), sbn.getUserId());
         mBinderService.cancelAllNotifications("other_pkg_name", sbn.getUserId());
         waitForIdle();
         StatusBarNotification[] notifs =
@@ -373,7 +373,7 @@
     public void testCancelAllNotifications_NullPkgRemovesAll() throws Exception {
         final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", "tag",
-                sbn.getId(), sbn.getNotification(), new int[1], sbn.getUserId());
+                sbn.getId(), sbn.getNotification(), sbn.getUserId());
         mBinderService.cancelAllNotifications(null, sbn.getUserId());
         waitForIdle();
         StatusBarNotification[] notifs =
@@ -386,7 +386,7 @@
     public void testCancelAllNotifications_NullPkgIgnoresUserAllNotifications() throws Exception {
         final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", "tag",
-                sbn.getId(), sbn.getNotification(), new int[1], UserHandle.USER_ALL);
+                sbn.getId(), sbn.getNotification(), UserHandle.USER_ALL);
         // Null pkg is how we signal a user switch.
         mBinderService.cancelAllNotifications(null, sbn.getUserId());
         waitForIdle();
@@ -401,7 +401,7 @@
         final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
         sbn.getNotification().flags |= Notification.FLAG_FOREGROUND_SERVICE;
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", null,
-                sbn.getId(), sbn.getNotification(), new int[1], sbn.getUserId());
+                sbn.getId(), sbn.getNotification(), sbn.getUserId());
         mInternalService.removeForegroundServiceFlagFromNotification(PKG, sbn.getId(),
                 sbn.getUserId());
         waitForIdle();
@@ -421,7 +421,7 @@
 
         Notification.TvExtender tv = new Notification.TvExtender().setChannel("foo");
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", "tag", 0,
-                generateNotificationRecord(null, tv).getNotification(), new int[1], 0);
+                generateNotificationRecord(null, tv).getNotification(), 0);
         verify(mRankingHelper, times(1)).getNotificationChannel(
                 anyString(), anyInt(), eq("foo"), anyBoolean());
     }
@@ -437,7 +437,7 @@
 
         Notification.TvExtender tv = new Notification.TvExtender().setChannel("foo");
         mBinderService.enqueueNotificationWithTag(PKG, "opPkg", "tag", 0,
-                generateNotificationRecord(null, tv).getNotification(), new int[1], 0);
+                generateNotificationRecord(null, tv).getNotification(), 0);
         verify(mRankingHelper, times(1)).getNotificationChannel(
                 anyString(), anyInt(), eq(mTestNotificationChannel.getId()), anyBoolean());
     }
diff --git a/services/tests/servicestests/src/com/android/server/BaseLockSettingsServiceTests.java b/services/tests/servicestests/src/com/android/server/BaseLockSettingsServiceTests.java
index 9343449..ca77528 100644
--- a/services/tests/servicestests/src/com/android/server/BaseLockSettingsServiceTests.java
+++ b/services/tests/servicestests/src/com/android/server/BaseLockSettingsServiceTests.java
@@ -20,40 +20,27 @@
 import static org.mockito.Matchers.anyInt;
 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.IActivityManager;
 import android.app.NotificationManager;
 import android.app.admin.DevicePolicyManager;
 import android.content.ComponentName;
-import android.content.Context;
 import android.content.pm.UserInfo;
-import android.database.sqlite.SQLiteDatabase;
 import android.os.FileUtils;
-import android.os.Handler;
 import android.os.IProgressListener;
-import android.os.RemoteException;
 import android.os.UserManager;
-import android.os.storage.IStorageManager;
 import android.security.KeyStore;
-import android.service.gatekeeper.GateKeeperResponse;
-import android.service.gatekeeper.IGateKeeperService;
 import android.test.AndroidTestCase;
 
 import com.android.internal.widget.LockPatternUtils;
-import com.android.internal.widget.VerifyCredentialResponse;
-import com.android.server.LockSettingsService.SynchronizedStrongAuthTracker;
-import com.android.server.LockSettingsStorage.CredentialHash;
-import com.android.server.MockGateKeeperService.AuthToken;
-import com.android.server.MockGateKeeperService.VerifyHandle;
 
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 
 import java.io.File;
-import java.util.Arrays;
 import java.util.ArrayList;
+import java.util.Arrays;
 
 
 public class BaseLockSettingsServiceTests extends AndroidTestCase {
@@ -110,10 +97,9 @@
         when(mUserManager.getUserInfo(eq(PRIMARY_USER_ID))).thenReturn(PRIMARY_USER_INFO);
         mPrimaryUserProfiles.add(PRIMARY_USER_INFO);
         installChildProfile(MANAGED_PROFILE_USER_ID);
-        installQuietModeChildProfile(TURNED_OFF_PROFILE_USER_ID);
+        installAndTurnOffChildProfile(TURNED_OFF_PROFILE_USER_ID);
         when(mUserManager.getProfiles(eq(PRIMARY_USER_ID))).thenReturn(mPrimaryUserProfiles);
         when(mUserManager.getUserInfo(eq(SECONDARY_USER_ID))).thenReturn(SECONDARY_USER_INFO);
-        when(mUserManager.isUserRunning(eq(MANAGED_PROFILE_USER_ID))).thenReturn(true);
 
         when(mActivityManager.unlockUser(anyInt(), any(), any(), any())).thenAnswer(
                 new Answer<Boolean>() {
@@ -139,12 +125,16 @@
         mPrimaryUserProfiles.add(userInfo);
         when(mUserManager.getUserInfo(eq(profileId))).thenReturn(userInfo);
         when(mUserManager.getProfileParent(eq(profileId))).thenReturn(PRIMARY_USER_INFO);
+        when(mUserManager.isUserRunning(eq(profileId))).thenReturn(true);
+        when(mUserManager.isUserUnlocked(eq(profileId))).thenReturn(true);
         return userInfo;
     }
 
-    private UserInfo installQuietModeChildProfile(int profileId) {
+    private UserInfo installAndTurnOffChildProfile(int profileId) {
         final UserInfo userInfo = installChildProfile(profileId);
         userInfo.flags |= UserInfo.FLAG_QUIET_MODE;
+        when(mUserManager.isUserRunning(eq(profileId))).thenReturn(false);
+        when(mUserManager.isUserUnlocked(eq(profileId))).thenReturn(false);
         return userInfo;
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/LockSettingsServiceTests.java b/services/tests/servicestests/src/com/android/server/LockSettingsServiceTests.java
index cfc3962..25cc426 100644
--- a/services/tests/servicestests/src/com/android/server/LockSettingsServiceTests.java
+++ b/services/tests/servicestests/src/com/android/server/LockSettingsServiceTests.java
@@ -98,14 +98,14 @@
         mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, false, null);
         final long primarySid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         final long profileSid = mGateKeeperService.getSecureUserId(MANAGED_PROFILE_USER_ID);
-        final long turnedOffprofileSid =
+        final long turnedOffProfileSid =
                 mGateKeeperService.getSecureUserId(TURNED_OFF_PROFILE_USER_ID);
         assertTrue(primarySid != 0);
         assertTrue(profileSid != 0);
         assertTrue(profileSid != primarySid);
-        assertTrue(turnedOffprofileSid != 0);
-        assertTrue(turnedOffprofileSid != primarySid);
-        assertTrue(turnedOffprofileSid != profileSid);
+        assertTrue(turnedOffProfileSid != 0);
+        assertTrue(turnedOffProfileSid != primarySid);
+        assertTrue(turnedOffProfileSid != profileSid);
 
         // clear auth token and wait for verify challenge from primary user to re-generate it.
         mGateKeeperService.clearAuthToken(MANAGED_PROFILE_USER_ID);
@@ -119,7 +119,7 @@
         assertNotNull(mGateKeeperService.getAuthToken(MANAGED_PROFILE_USER_ID));
         assertEquals(profileSid, mGateKeeperService.getSecureUserId(MANAGED_PROFILE_USER_ID));
 
-        // Verify that profile which arent't running (e.g. turn off work) don't get unlocked
+        // Verify that profile which aren't running (e.g. turn off work) don't get unlocked
         assertNull(mGateKeeperService.getAuthToken(TURNED_OFF_PROFILE_USER_ID));
 
         /* Currently in LockSettingsService.setLockCredential, unlockUser() is called with the new
diff --git a/services/tests/servicestests/src/com/android/server/NetworkPolicyManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/NetworkPolicyManagerServiceTest.java
index 3671e4b..ad8303a 100644
--- a/services/tests/servicestests/src/com/android/server/NetworkPolicyManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/NetworkPolicyManagerServiceTest.java
@@ -1500,7 +1500,7 @@
         final FutureAnswer<String> futureAnswer = new FutureAnswer<String>(2);
         doAnswer(futureAnswer).when(mNotifManager).enqueueNotificationWithTag(
                 anyString(), anyString(), anyString() /* capture here (index 2)*/,
-                anyInt(), isA(Notification.class), isA(int[].class), anyInt());
+                anyInt(), isA(Notification.class), anyInt());
         return futureAnswer;
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/net/ConnOnActivityStartTest.java b/services/tests/servicestests/src/com/android/server/net/ConnOnActivityStartTest.java
index f971971..9014539 100644
--- a/services/tests/servicestests/src/com/android/server/net/ConnOnActivityStartTest.java
+++ b/services/tests/servicestests/src/com/android/server/net/ConnOnActivityStartTest.java
@@ -19,6 +19,7 @@
 import static android.util.DebugUtils.valueToString;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
@@ -36,8 +37,10 @@
 import android.content.pm.IPackageDeleteObserver;
 import android.content.pm.PackageInstaller;
 import android.content.pm.PackageManager;
+import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
 import android.net.Uri;
+import android.os.BatteryManager;
 import android.os.Bundle;
 import android.os.RemoteException;
 import android.os.SystemClock;
@@ -91,11 +94,14 @@
 
     private static final String EXTRA_NETWORK_STATE_OBSERVER = TEST_PKG + ".observer";
 
-    private static final int WAIT_FOR_INSTALL_TIMEOUT_MS = 2000; // 2 sec
+    private static final long BATTERY_OFF_TIMEOUT_MS = 2000; // 2 sec
+    private static final long BATTERY_OFF_CHECK_INTERVAL_MS = 200; // 0.2 sec
 
-    private static final int NETWORK_CHECK_TIMEOUT_MS = 6000; // 6 sec
+    private static final long WAIT_FOR_INSTALL_TIMEOUT_MS = 2000; // 2 sec
 
-    private static final int SCREEN_ON_DELAY_MS = 500; // 0.5 sec
+    private static final long NETWORK_CHECK_TIMEOUT_MS = 6000; // 6 sec
+
+    private static final long SCREEN_ON_DELAY_MS = 500; // 0.5 sec
 
     private static final String NETWORK_STATUS_SEPARATOR = "\\|";
 
@@ -104,6 +110,8 @@
     private static Context mContext;
     private static UiDevice mUiDevice;
     private static int mTestPkgUid;
+    private static BatteryManager mBatteryManager;
+    private static ConnectivityManager mConnectivityManager;
 
     @BeforeClass
     public static void setUpOnce() throws Exception {
@@ -114,6 +122,10 @@
         mContext.getPackageManager().setApplicationEnabledSetting(TEST_PKG,
                 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
         mTestPkgUid = mContext.getPackageManager().getPackageUid(TEST_PKG, 0);
+
+        mBatteryManager = (BatteryManager) mContext.getSystemService(Context.BATTERY_SERVICE);
+        mConnectivityManager = (ConnectivityManager) mContext.getSystemService(
+                Context.CONNECTIVITY_SERVICE);
     }
 
     @AfterClass
@@ -130,6 +142,9 @@
 
     @Test
     public void testStartActivity_batterySaver() throws Exception {
+        if (!isNetworkAvailable()) {
+            fail("Device doesn't have network connectivity");
+        }
         setBatterySaverMode(true);
         try {
             testConnOnActivityStart("testStartActivity_batterySaver");
@@ -140,6 +155,9 @@
 
     @Test
     public void testStartActivity_dataSaver() throws Exception {
+        if (!isNetworkAvailable()) {
+            fail("Device doesn't have network connectivity");
+        }
         setDataSaverMode(true);
         try {
             testConnOnActivityStart("testStartActivity_dataSaver");
@@ -150,6 +168,9 @@
 
     @Test
     public void testStartActivity_dozeMode() throws Exception {
+        if (!isNetworkAvailable()) {
+            fail("Device doesn't have network connectivity");
+        }
         setDozeMode(true);
         try {
             testConnOnActivityStart("testStartActivity_dozeMode");
@@ -160,6 +181,9 @@
 
     @Test
     public void testStartActivity_appStandby() throws Exception {
+        if (!isNetworkAvailable()) {
+            fail("Device doesn't have network connectivity");
+        }
         try{
             turnBatteryOff();
             setAppIdle(true);
@@ -174,6 +198,9 @@
 
     @Test
     public void testStartActivity_backgroundRestrict() throws Exception {
+        if (!isNetworkAvailable()) {
+            fail("Device doesn't have network connectivity");
+        }
         updateRestrictBackgroundBlacklist(true);
         try {
             testConnOnActivityStart("testStartActivity_backgroundRestrict");
@@ -271,6 +298,15 @@
 
     private void turnBatteryOff() throws Exception {
         executeCommand("cmd battery unplug");
+        assertBatteryOff();
+    }
+
+    private void assertBatteryOff() throws Exception {
+        final long endTime = SystemClock.uptimeMillis() + BATTERY_OFF_TIMEOUT_MS;
+        while (mBatteryManager.isCharging() && SystemClock.uptimeMillis() < endTime) {
+            SystemClock.sleep(BATTERY_OFF_CHECK_INTERVAL_MS);
+        }
+        assertFalse("Power should be disconnected", mBatteryManager.isCharging());
     }
 
     private void turnBatteryOn() throws Exception {
@@ -309,6 +345,11 @@
                 + maxTries + " attempts. Last result: '" + result + "'");
     }
 
+    private boolean isNetworkAvailable() throws Exception {
+        final NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
+        return networkInfo != null && networkInfo.isConnected();
+    }
+
     private void startActivityAndCheckNetworkAccess() throws Exception {
         final CountDownLatch latch = new CountDownLatch(1);
         final Intent launchIntent = new Intent().setComponent(
diff --git a/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java b/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java
index b5a6178..3fd1d55 100644
--- a/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java
@@ -120,15 +120,7 @@
     }
 
     public void testGetUserSize() throws Exception {
-        int[] appIds = null;
-
-        final PackageManager pm = getContext().getPackageManager();
-        for (ApplicationInfo app : pm.getInstalledApplications(0)) {
-            final int appId = UserHandle.getAppId(app.uid);
-            if (!ArrayUtils.contains(appIds, appId)) {
-                appIds = ArrayUtils.appendInt(appIds, appId);
-            }
-        }
+        final int[] appIds = getAppIds(UserHandle.USER_SYSTEM);
 
         final PackageStats stats = new PackageStats("android");
         final PackageStats quotaStats = new PackageStats("android");
@@ -147,13 +139,15 @@
     }
 
     public void testGetExternalSize() throws Exception {
+        final int[] appIds = getAppIds(UserHandle.USER_SYSTEM);
+
         mManual.start();
-        final long[] stats = mInstaller.getExternalSize(null, UserHandle.USER_SYSTEM, 0);
+        final long[] stats = mInstaller.getExternalSize(null, UserHandle.USER_SYSTEM, 0, appIds);
         mManual.stop();
 
         mQuota.start();
         final long[] quotaStats = mInstaller.getExternalSize(null, UserHandle.USER_SYSTEM,
-                Installer.FLAG_USE_QUOTA);
+                Installer.FLAG_USE_QUOTA, appIds);
         mQuota.stop();
 
         for (int i = 0; i < stats.length; i++) {
@@ -161,6 +155,18 @@
         }
     }
 
+    private int[] getAppIds(int userId) {
+        int[] appIds = null;
+        for (ApplicationInfo app : getContext().getPackageManager().getInstalledApplicationsAsUser(
+                PackageManager.MATCH_UNINSTALLED_PACKAGES, userId)) {
+            final int appId = UserHandle.getAppId(app.uid);
+            if (!ArrayUtils.contains(appIds, appId)) {
+                appIds = ArrayUtils.appendInt(appIds, appId);
+            }
+        }
+        return appIds;
+    }
+
     private static void checkEquals(String msg, PackageStats a, PackageStats b) {
         checkEquals(msg + " codeSize", a.codeSize, b.codeSize);
         checkEquals(msg + " dataSize", a.dataSize, b.dataSize);
diff --git a/services/usage/java/com/android/server/usage/StorageStatsService.java b/services/usage/java/com/android/server/usage/StorageStatsService.java
index 094c7bd..2ebf5fc 100644
--- a/services/usage/java/com/android/server/usage/StorageStatsService.java
+++ b/services/usage/java/com/android/server/usage/StorageStatsService.java
@@ -235,7 +235,14 @@
             final int appId = UserHandle.getUserId(appInfo.uid);
             final String[] packageNames = new String[] { packageName };
             final long[] ceDataInodes = new long[1];
-            final String[] codePaths = new String[] { appInfo.getCodePath() };
+            String[] codePaths = new String[0];
+
+            if (appInfo.isSystemApp() && !appInfo.isUpdatedSystemApp()) {
+                // We don't count code baked into system image
+            } else {
+                codePaths = ArrayUtils.appendElement(String.class, codePaths,
+                        appInfo.getCodePath());
+            }
 
             final PackageStats stats = new PackageStats(TAG);
             try {
@@ -261,12 +268,18 @@
 
         final String[] packageNames = mPackage.getPackagesForUid(uid);
         final long[] ceDataInodes = new long[packageNames.length];
-        final String[] codePaths = new String[packageNames.length];
+        String[] codePaths = new String[0];
 
         for (int i = 0; i < packageNames.length; i++) {
             try {
-                codePaths[i] = mPackage.getApplicationInfoAsUser(packageNames[i],
-                        PackageManager.MATCH_UNINSTALLED_PACKAGES, userId).getCodePath();
+                final ApplicationInfo appInfo = mPackage.getApplicationInfoAsUser(packageNames[i],
+                        PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
+                if (appInfo.isSystemApp() && !appInfo.isUpdatedSystemApp()) {
+                    // We don't count code baked into system image
+                } else {
+                    codePaths = ArrayUtils.appendElement(String.class, codePaths,
+                            appInfo.getCodePath());
+                }
             } catch (NameNotFoundException e) {
                 throw new ParcelableException(e);
             }
@@ -297,15 +310,7 @@
                     android.Manifest.permission.INTERACT_ACROSS_USERS, TAG);
         }
 
-        int[] appIds = null;
-        for (ApplicationInfo app : mPackage.getInstalledApplicationsAsUser(
-                PackageManager.MATCH_UNINSTALLED_PACKAGES, userId)) {
-            final int appId = UserHandle.getAppId(app.uid);
-            if (!ArrayUtils.contains(appIds, appId)) {
-                appIds = ArrayUtils.appendInt(appIds, appId);
-            }
-        }
-
+        final int[] appIds = getAppIds(userId);
         final PackageStats stats = new PackageStats(TAG);
         try {
             mInstaller.getUserSize(volumeUuid, userId, getDefaultFlags(), appIds, stats);
@@ -330,12 +335,14 @@
                     android.Manifest.permission.INTERACT_ACROSS_USERS, TAG);
         }
 
+        final int[] appIds = getAppIds(userId);
         final long[] stats;
         try {
-            stats = mInstaller.getExternalSize(volumeUuid, userId, getDefaultFlags());
+            stats = mInstaller.getExternalSize(volumeUuid, userId, getDefaultFlags(), appIds);
 
             if (SystemProperties.getBoolean(PROP_VERIFY_STORAGE, false)) {
-                final long[] manualStats = mInstaller.getExternalSize(volumeUuid, userId, 0);
+                final long[] manualStats = mInstaller.getExternalSize(volumeUuid, userId, 0,
+                        appIds);
                 checkEquals("External " + userId, manualStats, stats);
             }
         } catch (InstallerException e) {
@@ -347,9 +354,22 @@
         res.audioBytes = stats[1];
         res.videoBytes = stats[2];
         res.imageBytes = stats[3];
+        res.appBytes = stats[4];
         return res;
     }
 
+    private int[] getAppIds(int userId) {
+        int[] appIds = null;
+        for (ApplicationInfo app : mPackage.getInstalledApplicationsAsUser(
+                PackageManager.MATCH_UNINSTALLED_PACKAGES, userId)) {
+            final int appId = UserHandle.getAppId(app.uid);
+            if (!ArrayUtils.contains(appIds, appId)) {
+                appIds = ArrayUtils.appendInt(appIds, appId);
+            }
+        }
+        return appIds;
+    }
+
     private static int getDefaultFlags() {
         if (SystemProperties.getBoolean(PROP_DISABLE_QUOTA, false)) {
             return 0;
diff --git a/services/usb/java/com/android/server/usb/UsbDeviceManager.java b/services/usb/java/com/android/server/usb/UsbDeviceManager.java
index 31595a6..3f6f8ec 100644
--- a/services/usb/java/com/android/server/usb/UsbDeviceManager.java
+++ b/services/usb/java/com/android/server/usb/UsbDeviceManager.java
@@ -63,6 +63,7 @@
 import java.util.HashMap;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Random;
 import java.util.Scanner;
 import java.util.Set;
 
@@ -537,6 +538,7 @@
                     oldFunctions = UsbManager.USB_FUNCTION_NONE;
                 }
 
+                Slog.i(TAG, "Setting adb to " + String.valueOf(enable));
                 setEnabledFunctions(oldFunctions, true, mUsbDataUnlocked);
                 updateAdbNotification();
             }
@@ -764,15 +766,16 @@
 
             // send broadcast intent only if the USB state has changed
             if (!isUsbStateChanged(intent)) {
-                if (DEBUG) {
-                    Slog.d(TAG, "skip broadcasting " + intent + " extras: " + intent.getExtras());
-                }
+                Slog.i(TAG, "skip broadcasting " + intent + " extras: " + intent.getExtras());
                 return;
             }
-
-            if (DEBUG) Slog.d(TAG, "broadcasting " + intent + " extras: " + intent.getExtras());
-            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
             mBroadcastedIntent = intent;
+
+            Random rand = new Random();
+            intent.putExtra("random_tag", rand.nextInt(1000));
+            Slog.i(TAG, "broadcasting " + intent + " extras: " + intent.getExtras());
+            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
+            intent.removeExtra("random_tag");
         }
 
         private void updateUsbFunctions() {
@@ -845,8 +848,10 @@
                         updateCurrentAccessory();
                     }
                     if (mBootCompleted) {
+                        Slog.i(TAG, "update state " + mConnected + " " + mConfigured);
                         if (!mConnected) {
                             // restore defaults when USB is disconnected
+                            Slog.i(TAG, "Disconnect, setting usb functions to null");
                             setEnabledFunctions(null, false, false);
                         }
                         updateUsbStateBroadcastIfNeeded(false);
@@ -880,6 +885,7 @@
                     break;
                 case MSG_SET_CURRENT_FUNCTIONS:
                     String functions = (String) msg.obj;
+                    Slog.i(TAG, "Getting setFunction command for " + functions);
                     setEnabledFunctions(functions, false, msg.arg1 == 1);
                     break;
                 case MSG_UPDATE_USER_RESTRICTIONS:
@@ -887,6 +893,8 @@
                     final boolean forceRestart = mUsbDataUnlocked
                             && isUsbDataTransferActive()
                             && !isUsbTransferAllowed();
+                    Slog.i(TAG, "Updating user restrictions, force restart is "
+                            + String.valueOf(forceRestart));
                     setEnabledFunctions(
                             mCurrentFunctions, forceRestart, mUsbDataUnlocked && !forceRestart);
                     break;
@@ -901,6 +909,7 @@
                         updateUsbStateBroadcastIfNeeded(false);
                         mPendingBootBroadcast = false;
                     }
+                    Slog.i(TAG, "Boot complete, setting default functions");
                     setEnabledFunctions(null, false, false);
                     if (mCurrentAccessory != null) {
                         getCurrentSettings().accessoryAttached(mCurrentAccessory);
@@ -918,6 +927,7 @@
                             Slog.v(TAG, "Current user switched to " + msg.arg1
                                     + "; resetting USB host stack for MTP or PTP");
                             // avoid leaking sensitive data from previous user
+                            Slog.i(TAG, "User Switched, kicking usb stack");
                             setEnabledFunctions(mCurrentFunctions, true, false);
                         }
                         mCurrentUser = msg.arg1;
diff --git a/telecomm/java/android/telecom/TelecomManager.java b/telecomm/java/android/telecom/TelecomManager.java
index 0342da7..0a47a98 100644
--- a/telecomm/java/android/telecom/TelecomManager.java
+++ b/telecomm/java/android/telecom/TelecomManager.java
@@ -16,6 +16,7 @@
 
 import android.Manifest;
 import android.annotation.RequiresPermission;
+import android.annotation.SuppressAutoDoc;
 import android.annotation.SystemApi;
 import android.content.ComponentName;
 import android.content.Context;
@@ -46,6 +47,7 @@
  * permissions declared in its manifest file. Where permissions apply, they are noted in the method
  * descriptions.
  */
+@SuppressAutoDoc
 public class TelecomManager {
 
     /**
diff --git a/tests/net/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachineTest.java b/tests/net/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachineTest.java
index caf1a55..a3f33dc 100644
--- a/tests/net/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachineTest.java
+++ b/tests/net/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachineTest.java
@@ -32,7 +32,6 @@
 import static android.net.ConnectivityManager.TETHERING_USB;
 import static android.net.ConnectivityManager.TETHERING_WIFI;
 import static com.android.server.connectivity.tethering.IControlsTethering.STATE_AVAILABLE;
-import static com.android.server.connectivity.tethering.IControlsTethering.STATE_LOCAL_HOTSPOT;
 import static com.android.server.connectivity.tethering.IControlsTethering.STATE_TETHERED;
 import static com.android.server.connectivity.tethering.IControlsTethering.STATE_UNAVAILABLE;
 
diff --git a/wifi/java/android/net/wifi/IWifiManager.aidl b/wifi/java/android/net/wifi/IWifiManager.aidl
index 1852feb..229aa97 100644
--- a/wifi/java/android/net/wifi/IWifiManager.aidl
+++ b/wifi/java/android/net/wifi/IWifiManager.aidl
@@ -125,6 +125,10 @@
 
     void setWifiApEnabled(in WifiConfiguration wifiConfig, boolean enable);
 
+    boolean startSoftAp(in WifiConfiguration wifiConfig);
+
+    boolean stopSoftAp();
+
     int getWifiApEnabledState();
 
     WifiConfiguration getWifiApConfiguration();
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
index 7268ee5..ed54c3b 100644
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ b/wifi/java/android/net/wifi/WifiManager.java
@@ -16,6 +16,7 @@
 
 package android.net.wifi;
 
+import android.annotation.Nullable;
 import android.annotation.SdkConstant;
 import android.annotation.SdkConstant.SdkConstantType;
 import android.annotation.SystemApi;
@@ -1731,6 +1732,39 @@
     }
 
     /**
+     * Start SoftAp mode with the specified configuration.
+     * Note that starting in access point mode disables station
+     * mode operation
+     * @param wifiConfig SSID, security and channel details as
+     *        part of WifiConfiguration
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     *
+     * @hide
+     */
+    public boolean startSoftAp(@Nullable WifiConfiguration wifiConfig) {
+        try {
+            return mService.startSoftAp(wifiConfig);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Stop SoftAp mode.
+     * Note that stopping softap mode will restore the previous wifi mode.
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     *
+     * @hide
+     */
+    public boolean stopSoftAp() {
+        try {
+            return mService.stopSoftAp();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Gets the Wi-Fi enabled state.
      * @return One of {@link #WIFI_AP_STATE_DISABLED},
      *         {@link #WIFI_AP_STATE_DISABLING}, {@link #WIFI_AP_STATE_ENABLED},