Merge "Add an api to verify if ro.device_owner was set" into nyc-mr1-dev
diff --git a/cmds/bootanimation/BootAnimation.cpp b/cmds/bootanimation/BootAnimation.cpp
index e849f4b..a8dc3f6 100644
--- a/cmds/bootanimation/BootAnimation.cpp
+++ b/cmds/bootanimation/BootAnimation.cpp
@@ -202,25 +202,25 @@
 
     switch (bitmap.colorType()) {
         case kN32_SkColorType:
-            if (tw != w || th != h) {
+            if (!mUseNpotTextures && (tw != w || th != h)) {
                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
                         GL_UNSIGNED_BYTE, 0);
                 glTexSubImage2D(GL_TEXTURE_2D, 0,
                         0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, p);
             } else {
-                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
+                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
                         GL_UNSIGNED_BYTE, p);
             }
             break;
 
         case kRGB_565_SkColorType:
-            if (tw != w || th != h) {
+            if (!mUseNpotTextures && (tw != w || th != h)) {
                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
                         GL_UNSIGNED_SHORT_5_6_5, 0);
                 glTexSubImage2D(GL_TEXTURE_2D, 0,
                         0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, p);
             } else {
-                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
+                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
                         GL_UNSIGNED_SHORT_5_6_5, p);
             }
             break;
@@ -695,6 +695,20 @@
         mClockEnabled = false;
     }
 
+    // Check if npot textures are supported
+    mUseNpotTextures = false;
+    String8 gl_extensions;
+    const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
+    if (!exts) {
+        glGetError();
+    } else {
+        gl_extensions.setTo(exts);
+        if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
+            (gl_extensions.find("GL_OES_texture_npot") != -1)) {
+            mUseNpotTextures = true;
+        }
+    }
+
     // Blend required to draw time on top of animation frames.
     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
     glShadeModel(GL_FLAT);
@@ -839,9 +853,13 @@
                 break;
         }
 
-        // free the textures for this part
+    }
+
+    // Free textures created for looping parts now that the animation is done.
+    for (const Animation::Part& part : animation.parts) {
         if (part.count != 1) {
-            for (size_t j=0 ; j<fcount ; j++) {
+            const size_t fcount = part.frames.size();
+            for (size_t j = 0; j < fcount; j++) {
                 const Animation::Frame& frame(part.frames[j]);
                 glDeleteTextures(1, &frame.tid);
             }
diff --git a/cmds/bootanimation/BootAnimation.h b/cmds/bootanimation/BootAnimation.h
index a093c9b..85724f4 100644
--- a/cmds/bootanimation/BootAnimation.h
+++ b/cmds/bootanimation/BootAnimation.h
@@ -130,6 +130,7 @@
     Texture     mClock;
     int         mWidth;
     int         mHeight;
+    bool        mUseNpotTextures = false;
     EGLDisplay  mDisplay;
     EGLDisplay  mContext;
     EGLDisplay  mSurface;
diff --git a/cmds/bootanimation/bootanim.rc b/cmds/bootanimation/bootanim.rc
index ee0d0b8..7344ba7 100644
--- a/cmds/bootanimation/bootanim.rc
+++ b/cmds/bootanimation/bootanim.rc
@@ -4,3 +4,4 @@
     group graphics audio
     disabled
     oneshot
+    writepid /dev/stune/top-app/tasks
\ No newline at end of file
diff --git a/core/java/android/content/ContentProviderClient.java b/core/java/android/content/ContentProviderClient.java
index e49eb34..9221fbb 100644
--- a/core/java/android/content/ContentProviderClient.java
+++ b/core/java/android/content/ContentProviderClient.java
@@ -147,7 +147,13 @@
             if (cursor == null) {
                 return null;
             }
-            return new CursorWrapperInner(cursor);
+
+            if ("com.google.android.gms".equals(mPackageName)) {
+                // They're casting to a concrete subclass, sigh
+                return cursor;
+            } else {
+                return new CursorWrapperInner(cursor);
+            }
         } catch (DeadObjectException e) {
             if (!mStable) {
                 mContentResolver.unstableProviderDied(mContentProvider);
diff --git a/core/java/android/content/pm/LauncherApps.java b/core/java/android/content/pm/LauncherApps.java
index 528fe20..2133222 100644
--- a/core/java/android/content/pm/LauncherApps.java
+++ b/core/java/android/content/pm/LauncherApps.java
@@ -164,17 +164,19 @@
         }
 
         /**
-         * Indicates that one or more shortcuts (which may be dynamic and/or pinned)
+         * Indicates that one or more shortcuts of any kinds (dynamic, pinned, or manifest)
          * have been added, updated or removed.
          *
          * <p>Only the applications that are allowed to access the shortcut information,
          * as defined in {@link #hasShortcutHostPermission()}, will receive it.
          *
          * @param packageName The name of the package that has the shortcuts.
-         * @param shortcuts all shortcuts from the package (dynamic, manifest and/or pinned).
-         *    Only "key" information will be provided, as defined in
+         * @param shortcuts all shortcuts from the package (dynamic, manifest and/or pinned) will
+         *    be passed. Only "key" information will be provided, as defined in
          *    {@link ShortcutInfo#hasKeyFieldsOnly()}.
          * @param user The UserHandle of the profile that generated the change.
+         *
+         * @see ShortcutManager
          */
         public void onShortcutsChanged(@NonNull String packageName,
                 @NonNull List<ShortcutInfo> shortcuts, @NonNull UserHandle user) {
@@ -222,7 +224,17 @@
 
         /**
          * Requests "key" fields only.  See {@link ShortcutInfo#hasKeyFieldsOnly()} for which
-         * fields are available.
+         * fields are available.  This allows quicker access to shortcut information in order to
+         * determine in-memory cache in the caller needs to be updated.
+         *
+         * <p>Typically, launcher applications cache all or most shortcuts' information
+         * in memory in order to show shortcuts without a delay.  When they want to update their
+         * cache (e.g. when their process restart), they can fetch all shortcuts' information with
+         * with this flag, then check {@link ShortcutInfo#getLastChangedTimestamp()} for each
+         * shortcut and issue a second call to fetch the non-key information of only updated
+         * shortcuts.
+         *
+         * @see ShortcutManager
          */
         public static final int FLAG_GET_KEY_FIELDS_ONLY = 1 << 2;
 
@@ -255,8 +267,8 @@
         }
 
         /**
-         * If non-zero, returns only shortcuts that have been added or updated since the timestamp,
-         * which is a milliseconds since the Epoch.
+         * If non-zero, returns only shortcuts that have been added or updated since the timestamp.
+         * Units are as per {@link System#currentTimeMillis()}.
          */
         public ShortcutQuery setChangedSince(long changedSince) {
             mChangedSince = changedSince;
@@ -273,7 +285,7 @@
 
         /**
          * If non-null, return only the specified shortcuts by ID.  When setting this field,
-         * a packange name must also be set with {@link #setPackage}.
+         * a package name must also be set with {@link #setPackage}.
          */
         public ShortcutQuery setShortcutIds(@Nullable List<String> shortcutIds) {
             mShortcutIds = shortcutIds;
@@ -291,7 +303,13 @@
         }
 
         /**
-         * Set query options.
+         * Set query options.  At least one of the {@code MATCH} flags should be set.  (Otherwise
+         * no shortcuts will be returned.)
+         *
+         * @see {@link #FLAG_MATCH_DYNAMIC}
+         * @see {@link #FLAG_MATCH_PINNED}
+         * @see {@link #FLAG_MATCH_MANIFEST}
+         * @see {@link #FLAG_GET_KEY_FIELDS_ONLY}
          */
         public ShortcutQuery setQueryFlags(@QueryFlags int queryFlags) {
             mQueryFlags = queryFlags;
@@ -460,10 +478,14 @@
      *
      * <p>Only the default launcher can access the shortcut information.
      *
-     * <p>Note when this method returns {@code false}, that may be a temporary situation because
+     * <p>Note when this method returns {@code false}, it may be a temporary situation because
      * the user is trying a new launcher application.  The user may decide to change the default
-     * launcher to the calling application again, so even if a launcher application loses
+     * launcher back to the calling application again, so even if a launcher application loses
      * this permission, it does <b>not</b> have to purge pinned shortcut information.
+     * Also in this situation, pinned shortcuts can still be started, even though the caller
+     * no longer has the shortcut host permission.
+     *
+     * @see ShortcutManager
      */
     public boolean hasShortcutHostPermission() {
         try {
@@ -474,7 +496,7 @@
     }
 
     /**
-     * Returns the IDs of {@link ShortcutInfo}s that match {@code query}.
+     * Returns {@link ShortcutInfo}s that match {@code query}.
      *
      * <p>Callers must be allowed to access the shortcut information, as defined in {@link
      * #hasShortcutHostPermission()}.
@@ -483,6 +505,8 @@
      * @param user The UserHandle of the profile.
      *
      * @return the IDs of {@link ShortcutInfo}s that match the query.
+     *
+     * @see ShortcutManager
      */
     @Nullable
     public List<ShortcutInfo> getShortcuts(@NonNull ShortcutQuery query,
@@ -523,6 +547,8 @@
      * @param packageName The target package name.
      * @param shortcutIds The IDs of the shortcut to be pinned.
      * @param user The UserHandle of the profile.
+     *
+     * @see ShortcutManager
      */
     public void pinShortcuts(@NonNull String packageName, @NonNull List<String> shortcutIds,
             @NonNull UserHandle user) {
@@ -586,11 +612,17 @@
     /**
      * Returns the icon for this shortcut, without any badging for the profile.
      *
+     * <p>Callers must be allowed to access the shortcut information, as defined in {@link
+     * #hasShortcutHostPermission()}.
+     *
      * @param density The preferred density of the icon, zero for default density. Use
      * density DPI values from {@link DisplayMetrics}.
+     *
+     * @return The drawable associated with the shortcut.
+     *
+     * @see ShortcutManager
      * @see #getShortcutBadgedIconDrawable(ShortcutInfo, int)
      * @see DisplayMetrics
-     * @return The drawable associated with the shortcut.
      */
     public Drawable getShortcutIconDrawable(@NonNull ShortcutInfo shortcut, int density) {
         if (shortcut.hasIconFile()) {
@@ -628,10 +660,15 @@
     /**
      * Returns the shortcut icon with badging appropriate for the profile.
      *
+     * <p>Callers must be allowed to access the shortcut information, as defined in {@link
+     * #hasShortcutHostPermission()}.
+     *
      * @param density Optional density for the icon, or 0 to use the default density. Use
-     * {@link DisplayMetrics} for DPI values.
-     * @see DisplayMetrics
      * @return A badged icon for the shortcut.
+     *
+     * @see ShortcutManager
+     * @see #getShortcutBadgedIconDrawable(ShortcutInfo, int)
+     * @see DisplayMetrics
      */
     public Drawable getShortcutBadgedIconDrawable(ShortcutInfo shortcut, int density) {
         final Drawable originalIcon = getShortcutIconDrawable(shortcut, density);
@@ -641,7 +678,7 @@
     }
 
     /**
-     * Launches a shortcut.
+     * Starts a shortcut.
      *
      * <p>Callers must be allowed to access the shortcut information, as defined in {@link
      * #hasShortcutHostPermission()}.
diff --git a/core/java/android/content/pm/ShortcutInfo.java b/core/java/android/content/pm/ShortcutInfo.java
index 39e15e0..8ea77d6 100644
--- a/core/java/android/content/pm/ShortcutInfo.java
+++ b/core/java/android/content/pm/ShortcutInfo.java
@@ -22,8 +22,10 @@
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.LauncherApps.ShortcutQuery;
 import android.content.res.Resources;
 import android.content.res.Resources.NotFoundException;
+import android.graphics.Bitmap;
 import android.graphics.drawable.Icon;
 import android.os.Bundle;
 import android.os.Parcel;
@@ -42,20 +44,10 @@
 import java.util.List;
 import java.util.Set;
 
-// TODO Enhance javadoc
 /**
+ * Represents a "launcher shortcut" that can be published via {@link ShortcutManager}.
  *
- * Represents a shortcut from an application.
- *
- * <p>Notes about icons:
- * <ul>
- *     <li>If an {@link Icon} is a resource, the system keeps the package name and the resource ID.
- *     Otherwise, the bitmap is fetched when it's registered to ShortcutManager,
- *     then shrunk if necessary, and persisted.
- *     <li>The system disallows byte[] icons, because they can easily go over the binder size limit.
- * </ul>
- *
- * @see {@link ShortcutManager}.
+ * @see ShortcutManager
  */
 public final class ShortcutInfo implements Parcelable {
     static final String TAG = "Shortcut";
@@ -149,7 +141,7 @@
     public @interface CloneFlags {}
 
     /**
-     * Shortcut category for
+     * Shortcut category for messaging related actions, such as chat.
      */
     public static final String SHORTCUT_CATEGORY_CONVERSATION = "android.shortcut.conversation";
 
@@ -665,6 +657,8 @@
 
     /**
      * Builder class for {@link ShortcutInfo} objects.
+     *
+     * @see ShortcutManager
      */
     public static class Builder {
         private final Context mContext;
@@ -727,19 +721,25 @@
         }
 
         /**
-         * Sets the target activity. A shortcut will be shown with this activity on the launcher.
+         * Sets the target activity.  A shortcut will be shown along with this activity's icon
+         * on the launcher.
          *
-         * <p>Only "main" activities -- i.e. ones with an intent filter for
-         * {@link Intent#ACTION_MAIN} and {@link Intent#CATEGORY_LAUNCHER} can be target activities.
+         * <p>This is a mandatory field when publishing a new shortcut with
+         * {@link ShortcutManager#addDynamicShortcuts(List)} or
+         * {@link ShortcutManager#setDynamicShortcuts(List)}.
          *
-         * <p>By default, the first main activity defined in the application manifest will be
+         * <ul>
+         * <li>Only "main" activities (ones with an intent filter for
+         * {@link Intent#ACTION_MAIN} and {@link Intent#CATEGORY_LAUNCHER}) can be target
+         * activities.
+         *
+         * <li>By default, the first main activity defined in the application manifest will be
          * the target.
          *
-         * <p>The package name of the target activity must match the package name of the shortcut
-         * publisher.
+         * <li>A target activity must belong to the publisher application.
+         * </ul>
          *
-         * <p>This has nothing to do with the activity that this shortcut will launch.  This is
-         * a hint to the launcher app about which launcher icon to associate this shortcut with.
+         * @see ShortcutInfo#getActivity()
          */
         @NonNull
         public Builder setActivity(@NonNull ComponentName activity) {
@@ -748,18 +748,23 @@
         }
 
         /**
-         * Sets an icon.
+         * Sets an icon of a shortcut.
          *
-         * <ul>
-         *     <li>Tints set by {@link Icon#setTint} or {@link Icon#setTintList} are not supported.
-         *     <li>Bitmaps and resources are supported, but "content:" URIs are not supported.
-         * </ul>
-         *
-         * <p>For performance and security reasons, icons will <b>NOT</b> be available on instances
-         * returned by {@link ShortcutManager} or {@link LauncherApps}.  Default launcher application
-         * can use {@link LauncherApps#getShortcutIconDrawable(ShortcutInfo, int)}
+         * <p>Icons are not available on {@link ShortcutInfo} instances
+         * returned by {@link ShortcutManager} or {@link LauncherApps}.  The default launcher
+         * application can use {@link LauncherApps#getShortcutIconDrawable(ShortcutInfo, int)}
          * or {@link LauncherApps#getShortcutBadgedIconDrawable(ShortcutInfo, int)} to fetch
          * shortcut icons.
+         *
+         * <p>Tints set with {@link Icon#setTint} or {@link Icon#setTintList} are not supported
+         * and will be ignored.
+         *
+         * <p>Only icons created with {@link Icon#createWithBitmap(Bitmap)} and
+         * {@link Icon#createWithResource} are supported.  Other types such as URI based icons
+         * are not supported.
+         *
+         * @see LauncherApps#getShortcutIconDrawable(ShortcutInfo, int)
+         * @see LauncherApps#getShortcutBadgedIconDrawable(ShortcutInfo, int)
          */
         @NonNull
         public Builder setIcon(Icon icon) {
@@ -781,11 +786,15 @@
         /**
          * Sets the short title of a shortcut.
          *
-         * <p>This is a mandatory field, unless it's passed to
-         * {@link ShortcutManager#updateShortcuts(List)}.
+         * <p>This is a mandatory field when publishing a new shortcut with
+         * {@link ShortcutManager#addDynamicShortcuts(List)} or
+         * {@link ShortcutManager#setDynamicShortcuts(List)}.
          *
-         * <p>This field is intended for a concise description of a shortcut displayed under
-         * an icon.  The recommend max length is 10 characters.
+         * <p>This field is intended for a concise description of a shortcut.
+         *
+         * <p>The recommended max length is 10 characters.
+         *
+         * @see ShortcutInfo#getShortLabel()
          */
         @NonNull
         public Builder setShortLabel(@NonNull CharSequence shortLabel) {
@@ -809,8 +818,11 @@
          * Sets the text of a shortcut.
          *
          * <p>This field is intended to be more descriptive than the shortcut title.  The launcher
-         * shows this instead of the short title, when it has enough space.
-         * The recommend max length is 25 characters.
+         * shows this instead of the short title when it has enough space.
+         *
+         * <p>The recommend max length is 25 characters.
+         *
+         * @see ShortcutInfo#getLongLabel()
          */
         @NonNull
         public Builder setLongLabel(@NonNull CharSequence longLabel) {
@@ -854,6 +866,11 @@
             return this;
         }
 
+        /**
+         * Sets the message that should be shown when a shortcut is launched when disabled.
+         *
+         * @see ShortcutInfo#getDisabledMessage()
+         */
         @NonNull
         public Builder setDisabledMessage(@NonNull CharSequence disabledMessage) {
             Preconditions.checkState(
@@ -869,6 +886,7 @@
          * categorise shortcuts.
          *
          * @see #SHORTCUT_CATEGORY_CONVERSATION
+         * @see ShortcutInfo#getCategories()
          */
         @NonNull
         public Builder setCategories(Set<String> categories) {
@@ -877,8 +895,22 @@
         }
 
         /**
-         * Sets the intent of a shortcut.  This is a mandatory field.  The extras must only contain
-         * persistable information.  (See {@link PersistableBundle}).
+         * Sets the intent of a shortcut.
+         *
+         * <p>This is a mandatory field when publishing a new shortcut with
+         * {@link ShortcutManager#addDynamicShortcuts(List)} or
+         * {@link ShortcutManager#setDynamicShortcuts(List)}.
+         *
+         * <p>A shortcut can launch any intent that the publisher application has a permission to
+         * launch -- for example, a shortcut can launch an unexported activity within the publisher
+         * application.
+         *
+         * <p>A shortcut intent doesn't have to point at the target activity.
+         *
+         * <p>{@code intent} can contain extras, but only values of the primitive types are
+         * supported so the system can persist them.
+         *
+         * @see ShortcutInfo#getIntent()
          */
         @NonNull
         public Builder setIntent(@NonNull Intent intent) {
@@ -890,6 +922,8 @@
         /**
          * "Rank" of a shortcut, which is a non-negative value that's used by the launcher app
          * to sort shortcuts.
+         *
+         * See {@link ShortcutInfo#getRank()} for details.
          */
         @NonNull
         public Builder setRank(int rank) {
@@ -903,7 +937,7 @@
          * Extras that application can set to any purposes.
          *
          * <p>Applications can store any meta-data of
-         * shortcuts in this, and retrieve later from {@link ShortcutInfo#getExtras()}.
+         * shortcuts in extras, and retrieve later from {@link ShortcutInfo#getExtras()}.
          */
         @NonNull
         public Builder setExtras(@NonNull PersistableBundle extras) {
@@ -921,7 +955,11 @@
     }
 
     /**
-     * Return the ID of the shortcut.
+     * Returns the ID of a shortcut.
+     *
+     * <p>Shortcut IDs are unique within each publisher application, and must be stable across
+     * devices to that shortcuts will still be valid when restored.  See {@link ShortcutManager}
+     * for details.
      */
     @NonNull
     public String getId() {
@@ -929,7 +967,7 @@
     }
 
     /**
-     * Return the package name of the creator application.
+     * Return the package name of the publisher application.
      */
     @NonNull
     public String getPackage() {
@@ -937,11 +975,10 @@
     }
 
     /**
-     * Return the target activity, which may be null, in which case the shortcut is not associated
-     * with a specific activity.
+     * Return the target activity.
      *
-     * <p>This has nothing to do with the activity that this shortcut will launch.  This is
-     * a hint to the launcher app that on which launcher icon this shortcut should be shown.
+     * <p>This has nothing to do with the activity that this shortcut will launch.  Launcher
+     * applications should show a shortcut along with the launcher icon for this activity.
      *
      * @see Builder#setActivity
      */
@@ -956,11 +993,7 @@
     }
 
     /**
-     * Icon.
-     *
-     * For performance reasons, this will <b>NOT</b> be available when an instance is returned
-     * by {@link ShortcutManager} or {@link LauncherApps}.  A launcher application needs to use
-     * other APIs in LauncherApps to fetch the bitmap.
+     * Returns the shortcut icon.
      *
      * @hide
      */
@@ -996,10 +1029,9 @@
     }
 
     /**
-     * Return the shorter version of the shortcut title.
+     * Return the shorter description of a shortcut.
      *
-     * <p>All shortcuts must have a non-empty title, but this method will return null when
-     * {@link #hasKeyFieldsOnly()} is true.
+     * @see Builder#setShortLabel(CharSequence)
      */
     @Nullable
     public CharSequence getShortLabel() {
@@ -1012,7 +1044,9 @@
     }
 
     /**
-     * Return the shortcut text.
+     * Return the longer description of a shortcut.
+     *
+     * @see Builder#setLongLabel(CharSequence)
      */
     @Nullable
     public CharSequence getLongLabel() {
@@ -1026,6 +1060,8 @@
 
     /**
      * Return the message that should be shown when a shortcut in disabled state is launched.
+     *
+     * @see Builder#setDisabledMessage(CharSequence)
      */
     @Nullable
     public CharSequence getDisabledMessage() {
@@ -1039,6 +1075,8 @@
 
     /**
      * Return the categories.
+     *
+     * @see Builder#setCategories(Set)
      */
     @Nullable
     public Set<String> getCategories() {
@@ -1048,12 +1086,11 @@
     /**
      * Return the intent.
      *
-     * <p>All shortcuts must have an intent, but this method will return null when
-     * {@link #hasKeyFieldsOnly()} is true.
+     * <p>Launcher applications <b>cannot</b> see the intent.  If a {@link ShortcutInfo} is
+     * obtained via {@link LauncherApps}, then this method will always return null.
+     * Launchers can only start a shortcut intent with {@link LauncherApps#startShortcut}.
      *
-     * <p>Launcher apps <b>cannot</b> see the intent.  If a {@link ShortcutInfo} is obtained via
-     * {@link LauncherApps}, then this method will always return null.  Launcher apps can only
-     * start a shortcut intent with {@link LauncherApps#startShortcut}.
+     * @see Builder#setIntent(Intent)
      */
     @Nullable
     public Intent getIntent() {
@@ -1096,6 +1133,10 @@
      *
      * <p>"Floating" shortcuts (i.e. shortcuts that are neither dynamic nor manifest) will all
      * have rank 0, because there's no sorting for them.
+     *
+     * See the {@link ShortcutManager}'s class javadoc for details.
+     *
+     * @see Builder#setRank(int)
      */
     public int getRank() {
         return mRank;
@@ -1139,6 +1180,8 @@
 
     /**
      * Extras that application can set to any purposes.
+     *
+     * @see Builder#setExtras(PersistableBundle)
      */
     @Nullable
     public PersistableBundle getExtras() {
@@ -1151,7 +1194,7 @@
     }
 
     /**
-     * {@link UserHandle} on which the publisher created shortcuts.
+     * {@link UserHandle} on which the publisher created a shortcut.
      */
     public UserHandle getUserHandle() {
         return UserHandle.of(mUserId);
@@ -1201,16 +1244,13 @@
     }
 
     /**
-     * Return whether a shortcut is published via AndroidManifest.xml or not.  If {@code true},
+     * Return whether a shortcut is published AndroidManifest.xml or not.  If {@code true},
      * it's also {@link #isImmutable()}.
      *
      * <p>When an app is upgraded and a shortcut is no longer published from AndroidManifest.xml,
      * this will be set to {@code false}.  If the shortcut is not pinned, then it'll just disappear.
      * However, if it's pinned, it will still be alive, and {@link #isEnabled()} will be
      * {@code false} and {@link #isImmutable()} will be {@code true}.
-     *
-     * <p>NOTE this is whether a shortcut is published from the <b>current version's</b>
-     * AndroidManifest.xml.
      */
     public boolean isDeclaredInManifest() {
         return hasFlags(FLAG_MANIFEST);
@@ -1311,6 +1351,12 @@
      *     <li>{@link #isEnabled()}
      *     <li>{@link #getUserHandle()}
      * </ul>
+     *
+     * <p>{@link ShortcutInfo}s passed to
+     * {@link LauncherApps.Callback#onShortcutsChanged(String, List, UserHandle)}
+     * as well as returned by {@link LauncherApps#getShortcuts(ShortcutQuery, UserHandle)} with
+     * the {@link ShortcutQuery#FLAG_GET_KEY_FIELDS_ONLY} option will only have key information
+     * for performance reasons.
      */
     public boolean hasKeyFieldsOnly() {
         return hasFlags(FLAG_KEY_FIELDS_ONLY);
diff --git a/core/java/android/content/pm/ShortcutManager.java b/core/java/android/content/pm/ShortcutManager.java
index 1af63a0..f6c0be0 100644
--- a/core/java/android/content/pm/ShortcutManager.java
+++ b/core/java/android/content/pm/ShortcutManager.java
@@ -20,6 +20,7 @@
 import android.annotation.UserIdInt;
 import android.app.usage.UsageStatsManager;
 import android.content.Context;
+import android.content.Intent;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.UserHandle;
@@ -28,62 +29,333 @@
 
 import java.util.List;
 
-// TODO Enhance javadoc
 /**
- * <b>TODO: Update to reflect DR changes, such as manifest shortcuts.</b><br>
+ * ShortcutManager manages "launcher shortcuts" (or simply "shortcuts").  Shortcuts provide user
+ * with quick
+ * ways to access activities other than the main activity from the launcher to users.  For example,
+ * an email application may publish the "compose new email" action which will directly open the
+ * compose activity.  The {@link ShortcutInfo} class represents shortcuts.
  *
- * {@link ShortcutManager} manages shortcuts created by applications.
+ * <h3>Dynamic Shortcuts and Manifest Shortcuts</h3>
  *
- * <h3>Dynamic shortcuts and pinned shortcuts</h3>
+ * There are two ways to publish shortcuts: manifest shortcuts and dynamic shortcuts.
  *
- * An application can publish shortcuts with {@link #setDynamicShortcuts(List)} and
- * {@link #addDynamicShortcuts(List)}.  There can be at most
- * {@link #getMaxShortcutCountPerActivity()} number of dynamic shortcuts at a time from the
- * same application.
- * A dynamic shortcut can be deleted with {@link #removeDynamicShortcuts(List)}, and apps
- * can also use {@link #removeAllDynamicShortcuts()} to delete all dynamic shortcuts.
+ * <ul>
+ * <li>Manifest shortcuts are declared in a resource XML which is referred to from
+ * AndroidManifest.xml.  Manifest shortcuts are published when an application is installed,
+ * and are updated when an application is upgraded with an updated XML file.
+ * Manifest shortcuts are immutable and their
+ * definitions (e.g. icons and labels) can not be changed dynamically (without upgrading the
+ * publisher application).
  *
- * <p>The shortcuts that are currently published by the above APIs are called "dynamic", because
- * they can be removed by the creator application at any time.  The user may "pin" dynamic shortcuts
- * on Launcher to make "pinned" shortcuts.  Pinned shortcuts <b>cannot</b> be removed by the creator
- * app.  An application can obtain all pinned shortcuts from itself with
- * {@link #getPinnedShortcuts()}.  Applications should keep the pinned shortcut information
- * up-to-date using {@link #updateShortcuts(List)}.
+ * <li>Dynamic shortcuts are published at runtime with {@link ShortcutManager} APIs.
+ * Applications can publish, update and remove dynamic shortcuts at runtime with certain limitations
+ * described below.
+ * </ul>
  *
- * <p>The number of pinned shortcuts does not affect the number of dynamic shortcuts that can be
- * published by an application at a time.
- * No matter how many pinned shortcuts that Launcher has for an application, the
- * application can still always publish {@link #getMaxShortcutCountPerActivity()} number of
- * dynamic
- * shortcuts.
+ * <p>Only "main" activities (i.e. activities that handle the {@code MAIN} action and the
+ * {@code LAUNCHER} category) can have shortcuts.  If an application has multiple main activities,
+ * they will have different set of shortcuts.
  *
- * <h3>Shortcut IDs</h3>
+ * <p>Dynamic shortcuts and manifest shortcuts are shown by launcher applications when the user
+ * takes a certain action (e.g. long-press) on an application launcher icon.
  *
- * Each shortcut must have an ID, which must be unique within each application.  When a shortcut is
- * published, existing shortcuts with the same ID will be updated.  Note this may include a
- * pinned shortcut.
+ * <p>Each launcher icon can have at most {@link #getMaxShortcutCountPerActivity()} number of
+ * dynamic and manifest shortcuts combined.
+ *
+ *
+ * <h3>Pinning Shortcuts</h3>
+ *
+ * Launcher applications allow users to "pin" shortcuts so they're easier to access.  Both manifest
+ * and dynamic shortcuts can be pinned, to avoid user's confusion.
+ * Pinned shortcuts <b>cannot</b> be removed by publisher
+ * applications -- they are only removed when the publisher is uninstalled. (Or the user performs
+ * "clear data" on the publisher application on the Settings application.)
+ *
+ * <p>Publisher can however "disable" pinned shortcuts so they cannot be launched.  See below
+ * for details.
+ *
+ *
+ * <h3>Updating and Disabling Shortcuts</h3>
+ *
+ * <p>When a dynamic shortcut is pinned, even when the publisher removes it as a dynamic shortcut,
+ * the pinned shortcut will still be available and launchable.  This allows an application to have
+ * more than {@link #getMaxShortcutCountPerActivity()} number of shortcuts -- for example, suppose
+ * {@link #getMaxShortcutCountPerActivity()} is 5:
+ * <ul>
+ *     <li>A chat application publishes 5 dynamic shortcuts for the 5 most recent
+ *     conversations, "c1" - "c5".
+ *
+ *     <li>The user pins all of the 5 shortcuts.
+ *
+ *     <li>Later, the user has 3 newer conversations ("c6", "c7" and "c8"), so the application
+ *     re-publishes dynamic shortcuts and now it has the dynamic shortcuts "c4", "c5", "c6", "c7"
+ *     and "c8".  The publisher has to remove "c1", "c2" and "c3" because it can't have more than
+ *     5 dynamic shortcuts.
+ *
+ *     <li>However, even though "c1", "c2" and "c3" are no longer dynamic shortcuts, the pinned
+ *     shortcuts for those conversations are still available and launchable.
+ *
+ *     <li>At this point, the application has 8 shortcuts in total, including the 3 pinned
+ *     shortcuts, even though it's allowed to have at most 5 dynamic shortcuts.
+ *
+ *     <li>The application can use {@link #updateShortcuts(List)} to update any of the existing
+ *     8 shortcuts, when, for example, the chat peers' icons have changed.
+ * </ul>
+ * {@link #addDynamicShortcuts(List)} and {@link #setDynamicShortcuts(List)} can also be used
+ * to update existing shortcuts with the same IDs, but they <b>cannot</b> be used for
+ * non-dynamic pinned shortcuts because these two APIs will always try to make the passed
+ * shortcuts dynamic.
+ *
+ *
+ * <h4>Disabling Manifest Shortcuts</h4>
+ * Sometimes pinned shortcuts become obsolete and may not be usable.  For example, a pinned shortcut
+ * to a group chat will be unusable when the group chat room is deleted.  In cases like this,
+ * applications should use {@link #disableShortcuts(List)}, which will remove the specified dynamic
+ * shortcuts and also make the pinned shortcuts un-launchable, if any.
+ * {@link #disableShortcuts(List, CharSequence)} can also be used to disable shortcuts with
+ * a custom error message that will be shown when the user starts the shortcut.
+ *
+ * <h4>Disabling Manifest Shortcuts</h4>
+ * When an application is upgraded and the new version no longer has a manifest shortcut that
+ * the previous version had, this shortcut will no longer be published as a manifest shortcut.
+ *
+ * <p>If the shortcut is pinned, then the pinned shortcut will remain on the launcher, but will be
+ * disabled.  Note in this case, the pinned shortcut is no longer a manifest shortcut, but is
+ * still <b>immutable</b> and cannot be updated with the {@link ShortcutManager} APIs.
+ *
+ *
+ * <h3>Publishing Dynamic Shortcuts</h3>
+ *
+ * Applications can publish dynamic shortcuts with {@link #setDynamicShortcuts(List)}
+ * or {@link #addDynamicShortcuts(List)}.  {@link #updateShortcuts(List)} can also be used to
+ * update existing (mutable) shortcuts.
+ * Use {@link #removeDynamicShortcuts(List)} or {@link #removeAllDynamicShortcuts()} to remove
+ * dynamic shortcuts.
+ *
+ * <p>Example:
+ * <pre>
+ * ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
+ *
+ * ShortcutInfo shortcut = new ShortcutInfo.Builder(this, "id1")
+ *     .setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.mysite.com/")))
+ *     .setShortLabel("Web site")
+ *     .setLongLabel("Open the web site")
+ *     .setIcon(Icon.createWithResource(context, R.drawable.icon_website))
+ *     .build();
+ *
+ * shortcutManager.setDynamicShortcuts(Arrays.asList(shortcut));
+ * </pre>
+ *
+ *
+ * <h3>Publishing Manifest Shortcuts</h3>
+ *
+ * In order to add manifest shortcuts to your application, first add
+ * {@code <meta-data android:name="android.app.shortcuts" />} to your main activity in
+ * AndroidManifest.xml.
+ * <pre>
+ * &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
+ *   package=&quot;com.example.myapplication&quot;&gt;
+ *   &lt;application . . .&gt;
+ *     &lt;activity android:name=&quot;Main&quot;&gt;
+ *       &lt;intent-filter&gt;
+ *         &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
+ *         &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
+ *       &lt;/intent-filter&gt;
+ *       <b>&lt;meta-data android:name=&quot;android.app.shortcuts&quot; android:resource=&quot;@xml/shortcuts&quot;/&gt;</b>
+ *     &lt;/activity&gt;
+ *   &lt;/application&gt;
+ * &lt;/manifest&gt;
+ * </pre>
+ *
+ * Then define shortcuts in res/xml/shortcuts.xml.
+ * <pre>
+ * &lt;shortcuts xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; &gt;
+ *   &lt;shortcut
+ *     android:shortcutId=&quot;compose&quot;
+ *     android:enabled=&quot;true&quot;
+ *     android:icon=&quot;@drawable/compose_icon&quot;
+ *     android:shortcutShortLabel=&quot;@string/compose_shortcut_short_label1&quot;
+ *     android:shortcutLongLabel=&quot;@string/compose_shortcut_short_label1&quot;
+ *     android:shortcutDisabledMessage=&quot;@string/compose_disabled_message1&quot;
+ *     &gt;
+ *     &lt;intent
+ *       android:action=&quot;android.intent.action.VIEW&quot;
+ *       android:targetPackage=&quot;com.example.myapplication&quot;
+ *       android:targetClass=&quot;com.example.myapplication.ComposeActivity&quot; /&gt;
+ *     &lt;categories android:name=&quot;android.shortcut.conversation&quot; /&gt;
+ *   &lt;/shortcut&gt;
+ *   &lt;!-- more shortcut can go here --&gt;
+ * &lt;/shortcuts&gt;
+ * </pre>
+ * <ul>
+ *   <li>{@code android:shortcutId} Mandatory shortcut ID
+ *
+ *   <li>{@code android:enabled} Default is {@code true}.  Can be set to {@code false} in order
+ *   to disable a manifest shortcut that was published on a previous version with a custom
+ *   disabled message.  If a custom disabled message is not needed, then a manifest shortcut can
+ *   be simply removed from the xml file rather than keeping it with {@code enabled="false"}.
+ *
+ *   <li>{@code android:icon} Shortcut icon.
+ *
+ *   <li>{@code android:shortcutShortLabel} Mandatory shortcut short label.
+ *   See {@link ShortcutInfo.Builder#setShortLabel(CharSequence)}
+ *
+ *   <li>{@code android:shortcutLongLabel} Shortcut long label.
+ *   See {@link ShortcutInfo.Builder#setLongLabel(CharSequence)}
+ *
+ *   <li>{@code android:shortcutDisabledMessage} When {@code android:enabled} is set to
+ *   {@code false}, this can be used to set a custom disabled message.
+ *
+ *   <li>{@code intent} Intent to launch.  {@code android:action} is mandatory.
+ *   See <a href="{@docRoot}guide/topics/ui/settings.html#Intents">Using intents</a> for the
+ *   other supported tags.
+ * </ul>
+ *
+ * <h3>Updating Shortcuts v.s. Re-publishing New One with Different ID</h3>
+ * In order to avoid users' confusion, {@link #updateShortcuts(List)} should not be used to update
+ * a shortcut to something that is conceptually different.
+ *
+ * <p>For example, a phone application may publish the most frequently called contact as a dynamic
+ * shortcut.  Over the time, this contact may change, but when it changes the application should
+ * publish a new contact with a different ID with either
+ * {@link #setDynamicShortcuts(List)} or {@link #addDynamicShortcuts(List)}, rather than updating
+ * the existing shortcut with {@link #updateShortcuts(List)}.
+ *
+ * This is because when the shortcut is pinned, changing it to a different contact
+ * will likely confuse the user.
+ *
+ * <p>On the other hand, when the contact's information (e.g. the name or picture) has changed,
+ * then the application should use {@link #updateShortcuts(List)} so that the pinned shortcut
+ * will be updated too.
+ *
+ *
+ * <h3>Shortcut Display Order</h3>
+ * When the launcher show the shortcuts for a launcher icon, the showing order should be the
+ * following:
+ * <ul>
+ *   <li>First show manifest shortcuts
+ *   ({@link ShortcutInfo#isDeclaredInManifest()} is {@code true}),
+ *   and then dynamic shortcuts ({@link ShortcutInfo#isDynamic()} is {@code true}).
+ *   <li>Within each category, sort by {@link ShortcutInfo#getRank()}.
+ * </ul>
+ * <p>Shortcut ranks are non-negative sequential integers for each target activity.  Ranks of
+ * existing shortcuts can be updated with
+ * {@link #updateShortcuts(List)} ({@link #addDynamicShortcuts(List)} and
+ * {@link #setDynamicShortcuts(List)} may be used too).
+ *
+ * <p>Ranks will be auto-adjusted so that they're unique for each target activity for each category
+ * (dynamic or manifest).  For example, if there are 3 dynamic shortcuts with ranks 0, 1 and 2,
+ * adding another dynamic shortcut with rank = 1 means to place this shortcut at the second
+ * position.  The third and forth shortcuts (that were originally second and third) will be adjusted
+ * to 2 and 3 respectively.
+ *
+ * <h3>Rate Limiting</h3>
+ *
+ * Calls to {@link #setDynamicShortcuts(List)}, {@link #addDynamicShortcuts(List)} and
+ * {@link #updateShortcuts(List)} may be rate-limited when called by background applications (i.e.
+ * applications with no foreground activity or service).  When rate-limited, these APIs will return
+ * {@code false}.
+ *
+ * <p>Applications with a foreground activity or service will not be rate-limited.
+ *
+ * <p>Rate-limiting will be reset upon certain events, so that even background applications
+ * will be able to call these APIs again (until they are rate-limited again).
+ * <ul>
+ *   <li>When an application comes to foreground.
+ *   <li>When the system locale changes.
+ *   <li>When the user performs "inline reply" on a notification.
+ * </ul>
+ *
+ * <h4>Resetting rate-limiting for testing</h4>
+ *
+ * If your application is rate-limited during development or testing, you can use the
+ * "Reset ShortcutManager rate-limiting" development option, or the following adb command to reset
+ * it.
+ * <pre>
+ * adb shell cmd shortcut reset-throttling [ --user USER-ID ]
+ * </pre>
+ *
+ * <h3>Handling System Locale Change</h3>
+ *
+ * Applications should update dynamic and pinned shortcuts when the system locale changes
+ * using the {@link Intent#ACTION_LOCALE_CHANGED} broadcast.
+ *
+ * <p>When the system locale changes, rate-limiting will be reset, so even background applications
+ * what were previously rate-limited will be able to call {@link #updateShortcuts(List)}.
  *
  *
  * <h3>Backup and Restore</h3>
  *
- * Pinned shortcuts will be backed up and restored across devices.  This means all information
- * within shortcuts, including IDs, must be meaningful on different devices.
+ * When an application has {@code android:allowBackup="true"} in its AndroidManifest.xml, pinned
+ * shortcuts will be backed up automatically and restored when the user sets up a new device.
  *
- * <p>Note that:
+ * <h4>What will be backed up and what will not be backed up</h4>
+ *
  * <ul>
- *     <li>Dynamic shortcuts will not be backed up or restored.
- *     <li>Icons of pinned shortcuts will <b>not</b> be backed up for performance reasons, unless
- *     they refer to resources.  Instead, launcher applications are supposed to back up and restore
- *     icons of pinned shortcuts by themselves, and thus from the user's point of view, pinned
- *     shortcuts will look to have icons restored.
+ *  <li>Pinned shortcuts will be backed up.  Bitmap icons will not be backed up by the system,
+ *  but launcher applications should back them up and restore them, so the user will still get
+ *  icons for pinned shortcuts on the launcher.  Applications can always use
+ *  {@link #updateShortcuts(List)} to re-publish icons.
+ *
+ *  <li>Manifest shortcuts will not be backed up, but when an application is re-installed on a new
+ *  device, they will be re-published from AndroidManifest.xml anyway.
+ *
+ *  <li>Dynamic shortcuts will <b>not</b> be backed up.
  * </ul>
  *
+ * <p>Because dynamic shortcuts will not restored, it is recommended that applications check
+ * currently published dynamic shortcuts with {@link #getDynamicShortcuts()} when they start,
+ * and re-publish dynamic shortcuts when necessary.
  *
- * <h3>APIs for launcher</h3>
+ * <pre>
+ * public class MainActivity extends Activity {
+ *     public void onCreate(Bundle savedInstanceState) {
+ *         super.onCreate(savedInstanceState);
  *
- * Launcher applications should use {@link LauncherApps} to get shortcuts that are published from
- * applications.  Launcher applications can also pin shortcuts with
- * {@link LauncherApps#pinShortcuts(String, List, UserHandle)}.
+ *         ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
+ *
+ *         if (shortcutManager.getDynamicShortcuts().size() == 0) {
+ *             // Application restored; re-publish dynamic shortcuts.
+ *
+ *             if (shortcutManager.getPinnedShortcuts().size() > 0) {
+ *                 // Pinned shortcuts have been restored.  use updateShortcuts() to make sure
+ *                 // they have up-to-date information.
+ *             }
+ *         }
+ *     }
+ *     :
+ *
+ * }
+ * </pre>
+ *
+ *
+ * <h4>Backup/restore and shortcut IDs</h4>
+ *
+ * Because pinned shortcuts will be backed up and restored on new devices, shortcut IDs should be
+ * meaningful across devices; that is, IDs should be either stable constant strings, or server-side
+ * identifiers, rather than identifiers generated locally that may not make sense on other devices.
+ *
+ *
+ * <h3>Report Shortcut Usage and Prediction</h3>
+ *
+ * Launcher applications may be capable of predicting which shortcuts will most likely be used at
+ * the moment with the shortcut usage history data.
+ *
+ * <p>In order to provide launchers with such data, publisher applications should report which
+ * shortcut is used with {@link #reportShortcutUsed(String)} when a shortcut is started,
+ * <b>or when an action equivalent to a shortcut is taken by the user even if it wasn't started
+ * with the shortcut</b>.
+ *
+ * <p>For example, suppose a GPS navigation application exposes "navigate to work" as a shortcut.
+ * Then it should report it when the user starts this shortcut, and also when the user navigates
+ * to work within the application without using the shortcut.  This helps the launcher application
+ * learn that the user wants to navigate to work at a certain time every weekday, so that the
+ * launcher can show this shortcut in a suggestion list.
+ *
+ * <h3>Launcher API</h3>
+ *
+ * {@link LauncherApps} provides APIs for launcher applications to access shortcuts.
  */
 public class ShortcutManager {
     private static final String TAG = "ShortcutManager";
@@ -110,14 +382,15 @@
 
     /**
      * Publish a list of shortcuts.  All existing dynamic shortcuts from the caller application
-     * will be replaced.
+     * will be replaced.  If there's already pinned shortcuts with the same IDs, they will all be
+     * updated, unless they're immutable.
      *
      * <p>This API will be rate-limited.
      *
      * @return {@code true} if the call has succeeded. {@code false} if the call is rate-limited.
      *
-     * @throws IllegalArgumentException if {@code shortcutInfoList} contains more than
-     * {@link #getMaxShortcutCountPerActivity()} shortcuts.
+     * @throws IllegalArgumentException if {@link #getMaxShortcutCountPerActivity()} is exceeded,
+     * or trying to update immutable shortcuts.
      */
     public boolean setDynamicShortcuts(@NonNull List<ShortcutInfo> shortcutInfoList) {
         try {
@@ -129,8 +402,7 @@
     }
 
     /**
-     * Return all dynamic shortcuts from the caller application.  The number of result items
-     * will not exceed the value returned by {@link #getMaxShortcutCountPerActivity()}.
+     * Return all dynamic shortcuts from the caller application.
      */
     @NonNull
     public List<ShortcutInfo> getDynamicShortcuts() {
@@ -143,7 +415,7 @@
     }
 
     /**
-     * TODO Javadoc
+     * Return all manifest shortcuts from the caller application.
      */
     @NonNull
     public List<ShortcutInfo> getManifestShortcuts() {
@@ -157,14 +429,14 @@
 
     /**
      * Publish list of dynamic shortcuts.  If there's already dynamic or pinned shortcuts with
-     * the same IDs, they will all be updated.
+     * the same IDs, they will all be updated, unless they're immutable.
      *
      * <p>This API will be rate-limited.
      *
      * @return {@code true} if the call has succeeded. {@code false} if the call is rate-limited.
      *
-     * @throws IllegalArgumentException if the caller application has already published the
-     * max number of dynamic shortcuts.
+     * @throws IllegalArgumentException if {@link #getMaxShortcutCountPerActivity()} is exceeded,
+     * or trying to update immutable shortcuts.
      */
     public boolean addDynamicShortcuts(@NonNull List<ShortcutInfo> shortcutInfoList) {
         try {
@@ -212,11 +484,14 @@
     }
 
     /**
-     * Update all existing shortcuts with the same IDs.  Shortcuts may be pinned and/or dynamic.
+     * Update all existing shortcuts with the same IDs.  Target shortcuts may be pinned and/or
+     * dynamic, but may not be immutable.
      *
      * <p>This API will be rate-limited.
      *
      * @return {@code true} if the call has succeeded. {@code false} if the call is rate-limited.
+     *
+     * @throws IllegalArgumentException if trying to update immutable shortcuts.
      */
     public boolean updateShortcuts(List<ShortcutInfo> shortcutInfoList) {
         try {
@@ -228,7 +503,7 @@
     }
 
     /**
-     * TODO Javadoc
+     * Disable pinned shortcuts.  See {@link ShortcutManager}'s class javadoc for details.
      */
     public void disableShortcuts(@NonNull List<String> shortcutIds) {
         try {
@@ -261,7 +536,8 @@
     }
 
     /**
-     * TODO Javadoc
+     * Disable pinned shortcuts with a custom error message.
+     * See {@link ShortcutManager}'s class javadoc for details.
      */
     public void disableShortcuts(@NonNull List<String> shortcutIds, CharSequence disabledMessage) {
         try {
@@ -274,7 +550,7 @@
     }
 
     /**
-     * TODO Javadoc
+     * Re-enable disabled pinned shortcuts.
      */
     public void enableShortcuts(@NonNull List<String> shortcutIds) {
         try {
@@ -293,7 +569,7 @@
     }
 
     /**
-     * Return the max number of dynamic shortcuts + manifest shortcuts that each launcher icon
+     * Return the max number of dynamic and manifest shortcuts that each launcher icon
      * can have at a time.
      */
     public int getMaxShortcutCountPerActivity() {
@@ -362,12 +638,9 @@
     }
 
     /**
-     * Applications that publish shortcuts should call this method whenever an action that's
-     * equivalent to an existing shortcut has been taken by the user.  This includes not only when
-     * the user manually taps a shortcut, but when the user takes an equivalent action within the
-     * application -- for example, when a music player application has a shortcut to playlist X,
-     * then the application should not only report it when the playlist is opened from the
-     * shortcut, but also when the user plays the playlist within the application.
+     * Applications that publish shortcuts should call this method whenever a shortcut is started
+     * or an action equivalent to a shortcut is taken.  See the {@link ShortcutManager} class
+     * javadoc for details.
      *
      * <p>The information is accessible via {@link UsageStatsManager#queryEvents}
      * Typically, launcher applications use this information to build a prediction model
diff --git a/core/java/android/content/pm/ShortcutServiceInternal.java b/core/java/android/content/pm/ShortcutServiceInternal.java
index 3f8bad1..de52f73 100644
--- a/core/java/android/content/pm/ShortcutServiceInternal.java
+++ b/core/java/android/content/pm/ShortcutServiceInternal.java
@@ -73,4 +73,11 @@
      * any locks in this method.
      */
     public abstract void onSystemLocaleChangedNoLock();
+
+    /**
+     * Called by PM before sending package broadcasts to other components.  PM doesn't hold the PM
+     * lock, but do not take any locks in here anyway, and don't do any heavy tasks, as doing so
+     * would slow down all the package broadcasts.
+     */
+    public abstract void onPackageBroadcast(Intent intent);
 }
diff --git a/core/java/android/hardware/usb/UsbManager.java b/core/java/android/hardware/usb/UsbManager.java
index 8f21b38..629db06 100644
--- a/core/java/android/hardware/usb/UsbManager.java
+++ b/core/java/android/hardware/usb/UsbManager.java
@@ -43,7 +43,7 @@
  * <div class="special reference">
  * <h3>Developer Guides</h3>
  * <p>For more information about communicating with USB hardware, read the
- * <a href="{@docRoot}guide/topics/usb/index.html">USB</a> developer guide.</p>
+ * <a href="{@docRoot}guide/topics/connectivity/usb/index.html">USB developer guide</a>.</p>
  * </div>
  */
 public class UsbManager {
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index 8d413795..3c2ac67 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -1035,6 +1035,26 @@
     }
 
     /**
+     * Request that this callback be invoked at ConnectivityService's earliest
+     * convenience with the current satisfying network's LinkProperties.
+     * If no such network exists no callback invocation is performed.
+     *
+     * The callback must have been registered with #requestNetwork() or
+     * #registerDefaultNetworkCallback(); callbacks registered with
+     * registerNetworkCallback() are not specific to any particular Network so
+     * do not cause any updates.
+     *
+     * @hide
+     */
+    public void requestLinkProperties(NetworkCallback networkCallback) {
+        try {
+            mService.requestLinkProperties(networkCallback.networkRequest);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}.  This
      * will return {@code null} if the network is unknown.
      * <p>This method requires the caller to hold the permission
@@ -1052,6 +1072,26 @@
     }
 
     /**
+     * Request that this callback be invoked at ConnectivityService's earliest
+     * convenience with the current satisfying network's NetworkCapabilities.
+     * If no such network exists no callback invocation is performed.
+     *
+     * The callback must have been registered with #requestNetwork() or
+     * #registerDefaultNetworkCallback(); callbacks registered with
+     * registerNetworkCallback() are not specific to any particular Network so
+     * do not cause any updates.
+     *
+     * @hide
+     */
+    public void requestNetworkCapabilities(NetworkCallback networkCallback) {
+        try {
+            mService.requestNetworkCapabilities(networkCallback.networkRequest);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Gets the URL that should be used for resolving whether a captive portal is present.
      * 1. This URL should respond with a 204 response to a GET request to indicate no captive
      *    portal is present.
diff --git a/core/java/android/net/IConnectivityManager.aidl b/core/java/android/net/IConnectivityManager.aidl
index 0d518cc..d48c155 100644
--- a/core/java/android/net/IConnectivityManager.aidl
+++ b/core/java/android/net/IConnectivityManager.aidl
@@ -156,6 +156,8 @@
     void pendingListenForNetwork(in NetworkCapabilities networkCapabilities,
             in PendingIntent operation);
 
+    void requestLinkProperties(in NetworkRequest networkRequest);
+    void requestNetworkCapabilities(in NetworkRequest networkRequest);
     void releaseNetworkRequest(in NetworkRequest networkRequest);
 
     void setAcceptUnvalidated(in Network network, boolean accept, boolean always);
diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java
index 141af3d..35e3065 100644
--- a/core/java/android/net/NetworkUtils.java
+++ b/core/java/android/net/NetworkUtils.java
@@ -45,13 +45,20 @@
     public native static void attachDhcpFilter(FileDescriptor fd) throws SocketException;
 
     /**
-     * Attaches a socket filter that accepts ICMP6 router advertisement packets to the given socket.
+     * Attaches a socket filter that accepts ICMPv6 router advertisements to the given socket.
      * @param fd the socket's {@link FileDescriptor}.
      * @param packetType the hardware address type, one of ARPHRD_*.
      */
     public native static void attachRaFilter(FileDescriptor fd, int packetType) throws SocketException;
 
     /**
+     * Configures a socket for receiving ICMPv6 router solicitations and sending advertisements.
+     * @param fd the socket's {@link FileDescriptor}.
+     * @param ifIndex the interface index.
+     */
+    public native static void setupRaSocket(FileDescriptor fd, int ifIndex) throws SocketException;
+
+    /**
      * Binds the current process to the network designated by {@code netId}.  All sockets created
      * in the future (and not explicitly bound via a bound {@link SocketFactory} (see
      * {@link Network#getSocketFactory}) will be bound to this network.  Note that if this
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index c26d974..84d2c98 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -971,6 +971,9 @@
      * priority.
      * If the thread is a thread group leader, that is it's gettid() == getpid(),
      * then the other threads in the same thread group are _not_ affected.
+     *
+     * Does not set cpuset for some historical reason, just calls
+     * libcutils::set_sched_policy().
      */
     public static final native void setThreadGroup(int tid, int group)
             throws IllegalArgumentException, SecurityException;
@@ -992,6 +995,8 @@
      * priority threads alone.  group == THREAD_GROUP_BG_NONINTERACTIVE moves all
      * threads, regardless of priority, to the background scheduling group.
      * group == THREAD_GROUP_FOREGROUND is not allowed.
+     *
+     * Always sets cpusets.
      */
     public static final native void setProcessGroup(int pid, int group)
             throws IllegalArgumentException, SecurityException;
diff --git a/core/java/android/view/DragEvent.java b/core/java/android/view/DragEvent.java
index fb482b4..b0f15b5 100644
--- a/core/java/android/view/DragEvent.java
+++ b/core/java/android/view/DragEvent.java
@@ -102,8 +102,8 @@
  *  </tr>
  *  <tr>
  *      <td>ACTION_DRAG_ENDED</td>
- *      <td style="text-align: center;">X</td>
- *      <td style="text-align: center;">X</td>
+ *      <td style="text-align: center;">&nbsp;</td>
+ *      <td style="text-align: center;">&nbsp;</td>
  *      <td style="text-align: center;">&nbsp;</td>
  *      <td style="text-align: center;">&nbsp;</td>
  *      <td style="text-align: center;">&nbsp;</td>
@@ -359,7 +359,7 @@
      * The drag handler or listener for a View can use the metadata in this object to decide if the
      * View can accept the dragged View object's data.
      * <p>
-     * This method returns valid data for all event actions.
+     * This method returns valid data for all event actions except for {@link #ACTION_DRAG_ENDED}.
      * @return The ClipDescription that was part of the ClipData sent to the system by startDrag().
      */
     public ClipDescription getClipDescription() {
@@ -377,7 +377,7 @@
      * The object is intended to provide local information about the drag and drop operation. For
      * example, it can indicate whether the drag and drop operation is a copy or a move.
      * <p>
-     *  This method returns valid data for all event actions.
+     *  This method returns valid data for all event actions except for {@link #ACTION_DRAG_ENDED}.
      * </p>
      * @return The local state object sent to the system by startDrag().
      */
diff --git a/core/jni/android_net_NetUtils.cpp b/core/jni/android_net_NetUtils.cpp
index 2364787..679e882 100644
--- a/core/jni/android_net_NetUtils.cpp
+++ b/core/jni/android_net_NetUtils.cpp
@@ -125,6 +125,99 @@
     }
 }
 
+static void android_net_utils_setupRaSocket(JNIEnv *env, jobject clazz, jobject javaFd,
+        jint ifIndex)
+{
+    static const int kLinkLocalHopLimit = 255;
+
+    int fd = jniGetFDFromFileDescriptor(env, javaFd);
+
+    // Set an ICMPv6 filter that only passes Router Solicitations.
+    struct icmp6_filter rs_only;
+    ICMP6_FILTER_SETBLOCKALL(&rs_only);
+    ICMP6_FILTER_SETPASS(ND_ROUTER_SOLICIT, &rs_only);
+    socklen_t len = sizeof(rs_only);
+    if (setsockopt(fd, IPPROTO_ICMPV6, ICMP6_FILTER, &rs_only, len) != 0) {
+        jniThrowExceptionFmt(env, "java/net/SocketException",
+                "setsockopt(ICMP6_FILTER): %s", strerror(errno));
+        return;
+    }
+
+    // Most/all of the rest of these options can be set via Java code, but
+    // because we're here on account of setting an icmp6_filter go ahead
+    // and do it all natively for now.
+    //
+    // TODO: Consider moving these out to Java.
+
+    // Set the multicast hoplimit to 255 (link-local only).
+    int hops = kLinkLocalHopLimit;
+    len = sizeof(hops);
+    if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &hops, len) != 0) {
+        jniThrowExceptionFmt(env, "java/net/SocketException",
+                "setsockopt(IPV6_MULTICAST_HOPS): %s", strerror(errno));
+        return;
+    }
+
+    // Set the unicast hoplimit to 255 (link-local only).
+    hops = kLinkLocalHopLimit;
+    len = sizeof(hops);
+    if (setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &hops, len) != 0) {
+        jniThrowExceptionFmt(env, "java/net/SocketException",
+                "setsockopt(IPV6_UNICAST_HOPS): %s", strerror(errno));
+        return;
+    }
+
+    // Explicitly disable multicast loopback.
+    int off = 0;
+    len = sizeof(off);
+    if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &off, len) != 0) {
+        jniThrowExceptionFmt(env, "java/net/SocketException",
+                "setsockopt(IPV6_MULTICAST_LOOP): %s", strerror(errno));
+        return;
+    }
+
+    // Specify the IPv6 interface to use for outbound multicast.
+    len = sizeof(ifIndex);
+    if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &ifIndex, len) != 0) {
+        jniThrowExceptionFmt(env, "java/net/SocketException",
+                "setsockopt(IPV6_MULTICAST_IF): %s", strerror(errno));
+        return;
+    }
+
+    // Additional options to be considered:
+    //     - IPV6_TCLASS
+    //     - IPV6_RECVPKTINFO
+    //     - IPV6_RECVHOPLIMIT
+
+    // Bind to [::].
+    const struct sockaddr_in6 sin6 = {
+            .sin6_family = AF_INET6,
+            .sin6_port = 0,
+            .sin6_flowinfo = 0,
+            .sin6_addr = IN6ADDR_ANY_INIT,
+            .sin6_scope_id = 0,
+    };
+    auto sa = reinterpret_cast<const struct sockaddr *>(&sin6);
+    len = sizeof(sin6);
+    if (bind(fd, sa, len) != 0) {
+        jniThrowExceptionFmt(env, "java/net/SocketException",
+                "bind(IN6ADDR_ANY): %s", strerror(errno));
+        return;
+    }
+
+    // Join the all-routers multicast group, ff02::2%index.
+    struct ipv6_mreq all_rtrs = {
+        .ipv6mr_multiaddr = {{{0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2}}},
+        .ipv6mr_interface = ifIndex,
+    };
+    len = sizeof(all_rtrs);
+    if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &all_rtrs, len) != 0) {
+        jniThrowExceptionFmt(env, "java/net/SocketException",
+                "setsockopt(IPV6_JOIN_GROUP): %s", strerror(errno));
+        return;
+    }
+}
+
 static jboolean android_net_utils_bindProcessToNetwork(JNIEnv *env, jobject thiz, jint netId)
 {
     return (jboolean) !setNetworkForProcess(netId);
@@ -173,6 +266,7 @@
     { "queryUserAccess", "(II)Z", (void*)android_net_utils_queryUserAccess },
     { "attachDhcpFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_attachDhcpFilter },
     { "attachRaFilter", "(Ljava/io/FileDescriptor;I)V", (void*) android_net_utils_attachRaFilter },
+    { "setupRaSocket", "(Ljava/io/FileDescriptor;I)V", (void*) android_net_utils_setupRaSocket },
 };
 
 int register_android_net_NetworkUtils(JNIEnv* env)
diff --git a/core/res/res/values-mcc466-mnc01/config.xml b/core/res/res/values-mcc466-mnc01/config.xml
new file mode 100644
index 0000000..3c379d14
--- /dev/null
+++ b/core/res/res/values-mcc466-mnc01/config.xml
@@ -0,0 +1,21 @@
+<?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>
+    <bool name="config_use_sim_language_file">false</bool>
+</resources>
diff --git a/core/res/res/values-mcc466-mnc02/config.xml b/core/res/res/values-mcc466-mnc02/config.xml
new file mode 100644
index 0000000..3c379d14
--- /dev/null
+++ b/core/res/res/values-mcc466-mnc02/config.xml
@@ -0,0 +1,21 @@
+<?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>
+    <bool name="config_use_sim_language_file">false</bool>
+</resources>
diff --git a/core/res/res/values-mcc466-mnc03/config.xml b/core/res/res/values-mcc466-mnc03/config.xml
new file mode 100644
index 0000000..3c379d14
--- /dev/null
+++ b/core/res/res/values-mcc466-mnc03/config.xml
@@ -0,0 +1,21 @@
+<?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>
+    <bool name="config_use_sim_language_file">false</bool>
+</resources>
diff --git a/core/res/res/values-mcc466-mnc06/config.xml b/core/res/res/values-mcc466-mnc06/config.xml
new file mode 100644
index 0000000..3c379d14
--- /dev/null
+++ b/core/res/res/values-mcc466-mnc06/config.xml
@@ -0,0 +1,21 @@
+<?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>
+    <bool name="config_use_sim_language_file">false</bool>
+</resources>
diff --git a/core/res/res/values-mcc466-mnc07/config.xml b/core/res/res/values-mcc466-mnc07/config.xml
new file mode 100644
index 0000000..3c379d14
--- /dev/null
+++ b/core/res/res/values-mcc466-mnc07/config.xml
@@ -0,0 +1,21 @@
+<?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>
+    <bool name="config_use_sim_language_file">false</bool>
+</resources>
diff --git a/core/res/res/values-mcc466-mnc11/config.xml b/core/res/res/values-mcc466-mnc11/config.xml
new file mode 100644
index 0000000..3c379d14
--- /dev/null
+++ b/core/res/res/values-mcc466-mnc11/config.xml
@@ -0,0 +1,21 @@
+<?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>
+    <bool name="config_use_sim_language_file">false</bool>
+</resources>
diff --git a/core/res/res/values-mcc466-mnc92/config.xml b/core/res/res/values-mcc466-mnc92/config.xml
new file mode 100644
index 0000000..3c379d14
--- /dev/null
+++ b/core/res/res/values-mcc466-mnc92/config.xml
@@ -0,0 +1,21 @@
+<?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>
+    <bool name="config_use_sim_language_file">false</bool>
+</resources>
diff --git a/docs/html-intl/intl/ja/training/basics/data-storage/files.jd b/docs/html-intl/intl/ja/training/basics/data-storage/files.jd
index dddfe37..b920c1a 100644
--- a/docs/html-intl/intl/ja/training/basics/data-storage/files.jd
+++ b/docs/html-intl/intl/ja/training/basics/data-storage/files.jd
@@ -183,7 +183,7 @@
     try {
         String fileName = Uri.parse(url).getLastPathSegment();
         file = File.createTempFile(fileName, null, context.getCacheDir());
-    catch (IOException e) {
+    } catch (IOException e) {
         // Error while creating file
     }
     return file;
@@ -250,7 +250,7 @@
 
 
 
- 
+
   <p>たとえば、自分のアプリでダウンロードした追加のリソースや一時的なメディア ファイルです。</p>
   </dd>
 </dl>
@@ -265,7 +265,7 @@
 
 <pre>
 public File getAlbumStorageDir(String albumName) {
-    // Get the directory for the user's public pictures directory. 
+    // Get the directory for the user's public pictures directory.
     File file = new File(Environment.getExternalStoragePublicDirectory(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -287,7 +287,7 @@
 
 <pre>
 public File getAlbumStorageDir(Context context, String albumName) {
-    // Get the directory for the app's private pictures directory. 
+    // Get the directory for the app's private pictures directory.
     File file = new File(context.getExternalFilesDir(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -366,7 +366,7 @@
 
 <div class="note">
 <p><strong>注:</strong> ユーザーがアプリをアンインストールすると、Android システムは次を削除します。
-</p> 
+</p>
 <ul>
 <li>内部ストレージに保存したすべてのファイル</li>
 <li>{@link
diff --git a/docs/html-intl/intl/ko/training/basics/data-storage/files.jd b/docs/html-intl/intl/ko/training/basics/data-storage/files.jd
index 71652b5..0b717a8 100644
--- a/docs/html-intl/intl/ko/training/basics/data-storage/files.jd
+++ b/docs/html-intl/intl/ko/training/basics/data-storage/files.jd
@@ -183,7 +183,7 @@
     try {
         String fileName = Uri.parse(url).getLastPathSegment();
         file = File.createTempFile(fileName, null, context.getCacheDir());
-    catch (IOException e) {
+    } catch (IOException e) {
         // Error while creating file
     }
     return file;
@@ -250,7 +250,7 @@
 앱을 제거하면 같이 삭제됩니다. 이러한 파일은
 엄밀히 말해 외부 저장소에 저장된 파일이기 때문에 사용자 및 다른 앱의 액세스가 가능하긴 하지만, 앱 외부에서
 사용자에게 값을 실제로 제공하지는 않습니다. 사용자가 앱을 제거하면 앱의 외부 개인 디렉터리 내 모든 파일을 시스템에서
-삭제합니다. 
+삭제합니다.
   <p>예를 들어 앱에서 다운로드한 추가 리소스 또는 임시 미디어 파일이 이에 해당합니다.</p>
   </dd>
 </dl>
@@ -265,7 +265,7 @@
 
 <pre>
 public File getAlbumStorageDir(String albumName) {
-    // Get the directory for the user's public pictures directory. 
+    // Get the directory for the user's public pictures directory.
     File file = new File(Environment.getExternalStoragePublicDirectory(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -287,7 +287,7 @@
 
 <pre>
 public File getAlbumStorageDir(Context context, String albumName) {
-    // Get the directory for the app's private pictures directory. 
+    // Get the directory for the app's private pictures directory.
     File file = new File(context.getExternalFilesDir(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -357,7 +357,7 @@
 myFile.delete();
 </pre>
 
-<p>파일이 내부 저장소에 저장되어 있는 경우, {@link android.content.Context}에 위치를 요청하고 {@link android.content.Context#deleteFile deleteFile()}을 호출하여 파일을 
+<p>파일이 내부 저장소에 저장되어 있는 경우, {@link android.content.Context}에 위치를 요청하고 {@link android.content.Context#deleteFile deleteFile()}을 호출하여 파일을
 삭제할 수도 있습니다.</p>
 
 <pre>
@@ -366,7 +366,7 @@
 
 <div class="note">
 <p><strong>참고:</strong> 사용자가 앱을 제거하면 Android 시스템이
-다음 항목을 삭제합니다.</p> 
+다음 항목을 삭제합니다.</p>
 <ul>
 <li>내부 저장소에 저장한 모든 파일</li>
 <li>{@link
diff --git a/docs/html-intl/intl/pt-br/training/basics/data-storage/files.jd b/docs/html-intl/intl/pt-br/training/basics/data-storage/files.jd
index d071d39..0e00645 100644
--- a/docs/html-intl/intl/pt-br/training/basics/data-storage/files.jd
+++ b/docs/html-intl/intl/pt-br/training/basics/data-storage/files.jd
@@ -183,7 +183,7 @@
     try {
         String fileName = Uri.parse(url).getLastPathSegment();
         file = File.createTempFile(fileName, null, context.getCacheDir());
-    catch (IOException e) {
+    } catch (IOException e) {
         // Error while creating file
     }
     return file;
@@ -250,12 +250,12 @@
 . Embora esses arquivos estejam teoricamente à disposição do usuário e de outros aplicativo por estarem
 no armazenamento externo, na verdade são arquivos que não têm valor para o usuário
 fora do aplicativo. Ao desinstalar o aplicativo, o sistema exclui
-todos os arquivos no diretório privado externo do aplicativo. 
+todos os arquivos no diretório privado externo do aplicativo.
   <p>Por exemplo, recursos adicionais baixados através do aplicativo ou arquivos de mídia temporários.</p>
   </dd>
 </dl>
 
-<p>Para salvar arquivos públicos no armazenamento externo, use o método 
+<p>Para salvar arquivos públicos no armazenamento externo, use o método
 {@link android.os.Environment#getExternalStoragePublicDirectory
 getExternalStoragePublicDirectory()} para obter um {@link java.io.File} que representa
 o diretório correto no armazenamento externo. O método exige um argumento que especifica
@@ -265,7 +265,7 @@
 
 <pre>
 public File getAlbumStorageDir(String albumName) {
-    // Get the directory for the user's public pictures directory. 
+    // Get the directory for the user's public pictures directory.
     File file = new File(Environment.getExternalStoragePublicDirectory(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -287,7 +287,7 @@
 
 <pre>
 public File getAlbumStorageDir(Context context, String albumName) {
-    // Get the directory for the app's private pictures directory. 
+    // Get the directory for the app's private pictures directory.
     File file = new File(context.getExternalFilesDir(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -366,7 +366,7 @@
 
 <div class="note">
 <p><strong>Observação:</strong> quando o usuário desinstala o aplicativo, o sistema Android também
-exclui:</p> 
+exclui:</p>
 <ul>
 <li>Todos os arquivos salvos no armazenamento interno</li>
 <li>Todos os arquivos salvos no armazenamento externo usando {@link
diff --git a/docs/html-intl/intl/ru/training/basics/data-storage/files.jd b/docs/html-intl/intl/ru/training/basics/data-storage/files.jd
index 2afecea..2b8f880 100644
--- a/docs/html-intl/intl/ru/training/basics/data-storage/files.jd
+++ b/docs/html-intl/intl/ru/training/basics/data-storage/files.jd
@@ -183,7 +183,7 @@
     try {
         String fileName = Uri.parse(url).getLastPathSegment();
         file = File.createTempFile(fileName, null, context.getCacheDir());
-    catch (IOException e) {
+    } catch (IOException e) {
         // Error while creating file
     }
     return file;
@@ -250,7 +250,7 @@
 вашего приложения пользователем. Хотя технически эти файлы доступны для пользователя и других приложений, поскольку находятся
 во внешнем хранилище, они не имеют никакой ценности для пользователей
 вне вашего приложения. Когда пользователь удаляет ваше приложение, система удаляет
-все файлы из каталога закрытых файлов вашего приложения во внешнем хранилище. 
+все файлы из каталога закрытых файлов вашего приложения во внешнем хранилище.
   <p>Например, к этой категории относятся дополнительные ресурсы, загруженные приложением, и временные мультимедийные файлы.</p>
   </dd>
 </dl>
@@ -265,7 +265,7 @@
 
 <pre>
 public File getAlbumStorageDir(String albumName) {
-    // Get the directory for the user's public pictures directory. 
+    // Get the directory for the user's public pictures directory.
     File file = new File(Environment.getExternalStoragePublicDirectory(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -287,7 +287,7 @@
 
 <pre>
 public File getAlbumStorageDir(Context context, String albumName) {
-    // Get the directory for the app's private pictures directory. 
+    // Get the directory for the app's private pictures directory.
     File file = new File(context.getExternalFilesDir(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -332,7 +332,7 @@
 общее пространство в хранилище. Эта информация также позволять
 избежать переполнения объема хранилища сверх определенного уровня.</p>
 
-<p>Однако система не гарантирует возможность записи такого же количества байт, как указано 
+<p>Однако система не гарантирует возможность записи такого же количества байт, как указано
 в {@link java.io.File#getFreeSpace}.  Если выводимое число на
 несколько мегабайт превышает размер данных, которые вы хотите сохранить, или если файловая система заполнена
 менее, чем на 90%, дальше можно действовать спокойно.
@@ -366,13 +366,13 @@
 
 <div class="note">
 <p><strong>Примечание.</strong> При удалении пользователем вашего приложения система Android удаляет
-следующие элементы:</p> 
+следующие элементы:</p>
 <ul>
 <li>Все файлы, сохраненные во внутреннем хранилище</li>
 <li>Все файлы, сохраненные во внешнем хранилище с использованием {@link
 android.content.Context#getExternalFilesDir getExternalFilesDir()}.</li>
 </ul>
-<p>Однако вам следует регулярно вручную очищать кэш-память, чтобы удалить файлы, созданные с помощью 
+<p>Однако вам следует регулярно вручную очищать кэш-память, чтобы удалить файлы, созданные с помощью
 {@link android.content.Context#getCacheDir()}, а также удалять любые
 другие ненужные файлы.</p>
 </div>
diff --git a/docs/html-intl/intl/zh-cn/training/basics/data-storage/files.jd b/docs/html-intl/intl/zh-cn/training/basics/data-storage/files.jd
index 1442275..4ec1d68 100644
--- a/docs/html-intl/intl/zh-cn/training/basics/data-storage/files.jd
+++ b/docs/html-intl/intl/zh-cn/training/basics/data-storage/files.jd
@@ -183,7 +183,7 @@
     try {
         String fileName = Uri.parse(url).getLastPathSegment();
         file = File.createTempFile(fileName, null, context.getCacheDir());
-    catch (IOException e) {
+    } catch (IOException e) {
         // Error while creating file
     }
     return file;
@@ -250,7 +250,7 @@
 
 
 
- 
+
   <p>例如,您的应用下载的其他资源或临时介质文件。</p>
   </dd>
 </dl>
@@ -265,7 +265,7 @@
 
 <pre>
 public File getAlbumStorageDir(String albumName) {
-    // Get the directory for the user's public pictures directory. 
+    // Get the directory for the user's public pictures directory.
     File file = new File(Environment.getExternalStoragePublicDirectory(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -287,7 +287,7 @@
 
 <pre>
 public File getAlbumStorageDir(Context context, String albumName) {
-    // Get the directory for the app's private pictures directory. 
+    // Get the directory for the app's private pictures directory.
     File file = new File(context.getExternalFilesDir(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -311,7 +311,7 @@
 
 <p>无论您对于共享的文件使用 {@link
 android.os.Environment#getExternalStoragePublicDirectory
-getExternalStoragePublicDirectory()} 还是对您的应用专用文件使用 
+getExternalStoragePublicDirectory()} 还是对您的应用专用文件使用
 {@link android.content.Context#getExternalFilesDir
 getExternalFilesDir()} ,您使用诸如
 {@link android.os.Environment#DIRECTORY_PICTURES} 的 API 常数提供的目录名称非常重要。
@@ -332,7 +332,7 @@
 此信息也可用来避免填充存储卷以致超出特定阈值。
 </p>
 
-<p>但是,系统并不保证您可以写入与 {@link java.io.File#getFreeSpace} 
+<p>但是,系统并不保证您可以写入与 {@link java.io.File#getFreeSpace}
 指示的一样多的字节。如果返回的数字比您要保存的数据大小大出几 MB,或如果文件系统所占空间不到 90%,则可安全继续操作。否则,您可能不应写入存储。
 
 
@@ -366,7 +366,7 @@
 
 <div class="note">
 <p><strong>注意:</strong>当用户卸载您的应用时,Android 系统会删除以下各项:
-</p> 
+</p>
 <ul>
 <li>您保存在内部存储中的所有文件</li>
 <li>您使用 {@link
diff --git a/docs/html-intl/intl/zh-tw/training/basics/data-storage/files.jd b/docs/html-intl/intl/zh-tw/training/basics/data-storage/files.jd
index 8b8d0a7..cda5864 100644
--- a/docs/html-intl/intl/zh-tw/training/basics/data-storage/files.jd
+++ b/docs/html-intl/intl/zh-tw/training/basics/data-storage/files.jd
@@ -40,7 +40,7 @@
 該物件的用途很廣,例如非常適用於影像檔案或透過網路交換的項目。
 </p>
 
-<p>本課程將顯示如何在您的應用程式中執行與檔案相關的基本任務。本課程假設您已熟悉 Linux 檔案系統的基本概念,以及 
+<p>本課程將顯示如何在您的應用程式中執行與檔案相關的基本任務。本課程假設您已熟悉 Linux 檔案系統的基本概念,以及
 {@link java.io} 中的標準檔案輸入/輸出 API。
 </p>
 
@@ -183,7 +183,7 @@
     try {
         String fileName = Uri.parse(url).getLastPathSegment();
         file = File.createTempFile(fileName, null, context.getCacheDir());
-    catch (IOException e) {
+    } catch (IOException e) {
         // Error while creating file
     }
     return file;
@@ -250,12 +250,12 @@
 
 
 
- 
+
   <p>例如,您的應用程式下載的附加資源,或暫存媒體檔案都是私用檔案。</p>
   </dd>
 </dl>
 
-<p>若您希望將公用檔案儲存在外部儲存空間,請使用 
+<p>若您希望將公用檔案儲存在外部儲存空間,請使用
 {@link android.os.Environment#getExternalStoragePublicDirectory
 getExternalStoragePublicDirectory()} 方法取得代表外部儲存空間內相應目錄的 {@link java.io.File}。
 該方法採用對要儲存的檔案類型進行指定 (以便能合理區分這些檔案與其他公用檔案) 的引數,諸如 {@link android.os.Environment#DIRECTORY_MUSIC} 或 {@link
@@ -265,7 +265,7 @@
 
 <pre>
 public File getAlbumStorageDir(String albumName) {
-    // Get the directory for the user's public pictures directory. 
+    // Get the directory for the user's public pictures directory.
     File file = new File(Environment.getExternalStoragePublicDirectory(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -287,7 +287,7 @@
 
 <pre>
 public File getAlbumStorageDir(Context context, String albumName) {
-    // Get the directory for the app's private pictures directory. 
+    // Get the directory for the app's private pictures directory.
     File file = new File(context.getExternalFilesDir(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -366,7 +366,7 @@
 
 <div class="note">
 <p><strong>注意:</strong>使用者解除安裝您的應用程式時,Android 系統會刪除以下檔案:
-</p> 
+</p>
 <ul>
 <li>您在內部儲存空間儲存的所有檔案</li>
 <li>您使用 {@link
diff --git a/docs/html/auto/images/logos/auto/lincoln.png b/docs/html/auto/images/logos/auto/lincoln.png
new file mode 100644
index 0000000..0ade9fe
--- /dev/null
+++ b/docs/html/auto/images/logos/auto/lincoln.png
Binary files differ
diff --git a/docs/html/auto/images/logos/auto/mbenz.png b/docs/html/auto/images/logos/auto/mbenz.png
new file mode 100644
index 0000000..84deacd
--- /dev/null
+++ b/docs/html/auto/images/logos/auto/mbenz.png
Binary files differ
diff --git a/docs/html/auto/images/logos/auto/opel.png b/docs/html/auto/images/logos/auto/opel.png
index 7e25ed5..fcb7040 100644
--- a/docs/html/auto/images/logos/auto/opel.png
+++ b/docs/html/auto/images/logos/auto/opel.png
Binary files differ
diff --git a/docs/html/auto/images/logos/auto/renault.png b/docs/html/auto/images/logos/auto/renault.png
index d252aa3..2970430 100644
--- a/docs/html/auto/images/logos/auto/renault.png
+++ b/docs/html/auto/images/logos/auto/renault.png
Binary files differ
diff --git a/docs/html/auto/images/logos/auto/rsm.png b/docs/html/auto/images/logos/auto/rsm.png
new file mode 100644
index 0000000..fa0e56af
--- /dev/null
+++ b/docs/html/auto/images/logos/auto/rsm.png
Binary files differ
diff --git a/docs/html/auto/images/logos/auto/tata.png b/docs/html/auto/images/logos/auto/tata.png
new file mode 100644
index 0000000..dfc4a5f
--- /dev/null
+++ b/docs/html/auto/images/logos/auto/tata.png
Binary files differ
diff --git a/docs/html/auto/index.jd b/docs/html/auto/index.jd
index 843aabf..5b67641 100644
--- a/docs/html/auto/index.jd
+++ b/docs/html/auto/index.jd
@@ -507,7 +507,12 @@
                       width="120" height="120" class="img-logo" />
               </a>
             </div>
-
+			      <div class="col-5">
+              <a href=" http://www.lincoln.com/">
+                <img src="{@docRoot}auto/images/logos/auto/lincoln.png"
+                    width="120" height="120" class="img-logo" />
+              </a>
+            </div>
             <div class="col-5">
               <a href="http://www.mahindra.com/">
                   <img src="{@docRoot}auto/images/logos/auto/mahindra.png"
@@ -520,16 +525,22 @@
                       width="120" height="120" class="img-logo" />
               </a>
             </div>
+            </div>
+            <div class="cols cols-leftp">
             <div class="col-5">
               <a href="http://www.mazda.com/">
                   <img src="{@docRoot}auto/images/logos/auto/mazda.png"
                       width="120" height="120" class="img-logo" />
               </a>
             </div>
-            </div>
 
-              <div class="cols cols-leftp">
-              <div class="col-5">
+            <div class="col-5">
+              <a href="http://www.mercedes-benz.com/">
+                  <img src="{@docRoot}auto/images/logos/auto/mbenz.png"
+                      width="120" height="120" class="img-logo" />
+              </a>
+            </div>
+             <div class="col-5">
               <a href="http://www.mitsubishi-motors.com/">
                   <img src="{@docRoot}auto/images/logos/auto/mitsubishi.png"
                       width="120" height="120" class="img-logo" />
@@ -542,20 +553,22 @@
                       width="120" height="120" class="img-logo" />
               </a>
             </div>
+            </div>
+            <div class="cols cols-leftp">
             <div class="col-5">
               <a href="http://www.opel.com/">
                   <img src="{@docRoot}auto/images/logos/auto/opel.png"
                       width="120" height="120" class="img-logo" />
               </a>
             </div>
+
             <div class="col-5">
               <a href="http://www.peugeot.com/">
                   <img src="{@docRoot}auto/images/logos/auto/peugeot.png"
                       width="120" height="120" class="img-logo" />
               </a>
             </div>
-            </div>
-            <div class="cols cols-leftp">
+           
             <div class="col-5">
               <a href="http://www.ramtrucks.com/">
                   <img src="{@docRoot}auto/images/logos/auto/ram.png"
@@ -569,27 +582,37 @@
                       width="120" height="120" class="img-logo" />
               </a>
             </div>
+            </div>
+            <div class="cols cols-leftp">
+            <div class="col-5">
+              <a href="http://www.renaultsamsungm.com/ ">
+                  <img src="{@docRoot}auto/images/logos/auto/rsm.png"
+                      width="120" height="120" class="img-logo" />
+              </a>
+            </div>
+           
             <div class="col-5">
               <a href="http://www.seat.com/">
                   <img src="{@docRoot}auto/images/logos/auto/seat.png"
                       width="120" height="120" class="img-logo" />
               </a>
             </div>
+
             <div class="col-5">
               <a href="http://www.skoda-auto.com/">
                   <img src="{@docRoot}auto/images/logos/auto/skoda.png"
                       width="120" height="120" class="img-logo" />
               </a>
             </div>
-            </div>
-            <div class="cols cols-leftp">
+            
             <div class="col-5">
               <a href="http://www.smotor.com/">
                   <img src="{@docRoot}auto/images/logos/auto/ssangyong.png"
                       width="120" height="120" class="img-logo" />
               </a>
             </div>
-
+            </div>
+            <div class="cols cols-leftp">
             <div class="col-5">
               <a href="http://www.subaru-global.com/">
                   <img src="{@docRoot}auto/images/logos/auto/subaru.png"
@@ -597,13 +620,20 @@
               </a>
             </div>
 
-
             <div class="col-5">
               <a href="http://www.globalsuzuki.com/automobile/">
                   <img src="{@docRoot}auto/images/logos/auto/suzuki.png"
                       width="120" height="120" class="img-logo" />
               </a>
             </div>
+            
+            <div class="col-5">
+              <a href="http://www.tatamotors.com/">
+                  <img src="{@docRoot}auto/images/logos/auto/tata.png"
+                      width="120" height="120" class="img-logo" />
+              </a>
+            </div>
+
             <div class="col-5">
               <a href="http://www.vauxhall.co.uk/">
                   <img src="{@docRoot}auto/images/logos/auto/vauxhall.png"
@@ -618,7 +648,8 @@
                       width="120" height="120" class="img-logo" />
               </a>
             </div>
-
+			
+			
             <div class="col-5">
               <a href="http://www.volvocars.com/intl">
                   <img src="{@docRoot}auto/images/logos/auto/volvo.png"
diff --git a/docs/html/guide/topics/resources/layout-resource.jd b/docs/html/guide/topics/resources/layout-resource.jd
index 8c5708a..ab381c3 100644
--- a/docs/html/guide/topics/resources/layout-resource.jd
+++ b/docs/html/guide/topics/resources/layout-resource.jd
@@ -33,16 +33,17 @@
 <dt>syntax:</dt>
 <dd>
 <pre class="stx">
-&lt;?xml version="1.0" encoding="utf-8"?>
-&lt;<a href="#viewgroup-element"><em>ViewGroup</em></a> xmlns:android="http://schemas.android.com/apk/res/android"
+&lt;?xml version="1.0" encoding="utf-8"?&gt;
+&lt;<a href="#viewgroup-element"><em>ViewGroup</em></a>
+    xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@[+][<em>package</em>:]id/<em>resource_name</em>"
-    android:layout_height=["<em>dimension</em>" | "fill_parent" | "wrap_content"]
-    android:layout_width=["<em>dimension</em>" | "fill_parent" | "wrap_content"]
+    android:layout_height=["<em>dimension</em>" | "match_parent" | "wrap_content"]
+    android:layout_width=["<em>dimension</em>" | "match_parent" | "wrap_content"]
     [<em>ViewGroup-specific attributes</em>] &gt;
     &lt;<a href="#view-element"><em>View</em></a>
         android:id="@[+][<em>package</em>:]id/<em>resource_name</em>"
-        android:layout_height=["<em>dimension</em>" | "fill_parent" | "wrap_content"]
-        android:layout_width=["<em>dimension</em>" | "fill_parent" | "wrap_content"]
+        android:layout_height=["<em>dimension</em>" | "match_parent" | "wrap_content"]
+        android:layout_width=["<em>dimension</em>" | "match_parent" | "wrap_content"]
         [<em>View-specific attributes</em>] &gt;
         &lt;<a href="#requestfocus-element">requestFocus</a>/&gt;
     &lt;/<em>View</em>&gt;
@@ -82,15 +83,17 @@
         </dd>
         <dt><code>android:layout_height</code></dt>
         <dd><em>Dimension or keyword</em>. <strong>Required</strong>. The height for the group, as a
-dimension value (or <a
-href="more-resources.html#Dimension">dimension resource</a>) or a keyword ({@code "fill_parent"}
-or {@code "wrap_content"}). See the <a href="#layoutvalues">valid values</a> below.
+dimension value (or
+<a href="more-resources.html#Dimension">dimension resource</a>) or a keyword
+({@code "match_parent"} or {@code "wrap_content"}). See the <a href=
+"#layoutvalues">valid values</a> below.
         </dd>
         <dt><code>android:layout_width</code></dt>
         <dd><em>Dimension or keyword</em>. <strong>Required</strong>. The width for the group, as a
-dimension value (or <a
-href="more-resources.html#Dimension">dimension resource</a>) or a keyword ({@code "fill_parent"}
-or {@code "wrap_content"}). See the <a href="#layoutvalues">valid values</a> below.
+dimension value (or
+<a href="more-resources.html#Dimension">dimension resource</a>) or a keyword
+({@code "match_parent"} or {@code "wrap_content"}). See the <a href=
+"#layoutvalues">valid values</a> below.
         </dd>
       </dl>
       <p>More attributes are supported by the {@link android.view.ViewGroup}
@@ -114,15 +117,17 @@
         </dd>
         <dt><code>android:layout_height</code></dt>
         <dd><em>Dimension or keyword</em>. <strong>Required</strong>. The height for the element, as
-a dimension value (or <a
-href="more-resources.html#Dimension">dimension resource</a>) or a keyword ({@code "fill_parent"}
-or {@code "wrap_content"}). See the <a href="#layoutvalues">valid values</a> below.
+a dimension value (or
+<a href="more-resources.html#Dimension">dimension resource</a>) or a keyword
+({@code "match_parent"} or {@code "wrap_content"}). See the <a href=
+"#layoutvalues">valid values</a> below.
         </dd>
         <dt><code>android:layout_width</code></dt>
         <dd><em>Dimension or keyword</em>. <strong>Required</strong>. The width for the element, as
-a dimension value (or <a
-href="more-resources.html#Dimension">dimension resource</a>) or a keyword ({@code "fill_parent"}
-or {@code "wrap_content"}). See the <a href="#layoutvalues">valid values</a> below.
+a dimension value (or
+<a href="more-resources.html#Dimension">dimension resource</a>) or a keyword
+({@code "match_parent"} or {@code "wrap_content"}). See the <a href=
+"#layoutvalues">valid values</a> below.
         </dd>
       </dl>
       <p>More attributes are supported by the {@link android.view.View}
@@ -221,9 +226,6 @@
 deprecate <code>fill_parent</code>.</td>
     </tr>
     <tr>
-      <td><code>fill_parent</code></td>
-      <td>Sets the dimension to match that of the parent element.</td>
-    </tr><tr>
       <td><code>wrap_content</code></td>
       <td>Sets the dimension only to the size required to fit the content of this element.</td>
     </tr>
@@ -245,8 +247,8 @@
 <pre>
 &lt;?xml version="1.0" encoding="utf-8"?>
 &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-              android:layout_width="fill_parent" 
-              android:layout_height="fill_parent" 
+              android:layout_width="match_parent"
+              android:layout_height="match_parent"
               android:orientation="vertical" >
     &lt;TextView android:id="@+id/text"
               android:layout_width="wrap_content"
@@ -279,4 +281,4 @@
 </ul>
 </dd>
 
-</dl>
+</dl>
\ No newline at end of file
diff --git a/docs/html/images/training/tv/tif/app-link-2x.png b/docs/html/images/training/tv/tif/app-link-2x.png
new file mode 100644
index 0000000..d9d0582
--- /dev/null
+++ b/docs/html/images/training/tv/tif/app-link-2x.png
Binary files differ
diff --git a/docs/html/images/training/tv/tif/app-link-diagram.png b/docs/html/images/training/tv/tif/app-link-diagram.png
new file mode 100644
index 0000000..92328ad
--- /dev/null
+++ b/docs/html/images/training/tv/tif/app-link-diagram.png
Binary files differ
diff --git a/docs/html/images/training/tv/tif/app-link.png b/docs/html/images/training/tv/tif/app-link.png
new file mode 100644
index 0000000..7573a18
--- /dev/null
+++ b/docs/html/images/training/tv/tif/app-link.png
Binary files differ
diff --git a/docs/html/topic/libraries/support-library/features.jd b/docs/html/topic/libraries/support-library/features.jd
index 584bef8..d648384 100755
--- a/docs/html/topic/libraries/support-library/features.jd
+++ b/docs/html/topic/libraries/support-library/features.jd
@@ -142,7 +142,7 @@
 </p>
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/v4/} directory. The library does not contain user
+<code>&lt;sdk&gt;/extras/android/support/v4/</code> directory. The library does not contain user
 interface resources. To include it in your application project, follow the instructions for
 <a href="{@docRoot}tools/support-library/setup.html#libs-without-res">Adding libraries without
 resources</a>.</p>
@@ -169,7 +169,7 @@
 
 <p>
   After you download the Android Support Libraries, this library is located in the
-  {@code &lt;sdk&gt;/extras/android/support/multidex/} directory. The library does not contain
+  <code>&lt;sdk&gt;/extras/android/support/multidex/</code> directory. The library does not contain
   user interface resources. To include it in your application project, follow the instructions
   for
   <a href= "{@docRoot}tools/support-library/setup.html#libs-without-res">Adding libraries without
@@ -229,7 +229,7 @@
 </ul>
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/v7/appcompat/} directory. The library contains user
+<code>&lt;sdk&gt;/extras/android/support/v7/appcompat/</code> directory. The library contains user
 interface resources. To include it in your application project, follow the instructions for
 <a href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries with
 resources</a>.</p>
@@ -250,7 +250,7 @@
 implementations, and are used extensively in layouts for TV apps.</p>
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/v7/cardview/} directory. The library contains user interface
+<code>&lt;sdk&gt;/extras/android/support/v7/cardview/</code> directory. The library contains user interface
 resources. To include it in your application project, follow the instructions
 for <a href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding
 libraries with resources</a>.</p>
@@ -271,7 +271,7 @@
 For detailed information about the v7 gridlayout library APIs, see the
 {@link android.support.v7.widget android.support.v7.widget} package in the API reference.</p>
 
-<p>This library is located in the {@code &lt;sdk&gt;/extras/android/support/v7/gridlayout/}
+<p>This library is located in the <code>&lt;sdk&gt;/extras/android/support/v7/gridlayout/</code>
   directory . The library contains user
   interface resources. To include it in your application project, follow the instructions for
   <a href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries with
@@ -332,7 +332,7 @@
 title card.</p>
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/v7/palette/} directory. The library does not contain
+<code>&lt;sdk&gt;/extras/android/support/v7/palette/</code> directory. The library does not contain
 user interface resources. To include it in your application project, follow the instructions for
 <a href="{@docRoot}tools/support-library/setup.html#libs-without-res">Adding libraries without
 resources</a>.</p>
@@ -354,7 +354,7 @@
 limited window of data items.</p>
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/v7/recyclerview/} directory. The library contains
+<code>&lt;sdk&gt;/extras/android/support/v7/recyclerview/</code> directory. The library contains
 user interface resources. To include it in your application project, follow the instructions
 for <a href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding
 libraries with resources</a>.</p>
@@ -383,7 +383,7 @@
 
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/v7/preference} directory. For more information
+<code>&lt;sdk&gt;/extras/android/support/v7/preference</code> directory. For more information
 on how to set up your project, follow the instructions in <a
 href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries
 with resources</a>. </p>
@@ -447,7 +447,7 @@
 </p>
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/v13/} directory. The library does not contain user
+<code>&lt;sdk&gt;/extras/android/support/v13/</code> directory. The library does not contain user
 interface resources. To include it in your application project, follow the instructions for
 <a href="{@docRoot}tools/support-library/setup.html#libs-without-res">Adding libraries without
 resources</a>.</p>
@@ -479,7 +479,7 @@
 </p>
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/v14/} directory. The library does not contain user
+<code>&lt;sdk&gt;/extras/android/support/v14/</code> directory. The library does not contain user
 interface resources. To include it in your application project, follow the instructions for
 <a href="{@docRoot}tools/support-library/setup.html#libs-without-res">Adding libraries without
 resources</a>.</p>
@@ -508,7 +508,7 @@
 </p>
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/v17/} directory. The library does not contain user
+<code>&lt;sdk&gt;/extras/android/support/v17/</code> directory. The library does not contain user
 interface resources. To include it in your application project, follow the instructions for
 <a href="{@docRoot}tools/support-library/setup.html#libs-without-res">Adding libraries without
 resources</a>.</p>
@@ -550,7 +550,7 @@
 </ul>
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/v17/leanback} directory. For more information
+<code>&lt;sdk&gt;/extras/android/support/v17/leanback</code> directory. For more information
 on how to set up your project, follow the instructions in <a
 href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries
 with resources</a>. </p>
@@ -571,7 +571,7 @@
 <p></p>
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/annotations} directory. For more information
+<code>&lt;sdk&gt;/extras/android/support/annotations</code> directory. For more information
 on how to set up your project, follow the instructions in <a
 href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries
 with resources</a>. </p>
@@ -596,7 +596,7 @@
 
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/design} directory. For more information
+<code>&lt;sdk&gt;/extras/android/support/design</code> directory. For more information
 on how to set up your project, follow the instructions in <a
 href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries
 with resources</a>. </p>
@@ -624,7 +624,7 @@
 
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/customtabs} directory. For more information
+<code>&lt;sdk&gt;/extras/android/support/customtabs</code> directory. For more information
 on how to set up your project, follow the instructions in <a
 href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries
 with resources</a>. </p>
@@ -655,7 +655,7 @@
 
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/percent} directory. For more information
+<code>&lt;sdk&gt;/extras/android/support/percent</code> directory. For more information
 on how to set up your project, follow the instructions in <a
 href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries
 with resources</a>. </p>
@@ -685,7 +685,7 @@
 
 
 <p>After you download the Android Support Libraries, this library is located in the
-{@code &lt;sdk&gt;/extras/android/support/recommendation} directory. For more information
+<code>&lt;sdk&gt;/extras/android/support/recommendation</code> directory. For more information
 on how to set up your project, follow the instructions in <a
 href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries
 with resources</a>. </p>
diff --git a/docs/html/training/articles/perf-tips.jd b/docs/html/training/articles/perf-tips.jd
index 4a3184c..82de69a 100644
--- a/docs/html/training/articles/perf-tips.jd
+++ b/docs/html/training/articles/perf-tips.jd
@@ -43,7 +43,7 @@
 that you can simply say "device X is a factor F faster/slower than device Y",
 and scale your results from one device to others. In particular, measurement
 on the emulator tells you very little about performance on any device. There
-are also huge differences between devices with and without a 
+are also huge differences between devices with and without a
 <acronym title="Just In Time compiler">JIT</acronym>: the best
 code for a device with a JIT is not always the best code for a device
 without.</p>
@@ -88,7 +88,7 @@
     but this also generalizes to the fact that two parallel arrays of ints
     are also a <strong>lot</strong> more efficient than an array of {@code (int,int)}
     objects.  The same goes for any combination of primitive types.</li>
-    
+
     <li>If you need to implement a container that stores tuples of {@code (Foo,Bar)}
     objects, try to remember that two parallel {@code Foo[]} and {@code Bar[]} arrays are
     generally much better than a single array of custom {@code (Foo,Bar)} objects.
@@ -401,19 +401,6 @@
 need to solve. Make sure you can accurately measure your existing performance,
 or you won't be able to measure the benefit of the alternatives you try.</p>
 
-<p>Every claim made in this document is backed up by a benchmark. The source
-to these benchmarks can be found in the <a
-href="http://code.google.com/p/dalvik/source/browse/#svn/trunk/benchmarks">code.google.com
-"dalvik" project</a>.</p>
-
-<p>The benchmarks are built with the
-<a href="http://code.google.com/p/caliper/">Caliper</a> microbenchmarking
-framework for Java. Microbenchmarks are hard to get right, so Caliper goes out
-of its way to do the hard work for you, and even detect some cases where you're
-not measuring what you think you're measuring (because, say, the VM has
-managed to optimize all your code away). We highly recommend you use Caliper
-to run your own microbenchmarks.</p>
-
 <p>You may also find
 <a href="{@docRoot}tools/debugging/debugging-tracing.html">Traceview</a> useful
 for profiling, but it's important to realize that it currently disables the JIT,
diff --git a/docs/html/training/basics/data-storage/files.jd b/docs/html/training/basics/data-storage/files.jd
index 58a1d5f..349af78 100644
--- a/docs/html/training/basics/data-storage/files.jd
+++ b/docs/html/training/basics/data-storage/files.jd
@@ -192,7 +192,7 @@
     try {
         String fileName = Uri.parse(url).getLastPathSegment();
         file = File.createTempFile(fileName, null, context.getCacheDir());
-    catch (IOException e) {
+    } catch (IOException e) {
         // Error while creating file
     }
     return file;
@@ -259,7 +259,7 @@
   your app. Although these files are technically accessible by the user and other apps because they
   are on the external storage, they are files that realistically don't provide value to the user
   outside your app. When the user uninstalls your app, the system deletes
-  all files in your app's external private  directory. 
+  all files in your app's external private  directory.
   <p>For example, additional resources downloaded by your app or temporary media files.</p>
   </dd>
 </dl>
@@ -274,7 +274,7 @@
 
 <pre>
 public File getAlbumStorageDir(String albumName) {
-    // Get the directory for the user's public pictures directory. 
+    // Get the directory for the user's public pictures directory.
     File file = new File(Environment.getExternalStoragePublicDirectory(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -296,7 +296,7 @@
 
 <pre>
 public File getAlbumStorageDir(Context context, String albumName) {
-    // Get the directory for the app's private pictures directory. 
+    // Get the directory for the app's private pictures directory.
     File file = new File(context.getExternalFilesDir(
             Environment.DIRECTORY_PICTURES), albumName);
     if (!file.mkdirs()) {
@@ -375,7 +375,7 @@
 
 <div class="note">
 <p><strong>Note:</strong> When the user uninstalls your app, the Android system deletes
-the following:</p> 
+the following:</p>
 <ul>
 <li>All files you saved on internal storage</li>
 <li>All files you saved on external storage using {@link
diff --git a/docs/html/training/basics/firstapp/creating-project.jd b/docs/html/training/basics/firstapp/creating-project.jd
index e66237a..4c2155b 100644
--- a/docs/html/training/basics/firstapp/creating-project.jd
+++ b/docs/html/training/basics/firstapp/creating-project.jd
@@ -93,13 +93,19 @@
         Activities</a> for more information.</p>
     </div>
   </div>
-  <li>Under <strong>Add an activity to &lt;<em>template</em>&gt;</strong>, select <strong>Blank
-    Activity</strong> and click <strong>Next</strong>.</li>
+  <li>Under <strong>Add an activity to &lt;<em>template</em>&gt;</strong>,
+  select <strong>Basic Activity</strong> and click <strong>Next</strong>.
+  </li>
+
   <li>Under <strong>Customize the Activity</strong>, change the
-    <strong>Activity Name</strong> to <em>MyActivity</em>. The <strong>Layout Name</strong> changes
-    to <em>activity_my</em>, and the <strong>Title</strong> to <em>MyActivity</em>. The
-    <strong>Menu Resource Name</strong> is <em>menu_my</em>.
-   <li>Click the <strong>Finish</strong> button to create the project.</li>
+  <strong>Activity Name</strong> to <em>MyActivity</em>. The <strong>Layout
+  Name</strong> changes to <em>activity_my</em>, and the <strong>Title</strong>
+  to <em>MyActivity</em>. The <strong>Menu Resource Name</strong> is
+  <em>menu_my</em>.
+  </li>
+
+  <li>Click the <strong>Finish</strong> button to create the project.
+  </li>
 </ol>
 
 <p>Your Android project is now a basic "Hello World" app that contains some default files. Take a
@@ -180,4 +186,6 @@
       string and color definitions.</dd>
 </dl>
 
-<p>To run the app, continue to the <a href="running-app.html">next lesson</a>.</p>
+<p>
+  To run the app, continue to the <a href="running-app.html">next lesson</a>.
+</p>
\ No newline at end of file
diff --git a/docs/html/training/displaying-bitmaps/load-bitmap.jd b/docs/html/training/displaying-bitmaps/load-bitmap.jd
index f963baa..81eb1ab 100644
--- a/docs/html/training/displaying-bitmaps/load-bitmap.jd
+++ b/docs/html/training/displaying-bitmaps/load-bitmap.jd
@@ -115,8 +115,8 @@
 
         // Calculate the largest inSampleSize value that is a power of 2 and keeps both
         // height and width larger than the requested height and width.
-        while ((halfHeight / inSampleSize) &gt; reqHeight
-                && (halfWidth / inSampleSize) &gt; reqWidth) {
+        while ((halfHeight / inSampleSize) &gt;= reqHeight
+                && (halfWidth / inSampleSize) &gt;= reqWidth) {
             inSampleSize *= 2;
         }
     }
diff --git a/docs/html/training/testing/ui-testing/uiautomator-testing.jd b/docs/html/training/testing/ui-testing/uiautomator-testing.jd
index 05ddc34..5d42107 100644
--- a/docs/html/training/testing/ui-testing/uiautomator-testing.jd
+++ b/docs/html/training/testing/ui-testing/uiautomator-testing.jd
@@ -26,7 +26,7 @@
   <h2>You should also read</h2>
 
   <ul>
-    <li><a href="{@docRoot}reference/android/support/test/package-summary.html">
+    <li><a href="{@docRoot}reference/android/support/test/uiautomator/package-summary.html">
 UI Automator API Reference</a></li>
   </ul>
 
diff --git a/docs/html/training/tv/tif/channel.jd b/docs/html/training/tv/tif/channel.jd
index 999f1ca..59e357a 100644
--- a/docs/html/training/tv/tif/channel.jd
+++ b/docs/html/training/tv/tif/channel.jd
@@ -13,6 +13,7 @@
     <li><a href="#permission">Get Permission</a></li>
     <li><a href="#register">Register Channels in the Database</a></li>
     <li><a href="#update">Update Channel Data</a></li>
+    <li><a href="#applink">Add App Link Information</a></li>
   </ol>
   <h2>Try It Out</h2>
   <ul>
@@ -22,10 +23,13 @@
 </div>
 </div>
 
-<p>Your TV input must provide Electronic Program Guide (EPG) data for at least one channel in its
-setup activity. You should also periodically update that data, with consideration for the size of
-the update and the processing thread that handles it. This lesson discusses creating and updating
-channel and program data on the system database with these considerations in mind.</p>
+<p>Your TV input must provide Electronic Program Guide (EPG) data for at least
+one channel in its setup activity. You should also periodically update that
+data, with consideration for the size of the update and the processing thread
+that handles it. Additionally, you can provide app links for channels
+that guide the user to related content and activities.
+This lesson discusses creating and updating channel and program data on the
+system database with these considerations in mind.</p>
 
 <p>&nbsp;</p>
 
@@ -70,6 +74,10 @@
   ID</li>
 </ul>
 
+<p>If you want to provide app link details for your channels, you need to
+update some additional fields. For more information on app link fields, see
+<a href="#applink">Add App Link Information</a>.
+
 <p>For internet streaming based TV inputs, assign your own values to the above accordingly so that
 each channel can be identified uniquely.</p>
 
@@ -236,4 +244,112 @@
 <p>Other techniques to separate the data update tasks from the UI thread include using the
 {@link android.os.HandlerThread} class, or you may implement your own using {@link android.os.Looper}
 and {@link android.os.Handler} classes.  See <a href="{@docRoot}guide/components/processes-and-threads.html">
-Processes and Threads</a> for more information.</p>
\ No newline at end of file
+Processes and Threads</a> for more information.</p>
+
+<h2 id="applink">Add App Link Information</h2>
+
+<p>Channels can use <em>app links</em> to let users easily launch a related
+activity while they are watching channel content. Channel apps use
+app links to extend user engagement by launching activities that show
+related information or additional content. For example, you can use app links
+to do the following:</p>
+
+<ul>
+<li>Guide the user to discover and purchase related content.</li>
+<li>Provide additional information about currently playing content.</li>
+<li>While viewing episodic content, start viewing the next episode in a
+series.</li>
+<li>Let the user interact with content&mdash;for example, rate or review
+content&mdash;without interrupting content playback.</li>
+</ul>
+
+<p>App links are displayed when the user presses <b>Select</b> to show the
+TV menu while watching channel content.</p>
+
+<img alt="" src="{@docRoot}images/training/tv/tif/app-link.png"
+srcset="{@docRoot}images/training/tv/tif/app-link.png 1x,
+{@docRoot}images/training/tv/tif/app-link-2x.png 2x" id="figure1"/>
+<p class="img-caption"><strong>Figure 1.</strong> An example app link
+displayed on the <b>Channels</b> row while channel content is shown.</p>
+
+<p>When the user selects the app link, the system starts an activity using
+an intent URI specified by the channel app. Channel content continues to play
+while the app link activity is active. The user can return to the channel
+content by pressing <b>Back</b>.</p>
+
+<h3 id="card">Provide App Link Channel Data</h4>
+
+<p>Android TV automatically creates an app link for each channel,
+using information from the channel data. To provide app link information,
+specify the following details in your
+{@link android.media.tv.TvContract.Channels} fields:
+</p>
+
+<ul>
+<li>{@link android.media.tv.TvContract.Channels#COLUMN_APP_LINK_COLOR} - The
+accent color of the app link for this channel. For an example accent color,
+see figure 2, callout 3.
+</li>
+<li>{@link android.media.tv.TvContract.Channels#COLUMN_APP_LINK_ICON_URI} -
+The URI for the app badge icon of the app link for this channel. For an
+example app badge icon, see figure 2, callout 2.
+</li>
+<li>{@link android.media.tv.TvContract.Channels#COLUMN_APP_LINK_INTENT_URI} -
+The intent URI of the app link for this channel. You can create the URI
+using {@link android.content.Intent#toUri(int) toUri(int)} with
+{@link android.content.Intent#URI_INTENT_SCHEME URI_INTENT_SCHEME} and
+convert the URI back to the original intent with
+{@link android.content.Intent#parseUri parseUri()}.
+</li>
+<li>{@link android.media.tv.TvContract.Channels#COLUMN_APP_LINK_POSTER_ART_URI}
+- The URI for the poster art used as the background of the app link
+for this channel. For an example poster image, see figure 2, callout 1.</li>
+<li>{@link android.media.tv.TvContract.Channels#COLUMN_APP_LINK_TEXT} -
+The descriptive link text of the app link for this channel. For an example
+app link description, see the text in figure 2, callout 3.</li>
+</ul>
+
+<img alt="" src="{@docRoot}images/training/tv/tif/app-link-diagram.png"/>
+<p class="img-caption"><strong>Figure 2.</strong> App link details.</p>
+
+<p>If the channel data doesn't specify app link information, the system
+creates a default app link. The system chooses default details as follows:</p>
+
+<ul>
+<li>For the intent URI
+({@link android.media.tv.TvContract.Channels#COLUMN_APP_LINK_INTENT_URI}),
+the system uses the {@link android.content.Intent#ACTION_MAIN ACTION_MAIN}
+activity for the {@link android.content.Intent#CATEGORY_LEANBACK_LAUNCHER
+CATEGORY_LEANBACK_LAUNCHER} category, typically defined in the app manifest.
+If this activity is not defined, a non-functioning app link appears&mdash;if
+the user clicks it, nothing happens.</li>
+<li>For the descriptive text
+({@link android.media.tv.TvContract.Channels#COLUMN_APP_LINK_TEXT}), the system
+uses "Open <var>app-name</var>". If no viable app link intent URI is defined,
+the system uses "No link available".</li>
+<li>For the accent color
+({@link android.media.tv.TvContract.Channels#COLUMN_APP_LINK_COLOR}),
+the system uses the default app color.</li>
+<li>For the poster image
+({@link android.media.tv.TvContract.Channels#COLUMN_APP_LINK_POSTER_ART_URI}),
+the system uses the app's home screen banner. If the app doesn't provide a
+banner, the system uses a default TV app image.</li>
+<li>For the badge icon
+({@link android.media.tv.TvContract.Channels#COLUMN_APP_LINK_ICON_URI}), the
+system uses a badge that shows the app name. If the system is also using the
+app banner or default app image for the poster image, no app badge is shown.
+</li>
+</ul>
+
+<p>You specify app link details for your channels in your app's
+setup activity. You can update these app link details at any point, so
+if an app link needs to match channel changes, update app
+link details and call
+{@link android.content.ContentResolver#update(android.net.Uri,
+android.content.ContentValues, java.lang.String, java.lang.String[])
+ContentResolver.update()} as needed. For more details on updating
+channel data, see <a href="#update">Update Channel Data</a>.
+</p>
+
+
+
diff --git a/docs/html/wear/preview/_book.yaml b/docs/html/wear/preview/_book.yaml
index a4acad0..3bea2fd 100644
--- a/docs/html/wear/preview/_book.yaml
+++ b/docs/html/wear/preview/_book.yaml
@@ -18,6 +18,8 @@
     path: /wear/preview/features/ui-nav-actions.html
   - title: Bridging for Notifications
     path: /wear/preview/features/bridger.html
+  - title: Wrist Gestures
+    path: /wear/preview/features/gestures.html
 
 - title: Get Started
   path: /wear/preview/start.html
diff --git a/docs/html/wear/preview/api-overview.jd b/docs/html/wear/preview/api-overview.jd
index 11331a7..4233624 100644
--- a/docs/html/wear/preview/api-overview.jd
+++ b/docs/html/wear/preview/api-overview.jd
@@ -25,6 +25,7 @@
             <li><a href="#remote-input">Remote Input</a></li>
             <li><a href="#bridging">Bridging Mode</a></li>
             <li><a href="#imf">Input Method Framework</a></li>
+            <li><a href="#wrist-gestures">Wrist Gestures</a></li>
           </ol>
         </li>
 
@@ -79,12 +80,11 @@
   watch face using the API.
 </p>
 
-<p>For examples of how to use this feature,
+<p>For information about this API,
 see <a href="{@docRoot}wear/preview/features/complications.html">
  Watch Face Complications</a>.
 </p>
 
-
 <h3 id="drawers">Navigation and Action drawers</h3>
 
 <p>Wear 2.0 introduces two new widgets, navigation drawer and action drawer. These
@@ -233,6 +233,24 @@
 Input Method Framework</a>.
 </p>
 
+<h3 id="wrist-gestures">Wrist Gestures</h3>
+
+<p>
+  Wrist gestures can enable quick, one-handed interactions with your app
+  when use of a touch screen is inconvenient. The following
+  <a href="https://support.google.com/androidwear/answer/6312406">wrist gestures</a>
+  are available for use by apps:
+</p>
+
+<ul>
+  <li>Flick wrist out</li>
+  <li>Flick wrist in</li>
+</ul>
+
+<p>For more information, see
+<a href="{@docRoot}wear/preview/features/gestures.html">
+ Wrist Gestures</a>.
+</p>
 
 <h2 id="stand-alone">Standalone Devices</h2>
 
diff --git a/docs/html/wear/preview/downloads.jd b/docs/html/wear/preview/downloads.jd
index 8689504..4bc401b 100644
--- a/docs/html/wear/preview/downloads.jd
+++ b/docs/html/wear/preview/downloads.jd
@@ -223,8 +223,8 @@
     </p>
 
     <p class="warning">
-      <strong>Warning:</strong> Installing a system image on a watch removes all data from the
-      watch, so you should back up your data first.
+      <strong>Warning:</strong> Installing a system image on a watch removes all
+      data from the watch, so you should back up your data first.
     </p>
 
     <h3 id="preview_system_images">
@@ -233,8 +233,13 @@
 
     <p>
       The preview includes system images for testing your app. Based on your
-      device, you can download a preview system image from the following tables
-      and flash it to the corresponding device.
+      device, you can download a preview system image from one of the
+      following tables and flash it to the corresponding device.
+    </p>
+
+    <p>
+      To restore your device to its original state during the preview,
+      you can flash the appropriate retail system image, below, to the device.
     </p>
 
     <h4 id="preview_image_for_lge_watch_urbane_2nd_edition">
@@ -261,9 +266,9 @@
         <td>
           Preview image for testing
         </td>
-        <td><a href="#top" onclick="onDownload(this)">nemo-nvd36i-factory-9cdd2ac0.tgz</a><br>
-          MD5: b33ba8e59780fbe5c83d8936b108640f<br>
-          SHA-1: 9cdd2ac01f2976cafe5a21958298dac159b7a325
+        <td><a href="#top" onclick="onDownload(this)">nemo-nvd83h-factory-48ac950c.tgz</a><br>
+          MD5: dd351884cce9fb5bf1bdec0a8e5f56e3<br>
+          SHA-1: 48ac950c48faef96a7770e3c1acb56d23a28d859
         </td>
       </tr>
 
@@ -302,9 +307,9 @@
         <td>
           Preview image for testing
         </td>
-        <td><a href="#top" onclick="onDownload(this)">sturgeon-nvd36i-factory-2cbe5080.tgz</a><br>
-          MD5: ccc972cdc33cba778a2f624066ef5713<br>
-          SHA-1: 2cbe5080ded060ce43ba65ff27e2290b28981634
+        <td><a href="#top" onclick="onDownload(this)">sturgeon-nvd83h-factory-cb5a11ab.tgz</a><br>
+          MD5: 38c1047992b1d28f6833d9f6c8470cdc<br>
+          SHA-1: cb5a11ab0260ea3ca7da5894e73e41f70357da6b
         </td>
       </tr>
       <tr id="sturgeon-non-preview">
diff --git a/docs/html/wear/preview/features/gestures.jd b/docs/html/wear/preview/features/gestures.jd
new file mode 100644
index 0000000..7806c4e
--- /dev/null
+++ b/docs/html/wear/preview/features/gestures.jd
@@ -0,0 +1,323 @@
+page.title=Wrist Gestures
+meta.keywords="wear-preview"
+page.tags="wear-preview"
+page.image=images/cards/card-n-sdk_2x.png
+
+@jd:body
+
+<div id="qv-wrapper">
+<div id="qv">
+
+<h2>In this document</h2>
+
+  <ul>
+    <li><a href="#using_wlv">Using a WearableListView</a></li>
+    <li><a href="#using_key_events">Using Key Events Directly</a></li>
+    <li><a href="#best_practices">Best Practices</a></li>
+  </ul>
+
+</div>
+</div>
+
+    <p>
+      Wrist gestures can enable quick, one-handed interactions with your app
+      when use of a touch screen is inconvenient. For example, a user can scroll
+      through notifications with one hand while holding a cup of water with the
+      other. Other examples of using wrist gestures when a touch screen would
+      be inconvenient include:
+    </p>
+
+    <ul>
+      <li>In an app for jogging, navigating through vertical screens that show
+      the steps taken, time elapsed, and current pace
+      </li>
+
+      <li>At the airport with luggage, scrolling through flight and gate
+      information
+      </li>
+
+      <li>Scrolling through news articles
+      </li>
+    </ul>
+
+    <p>
+      To review the wrist gestures on your watch, first confirm gestures are
+      turned on by selecting <strong>Settings &gt; Gestures &gt; Wrist Gestures
+      On</strong>. (Wrist gestures are on by default.) Then complete the
+      Gestures tutorial on the watch (<strong>Settings &gt; Gestures &gt;
+      Launch Tutorial</strong>).
+    </p>
+
+    <p>
+      The following gestures from the <a href=
+      "https://support.google.com/androidwear/answer/6312406">Android Wear
+      Help</a> are unavailable to apps:
+    </p>
+
+    <ul>
+      <li>Push wrist down
+      </li>
+
+      <li>Raise wrist up
+      </li>
+
+      <li>Shaking the wrist
+      </li>
+    </ul>
+
+    <p>
+      Wrist gestures can be used in these ways:
+    </p>
+
+    <ul>
+      <li>
+        <a href="#using_wlv">Using a WearableListView</a>, which
+        has predefined gesture actions
+      </li>
+
+      <li>
+        <a href="#using_key_events">Using key events directly</a> to
+        define new user actions
+      </li>
+    </ul>
+
+    <p>
+      Each wrist gesture is mapped to an <code>int</code> constant from the
+      <code><a href=
+      "{@docRoot}reference/android/view/KeyEvent.html">KeyEvent</a></code>
+      class, as shown in the following table:
+    </p>
+
+    <table>
+      <tr>
+        <th>
+          Gesture
+        </th>
+        <th>
+          KeyEvent
+        </th>
+        <th>
+          Description
+        </th>
+      </tr>
+
+      <tr>
+        <td>
+          Flick wrist out
+        </td>
+        <td>
+          <a href=
+          "{@docRoot}reference/android/view/KeyEvent.html#KEYCODE_NAVIGATE_NEXT">
+          KEYCODE_NAVIGATE_NEXT</a>
+        </td>
+        <td>
+          This key code goes to the next item.
+        </td>
+      </tr>
+
+      <tr>
+        <td>
+          Flick wrist in
+        </td>
+        <td>
+          <a href=
+          "{@docRoot}reference/android/view/KeyEvent.html#KEYCODE_NAVIGATE_PREVIOUS">
+          KEYCODE_NAVIGATE_PREVIOUS</a>
+        </td>
+        <td>
+          This key code goes to the previous item.
+        </td>
+      </tr>
+    </table>
+
+    <h2 id="using_wlv">
+      Using a WearableListView
+    </h2>
+
+    <p>
+      A <code><a href=
+      "{@docRoot}reference/android/support/wearable/view/WearableListView.html">
+      WearableListView</a></code> has predefined actions for occurrences of
+      wrist gestures when the View has the focus. For more information, see
+      <a href="#best_practices">Best Practices</a>. For information about using
+      <code>WearableListView</code>, see <a href=
+      "{@docRoot}training/wearables/ui/lists.html">Creating
+      Lists</a>.
+    </p>
+
+    <p>
+      Even if you use a <code>WearableListView</code>, you may want to use
+      constants from the <code><a href=
+      "{@docRoot}reference/android/view/KeyEvent.html">KeyEvent</a></code>
+      class. The predefined actions can be overridden by subclassing the
+      <code>WearableListView</code> and re-implementing the
+      <code>onKeyDown()</code> callback. The behavior can be disabled entirely
+      by using <code>setEnableGestureNavigation(false)</code>. Also see
+      <a href="{@docRoot}training/keyboard-input/commands.html">
+      Handling Keyboard Actions</a>.
+    </p>
+
+    <h2 id="using_key_events">
+      Using Key Events Directly
+    </h2>
+
+    <p>
+      You can use key events outside of a <code><a href=
+      "{@docRoot}reference/android/support/wearable/view/WearableListView.html">
+      WearableListView</a></code> to trigger new actions in response to gesture
+      events. Importantly, these gesture events:
+    </p>
+
+    <ul>
+      <li>Are recognized when a device is in Active mode
+      </li>
+
+      <li>Are delivered in the same way as all key events
+      </li>
+    </ul>
+
+    <p>
+      Specifically, these events are delivered to the top Activity, to the View
+      with keyboard focus. Just as any other key event, a class that relates to
+      user interaction (such as a View or an Activity) that implements
+      <code><a href=
+      "{@docRoot}reference/android/view/KeyEvent.Callback.html">
+      KeyEvent.Callback</a></code> can listen to key events that relate to
+      wrist gestures. The Android framework calls the View or Activity that has
+      the focus with the key events; for gestures, the <code>onKeyDown()</code>
+      method callback is called when gestures occur.
+    </p>
+
+    <p>
+      As an example, an app may override predefined actions in a View or
+      Activity (both implementing <code>KeyEvent.Callback</code>) as follows:
+    </p>
+
+    <pre>
+public final class GesturesActivity extends Activity {
+
+ &#64;Override /* KeyEvent.Callback */
+ public boolean onKeyDown(int keyCode, KeyEvent event) {
+  switch (keyCode) {
+   case KeyEvent.KEYCODE_NAVIGATE_NEXT:
+    // Do something that advances a user View to the next item in an ordered list.
+    return moveToNextItem();
+   case KeyEvent.KEYCODE_NAVIGATE_PREVIOUS:
+    // Do something that advances a user View to the previous item in an ordered list.
+    return moveToPreviousItem();
+  }
+  // If you did not handle it, let it be handled by the next possible element as deemed by the Activity.
+  return super.onKeyDown(keyCode, event);
+ }
+
+ /** Shows the next item in the custom list. */
+ private boolean moveToNextItem() {
+  boolean handled = false;
+  …
+  // Return true if handled successfully, otherwise return false.
+  return handled;
+ }
+
+ /** Shows the previous item in the custom list. */
+ private boolean moveToPreviousItem() {
+  boolean handled = false;
+  …
+  // Return true if handled successfully, otherwise return false.
+  return handled;
+ }
+}
+</pre>
+
+    <h2 id="best_practices">
+      Best Practices
+    </h2>
+
+    <ul>
+      <li>Review the <code><a href=
+      "{@docRoot}reference/android/view/KeyEvent.html">KeyEvent</a></code>
+      and <code><a href=
+      "{@docRoot}reference/android/view/KeyEvent.Callback.html">
+        KeyEvent.Callback</a></code> pages for the delivery of key events to
+        your View and Activity.
+      </li>
+
+      <li>Keep a consistent directional affordance:
+        <ul>
+          <li>Use "Flick wrist out" for next, "Flick wrist in" for previous
+          </li>
+        </ul>
+      </li>
+
+      <li>Have a touch parallel for a gesture.
+      </li>
+
+      <li>Provide visual feedback.
+      </li>
+
+      <li>Don't use a keycode to implement functionality that would be
+      counter-intuitive to the rest of the system. For example, do not use
+      <code>KEYCODE_NAVIGATE_NEXT</code> to cancel an action or to navigate the
+      left-right axis with flicks.
+      </li>
+
+      <li>Don't intercept the key events on elements that are not part of the
+      user interface, for example the Views that are offscreen or partially
+      covered. This is the same as any other key event.
+      </li>
+
+      <li>Don't reinterpret repeated flick gestures into your own, new gesture.
+      It may conflict with the system's "Shaking the wrist" gesture.
+      </li>
+
+      <li>For a View to receive gesture key events, it must have <a href=
+      "{@docRoot}reference/android/view/View.html#attr_android:focusable">
+        focus</a>; see <a href=
+        "{@docRoot}reference/android/view/View.html#setFocusable(boolean)">
+        View::setFocusable()</a>. Because gestures are treated as key events,
+        they trigger a transition out of "Touch mode" that may do unexpected
+        things. Therefore, since users may alternate between using touch and
+        gestures, the <a href=
+        "{@docRoot}reference/android/view/View.html#setFocusableInTouchMode(boolean)">
+        View::setFocusableInTouchmode()</a> method may be necessary. In some
+        cases, it also may be necessary to use
+        <code>setDescendantFocusability(FOCUS_BEFORE_DESCENDANTS)</code> so
+        that when focus changes after a change to or from "Touch mode," your
+        intended View gets the focus.
+      </li>
+
+      <li>Use <code>requestFocus()</code> and <code>clearFocus()</code>
+      carefully:
+        <ul>
+          <li>When calling <code><a href=
+          "{@docRoot}reference/android/view/View.html#requestFocus()">
+            requestFocus()</a></code>, be sure that the View really should have
+            focus. If the View is offscreen, or is covered by another View,
+            surprises can occur when gestures trigger callbacks.
+          </li>
+
+          <li>The <code><a href=
+          "{@docRoot}reference/android/view/View.html#clearFocus()">
+            clearFocus()</a></code> initiates a focus search to find another
+            suitable View. Depending on the View hierarchy, this search might
+            require non-trivial computation. It can also end up assigning focus
+            to a View you don’t expect to receive focus.
+          </li>
+        </ul>
+      </li>
+
+      <li>Key events are delivered first to the View with focus in the View
+      hierarchy. If the focused View does not handle the event (i.e., returns
+      <code>false</code>), the event is not delivered to the parent View, even
+      if it can receive focus and has a <a href=
+      "{@docRoot}reference/android/text/method/KeyListener.html">
+        KeyListener</a>. Rather, the event is delivered to the current Activity
+        holding the View hierarchy with focus. Thus, it may be necessary to
+        catch all events at the higher level and then pass relevant codes down.
+        Alternatively, you might subclass the Activity and override the
+        <code><a href=
+        "{@docRoot}reference/android/app/Activity.html#dispatchKeyEvent(android.view.KeyEvent)">
+        dispatchKeyEvent(KeyEvent event)</a></code> method to ensure that keys
+        are intercepted when necessary, or are handled when not handled at
+        lower layers.
+      </li>
+    </ul>
diff --git a/docs/html/wear/preview/features/ui-nav-actions.jd b/docs/html/wear/preview/features/ui-nav-actions.jd
index 1ba275f..fb14264 100644
--- a/docs/html/wear/preview/features/ui-nav-actions.jd
+++ b/docs/html/wear/preview/features/ui-nav-actions.jd
@@ -12,7 +12,7 @@
     <ol>
       <li><a href="#create a drawer">Create a Drawer Layout</a></li>
       <li><a href="#initialize">Initialize the Drawer List</a></li>
-      <li><a href="#creating">Create a Custom View Drawer</a></li>
+      <li><a href="#creating">Create a Custom Drawer View</a></li>
       <li><a href="#listen to events">Listen for Drawer Events</a></li>
       <li><a href=#peeking">Peeking Drawers</a></li>
     </ol>
@@ -37,8 +37,8 @@
 </div>
 </div>
 <p>As part of the <a href="http://www.google.com/design/spec-wear">Material Design</a>
- for Android Wear, Wear 2.0 adds interactive navigation and action drawers. 
- The navigation drawer appears at the top of the screen and lets users jump to 
+ for Android Wear, Wear 2.0 adds interactive navigation and action drawers.
+ The navigation drawer appears at the top of the screen and lets users jump to
  different views within
 the app, similar to the navigation drawer on a phone. The action drawer appears
 at the bottom of the screen and provides context-specific actions for the user,
@@ -59,7 +59,8 @@
 <div class="cols">
 
 <p>This lesson describes how to implement action and navigation drawers in your
-app using the {@code WearableDrawerLayout} APIs.
+app using the {@code WearableDrawerLayout} APIs. For more information, see the
+downloadable <a href="{@docRoot}preview/setup-sdk.html#docs-dl">API reference</a>.
 </p>
 
 <h2 id="create a drawer">Create a Drawer Layout</h2>
@@ -99,41 +100,44 @@
 &lt;/android.support.wearable.view.drawer.WearableDrawerLayout>
 
 </pre>
+
 <h2 id="initialize">Initialize the Drawer List</h2>
 <p>One of the first things you need to do in your activity is to initialize the
 drawers list of items. You should implement {@code WearableNavigationDrawerAdapter}
 to populate the navigation drawer contents. To populate the action drawer with
-a list of actions, inflate an XML file into the Menu (via MenuInflater).</p>
+a list of actions, inflate an XML file into the Menu (via {@code MenuInflater}).
+</p>
 
 <p>The following code snippet shows how to initialize the contents of your drawers:
 </p>
+
 <pre>
 public class MainActivity extends  WearableActivity implements
 WearableActionDrawer.OnMenuItemClickListener{
     private WearableDrawerLayout mwearableDrawerLayout;
     private WearableNavigationDrawer mWearableNavigationDrawer;
     private WearableActionDrawer mWearableActionDrawer;
-    
+
     ...
-    
+
     &#64;Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
-        
+
         ......
-        
-        
+
+
         // Main Wearable Drawer Layout that wraps all content
         mWearableDrawerLayout = (WearableDrawerLayout) findViewById(R.id.drawer_layout);
-        
+
         // Top Navigation Drawer
         mWearableNavigationDrawer = (WearableNavigationDrawer) findViewById(R.id.top_navigation_drawer);
         mWearableNavigationDrawer.setAdapter(new YourImplementationNavigationAdapter(this));
 
         // Peeks Navigation drawer on the top.
         mWearableDrawerLayout.peekDrawer(Gravity.TOP);
-        
+
         // Bottom Action Drawer
         mWearableActionDrawer = (WearableActionDrawer) findViewById(R.id.bottom_action_drawer);
 
@@ -149,44 +153,58 @@
 }
 
 </pre>
-<h2 id="creating">Create a Custom View Drawer</h2>
 
-<p>To use custom views in drawers,  add  <code>WearableDrawerView</code> to  the
-<code>WearableDrawerLayout</code>. To set the contents of the drawer, call <code>
-<a href="https://x20web.corp.google.com/~psoulos/docs/reference/android/support/wearable/view/drawer/WearableDrawerView.html#setDrawerContent(android.view.View)">setDrawerContent(View)</a></code>
- instead of manually adding the view to the hierarchy. You must also specify the
-  drawer position with the <code>android:layout_gravity</code> attribute. </p>
-<p> The following example specifies a top drawer:</p>
+<h2 id="creating">Create a Custom Drawer View</h2>
+
+<p>To use custom views in drawers, add <code>WearableDrawerView</code> to the
+<code>WearableDrawerLayout</code>. To set the peek view and drawer contents, add
+ them as children of the {@code WearableDrawerView} and specify their IDs in the
+ {@code peek_view} and {@code drawer_content} attributes respectively. You must
+ also specify the drawer position with the {@code android:layout_gravity}
+ attribute. </p>
+
+<p> The following example specifies a top drawer with peek view and drawer
+contents:</p>
+
 <pre>
-&lt;android.support.wearable.view.drawer.WearableDrawerLayout&gt;
-    &lt;FrameLayout 
-    android:id=”@+id/content” /&gt;
-
-    &lt;WearableDrawerView
-        android:layout_width=”match_parent”
-        andndroid:layout_height=”match_parent”
-        android:layout_gravity=”top”&gt;
-        &lt;FrameLayout 
-            android:id=”@+id/top_drawer_content” /&gt;
-    &lt;/WearableDrawerView&gt;
-&lt;/android.support.wearable.view.drawer.WearableDrawerView&gt;
+   &lt;android.support.wearable.view.drawer.WearableDrawerView
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:layout_gravity="top"
+        android:background="@color/red"
+        app:drawer_content="@+id/drawer_content"
+        app:peek_view="@+id/peek_view">
+        &lt;FrameLayout
+            android:id="@id/drawer_content"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent">
+            &lt;!-- Drawer content goes here.  -->
+        &lt;/FrameLayout>
+        &lt;LinearLayout
+            android:id="@id/peek_view"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_gravity="center_horizontal"
+            android:orientation="horizontal">
+            &lt;!-- Peek view content goes here.  -->
+        &lt;LinearLayout>
+    &lt;/android.support.wearable.view.drawer.WearableDrawerView>
 
 </pre>
 
 <h2 id="listen to events">Listen for Drawer Events</h2>
-<p>To listen for drawer events, call {@code setDrawerStateCallback()}on your
+<p>To listen for drawer events, call {@code setDrawerStateCallback()} on your
 {@code WearableDrawerLayout} and pass it an implementation of
 {@code WearableDrawerLayout.DrawerStateCallback}. This interface provides callbacks
  for drawer events such as <code>onDrawerOpened()</code>,
  <code>onDrawerClosed(),</code> and <code>onDrawerStatechanged()</code>.</p>
 
 <h2 id="peeking">Peeking Drawers</h2>
-<p>To  set the drawers to temporarily appear, call  <code>peekDrawer()</code> on
+<p>To set the drawers to temporarily appear, call <code>peekDrawer()</code> on
 your {@code WearableDrawerLayout} and pass it the {@code Gravity} of the drawer.
  This feature is especially useful because it allows immediate access to the
- alternate drawer views or actions associated with it. </p>
+ alternate drawer views or actions associated with it: </p>
 
-<pre>{@code mWearableDrawerLayout.peekDrawer</code>(<code>Gravity.BOTTOM);}</pre>
+<pre>{@code mWearableDrawerLayout.peekDrawer(Gravity.BOTTOM);}</pre>
 
-<p>You can also call {@code setPeekContent()} on your drawer to display a custom
- view when the drawer is peeking.</p>
+
diff --git a/docs/html/wear/preview/program.jd b/docs/html/wear/preview/program.jd
index a130663..e2bf92f 100644
--- a/docs/html/wear/preview/program.jd
+++ b/docs/html/wear/preview/program.jd
@@ -79,6 +79,11 @@
           </div>
 
           <div class="col-4of12">
+            <h5>
+            </h5>
+
+            <p>
+            </p>
           </div>
         </div>
       </div>
@@ -90,7 +95,7 @@
 
     <p>
       The Android Wear 2.0 Developer Preview runs from 18 May 2016 until the
-      final Android Wear public release to OEMs, planned for Q4 2016.
+      final Android Wear public release to OEMs.
     </p>
 
     <p>
@@ -136,7 +141,7 @@
     </p>
 
     <p>
-      At milestones 4 and 5 you'll have access to the final Android Wear 2.0
+      At milestone 4, you'll have access to the final Android Wear 2.0
       APIs and SDK to develop with, as well as near-final system images to test
       system behaviors and features. Android Wear 2.0 will use the Android N
       API level at this time. You can begin final compatibility testing of your
@@ -196,9 +201,9 @@
     </h3>
 
     <p>
-      You can download these hardware system images at <a href=
+      You can download these hardware system images from the <a href=
       "{@docRoot}wear/preview/downloads.html">Download and Test with a
-      Device</a>:
+      Device</a> page:
     </p>
 
     <ul>
@@ -210,7 +215,15 @@
     </ul>
 
     <p>
-     Please keep in mind that the Developer Preview system images
+     To restore your device to its
+     original state during the preview, you can flash the
+     appropriate retail system image from
+     the <a href="{@docRoot}wear/preview/downloads.html">Download and
+     Test with a Device</a> page.
+    </p>
+
+    <p>
+     Please keep in mind that the preview system images
      are for app developers only, and for compatibility testing and
      early development only, and are not ready for day-to-day use.
     </p>
diff --git a/docs/html/wear/preview/start.jd b/docs/html/wear/preview/start.jd
index 65d4b56..8fccdc8 100644
--- a/docs/html/wear/preview/start.jd
+++ b/docs/html/wear/preview/start.jd
@@ -107,10 +107,10 @@
 
       <tr>
         <td>
-          <a href="http://storage.googleapis.com/androiddevelopers/shareables/wear-preview/wearable-support-preview-1-docs.zip">wearable-support-preview-1-docs.zip</a>
+          <a href="http://storage.googleapis.com/androiddevelopers/shareables/wear-preview/wearable-support-preview-2-docs.zip">wearable-support-preview-2-docs.zip</a>
         </td>
-        <td>MD5: 02f9dc7714c00076b323c9081655c3b2<br>
-            SHA-1: 075f3821ee9b66a919a0e8086f79c12bc9576fb2
+        <td>MD5: afb770c9c5c0431bbcbdde186f1eae06<br>
+            SHA-1: 81d681e61cee01f222ea82e83297d23c4e55b8f3
         </td>
       </tr>
     </table>
@@ -146,16 +146,26 @@
       plugin.
       </li>
 
-      <li>In the <code>build.gradle</code> file for the Wear module, in the
-      <code>dependencies</code> section, update the existing reference to the
+      <li>In the <code>build.gradle</code> file for the Wear module:
+      <ul>
+        <li>In the <code>android</code> section, update the
+        <code>compileSdkVersion</code> to 24.
+        </li>
+
+        <li>In the <code>android</code> section, update the
+        <code>targetSdkVersion</code> to 24.
+        </li>
+
+        <li>In the <code>dependencies</code> section, update
+      the existing reference to the
       Wearable Support Library (for example, <code>compile
       'com.google.android.support:wearable:1.4.0'</code>) by changing it to the
       following, which requires that your the Google Repository <a href=
       "#install_android_studio_and_the_latest_packages">is the latest
       version</a>:
-      <pre>
-compile 'com.google.android.support:wearable:2.0.0-alpha1'
-      </pre>
+      <code>compile 'com.google.android.support:wearable:2.0.0-alpha2'</code>
+        </li>
+      </ul>
       </li>
 
       <li>See the following page for setting up a watch or emulator with a
@@ -190,13 +200,24 @@
       wizard.
       </li>
 
-      <li>In the <code>build.gradle</code> file for the Wear module, in the
-      <code>dependencies</code> section, update the existing reference to the
-      Wearable Support Library (perhaps <code>compile
-      'com.google.android.support:wearable:1.4.0'</code>) to:
-      <pre>
-compile 'com.google.android.support:wearable:2.0.0-alpha1'
-      </pre>
+      <li>In the <code>build.gradle</code> file for the Wear module:
+      <ul>
+        <li>In the <code>android</code> section, update the
+        <code>compileSdkVersion</code> to 24.
+        </li>
+        <li>In the <code>android</code> section, update the
+        <code>targetSdkVersion</code> to 24.
+        </li>
+        <li>In the <code>dependencies</code> section, update
+      the existing reference to the
+      Wearable Support Library (for example, <code>compile
+      'com.google.android.support:wearable:1.4.0'</code>) by changing it to the
+      following, which requires that your the Google Repository <a href=
+      "#install_android_studio_and_the_latest_packages">is the latest
+      version</a>:
+      <code>compile 'com.google.android.support:wearable:2.0.0-alpha2'</code>
+        </li>
+      </ul>
       </li>
 
       <li>See the following page for setting up a watch or emulator with a
diff --git a/docs/html/wear/preview/support.jd b/docs/html/wear/preview/support.jd
index d03edf3..78b4e4b 100644
--- a/docs/html/wear/preview/support.jd
+++ b/docs/html/wear/preview/support.jd
@@ -16,7 +16,262 @@
   Wear Developer Google+ community</a>.
 </p>
 
-<h2 id="dp">Developer Preview 1</h2>
+<div id="qv-wrapper">
+<div id="qv">
+
+<h2>In this document</h2>
+
+<ul>
+  <li><a href="#general">General Advisories</a></li>
+  <li><a href="#deprecations">Deprecations</a></li>
+  <li><a href="#dp2">Developer Preview 2</a></li>
+  <li><a href="#dp1">Developer Preview 1</a></li>
+</ul>
+
+</div>
+</div>
+
+<h2 id="general">General Advisories</h2>
+
+<p>
+  The developer preview is for <strong>app developers and other early
+  adopters</strong> and is available for daily use, development, or
+  compatibility testing. Please be aware of these general notes about the
+  release:
+</p>
+
+<ul>
+  <li>The developer preview may have various <strong>stability issues</strong> on
+    supported devices. Users may encounter system instability, such as kernel
+    panics and crashes.
+  </li>
+  <li>Some apps <strong>may not function as expected</strong> on the new
+  platform version. This includes Google’s apps and other apps.
+  </li>
+</ul>
+
+<h2 id="deprecations">Deprecations</h2>
+
+<p>The following fields are deprecated in the preview:</p>
+
+<ul>
+  <li>The <code>Notification.WearableExtender#setCustomSizePreset(int)</code>
+  method no longer accepts <code>SIZE_FULL_SCREEN</code> and this value is now
+  undefined.
+  </li>
+  <li>The <code>Notification.WearableExtender#setContentIcon(int)</code> method
+  is deprecated.
+  </li>
+</ul>
+
+<h2 id="dp2">Developer Preview 2</h2>
+
+<div class="wrap">
+  <div class="cols">
+    <div class="col-6of12">
+      <p><em>Date: July 2016<br />
+      Builds: Wearable Support 2.0.0-alpha2, NVD83H<br/>
+      Emulator support: x86 & ARM (32-bit)<br/>
+      </em></p>
+    </div>
+  </div>
+</div>
+
+<h3 id="new-in-fdp2">
+  <strong>New in Preview 2</strong>
+</h3>
+
+<h4 id="platform-version-24">
+  Platform API Version
+</h4>
+
+<p>
+  The Android Platform API version is incremented to 24 to match Android Nougat.
+  You can update the following in your Android Wear 2.0 Preview project
+  to <strong>24</strong>:
+</p>
+
+<ul>
+  <li><code>compileSdkVersion</code></li>
+  <li><code>targetSdkVersion</code></li>
+</ul>
+
+<h4 id="wearable-drawers">
+  Wearable drawers
+</h4>
+
+<p>
+  The following are feature additions for <a href=
+  "{@docRoot}wear/preview/features/ui-nav-actions.html">
+  wearable drawers</a>:
+</p>
+
+<ul>
+  <li>Drawer peeking is now supported in the <code>onCreate()</code> method
+  of your app's activity.
+  </li>
+
+  <li>The automatic drawer peeking behavior is
+  inverted. Now the bottom drawer peeks when the user scrolls down the view
+  and top drawer peeks when the user scrolls to the top of the view
+  (previously scrolling down did not show peek view).
+  </li>
+
+  <li>Two new attributes, <code>peek_view</code> and
+  <code>drawer_content</code>, are added to
+  <code>WearableDrawerView</code> to specify contents of custom drawers and
+  peek view in your XML layout (previously, custom drawer contents were
+  specified only through Java code).
+  </li>
+
+  <li>The Navigation drawer now displays page indicator dots.
+  </li>
+
+  <li>Peek views now close automatically after one second.
+  </li>
+
+  <li>The <code>WearableNavigationDrawer</code> now automatically closes
+  after five seconds or when an item is tapped.
+  </li>
+
+  <li>There is improved drawer handling (size and margins) for devices with chins:
+    <ul>
+      <li>Size: The bottom drawer is slightly smaller when there is a
+      chin.
+      </li>
+      <li>Margins: <code>WearableDrawerLayout</code> sets its bottom margin
+      size equal to the size of the chin, so that the bottom drawer is
+      fully visible.
+      </li>
+    </ul>
+  <li>The navigation drawer contents are now updated when
+        <code><a href="{@docRoot}reference/android/widget/ArrayAdapter.html#notifyDataSetChanged()">
+        notifyDataSetChanged</a></code> is called on the adapter.
+  </li>
+
+    <li>In your <code>WearableActionDrawer</code>, when there is only one
+      action, its icon is shown in the peek view and the action is executed
+      when the peek view is tapped.
+    </li>
+
+    <li>When the peek view of your <code>WearableActionDrawer</code> has
+      more than one action, both the first action and the overflow icons are
+      shown.
+    </li>
+</ul>
+
+<h4 id="gestures">
+  Wrist gestures
+</h4>
+
+<p>
+  Wrist gestures can enable quick, one-handed interactions with your app.
+  For example, a user can
+  scroll through notifications with one hand while holding a cup of water
+  with the other. For more information, see <a href=
+  "{@docRoot}wear/preview/features/gestures.html">
+  Wrist Gestures</a>.
+</p>
+
+<h3 id="known-issues-2">
+  <strong>Known Issues</strong>
+</h3>
+
+<h4 id="notifications-2">
+  Notifications
+</h4>
+
+<ul>
+  <li>This preview release does not include support for notification
+  groups.
+  </li>
+
+  <li>The user interface for the action drawer can sometimes have a
+  transparent background.
+  </li>
+
+  <li>The system does not generate Smart Reply responses even if
+  <code>setAllowGeneratedReplies(true)</code> is set.
+  </li>
+</ul>
+
+<h4 id="complications-2">
+  Complications
+</h4>
+
+<ul>
+  <li>When tapping on the music complication on a watch face, Play Music
+  crashes if the Apps launcher provider is used.
+  </li>
+</ul>
+
+<h4 id="system-user-interface-2">
+  System User Interface
+</h4>
+
+<ul>
+  <li>Pressing the hardware button in ambient mode triggers active mode
+  with the app launcher instead of active mode only.
+  </li>
+
+  <li>Double pressing the power hardware button while on the launcher
+  causes the watch screen to turn black.
+  </li>
+
+  <li>Dismissing multiple notifications can cause app to forcibly close.
+  </li>
+
+  <li>Turning screen lock to off (Enable and disable) functionality is not
+  reliable.
+  </li>
+
+  <li>The "Ok Google" detection and voice transcription may not work
+  reliably. Additionally, Search does not retrieve results.
+  </li>
+
+  <li>Tapping Google keyboard English (United States) displays a "Settings
+  under construction" message.
+  </li>
+
+  <li>First calendar event notification must be dismissed in order to show
+  the rest of the event card.
+  </li>
+
+  <li>Unable to turn off the Wi-Fi on a wearable.
+  </li>
+</ul>
+
+<h4 id="companion-app-2">
+  Companion App
+</h4>
+
+<ul>
+  <li>An actions card is shown in the Android Wear companion app, even
+  though there are no actions.
+  </li>
+</ul>
+
+<h4 id="devices-2">
+  Devices
+</h4>
+
+<ul>
+  <li>On the Huawei Watch, selecting the language, followed by multiple
+  acknowledgement dialogues results in a black screen.
+  </li>
+
+  <li>On the LG Watch Urbane 2nd Edition, when answering a call from the watch, the
+  watch does not provide audio from the caller.
+  </li>
+
+  <li>On the LG Watch Urbane 2nd Edition,
+  please do the following to prevent battery drain:
+  Turn on Airplane mode (to disable the cellular radio) and then
+  turn on Bluetooth.
+  </li>
+</ul>
+
+<h2 id="dp1">Developer Preview 1</h2>
 
 <div class="wrap">
   <div class="cols">
@@ -29,36 +284,10 @@
   </div>
 </div>
 
-
-<h3 id="general_advisories">General advisories</h3>
-
-<p>
-  This Developer Preview release is for app developers only and is designed for
-  use in compatibility testing and early development only.
-</p>
-
-<h4 id="deprecations">Deprecations</h4>
-
-
-<p>The following fields are deprecated in the Preview:</p>
-
-<ul>
-  <li>The <code>Notification.WearableExtender#setCustomSizePreset(int)</code>
-  method no longer accepts <code>SIZE_FULL_SCREEN</code> and this value is now
-  undefined.
-  </li>
-
-  <li>The <code>Notification.WearableExtender#setContentIcon(int)</code> method
-  is deprecated.
-  </li>
-</ul>
-
 <h3 id="known_issues">Known Issues</h3>
 
-
 <h4 id="notifications">Notifications</h4>
 
-
 <ul>
   <li>This preview release does not include support for notification groups,
   but will be supported in a future release.
@@ -74,18 +303,17 @@
   </li>
 </ul>
 
-
 <h4 id="complications">Complications</h4>
 
 <ul>
-  <li>Battery information is not synchronized between watch face and drop down
-  quick menu.
+  <li>Battery information is not synchronized between the
+  watch face and the drop-down Quick menu.
   </li>
-  <li>Play music crashes when tapping on music complication in watch face.
+  <li>When tapping on the music complication on a watch face, Play Music
+      crashes if the Apps launcher provider is used.
   </li>
 </ul>
 
-
 <h4 id="system_user_interface">System User Interface</h4>
 
 <ul>
@@ -114,26 +342,24 @@
   </li>
 </ul>
 
-
 <h4 id="companion_app">Companion App</h4>
 
 <ul>
-  <li>'More actions' via Companion app shows a blank screen on phone running
-  nyc-release and watch running feldspar-release.
-  </li>
-  <li>Select watch face on companion wear app will not change watch face on
-  wearable.
-  </li>
+   <li>Selecting a watch face on the companion app will not change the watch face on
+   wearable.</li>
+   <li>An actions card is shown in the Android Wear companion app, even
+   though there are no actions.
+   </li>
 </ul>
 
-
 <h4 id="devices">Devices</h4>
 
 <ul>
   <li>On the Huawei Watch, selecting the language, followed by multiple
   acknowledgement dialogues results in a black screen.
   </li>
-  <li>On the LG Watch Urbane LTE, when answering call from the watch, the watch
+  <li>On the LG Watch Urbane 2nd Edition, when
+  answering a call from the watch, the watch
   does not provide audio from the caller.
   </li>
 </ul>
diff --git a/docs/html/work/managed-configurations.jd b/docs/html/work/managed-configurations.jd
index dc3ef0d..91c0637 100644
--- a/docs/html/work/managed-configurations.jd
+++ b/docs/html/work/managed-configurations.jd
@@ -149,9 +149,9 @@
 
   &lt;restriction
     android:key="downloadOnCellular"
-    android:title="App is allowed to download data via cellular"
+    android:title="@string/download_on_cell_title"
     android:restrictionType="bool"
-    android:description="If 'false', app can only download data via Wi-Fi"
+    android:description="@string/download_on_cell_description"
     android:defaultValue="true" /&gt;
 
 &lt;/restrictions&gt;
diff --git a/docs/image_sources/training/tv/tif/app-link-diagram.graffle.zip b/docs/image_sources/training/tv/tif/app-link-diagram.graffle.zip
new file mode 100644
index 0000000..8b6779d
--- /dev/null
+++ b/docs/image_sources/training/tv/tif/app-link-diagram.graffle.zip
Binary files differ
diff --git a/libs/hwui/RenderNode.cpp b/libs/hwui/RenderNode.cpp
index f8797bf..6facf20 100644
--- a/libs/hwui/RenderNode.cpp
+++ b/libs/hwui/RenderNode.cpp
@@ -301,7 +301,10 @@
     LayerType layerType = properties().effectiveLayerType();
     // If we are not a layer OR we cannot be rendered (eg, view was detached)
     // we need to destroy any Layers we may have had previously
-    if (CC_LIKELY(layerType != LayerType::RenderLayer) || CC_UNLIKELY(!isRenderable())) {
+    if (CC_LIKELY(layerType != LayerType::RenderLayer)
+            || CC_UNLIKELY(!isRenderable())
+            || CC_UNLIKELY(properties().getWidth() == 0)
+            || CC_UNLIKELY(properties().getHeight() == 0)) {
         if (CC_UNLIKELY(mLayer)) {
             destroyLayer(mLayer);
             mLayer = nullptr;
diff --git a/libs/hwui/RenderProperties.h b/libs/hwui/RenderProperties.h
index 696cc29..3952798 100644
--- a/libs/hwui/RenderProperties.h
+++ b/libs/hwui/RenderProperties.h
@@ -611,9 +611,7 @@
     bool fitsOnLayer() const {
         const DeviceInfo* deviceInfo = DeviceInfo::get();
         return mPrimitiveFields.mWidth <= deviceInfo->maxTextureSize()
-                        && mPrimitiveFields.mHeight <= deviceInfo->maxTextureSize()
-                        && mPrimitiveFields.mWidth > 0
-                        && mPrimitiveFields.mHeight > 0;
+                        && mPrimitiveFields.mHeight <= deviceInfo->maxTextureSize();
     }
 
     bool promotedToLayer() const {
diff --git a/libs/hwui/tests/unit/RenderPropertiesTests.cpp b/libs/hwui/tests/unit/RenderPropertiesTests.cpp
index 9001098..85655fc 100644
--- a/libs/hwui/tests/unit/RenderPropertiesTests.cpp
+++ b/libs/hwui/tests/unit/RenderPropertiesTests.cpp
@@ -42,7 +42,7 @@
     props.setLeftTopRightBottom(0, 0, maxTextureSize + 1, maxTextureSize + 1);
     ASSERT_FALSE(props.fitsOnLayer());
 
-    // Too small - can't have 0 dimen layer
+    // Too small, but still 'fits'. Not fitting is an error case, so don't report empty as such.
     props.setLeftTopRightBottom(0, 0, 100, 0);
-    ASSERT_FALSE(props.fitsOnLayer());
+    ASSERT_TRUE(props.fitsOnLayer());
 }
diff --git a/packages/PrintSpooler/src/com/android/printspooler/ui/PrintActivity.java b/packages/PrintSpooler/src/com/android/printspooler/ui/PrintActivity.java
index 2c4025d..3e262d0 100644
--- a/packages/PrintSpooler/src/com/android/printspooler/ui/PrintActivity.java
+++ b/packages/PrintSpooler/src/com/android/printspooler/ui/PrintActivity.java
@@ -526,6 +526,14 @@
                     .setContentType(info.getContentType())
                     .setPageCount(pageCount)
                     .build();
+
+            File file = mFileProvider.acquireFile(null);
+            try {
+                adjustedInfo.setDataSize(file.length());
+            } finally {
+                mFileProvider.releaseFile();
+            }
+
             mPrintJob.setDocumentInfo(adjustedInfo);
             mPrintJob.setPages(document.printedPages);
         }
@@ -3077,6 +3085,14 @@
                     .setContentType(oldDocInfo.getContentType())
                     .setPageCount(newPageCount)
                     .build();
+
+            File file = mFileProvider.acquireFile(null);
+            try {
+                newDocInfo.setDataSize(file.length());
+            } finally {
+                mFileProvider.releaseFile();
+            }
+
             mPrintJob.setDocumentInfo(newDocInfo);
         }
 
diff --git a/services/backup/java/com/android/server/backup/BackupManagerService.java b/services/backup/java/com/android/server/backup/BackupManagerService.java
index e6f99c1..0b85198 100644
--- a/services/backup/java/com/android/server/backup/BackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/BackupManagerService.java
@@ -234,6 +234,7 @@
     private static final int MSG_WIDGET_BROADCAST = 13;
     private static final int MSG_RUN_FULL_TRANSPORT_BACKUP = 14;
     private static final int MSG_REQUEST_BACKUP = 15;
+    private static final int MSG_SCHEDULE_BACKUP_PACKAGE = 16;
 
     // backup task state machine tick
     static final int MSG_BACKUP_RESTORE_STEP = 20;
@@ -1037,6 +1038,16 @@
                 sendMessage(pbtMessage);
                 break;
             }
+
+            case MSG_SCHEDULE_BACKUP_PACKAGE:
+            {
+                String pkgName = (String)msg.obj;
+                if (MORE_DEBUG) {
+                    Slog.d(TAG, "MSG_SCHEDULE_BACKUP_PACKAGE " + pkgName);
+                }
+                dataChangedImpl(pkgName);
+                break;
+            }
             }
         }
     }
@@ -1216,7 +1227,7 @@
 
         // Now that we know about valid backup participants, parse any
         // leftover journal files into the pending backup set
-        parseLeftoverJournals();
+        mBackupHandler.post(() -> parseLeftoverJournals());
 
         // Power management
         mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
@@ -2161,7 +2172,7 @@
                 int uid = pkg.applicationInfo.uid;
                 HashSet<String> set = mBackupParticipants.get(uid);
                 if (set == null) {
-                    set = new HashSet<String>();
+                    set = new HashSet<>();
                     mBackupParticipants.put(uid, set);
                 }
                 set.add(pkg.packageName);
@@ -2169,7 +2180,9 @@
 
                 // Schedule a backup for it on general principles
                 if (MORE_DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
-                dataChangedImpl(pkg.packageName);
+                Message msg = mBackupHandler
+                        .obtainMessage(MSG_SCHEDULE_BACKUP_PACKAGE, pkg.packageName);
+                mBackupHandler.sendMessage(msg);
             }
         }
     }
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index b12a961..ef41f49 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -303,7 +303,7 @@
 
     /**
      * indicates a timeout period is over - check if we had a network yet or not
-     * and if not, call the timeout calback (but leave the request live until they
+     * and if not, call the timeout callback (but leave the request live until they
      * cancel it.
      * includes a NetworkRequestInfo
      */
@@ -380,6 +380,16 @@
      */
     private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
 
+    /**
+     * Indicates a caller has requested to have its callback invoked with
+     * the latest LinkProperties or NetworkCapabilities.
+     *
+     * arg1 = UID of caller
+     * obj  = NetworkRequest
+     */
+    private static final int EVENT_REQUEST_LINKPROPERTIES  = 32;
+    private static final int EVENT_REQUEST_NETCAPABILITIES = 33;
+
     /** Handler thread used for both of the handlers below. */
     @VisibleForTesting
     protected final HandlerThread mHandlerThread;
@@ -439,6 +449,11 @@
     private static final int MAX_NETWORK_REQUEST_LOGS = 20;
     private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
 
+    // NetworkInfo blocked and unblocked String log entries
+    // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
+    private static final int MAX_NETWORK_INFO_LOGS = 100;
+    private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
+
     // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
     private static final int MAX_VALIDATION_LOGS = 10;
     private static class ValidationLog {
@@ -1003,7 +1018,9 @@
     }
 
     private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
-        if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
+        if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
+            return;
+        }
         boolean removed = false;
         boolean added = false;
         synchronized (mBlockedAppUids) {
@@ -1013,8 +1030,13 @@
                 removed = true;
             }
         }
-        if (added) log("Returning blocked NetworkInfo to uid=" + uid);
-        else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
+        if (added) {
+            log("Returning blocked NetworkInfo to uid=" + uid);
+            mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
+        } else if (removed) {
+            log("Returning unblocked NetworkInfo to uid=" + uid);
+            mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
+        }
     }
 
     /**
@@ -2014,6 +2036,12 @@
             pw.increaseIndent();
             mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
             pw.decreaseIndent();
+
+            pw.println();
+            pw.println("mNetworkInfoBlockingLogs (most recent first):");
+            pw.increaseIndent();
+            mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
+            pw.decreaseIndent();
         }
     }
 
@@ -2447,106 +2475,146 @@
         return true;
     }
 
-    private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
-        NetworkRequestInfo nri = mNetworkRequests.get(request);
+    private NetworkRequestInfo getNriForAppRequest(
+            NetworkRequest request, int callingUid, String requestedOperation) {
+        final NetworkRequestInfo nri = mNetworkRequests.get(request);
+
         if (nri != null) {
             if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
-                if (DBG) log("Attempt to release unowned NetworkRequest " + request);
-                return;
+                log(String.format("UID %d attempted to %s for unowned request %s",
+                        callingUid, requestedOperation, nri));
+                return null;
             }
-            if (VDBG || (DBG && nri.request.isRequest())) log("releasing " + request);
-            nri.unlinkDeathRecipient();
-            mNetworkRequests.remove(request);
-            synchronized (mUidToNetworkRequestCount) {
-                int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
-                if (requests < 1) {
-                    Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
-                            nri.mUid);
-                } else if (requests == 1) {
-                    mUidToNetworkRequestCount.removeAt(
-                            mUidToNetworkRequestCount.indexOfKey(nri.mUid));
+        }
+
+        return nri;
+    }
+
+    private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
+            String description, int callbackType) {
+        final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
+        if (nri == null) return;
+
+        final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
+        // The network that is satisfying this request may have changed since
+        // the application requested the update.
+        //
+        // - If the request is no longer satisfied, don't send any updates.
+        // - If the request is satisfied by a different network, it is the
+        //   caller's responsibility to check that the Network object in the
+        //   callback matches the network that was returned in the last
+        //   onAvailable() callback for this request.
+        if (nai == null) return;
+        callCallbackForRequest(nri, nai, callbackType, 0);
+    }
+
+    private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
+        handleRequestCallbackUpdate(request, callingUid,
+                "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
+    }
+
+    private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
+        handleRequestCallbackUpdate(request, callingUid,
+                "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
+    }
+
+    private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
+        final NetworkRequestInfo nri = getNriForAppRequest(
+                request, callingUid, "release NetworkRequest");
+        if (nri == null) return;
+
+        if (VDBG || (DBG && nri.request.isRequest())) log("releasing " + request);
+        nri.unlinkDeathRecipient();
+        mNetworkRequests.remove(request);
+        synchronized (mUidToNetworkRequestCount) {
+            int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
+            if (requests < 1) {
+                Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
+                        nri.mUid);
+            } else if (requests == 1) {
+                mUidToNetworkRequestCount.removeAt(
+                        mUidToNetworkRequestCount.indexOfKey(nri.mUid));
+            } else {
+                mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
+            }
+        }
+        mNetworkRequestInfoLogs.log("RELEASE " + nri);
+        if (nri.request.isRequest()) {
+            boolean wasKept = false;
+            NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
+            if (nai != null) {
+                nai.removeRequest(nri.request.requestId);
+                if (VDBG) {
+                    log(" Removing from current network " + nai.name() +
+                            ", leaving " + nai.numNetworkRequests() + " requests.");
+                }
+                // If there are still lingered requests on this network, don't tear it down,
+                // but resume lingering instead.
+                updateLingerState(nai, SystemClock.elapsedRealtime());
+                if (unneeded(nai)) {
+                    if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
+                    teardownUnneededNetwork(nai);
                 } else {
-                    mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
+                    wasKept = true;
+                }
+                mNetworkForRequestId.remove(nri.request.requestId);
+            }
+
+            // TODO: remove this code once we know that the Slog.wtf is never hit.
+            //
+            // Find all networks that are satisfying this request and remove the request
+            // from their request lists.
+            // TODO - it's my understanding that for a request there is only a single
+            // network satisfying it, so this loop is wasteful
+            for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
+                if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
+                    Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
+                            otherNai.name() + ", but mNetworkAgentInfos says " +
+                            (nai != null ? nai.name() : "null"));
                 }
             }
-            mNetworkRequestInfoLogs.log("RELEASE " + nri);
-            if (nri.request.isRequest()) {
-                boolean wasKept = false;
-                NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
-                if (nai != null) {
-                    nai.removeRequest(nri.request.requestId);
-                    if (VDBG) {
-                        log(" Removing from current network " + nai.name() +
-                                ", leaving " + nai.numNetworkRequests() + " requests.");
-                    }
-                    // If there are still lingered requests on this network, don't tear it down,
-                    // but resume lingering instead.
-                    updateLingerState(nai, SystemClock.elapsedRealtime());
-                    if (unneeded(nai)) {
-                        if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
-                        teardownUnneededNetwork(nai);
-                    } else {
-                        wasKept = true;
-                    }
-                    mNetworkForRequestId.remove(nri.request.requestId);
-                }
 
-                // TODO: remove this code once we know that the Slog.wtf is never hit.
-                //
-                // Find all networks that are satisfying this request and remove the request
-                // from their request lists.
-                // TODO - it's my understanding that for a request there is only a single
-                // network satisfying it, so this loop is wasteful
-                for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
-                    if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
-                        Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
-                                otherNai.name() + ", but mNetworkAgentInfos says " +
-                                (nai != null ? nai.name() : "null"));
-                    }
-                }
-
-                // Maintain the illusion.  When this request arrived, we might have pretended
-                // that a network connected to serve it, even though the network was already
-                // connected.  Now that this request has gone away, we might have to pretend
-                // that the network disconnected.  LegacyTypeTracker will generate that
-                // phantom disconnect for this type.
-                if (nri.request.legacyType != TYPE_NONE && nai != null) {
-                    boolean doRemove = true;
-                    if (wasKept) {
-                        // check if any of the remaining requests for this network are for the
-                        // same legacy type - if so, don't remove the nai
-                        for (int i = 0; i < nai.numNetworkRequests(); i++) {
-                            NetworkRequest otherRequest = nai.requestAt(i);
-                            if (otherRequest.legacyType == nri.request.legacyType &&
-                                    otherRequest.isRequest()) {
-                                if (DBG) log(" still have other legacy request - leaving");
-                                doRemove = false;
-                            }
+            // Maintain the illusion.  When this request arrived, we might have pretended
+            // that a network connected to serve it, even though the network was already
+            // connected.  Now that this request has gone away, we might have to pretend
+            // that the network disconnected.  LegacyTypeTracker will generate that
+            // phantom disconnect for this type.
+            if (nri.request.legacyType != TYPE_NONE && nai != null) {
+                boolean doRemove = true;
+                if (wasKept) {
+                    // check if any of the remaining requests for this network are for the
+                    // same legacy type - if so, don't remove the nai
+                    for (int i = 0; i < nai.numNetworkRequests(); i++) {
+                        NetworkRequest otherRequest = nai.requestAt(i);
+                        if (otherRequest.legacyType == nri.request.legacyType &&
+                                otherRequest.isRequest()) {
+                            if (DBG) log(" still have other legacy request - leaving");
+                            doRemove = false;
                         }
                     }
-
-                    if (doRemove) {
-                        mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
-                    }
                 }
 
-                for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
-                    nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
-                            nri.request);
-                }
-            } else {
-                // listens don't have a singular affectedNetwork.  Check all networks to see
-                // if this listen request applies and remove it.
-                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
-                    nai.removeRequest(nri.request.requestId);
-                    if (nri.request.networkCapabilities.hasSignalStrength() &&
-                            nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
-                        updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
-                    }
+                if (doRemove) {
+                    mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
                 }
             }
-            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED, 0);
+
+            for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
+                nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
+                        nri.request);
+            }
+        } else {
+            // listens don't have a singular affectedNetwork.  Check all networks to see
+            // if this listen request applies and remove it.
+            for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
+                nai.removeRequest(nri.request.requestId);
+                if (nri.request.networkCapabilities.hasSignalStrength() &&
+                        nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
+                    updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
+                }
+            }
         }
+        callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED, 0);
     }
 
     @Override
@@ -2709,6 +2777,12 @@
                     handleMobileDataAlwaysOn();
                     break;
                 }
+                case EVENT_REQUEST_LINKPROPERTIES:
+                    handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
+                    break;
+                case EVENT_REQUEST_NETCAPABILITIES:
+                    handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
+                    break;
                 // Sent by KeepaliveTracker to process an app request on the state machine thread.
                 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
                     mKeepaliveTracker.handleStartKeepalive(msg);
@@ -4170,10 +4244,26 @@
     }
 
     @Override
+    public void requestLinkProperties(NetworkRequest networkRequest) {
+        ensureNetworkRequestHasType(networkRequest);
+        if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
+        mHandler.sendMessage(mHandler.obtainMessage(
+                EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
+    }
+
+    @Override
+    public void requestNetworkCapabilities(NetworkRequest networkRequest) {
+        ensureNetworkRequestHasType(networkRequest);
+        if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
+        mHandler.sendMessage(mHandler.obtainMessage(
+                EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
+    }
+
+    @Override
     public void releaseNetworkRequest(NetworkRequest networkRequest) {
         ensureNetworkRequestHasType(networkRequest);
-        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
-                0, networkRequest));
+        mHandler.sendMessage(mHandler.obtainMessage(
+                EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
     }
 
     @Override
diff --git a/services/core/java/com/android/server/UiThread.java b/services/core/java/com/android/server/UiThread.java
index c06afc2..1bc6250 100644
--- a/services/core/java/com/android/server/UiThread.java
+++ b/services/core/java/com/android/server/UiThread.java
@@ -17,6 +17,7 @@
 package com.android.server;
 
 import android.os.Handler;
+import android.os.Process;
 import android.os.Trace;
 
 /**
@@ -29,7 +30,9 @@
     private static Handler sHandler;
 
     private UiThread() {
-        super("android.ui", android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
+        super("android.ui", Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
+        // Make sure UiThread is in the fg stune boost group
+        Process.setThreadGroup(Process.myTid(), Process.THREAD_GROUP_TOP_APP);
     }
 
     private static void ensureThreadLocked() {
diff --git a/services/core/java/com/android/server/connectivity/Tethering.java b/services/core/java/com/android/server/connectivity/Tethering.java
index bef48d6..6f67b6f 100644
--- a/services/core/java/com/android/server/connectivity/Tethering.java
+++ b/services/core/java/com/android/server/connectivity/Tethering.java
@@ -270,14 +270,16 @@
                     trackNewTetherableInterface(iface, interfaceType);
                 }
             } else {
-                if (interfaceType == ConnectivityManager.TETHERING_USB) {
-                    // ignore usb0 down after enabling RNDIS
-                    // we will handle disconnect in interfaceRemoved instead
-                    if (VDBG) Log.d(TAG, "ignore interface down for " + iface);
-                } else if (tetherState != null) {
+                if (interfaceType == ConnectivityManager.TETHERING_BLUETOOTH) {
                     tetherState.mStateMachine.sendMessage(
                             TetherInterfaceStateMachine.CMD_INTERFACE_DOWN);
                     mTetherStates.remove(iface);
+                } else {
+                    // Ignore usb0 down after enabling RNDIS.
+                    // We will handle disconnect in interfaceRemoved.
+                    // Similarly, ignore interface down for WiFi.  We monitor WiFi AP status
+                    // through the WifiManager.WIFI_AP_STATE_CHANGED_ACTION intent.
+                    if (VDBG) Log.d(TAG, "ignore interface down for " + iface);
                 }
             }
         }
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 84ebdd1..455e1fa 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -159,6 +159,7 @@
 import android.content.pm.ProviderInfo;
 import android.content.pm.ResolveInfo;
 import android.content.pm.ServiceInfo;
+import android.content.pm.ShortcutServiceInternal;
 import android.content.pm.Signature;
 import android.content.pm.UserInfo;
 import android.content.pm.VerifierDeviceIdentity;
@@ -7267,22 +7268,17 @@
         try {
             IMountService ms = PackageHelper.getMountService();
             if (ms != null) {
-                final boolean isUpgrade = isUpgrade();
-                boolean doTrim = isUpgrade;
-                if (doTrim) {
-                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
-                } else {
-                    final long interval = android.provider.Settings.Global.getLong(
-                            mContext.getContentResolver(),
-                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
-                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
-                    if (interval > 0) {
-                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
-                        if (timeSinceLast > interval) {
-                            doTrim = true;
-                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
-                                    + "; running immediately");
-                        }
+                boolean doTrim = false;
+                final long interval = android.provider.Settings.Global.getLong(
+                        mContext.getContentResolver(),
+                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
+                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
+                if (interval > 0) {
+                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
+                    if (timeSinceLast > interval) {
+                        doTrim = true;
+                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
+                                + "; running immediately");
                     }
                 }
                 if (doTrim) {
@@ -11443,6 +11439,9 @@
                     } else {
                         resolvedUserIds = userIds;
                     }
+                    final ShortcutServiceInternal shortcutService =
+                            LocalServices.getService(ShortcutServiceInternal.class);
+
                     for (int id : resolvedUserIds) {
                         final Intent intent = new Intent(action,
                                 pkg != null ? Uri.fromParts("package", pkg, null) : null);
@@ -11467,6 +11466,10 @@
                                     + intent.toShortString(false, true, false, false)
                                     + " " + intent.getExtras(), here);
                         }
+                        // TODO b/29385425 Consider making lifecycle callbacks for this.
+                        if (shortcutService != null) {
+                            shortcutService.onPackageBroadcast(intent);
+                        }
                         am.broadcastIntent(null, intent, null, finishedReceiver,
                                 0, null, null, null, android.app.AppOpsManager.OP_NONE,
                                 null, finishedReceiver != null, false, id);
diff --git a/services/core/java/com/android/server/pm/ShortcutPendingTasks.java b/services/core/java/com/android/server/pm/ShortcutPendingTasks.java
new file mode 100644
index 0000000..a5ace56
--- /dev/null
+++ b/services/core/java/com/android/server/pm/ShortcutPendingTasks.java
@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 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.
+ */
+package com.android.server.pm;
+
+import android.annotation.NonNull;
+import android.util.Slog;
+
+import java.io.PrintWriter;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BooleanSupplier;
+import java.util.function.Consumer;
+import java.util.logging.Handler;
+
+/**
+ * Used by {@link ShortcutService} to register tasks to be executed on Handler and also wait for
+ * all pending tasks.
+ *
+ * Tasks can be registered with {@link #addTask(Runnable)}.  Call {@link #waitOnAllTasks()} to wait
+ * on all tasks that have been registered.
+ *
+ * In order to avoid deadlocks, {@link #waitOnAllTasks} MUST NOT be called with any lock held, nor
+ * on the handler thread.  These conditions are checked by {@link #mWaitThreadChecker} and wtf'ed.
+ *
+ * During unit tests, we can't run tasks asynchronously, so we just run Runnables synchronously,
+ * which also means the "is lock held" check doesn't work properly during unit tests (e.g. normally
+ * when a Runnable is executed on a Handler, the thread doesn't hold any lock, but during the tests
+ * we just run a Runnable on the thread that registers it, so the thread may or may not hold locks.)
+ * So unfortunately we have to disable {@link #mWaitThreadChecker} during unit tests.
+ *
+ * Because of the complications like those, this class should be used only for specific purposes:
+ * - {@link #addTask(Runnable)} should only be used to register tasks on callbacks from lower level
+ * services like the package manager or the activity manager.
+ *
+ * - {@link #waitOnAllTasks} should only be called at the entry point of RPC calls (or the test only
+ * accessors}.
+ */
+public class ShortcutPendingTasks {
+    private static final String TAG = "ShortcutPendingTasks";
+
+    private static final boolean DEBUG = false || ShortcutService.DEBUG; // DO NOT SUBMIT WITH TRUE.
+
+    private final Consumer<Runnable> mRunner;
+
+    private final BooleanSupplier mWaitThreadChecker;
+
+    private final Consumer<Throwable> mExceptionHandler;
+
+    /** # of tasks in the queue, including the running one. */
+    private final AtomicInteger mRunningTaskCount = new AtomicInteger();
+
+    /** For dumpsys */
+    private final AtomicLong mLastTaskStartTime = new AtomicLong();
+
+    /**
+     * Constructor.  In order to allow injection during unit tests, it doesn't take a
+     * {@link Handler} directly, and instead takes {@code runner} which will post an argument
+     * to a handler.
+     */
+    public ShortcutPendingTasks(Consumer<Runnable> runner, BooleanSupplier waitThreadChecker,
+            Consumer<Throwable> exceptionHandler) {
+        mRunner = runner;
+        mWaitThreadChecker = waitThreadChecker;
+        mExceptionHandler = exceptionHandler;
+    }
+
+    private static void dlog(String message) {
+        if (DEBUG) {
+            Slog.d(TAG, message);
+        }
+    }
+
+    /**
+     * Block until all tasks that are already queued finish.  DO NOT call it while holding any lock
+     * or on the handler thread.
+     */
+    public boolean waitOnAllTasks() {
+        dlog("waitOnAllTasks: enter");
+        try {
+            // Make sure it's not holding the lock.
+            if (!mWaitThreadChecker.getAsBoolean()) {
+                return false;
+            }
+
+            // Optimize for the no-task case.
+            if (mRunningTaskCount.get() == 0) {
+                return true;
+            }
+
+            final CountDownLatch latch = new CountDownLatch(1);
+
+            addTask(latch::countDown);
+
+            for (; ; ) {
+                try {
+                    if (latch.await(1, TimeUnit.SECONDS)) {
+                        return true;
+                    }
+                    dlog("waitOnAllTasks: Task(s) still running...");
+                } catch (InterruptedException ignore) {
+                }
+            }
+        } finally {
+            dlog("waitOnAllTasks: exit");
+        }
+    }
+
+    /**
+     * Add a new task.  This operation is lock-free.
+     */
+    public void addTask(Runnable task) {
+        mRunningTaskCount.incrementAndGet();
+        mLastTaskStartTime.set(System.currentTimeMillis());
+
+        dlog("Task registered");
+
+        mRunner.accept(() -> {
+            try {
+                dlog("Task started");
+
+                task.run();
+            } catch (Throwable th) {
+                mExceptionHandler.accept(th);
+            } finally {
+                dlog("Task finished");
+                mRunningTaskCount.decrementAndGet();
+            }
+        });
+    }
+
+    public void dump(@NonNull PrintWriter pw, @NonNull String prefix) {
+        pw.print(prefix);
+        pw.print("Pending tasks:  # running tasks: ");
+        pw.println(mRunningTaskCount.get());
+
+        pw.print(prefix);
+        pw.print("  Last task started time: ");
+        final long lastStarted = mLastTaskStartTime.get();
+        pw.print(" [");
+        pw.print(lastStarted);
+        pw.print("] ");
+        pw.println(ShortcutService.formatTime(lastStarted));
+    }
+}
diff --git a/services/core/java/com/android/server/pm/ShortcutService.java b/services/core/java/com/android/server/pm/ShortcutService.java
index c6949e4..dda9a5d 100644
--- a/services/core/java/com/android/server/pm/ShortcutService.java
+++ b/services/core/java/com/android/server/pm/ShortcutService.java
@@ -49,6 +49,7 @@
 import android.graphics.Canvas;
 import android.graphics.RectF;
 import android.graphics.drawable.Icon;
+import android.net.Uri;
 import android.os.Binder;
 import android.os.Environment;
 import android.os.FileUtils;
@@ -81,7 +82,6 @@
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.content.PackageMonitor;
 import com.android.internal.os.BackgroundThread;
 import com.android.internal.util.FastXmlSerializer;
 import com.android.internal.util.Preconditions;
@@ -122,9 +122,6 @@
 
 /**
  * TODO:
- * - Deal with the async nature of PACKAGE_ADD.  Basically when a publisher does anything after
- *   it's upgraded, the manager should make sure the upgrade process has been executed.
- *
  * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
  *   -> But TypedValue.applyDimension() doesn't differentiate x and y..?
  *
@@ -304,6 +301,8 @@
 
     private final AtomicBoolean mBootCompleted = new AtomicBoolean();
 
+    private final ShortcutPendingTasks mPendingTasks;
+
     private static final int PACKAGE_MATCH_FLAGS =
             PackageManager.MATCH_DIRECT_BOOT_AWARE
                     | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
@@ -355,6 +354,12 @@
     @interface ShortcutOperation {
     }
 
+    @GuardedBy("mLock")
+    private int mWtfCount = 0;
+
+    @GuardedBy("mLock")
+    private Exception mLastWtfStacktrace;
+
     public ShortcutService(Context context) {
         this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
     }
@@ -371,16 +376,41 @@
         mUsageStatsManagerInternal = Preconditions.checkNotNull(
                 LocalServices.getService(UsageStatsManagerInternal.class));
 
+        mPendingTasks = new ShortcutPendingTasks(
+                this::injectPostToHandler,
+                this::injectCheckPendingTaskWaitThread,
+                throwable -> wtf(throwable.getMessage(), throwable));
+
         if (onlyForPackageManagerApis) {
             return; // Don't do anything further.  For unit tests only.
         }
 
-        mPackageMonitor.register(context, looper, UserHandle.ALL, /* externalStorage= */ false);
-
         injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
                 | ActivityManager.UID_OBSERVER_GONE);
     }
 
+    /**
+     * Check whether {@link ShortcutPendingTasks#waitOnAllTasks()} can be called on the current
+     * thread.
+     *
+     * During unit tests, all tasks are executed synchronously which makes the lock held check would
+     * misfire, so we override this method to always return true.
+     */
+    @VisibleForTesting
+    boolean injectCheckPendingTaskWaitThread() {
+        // We shouldn't wait while holding mLock.  We should never do this so wtf().
+        if (Thread.holdsLock(mLock)) {
+            wtf("waitOnAllTasks() called while holding the lock");
+            return false;
+        }
+        // This shouldn't be called on the handler thread either.
+        if (Thread.currentThread() == mHandler.getLooper().getThread()) {
+            wtf("waitOnAllTasks() called on handler thread");
+            return false;
+        }
+        return true;
+    }
+
     void logDurationStat(int statId, long start) {
         synchronized (mStatLock) {
             mCountStats[statId]++;
@@ -1486,6 +1516,8 @@
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
 
+        mPendingTasks.waitOnAllTasks();
+
         final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
         final int size = newShortcuts.size();
 
@@ -1535,6 +1567,8 @@
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
 
+        mPendingTasks.waitOnAllTasks();
+
         final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
         final int size = newShortcuts.size();
 
@@ -1613,6 +1647,8 @@
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
 
+        mPendingTasks.waitOnAllTasks();
+
         final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
         final int size = newShortcuts.size();
 
@@ -1663,6 +1699,8 @@
         verifyCaller(packageName, userId);
         Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
 
+        mPendingTasks.waitOnAllTasks();
+
         synchronized (mLock) {
             final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
 
@@ -1690,6 +1728,8 @@
         verifyCaller(packageName, userId);
         Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
 
+        mPendingTasks.waitOnAllTasks();
+
         synchronized (mLock) {
             final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
 
@@ -1710,6 +1750,8 @@
         verifyCaller(packageName, userId);
         Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
 
+        mPendingTasks.waitOnAllTasks();
+
         synchronized (mLock) {
             final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
 
@@ -1732,6 +1774,8 @@
     public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
         verifyCaller(packageName, userId);
 
+        mPendingTasks.waitOnAllTasks();
+
         synchronized (mLock) {
             getPackageShortcutsLocked(packageName, userId).deleteAllDynamicShortcuts();
         }
@@ -1744,6 +1788,9 @@
     public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
+
+        mPendingTasks.waitOnAllTasks();
+
         synchronized (mLock) {
             return getShortcutsWithQueryLocked(
                     packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
@@ -1755,6 +1802,9 @@
     public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
+
+        mPendingTasks.waitOnAllTasks();
+
         synchronized (mLock) {
             return getShortcutsWithQueryLocked(
                     packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
@@ -1766,6 +1816,9 @@
     public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
+
+        mPendingTasks.waitOnAllTasks();
+
         synchronized (mLock) {
             return getShortcutsWithQueryLocked(
                     packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
@@ -1795,6 +1848,8 @@
     public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
         verifyCaller(packageName, userId);
 
+        mPendingTasks.waitOnAllTasks();
+
         synchronized (mLock) {
             return mMaxUpdatesPerInterval
                     - getPackageShortcutsLocked(packageName, userId).getApiCallCount();
@@ -1805,6 +1860,8 @@
     public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
         verifyCaller(packageName, userId);
 
+        mPendingTasks.waitOnAllTasks();
+
         synchronized (mLock) {
             return getNextResetTimeLocked();
         }
@@ -1823,6 +1880,8 @@
     public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
         verifyCaller(packageName, userId);
 
+        mPendingTasks.waitOnAllTasks();
+
         Preconditions.checkNotNull(shortcutId);
 
         if (DEBUG) {
@@ -1855,6 +1914,8 @@
     public void resetThrottling() {
         enforceSystemOrShell();
 
+        mPendingTasks.waitOnAllTasks();
+
         resetThrottlingInner(getCallingUserId());
     }
 
@@ -1887,6 +1948,9 @@
         if (DEBUG) {
             Slog.d(TAG, "onApplicationActive: package=" + packageName + "  userid=" + userId);
         }
+
+        mPendingTasks.waitOnAllTasks();
+
         enforceResetThrottlingPermission();
         resetPackageThrottling(packageName, userId);
     }
@@ -2049,6 +2113,14 @@
                 @Nullable String packageName, @Nullable List<String> shortcutIds,
                 @Nullable ComponentName componentName,
                 int queryFlags, int userId) {
+
+            // When this method is called from onShortcutChangedInner() in LauncherApps,
+            // we're on the handler thread.  Do not try to wait on tasks.  Not waiting for pending
+            // tasks on this specific case should be fine.
+            if (Thread.currentThread() != mHandler.getLooper().getThread()) {
+                mPendingTasks.waitOnAllTasks();
+            }
+
             final ArrayList<ShortcutInfo> ret = new ArrayList<>();
             final boolean cloneKeyFieldOnly =
                     ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
@@ -2127,6 +2199,8 @@
             Preconditions.checkStringNotEmpty(packageName, "packageName");
             Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
 
+            mPendingTasks.waitOnAllTasks();
+
             synchronized (mLock) {
                 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
                         .attemptToRestoreIfNeededAndSave();
@@ -2164,6 +2238,8 @@
             Preconditions.checkStringNotEmpty(packageName, "packageName");
             Preconditions.checkNotNull(shortcutIds, "shortcutIds");
 
+            mPendingTasks.waitOnAllTasks();
+
             synchronized (mLock) {
                 final ShortcutLauncher launcher =
                         getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
@@ -2184,6 +2260,8 @@
             Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
             Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
 
+            mPendingTasks.waitOnAllTasks();
+
             synchronized (mLock) {
                 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
                         .attemptToRestoreIfNeededAndSave();
@@ -2213,6 +2291,8 @@
             Preconditions.checkNotNull(packageName, "packageName");
             Preconditions.checkNotNull(shortcutId, "shortcutId");
 
+            mPendingTasks.waitOnAllTasks();
+
             synchronized (mLock) {
                 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
                         .attemptToRestoreIfNeededAndSave();
@@ -2237,6 +2317,8 @@
             Preconditions.checkNotNull(packageName, "packageName");
             Preconditions.checkNotNull(shortcutId, "shortcutId");
 
+            mPendingTasks.waitOnAllTasks();
+
             synchronized (mLock) {
                 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
                         .attemptToRestoreIfNeededAndSave();
@@ -2297,9 +2379,18 @@
                 if (DEBUG) {
                     Slog.d(TAG, "onSystemLocaleChangedNoLock: " + mLocaleChangeSequenceNumber.get());
                 }
-                injectPostToHandler(() -> handleLocaleChanged());
+                mPendingTasks.addTask(() -> handleLocaleChanged());
             }
         }
+
+        @Override
+        public void onPackageBroadcast(Intent intent) {
+            if (DEBUG) {
+                Slog.d(TAG, "onPackageBroadcast");
+            }
+            mPendingTasks.addTask(() -> ShortcutService.this.onPackageBroadcast(
+                    new Intent(intent)));
+        }
     }
 
     void handleLocaleChanged() {
@@ -2316,37 +2407,49 @@
         }
     }
 
-    /**
-     * Package event callbacks.
-     */
-    @VisibleForTesting
-    final PackageMonitor mPackageMonitor = new PackageMonitor() {
-        @Override
-        public void onPackageAdded(String packageName, int uid) {
-            handlePackageAdded(packageName, getChangingUserId());
+    private void onPackageBroadcast(Intent intent) {
+        final int userId  = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
+        if (userId == UserHandle.USER_NULL) {
+            Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
+            return;
         }
 
-        @Override
-        public void onPackageUpdateFinished(String packageName, int uid) {
-            handlePackageUpdateFinished(packageName, getChangingUserId());
+        final String action = intent.getAction();
+
+        if (!mUserManager.isUserUnlocked(userId)) {
+            if (DEBUG) {
+                Slog.d(TAG, "Ignoring package broadcast " + action + " for locked/stopped user "
+                        + userId);
+            }
+            return;
         }
 
-        @Override
-        public void onPackageRemoved(String packageName, int uid) {
-            handlePackageRemoved(packageName, getChangingUserId());
+        final Uri intentUri = intent.getData();
+        final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart() : null;
+        if (packageName == null) {
+            Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
+            return;
         }
 
-        @Override
-        public void onPackageDataCleared(String packageName, int uid) {
-            handlePackageDataCleared(packageName, getChangingUserId());
-        }
+        final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
 
-        @Override
-        public boolean onPackageChanged(String packageName, int uid, String[] components) {
-            handlePackageChanged(packageName, getChangingUserId());
-            return false; // We don't need to receive onSomePackagesChanged(), so just false.
+        if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
+            if (replacing) {
+                handlePackageUpdateFinished(packageName, userId);
+            } else {
+                handlePackageAdded(packageName, userId);
+            }
+        } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
+            if (!replacing) {
+                handlePackageRemoved(packageName, userId);
+            }
+        } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
+            handlePackageChanged(packageName, userId);
+
+        } else if (Intent.ACTION_PACKAGE_DATA_CLEARED.equals(action)) {
+            handlePackageDataCleared(packageName, userId);
         }
-    };
+    }
 
     /**
      * Called when a user is unlocked.
@@ -2984,6 +3087,18 @@
                 dumpStatLS(pw, p, Stats.IS_ACTIVITY_ENABLED, "isActivityEnabled");
             }
 
+            pw.println();
+            pw.print("  #Failures: ");
+            pw.println(mWtfCount);
+
+            if (mLastWtfStacktrace != null) {
+                pw.print("  Last failure stack trace: ");
+                pw.println(Log.getStackTraceString(mLastWtfStacktrace));
+            }
+
+            pw.println();
+            mPendingTasks.dump(pw, "  ");
+
             for (int i = 0; i < mUsers.size(); i++) {
                 pw.println();
                 mUsers.valueAt(i).dump(pw, "  ");
@@ -3032,6 +3147,8 @@
 
         enforceShell();
 
+        mPendingTasks.waitOnAllTasks();
+
         final int status = (new MyShellCommand()).exec(this, in, out, err, args, resultReceiver);
 
         resultReceiver.send(status, null);
@@ -3303,7 +3420,14 @@
     }
 
     // Injection point.
-    void wtf(String message, Exception e) {
+    void wtf(String message, Throwable e) {
+        if (e == null) {
+            e = new RuntimeException("Stacktrace");
+        }
+        synchronized (mLock) {
+            mWtfCount++;
+            mLastWtfStacktrace = new Exception("Last failure was logged here:");
+        }
         Slog.wtf(TAG, message, e);
     }
 
@@ -3376,6 +3500,7 @@
 
     @VisibleForTesting
     ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
+        mPendingTasks.waitOnAllTasks();
         synchronized (mLock) {
             final ShortcutUser user = mUsers.get(userId);
             if (user == null) return null;
@@ -3386,8 +3511,12 @@
 
     @VisibleForTesting
     ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
+        mPendingTasks.waitOnAllTasks();
         synchronized (mLock) {
-            final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
+            final ShortcutUser user = mUsers.get(userId);
+            if (user == null) return null;
+
+            final ShortcutPackage pkg = user.getAllPackagesForTest().get(packageName);
             if (pkg == null) return null;
 
             return pkg.findShortcutById(shortcutId);
@@ -3422,4 +3551,12 @@
             forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
         }
     }
+
+    ShortcutPendingTasks getPendingTasksForTest() {
+        return mPendingTasks;
+    }
+
+    Object getLockForTest() {
+        return mLock;
+    }
 }
diff --git a/services/core/java/com/android/server/wm/DockedStackDividerController.java b/services/core/java/com/android/server/wm/DockedStackDividerController.java
index e73649d..f93e2ff 100644
--- a/services/core/java/com/android/server/wm/DockedStackDividerController.java
+++ b/services/core/java/com/android/server/wm/DockedStackDividerController.java
@@ -388,8 +388,8 @@
                 inputMethodManagerInternal.hideCurrentInputMethod();
                 mImeHideRequested = true;
             }
-        } else {
-            setMinimizedDockedStack(false);
+        } else if (setMinimizedDockedStack(false)) {
+            mService.mWindowPlacerLocked.performSurfacePlacement();
         }
     }
 
@@ -542,31 +542,43 @@
             return;
         }
 
-        clearImeAdjustAnimation();
+        final boolean imeChanged = clearImeAdjustAnimation();
+        boolean minimizedChange = false;
         if (minimizedDock) {
             if (animate) {
                 startAdjustAnimation(0f, 1f);
             } else {
-                setMinimizedDockedStack(true);
+                minimizedChange |= setMinimizedDockedStack(true);
             }
         } else {
             if (animate) {
                 startAdjustAnimation(1f, 0f);
             } else {
-                setMinimizedDockedStack(false);
+                minimizedChange |= setMinimizedDockedStack(false);
             }
         }
+        if (imeChanged || minimizedChange) {
+            if (imeChanged && !minimizedChange) {
+                Slog.d(TAG, "setMinimizedDockedStack: IME adjust changed due to minimizing,"
+                        + " minimizedDock=" + minimizedDock
+                        + " minimizedChange=" + minimizedChange);
+            }
+            mService.mWindowPlacerLocked.performSurfacePlacement();
+        }
     }
 
-    private void clearImeAdjustAnimation() {
+    private boolean clearImeAdjustAnimation() {
+        boolean changed = false;
         final ArrayList<TaskStack> stacks = mDisplayContent.getStacks();
         for (int i = stacks.size() - 1; i >= 0; --i) {
             final TaskStack stack = stacks.get(i);
             if (stack != null && stack.isAdjustedForIme()) {
                 stack.resetAdjustedForIme(true /* adjustBoundsNow */);
+                changed  = true;
             }
         }
         mAnimatingForIme = false;
+        return changed;
     }
 
     private void startAdjustAnimation(float from, float to) {
@@ -625,8 +637,21 @@
                 if (mDelayedImeWin != null) {
                     mDelayedImeWin.mWinAnimator.endDelayingAnimationStart();
                 }
+                // If the adjust status changed since this was posted, only notify
+                // the new states and don't animate.
+                long duration = 0;
+                if (mAdjustedForIme == adjustedForIme
+                        && mAdjustedForDivider == adjustedForDivider) {
+                    duration = IME_ADJUST_ANIM_DURATION;
+                } else {
+                    Slog.w(TAG, "IME adjust changed while waiting for drawn:"
+                            + " adjustedForIme=" + adjustedForIme
+                            + " adjustedForDivider=" + adjustedForDivider
+                            + " mAdjustedForIme=" + mAdjustedForIme
+                            + " mAdjustedForDivider=" + mAdjustedForDivider);
+                }
                 notifyAdjustedForImeChanged(
-                        adjustedForIme || adjustedForDivider, IME_ADJUST_ANIM_DURATION);
+                        mAdjustedForIme || mAdjustedForDivider, duration);
             };
         } else {
             notifyAdjustedForImeChanged(
@@ -634,15 +659,10 @@
         }
     }
 
-    private void setMinimizedDockedStack(boolean minimized) {
+    private boolean setMinimizedDockedStack(boolean minimized) {
         final TaskStack stack = mDisplayContent.getDockedStackVisibleForUserLocked();
         notifyDockedStackMinimizedChanged(minimized, 0);
-        if (stack == null) {
-            return;
-        }
-        if (stack.setAdjustedForMinimizedDock(minimized ? 1f : 0f)) {
-            mService.mWindowPlacerLocked.performSurfacePlacement();
-        }
+        return stack != null && stack.setAdjustedForMinimizedDock(minimized ? 1f : 0f);
     }
 
     private boolean isAnimationMaximizing() {
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 1002b0d..a839373 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -159,6 +159,8 @@
             "com.google.android.clockwork.ThermalObserver";
     private static final String WEAR_BLUETOOTH_SERVICE_CLASS =
             "com.google.android.clockwork.bluetooth.WearBluetoothService";
+    private static final String WEAR_WIFI_MEDIATOR_SERVICE_CLASS =
+            "com.google.android.clockwork.wifi.WearWifiMediatorService";
     private static final String WEAR_TIME_SERVICE_CLASS =
             "com.google.android.clockwork.time.WearTimeService";
     private static final String ACCOUNT_SERVICE_CLASS =
@@ -1163,6 +1165,7 @@
 
         if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
             mSystemServiceManager.startService(WEAR_BLUETOOTH_SERVICE_CLASS);
+            mSystemServiceManager.startService(WEAR_WIFI_MEDIATOR_SERVICE_CLASS);
           if (!disableNonCoreServices) {
               mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);
           }
diff --git a/services/net/java/android/net/ip/RouterAdvertisementDaemon.java b/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
new file mode 100644
index 0000000..53c2fd7
--- /dev/null
+++ b/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
@@ -0,0 +1,581 @@
+/*
+ * Copyright (C) 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.
+ */
+
+package android.net.ip;
+
+import static android.system.OsConstants.*;
+
+import android.net.IpPrefix;
+import android.net.LinkAddress;
+import android.net.LinkProperties;
+import android.net.NetworkUtils;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.StructGroupReq;
+import android.system.StructTimeval;
+import android.util.Log;
+
+import com.android.internal.annotations.GuardedBy;
+
+import libcore.io.IoUtils;
+import libcore.util.HexEncoding;
+
+import java.io.FileDescriptor;
+import java.io.InterruptedIOException;
+import java.io.IOException;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.SocketException;
+import java.net.UnknownHostException;
+import java.nio.BufferOverflowException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+
+
+/**
+ * Basic IPv6 Router Advertisement Daemon.
+ *
+ * TODO:
+ *
+ *     - Rewrite using Handler (and friends) so that AlarmManager can deliver
+ *       "kick" messages when it's time to send a multicast RA.
+ *
+ *     - Support transmitting MAX_URGENT_RTR_ADVERTISEMENTS number of empty
+ *       RAs with zero default router lifetime when transitioning from an
+ *       advertising state to a non-advertising state.
+ *
+ * @hide
+ */
+public class RouterAdvertisementDaemon {
+    private static final String TAG = RouterAdvertisementDaemon.class.getSimpleName();
+    private static final byte ICMPV6_ND_ROUTER_SOLICIT = asByte(133);
+    private static final byte ICMPV6_ND_ROUTER_ADVERT  = asByte(134);
+    private static final int IPV6_MIN_MTU = 1280;
+    private static final int MIN_RA_HEADER_SIZE = 16;
+
+    // Summary of various timers and lifetimes.
+    private static final int MIN_RTR_ADV_INTERVAL_SEC = 300;
+    private static final int MAX_RTR_ADV_INTERVAL_SEC = 600;
+    // In general, router, prefix, and DNS lifetimes are all advised to be
+    // greater than or equal to 3 * MAX_RTR_ADV_INTERVAL.  Here, we double
+    // that to allow for multicast packet loss.
+    //
+    // This MAX_RTR_ADV_INTERVAL_SEC and DEFAULT_LIFETIME are also consistent
+    // with the https://tools.ietf.org/html/rfc7772#section-4 discussion of
+    // "approximately 7 RAs per hour".
+    private static final int DEFAULT_LIFETIME = 6 * MAX_RTR_ADV_INTERVAL_SEC;
+    // From https://tools.ietf.org/html/rfc4861#section-10 .
+    private static final int MIN_DELAY_BETWEEN_RAS_SEC = 3;
+    // Both initial and final RAs, but also for changes in RA contents.
+    // From https://tools.ietf.org/html/rfc4861#section-10 .
+    private static final int  MAX_URGENT_RTR_ADVERTISEMENTS = 5;
+
+    private static final int DAY_IN_SECONDS = 86_400;
+
+    private static final byte[] ALL_NODES = new byte[] {
+            (byte) 0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
+    };
+
+    private final String mIfName;
+    private final int mIfIndex;
+    private final byte[] mHwAddr;
+    private final InetSocketAddress mAllNodes;
+
+    // This lock is to protect the RA from being updated while being
+    // transmitted on another thread  (multicast or unicast).
+    //
+    // TODO: This should be handled with a more RCU-like approach.
+    private final Object mLock = new Object();
+    @GuardedBy("mLock")
+    private final byte[] mRA = new byte[IPV6_MIN_MTU];
+    @GuardedBy("mLock")
+    private int mRaLength;
+
+    private volatile FileDescriptor mSocket;
+    private volatile MulticastTransmitter mMulticastTransmitter;
+    private volatile UnicastResponder mUnicastResponder;
+
+    public static class RaParams {
+        public boolean hasDefaultRoute;
+        public int mtu;
+        public HashSet<IpPrefix> prefixes;
+        public HashSet<Inet6Address> dnses;
+
+        public RaParams() {
+            hasDefaultRoute = false;
+            mtu = IPV6_MIN_MTU;
+            prefixes = new HashSet<IpPrefix>();
+            dnses = new HashSet<Inet6Address>();
+        }
+
+        public RaParams(RaParams other) {
+            hasDefaultRoute = other.hasDefaultRoute;
+            mtu = other.mtu;
+            prefixes = (HashSet) other.prefixes.clone();
+            dnses = (HashSet) other.dnses.clone();
+        }
+    }
+
+
+    public RouterAdvertisementDaemon(String ifname, int ifindex, byte[] hwaddr) {
+        mIfName = ifname;
+        mIfIndex = ifindex;
+        mHwAddr = hwaddr;
+        mAllNodes = new InetSocketAddress(getAllNodesForScopeId(mIfIndex), 0);
+    }
+
+    public void buildNewRa(RaParams params) {
+        if (params == null || params.prefixes.isEmpty()) {
+            // No RA to be served at this time.
+            clearRa();
+            return;
+        }
+
+        if (params.mtu < IPV6_MIN_MTU) {
+            params.mtu = IPV6_MIN_MTU;
+        }
+
+        final ByteBuffer ra = ByteBuffer.wrap(mRA);
+        ra.order(ByteOrder.BIG_ENDIAN);
+
+        synchronized (mLock) {
+            try {
+                putHeader(ra, params.hasDefaultRoute);
+                putSlla(ra, mHwAddr);
+                // https://tools.ietf.org/html/rfc5175#section-4 says:
+                //
+                //     "MUST NOT be added to a Router Advertisement message
+                //      if no flags in the option are set."
+                //
+                // putExpandedFlagsOption(ra);
+                putMtu(ra, params.mtu);
+                for (IpPrefix ipp : params.prefixes) {
+                    putPio(ra, ipp);
+                }
+                if (params.dnses.size() > 0) {
+                    putRdnss(ra, params.dnses);
+                }
+                mRaLength = ra.position();
+            } catch (BufferOverflowException e) {
+                Log.e(TAG, "Could not construct new RA: " + e);
+                mRaLength = 0;
+                return;
+            }
+        }
+
+        maybeNotifyMulticastTransmitter();
+    }
+
+    public boolean start() {
+        if (!createSocket()) {
+            return false;
+        }
+
+        mMulticastTransmitter = new MulticastTransmitter();
+        mMulticastTransmitter.start();
+
+        mUnicastResponder = new UnicastResponder();
+        mUnicastResponder.start();
+
+        return true;
+    }
+
+    public void stop() {
+        closeSocket();
+        mMulticastTransmitter = null;
+        mUnicastResponder = null;
+    }
+
+    private void clearRa() {
+        boolean notifySocket;
+        synchronized (mLock) {
+            notifySocket = (mRaLength != 0);
+            mRaLength = 0;
+        }
+        if (notifySocket) {
+            maybeNotifyMulticastTransmitter();
+        }
+    }
+
+    private void maybeNotifyMulticastTransmitter() {
+        final MulticastTransmitter m = mMulticastTransmitter;
+        if (m != null) {
+            m.hup();
+        }
+    }
+
+    private static Inet6Address getAllNodesForScopeId(int scopeId) {
+        try {
+            return Inet6Address.getByAddress("ff02::1", ALL_NODES, scopeId);
+        } catch (UnknownHostException uhe) {
+            Log.wtf(TAG, "Failed to construct ff02::1 InetAddress: " + uhe);
+            return null;
+        }
+    }
+
+    private static byte asByte(int value) { return (byte) value; }
+    private static short asShort(int value) { return (short) value; }
+
+    private static void putHeader(ByteBuffer ra, boolean hasDefaultRoute) {
+        /**
+            Router Advertisement Message Format
+
+             0                   1                   2                   3
+             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |     Type      |     Code      |          Checksum             |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            | Cur Hop Limit |M|O|H|Prf|P|R|R|       Router Lifetime         |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |                         Reachable Time                        |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |                          Retrans Timer                        |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |   Options ...
+            +-+-+-+-+-+-+-+-+-+-+-+-
+        */
+        final byte DEFAULT_HOPLIMIT = 64;
+        ra.put(ICMPV6_ND_ROUTER_ADVERT)
+          .put(asByte(0))
+          .putShort(asShort(0))
+          .put(DEFAULT_HOPLIMIT)
+          // RFC 4191 "high" preference, iff. advertising a default route.
+          .put(hasDefaultRoute ? asByte(0x08) : asByte(0))
+          .putShort(hasDefaultRoute ? asShort(DEFAULT_LIFETIME) : asShort(0))
+          .putInt(0)
+          .putInt(0);
+    }
+
+    private static void putSlla(ByteBuffer ra, byte[] slla) {
+        /**
+            Source/Target Link-layer Address
+
+             0                   1                   2                   3
+             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |     Type      |    Length     |    Link-Layer Address ...
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+        */
+        if (slla == null || slla.length != 6) {
+            // Only IEEE 802.3 6-byte addresses are supported.
+            return;
+        }
+        final byte ND_OPTION_SLLA = 1;
+        final byte SLLA_NUM_8OCTETS = 1;
+        ra.put(ND_OPTION_SLLA)
+          .put(SLLA_NUM_8OCTETS)
+          .put(slla);
+    }
+
+    private static void putExpandedFlagsOption(ByteBuffer ra) {
+        /**
+            Router Advertisement Expanded Flags Option
+
+             0                   1                   2                   3
+             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |     Type      |    Length     |         Bit fields available ..
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            ... for assignment                                              |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         */
+
+        final byte ND_OPTION_EFO = 26;
+        final byte EFO_NUM_8OCTETS = 1;
+
+        ra.put(ND_OPTION_EFO)
+          .put(EFO_NUM_8OCTETS)
+          .putShort(asShort(0))
+          .putInt(0);
+    }
+
+    private static void putMtu(ByteBuffer ra, int mtu) {
+        /**
+            MTU
+
+             0                   1                   2                   3
+             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |     Type      |    Length     |           Reserved            |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |                              MTU                              |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+        */
+        final byte ND_OPTION_MTU = 5;
+        final byte MTU_NUM_8OCTETS = 1;
+        ra.put(ND_OPTION_MTU)
+          .put(MTU_NUM_8OCTETS)
+          .putShort(asShort(0))
+          .putInt(mtu);
+    }
+
+    private static void putPio(ByteBuffer ra, IpPrefix ipp) {
+        /**
+            Prefix Information
+
+             0                   1                   2                   3
+             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |     Type      |    Length     | Prefix Length |L|A| Reserved1 |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |                         Valid Lifetime                        |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |                       Preferred Lifetime                      |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |                           Reserved2                           |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |                                                               |
+            +                                                               +
+            |                                                               |
+            +                            Prefix                             +
+            |                                                               |
+            +                                                               +
+            |                                                               |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+        */
+        final int prefixLength = ipp.getPrefixLength();
+        if (prefixLength != 64) {
+            return;
+        }
+        final byte ND_OPTION_PIO = 3;
+        final byte PIO_NUM_8OCTETS = 4;
+
+        final byte[] addr = ipp.getAddress().getAddress();
+        ra.put(ND_OPTION_PIO)
+          .put(PIO_NUM_8OCTETS)
+          .put(asByte(prefixLength))
+          .put(asByte(0xc0))  // L&A set
+          .putInt(DEFAULT_LIFETIME)
+          .putInt(DEFAULT_LIFETIME)
+          .putInt(0)
+          .put(addr);
+    }
+
+    private static void putRio(ByteBuffer ra, IpPrefix ipp) {
+        /**
+            Route Information Option
+
+             0                   1                   2                   3
+             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |     Type      |    Length     | Prefix Length |Resvd|Prf|Resvd|
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |                        Route Lifetime                         |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |                   Prefix (Variable Length)                    |
+            .                                                               .
+            .                                                               .
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         */
+        final int prefixLength = ipp.getPrefixLength();
+        if (prefixLength > 64) {
+            return;
+        }
+        final byte ND_OPTION_RIO = 24;
+        final byte RIO_NUM_8OCTETS = asByte(
+                (prefixLength == 0) ? 1 : (prefixLength <= 8) ? 2 : 3);
+
+        final byte[] addr = ipp.getAddress().getAddress();
+        ra.put(ND_OPTION_RIO)
+          .put(RIO_NUM_8OCTETS)
+          .put(asByte(prefixLength))
+          .put(asByte(0x18))
+          .putInt(DEFAULT_LIFETIME);
+
+        // Rely upon an IpPrefix's address being properly zeroed.
+        if (prefixLength > 0) {
+            ra.put(addr, 0, (prefixLength <= 64) ? 8 : 16);
+        }
+    }
+
+    private static void putRdnss(ByteBuffer ra, Set<Inet6Address> dnses) {
+        /**
+            Recursive DNS Server (RDNSS) Option
+
+             0                   1                   2                   3
+             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |     Type      |     Length    |           Reserved            |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |                           Lifetime                            |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |                                                               |
+            :            Addresses of IPv6 Recursive DNS Servers            :
+            |                                                               |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         */
+
+        final byte ND_OPTION_RDNSS = 25;
+        final byte RDNSS_NUM_8OCTETS = asByte(dnses.size() * 2 + 1);
+        ra.put(ND_OPTION_RDNSS)
+          .put(RDNSS_NUM_8OCTETS)
+          .putShort(asShort(0))
+          .putInt(DEFAULT_LIFETIME);
+
+        for (Inet6Address dns : dnses) {
+            ra.put(dns.getAddress());
+        }
+    }
+
+    private boolean createSocket() {
+        final int SEND_TIMEOUT_MS = 300;
+
+        try {
+            mSocket = Os.socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
+            // Setting SNDTIMEO is purely for defensive purposes.
+            Os.setsockoptTimeval(
+                    mSocket, SOL_SOCKET, SO_SNDTIMEO, StructTimeval.fromMillis(SEND_TIMEOUT_MS));
+            Os.setsockoptIfreq(mSocket, SOL_SOCKET, SO_BINDTODEVICE, mIfName);
+            NetworkUtils.protectFromVpn(mSocket);
+            NetworkUtils.setupRaSocket(mSocket, mIfIndex);
+        } catch (ErrnoException | IOException e) {
+            Log.e(TAG, "Failed to create RA daemon socket: " + e);
+            return false;
+        }
+
+        return true;
+    }
+
+    private void closeSocket() {
+        if (mSocket != null) {
+            IoUtils.closeQuietly(mSocket);
+        }
+        mSocket = null;
+    }
+
+    private boolean isSocketValid() {
+        final FileDescriptor s = mSocket;
+        return (s != null) && s.valid();
+    }
+
+    private boolean isSuitableDestination(InetSocketAddress dest) {
+        if (mAllNodes.equals(dest)) {
+            return true;
+        }
+
+        final InetAddress destip = dest.getAddress();
+        return (destip instanceof Inet6Address) &&
+                destip.isLinkLocalAddress() &&
+               (((Inet6Address) destip).getScopeId() == mIfIndex);
+    }
+
+    private void maybeSendRA(InetSocketAddress dest) {
+        if (dest == null || !isSuitableDestination(dest)) {
+            dest = mAllNodes;
+        }
+
+        try {
+            synchronized (mLock) {
+                if (mRaLength < MIN_RA_HEADER_SIZE) {
+                    // No actual RA to send.
+                    return;
+                }
+                Os.sendto(mSocket, mRA, 0, mRaLength, 0, dest);
+            }
+            Log.d(TAG, "RA sendto " + dest.getAddress().getHostAddress());
+        } catch (ErrnoException | SocketException e) {
+            if (isSocketValid()) {
+                Log.e(TAG, "sendto error: " + e);
+            }
+        }
+    }
+
+    private final class UnicastResponder extends Thread {
+        private final InetSocketAddress solicitor = new InetSocketAddress();
+        // The recycled buffer for receiving Router Solicitations from clients.
+        // If the RS is larger than IPV6_MIN_MTU the packets are truncated.
+        // This is fine since currently only byte 0 is examined anyway.
+        private final byte mSolication[] = new byte[IPV6_MIN_MTU];
+
+        @Override
+        public void run() {
+            while (isSocketValid()) {
+                try {
+                    // Blocking receive.
+                    final int rval = Os.recvfrom(
+                            mSocket, mSolication, 0, mSolication.length, 0, solicitor);
+                    // Do the least possible amount of validation.
+                    if (rval < 1 || mSolication[0] != ICMPV6_ND_ROUTER_SOLICIT) {
+                        continue;
+                    }
+                } catch (ErrnoException | SocketException e) {
+                    if (isSocketValid()) {
+                        Log.e(TAG, "recvfrom error: " + e);
+                    }
+                    continue;
+                }
+
+                maybeSendRA(solicitor);
+            }
+        }
+    }
+
+    // TODO: Consider moving this to run on a provided Looper as a Handler,
+    // with WakeupMessage-style messages providing the timer driven input.
+    private final class MulticastTransmitter extends Thread {
+        private final Random mRandom = new Random();
+        private final AtomicInteger mUrgentAnnouncements = new AtomicInteger(0);
+
+        @Override
+        public void run() {
+            while (isSocketValid()) {
+                try {
+                    Thread.sleep(getNextMulticastTransmitDelayMs());
+                } catch (InterruptedException ignored) {
+                    // Stop sleeping, immediately send an RA, and continue.
+                }
+
+                maybeSendRA(mAllNodes);
+            }
+        }
+
+        public void hup() {
+            // Set to one fewer that the desired number, because as soon as
+            // the thread interrupt is processed we immediately send an RA
+            // and mUrgentAnnouncements is not examined until the subsequent
+            // sleep interval computation (i.e. this way we send 3 and not 4).
+            mUrgentAnnouncements.set(MAX_URGENT_RTR_ADVERTISEMENTS - 1);
+            interrupt();
+        }
+
+        private int getNextMulticastTransmitDelaySec() {
+            synchronized (mLock) {
+                if (mRaLength < MIN_RA_HEADER_SIZE) {
+                    // No actual RA to send; just sleep for 1 day.
+                    return DAY_IN_SECONDS;
+                }
+            }
+
+            final int urgentPending = mUrgentAnnouncements.getAndDecrement();
+            if (urgentPending > 0) {
+                return MIN_DELAY_BETWEEN_RAS_SEC;
+            }
+
+            return MIN_RTR_ADV_INTERVAL_SEC + mRandom.nextInt(
+                    MAX_RTR_ADV_INTERVAL_SEC - MIN_RTR_ADV_INTERVAL_SEC);
+        }
+
+        private long getNextMulticastTransmitDelayMs() {
+            return 1000 * (long) getNextMulticastTransmitDelaySec();
+        }
+    }
+}
diff --git a/services/retaildemo/java/com/android/server/retaildemo/RetailDemoModeService.java b/services/retaildemo/java/com/android/server/retaildemo/RetailDemoModeService.java
index a92498b..855a2b6 100644
--- a/services/retaildemo/java/com/android/server/retaildemo/RetailDemoModeService.java
+++ b/services/retaildemo/java/com/android/server/retaildemo/RetailDemoModeService.java
@@ -231,8 +231,8 @@
                 BackgroundThread.getHandler().post(new Runnable() {
                     @Override
                     public void run() {
-                        if (!deleteDemoFolderContents()) {
-                            Slog.w(TAG, "Failed to delete demo folder contents");
+                        if (!deletePreloadsFolderContents()) {
+                            Slog.w(TAG, "Failed to delete preloads folder contents");
                         }
                     }
                 });
@@ -388,8 +388,8 @@
                 getContext().getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) != 0;
     }
 
-    private boolean deleteDemoFolderContents() {
-        final File dir = Environment.getDataPreloadsDemoDirectory();
+    private boolean deletePreloadsFolderContents() {
+        final File dir = Environment.getDataPreloadsDirectory();
         Slog.i(TAG, "Deleting contents of " + dir);
         return FileUtils.deleteContents(dir);
     }
diff --git a/services/tests/servicestests/src/com/android/server/ConnectivityServiceTest.java b/services/tests/servicestests/src/com/android/server/ConnectivityServiceTest.java
index ba77b03..f2a9315 100644
--- a/services/tests/servicestests/src/com/android/server/ConnectivityServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/ConnectivityServiceTest.java
@@ -1040,6 +1040,8 @@
     enum CallbackState {
         NONE,
         AVAILABLE,
+        NETWORK_CAPABILITIES,
+        LINK_PROPERTIES,
         LOSING,
         LOST
     }
@@ -1072,18 +1074,21 @@
         }
         private final LinkedBlockingQueue<CallbackInfo> mCallbacks = new LinkedBlockingQueue<>();
 
-        private void setLastCallback(CallbackState state, Network network, Object o) {
+        protected void setLastCallback(CallbackState state, Network network, Object o) {
             mCallbacks.offer(new CallbackInfo(state, network, o));
         }
 
+        @Override
         public void onAvailable(Network network) {
             setLastCallback(CallbackState.AVAILABLE, network, null);
         }
 
+        @Override
         public void onLosing(Network network, int maxMsToLive) {
             setLastCallback(CallbackState.LOSING, network, maxMsToLive /* autoboxed int */);
         }
 
+        @Override
         public void onLost(Network network) {
             setLastCallback(CallbackState.LOST, network, null);
         }
@@ -1744,6 +1749,67 @@
         defaultNetworkCallback.expectCallback(CallbackState.LOST, mCellNetworkAgent);
     }
 
+    private class TestRequestUpdateCallback extends TestNetworkCallback {
+        @Override
+        public void onCapabilitiesChanged(Network network, NetworkCapabilities netCap) {
+            setLastCallback(CallbackState.NETWORK_CAPABILITIES, network, netCap);
+        }
+
+        @Override
+        public void onLinkPropertiesChanged(Network network, LinkProperties linkProp) {
+            setLastCallback(CallbackState.LINK_PROPERTIES, network, linkProp);
+        }
+    }
+
+    @LargeTest
+    public void testRequestCallbackUpdates() throws Exception {
+        // File a network request for mobile.
+        final TestNetworkCallback cellNetworkCallback = new TestRequestUpdateCallback();
+        final NetworkRequest cellRequest = new NetworkRequest.Builder()
+                .addTransportType(TRANSPORT_CELLULAR).build();
+        mCm.requestNetwork(cellRequest, cellNetworkCallback);
+
+        // Bring up the mobile network.
+        mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
+        mCellNetworkAgent.connect(true);
+
+        // We should get onAvailable().
+        cellNetworkCallback.expectCallback(CallbackState.AVAILABLE, mCellNetworkAgent);
+        // We should get onCapabilitiesChanged(), when the mobile network successfully validates.
+        cellNetworkCallback.expectCallback(CallbackState.NETWORK_CAPABILITIES, mCellNetworkAgent);
+        cellNetworkCallback.assertNoCallback();
+
+        // Update LinkProperties.
+        final LinkProperties lp = new LinkProperties();
+        lp.setInterfaceName("foonet_data0");
+        mCellNetworkAgent.sendLinkProperties(lp);
+        // We should get onLinkPropertiesChanged().
+        cellNetworkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
+        cellNetworkCallback.assertNoCallback();
+
+        // Register a garden variety default network request.
+        final TestNetworkCallback dfltNetworkCallback = new TestRequestUpdateCallback();
+        mCm.registerDefaultNetworkCallback(dfltNetworkCallback);
+        // Only onAvailable() is called; no other information is delivered.
+        dfltNetworkCallback.expectCallback(CallbackState.AVAILABLE, mCellNetworkAgent);
+        dfltNetworkCallback.assertNoCallback();
+
+        // Request a NetworkCapabilities update; only the requesting callback is notified.
+        mCm.requestNetworkCapabilities(dfltNetworkCallback);
+        dfltNetworkCallback.expectCallback(CallbackState.NETWORK_CAPABILITIES, mCellNetworkAgent);
+        cellNetworkCallback.assertNoCallback();
+        dfltNetworkCallback.assertNoCallback();
+
+        // Request a LinkProperties update; only the requesting callback is notified.
+        mCm.requestLinkProperties(dfltNetworkCallback);
+        dfltNetworkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
+        cellNetworkCallback.assertNoCallback();
+        dfltNetworkCallback.assertNoCallback();
+
+        mCm.unregisterNetworkCallback(dfltNetworkCallback);
+        mCm.unregisterNetworkCallback(cellNetworkCallback);
+    }
+
     @SmallTest
     public void testRequestBenchmark() throws Exception {
         // Benchmarks connecting and switching performance in the presence of a large number of
diff --git a/services/tests/servicestests/src/com/android/server/pm/BaseShortcutManagerTest.java b/services/tests/servicestests/src/com/android/server/pm/BaseShortcutManagerTest.java
index 3f6ab36..d853f91 100644
--- a/services/tests/servicestests/src/com/android/server/pm/BaseShortcutManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/BaseShortcutManagerTest.java
@@ -104,6 +104,7 @@
 import java.util.function.BiFunction;
 import java.util.function.BiPredicate;
 import java.util.function.Consumer;
+import java.util.function.Function;
 
 public abstract class BaseShortcutManagerTest extends InstrumentationTestCase {
     protected static final String TAG = "ShortcutManagerTest";
@@ -382,9 +383,7 @@
 
         @Override
         void injectPostToHandler(Runnable r) {
-            final long token = mContext.injectClearCallingIdentity();
-            r.run();
-            mContext.injectRestoreCallingIdentity(token);
+            runOnHandler(r);
         }
 
         @Override
@@ -400,9 +399,14 @@
         }
 
         @Override
-        void wtf(String message, Exception e) {
+        void wtf(String message, Throwable th) {
             // During tests, WTF is fatal.
-            fail(message + "  exception: " + e);
+            fail(message + "  exception: " + th + "\n" + Log.getStackTraceString(th));
+        }
+
+        @Override
+        boolean injectCheckPendingTaskWaitThread() {
+            return true;
         }
     }
 
@@ -452,9 +456,7 @@
 
         @Override
         void postToPackageMonitorHandler(Runnable r) {
-            final long token = mContext.injectClearCallingIdentity();
-            r.run();
-            mContext.injectRestoreCallingIdentity(token);
+            runOnHandler(r);
         }
 
         @Override
@@ -497,6 +499,9 @@
     public static class ShortcutActivity3 extends Activity {
     }
 
+    protected Looper mLooper;
+    protected Handler mHandler;
+
     protected ServiceContext mServiceContext;
     protected ClientContext mClientContext;
 
@@ -615,6 +620,10 @@
     protected final HashMap<String, LinkedHashMap<ComponentName, Integer>> mActivityMetadataResId
             = new HashMap<>();
 
+    protected final Map<Integer, UserInfo> mUserInfos = new HashMap<>();
+    protected final Map<Integer, Boolean> mRunningUsers = new HashMap<>();
+    protected final Map<Integer, Boolean> mUnlockedUsers = new HashMap<>();
+
     static {
         QUERY_ALL.setQueryFlags(
                 ShortcutQuery.FLAG_GET_ALL_KINDS);
@@ -624,6 +633,9 @@
     protected void setUp() throws Exception {
         super.setUp();
 
+        mLooper = Looper.getMainLooper();
+        mHandler = new Handler(mLooper);
+
         mServiceContext = spy(new ServiceContext());
         mClientContext = new ClientContext();
 
@@ -667,29 +679,37 @@
         deleteAllSavedFiles();
 
         // Set up users.
-        doAnswer(inv -> {
-                assertSystem();
-                return USER_INFO_0;
-        }).when(mMockUserManager).getUserInfo(eq(USER_0));
+        when(mMockUserManager.getUserInfo(anyInt())).thenAnswer(new AnswerWithSystemCheck<>(
+                inv -> mUserInfos.get((Integer) inv.getArguments()[0])));
 
-        doAnswer(inv -> {
-                assertSystem();
-                return USER_INFO_10;
-        }).when(mMockUserManager).getUserInfo(eq(USER_10));
+        mUserInfos.put(USER_0, USER_INFO_0);
+        mUserInfos.put(USER_10, USER_INFO_10);
+        mUserInfos.put(USER_11, USER_INFO_11);
+        mUserInfos.put(USER_P0, USER_INFO_P0);
 
-        doAnswer(inv -> {
-                assertSystem();
-                return USER_INFO_11;
-        }).when(mMockUserManager).getUserInfo(eq(USER_11));
+        // Set up isUserRunning and isUserUnlocked.
+        when(mMockUserManager.isUserRunning(anyInt())).thenAnswer(new AnswerWithSystemCheck<>(
+                        inv -> mRunningUsers.get((Integer) inv.getArguments()[0])));
 
-        doAnswer(inv -> {
-                assertSystem();
-                return USER_INFO_P0;
-        }).when(mMockUserManager).getUserInfo(eq(USER_P0));
+        when(mMockUserManager.isUserUnlocked(anyInt())).thenAnswer(new AnswerWithSystemCheck<>(
+                        inv -> {
+                            final int userId = (Integer) inv.getArguments()[0];
+                            return mRunningUsers.get(userId) && mUnlockedUsers.get(userId);
+                        }));
 
-        // User 0 is always running.
-        when(mMockUserManager.isUserRunning(eq(USER_0))).thenAnswer(new AnswerIsUserRunning(true));
+        // User 0 is always running
+        mRunningUsers.put(USER_0, true);
+        mRunningUsers.put(USER_10, false);
+        mRunningUsers.put(USER_11, false);
+        mRunningUsers.put(USER_P0, false);
 
+        // Unlock all users by default.
+        mUnlockedUsers.put(USER_0, true);
+        mUnlockedUsers.put(USER_10, true);
+        mUnlockedUsers.put(USER_11, true);
+        mUnlockedUsers.put(USER_P0, true);
+
+        // Set up resources
         setUpAppResources();
 
         // Start the service.
@@ -705,18 +725,18 @@
     /**
      * Returns a boolean but also checks if the current UID is SYSTEM_UID.
      */
-    protected class AnswerIsUserRunning implements Answer<Boolean> {
-        protected final boolean mAnswer;
+    protected class AnswerWithSystemCheck<T> implements Answer<T> {
+        private final Function<InvocationOnMock, T> mChecker;
 
-        protected AnswerIsUserRunning(boolean answer) {
-            mAnswer = answer;
+        public AnswerWithSystemCheck(Function<InvocationOnMock, T> checker) {
+            mChecker = checker;
         }
 
         @Override
-        public Boolean answer(InvocationOnMock invocation) throws Throwable {
-            assertEquals("isUserRunning() must be called on SYSTEM UID.",
+        public T answer(InvocationOnMock invocation) throws Throwable {
+            assertEquals("Must be called on SYSTEM UID.",
                     Process.SYSTEM_UID, mInjectedCallingUid);
-            return mAnswer;
+            return mChecker.apply(invocation);
         }
     }
 
@@ -805,7 +825,7 @@
         LocalServices.removeServiceForTest(ShortcutServiceInternal.class);
 
         // Instantiate targets.
-        mService = new ShortcutServiceTestable(mServiceContext, Looper.getMainLooper());
+        mService = new ShortcutServiceTestable(mServiceContext, mLooper);
         mManager = new ShortcutManagerTestable(mClientContext, mService);
 
         mInternal = LocalServices.getService(ShortcutServiceInternal.class);
@@ -828,6 +848,8 @@
 
     protected void shutdownServices() {
         if (mService != null) {
+            mService.getPendingTasksForTest().waitOnAllTasks();
+
             // Flush all the unsaved data from the previous instance.
             mService.saveDirtyInfo();
 
@@ -844,6 +866,15 @@
         mLauncherAppsMap.clear();
     }
 
+    protected void runOnHandler(Runnable r) {
+        final long token = mServiceContext.injectClearCallingIdentity();
+        try {
+            r.run();
+        } finally {
+            mServiceContext.injectRestoreCallingIdentity(token);
+        }
+    }
+
     protected void addPackage(String packageName, int uid, int version) {
         addPackage(packageName, uid, version, packageName);
     }
diff --git a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest1.java b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest1.java
index c7be3d9..f5ae706 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest1.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest1.java
@@ -54,9 +54,7 @@
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.waitOnMainThread;
 
 import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.times;
@@ -1293,8 +1291,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_3);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
-                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+        mInternal.onPackageBroadcast(genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
             assertTrue(mManager.setDynamicShortcuts(list(
@@ -1312,8 +1309,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
-                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+        mInternal.onPackageBroadcast(genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
             assertTrue(mManager.setDynamicShortcuts(list(
@@ -2669,7 +2665,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                     R.xml.shortcut_2);
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mService.mPackageMonitor.onReceive(getTestContext(),
+            mInternal.onPackageBroadcast(
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
                 .areAllManifest()
@@ -2706,7 +2702,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_0);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         assertForLauncherCallback(mLauncherApps, () -> {
@@ -2843,8 +2839,8 @@
         assertCallbackNotReceived(c11_1);
 
         // Work profile, now running.
-        doAnswer(new AnswerIsUserRunning(false)).when(mMockUserManager).isUserRunning(anyInt());
-        doAnswer(new AnswerIsUserRunning(true)).when(mMockUserManager).isUserRunning(eq(USER_P0));
+        mRunningUsers.clear();
+        mRunningUsers.put(USER_P0, true);
 
         resetAll(all);
         runWithCaller(CALLING_PACKAGE_1, USER_P0, () -> {
@@ -2862,9 +2858,8 @@
         assertCallbackReceived(cP0_1, HANDLE_USER_P0, CALLING_PACKAGE_1, "s1", "s2", "s3", "s4");
 
         // Normal secondary user.
-
-        doAnswer(new AnswerIsUserRunning(false)).when(mMockUserManager).isUserRunning(anyInt());
-        doAnswer(new AnswerIsUserRunning(true)).when(mMockUserManager).isUserRunning(eq(USER_10));
+        mRunningUsers.clear();
+        mRunningUsers.put(USER_10, true);
 
         resetAll(all);
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -3327,7 +3322,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -3344,7 +3339,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -3706,7 +3701,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
             assertWith(getCallerShortcuts())
@@ -3746,7 +3741,7 @@
         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
 
         uninstallPackage(USER_0, CALLING_PACKAGE_1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageDeleteIntent(CALLING_PACKAGE_1, USER_0));
 
         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
@@ -3763,8 +3758,10 @@
         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
 
+        mRunningUsers.put(USER_10, true);
+
         uninstallPackage(USER_10, CALLING_PACKAGE_2);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageDeleteIntent(CALLING_PACKAGE_2, USER_10));
 
         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
@@ -3855,7 +3852,7 @@
         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
 
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageDataClear(CALLING_PACKAGE_1, USER_0));
 
         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
@@ -3872,7 +3869,9 @@
         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
 
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mRunningUsers.put(USER_10, true);
+
+        mInternal.onPackageBroadcast(
                 genPackageDataClear(CALLING_PACKAGE_2, USER_10));
 
         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
@@ -3892,12 +3891,14 @@
 
     public void testHandlePackageClearData_manifestRepublished() {
 
+        mRunningUsers.put(USER_10, true);
+
         // Add two manifests and two dynamics.
         addManifestShortcutResource(
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_10));
 
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -3918,7 +3919,7 @@
         });
 
         // Clear data
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageDataClear(CALLING_PACKAGE_1, USER_10));
 
         // Only manifest shortcuts will remain, and are no longer pinned.
@@ -3983,9 +3984,9 @@
         reset(c0);
         reset(c10);
 
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageUpdateIntent(CALLING_PACKAGE_1, USER_0));
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageUpdateIntent(CALLING_PACKAGE_1, USER_10));
 
         waitOnMainThread();
@@ -4006,7 +4007,7 @@
         updatePackageVersion(CALLING_PACKAGE_1, 1);
 
         // Then send the broadcast, to only user-0.
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageUpdateIntent(CALLING_PACKAGE_1, USER_0));
 
         waitOnMainThread();
@@ -4037,12 +4038,14 @@
         // notification to the launcher.
         mInjectedCurrentTimeMillis = START_TIME + 200;
 
-        doAnswer(new AnswerIsUserRunning(true)).when(mMockUserManager).isUserRunning(eq(USER_10));
+        mRunningUsers.put(USER_10, true);
 
         reset(c0);
         reset(c10);
         mService.handleUnlockUser(USER_10);
 
+        waitOnMainThread();
+
         shortcuts = ArgumentCaptor.forClass(List.class);
         verify(c0, times(0)).onShortcutsChanged(
                 eq(CALLING_PACKAGE_1),
@@ -4069,7 +4072,7 @@
         updatePackageVersion(CALLING_PACKAGE_2, 10);
 
         // Then send the broadcast, to only user-0.
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageUpdateIntent(CALLING_PACKAGE_2, USER_0));
         mService.handleUnlockUser(USER_10);
 
@@ -4093,7 +4096,7 @@
         updatePackageVersion(CALLING_PACKAGE_3, 100);
 
         // Then send the broadcast, to only user-0.
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageUpdateIntent(CALLING_PACKAGE_3, USER_0));
         mService.handleUnlockUser(USER_10);
 
@@ -4175,7 +4178,7 @@
 
         // Update the package.
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageUpdateIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -4201,8 +4204,10 @@
         addManifestShortcutResource(ACTIVITY1, R.xml.shortcut_1);
         addManifestShortcutResource(ACTIVITY2, R.xml.shortcut_1_alt);
 
+        mRunningUsers.put(USER_10, true);
+
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_10));
 
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -4234,7 +4239,7 @@
         });
 
         // First, no changes.
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageChangedIntent(CALLING_PACKAGE_1, USER_10));
 
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -4257,7 +4262,7 @@
 
         // Disable activity 1
         mEnabledActivityChecker = (activity, userId) -> !ACTIVITY1.equals(activity);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageChangedIntent(CALLING_PACKAGE_1, USER_10));
 
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -4277,7 +4282,7 @@
         // Re-enable activity 1.
         // Manifest shortcuts will be re-published, but dynamic ones are not.
         mEnabledActivityChecker = (activity, userId) -> true;
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageChangedIntent(CALLING_PACKAGE_1, USER_10));
 
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -4301,7 +4306,7 @@
         // Disable activity 2
         // Because "ms1-alt" and "s2" are both pinned, they will remain, but disabled.
         mEnabledActivityChecker = (activity, userId) -> !ACTIVITY2.equals(activity);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageChangedIntent(CALLING_PACKAGE_1, USER_10));
 
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -4364,7 +4369,7 @@
         setCaller(LAUNCHER_1, USER_0);
         assertForLauncherCallback(mLauncherApps, () -> {
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mService.mPackageMonitor.onReceive(getTestContext(),
+            mInternal.onPackageBroadcast(
                     genPackageUpdateIntent(CALLING_PACKAGE_1, USER_0));
         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
                 // Make sure the launcher gets callbacks.
@@ -5364,7 +5369,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -5385,7 +5390,7 @@
                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
                 R.xml.shortcut_5);
         updatePackageVersion(CALLING_PACKAGE_2, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -5422,7 +5427,7 @@
                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageLastUpdateTime(CALLING_PACKAGE_2, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -5455,8 +5460,32 @@
             assertEmpty(mManager.getManifestShortcuts());
             assertEmpty(mManager.getPinnedShortcuts());
         });
+        // Send add broadcast, but the user is not running, so should be ignored.
+        mRunningUsers.put(USER_10, false);
+        mUnlockedUsers.put(USER_10, false);
+
+        mInternal.onPackageBroadcast(
+                genPackageAddIntent(CALLING_PACKAGE_2, USER_10));
+        runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        // Try again, but the user is locked, so still ignored.
+        mRunningUsers.put(USER_10, true);
+
+        mInternal.onPackageBroadcast(
+                genPackageAddIntent(CALLING_PACKAGE_2, USER_10));
+        runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        // Unlock the user, now it should work.
+        mUnlockedUsers.put(USER_10, true);
+
         // Send PACKAGE_ADD broadcast to have Package 2 on user-10 publish manifest shortcuts.
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_2, USER_10));
 
         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
@@ -5497,7 +5526,7 @@
                 R.xml.shortcut_5_reverse);
 
         updatePackageLastUpdateTime(CALLING_PACKAGE_2, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
 
         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
@@ -5525,7 +5554,7 @@
                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity2.class.getName()),
                 R.xml.shortcut_0);
         updatePackageLastUpdateTime(CALLING_PACKAGE_2, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
 
         // No manifest shortcuts, and pinned ones are disabled.
@@ -5556,7 +5585,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_error_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Only the valid one is published.
@@ -5571,7 +5600,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_error_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Only the valid one is published.
@@ -5586,7 +5615,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_error_3);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Only the valid one is published.
@@ -5602,7 +5631,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_error_4);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -5630,7 +5659,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_5);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -5668,7 +5697,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_error_4);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Make sure 3, 4 and 5 still exist but disabled.
@@ -5716,7 +5745,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_5);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Only the valid one is published.
@@ -5821,7 +5850,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -5918,7 +5947,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Only the valid one is published.
@@ -5937,7 +5966,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1_disable);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Because shortcut 1 wasn't pinned, it'll just go away.
@@ -5958,7 +5987,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Only the valid one is published.
@@ -5981,7 +6010,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1_disable);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Because shortcut 1 was pinned, it'll still exist as pinned, but disabled.
@@ -6014,7 +6043,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2_duplicate);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -6044,7 +6073,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
                 R.xml.shortcut_5);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -6116,7 +6145,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_5);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -6166,7 +6195,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(LAUNCHER_1, USER_0, () -> {
@@ -6177,7 +6206,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -6259,7 +6288,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_5);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -6329,7 +6358,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                     R.xml.shortcut_2);
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mService.mPackageMonitor.onReceive(getTestContext(),
+            mInternal.onPackageBroadcast(
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
             assertEquals(2, mManager.getManifestShortcuts().size());
 
@@ -6455,7 +6484,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                     R.xml.shortcut_2);
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mService.mPackageMonitor.onReceive(getTestContext(),
+            mInternal.onPackageBroadcast(
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
             assertEquals(2, mManager.getManifestShortcuts().size());
@@ -6604,7 +6633,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                     R.xml.shortcut_1);
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mService.mPackageMonitor.onReceive(getTestContext(),
+            mInternal.onPackageBroadcast(
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
             assertEquals(1, mManager.getManifestShortcuts().size());
 
@@ -6624,7 +6653,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
                     R.xml.shortcut_1_alt);
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mService.mPackageMonitor.onReceive(getTestContext(),
+            mInternal.onPackageBroadcast(
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
             assertEquals(3, mManager.getManifestShortcuts().size());
 
@@ -6644,7 +6673,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
                     R.xml.shortcut_5_alt); // manifest has 5, but max is 3, so a2 will have 3.
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mService.mPackageMonitor.onReceive(getTestContext(),
+            mInternal.onPackageBroadcast(
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
             assertEquals(5, mManager.getManifestShortcuts().size());
 
@@ -6663,7 +6692,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
                     R.xml.shortcut_0);
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mService.mPackageMonitor.onReceive(getTestContext(),
+            mInternal.onPackageBroadcast(
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
             assertEquals(0, mManager.getManifestShortcuts().size());
 
diff --git a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest3.java b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest3.java
index eb4db7a..fcf7ea2 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest3.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest3.java
@@ -66,7 +66,7 @@
     private void publishManifestShortcuts(ComponentName activity, int resId) {
         addManifestShortcutResource(activity, resId);
         updatePackageVersion(CALLING_PACKAGE, 1);
-        mService.mPackageMonitor.onReceive(getTestContext(),
+        mInternal.onPackageBroadcast(
                 genPackageAddIntent(CALLING_PACKAGE, USER_0));
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/pm/ShortcutPendingTasksTest.java b/services/tests/servicestests/src/com/android/server/pm/ShortcutPendingTasksTest.java
new file mode 100644
index 0000000..bf1ed98
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/pm/ShortcutPendingTasksTest.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright (C) 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.
+ */
+package com.android.server.pm;
+
+import android.os.Handler;
+import android.os.Looper;
+import android.test.MoreAsserts;
+import android.test.suitebuilder.annotation.LargeTest;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * Run with:
+ adb install \
+   -r -g ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
+ adb shell am instrument -e class com.android.server.pm.ShortcutPendingTasksTest \
+   -w com.android.frameworks.servicestests
+ */
+@LargeTest
+public class ShortcutPendingTasksTest extends BaseShortcutManagerTest {
+    public void testAll() {
+        final AtomicReference<Throwable> thrown = new AtomicReference<>();
+
+        final AtomicBoolean threadCheckerResult = new AtomicBoolean(true);
+
+        final Handler handler = new Handler(Looper.getMainLooper());
+
+        final ShortcutPendingTasks tasks = new ShortcutPendingTasks(
+                handler::post,
+                threadCheckerResult::get,
+                thrown::set);
+
+        // No pending tasks, shouldn't block.
+        assertTrue(tasks.waitOnAllTasks());
+
+        final AtomicInteger counter = new AtomicInteger();
+
+        // Run one task.
+        tasks.addTask(() -> {
+            try {
+                Thread.sleep(1000);
+            } catch (InterruptedException ignore) {
+            }
+            counter.incrementAndGet();
+        });
+
+        assertTrue(tasks.waitOnAllTasks());
+        assertNull(thrown.get());
+
+        assertEquals(1, counter.get());
+
+        // Run 3 tasks.
+
+        // We use this ID to make sure only one task can run at the same time.
+        final AtomicInteger currentTaskId = new AtomicInteger();
+
+        tasks.addTask(() -> {
+            currentTaskId.set(1);
+            try {
+                Thread.sleep(500);
+            } catch (InterruptedException ignore) {
+            }
+            counter.incrementAndGet();
+            assertEquals(1, currentTaskId.get());
+        });
+        tasks.addTask(() -> {
+            currentTaskId.set(2);
+            try {
+                Thread.sleep(500);
+            } catch (InterruptedException ignore) {
+            }
+            counter.incrementAndGet();
+            assertEquals(2, currentTaskId.get());
+        });
+        tasks.addTask(() -> {
+            currentTaskId.set(3);
+            try {
+                Thread.sleep(500);
+            } catch (InterruptedException ignore) {
+            }
+            counter.incrementAndGet();
+            assertEquals(3, currentTaskId.get());
+        });
+
+        assertTrue(tasks.waitOnAllTasks());
+        assertNull(thrown.get());
+        assertEquals(4, counter.get());
+
+        // No tasks running, shouldn't block.
+        assertTrue(tasks.waitOnAllTasks());
+        assertNull(thrown.get());
+        assertEquals(4, counter.get());
+
+        // Now the thread checker returns false, so waitOnAllTasks() returns false.
+        threadCheckerResult.set(false);
+        assertFalse(tasks.waitOnAllTasks());
+
+        threadCheckerResult.set(true);
+
+        // Make sure the exception handler is called.
+        tasks.addTask(() -> {
+            throw new RuntimeException("XXX");
+        });
+        assertTrue(tasks.waitOnAllTasks());
+        assertNotNull(thrown.get());
+        MoreAsserts.assertContainsRegex("XXX", thrown.get().getMessage());
+    }
+}
diff --git a/telecomm/java/android/telecom/Connection.java b/telecomm/java/android/telecom/Connection.java
index 441efb7..52f75f6 100644
--- a/telecomm/java/android/telecom/Connection.java
+++ b/telecomm/java/android/telecom/Connection.java
@@ -1551,6 +1551,8 @@
                 return "RINGING";
             case STATE_DIALING:
                 return "DIALING";
+            case STATE_PULLING_CALL:
+                return "PULLING_CALL";
             case STATE_ACTIVE:
                 return "ACTIVE";
             case STATE_HOLDING:
diff --git a/telecomm/java/android/telecom/ConnectionService.java b/telecomm/java/android/telecom/ConnectionService.java
index fc7d741..0c75630c 100644
--- a/telecomm/java/android/telecom/ConnectionService.java
+++ b/telecomm/java/android/telecom/ConnectionService.java
@@ -556,6 +556,9 @@
                 case Connection.STATE_DIALING:
                     mAdapter.setDialing(id);
                     break;
+                case Connection.STATE_PULLING_CALL:
+                    mAdapter.setPulling(id);
+                    break;
                 case Connection.STATE_DISCONNECTED:
                     // Handled in onDisconnected()
                     break;
diff --git a/telecomm/java/android/telecom/ConnectionServiceAdapter.java b/telecomm/java/android/telecom/ConnectionServiceAdapter.java
index c8cd3c0..df7d539 100644
--- a/telecomm/java/android/telecom/ConnectionServiceAdapter.java
+++ b/telecomm/java/android/telecom/ConnectionServiceAdapter.java
@@ -143,6 +143,21 @@
     }
 
     /**
+     * Sets a call's state to pulling (e.g. a call with {@link Connection#PROPERTY_IS_EXTERNAL_CALL}
+     * is being pulled to the local device.
+     *
+     * @param callId The unique ID of the call whose state is changing to dialing.
+     */
+    void setPulling(String callId) {
+        for (IConnectionServiceAdapter adapter : mAdapters) {
+            try {
+                adapter.setPulling(callId);
+            } catch (RemoteException e) {
+            }
+        }
+    }
+
+    /**
      * Sets a call's state to disconnected.
      *
      * @param callId The unique ID of the call whose state is changing to disconnected.
diff --git a/telecomm/java/android/telecom/ConnectionServiceAdapterServant.java b/telecomm/java/android/telecom/ConnectionServiceAdapterServant.java
index bf28feb..486f9d5 100644
--- a/telecomm/java/android/telecom/ConnectionServiceAdapterServant.java
+++ b/telecomm/java/android/telecom/ConnectionServiceAdapterServant.java
@@ -65,6 +65,7 @@
     private static final int MSG_REMOVE_EXTRAS = 25;
     private static final int MSG_ON_CONNECTION_EVENT = 26;
     private static final int MSG_SET_CONNECTION_PROPERTIES = 27;
+    private static final int MSG_SET_PULLING = 28;
 
     private final IConnectionServiceAdapter mDelegate;
 
@@ -101,6 +102,9 @@
                 case MSG_SET_DIALING:
                     mDelegate.setDialing((String) msg.obj);
                     break;
+                case MSG_SET_PULLING:
+                    mDelegate.setPulling((String) msg.obj);
+                    break;
                 case MSG_SET_DISCONNECTED: {
                     SomeArgs args = (SomeArgs) msg.obj;
                     try {
@@ -299,6 +303,11 @@
         }
 
         @Override
+        public void setPulling(String connectionId) {
+            mHandler.obtainMessage(MSG_SET_PULLING, connectionId).sendToTarget();
+        }
+
+        @Override
         public void setDisconnected(
                 String connectionId, DisconnectCause disconnectCause) {
             SomeArgs args = SomeArgs.obtain();
diff --git a/telecomm/java/android/telecom/RemoteConnectionService.java b/telecomm/java/android/telecom/RemoteConnectionService.java
index 21a7706..306b3c1 100644
--- a/telecomm/java/android/telecom/RemoteConnectionService.java
+++ b/telecomm/java/android/telecom/RemoteConnectionService.java
@@ -118,6 +118,12 @@
         }
 
         @Override
+        public void setPulling(String callId) {
+            findConnectionForAction(callId, "setPulling")
+                    .setState(Connection.STATE_PULLING_CALL);
+        }
+
+        @Override
         public void setDisconnected(String callId, DisconnectCause disconnectCause) {
             if (mConnectionById.containsKey(callId)) {
                 findConnectionForAction(callId, "setDisconnected")
diff --git a/telecomm/java/com/android/internal/telecom/IConnectionServiceAdapter.aidl b/telecomm/java/com/android/internal/telecom/IConnectionServiceAdapter.aidl
index 9bc8ffe..3bf83ae 100644
--- a/telecomm/java/com/android/internal/telecom/IConnectionServiceAdapter.aidl
+++ b/telecomm/java/com/android/internal/telecom/IConnectionServiceAdapter.aidl
@@ -47,6 +47,8 @@
 
     void setDialing(String callId);
 
+    void setPulling(String callId);
+
     void setDisconnected(String callId, in DisconnectCause disconnectCause);
 
     void setOnHold(String callId);
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index 9603662..2a95d3e 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -24,6 +24,7 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 
+import com.android.ims.ImsReasonInfo;
 import com.android.internal.telephony.ICarrierConfigLoader;
 
 /**
@@ -285,6 +286,16 @@
     public static final String KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_ENABLED_BOOL =
             "carrier_default_wfc_ims_roaming_enabled_bool";
 
+    /**
+     * Flag indicating whether failed calls due to no service should prompt the user to enable
+     * WIFI calling.  When {@code true}, if the user attempts to establish a call when there is no
+     * service available, they are connected to WIFI, and WIFI calling is disabled, a different
+     * call failure message will be used to encourage the user to enable WIFI calling.
+     * @hide
+     */
+    public static final String KEY_CARRIER_PROMOTE_WFC_ON_CALL_FAIL_BOOL =
+            "carrier_promote_wfc_on_call_fail_bool";
+
     /** Flag specifying whether provisioning is required for VOLTE. */
     public static final String KEY_CARRIER_VOLTE_PROVISIONING_REQUIRED_BOOL
             = "carrier_volte_provisioning_required_bool";
@@ -826,6 +837,25 @@
     public static final String KEY_ALLOW_ADD_CALL_DURING_VIDEO_CALL_BOOL =
             "allow_add_call_during_video_call";
 
+    /**
+     * Defines operator-specific {@link com.android.ims.ImsReasonInfo} mappings.
+     *
+     * Format: "ORIGINAL_CODE|MESSAGE|NEW_CODE"
+     * Where {@code ORIGINAL_CODE} corresponds to a {@link ImsReasonInfo#getCode()} code,
+     * {@code MESSAGE} corresponds to an expected {@link ImsReasonInfo#getExtraMessage()} string,
+     * and {@code NEW_CODE} is the new {@code ImsReasonInfo#CODE_*} which this combination of
+     * original code and message shall be remapped to.
+     *
+     * Example: "501|call completion elsewhere|1014"
+     * When the {@link ImsReasonInfo#getCode()} is {@link ImsReasonInfo#CODE_USER_TERMINATED} and
+     * the {@link ImsReasonInfo#getExtraMessage()} is {@code "call completion elsewhere"},
+     * {@link ImsReasonInfo#CODE_ANSWERED_ELSEWHERE} shall be used as the {@link ImsReasonInfo}
+     * code instead.
+     * @hide
+     */
+    public static final String KEY_IMS_REASONINFO_MAPPING_STRING_ARRAY =
+            "ims_reasoninfo_mapping_string_array";
+
     /** The default value for every variable. */
     private final static PersistableBundle sDefaults;
 
@@ -843,6 +873,7 @@
         sDefaults.putBoolean(KEY_CARRIER_WFC_SUPPORTS_WIFI_ONLY_BOOL, false);
         sDefaults.putBoolean(KEY_CARRIER_DEFAULT_WFC_IMS_ENABLED_BOOL, false);
         sDefaults.putBoolean(KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_ENABLED_BOOL, false);
+        sDefaults.putBoolean(KEY_CARRIER_PROMOTE_WFC_ON_CALL_FAIL_BOOL, false);
         sDefaults.putInt(KEY_CARRIER_DEFAULT_WFC_IMS_MODE_INT, 2);
         sDefaults.putBoolean(KEY_CARRIER_FORCE_DISABLE_ETWS_CMAS_TEST_BOOL, false);
         sDefaults.putBoolean(KEY_CARRIER_VOLTE_PROVISIONING_REQUIRED_BOOL, false);
@@ -981,6 +1012,8 @@
         sDefaults.putBoolean(KEY_DROP_VIDEO_CALL_WHEN_ANSWERING_AUDIO_CALL_BOOL, false);
         sDefaults.putBoolean(KEY_ALLOW_MERGE_WIFI_CALLS_WHEN_VOWIFI_OFF_BOOL, true);
         sDefaults.putBoolean(KEY_ALLOW_ADD_CALL_DURING_VIDEO_CALL_BOOL, true);
+
+        sDefaults.putStringArray(KEY_IMS_REASONINFO_MAPPING_STRING_ARRAY, null);
     }
 
     /**
diff --git a/telephony/java/android/telephony/DisconnectCause.java b/telephony/java/android/telephony/DisconnectCause.java
index 80ae4af..d7d4e84 100644
--- a/telephony/java/android/telephony/DisconnectCause.java
+++ b/telephony/java/android/telephony/DisconnectCause.java
@@ -206,6 +206,12 @@
      */
     public static final int ANSWERED_ELSEWHERE = 52;
 
+    /**
+     * The call was terminated because the maximum allowable number of calls has been reached.
+     * {@hide}
+     */
+    public static final int MAXIMUM_NUMBER_OF_CALLS_REACHED = 53;
+
     //*********************************************************************************************
     // When adding a disconnect type:
     // 1) Please assign the new type the next id value below.
@@ -214,14 +220,14 @@
     // 4) Update toString() with the newly added disconnect type.
     // 5) Update android.telecom.DisconnectCauseUtil with any mappings to a telecom.DisconnectCause.
     //
-    // NextId: 53
+    // NextId: 54
     //*********************************************************************************************
 
     /** Smallest valid value for call disconnect codes. */
     public static final int MINIMUM_VALID_VALUE = NOT_DISCONNECTED;
 
     /** Largest valid value for call disconnect codes. */
-    public static final int MAXIMUM_VALID_VALUE = ANSWERED_ELSEWHERE;
+    public static final int MAXIMUM_VALID_VALUE = MAXIMUM_NUMBER_OF_CALLS_REACHED;
 
     /** Private constructor to avoid class instantiation. */
     private DisconnectCause() {
@@ -335,6 +341,8 @@
             return "CALL_PULLED";
         case ANSWERED_ELSEWHERE:
             return "ANSWERED_ELSEWHERE";
+        case MAXIMUM_NUMBER_OF_CALLS_REACHED:
+            return "MAXIMUM_NUMER_OF_CALLS_REACHED";
         default:
             return "INVALID: " + cause;
         }
diff --git a/telephony/java/com/android/ims/ImsExternalCallState.java b/telephony/java/com/android/ims/ImsExternalCallState.java
index 71c1837..da26073 100644
--- a/telephony/java/com/android/ims/ImsExternalCallState.java
+++ b/telephony/java/com/android/ims/ImsExternalCallState.java
@@ -19,6 +19,7 @@
 import android.net.Uri;
 import android.os.Parcel;
 import android.os.Parcelable;
+import android.telecom.Log;
 import android.telephony.Rlog;
 
 /*
@@ -130,7 +131,7 @@
     @Override
     public String toString() {
         return "ImsExternalCallState { mCallId = " + mCallId +
-                ", mAddress = " + mAddress +
+                ", mAddress = " + Log.pii(mAddress) +
                 ", mIsPullable = " + mIsPullable +
                 ", mCallState = " + mCallState +
                 ", mCallType = " + mCallType +
diff --git a/telephony/java/com/android/ims/ImsReasonInfo.java b/telephony/java/com/android/ims/ImsReasonInfo.java
index 9369b20..408ad31 100644
--- a/telephony/java/com/android/ims/ImsReasonInfo.java
+++ b/telephony/java/com/android/ims/ImsReasonInfo.java
@@ -25,6 +25,7 @@
  * @hide
  */
 public class ImsReasonInfo implements Parcelable {
+
     /**
      * Specific code of each types
      */
@@ -284,6 +285,19 @@
     public static final int CODE_EPDG_TUNNEL_LOST_CONNECTION = 1402;
 
     /**
+     * The maximum number of calls allowed has been reached.  Used in a multi-endpoint scenario
+     * where the number of calls across all connected devices has reached the maximum.
+     */
+    public static final int CODE_MAXIMUM_NUMBER_OF_CALLS_REACHED = 1403;
+
+    /**
+     * Similar to {@link #CODE_LOCAL_CALL_DECLINE}, except indicates that a remote device has
+     * declined the call.  Used in a multi-endpoint scenario where a remote device declined an
+     * incoming call.
+     */
+    public static final int CODE_REMOTE_CALL_DECLINE = 1404;
+
+    /**
      * Network string error messages.
      * mExtraMessage may have these values.
      */
diff --git a/tools/aapt/Android.mk b/tools/aapt/Android.mk
index b701445..2a490d1 100644
--- a/tools/aapt/Android.mk
+++ b/tools/aapt/Android.mk
@@ -57,8 +57,8 @@
 aaptHostStaticLibs := \
     libandroidfw \
     libpng \
-    liblog \
     libutils \
+    liblog \
     libcutils \
     libexpat \
     libziparchive-host \
diff --git a/tools/aapt2/util/Util.cpp b/tools/aapt2/util/Util.cpp
index 7b0c71d..5a87c33 100644
--- a/tools/aapt2/util/Util.cpp
+++ b/tools/aapt2/util/Util.cpp
@@ -441,8 +441,10 @@
     }
 
     std::string utf8;
+    // Make room for '\0' explicitly.
+    utf8.resize(utf8Length + 1);
+    utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin(), utf8Length + 1);
     utf8.resize(utf8Length);
-    utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin());
     return utf8;
 }
 
diff --git a/tools/split-select/Android.mk b/tools/split-select/Android.mk
index 239bed5..863abae 100644
--- a/tools/split-select/Android.mk
+++ b/tools/split-select/Android.mk
@@ -47,8 +47,8 @@
     libaapt \
     libandroidfw \
     libpng \
-    liblog \
     libutils \
+    liblog \
     libcutils \
     libexpat \
     libziparchive-host \