Merge "Store GrContext on RenderThread for use by Skia-based renderers."
diff --git a/Android.mk b/Android.mk
index 5fef91e..0b5e0cc 100644
--- a/Android.mk
+++ b/Android.mk
@@ -575,6 +575,7 @@
 	frameworks/base/core/java/android/accounts/AuthenticatorDescription.aidl \
 	frameworks/base/core/java/android/accounts/Account.aidl \
 	frameworks/base/core/java/android/app/admin/SystemUpdatePolicy.aidl \
+	frameworks/base/core/java/android/app/admin/PasswordMetrics.aidl \
 	frameworks/base/core/java/android/print/PrintDocumentInfo.aidl \
 	frameworks/base/core/java/android/print/PageRange.aidl \
 	frameworks/base/core/java/android/print/PrintAttributes.aidl \
diff --git a/api/current.txt b/api/current.txt
index 9aa8c59..564653a 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -4489,6 +4489,7 @@
     method public void onTrimMemory(int);
     method public void onViewCreated(android.view.View, android.os.Bundle);
     method public void onViewStateRestored(android.os.Bundle);
+    method public void postponeEnterTransition();
     method public void registerForContextMenu(android.view.View);
     method public final void requestPermissions(java.lang.String[], int);
     method public void setAllowEnterTransitionOverlap(boolean);
@@ -4514,6 +4515,7 @@
     method public void startActivityForResult(android.content.Intent, int);
     method public void startActivityForResult(android.content.Intent, int, android.os.Bundle);
     method public void startIntentSenderForResult(android.content.IntentSender, int, android.content.Intent, int, int, int, android.os.Bundle) throws android.content.IntentSender.SendIntentException;
+    method public void startPostponedEnterTransition();
     method public void unregisterForContextMenu(android.view.View);
   }
 
@@ -4671,6 +4673,7 @@
     method public abstract android.app.FragmentTransaction remove(android.app.Fragment);
     method public abstract android.app.FragmentTransaction replace(int, android.app.Fragment);
     method public abstract android.app.FragmentTransaction replace(int, android.app.Fragment, java.lang.String);
+    method public abstract android.app.FragmentTransaction setAllowOptimization(boolean);
     method public abstract android.app.FragmentTransaction setBreadCrumbShortTitle(int);
     method public abstract android.app.FragmentTransaction setBreadCrumbShortTitle(java.lang.CharSequence);
     method public abstract android.app.FragmentTransaction setBreadCrumbTitle(int);
@@ -44024,8 +44027,8 @@
     field public static final int ROTATION_ANIMATION_CHANGED = 4096; // 0x1000
     field public static final int ROTATION_ANIMATION_CROSSFADE = 1; // 0x1
     field public static final int ROTATION_ANIMATION_JUMPCUT = 2; // 0x2
-    field public static final int ROTATION_ANIMATION_SEAMLESS = 3; // 0x3
     field public static final int ROTATION_ANIMATION_ROTATE = 0; // 0x0
+    field public static final int ROTATION_ANIMATION_SEAMLESS = 3; // 0x3
     field public static final int SCREEN_BRIGHTNESS_CHANGED = 2048; // 0x800
     field public static final int SCREEN_ORIENTATION_CHANGED = 1024; // 0x400
     field public static final int SOFT_INPUT_ADJUST_NOTHING = 48; // 0x30
diff --git a/api/system-current.txt b/api/system-current.txt
index e6e5d38..fd51a6a 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -103,7 +103,6 @@
     field public static final java.lang.String GET_ACCOUNTS = "android.permission.GET_ACCOUNTS";
     field public static final java.lang.String GET_ACCOUNTS_PRIVILEGED = "android.permission.GET_ACCOUNTS_PRIVILEGED";
     field public static final java.lang.String GET_APP_OPS_STATS = "android.permission.GET_APP_OPS_STATS";
-    field public static final java.lang.String GET_PACKAGE_IMPORTANCE = "android.permission.GET_PACKAGE_IMPORTANCE";
     field public static final java.lang.String GET_PACKAGE_SIZE = "android.permission.GET_PACKAGE_SIZE";
     field public static final java.lang.String GET_PROCESS_STATE_AND_OOM_SCORE = "android.permission.GET_PROCESS_STATE_AND_OOM_SCORE";
     field public static final deprecated java.lang.String GET_TASKS = "android.permission.GET_TASKS";
@@ -4634,6 +4633,7 @@
     method public void onTrimMemory(int);
     method public void onViewCreated(android.view.View, android.os.Bundle);
     method public void onViewStateRestored(android.os.Bundle);
+    method public void postponeEnterTransition();
     method public void registerForContextMenu(android.view.View);
     method public final void requestPermissions(java.lang.String[], int);
     method public void setAllowEnterTransitionOverlap(boolean);
@@ -4659,6 +4659,7 @@
     method public void startActivityForResult(android.content.Intent, int);
     method public void startActivityForResult(android.content.Intent, int, android.os.Bundle);
     method public void startIntentSenderForResult(android.content.IntentSender, int, android.content.Intent, int, int, int, android.os.Bundle) throws android.content.IntentSender.SendIntentException;
+    method public void startPostponedEnterTransition();
     method public void unregisterForContextMenu(android.view.View);
   }
 
@@ -4816,6 +4817,7 @@
     method public abstract android.app.FragmentTransaction remove(android.app.Fragment);
     method public abstract android.app.FragmentTransaction replace(int, android.app.Fragment);
     method public abstract android.app.FragmentTransaction replace(int, android.app.Fragment, java.lang.String);
+    method public abstract android.app.FragmentTransaction setAllowOptimization(boolean);
     method public abstract android.app.FragmentTransaction setBreadCrumbShortTitle(int);
     method public abstract android.app.FragmentTransaction setBreadCrumbShortTitle(java.lang.CharSequence);
     method public abstract android.app.FragmentTransaction setBreadCrumbTitle(int);
@@ -47206,8 +47208,8 @@
     field public static final int ROTATION_ANIMATION_CHANGED = 4096; // 0x1000
     field public static final int ROTATION_ANIMATION_CROSSFADE = 1; // 0x1
     field public static final int ROTATION_ANIMATION_JUMPCUT = 2; // 0x2
-    field public static final int ROTATION_ANIMATION_SEAMLESS = 3; // 0x3
     field public static final int ROTATION_ANIMATION_ROTATE = 0; // 0x0
+    field public static final int ROTATION_ANIMATION_SEAMLESS = 3; // 0x3
     field public static final int SCREEN_BRIGHTNESS_CHANGED = 2048; // 0x800
     field public static final int SCREEN_ORIENTATION_CHANGED = 1024; // 0x400
     field public static final int SOFT_INPUT_ADJUST_NOTHING = 48; // 0x30
diff --git a/api/test-current.txt b/api/test-current.txt
index ee3cb0d..150fbfe 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -4492,6 +4492,7 @@
     method public void onTrimMemory(int);
     method public void onViewCreated(android.view.View, android.os.Bundle);
     method public void onViewStateRestored(android.os.Bundle);
+    method public void postponeEnterTransition();
     method public void registerForContextMenu(android.view.View);
     method public final void requestPermissions(java.lang.String[], int);
     method public void setAllowEnterTransitionOverlap(boolean);
@@ -4517,6 +4518,7 @@
     method public void startActivityForResult(android.content.Intent, int);
     method public void startActivityForResult(android.content.Intent, int, android.os.Bundle);
     method public void startIntentSenderForResult(android.content.IntentSender, int, android.content.Intent, int, int, int, android.os.Bundle) throws android.content.IntentSender.SendIntentException;
+    method public void startPostponedEnterTransition();
     method public void unregisterForContextMenu(android.view.View);
   }
 
@@ -4674,6 +4676,7 @@
     method public abstract android.app.FragmentTransaction remove(android.app.Fragment);
     method public abstract android.app.FragmentTransaction replace(int, android.app.Fragment);
     method public abstract android.app.FragmentTransaction replace(int, android.app.Fragment, java.lang.String);
+    method public abstract android.app.FragmentTransaction setAllowOptimization(boolean);
     method public abstract android.app.FragmentTransaction setBreadCrumbShortTitle(int);
     method public abstract android.app.FragmentTransaction setBreadCrumbShortTitle(java.lang.CharSequence);
     method public abstract android.app.FragmentTransaction setBreadCrumbTitle(int);
@@ -44260,8 +44263,8 @@
     field public static final int ROTATION_ANIMATION_CHANGED = 4096; // 0x1000
     field public static final int ROTATION_ANIMATION_CROSSFADE = 1; // 0x1
     field public static final int ROTATION_ANIMATION_JUMPCUT = 2; // 0x2
-    field public static final int ROTATION_ANIMATION_SEAMLESS = 3; // 0x3
     field public static final int ROTATION_ANIMATION_ROTATE = 0; // 0x0
+    field public static final int ROTATION_ANIMATION_SEAMLESS = 3; // 0x3
     field public static final int SCREEN_BRIGHTNESS_CHANGED = 2048; // 0x800
     field public static final int SCREEN_ORIENTATION_CHANGED = 1024; // 0x400
     field public static final int SOFT_INPUT_ADJUST_NOTHING = 48; // 0x30
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index 0d9be5f..4066f1c 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -3045,6 +3045,7 @@
      * @hide
      */
     @SystemApi
+    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
     public int getPackageImportance(String packageName) {
         try {
             int procState = ActivityManagerNative.getDefault().getPackageProcessState(packageName,
diff --git a/core/java/android/app/ActivityManagerNative.java b/core/java/android/app/ActivityManagerNative.java
index 4de5b42..4df1325 100644
--- a/core/java/android/app/ActivityManagerNative.java
+++ b/core/java/android/app/ActivityManagerNative.java
@@ -1235,6 +1235,16 @@
             return true;
         }
 
+        case UPDATE_DISPLAY_OVERRIDE_CONFIGURATION_TRANSACTION: {
+            data.enforceInterface(IActivityManager.descriptor);
+            final Configuration config = Configuration.CREATOR.createFromParcel(data);
+            final int displayId = data.readInt();
+            final boolean updated = updateDisplayOverrideConfiguration(config, displayId);
+            reply.writeNoException();
+            reply.writeInt(updated ? 1 : 0);
+            return true;
+        }
+
         case SET_REQUESTED_ORIENTATION_TRANSACTION: {
             data.enforceInterface(IActivityManager.descriptor);
             IBinder token = data.readStrongBinder();
@@ -4608,8 +4618,7 @@
         data.recycle();
         return res;
     }
-    public boolean updateConfiguration(Configuration values) throws RemoteException
-    {
+    public boolean updateConfiguration(Configuration values) throws RemoteException {
         Parcel data = Parcel.obtain();
         Parcel reply = Parcel.obtain();
         data.writeInterfaceToken(IActivityManager.descriptor);
@@ -4621,6 +4630,20 @@
         reply.recycle();
         return updated;
     }
+    public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId)
+            throws RemoteException {
+        Parcel data = Parcel.obtain();
+        Parcel reply = Parcel.obtain();
+        data.writeInterfaceToken(IActivityManager.descriptor);
+        values.writeToParcel(data, 0);
+        data.writeInt(displayId);
+        mRemote.transact(UPDATE_DISPLAY_OVERRIDE_CONFIGURATION_TRANSACTION, data, reply, 0);
+        reply.readException();
+        boolean updated = reply.readInt() == 1;
+        data.recycle();
+        reply.recycle();
+        return updated;
+    }
     public void setRequestedOrientation(IBinder token, int requestedOrientation)
             throws RemoteException {
         Parcel data = Parcel.obtain();
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index fbbfec3..e9a200f 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -978,6 +978,10 @@
             sendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0, 0, true /*async*/);
         }
 
+        public void attachAgent(String agent) {
+            sendMessage(H.ATTACH_AGENT, agent);
+        }
+
         public void setSchedulingGroup(int group) {
             // Note: do this immediately, since going into the foreground
             // should happen regardless of what pending work we have to do
@@ -1429,6 +1433,7 @@
         public static final int MULTI_WINDOW_MODE_CHANGED = 152;
         public static final int PICTURE_IN_PICTURE_MODE_CHANGED = 153;
         public static final int LOCAL_VOICE_INTERACTION_STARTED = 154;
+        public static final int ATTACH_AGENT = 155;
 
         String codeToString(int code) {
             if (DEBUG_MESSAGES) {
@@ -1485,6 +1490,7 @@
                     case MULTI_WINDOW_MODE_CHANGED: return "MULTI_WINDOW_MODE_CHANGED";
                     case PICTURE_IN_PICTURE_MODE_CHANGED: return "PICTURE_IN_PICTURE_MODE_CHANGED";
                     case LOCAL_VOICE_INTERACTION_STARTED: return "LOCAL_VOICE_INTERACTION_STARTED";
+                    case ATTACH_AGENT: return "ATTACH_AGENT";
                 }
             }
             return Integer.toString(code);
@@ -1739,6 +1745,8 @@
                 case LOCAL_VOICE_INTERACTION_STARTED:
                     handleLocalVoiceInteractionStarted((IBinder) ((SomeArgs) msg.obj).arg1,
                             (IVoiceInteractor) ((SomeArgs) msg.obj).arg2);
+                case ATTACH_AGENT:
+                    handleAttachAgent((String) msg.obj);
                     break;
             }
             Object obj = msg.obj;
@@ -3008,6 +3016,14 @@
         }
     }
 
+    static final void handleAttachAgent(String agent) {
+        try {
+            VMDebug.attachAgent(agent);
+        } catch (IOException e) {
+            Slog.e(TAG, "Attaching agent failed: " + agent);
+        }
+    }
+
     private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
 
     /**
diff --git a/core/java/android/app/BackStackRecord.java b/core/java/android/app/BackStackRecord.java
index a4b1a1f..cf794c5 100644
--- a/core/java/android/app/BackStackRecord.java
+++ b/core/java/android/app/BackStackRecord.java
@@ -16,21 +16,13 @@
 
 package android.app;
 
-import android.graphics.Rect;
 import android.os.Build;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.text.TextUtils;
-import android.transition.Transition;
-import android.transition.TransitionManager;
-import android.transition.TransitionSet;
-import android.util.ArrayMap;
 import android.util.Log;
 import android.util.LogWriter;
-import android.util.SparseArray;
 import android.view.View;
-import android.view.ViewGroup;
-import android.view.ViewTreeObserver;
 
 import com.android.internal.util.FastPrintWriter;
 
@@ -38,7 +30,6 @@
 import java.io.PrintWriter;
 import java.lang.reflect.Modifier;
 import java.util.ArrayList;
-import java.util.List;
 
 final class BackStackState implements Parcelable {
     final int[] mOps;
@@ -52,6 +43,7 @@
     final CharSequence mBreadCrumbShortTitleText;
     final ArrayList<String> mSharedElementSourceNames;
     final ArrayList<String> mSharedElementTargetNames;
+    final boolean mAllowOptimization;
 
     public BackStackState(FragmentManagerImpl fm, BackStackRecord bse) {
         final int numOps = bse.mOps.size();
@@ -81,6 +73,7 @@
         mBreadCrumbShortTitleText = bse.mBreadCrumbShortTitleText;
         mSharedElementSourceNames = bse.mSharedElementSourceNames;
         mSharedElementTargetNames = bse.mSharedElementTargetNames;
+        mAllowOptimization = bse.mAllowOptimization;
     }
 
     public BackStackState(Parcel in) {
@@ -95,6 +88,7 @@
         mBreadCrumbShortTitleText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
         mSharedElementSourceNames = in.createStringArrayList();
         mSharedElementTargetNames = in.createStringArrayList();
+        mAllowOptimization = in.readInt() != 0;
     }
 
     public BackStackRecord instantiate(FragmentManagerImpl fm) {
@@ -137,6 +131,7 @@
         bse.mBreadCrumbShortTitleText = mBreadCrumbShortTitleText;
         bse.mSharedElementSourceNames = mSharedElementSourceNames;
         bse.mSharedElementTargetNames = mSharedElementTargetNames;
+        bse.mAllowOptimization = mAllowOptimization;
         bse.bumpBackStackNesting(1);
         return bse;
     }
@@ -157,6 +152,7 @@
         TextUtils.writeToParcel(mBreadCrumbShortTitleText, dest, 0);
         dest.writeStringList(mSharedElementSourceNames);
         dest.writeStringList(mSharedElementTargetNames);
+        dest.writeInt(mAllowOptimization ? 1 : 0);
     }
 
     public static final Parcelable.Creator<BackStackState> CREATOR
@@ -175,7 +171,7 @@
  * @hide Entry of an operation on the fragment back stack.
  */
 final class BackStackRecord extends FragmentTransaction implements
-        FragmentManager.BackStackEntry, Runnable {
+        FragmentManager.BackStackEntry, FragmentManagerImpl.OpGenerator {
     static final String TAG = FragmentManagerImpl.TAG;
 
     final FragmentManagerImpl mManager;
@@ -210,6 +206,7 @@
     String mName;
     boolean mCommitted;
     int mIndex = -1;
+    boolean mAllowOptimization;
 
     int mBreadCrumbTitleRes;
     CharSequence mBreadCrumbTitleText;
@@ -352,6 +349,7 @@
 
     public BackStackRecord(FragmentManagerImpl manager) {
         mManager = manager;
+        mAllowOptimization = Build.isAtLeastO();
     }
 
     public int getId() {
@@ -633,6 +631,12 @@
         mManager.execSingleAction(this, true);
     }
 
+    @Override
+    public FragmentTransaction setAllowOptimization(boolean allowOptimization) {
+        mAllowOptimization = allowOptimization;
+        return this;
+    }
+
     int commitInternal(boolean allowStateLoss) {
         if (mCommitted) {
             throw new IllegalStateException("commit already called");
@@ -654,94 +658,177 @@
         return mIndex;
     }
 
-    public void run() {
+    /**
+     * Implementation of {@link android.app.FragmentManagerImpl.OpGenerator}.
+     * This operation is added to the list of pending actions during {@link #commit()}, and
+     * will be executed on the UI thread to run this FragmentTransaction.
+     *
+     * @param records Modified to add this BackStackRecord
+     * @param isRecordPop Modified to add a false (this isn't a pop)
+     * @return true always because the records and isRecordPop will always be changed
+     */
+    @Override
+    public boolean generateOps(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop) {
         if (FragmentManagerImpl.DEBUG) {
             Log.v(TAG, "Run: " + this);
         }
 
+        records.add(this);
+        isRecordPop.add(false);
         if (mAddToBackStack) {
-            if (mIndex < 0) {
-                throw new IllegalStateException("addToBackStack() called after commit()");
-            }
+            mManager.addBackStackState(this);
         }
+        return true;
+    }
 
-        expandReplaceOps();
-        bumpBackStackNesting(1);
-
-        if (mManager.mCurState >= Fragment.CREATED) {
-            SparseArray<FragmentContainerTransition> transitioningFragments = new SparseArray<>();
-            calculateFragments(transitioningFragments);
-            beginTransition(transitioningFragments);
-        }
-
+    boolean interactsWith(int containerId) {
         final int numOps = mOps.size();
         for (int opNum = 0; opNum < numOps; opNum++) {
             final Op op = mOps.get(opNum);
-            Fragment f = op.fragment;
+            if (op.fragment.mContainerId == containerId) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    boolean interactsWith(ArrayList<BackStackRecord> records, int startIndex, int endIndex) {
+        if (endIndex == startIndex) {
+            return false;
+        }
+        final int numOps = mOps.size();
+        int lastContainer = -1;
+        for (int opNum = 0; opNum < numOps; opNum++) {
+            final Op op = mOps.get(opNum);
+            final int container = op.fragment.mContainerId;
+            if (container != 0 && container != lastContainer) {
+                lastContainer = container;
+                for (int i = startIndex; i < endIndex; i++) {
+                    BackStackRecord record = records.get(i);
+                    final int numThoseOps = record.mOps.size();
+                    for (int thoseOpIndex = 0; thoseOpIndex < numThoseOps; thoseOpIndex++) {
+                        final Op thatOp = record.mOps.get(thoseOpIndex);
+                        if (thatOp.fragment.mContainerId == container) {
+                            return true;
+                        }
+                    }
+                }
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Executes the operations contained within this transaction. The Fragment states will only
+     * be modified if optimizations are not allowed.
+     */
+    void executeOps() {
+        final int numOps = mOps.size();
+        for (int opNum = 0; opNum < numOps; opNum++) {
+            final Op op = mOps.get(opNum);
+            final Fragment f = op.fragment;
+            f.setNextTransition(mTransition, mTransitionStyle);
             switch (op.cmd) {
                 case OP_ADD:
-                    f.mNextAnim = op.enterAnim;
+                    f.setNextAnim(op.enterAnim);
                     mManager.addFragment(f, false);
                     break;
                 case OP_REMOVE:
-                    f.mNextAnim = op.exitAnim;
-                    mManager.removeFragment(f, mTransition, mTransitionStyle);
+                    f.setNextAnim(op.exitAnim);
+                    mManager.removeFragment(f);
                     break;
                 case OP_HIDE:
-                    f.mNextAnim = op.exitAnim;
-                    mManager.hideFragment(f, mTransition, mTransitionStyle);
+                    f.setNextAnim(op.exitAnim);
+                    mManager.hideFragment(f);
                     break;
                 case OP_SHOW:
-                    f.mNextAnim = op.enterAnim;
-                    mManager.showFragment(f, mTransition, mTransitionStyle);
+                    f.setNextAnim(op.enterAnim);
+                    mManager.showFragment(f);
                     break;
                 case OP_DETACH:
-                    f.mNextAnim = op.exitAnim;
-                    mManager.detachFragment(f, mTransition, mTransitionStyle);
+                    f.setNextAnim(op.exitAnim);
+                    mManager.detachFragment(f);
                     break;
                 case OP_ATTACH:
-                    f.mNextAnim = op.enterAnim;
-                    mManager.attachFragment(f, mTransition, mTransitionStyle);
+                    f.setNextAnim(op.enterAnim);
+                    mManager.attachFragment(f);
                     break;
                 default:
                     throw new IllegalArgumentException("Unknown cmd: " + op.cmd);
             }
+            if (!mAllowOptimization && op.cmd != OP_ADD) {
+                mManager.moveFragmentToExpectedState(f);
+            }
         }
-
-        mManager.moveToState(mManager.mCurState, mTransition,
-                mTransitionStyle, true);
-
-        if (mAddToBackStack) {
-            mManager.addBackStackState(this);
+        if (!mAllowOptimization) {
+            // Added fragments are added at the end to comply with prior behavior.
+            mManager.moveToState(mManager.mCurState);
         }
     }
 
-    private void expandReplaceOps() {
-        final int numOps = mOps.size();
-
-        boolean hasReplace = false;
-        // Before we do anything, check to see if any replace operations exist:
-        for (int opNum = 0; opNum < numOps; opNum++) {
+    /**
+     * Reverses the execution of the operations within this transaction. The Fragment states will
+     * only be modified if optimizations are not allowed.
+     */
+    void executePopOps() {
+        for (int opNum = mOps.size() - 1; opNum >= 0; opNum--) {
             final Op op = mOps.get(opNum);
-            if (op.cmd == OP_REPLACE) {
-                hasReplace = true;
-                break;
+            Fragment f = op.fragment;
+            f.setNextTransition(FragmentManagerImpl.reverseTransit(mTransition), mTransitionStyle);
+            switch (op.cmd) {
+                case OP_ADD:
+                    f.setNextAnim(op.popExitAnim);
+                    mManager.removeFragment(f);
+                    break;
+                case OP_REMOVE:
+                    f.setNextAnim(op.popEnterAnim);
+                    mManager.addFragment(f, false);
+                    break;
+                case OP_HIDE:
+                    f.setNextAnim(op.popEnterAnim);
+                    mManager.showFragment(f);
+                    break;
+                case OP_SHOW:
+                    f.setNextAnim(op.popExitAnim);
+                    mManager.hideFragment(f);
+                    break;
+                case OP_DETACH:
+                    f.setNextAnim(op.popEnterAnim);
+                    mManager.attachFragment(f);
+                    break;
+                case OP_ATTACH:
+                    f.setNextAnim(op.popExitAnim);
+                    mManager.detachFragment(f);
+                    break;
+                default:
+                    throw new IllegalArgumentException("Unknown cmd: " + op.cmd);
+            }
+            if (!mAllowOptimization && op.cmd != OP_ADD) {
+                mManager.moveFragmentToExpectedState(f);
             }
         }
-
-        if (!hasReplace) {
-            return; // nothing to expand
+        if (!mAllowOptimization) {
+            mManager.moveToState(mManager.mCurState);
         }
+    }
 
-        ArrayList<Fragment> added = (mManager.mAdded == null) ? new ArrayList<Fragment>() :
-                new ArrayList<>(mManager.mAdded);
+    /**
+     * Removes all OP_REPLACE ops and replaces them with the proper add and remove
+     * operations that are equivalent to the replace. This must be called prior to
+     * {@link #executeOps()} or any other call that operations on mOps.
+     *
+     * @param added Initialized to the fragments that are in the mManager.mAdded, this
+     *              will be modified to contain the fragments that will be in mAdded
+     *              after the execution ({@link #executeOps()}.
+     */
+    void expandReplaceOps(ArrayList<Fragment> added) {
         for (int opNum = 0; opNum < mOps.size(); opNum++) {
             final Op op = mOps.get(opNum);
             switch (op.cmd) {
                 case OP_ADD:
                 case OP_ATTACH:
                     added.add(op.fragment);
-                break;
+                    break;
                 case OP_REMOVE:
                 case OP_DETACH:
                     added.remove(op.fragment);
@@ -782,920 +869,29 @@
         }
     }
 
-    private static void setFirstOut(SparseArray<FragmentContainerTransition> transitioningFragments,
-                            Fragment fragment, boolean isPop) {
-        if (fragment != null) {
-            int containerId = fragment.mContainerId;
-            if (containerId != 0 && !fragment.isHidden()) {
-                FragmentContainerTransition fragments = transitioningFragments.get(containerId);
-                if (fragment.isAdded() && fragment.getView() != null && (fragments == null ||
-                        fragments.firstOut == null)) {
-                    if (fragments == null) {
-                        fragments = new FragmentContainerTransition();
-                        transitioningFragments.put(containerId, fragments);
-                    }
-                    fragments.firstOut = fragment;
-                    fragments.firstOutIsPop = isPop;
-                }
-                if (fragments != null && fragments.lastIn == fragment) {
-                    fragments.lastIn = null;
-                }
-            }
-        }
-    }
-
-    private void setLastIn(SparseArray<FragmentContainerTransition> transitioningFragments,
-            Fragment fragment, boolean isPop) {
-        if (fragment != null) {
-            int containerId = fragment.mContainerId;
-            if (containerId != 0) {
-                FragmentContainerTransition fragments = transitioningFragments.get(containerId);
-                if (!fragment.isAdded()) {
-                    if (fragments == null) {
-                        fragments = new FragmentContainerTransition();
-                        transitioningFragments.put(containerId, fragments);
-                    }
-                    fragments.lastIn = fragment;
-                    fragments.lastInIsPop = isPop;
-                }
-                if (fragments != null && fragments.firstOut == fragment) {
-                    fragments.firstOut = null;
-                }
-            }
-            /**
-             * Ensure that fragments that are entering are at least at the CREATED state
-             * so that they may load Transitions using TransitionInflater.
-             */
-            if (fragment.mState < Fragment.CREATED && mManager.mCurState >= Fragment.CREATED &&
-                    mManager.mHost.getContext().getApplicationInfo().targetSdkVersion >=
-                    Build.VERSION_CODES.N) {
-                mManager.makeActive(fragment);
-                mManager.moveToState(fragment, Fragment.CREATED, 0, 0, false);
-            }
-        }
-    }
-
-    /**
-     * Finds the first removed fragment and last added fragments when going forward.
-     * If none of the fragments have transitions, then both lists will be empty.
-     *
-     * @param transitioningFragments Keyed on the container ID, the first fragments to be removed,
-     *                               and last fragments to be added. This will be modified by
-     *                               this method.
-     */
-    private void calculateFragments(
-            SparseArray<FragmentContainerTransition> transitioningFragments) {
-        if (!mManager.mContainer.onHasView()) {
-            return; // nothing to see, so no transitions
-        }
-        final int numOps = mOps.size();
-        for (int opNum = 0; opNum < numOps; opNum++) {
+    boolean isPostponed() {
+        for (int opNum = 0; opNum < mOps.size(); opNum++) {
             final Op op = mOps.get(opNum);
-            switch (op.cmd) {
-                case OP_ADD:
-                case OP_SHOW:
-                case OP_ATTACH:
-                    setLastIn(transitioningFragments, op.fragment, false);
-                    break;
-                case OP_REMOVE:
-                case OP_HIDE:
-                case OP_DETACH:
-                    setFirstOut(transitioningFragments, op.fragment, false);
-                    break;
-            }
-        }
-    }
-
-    /**
-     * Finds the first removed fragment and last added fragments when popping the back stack.
-     * If none of the fragments have transitions, then both lists will be empty.
-     *
-     * @param transitioningFragments Keyed on the container ID, the first fragments to be removed,
-     *                               and last fragments to be added. This will be modified by
-     *                               this method.
-     */
-    public void calculateBackFragments(
-            SparseArray<FragmentContainerTransition> transitioningFragments) {
-        if (!mManager.mContainer.onHasView()) {
-            return; // nothing to see, so no transitions
-        }
-        final int numOps = mOps.size();
-        for (int opNum = numOps - 1; opNum >= 0; opNum--) {
-            final Op op = mOps.get(opNum);
-            switch (op.cmd) {
-                case OP_ADD:
-                case OP_SHOW:
-                case OP_ATTACH:
-                    setFirstOut(transitioningFragments, op.fragment, true);
-                    break;
-                case OP_REMOVE:
-                case OP_HIDE:
-                case OP_DETACH:
-                    setLastIn(transitioningFragments, op.fragment, true);
-                    break;
-            }
-        }
-    }
-
-    /**
-     * When custom fragment transitions are used, this sets up the state for each transition
-     * and begins the transition. A different transition is started for each fragment container
-     * and consists of up to 3 different transitions: the exit transition, a shared element
-     * transition and an enter transition.
-     *
-     * <p>The exit transition operates against the leaf nodes of the first fragment
-     * with a view that was removed. If no such fragment was removed, then no exit
-     * transition is executed. The exit transition comes from the outgoing fragment.</p>
-     *
-     * <p>The enter transition operates against the last fragment that was added. If
-     * that fragment does not have a view or no fragment was added, then no enter
-     * transition is executed. The enter transition comes from the incoming fragment.</p>
-     *
-     * <p>The shared element transition operates against all views and comes either
-     * from the outgoing fragment or the incoming fragment, depending on whether this
-     * is going forward or popping the back stack. When going forward, the incoming
-     * fragment's enter shared element transition is used, but when going back, the
-     * outgoing fragment's return shared element transition is used. Shared element
-     * transitions only operate if there is both an incoming and outgoing fragment.</p>
-     *
-     * @param containers The first in and last out fragments that are transitioning.
-     * @return The TransitionState used to complete the operation of the transition
-     * in {@link #setNameOverrides(android.app.BackStackRecord.TransitionState, java.util.ArrayList,
-     * java.util.ArrayList)}.
-     */
-    private TransitionState beginTransition(SparseArray<FragmentContainerTransition> containers) {
-        TransitionState state = new TransitionState();
-
-        // Adding a non-existent target view makes sure that the transitions don't target
-        // any views by default. They'll only target the views we tell add. If we don't
-        // add any, then no views will be targeted.
-        state.nonExistentView = new View(mManager.mHost.getContext());
-
-        final int numContainers = containers.size();
-        for (int i = 0; i < numContainers; i++) {
-            int containerId = containers.keyAt(i);
-            FragmentContainerTransition containerTransition = containers.valueAt(i);
-            configureTransitions(containerId, state, containerTransition);
-        }
-        return state;
-    }
-
-    private static Transition cloneTransition(Transition transition) {
-        if (transition != null) {
-            transition = transition.clone();
-        }
-        return transition;
-    }
-
-    private static Transition getEnterTransition(Fragment inFragment, boolean isBack) {
-        if (inFragment == null) {
-            return null;
-        }
-        return cloneTransition(isBack ? inFragment.getReenterTransition() :
-                inFragment.getEnterTransition());
-    }
-
-    private static Transition getExitTransition(Fragment outFragment, boolean isBack) {
-        if (outFragment == null) {
-            return null;
-        }
-        return cloneTransition(isBack ? outFragment.getReturnTransition() :
-                outFragment.getExitTransition());
-    }
-
-    private static TransitionSet getSharedElementTransition(Fragment inFragment,
-            Fragment outFragment, boolean isBack) {
-        if (inFragment == null || outFragment == null) {
-            return null;
-        }
-        Transition transition = cloneTransition(isBack
-                ? outFragment.getSharedElementReturnTransition()
-                : inFragment.getSharedElementEnterTransition());
-        if (transition == null) {
-            return null;
-        }
-        TransitionSet transitionSet = new TransitionSet();
-        transitionSet.addTransition(transition);
-        return transitionSet;
-    }
-
-    private static ArrayList<View> captureExitingViews(Transition exitTransition,
-            Fragment outFragment, ArrayMap<String, View> namedViews, View nonExistentView) {
-        ArrayList<View> viewList = null;
-        if (exitTransition != null) {
-            viewList = new ArrayList<View>();
-            View root = outFragment.getView();
-            root.captureTransitioningViews(viewList);
-            if (namedViews != null) {
-                viewList.removeAll(namedViews.values());
-            }
-            if (!viewList.isEmpty()) {
-                viewList.add(nonExistentView);
-                addTargets(exitTransition, viewList);
-            }
-        }
-        return viewList;
-    }
-
-    private ArrayMap<String, View> remapSharedElements(TransitionState state, Fragment outFragment,
-            boolean isBack) {
-        ArrayMap<String, View> namedViews = new ArrayMap<String, View>();
-        if (mSharedElementSourceNames != null) {
-            outFragment.getView().findNamedViews(namedViews);
-            if (isBack) {
-                namedViews.retainAll(mSharedElementTargetNames);
-            } else {
-                namedViews = remapNames(mSharedElementSourceNames, mSharedElementTargetNames,
-                        namedViews);
-            }
-        }
-
-        if (isBack) {
-            outFragment.mEnterTransitionCallback.onMapSharedElements(
-                    mSharedElementTargetNames, namedViews);
-            setBackNameOverrides(state, namedViews, false);
-        } else {
-            outFragment.mExitTransitionCallback.onMapSharedElements(
-                    mSharedElementTargetNames, namedViews);
-            setNameOverrides(state, namedViews, false);
-        }
-
-        return namedViews;
-    }
-
-    /**
-     * Prepares the enter transition by adding a non-existent view to the transition's target list
-     * and setting it epicenter callback. By adding a non-existent view to the target list,
-     * we can prevent any view from being targeted at the beginning of the transition.
-     * We will add to the views before the end state of the transition is captured so that the
-     * views will appear. At the start of the transition, we clear the list of targets so that
-     * we can restore the state of the transition and use it again.
-     *
-     * <p>The shared element transition maps its shared elements immediately prior to
-     * capturing the final state of the Transition.</p>
-     */
-    private ArrayList<View> addTransitionTargets(final TransitionState state,
-            final Transition enterTransition, final TransitionSet sharedElementTransition,
-            final Transition exitTransition, final Transition overallTransition,
-            final View container, final Fragment inFragment, final Fragment outFragment,
-            final ArrayList<View> hiddenFragmentViews, final boolean isBack,
-            final ArrayList<View> sharedElementTargets) {
-        if (enterTransition == null && sharedElementTransition == null &&
-                overallTransition == null) {
-            return null;
-        }
-        final ArrayList<View> enteringViews = new ArrayList<View>();
-        container.getViewTreeObserver().addOnPreDrawListener(
-                new ViewTreeObserver.OnPreDrawListener() {
-                    @Override
-                    public boolean onPreDraw() {
-                        container.getViewTreeObserver().removeOnPreDrawListener(this);
-
-                        // Don't include any newly-hidden fragments in the transition.
-                        if (inFragment != null) {
-                            excludeHiddenFragments(hiddenFragmentViews, inFragment.mContainerId,
-                                    overallTransition);
-                        }
-
-                        ArrayMap<String, View> namedViews = null;
-                        if (sharedElementTransition != null) {
-                            namedViews = mapSharedElementsIn(state, isBack, inFragment);
-                            removeTargets(sharedElementTransition, sharedElementTargets);
-                            // keep the nonExistentView as excluded so the list doesn't get emptied
-                            sharedElementTargets.remove(state.nonExistentView);
-                            excludeViews(exitTransition, sharedElementTransition,
-                                    sharedElementTargets, false);
-                            excludeViews(enterTransition, sharedElementTransition,
-                                    sharedElementTargets, false);
-
-                            setSharedElementTargets(sharedElementTransition,
-                                    state.nonExistentView, namedViews, sharedElementTargets);
-
-                            setEpicenterIn(namedViews, state);
-
-                            callSharedElementEnd(state, inFragment, outFragment, isBack,
-                                    namedViews);
-                        }
-
-                        if (enterTransition != null) {
-                            enterTransition.removeTarget(state.nonExistentView);
-                            View view = inFragment.getView();
-                            if (view != null) {
-                                view.captureTransitioningViews(enteringViews);
-                                if (namedViews != null) {
-                                    enteringViews.removeAll(namedViews.values());
-                                }
-                                enteringViews.add(state.nonExistentView);
-                                // We added this earlier to prevent any views being targeted.
-                                addTargets(enterTransition, enteringViews);
-                            }
-                            setSharedElementEpicenter(enterTransition, state);
-                        }
-
-                        excludeViews(exitTransition, enterTransition, enteringViews, true);
-                        excludeViews(exitTransition, sharedElementTransition, sharedElementTargets,
-                                true);
-                        excludeViews(enterTransition, sharedElementTransition, sharedElementTargets,
-                                true);
-                        return true;
-                    }
-                });
-        return enteringViews;
-    }
-
-    private void callSharedElementEnd(TransitionState state, Fragment inFragment,
-            Fragment outFragment, boolean isBack, ArrayMap<String, View> namedViews) {
-        SharedElementCallback sharedElementCallback = isBack ?
-                outFragment.mEnterTransitionCallback :
-                inFragment.mEnterTransitionCallback;
-        ArrayList<String> names = new ArrayList<String>(namedViews.keySet());
-        ArrayList<View> views = new ArrayList<View>(namedViews.values());
-        sharedElementCallback.onSharedElementEnd(names, views, null);
-    }
-
-    private void setEpicenterIn(ArrayMap<String, View> namedViews, TransitionState state) {
-        if (mSharedElementTargetNames != null && !namedViews.isEmpty()) {
-            // now we know the epicenter of the entering transition.
-            View epicenter = namedViews
-                    .get(mSharedElementTargetNames.get(0));
-            if (epicenter != null) {
-                state.enteringEpicenterView = epicenter;
-            }
-        }
-    }
-
-    private ArrayMap<String, View> mapSharedElementsIn(TransitionState state,
-            boolean isBack, Fragment inFragment) {
-        // Now map the shared elements in the incoming fragment
-        ArrayMap<String, View> namedViews = mapEnteringSharedElements(state, inFragment, isBack);
-
-        // remap shared elements and set the name mapping used
-        // in the shared element transition.
-        if (isBack) {
-            inFragment.mExitTransitionCallback.onMapSharedElements(
-                    mSharedElementTargetNames, namedViews);
-            setBackNameOverrides(state, namedViews, true);
-        } else {
-            inFragment.mEnterTransitionCallback.onMapSharedElements(
-                    mSharedElementTargetNames, namedViews);
-            setNameOverrides(state, namedViews, true);
-        }
-        return namedViews;
-    }
-
-    private static Transition mergeTransitions(Transition enterTransition,
-            Transition exitTransition, Transition sharedElementTransition, Fragment inFragment,
-            boolean isBack) {
-        boolean overlap = true;
-        if (enterTransition != null && exitTransition != null && inFragment != null) {
-            overlap = isBack ? inFragment.getAllowReturnTransitionOverlap() :
-                    inFragment.getAllowEnterTransitionOverlap();
-        }
-
-        // Wrap the transitions. Explicit targets like in enter and exit will cause the
-        // views to be targeted regardless of excluded views. If that happens, then the
-        // excluded fragments views (hidden fragments) will still be in the transition.
-
-        Transition transition;
-        if (overlap) {
-            // Regular transition -- do it all together
-            TransitionSet transitionSet = new TransitionSet();
-            if (enterTransition != null) {
-                transitionSet.addTransition(enterTransition);
-            }
-            if (exitTransition != null) {
-                transitionSet.addTransition(exitTransition);
-            }
-            if (sharedElementTransition != null) {
-                transitionSet.addTransition(sharedElementTransition);
-            }
-            transition = transitionSet;
-        } else {
-            // First do exit, then enter, but allow shared element transition to happen
-            // during both.
-            Transition staggered = null;
-            if (exitTransition != null && enterTransition != null) {
-                staggered = new TransitionSet()
-                        .addTransition(exitTransition)
-                        .addTransition(enterTransition)
-                        .setOrdering(TransitionSet.ORDERING_SEQUENTIAL);
-            } else if (exitTransition != null) {
-                staggered = exitTransition;
-            } else if (enterTransition != null) {
-                staggered = enterTransition;
-            }
-            if (sharedElementTransition != null) {
-                TransitionSet together = new TransitionSet();
-                if (staggered != null) {
-                    together.addTransition(staggered);
-                }
-                together.addTransition(sharedElementTransition);
-                transition = together;
-            } else {
-                transition = staggered;
-            }
-        }
-        return transition;
-    }
-
-    /**
-     * Configures custom transitions for a specific fragment container.
-     *
-     * @param containerId The container ID of the fragments to configure the transition for.
-     * @param state The Transition State keeping track of the executing transitions.
-     * @param transitioningFragments The first out and last in fragments for the fragment container.
-     */
-    private void configureTransitions(int containerId, TransitionState state,
-            FragmentContainerTransition transitioningFragments) {
-        ViewGroup sceneRoot = (ViewGroup) mManager.mContainer.onFindViewById(containerId);
-        if (sceneRoot != null) {
-            final Fragment inFragment = transitioningFragments.lastIn;
-            final Fragment outFragment = transitioningFragments.firstOut;
-
-            Transition enterTransition =
-                    getEnterTransition(inFragment, transitioningFragments.lastInIsPop);
-            TransitionSet sharedElementTransition = getSharedElementTransition(inFragment,
-                    outFragment, transitioningFragments.lastInIsPop);
-            Transition exitTransition =
-                    getExitTransition(outFragment, transitioningFragments.firstOutIsPop);
-
-            if (enterTransition == null && sharedElementTransition == null &&
-                    exitTransition == null) {
-                return; // no transitions!
-            }
-            if (enterTransition != null) {
-                enterTransition.addTarget(state.nonExistentView);
-            }
-            ArrayMap<String, View> namedViews = null;
-            ArrayList<View> sharedElementTargets = new ArrayList<View>();
-            if (sharedElementTransition != null) {
-                namedViews = remapSharedElements(state, outFragment,
-                        transitioningFragments.firstOutIsPop);
-                setSharedElementTargets(sharedElementTransition,
-                        state.nonExistentView, namedViews, sharedElementTargets);
-
-                // Notify the start of the transition.
-                SharedElementCallback callback = transitioningFragments.lastInIsPop ?
-                        outFragment.mEnterTransitionCallback :
-                        inFragment.mEnterTransitionCallback;
-                ArrayList<String> names = new ArrayList<String>(namedViews.keySet());
-                ArrayList<View> views = new ArrayList<View>(namedViews.values());
-                callback.onSharedElementStart(names, views, null);
-            }
-
-            ArrayList<View> exitingViews = captureExitingViews(exitTransition, outFragment,
-                    namedViews, state.nonExistentView);
-            if (exitingViews == null || exitingViews.isEmpty()) {
-                exitTransition = null;
-            }
-            excludeViews(enterTransition, exitTransition, exitingViews, true);
-            excludeViews(enterTransition, sharedElementTransition, sharedElementTargets, true);
-            excludeViews(exitTransition, sharedElementTransition, sharedElementTargets, true);
-
-            // Set the epicenter of the exit transition
-            if (mSharedElementTargetNames != null && namedViews != null) {
-                View epicenterView = namedViews.get(mSharedElementTargetNames.get(0));
-                if (epicenterView != null) {
-                    if (exitTransition != null) {
-                        setEpicenter(exitTransition, epicenterView);
-                    }
-                    if (sharedElementTransition != null) {
-                        setEpicenter(sharedElementTransition, epicenterView);
-                    }
-                }
-            }
-
-            Transition transition = mergeTransitions(enterTransition, exitTransition,
-                    sharedElementTransition, inFragment, transitioningFragments.lastInIsPop);
-
-            if (transition != null) {
-                ArrayList<View> hiddenFragments = new ArrayList<View>();
-                ArrayList<View> enteringViews = addTransitionTargets(state, enterTransition,
-                        sharedElementTransition, exitTransition, transition, sceneRoot, inFragment,
-                        outFragment, hiddenFragments, transitioningFragments.lastInIsPop,
-                        sharedElementTargets);
-
-                transition.setNameOverrides(state.nameOverrides);
-                // We want to exclude hidden views later, so we need a non-null list in the
-                // transition now.
-                transition.excludeTarget(state.nonExistentView, true);
-                // Now exclude all currently hidden fragments.
-                excludeHiddenFragments(hiddenFragments, containerId, transition);
-                TransitionManager.beginDelayedTransition(sceneRoot, transition);
-                // Remove the view targeting after the transition starts
-                removeTargetedViewsFromTransitions(sceneRoot, state.nonExistentView,
-                        enterTransition, enteringViews, exitTransition, exitingViews,
-                        sharedElementTransition, sharedElementTargets, transition,
-                        hiddenFragments);
-            }
-        }
-    }
-
-    /**
-     * Finds all children of the shared elements and sets the wrapping TransitionSet
-     * targets to point to those. It also limits transitions that have no targets to the
-     * specific shared elements. This allows developers to target child views of the
-     * shared elements specifically, but this doesn't happen by default.
-     */
-    private static void setSharedElementTargets(TransitionSet transition,
-            View nonExistentView, ArrayMap<String, View> namedViews,
-            ArrayList<View> sharedElementTargets) {
-        sharedElementTargets.clear();
-        sharedElementTargets.addAll(namedViews.values());
-
-        final List<View> views = transition.getTargets();
-        views.clear();
-        final int count = sharedElementTargets.size();
-        for (int i = 0; i < count; i++) {
-            final View view = sharedElementTargets.get(i);
-            bfsAddViewChildren(views, view);
-        }
-        sharedElementTargets.add(nonExistentView);
-        addTargets(transition, sharedElementTargets);
-    }
-
-    /**
-     * Uses a breadth-first scheme to add startView and all of its children to views.
-     * It won't add a child if it is already in views.
-     */
-    private static void bfsAddViewChildren(final List<View> views, final View startView) {
-        final int startIndex = views.size();
-        if (containedBeforeIndex(views, startView, startIndex)) {
-            return; // This child is already in the list, so all its children are also.
-        }
-        views.add(startView);
-        for (int index = startIndex; index < views.size(); index++) {
-            final View view = views.get(index);
-            if (view instanceof ViewGroup) {
-                ViewGroup viewGroup = (ViewGroup) view;
-                final int childCount =  viewGroup.getChildCount();
-                for (int childIndex = 0; childIndex < childCount; childIndex++) {
-                    final View child = viewGroup.getChildAt(childIndex);
-                    if (!containedBeforeIndex(views, child, startIndex)) {
-                        views.add(child);
-                    }
-                }
-            }
-        }
-    }
-
-    /**
-     * Does a linear search through views for view, limited to maxIndex.
-     */
-    private static boolean containedBeforeIndex(final List<View> views, final View view,
-            final int maxIndex) {
-        for (int i = 0; i < maxIndex; i++) {
-            if (views.get(i) == view) {
+            if (isFragmentPostponed(op)) {
                 return true;
             }
         }
         return false;
     }
 
-    private static void excludeViews(Transition transition, Transition fromTransition,
-            ArrayList<View> views, boolean exclude) {
-        if (transition != null) {
-            final int viewCount = fromTransition == null ? 0 : views.size();
-            for (int i = 0; i < viewCount; i++) {
-                transition.excludeTarget(views.get(i), exclude);
-            }
-        }
-    }
-
-    /**
-     * After the transition has started, remove all targets that we added to the transitions
-     * so that the transitions are left in a clean state.
-     */
-    private void removeTargetedViewsFromTransitions(
-            final ViewGroup sceneRoot, final View nonExistingView,
-            final Transition enterTransition, final ArrayList<View> enteringViews,
-            final Transition exitTransition, final ArrayList<View> exitingViews,
-            final Transition sharedElementTransition, final ArrayList<View> sharedElementTargets,
-            final Transition overallTransition, final ArrayList<View> hiddenViews) {
-        if (overallTransition != null) {
-            sceneRoot.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
-                @Override
-                public boolean onPreDraw() {
-                    sceneRoot.getViewTreeObserver().removeOnPreDrawListener(this);
-                    if (enterTransition != null) {
-                        removeTargets(enterTransition, enteringViews);
-                        excludeViews(enterTransition, exitTransition, exitingViews, false);
-                        excludeViews(enterTransition, sharedElementTransition, sharedElementTargets,
-                                false);
-                    }
-                    if (exitTransition != null) {
-                        removeTargets(exitTransition, exitingViews);
-                        excludeViews(exitTransition, enterTransition, enteringViews, false);
-                        excludeViews(exitTransition, sharedElementTransition, sharedElementTargets,
-                                false);
-                    }
-                    if (sharedElementTransition != null) {
-                        removeTargets(sharedElementTransition, sharedElementTargets);
-                    }
-                    int numViews = hiddenViews.size();
-                    for (int i = 0; i < numViews; i++) {
-                        overallTransition.excludeTarget(hiddenViews.get(i), false);
-                    }
-                    overallTransition.excludeTarget(nonExistingView, false);
-                    return true;
-                }
-            });
-        }
-    }
-
-    /**
-     * This method removes the views from transitions that target ONLY those views.
-     * The views list should match those added in addTargets and should contain
-     * one view that is not in the view hierarchy (state.nonExistentView).
-     */
-    public static void removeTargets(Transition transition, ArrayList<View> views) {
-        if (transition instanceof TransitionSet) {
-            TransitionSet set = (TransitionSet) transition;
-            int numTransitions = set.getTransitionCount();
-            for (int i = 0; i < numTransitions; i++) {
-                Transition child = set.getTransitionAt(i);
-                removeTargets(child, views);
-            }
-        } else if (!hasSimpleTarget(transition)) {
-            List<View> targets = transition.getTargets();
-            if (targets != null && targets.size() == views.size() &&
-                    targets.containsAll(views)) {
-                // We have an exact match. We must have added these earlier in addTargets
-                for (int i = views.size() - 1; i >= 0; i--) {
-                    transition.removeTarget(views.get(i));
-                }
-            }
-        }
-    }
-
-    /**
-     * This method adds views as targets to the transition, but only if the transition
-     * doesn't already have a target. It is best for views to contain one View object
-     * that does not exist in the view hierarchy (state.nonExistentView) so that
-     * when they are removed later, a list match will suffice to remove the targets.
-     * Otherwise, if you happened to have targeted the exact views for the transition,
-     * the removeTargets call will remove them unexpectedly.
-     */
-    public static void addTargets(Transition transition, ArrayList<View> views) {
-        if (transition instanceof TransitionSet) {
-            TransitionSet set = (TransitionSet) transition;
-            int numTransitions = set.getTransitionCount();
-            for (int i = 0; i < numTransitions; i++) {
-                Transition child = set.getTransitionAt(i);
-                addTargets(child, views);
-            }
-        } else if (!hasSimpleTarget(transition)) {
-            List<View> targets = transition.getTargets();
-            if (isNullOrEmpty(targets)) {
-                // We can just add the target views
-                int numViews = views.size();
-                for (int i = 0; i < numViews; i++) {
-                    transition.addTarget(views.get(i));
-                }
-            }
-        }
-    }
-
-    private static boolean hasSimpleTarget(Transition transition) {
-        return !isNullOrEmpty(transition.getTargetIds()) ||
-                !isNullOrEmpty(transition.getTargetNames()) ||
-                !isNullOrEmpty(transition.getTargetTypes());
-    }
-
-    private static boolean isNullOrEmpty(List list) {
-        return list == null || list.isEmpty();
-    }
-
-    /**
-     * Remaps a name-to-View map, substituting different names for keys.
-     *
-     * @param inMap A list of keys found in the map, in the order in toGoInMap
-     * @param toGoInMap A list of keys to use for the new map, in the order of inMap
-     * @param namedViews The current mapping
-     * @return a new Map after it has been mapped with the new names as keys.
-     */
-    private static ArrayMap<String, View> remapNames(ArrayList<String> inMap,
-            ArrayList<String> toGoInMap, ArrayMap<String, View> namedViews) {
-        ArrayMap<String, View> remappedViews = new ArrayMap<String, View>();
-        if (!namedViews.isEmpty()) {
-            int numKeys = inMap.size();
-            for (int i = 0; i < numKeys; i++) {
-                View view = namedViews.get(inMap.get(i));
-
-                if (view != null) {
-                    remappedViews.put(toGoInMap.get(i), view);
-                }
-            }
-        }
-        return remappedViews;
-    }
-
-    /**
-     * Maps shared elements to views in the entering fragment.
-     *
-     * @param state The transition State as returned from {@link #beginTransition(
-     * android.util.SparseArray, android.util.SparseArray, boolean)}.
-     * @param inFragment The last fragment to be added.
-     * @param isBack true if this is popping the back stack or false if this is a
-     *               forward operation.
-     */
-    private ArrayMap<String, View> mapEnteringSharedElements(TransitionState state,
-            Fragment inFragment, boolean isBack) {
-        ArrayMap<String, View> namedViews = new ArrayMap<String, View>();
-        View root = inFragment.getView();
-        if (root != null) {
-            if (mSharedElementSourceNames != null) {
-                root.findNamedViews(namedViews);
-                if (isBack) {
-                    namedViews = remapNames(mSharedElementSourceNames,
-                            mSharedElementTargetNames, namedViews);
-                } else {
-                    namedViews.retainAll(mSharedElementTargetNames);
-                }
-            }
-        }
-        return namedViews;
-    }
-
-    private void excludeHiddenFragments(final ArrayList<View> hiddenFragmentViews, int containerId,
-            Transition transition) {
-        if (mManager.mAdded != null) {
-            for (int i = 0; i < mManager.mAdded.size(); i++) {
-                Fragment fragment = mManager.mAdded.get(i);
-                if (fragment.mView != null && fragment.mContainer != null &&
-                        fragment.mContainerId == containerId) {
-                    if (fragment.mHidden) {
-                        if (!hiddenFragmentViews.contains(fragment.mView)) {
-                            transition.excludeTarget(fragment.mView, true);
-                            hiddenFragmentViews.add(fragment.mView);
-                        }
-                    } else {
-                        transition.excludeTarget(fragment.mView, false);
-                        hiddenFragmentViews.remove(fragment.mView);
-                    }
-                }
-            }
-        }
-    }
-
-    private static void setEpicenter(Transition transition, View view) {
-        final Rect epicenter = new Rect();
-        view.getBoundsOnScreen(epicenter);
-
-        transition.setEpicenterCallback(new Transition.EpicenterCallback() {
-            @Override
-            public Rect onGetEpicenter(Transition transition) {
-                return epicenter;
-            }
-        });
-    }
-
-    private void setSharedElementEpicenter(Transition transition, final TransitionState state) {
-        transition.setEpicenterCallback(new Transition.EpicenterCallback() {
-            private Rect mEpicenter;
-
-            @Override
-            public Rect onGetEpicenter(Transition transition) {
-                if (mEpicenter == null && state.enteringEpicenterView != null) {
-                    mEpicenter = new Rect();
-                    state.enteringEpicenterView.getBoundsOnScreen(mEpicenter);
-                }
-                return mEpicenter;
-            }
-        });
-    }
-
-    public TransitionState popFromBackStack(boolean doStateMove, TransitionState state,
-            SparseArray<FragmentContainerTransition> transitioningFragments) {
-        if (FragmentManagerImpl.DEBUG) {
-            Log.v(TAG, "popFromBackStack: " + this);
-            LogWriter logw = new LogWriter(Log.VERBOSE, TAG);
-            PrintWriter pw = new FastPrintWriter(logw, false, 1024);
-            dump("  ", null, pw, null);
-            pw.flush();
-        }
-
-        if (mManager.mCurState >= Fragment.CREATED) {
-            if (state == null) {
-                if (transitioningFragments.size() != 0) {
-                    state = beginTransition(transitioningFragments);
-                }
-            } else if (!doStateMove) {
-                setNameOverrides(state, mSharedElementTargetNames, mSharedElementSourceNames);
-            }
-        }
-
-        bumpBackStackNesting(-1);
-
-        final int numOps = mOps.size();
-        for (int opNum = numOps - 1; opNum >= 0; opNum--) {
+    void setOnStartPostponedListener(Fragment.OnStartEnterTransitionListener listener) {
+        for (int opNum = 0; opNum < mOps.size(); opNum++) {
             final Op op = mOps.get(opNum);
-            Fragment f = op.fragment;
-            switch (op.cmd) {
-                case OP_ADD:
-                    f.mNextAnim = op.popExitAnim;
-                    mManager.removeFragment(f,
-                            FragmentManagerImpl.reverseTransit(mTransition),
-                            mTransitionStyle);
-                    break;
-                case OP_REMOVE:
-                    f.mNextAnim = op.popEnterAnim;
-                    mManager.addFragment(f, false);
-                    break;
-                case OP_HIDE:
-                    f.mNextAnim = op.popEnterAnim;
-                    mManager.showFragment(f,
-                            FragmentManagerImpl.reverseTransit(mTransition), mTransitionStyle);
-                    break;
-                case OP_SHOW:
-                    f.mNextAnim = op.popExitAnim;
-                    mManager.hideFragment(f,
-                            FragmentManagerImpl.reverseTransit(mTransition), mTransitionStyle);
-                    break;
-                case OP_DETACH:
-                    f.mNextAnim = op.popEnterAnim;
-                    mManager.attachFragment(f,
-                            FragmentManagerImpl.reverseTransit(mTransition), mTransitionStyle);
-                    break;
-                case OP_ATTACH:
-                    f.mNextAnim = op.popExitAnim;
-                    mManager.detachFragment(f,
-                            FragmentManagerImpl.reverseTransit(mTransition), mTransitionStyle);
-                    break;
-                default:
-                    throw new IllegalArgumentException("Unknown cmd: " + op.cmd);
-            }
-        }
-
-        if (doStateMove) {
-            mManager.moveToState(mManager.mCurState,
-                    FragmentManagerImpl.reverseTransit(mTransition), mTransitionStyle, true);
-            state = null;
-        }
-
-        if (mIndex >= 0) {
-            mManager.freeBackStackIndex(mIndex);
-            mIndex = -1;
-        }
-        return state;
-    }
-
-    private static void setNameOverride(ArrayMap<String, String> overrides,
-            String source, String target) {
-        if (source != null && target != null && !source.equals(target)) {
-            for (int index = 0; index < overrides.size(); index++) {
-                if (source.equals(overrides.valueAt(index))) {
-                    overrides.setValueAt(index, target);
-                    return;
-                }
-            }
-            overrides.put(source, target);
-        }
-    }
-
-    private static void setNameOverrides(TransitionState state, ArrayList<String> sourceNames,
-            ArrayList<String> targetNames) {
-        if (sourceNames != null && targetNames != null) {
-            for (int i = 0; i < sourceNames.size(); i++) {
-                String source = sourceNames.get(i);
-                String target = targetNames.get(i);
-                setNameOverride(state.nameOverrides, source, target);
+            if (isFragmentPostponed(op)) {
+                op.fragment.setOnStartEnterTransitionListener(listener);
             }
         }
     }
 
-    private void setBackNameOverrides(TransitionState state, ArrayMap<String, View> namedViews,
-            boolean isEnd) {
-        int targetCount = mSharedElementTargetNames == null ? 0 : mSharedElementTargetNames.size();
-        int sourceCount = mSharedElementSourceNames == null ? 0 : mSharedElementSourceNames.size();
-        final int count = Math.min(targetCount, sourceCount);
-        for (int i = 0; i < count; i++) {
-            String source = mSharedElementSourceNames.get(i);
-            String originalTarget = mSharedElementTargetNames.get(i);
-            View view = namedViews.get(originalTarget);
-            if (view != null) {
-                String target = view.getTransitionName();
-                if (isEnd) {
-                    setNameOverride(state.nameOverrides, source, target);
-                } else {
-                    setNameOverride(state.nameOverrides, target, source);
-                }
-            }
-        }
-    }
-
-    private void setNameOverrides(TransitionState state, ArrayMap<String, View> namedViews,
-            boolean isEnd) {
-        int count = namedViews == null ? 0 : namedViews.size();
-        for (int i = 0; i < count; i++) {
-            String source = namedViews.keyAt(i);
-            String target = namedViews.valueAt(i).getTransitionName();
-            if (isEnd) {
-                setNameOverride(state.nameOverrides, source, target);
-            } else {
-                setNameOverride(state.nameOverrides, target, source);
-            }
-        }
+    private static boolean isFragmentPostponed(Op op) {
+        final Fragment fragment = op.fragment;
+        return (fragment.mAdded && fragment.mView != null && !fragment.mDetached &&
+                !fragment.mHidden && fragment.isPostponed());
     }
 
     public String getName() {
@@ -1713,36 +909,4 @@
     public boolean isEmpty() {
         return mOps.isEmpty();
     }
-
-    public class TransitionState {
-        public ArrayMap<String, String> nameOverrides = new ArrayMap<String, String>();
-        public View enteringEpicenterView;
-        public View nonExistentView;
-    }
-
-    /**
-     * Tracks the last fragment added and first fragment removed for fragment transitions.
-     * This also tracks which fragments are changed by push or pop transactions.
-     */
-    public static class FragmentContainerTransition {
-        /**
-         * The last fragment added/attached/shown in its container
-         */
-        public Fragment lastIn;
-
-        /**
-         * true when lastIn was added during a pop transaction or false if added with a push
-         */
-        public boolean lastInIsPop;
-
-        /**
-         * The first fragment with a View that was removed/detached/hidden in its container.
-         */
-        public Fragment firstOut;
-
-        /**
-         * true when firstOut was removed during a pop transaction or false otherwise
-         */
-        public boolean firstOutIsPop;
-    }
 }
diff --git a/core/java/android/app/Fragment.java b/core/java/android/app/Fragment.java
index 6ea170e..5d1cd3b 100644
--- a/core/java/android/app/Fragment.java
+++ b/core/java/android/app/Fragment.java
@@ -31,6 +31,8 @@
 import android.os.Build;
 import android.os.Build.VERSION_CODES;
 import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.transition.Transition;
@@ -375,15 +377,6 @@
 
     int mState = INITIALIZING;
 
-    // Non-null if the fragment's view hierarchy is currently animating away,
-    // meaning we need to wait a bit on completely destroying it.  This is the
-    // animation that is running.
-    Animator mAnimatingAway;
-
-    // If mAnimatingAway != null, this is the state we should move to once the
-    // animation is done.
-    int mStateAfterAnimating;
-
     // When instantiated from saved state, this is the saved state.
     Bundle mSavedFragmentState;
     SparseArray<Parcelable> mSavedViewState;
@@ -478,9 +471,6 @@
     // Used to verify that subclasses call through to super class.
     boolean mCalled;
 
-    // If app has requested a specific animation, this is the one to use.
-    int mNextAnim;
-
     // The parent container of the fragment after dynamically added to UI.
     ViewGroup mContainer;
 
@@ -498,17 +488,18 @@
     boolean mLoadersStarted;
     boolean mCheckedForLoaderManager;
 
-    private Transition mEnterTransition = null;
-    private Transition mReturnTransition = USE_DEFAULT_TRANSITION;
-    private Transition mExitTransition = null;
-    private Transition mReenterTransition = USE_DEFAULT_TRANSITION;
-    private Transition mSharedElementEnterTransition = null;
-    private Transition mSharedElementReturnTransition = USE_DEFAULT_TRANSITION;
-    private Boolean mAllowReturnTransitionOverlap;
-    private Boolean mAllowEnterTransitionOverlap;
+    // The animation and transition information for the fragment. This will be null
+    // unless the elements are explicitly accessed and should remain null for Fragments
+    // without Views.
+    AnimationInfo mAnimationInfo;
 
-    SharedElementCallback mEnterTransitionCallback = SharedElementCallback.NULL_CALLBACK;
-    SharedElementCallback mExitTransitionCallback = SharedElementCallback.NULL_CALLBACK;
+    // True if the View was added, and its animation has yet to be run. This could
+    // also indicate that the fragment view hasn't been made visible, even if there is no
+    // animation for this fragment.
+    boolean mIsNewlyAdded;
+
+    // True if mHidden has been changed and the animation should be scheduled.
+    boolean mHiddenChanged;
 
     /**
      * State information that has been retrieved from a fragment instance
@@ -1390,26 +1381,41 @@
 
         TypedArray a = context.obtainStyledAttributes(attrs,
                 com.android.internal.R.styleable.Fragment);
-        mEnterTransition = loadTransition(context, a, mEnterTransition, null,
-                com.android.internal.R.styleable.Fragment_fragmentEnterTransition);
-        mReturnTransition = loadTransition(context, a, mReturnTransition, USE_DEFAULT_TRANSITION,
-                com.android.internal.R.styleable.Fragment_fragmentReturnTransition);
-        mExitTransition = loadTransition(context, a, mExitTransition, null,
-                com.android.internal.R.styleable.Fragment_fragmentExitTransition);
-        mReenterTransition = loadTransition(context, a, mReenterTransition, USE_DEFAULT_TRANSITION,
-                com.android.internal.R.styleable.Fragment_fragmentReenterTransition);
-        mSharedElementEnterTransition = loadTransition(context, a, mSharedElementEnterTransition,
-                null, com.android.internal.R.styleable.Fragment_fragmentSharedElementEnterTransition);
-        mSharedElementReturnTransition = loadTransition(context, a, mSharedElementReturnTransition,
+        setEnterTransition(loadTransition(context, a, getEnterTransition(), null,
+                com.android.internal.R.styleable.Fragment_fragmentEnterTransition));
+        setReturnTransition(loadTransition(context, a, getReturnTransition(),
                 USE_DEFAULT_TRANSITION,
-                com.android.internal.R.styleable.Fragment_fragmentSharedElementReturnTransition);
-        if (mAllowEnterTransitionOverlap == null) {
-            mAllowEnterTransitionOverlap = a.getBoolean(
-                    com.android.internal.R.styleable.Fragment_fragmentAllowEnterTransitionOverlap, true);
+                com.android.internal.R.styleable.Fragment_fragmentReturnTransition));
+        setExitTransition(loadTransition(context, a, getExitTransition(), null,
+                com.android.internal.R.styleable.Fragment_fragmentExitTransition));
+
+        setReenterTransition(loadTransition(context, a, getReenterTransition(),
+                USE_DEFAULT_TRANSITION,
+                com.android.internal.R.styleable.Fragment_fragmentReenterTransition));
+        setSharedElementEnterTransition(loadTransition(context, a,
+                getSharedElementEnterTransition(), null,
+                com.android.internal.R.styleable.Fragment_fragmentSharedElementEnterTransition));
+        setSharedElementReturnTransition(loadTransition(context, a,
+                getSharedElementReturnTransition(), USE_DEFAULT_TRANSITION,
+                com.android.internal.R.styleable.Fragment_fragmentSharedElementReturnTransition));
+        boolean isEnterSet;
+        boolean isReturnSet;
+        if (mAnimationInfo == null) {
+            isEnterSet = false;
+            isReturnSet = false;
+        } else {
+            isEnterSet = mAnimationInfo.mAllowEnterTransitionOverlap != null;
+            isReturnSet = mAnimationInfo.mAllowReturnTransitionOverlap != null;
         }
-        if (mAllowReturnTransitionOverlap == null) {
-            mAllowReturnTransitionOverlap = a.getBoolean(
-                    com.android.internal.R.styleable.Fragment_fragmentAllowReturnTransitionOverlap, true);
+        if (!isEnterSet) {
+            setAllowEnterTransitionOverlap(a.getBoolean(
+                    com.android.internal.R.styleable.Fragment_fragmentAllowEnterTransitionOverlap,
+                    true));
+        }
+        if (!isReturnSet) {
+            setAllowReturnTransitionOverlap(a.getBoolean(
+                    com.android.internal.R.styleable.Fragment_fragmentAllowReturnTransitionOverlap,
+                    true));
         }
         a.recycle();
 
@@ -1934,16 +1940,12 @@
      */
     public void setEnterSharedElementCallback(SharedElementCallback callback) {
         if (callback == null) {
+            if (mAnimationInfo == null) {
+                return; // already a null callback
+            }
             callback = SharedElementCallback.NULL_CALLBACK;
         }
-        mEnterTransitionCallback = callback;
-    }
-
-    /**
-     * @hide
-     */
-    public void setEnterSharedElementTransitionCallback(SharedElementCallback callback) {
-        setEnterSharedElementCallback(callback);
+        ensureAnimationInfo().mEnterTransitionCallback = callback;
     }
 
     /**
@@ -1955,16 +1957,12 @@
      */
     public void setExitSharedElementCallback(SharedElementCallback callback) {
         if (callback == null) {
+            if (mAnimationInfo == null) {
+                return; // already a null callback
+            }
             callback = SharedElementCallback.NULL_CALLBACK;
         }
-        mExitTransitionCallback = callback;
-    }
-
-    /**
-     * @hide
-     */
-    public void setExitSharedElementTransitionCallback(SharedElementCallback callback) {
-        setExitSharedElementCallback(callback);
+        ensureAnimationInfo().mExitTransitionCallback = callback;
     }
 
     /**
@@ -1979,7 +1977,9 @@
      * @attr ref android.R.styleable#Fragment_fragmentEnterTransition
      */
     public void setEnterTransition(Transition transition) {
-        mEnterTransition = transition;
+        if (shouldChangeTransition(transition, null)) {
+            ensureAnimationInfo().mEnterTransition = transition;
+        }
     }
 
     /**
@@ -1993,7 +1993,10 @@
      * @attr ref android.R.styleable#Fragment_fragmentEnterTransition
      */
     public Transition getEnterTransition() {
-        return mEnterTransition;
+        if (mAnimationInfo == null) {
+            return null;
+        }
+        return mAnimationInfo.mEnterTransition;
     }
 
     /**
@@ -2011,7 +2014,9 @@
      * @attr ref android.R.styleable#Fragment_fragmentExitTransition
      */
     public void setReturnTransition(Transition transition) {
-        mReturnTransition = transition;
+        if (shouldChangeTransition(transition, USE_DEFAULT_TRANSITION)) {
+            ensureAnimationInfo().mReturnTransition = transition;
+        }
     }
 
     /**
@@ -2028,8 +2033,11 @@
      * @attr ref android.R.styleable#Fragment_fragmentExitTransition
      */
     public Transition getReturnTransition() {
-        return mReturnTransition == USE_DEFAULT_TRANSITION ? getEnterTransition()
-                : mReturnTransition;
+        if (mAnimationInfo == null) {
+            return null;
+        }
+        return mAnimationInfo.mReturnTransition == USE_DEFAULT_TRANSITION ? getEnterTransition()
+                : mAnimationInfo.mReturnTransition;
     }
 
     /**
@@ -2046,7 +2054,9 @@
      * @attr ref android.R.styleable#Fragment_fragmentExitTransition
      */
     public void setExitTransition(Transition transition) {
-        mExitTransition = transition;
+        if (shouldChangeTransition(transition, null)) {
+            ensureAnimationInfo().mExitTransition = transition;
+        }
     }
 
     /**
@@ -2063,7 +2073,10 @@
      * @attr ref android.R.styleable#Fragment_fragmentExitTransition
      */
     public Transition getExitTransition() {
-        return mExitTransition;
+        if (mAnimationInfo == null) {
+            return null;
+        }
+        return mAnimationInfo.mExitTransition;
     }
 
     /**
@@ -2080,7 +2093,9 @@
      * @attr ref android.R.styleable#Fragment_fragmentReenterTransition
      */
     public void setReenterTransition(Transition transition) {
-        mReenterTransition = transition;
+        if (shouldChangeTransition(transition, USE_DEFAULT_TRANSITION)) {
+            ensureAnimationInfo().mReenterTransition = transition;
+        }
     }
 
     /**
@@ -2097,8 +2112,11 @@
      * @attr ref android.R.styleable#Fragment_fragmentReenterTransition
      */
     public Transition getReenterTransition() {
-        return mReenterTransition == USE_DEFAULT_TRANSITION ? getExitTransition()
-                : mReenterTransition;
+        if (mAnimationInfo == null) {
+            return null;
+        }
+        return mAnimationInfo.mReenterTransition == USE_DEFAULT_TRANSITION ? getExitTransition()
+                : mAnimationInfo.mReenterTransition;
     }
 
     /**
@@ -2112,7 +2130,9 @@
      * @attr ref android.R.styleable#Fragment_fragmentSharedElementEnterTransition
      */
     public void setSharedElementEnterTransition(Transition transition) {
-        mSharedElementEnterTransition = transition;
+        if (shouldChangeTransition(transition, null)) {
+            ensureAnimationInfo().mSharedElementEnterTransition = transition;
+        }
     }
 
     /**
@@ -2126,7 +2146,10 @@
      * @attr ref android.R.styleable#Fragment_fragmentSharedElementEnterTransition
      */
     public Transition getSharedElementEnterTransition() {
-        return mSharedElementEnterTransition;
+        if (mAnimationInfo == null) {
+            return null;
+        }
+        return mAnimationInfo.mSharedElementEnterTransition;
     }
 
     /**
@@ -2143,7 +2166,9 @@
      * @attr ref android.R.styleable#Fragment_fragmentSharedElementReturnTransition
      */
     public void setSharedElementReturnTransition(Transition transition) {
-        mSharedElementReturnTransition = transition;
+        if (shouldChangeTransition(transition, USE_DEFAULT_TRANSITION)) {
+            ensureAnimationInfo().mSharedElementReturnTransition = transition;
+        }
     }
 
     /**
@@ -2160,8 +2185,12 @@
      * @attr ref android.R.styleable#Fragment_fragmentSharedElementReturnTransition
      */
     public Transition getSharedElementReturnTransition() {
-        return mSharedElementReturnTransition == USE_DEFAULT_TRANSITION ?
-                getSharedElementEnterTransition() : mSharedElementReturnTransition;
+        if (mAnimationInfo == null) {
+            return null;
+        }
+        return mAnimationInfo.mSharedElementReturnTransition == USE_DEFAULT_TRANSITION
+                ? getSharedElementEnterTransition()
+                : mAnimationInfo.mSharedElementReturnTransition;
     }
 
     /**
@@ -2174,7 +2203,7 @@
      * @attr ref android.R.styleable#Fragment_fragmentAllowEnterTransitionOverlap
      */
     public void setAllowEnterTransitionOverlap(boolean allow) {
-        mAllowEnterTransitionOverlap = allow;
+        ensureAnimationInfo().mAllowEnterTransitionOverlap = allow;
     }
 
     /**
@@ -2187,7 +2216,8 @@
      * @attr ref android.R.styleable#Fragment_fragmentAllowEnterTransitionOverlap
      */
     public boolean getAllowEnterTransitionOverlap() {
-        return (mAllowEnterTransitionOverlap == null) ? true : mAllowEnterTransitionOverlap;
+        return (mAnimationInfo == null || mAnimationInfo.mAllowEnterTransitionOverlap == null)
+                ? true : mAnimationInfo.mAllowEnterTransitionOverlap;
     }
 
     /**
@@ -2200,7 +2230,7 @@
      * @attr ref android.R.styleable#Fragment_fragmentAllowReturnTransitionOverlap
      */
     public void setAllowReturnTransitionOverlap(boolean allow) {
-        mAllowReturnTransitionOverlap = allow;
+        ensureAnimationInfo().mAllowReturnTransitionOverlap = allow;
     }
 
     /**
@@ -2213,7 +2243,90 @@
      * @attr ref android.R.styleable#Fragment_fragmentAllowReturnTransitionOverlap
      */
     public boolean getAllowReturnTransitionOverlap() {
-        return (mAllowReturnTransitionOverlap == null) ? true : mAllowReturnTransitionOverlap;
+        return (mAnimationInfo == null || mAnimationInfo.mAllowReturnTransitionOverlap == null)
+                ? true : mAnimationInfo.mAllowReturnTransitionOverlap;
+    }
+
+    /**
+     * Postpone the entering Fragment transition until {@link #startPostponedEnterTransition()}
+     * or {@link FragmentManager#executePendingTransactions()} has been called.
+     * <p>
+     * This method gives the Fragment the ability to delay Fragment animations
+     * until all data is loaded. Until then, the added, shown, and
+     * attached Fragments will be INVISIBLE and removed, hidden, and detached Fragments won't
+     * be have their Views removed. The transaction runs when all postponed added Fragments in the
+     * transaction have called {@link #startPostponedEnterTransition()}.
+     * <p>
+     * This method should be called before being added to the FragmentTransaction or
+     * in {@link #onCreate(Bundle), {@link #onAttach(Context)}, or
+     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}}.
+     * {@link #startPostponedEnterTransition()} must be called to allow the Fragment to
+     * start the transitions.
+     * <p>
+     * When a FragmentTransaction is started that may affect a postponed FragmentTransaction,
+     * based on which containers are in their operations, the postponed FragmentTransaction
+     * will have its start triggered. The early triggering may result in faulty or nonexistent
+     * animations in the postponed transaction. FragmentTransactions that operate only on
+     * independent containers will not interfere with each other's postponement.
+     * <p>
+     * Calling postponeEnterTransition on Fragments with a null View will not postpone the
+     * transition. Likewise, postponement only works if FragmentTransaction optimizations are
+     * enabled.
+     *
+     * @see Activity#postponeEnterTransition()
+     * @see FragmentTransaction#setAllowOptimization(boolean)
+     */
+    public void postponeEnterTransition() {
+        ensureAnimationInfo().mEnterTransitionPostponed = true;
+    }
+
+    /**
+     * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
+     * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
+     * or {@link FragmentManager#executePendingTransactions()} to complete the FragmentTransaction.
+     * If postponement was interrupted with {@link FragmentManager#executePendingTransactions()},
+     * before {@code startPostponedEnterTransition()}, animations may not run or may execute
+     * improperly.
+     *
+     * @see Activity#startPostponedEnterTransition()
+     */
+    public void startPostponedEnterTransition() {
+        if (mFragmentManager == null || mFragmentManager.mHost == null) {
+                ensureAnimationInfo().mEnterTransitionPostponed = false;
+        } else if (Looper.myLooper() != mFragmentManager.mHost.getHandler().getLooper()) {
+            mFragmentManager.mHost.getHandler().
+                    postAtFrontOfQueue(this::callStartTransitionListener);
+        } else {
+            callStartTransitionListener();
+        }
+    }
+
+    /**
+     * Calls the start transition listener. This must be called on the UI thread.
+     */
+    private void callStartTransitionListener() {
+        final OnStartEnterTransitionListener listener;
+        if (mAnimationInfo == null) {
+            listener = null;
+        } else {
+            mAnimationInfo.mEnterTransitionPostponed = false;
+            listener = mAnimationInfo.mStartEnterTransitionListener;
+            mAnimationInfo.mStartEnterTransitionListener = null;
+        }
+        if (listener != null) {
+            listener.onStartEnterTransition();
+        }
+    }
+
+    /**
+     * Returns true if mAnimationInfo is not null or the transition differs from the default value.
+     * This is broken out to ensure mAnimationInfo is properly locked when checking.
+     */
+    private boolean shouldChangeTransition(Transition transition, Transition defaultValue) {
+        if (transition == defaultValue) {
+            return mAnimationInfo != null;
+        }
+        return true;
     }
 
     /**
@@ -2274,8 +2387,8 @@
             writer.print(" mTargetRequestCode=");
             writer.println(mTargetRequestCode);
         }
-        if (mNextAnim != 0) {
-            writer.print(prefix); writer.print("mNextAnim="); writer.println(mNextAnim);
+        if (getNextAnim() != 0) {
+            writer.print(prefix); writer.print("mNextAnim="); writer.println(getNextAnim());
         }
         if (mContainer != null) {
             writer.print(prefix); writer.print("mContainer="); writer.println(mContainer);
@@ -2283,10 +2396,11 @@
         if (mView != null) {
             writer.print(prefix); writer.print("mView="); writer.println(mView);
         }
-        if (mAnimatingAway != null) {
-            writer.print(prefix); writer.print("mAnimatingAway="); writer.println(mAnimatingAway);
+        if (getAnimatingAway() != null) {
+            writer.print(prefix); writer.print("mAnimatingAway=");
+            writer.println(getAnimatingAway());
             writer.print(prefix); writer.print("mStateAfterAnimating=");
-            writer.println(mStateAfterAnimating);
+            writer.println(getStateAfterAnimating());
         }
         if (mLoaderManager != null) {
             writer.print(prefix); writer.println("Loader Manager:");
@@ -2613,6 +2727,23 @@
         }
     }
 
+    void setOnStartEnterTransitionListener(OnStartEnterTransitionListener listener) {
+        ensureAnimationInfo();
+        if (listener == mAnimationInfo.mStartEnterTransitionListener) {
+            return;
+        }
+        if (listener != null && mAnimationInfo.mStartEnterTransitionListener != null) {
+            throw new IllegalStateException("Trying to set a replacement " +
+                    "startPostponedEnterTransition on " + this);
+        }
+        if (mAnimationInfo.mEnterTransitionPostponed) {
+            mAnimationInfo.mStartEnterTransitionListener = listener;
+        }
+        if (listener != null) {
+            listener.startListening();
+        }
+    }
+
     private static Transition loadTransition(Context context, TypedArray typedArray,
             Transition currentValue, Transition defaultValue, int id) {
         if (currentValue != defaultValue) {
@@ -2631,4 +2762,147 @@
         return transition;
     }
 
+    private AnimationInfo ensureAnimationInfo() {
+        if (mAnimationInfo == null) {
+            mAnimationInfo = new AnimationInfo();
+        }
+        return mAnimationInfo;
+    }
+
+    int getNextAnim() {
+        if (mAnimationInfo == null) {
+            return 0;
+        }
+        return mAnimationInfo.mNextAnim;
+    }
+
+    void setNextAnim(int animResourceId) {
+        if (mAnimationInfo == null && animResourceId == 0) {
+            return; // no change!
+        }
+        ensureAnimationInfo().mNextAnim = animResourceId;
+    }
+
+    int getNextTransition() {
+        if (mAnimationInfo == null) {
+            return 0;
+        }
+        return mAnimationInfo.mNextTransition;
+    }
+
+    void setNextTransition(int nextTransition, int nextTransitionStyle) {
+        if (mAnimationInfo == null && nextTransition == 0 && nextTransitionStyle == 0) {
+            return; // no change!
+        }
+        ensureAnimationInfo();
+        mAnimationInfo.mNextTransition = nextTransition;
+        mAnimationInfo.mNextTransitionStyle = nextTransitionStyle;
+    }
+
+    int getNextTransitionStyle() {
+        if (mAnimationInfo == null) {
+            return 0;
+        }
+        return mAnimationInfo.mNextTransitionStyle;
+    }
+
+    SharedElementCallback getEnterTransitionCallback() {
+        if (mAnimationInfo == null) {
+            return SharedElementCallback.NULL_CALLBACK;
+        }
+        return mAnimationInfo.mEnterTransitionCallback;
+    }
+
+    SharedElementCallback getExitTransitionCallback() {
+        if (mAnimationInfo == null) {
+            return SharedElementCallback.NULL_CALLBACK;
+        }
+        return mAnimationInfo.mExitTransitionCallback;
+    }
+
+    Animator getAnimatingAway() {
+        if (mAnimationInfo == null) {
+            return null;
+        }
+        return mAnimationInfo.mAnimatingAway;
+    }
+
+    void setAnimatingAway(Animator animator) {
+        ensureAnimationInfo().mAnimatingAway = animator;
+    }
+
+    int getStateAfterAnimating() {
+        if (mAnimationInfo == null) {
+            return 0;
+        }
+        return mAnimationInfo.mStateAfterAnimating;
+    }
+
+    void setStateAfterAnimating(int state) {
+        ensureAnimationInfo().mStateAfterAnimating = state;
+    }
+
+    boolean isPostponed() {
+        if (mAnimationInfo == null) {
+            return false;
+        }
+        return mAnimationInfo.mEnterTransitionPostponed;
+    }
+
+    /**
+     * Used internally to be notified when {@link #startPostponedEnterTransition()} has
+     * been called. This listener will only be called once and then be removed from the
+     * listeners.
+     */
+    interface OnStartEnterTransitionListener {
+        void onStartEnterTransition();
+        void startListening();
+    }
+
+    /**
+     * Contains all the animation and transition information for a fragment. This will only
+     * be instantiated for Fragments that have Views.
+     */
+    static class AnimationInfo {
+        // Non-null if the fragment's view hierarchy is currently animating away,
+        // meaning we need to wait a bit on completely destroying it.  This is the
+        // animation that is running.
+        Animator mAnimatingAway;
+
+        // If mAnimatingAway != null, this is the state we should move to once the
+        // animation is done.
+        int mStateAfterAnimating;
+
+        // If app has requested a specific animation, this is the one to use.
+        int mNextAnim;
+
+        // If app has requested a specific transition, this is the one to use.
+        int mNextTransition;
+
+        // If app has requested a specific transition style, this is the one to use.
+        int mNextTransitionStyle;
+
+        private Transition mEnterTransition = null;
+        private Transition mReturnTransition = USE_DEFAULT_TRANSITION;
+        private Transition mExitTransition = null;
+        private Transition mReenterTransition = USE_DEFAULT_TRANSITION;
+        private Transition mSharedElementEnterTransition = null;
+        private Transition mSharedElementReturnTransition = USE_DEFAULT_TRANSITION;
+        private Boolean mAllowReturnTransitionOverlap;
+        private Boolean mAllowEnterTransitionOverlap;
+
+        SharedElementCallback mEnterTransitionCallback = SharedElementCallback.NULL_CALLBACK;
+        SharedElementCallback mExitTransitionCallback = SharedElementCallback.NULL_CALLBACK;
+
+        // True when postponeEnterTransition has been called and startPostponeEnterTransition
+        // hasn't been called yet.
+        boolean mEnterTransitionPostponed;
+
+        // Listener to wait for startPostponeEnterTransition. After being called, it will
+        // be set to null
+        OnStartEnterTransitionListener mStartEnterTransitionListener;
+
+        // True if the View was added, and its animation has yet to be run.
+        boolean mIsNewlyAdded;
+    }
 }
diff --git a/core/java/android/app/FragmentHostCallback.java b/core/java/android/app/FragmentHostCallback.java
index d869168..7e415e9 100644
--- a/core/java/android/app/FragmentHostCallback.java
+++ b/core/java/android/app/FragmentHostCallback.java
@@ -54,7 +54,8 @@
     private boolean mLoadersStarted;
 
     public FragmentHostCallback(Context context, Handler handler, int windowAnimations) {
-        this(null /*activity*/, context, handler, windowAnimations);
+        this((context instanceof Activity) ? (Activity)context : null, context,
+                chooseHandler(context, handler), windowAnimations);
     }
 
     FragmentHostCallback(Activity activity) {
@@ -70,6 +71,19 @@
     }
 
     /**
+     * Used internally in {@link #FragmentHostCallback(Context, Handler, int)} to choose
+     * the Activity's handler or the provided handler.
+     */
+    private static Handler chooseHandler(Context context, Handler handler) {
+        if (handler == null && context instanceof Activity) {
+            Activity activity = (Activity) context;
+            return activity.mHandler;
+        } else {
+            return handler;
+        }
+    }
+
+    /**
      * Print internal state into the given stream.
      *
      * @param prefix Desired prefix to prepend at each line of output.
diff --git a/core/java/android/app/FragmentManager.java b/core/java/android/app/FragmentManager.java
index 674c3f7..9345a03 100644
--- a/core/java/android/app/FragmentManager.java
+++ b/core/java/android/app/FragmentManager.java
@@ -28,7 +28,6 @@
 import android.content.res.TypedArray;
 import android.os.Bundle;
 import android.os.Debug;
-import android.os.Handler;
 import android.os.Looper;
 import android.os.Parcel;
 import android.os.Parcelable;
@@ -44,6 +43,7 @@
 import android.view.MenuItem;
 import android.view.View;
 import android.view.ViewGroup;
+
 import com.android.internal.util.FastPrintWriter;
 
 import java.io.FileDescriptor;
@@ -160,6 +160,9 @@
      * can call this function (only from the main thread) to do so.  Note that
      * all callbacks and other related behavior will be done from within this
      * call, so be careful about where this is called from.
+     * <p>
+     * This also forces the start of any postponed Transactions where
+     * {@link Fragment#postponeEnterTransition()} has been called.
      *
      * @return Returns true if there were any pending transactions to be
      * executed.
@@ -206,7 +209,7 @@
     /**
      * Like {@link #popBackStack()}, but performs the operation immediately
      * inside of the call.  This is like calling {@link #executePendingTransactions()}
-     * afterwards.
+     * afterwards without forcing the start of postponed Transactions.
      * @return Returns true if there was something popped, else false.
      */
     public abstract boolean popBackStackImmediate();
@@ -229,7 +232,7 @@
     /**
      * Like {@link #popBackStack(String, int)}, but performs the operation immediately
      * inside of the call.  This is like calling {@link #executePendingTransactions()}
-     * afterwards.
+     * afterwards without forcing the start of postponed Transactions.
      * @return Returns true if there was something popped, else false.
      */
     public abstract boolean popBackStackImmediate(String name, int flags);
@@ -253,7 +256,7 @@
     /**
      * Like {@link #popBackStack(int, int)}, but performs the operation immediately
      * inside of the call.  This is like calling {@link #executePendingTransactions()}
-     * afterwards.
+     * afterwards without forcing the start of postponed Transactions.
      * @return Returns true if there was something popped, else false.
      */
     public abstract boolean popBackStackImmediate(int id, int flags);
@@ -445,8 +448,7 @@
         }
     }
 
-    ArrayList<Runnable> mPendingActions;
-    Runnable[] mTmpActions;
+    ArrayList<OpGenerator> mPendingActions;
     boolean mExecutingActions;
     
     ArrayList<Fragment> mActive;
@@ -463,7 +465,6 @@
 
     int mCurState = Fragment.INITIALIZING;
     FragmentHostCallback<?> mHost;
-    FragmentController mController;
     FragmentContainer mContainer;
     Fragment mParent;
     
@@ -473,10 +474,18 @@
     String mNoTransactionsBecause;
     boolean mHavePendingDeferredStart;
 
+    // Temporary vars for optimizing execution of BackStackRecords:
+    ArrayList<BackStackRecord> mTmpRecords;
+    ArrayList<Boolean> mTmpIsPop;
+    ArrayList<Fragment> mTmpAddedFragments;
+
     // Temporary vars for state save and restore.
     Bundle mStateBundle = null;
     SparseArray<Parcelable> mStateArray = null;
-    
+
+    // Postponed transactions.
+    ArrayList<StartEnterTransitionListener> mPostponedTransactions;
+
     Runnable mExecCommit = new Runnable() {
         @Override
         public void run() {
@@ -560,61 +569,73 @@
 
     @Override
     public boolean executePendingTransactions() {
-        return execPendingActions();
+        boolean updates = execPendingActions();
+        forcePostponedTransactions();
+        return updates;
     }
 
     @Override
     public void popBackStack() {
-        enqueueAction(new Runnable() {
-            @Override public void run() {
-                popBackStackState(mHost.getHandler(), null, -1, 0);
-            }
-        }, false);
+        enqueueAction(new PopBackStackState(null, -1, 0), false);
     }
 
     @Override
     public boolean popBackStackImmediate() {
         checkStateLoss();
-        executePendingTransactions();
-        return popBackStackState(mHost.getHandler(), null, -1, 0);
+        return popBackStackImmediate(null, -1, 0);
     }
 
     @Override
-    public void popBackStack(final String name, final int flags) {
-        enqueueAction(new Runnable() {
-            @Override public void run() {
-                popBackStackState(mHost.getHandler(), name, -1, flags);
-            }
-        }, false);
+    public void popBackStack(String name, int flags) {
+        enqueueAction(new PopBackStackState(name, -1, flags), false);
     }
 
     @Override
     public boolean popBackStackImmediate(String name, int flags) {
         checkStateLoss();
-        executePendingTransactions();
-        return popBackStackState(mHost.getHandler(), name, -1, flags);
+        return popBackStackImmediate(name, -1, flags);
     }
 
     @Override
-    public void popBackStack(final int id, final int flags) {
+    public void popBackStack(int id, int flags) {
         if (id < 0) {
             throw new IllegalArgumentException("Bad id: " + id);
         }
-        enqueueAction(new Runnable() {
-            @Override public void run() {
-                popBackStackState(mHost.getHandler(), null, id, flags);
-            }
-        }, false);
+        enqueueAction(new PopBackStackState(null, id, flags), false);
     }
 
     @Override
     public boolean popBackStackImmediate(int id, int flags) {
         checkStateLoss();
-        executePendingTransactions();
         if (id < 0) {
             throw new IllegalArgumentException("Bad id: " + id);
         }
-        return popBackStackState(mHost.getHandler(), null, id, flags);
+        return popBackStackImmediate(null, id, flags);
+    }
+
+    /**
+     * Used by all public popBackStackImmediate methods, this executes pending transactions and
+     * returns true if the pop action did anything, regardless of what other pending
+     * transactions did.
+     *
+     * @return true if the pop operation did anything or false otherwise.
+     */
+    private boolean popBackStackImmediate(String name, int id, int flags) {
+        execPendingActions();
+        ensureExecReady(true);
+
+        boolean executePop = popBackStackState(mTmpRecords, mTmpIsPop, name, id, flags);
+        if (executePop) {
+            mExecutingActions = true;
+            try {
+                optimizeAndExecuteOps(mTmpRecords, mTmpIsPop);
+            } finally {
+                cleanupExec();
+            }
+        }
+
+        doPendingDeferredStart();
+        return executePop;
     }
 
     @Override
@@ -785,7 +806,7 @@
             if (N > 0) {
                 writer.print(prefix); writer.println("Pending Actions:");
                 for (int i=0; i<N; i++) {
-                    Runnable r = mPendingActions.get(i);
+                    OpGenerator r = mPendingActions.get(i);
                     writer.print(prefix); writer.print("  #"); writer.print(i);
                             writer.print(": "); writer.println(r);
                 }
@@ -817,14 +838,14 @@
 
     Animator loadAnimator(Fragment fragment, int transit, boolean enter,
             int transitionStyle) {
-        Animator animObj = fragment.onCreateAnimator(transit, enter,
-                fragment.mNextAnim);
+        Animator animObj = fragment.onCreateAnimator(transit, enter, fragment.getNextAnim());
         if (animObj != null) {
             return animObj;
         }
         
-        if (fragment.mNextAnim != 0) {
-            Animator anim = AnimatorInflater.loadAnimator(mHost.getContext(), fragment.mNextAnim);
+        if (fragment.getNextAnim() != 0) {
+            Animator anim = AnimatorInflater.loadAnimator(mHost.getContext(),
+                    fragment.getNextAnim());
             if (anim != null) {
                 return anim;
             }
@@ -900,13 +921,13 @@
             if (f.mFromLayout && !f.mInLayout) {
                 return;
             }
-            if (f.mAnimatingAway != null) {
+            if (f.getAnimatingAway() != null) {
                 // The fragment is currently being animated...  but!  Now we
                 // want to move our state back up.  Give up on waiting for the
                 // animation, move to whatever the final state should be once
                 // the animation is done, and then we can proceed from there.
-                f.mAnimatingAway = null;
-                moveToState(f, f.mStateAfterAnimating, 0, 0, true);
+                f.setAnimatingAway(null);
+                moveToState(f, f.getStateAfterAnimating(), 0, 0, true);
             }
             switch (f.mState) {
                 case Fragment.INITIALIZING:
@@ -997,16 +1018,13 @@
                             if (f.mView != null) {
                                 f.mView.setSaveFromParentEnabled(false);
                                 if (container != null) {
-                                    Animator anim = loadAnimator(f, transit, true,
-                                            transitionStyle);
-                                    if (anim != null) {
-                                        anim.setTarget(f.mView);
-                                        setHWLayerAnimListenerIfAlpha(f.mView, anim);
-                                        anim.start();
-                                    }
                                     container.addView(f.mView);
+                                    f.mIsNewlyAdded = true;
                                 }
-                                if (f.mHidden) f.mView.setVisibility(View.GONE);
+                                if (f.mHidden) {
+                                    f.mView.setVisibility(View.GONE);
+                                    f.mIsNewlyAdded = false; // No animation required
+                                }
                                 f.onViewCreated(f.mView, f.mSavedFragmentState);
                             }
                         }
@@ -1061,7 +1079,8 @@
                         f.performDestroyView();
                         if (f.mView != null && f.mContainer != null) {
                             Animator anim = null;
-                            if (mCurState > Fragment.INITIALIZING && !mDestroyed) {
+                            if (mCurState > Fragment.INITIALIZING && !mDestroyed &&
+                                    f.mView.getVisibility() == View.VISIBLE) {
                                 anim = loadAnimator(f, transit, false,
                                         transitionStyle);
                             }
@@ -1070,15 +1089,15 @@
                                 final View view = f.mView;
                                 final Fragment fragment = f;
                                 container.startViewTransition(view);
-                                f.mAnimatingAway = anim;
-                                f.mStateAfterAnimating = newState;
+                                f.setAnimatingAway(anim);
+                                f.setStateAfterAnimating(newState);
                                 anim.addListener(new AnimatorListenerAdapter() {
                                     @Override
                                     public void onAnimationEnd(Animator anim) {
                                         container.endViewTransition(view);
-                                        if (fragment.mAnimatingAway != null) {
-                                            fragment.mAnimatingAway = null;
-                                            moveToState(fragment, fragment.mStateAfterAnimating,
+                                        if (fragment.getAnimatingAway() != null) {
+                                            fragment.setAnimatingAway(null);
+                                            moveToState(fragment, fragment.getStateAfterAnimating(),
                                                     0, 0, false);
                                         }
                                     }
@@ -1096,24 +1115,24 @@
                 case Fragment.CREATED:
                     if (newState < Fragment.CREATED) {
                         if (mDestroyed) {
-                            if (f.mAnimatingAway != null) {
+                            if (f.getAnimatingAway() != null) {
                                 // The fragment's containing activity is
                                 // being destroyed, but this fragment is
                                 // currently animating away.  Stop the
                                 // animation right now -- it is not needed,
                                 // and we can't wait any more on destroying
                                 // the fragment.
-                                Animator anim = f.mAnimatingAway;
-                                f.mAnimatingAway = null;
+                                Animator anim = f.getAnimatingAway();
+                                f.setAnimatingAway(null);
                                 anim.cancel();
                             }
                         }
-                        if (f.mAnimatingAway != null) {
+                        if (f.getAnimatingAway() != null) {
                             // We are waiting for the fragment's view to finish
                             // animating away.  Just make a note of the state
                             // the fragment now should move to once the animation
                             // is done.
-                            f.mStateAfterAnimating = newState;
+                            f.setStateAfterAnimating(newState);
                             newState = Fragment.CREATED;
                         } else {
                             if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f);
@@ -1149,26 +1168,129 @@
         moveToState(f, mCurState, 0, 0, false);
     }
 
-    void moveToState(int newState, boolean always) {
-        moveToState(newState, 0, 0, always);
+    /**
+     * Fragments that have been shown or hidden don't have their visibility changed or
+     * animations run during the {@link #showFragment(Fragment)} or {@link #hideFragment(Fragment)}
+     * calls. After fragments are brought to their final state in
+     * {@link #moveFragmentToExpectedState(Fragment)} the fragments that have been shown or
+     * hidden must have their visibility changed and their animations started here.
+     *
+     * @param fragment The fragment with mHiddenChanged = true that should change its View's
+     *                 visibility and start the show or hide animation.
+     */
+    void completeShowHideFragment(final Fragment fragment) {
+        if (fragment.mView != null) {
+            Animator anim = loadAnimator(fragment, fragment.getNextTransition(), !fragment.mHidden,
+                    fragment.getNextTransitionStyle());
+            if (anim != null) {
+                anim.setTarget(fragment.mView);
+                if (fragment.mHidden) {
+                    // Delay the actual hide operation until the animation finishes, otherwise
+                    // the fragment will just immediately disappear
+                    anim.addListener(new AnimatorListenerAdapter() {
+                        @Override
+                        public void onAnimationEnd(Animator animation) {
+                            animation.removeListener(this);
+                            if (fragment.mView != null) {
+                                fragment.mView.setVisibility(View.GONE);
+                            }
+                        }
+                    });
+                }
+                setHWLayerAnimListenerIfAlpha(fragment.mView, anim);
+                anim.start();
+            } else {
+                final int visibility = fragment.mHidden ? View.GONE : View.VISIBLE;
+                fragment.mView.setVisibility(visibility);
+            }
+        }
+        if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) {
+            mNeedMenuInvalidate = true;
+        }
+        fragment.mHiddenChanged = false;
+        fragment.onHiddenChanged(fragment.mHidden);
     }
-    
-    void moveToState(int newState, int transit, int transitStyle, boolean always) {
+
+    /**
+     * Moves a fragment to its expected final state or the fragment manager's state, depending
+     * on whether the fragment manager's state is raised properly.
+     *
+     * @param f The fragment to change.
+     */
+    void moveFragmentToExpectedState(final Fragment f) {
+        if (f == null) {
+            return;
+        }
+        int nextState = mCurState;
+        if (f.mRemoving) {
+            if (f.isInBackStack()) {
+                nextState = Fragment.CREATED;
+            } else {
+                nextState = Fragment.INITIALIZING;
+            }
+        }
+
+        moveToState(f, nextState, f.getNextTransition(), f.getNextTransitionStyle(), false);
+
+        if (f.mView != null) {
+            // Move the view if it is out of order
+            Fragment underFragment = findFragmentUnder(f);
+            if (underFragment != null) {
+                final View underView = underFragment.mView;
+                // make sure this fragment is in the right order.
+                final ViewGroup container = f.mContainer;
+                int underIndex = container.indexOfChild(underView);
+                int viewIndex = container.indexOfChild(f.mView);
+                if (viewIndex < underIndex) {
+                    container.removeViewAt(viewIndex);
+                    container.addView(f.mView, underIndex);
+                }
+            }
+            if (f.mIsNewlyAdded && f.mContainer != null) {
+                // Make it visible and run the animations
+                f.mView.setVisibility(View.VISIBLE);
+                f.mIsNewlyAdded = false;
+                // run animations:
+                Animator anim = loadAnimator(f, f.getNextTransition(), true, f.getNextTransitionStyle());
+                if (anim != null) {
+                    anim.setTarget(f.mView);
+                    setHWLayerAnimListenerIfAlpha(f.mView, anim);
+                    anim.start();
+                }
+            }
+        }
+        if (f.mHiddenChanged) {
+            completeShowHideFragment(f);
+        }
+    }
+
+    void moveToState(int newState) {
         if (mHost == null && newState != Fragment.INITIALIZING) {
             throw new IllegalStateException("No activity");
         }
 
-        if (!always && mCurState == newState) {
-            return;
-        }
-
         mCurState = newState;
+
         if (mActive != null) {
             boolean loadersRunning = false;
-            for (int i=0; i<mActive.size(); i++) {
+
+            // Must add them in the proper order. mActive fragments may be out of order
+            final int numAdded = mAdded.size();
+            for (int i = 0; i < numAdded; i++) {
+                Fragment f = mAdded.get(i);
+                moveFragmentToExpectedState(f);
+                if (f.mLoaderManager != null) {
+                    loadersRunning |= f.mLoaderManager.hasRunningLoaders();
+                }
+            }
+
+            // Now iterate through all active fragments. These will include those that are removed
+            // and detached.
+            final int numActive = mActive.size();
+            for (int i = 0; i < numActive; i++) {
                 Fragment f = mActive.get(i);
-                if (f != null) {
-                    moveToState(f, newState, transit, transitStyle, false);
+                if (f != null && (f.mRemoving || f.mDetached) && !f.mIsNewlyAdded) {
+                    moveFragmentToExpectedState(f);
                     if (f.mLoaderManager != null) {
                         loadersRunning |= f.mLoaderManager.hasRunningLoaders();
                     }
@@ -1185,7 +1307,7 @@
             }
         }
     }
-    
+
     void startPendingDeferredFragments() {
         if (mActive == null) return;
 
@@ -1244,6 +1366,9 @@
             mAdded.add(fragment);
             fragment.mAdded = true;
             fragment.mRemoving = false;
+            if (fragment.mView == null) {
+                fragment.mHiddenChanged = false;
+            }
             if (fragment.mHasMenu && fragment.mMenuVisible) {
                 mNeedMenuInvalidate = true;
             }
@@ -1252,8 +1377,8 @@
             }
         }
     }
-    
-    public void removeFragment(Fragment fragment, int transition, int transitionStyle) {
+
+    public void removeFragment(Fragment fragment) {
         if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting);
         final boolean inactive = !fragment.isInBackStack();
         if (!fragment.mDetached || inactive) {
@@ -1273,66 +1398,42 @@
             }
             fragment.mAdded = false;
             fragment.mRemoving = true;
-            moveToState(fragment, inactive ? Fragment.INITIALIZING : Fragment.CREATED,
-                    transition, transitionStyle, false);
         }
     }
-    
-    public void hideFragment(Fragment fragment, int transition, int transitionStyle) {
+
+    /**
+     * Marks a fragment as hidden to be later animated in with
+     * {@link #completeShowHideFragment(Fragment)}.
+     *
+     * @param fragment The fragment to be shown.
+     */
+    public void hideFragment(Fragment fragment) {
         if (DEBUG) Log.v(TAG, "hide: " + fragment);
         if (!fragment.mHidden) {
             fragment.mHidden = true;
-            if (fragment.mView != null) {
-                Animator anim = loadAnimator(fragment, transition, false,
-                        transitionStyle);
-                if (anim != null) {
-                    anim.setTarget(fragment.mView);
-                    // Delay the actual hide operation until the animation finishes, otherwise
-                    // the fragment will just immediately disappear
-                    final Fragment finalFragment = fragment;
-                    anim.addListener(new AnimatorListenerAdapter() {
-                        @Override
-                        public void onAnimationEnd(Animator animation) {
-                            if (finalFragment.mView != null) {
-                                finalFragment.mView.setVisibility(View.GONE);
-                            }
-                        }
-                    });
-                    setHWLayerAnimListenerIfAlpha(finalFragment.mView, anim);
-                    anim.start();
-                } else {
-                    fragment.mView.setVisibility(View.GONE);
-                }
-            }
-            if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) {
-                mNeedMenuInvalidate = true;
-            }
-            fragment.onHiddenChanged(true);
+            // Toggle hidden changed so that if a fragment goes through show/hide/show
+            // it doesn't go through the animation.
+            fragment.mHiddenChanged = !fragment.mHiddenChanged;
         }
     }
-    
-    public void showFragment(Fragment fragment, int transition, int transitionStyle) {
+
+    /**
+     * Marks a fragment as shown to be later animated in with
+     * {@link #completeShowHideFragment(Fragment)}.
+     *
+     * @param fragment The fragment to be shown.
+     */
+    public void showFragment(Fragment fragment) {
         if (DEBUG) Log.v(TAG, "show: " + fragment);
         if (fragment.mHidden) {
             fragment.mHidden = false;
-            if (fragment.mView != null) {
-                Animator anim = loadAnimator(fragment, transition, true,
-                        transitionStyle);
-                if (anim != null) {
-                    anim.setTarget(fragment.mView);
-                    setHWLayerAnimListenerIfAlpha(fragment.mView, anim);
-                    anim.start();
-                }
-                fragment.mView.setVisibility(View.VISIBLE);
-            }
-            if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) {
-                mNeedMenuInvalidate = true;
-            }
-            fragment.onHiddenChanged(false);
+            // Toggle hidden changed so that if a fragment goes through show/hide/show
+            // it doesn't go through the animation.
+            fragment.mHiddenChanged = !fragment.mHiddenChanged;
         }
     }
-    
-    public void detachFragment(Fragment fragment, int transition, int transitionStyle) {
+
+    public void detachFragment(Fragment fragment) {
         if (DEBUG) Log.v(TAG, "detach: " + fragment);
         if (!fragment.mDetached) {
             fragment.mDetached = true;
@@ -1346,12 +1447,11 @@
                     mNeedMenuInvalidate = true;
                 }
                 fragment.mAdded = false;
-                moveToState(fragment, Fragment.CREATED, transition, transitionStyle, false);
             }
         }
     }
 
-    public void attachFragment(Fragment fragment, int transition, int transitionStyle) {
+    public void attachFragment(Fragment fragment) {
         if (DEBUG) Log.v(TAG, "attach: " + fragment);
         if (fragment.mDetached) {
             fragment.mDetached = false;
@@ -1368,7 +1468,6 @@
                 if (fragment.mHasMenu && fragment.mMenuVisible) {
                     mNeedMenuInvalidate = true;
                 }
-                moveToState(fragment, mCurState, transition, transitionStyle, false);
             }
         }
     }
@@ -1447,7 +1546,7 @@
      * @param allowStateLoss whether to allow loss of state information
      * @throws IllegalStateException if the activity has been destroyed
      */
-    public void enqueueAction(Runnable action, boolean allowStateLoss) {
+    public void enqueueAction(OpGenerator action, boolean allowStateLoss) {
         if (!allowStateLoss) {
             checkStateLoss();
         }
@@ -1456,10 +1555,25 @@
                 throw new IllegalStateException("Activity has been destroyed");
             }
             if (mPendingActions == null) {
-                mPendingActions = new ArrayList<Runnable>();
+                mPendingActions = new ArrayList<>();
             }
             mPendingActions.add(action);
-            if (mPendingActions.size() == 1) {
+            scheduleCommit();
+        }
+    }
+
+    /**
+     * Schedules the execution when one hasn't been scheduled already. This should happen
+     * the first time {@link #enqueueAction(OpGenerator, boolean)} is called or when
+     * a postponed transaction has been started with
+     * {@link Fragment#startPostponedEnterTransition()}
+     */
+    private void scheduleCommit() {
+        synchronized (this) {
+            boolean postponeReady =
+                    mPostponedTransactions != null && !mPostponedTransactions.isEmpty();
+            boolean pendingReady = mPendingActions != null && mPendingActions.size() == 1;
+            if (postponeReady || pendingReady) {
                 mHost.getHandler().removeCallbacks(mExecCommit);
                 mHost.getHandler().post(mExecCommit);
             }
@@ -1522,7 +1636,13 @@
         }
     }
 
-    public void execSingleAction(Runnable action, boolean allowStateLoss) {
+    /**
+     * Broken out from exec*, this prepares for gathering and executing operations.
+     *
+     * @param allowStateLoss true if state loss should be ignored or false if it should be
+     *                       checked.
+     */
+    private void ensureExecReady(boolean allowStateLoss) {
         if (mExecutingActions) {
             throw new IllegalStateException("FragmentManager is already executing transactions");
         }
@@ -1535,55 +1655,50 @@
             checkStateLoss();
         }
 
-        mExecutingActions = true;
-        try {
-            action.run();
-        } finally {
-            mExecutingActions = false;
+        if (mTmpRecords == null) {
+            mTmpRecords = new ArrayList<>();
+            mTmpIsPop = new ArrayList<>();
+        }
+        executePostponedTransaction(null, null);
+    }
+
+    public void execSingleAction(OpGenerator action, boolean allowStateLoss) {
+        ensureExecReady(allowStateLoss);
+        if (action.generateOps(mTmpRecords, mTmpIsPop)) {
+            mExecutingActions = true;
+            try {
+                optimizeAndExecuteOps(mTmpRecords, mTmpIsPop);
+            } finally {
+                cleanupExec();
+            }
         }
 
         doPendingDeferredStart();
     }
 
     /**
+     * Broken out of exec*, this cleans up the mExecutingActions and the temporary structures
+     * used in executing operations.
+     */
+    private void cleanupExec() {
+        mExecutingActions = false;
+        mTmpIsPop.clear();
+        mTmpRecords.clear();
+    }
+
+    /**
      * Only call from main thread!
      */
     public boolean execPendingActions() {
-        if (mExecutingActions) {
-            throw new IllegalStateException("Recursive entry to executePendingTransactions");
-        }
-        
-        if (Looper.myLooper() != mHost.getHandler().getLooper()) {
-            throw new IllegalStateException("Must be called from main thread of process");
-        }
+        ensureExecReady(true);
 
         boolean didSomething = false;
-
-        while (true) {
-            int numActions;
-            
-            synchronized (this) {
-                if (mPendingActions == null || mPendingActions.size() == 0) {
-                    break;
-                }
-                
-                numActions = mPendingActions.size();
-                if (mTmpActions == null || mTmpActions.length < numActions) {
-                    mTmpActions = new Runnable[numActions];
-                }
-                mPendingActions.toArray(mTmpActions);
-                mPendingActions.clear();
-                mHost.getHandler().removeCallbacks(mExecCommit);
-            }
-            
+        while (generateOpsForPendingActions(mTmpRecords, mTmpIsPop)) {
             mExecutingActions = true;
             try {
-                for (int i = 0; i < numActions; i++) {
-                    mTmpActions[i].run();
-                    mTmpActions[i] = null;
-                }
+                optimizeAndExecuteOps(mTmpRecords, mTmpIsPop);
             } finally {
-                mExecutingActions = false;
+                cleanupExec();
             }
             didSomething = true;
         }
@@ -1593,6 +1708,382 @@
         return didSomething;
     }
 
+    /**
+     * Complete the execution of transactions that have previously been postponed, but are
+     * now ready.
+     */
+    private void executePostponedTransaction(ArrayList<BackStackRecord> records,
+            ArrayList<Boolean> isRecordPop) {
+        int numPostponed = mPostponedTransactions == null ? 0 : mPostponedTransactions.size();
+        for (int i = 0; i < numPostponed; i++) {
+            StartEnterTransitionListener listener = mPostponedTransactions.get(i);
+            if (records != null && !listener.mIsBack) {
+                int index = records.indexOf(listener.mRecord);
+                if (index != -1 && isRecordPop.get(index)) {
+                    listener.cancelTransaction();
+                    continue;
+                }
+            }
+            if (listener.isReady() || (records != null &&
+                    listener.mRecord.interactsWith(records, 0, records.size()))) {
+                mPostponedTransactions.remove(i);
+                i--;
+                numPostponed--;
+                int index;
+                if (records != null && !listener.mIsBack &&
+                        (index = records.indexOf(listener.mRecord)) != -1 &&
+                        isRecordPop.get(index)) {
+                    // This is popping a postponed transaction
+                    listener.cancelTransaction();
+                } else {
+                    listener.completeTransaction();
+                }
+            }
+        }
+    }
+
+    /**
+     * Optimizes BackStackRecord operations. This method merges operations of proximate records
+     * that allow optimization. See {@link FragmentTransaction#setAllowOptimization(boolean)}.
+     * <p>
+     * For example, a transaction that adds to the back stack and then another that pops that
+     * back stack record will be optimized.
+     * <p>
+     * Likewise, two transactions committed that are executed at the same time will be optimized
+     * as well as two pop operations executed together.
+     *
+     * @param records The records pending execution
+     * @param isRecordPop The direction that these records are being run.
+     */
+    private void optimizeAndExecuteOps(ArrayList<BackStackRecord> records,
+            ArrayList<Boolean> isRecordPop) {
+        if (records == null || records.isEmpty()) {
+            return;
+        }
+
+        if (isRecordPop == null || records.size() != isRecordPop.size()) {
+            throw new IllegalStateException("Internal error with the back stack records");
+        }
+
+        // Force start of any postponed transactions that interact with scheduled transactions:
+        executePostponedTransaction(records, isRecordPop);
+
+        final int numRecords = records.size();
+        int startIndex = 0;
+        for (int recordNum = 0; recordNum < numRecords; recordNum++) {
+            final boolean canOptimize = records.get(recordNum).mAllowOptimization;
+            if (!canOptimize) {
+                // execute all previous transactions
+                if (startIndex != recordNum) {
+                    executeOpsTogether(records, isRecordPop, startIndex, recordNum);
+                }
+                // execute all unoptimized together
+                int optimizeEnd;
+                for (optimizeEnd = recordNum + 1; optimizeEnd < numRecords; optimizeEnd++) {
+                    if (records.get(optimizeEnd).mAllowOptimization) {
+                        break;
+                    }
+                }
+                executeOpsTogether(records, isRecordPop, recordNum, optimizeEnd);
+                startIndex = optimizeEnd;
+                recordNum = optimizeEnd - 1;
+            }
+        }
+        if (startIndex != numRecords) {
+            executeOpsTogether(records, isRecordPop, startIndex, numRecords);
+        }
+    }
+
+    /**
+     * Optimizes a subset of a list of BackStackRecords, all of which either allow optimization or
+     * do not allow optimization.
+     * @param records A list of BackStackRecords that are to be optimized
+     * @param isRecordPop The direction that these records are being run.
+     * @param startIndex The index of the first record in <code>records</code> to be optimized
+     * @param endIndex One more than the final record index in <code>records</code> to optimize.
+     */
+    private void executeOpsTogether(ArrayList<BackStackRecord> records,
+            ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) {
+        final boolean allowOptimization = records.get(startIndex).mAllowOptimization;
+        boolean addToBackStack = false;
+        if (mTmpAddedFragments == null) {
+            mTmpAddedFragments = new ArrayList<>();
+        } else {
+            mTmpAddedFragments.clear();
+        }
+        if (mAdded != null) {
+            mTmpAddedFragments.addAll(mAdded);
+        }
+        for (int recordNum = startIndex; recordNum < endIndex; recordNum++) {
+            final BackStackRecord record = records.get(recordNum);
+            final boolean isPop = isRecordPop.get(recordNum);
+            if (!isPop) {
+                record.expandReplaceOps(mTmpAddedFragments);
+            }
+            final int bumpAmount = isPop ? -1 : 1;
+            record.bumpBackStackNesting(bumpAmount);
+            addToBackStack = addToBackStack || record.mAddToBackStack;
+        }
+        mTmpAddedFragments.clear();
+
+        if (!allowOptimization) {
+            FragmentTransition.startTransitions(this, records, isRecordPop, startIndex, endIndex,
+                    false);
+        }
+        executeOps(records, isRecordPop, startIndex, endIndex);
+
+        int postponeIndex = endIndex;
+        if (allowOptimization) {
+            moveFragmentsToInvisible();
+            postponeIndex = postponePostponableTransactions(records, isRecordPop,
+                    startIndex, endIndex);
+        }
+
+        if (postponeIndex != startIndex && allowOptimization) {
+            // need to run something now
+            FragmentTransition.startTransitions(this, records, isRecordPop, startIndex,
+                    postponeIndex, true);
+            moveToState(mCurState);
+        }
+
+        for (int recordNum = startIndex; recordNum < endIndex; recordNum++) {
+            final BackStackRecord record = records.get(recordNum);
+            final boolean isPop = isRecordPop.get(recordNum);
+            if (isPop && record.mIndex >= 0) {
+                freeBackStackIndex(record.mIndex);
+                record.mIndex = -1;
+            }
+        }
+
+        if (addToBackStack) {
+            reportBackStackChanged();
+        }
+    }
+
+    /**
+     * Examine all transactions and determine which ones are marked as postponed. Those will
+     * have their operations rolled back and moved to the end of the record list (up to endIndex).
+     * It will also add the postponed transaction to the queue.
+     *
+     * @param records A list of BackStackRecords that should be checked.
+     * @param isRecordPop The direction that these records are being run.
+     * @param startIndex The index of the first record in <code>records</code> to be checked
+     * @param endIndex One more than the final record index in <code>records</code> to be checked.
+     * @return The index of the first postponed transaction or endIndex if no transaction was
+     * postponed.
+     */
+    private int postponePostponableTransactions(ArrayList<BackStackRecord> records,
+            ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) {
+        int postponeIndex = endIndex;
+        for (int i = endIndex - 1; i >= startIndex; i--) {
+            final BackStackRecord record = records.get(i);
+            final boolean isPop = isRecordPop.get(i);
+            boolean isPostponed = record.isPostponed() &&
+                    !record.interactsWith(records, i + 1, endIndex);
+            if (isPostponed) {
+                if (mPostponedTransactions == null) {
+                    mPostponedTransactions = new ArrayList<>();
+                }
+                StartEnterTransitionListener listener =
+                        new StartEnterTransitionListener(record, isPop);
+                mPostponedTransactions.add(listener);
+                record.setOnStartPostponedListener(listener);
+
+                // roll back the transaction
+                if (isPop) {
+                    record.executeOps();
+                } else {
+                    record.executePopOps();
+                }
+
+                // move to the end
+                postponeIndex--;
+                if (i != postponeIndex) {
+                    records.remove(i);
+                    records.add(postponeIndex, record);
+                }
+
+                // different views may be visible now
+                moveFragmentsToInvisible();
+            }
+        }
+        return postponeIndex;
+    }
+
+    /**
+     * When a postponed transaction is ready to be started, this completes the transaction,
+     * removing, hiding, or showing views as well as starting the animations and transitions.
+     * <p>
+     * {@code runtransitions} is set to false when the transaction postponement was interrupted
+     * abnormally -- normally by a new transaction being started that affects the postponed
+     * transaction.
+     *
+     * @param record The transaction to run
+     * @param isPop true if record is popping or false if it is adding
+     * @param runTransitions true if the fragment transition should be run or false otherwise.
+     * @param moveToState true if the state should be changed after executing the operations.
+     *                    This is false when the transaction is canceled when a postponed
+     *                    transaction is popped.
+     */
+    private void completeExecute(BackStackRecord record, boolean isPop, boolean runTransitions,
+            boolean moveToState) {
+        ArrayList<BackStackRecord> records = new ArrayList<>(1);
+        ArrayList<Boolean> isRecordPop = new ArrayList<>(1);
+        records.add(record);
+        isRecordPop.add(isPop);
+        executeOps(records, isRecordPop, 0, 1);
+        if (runTransitions) {
+            FragmentTransition.startTransitions(this, records, isRecordPop, 0, 1, true);
+        }
+        if (moveToState) {
+            moveToState(mCurState);
+        } else if (mActive != null) {
+            final int numActive = mActive.size();
+            for (int i = 0; i < numActive; i++) {
+                // Allow added fragments to be removed during the pop since we aren't going
+                // to move them to the final state with moveToState(mCurState).
+                Fragment fragment = mActive.get(i);
+                if (fragment.mView != null && fragment.mIsNewlyAdded &&
+                        record.interactsWith(fragment.mContainerId)) {
+                    fragment.mIsNewlyAdded = false;
+                }
+            }
+        }
+    }
+
+    /**
+     * Find a fragment within the fragment's container whose View should be below the passed
+     * fragment. {@code null} is returned when the fragment has no View or if there should be
+     * no fragment with a View below the given fragment.
+     *
+     * As an example, if mAdded has two Fragments with Views sharing the same container:
+     * FragmentA
+     * FragmentB
+     *
+     * Then, when processing FragmentB, FragmentA will be returned. If, however, FragmentA
+     * had no View, null would be returned.
+     *
+     * @param f The fragment that may be on top of another fragment.
+     * @return The fragment with a View under f, if one exists or null if f has no View or
+     * there are no fragments with Views in the same container.
+     */
+    private Fragment findFragmentUnder(Fragment f) {
+        final ViewGroup container = f.mContainer;
+        final View view = f.mView;
+
+        if (container == null || view == null) {
+            return null;
+        }
+
+        final int fragmentIndex = mAdded.indexOf(f);
+        for (int i = fragmentIndex - 1; i >= 0; i--) {
+            Fragment underFragment = mAdded.get(i);
+            if (underFragment.mContainer == container && underFragment.mView != null) {
+                // Found the fragment under this one
+                return underFragment;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Run the operations in the BackStackRecords, either to push or pop.
+     *
+     * @param records The list of records whose operations should be run.
+     * @param isRecordPop The direction that these records are being run.
+     * @param startIndex The index of the first entry in records to run.
+     * @param endIndex One past the index of the final entry in records to run.
+     */
+    private static void executeOps(ArrayList<BackStackRecord> records,
+            ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) {
+        for (int i = startIndex; i < endIndex; i++) {
+            final BackStackRecord record = records.get(i);
+            final boolean isPop = isRecordPop.get(i);
+            if (isPop) {
+                record.executePopOps();
+            } else {
+                record.executeOps();
+            }
+        }
+    }
+
+    /**
+     * Ensure that fragments that are added are moved to at least the CREATED state.
+     * Any newly-added Views are made INVISIBLE so that the Transaction can be postponed
+     * with {@link Fragment#postponeEnterTransition()}.
+     */
+    private void moveFragmentsToInvisible() {
+        if (mCurState < Fragment.CREATED) {
+            return;
+        }
+        // We want to leave the fragment in the started state
+        final int state = Math.min(mCurState, Fragment.STARTED);
+        final int numAdded = mAdded == null ? 0 : mAdded.size();
+        for (int i = 0; i < numAdded; i++) {
+            Fragment fragment = mAdded.get(i);
+            if (fragment.mState < state) {
+                moveToState(fragment, state, fragment.getNextAnim(), fragment.getNextTransition(), false);
+                if (fragment.mView != null && !fragment.mHidden && fragment.mIsNewlyAdded) {
+                    fragment.mView.setVisibility(View.INVISIBLE);
+                }
+            }
+        }
+    }
+
+    /**
+     * Starts all postponed transactions regardless of whether they are ready or not.
+     */
+    private void forcePostponedTransactions() {
+        if (mPostponedTransactions != null) {
+            while (!mPostponedTransactions.isEmpty()) {
+                mPostponedTransactions.remove(0).completeTransaction();
+            }
+        }
+    }
+
+    /**
+     * Ends the animations of fragments so that they immediately reach the end state.
+     * This is used prior to saving the state so that the correct state is saved.
+     */
+    private void endAnimatingAwayFragments() {
+        final int numFragments = mActive == null ? 0 : mActive.size();
+        for (int i = 0; i < numFragments; i++) {
+            Fragment fragment = mActive.get(i);
+            if (fragment != null && fragment.getAnimatingAway() != null) {
+                // Give up waiting for the animation and just end it.
+                fragment.getAnimatingAway().end();
+            }
+        }
+    }
+
+    /**
+     * Adds all records in the pending actions to records and whether they are add or pop
+     * operations to isPop. After executing, the pending actions will be empty.
+     *
+     * @param records All pending actions will generate BackStackRecords added to this.
+     *                This contains the transactions, in order, to execute.
+     * @param isPop All pending actions will generate booleans to add to this. This contains
+     *              an entry for each entry in records to indicate whether or not it is a
+     *              pop action.
+     */
+    private boolean generateOpsForPendingActions(ArrayList<BackStackRecord> records,
+            ArrayList<Boolean> isPop) {
+        int numActions;
+        synchronized (this) {
+            if (mPendingActions == null || mPendingActions.size() == 0) {
+                return false;
+            }
+
+            numActions = mPendingActions.size();
+            for (int i = 0; i < numActions; i++) {
+                mPendingActions.get(i).generateOps(records, isPop);
+            }
+            mPendingActions.clear();
+            mHost.getHandler().removeCallbacks(mExecCommit);
+        }
+        return numActions > 0;
+    }
+
     void doPendingDeferredStart() {
         if (mHavePendingDeferredStart) {
             boolean loadersRunning = false;
@@ -1624,24 +2115,19 @@
         mBackStack.add(state);
         reportBackStackChanged();
     }
-    
-    boolean popBackStackState(Handler handler, String name, int id, int flags) {
+
+    boolean popBackStackState(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop,
+            String name, int id, int flags) {
         if (mBackStack == null) {
             return false;
         }
-        if (name == null && id < 0 && (flags&POP_BACK_STACK_INCLUSIVE) == 0) {
-            int last = mBackStack.size()-1;
+        if (name == null && id < 0 && (flags & POP_BACK_STACK_INCLUSIVE) == 0) {
+            int last = mBackStack.size() - 1;
             if (last < 0) {
                 return false;
             }
-            final BackStackRecord bss = mBackStack.remove(last);
-            SparseArray<BackStackRecord.FragmentContainerTransition> transitioningFragments =
-                    new SparseArray<>();
-            if (mCurState >= Fragment.CREATED) {
-                bss.calculateBackFragments(transitioningFragments);
-            }
-            bss.popFromBackStack(true, null, transitioningFragments);
-            reportBackStackChanged();
+            records.add(mBackStack.remove(last));
+            isRecordPop.add(true);
         } else {
             int index = -1;
             if (name != null || id >= 0) {
@@ -1678,25 +2164,10 @@
             if (index == mBackStack.size()-1) {
                 return false;
             }
-            final ArrayList<BackStackRecord> states
-                    = new ArrayList<BackStackRecord>();
-            for (int i=mBackStack.size()-1; i>index; i--) {
-                states.add(mBackStack.remove(i));
+            for (int i = mBackStack.size() - 1; i > index; i--) {
+                records.add(mBackStack.remove(i));
+                isRecordPop.add(true);
             }
-            final int LAST = states.size()-1;
-            SparseArray<BackStackRecord.FragmentContainerTransition> transitioningFragments =
-                    new SparseArray<>();
-            if (mCurState >= Fragment.CREATED) {
-                for (int i = 0; i <= LAST; i++) {
-                    states.get(i).calculateBackFragments(transitioningFragments);
-                }
-            }
-            BackStackRecord.TransitionState state = null;
-            for (int i=0; i<=LAST; i++) {
-                if (DEBUG) Log.v(TAG, "Popping back stack state: " + states.get(i));
-                state = states.get(i).popFromBackStack(i == LAST, state, transitioningFragments);
-            }
-            reportBackStackChanged();
         }
         return true;
     }
@@ -1795,6 +2266,8 @@
     Parcelable saveAllState() {
         // Make sure all pending operations have now been executed to get
         // our state update-to-date.
+        forcePostponedTransactions();
+        endAnimatingAwayFragments();
         execPendingActions();
 
         mStateSaved = true;
@@ -2036,40 +2509,40 @@
     
     public void dispatchCreate() {
         mStateSaved = false;
-        moveToState(Fragment.CREATED, false);
+        moveToState(Fragment.CREATED);
     }
     
     public void dispatchActivityCreated() {
         mStateSaved = false;
-        moveToState(Fragment.ACTIVITY_CREATED, false);
+        moveToState(Fragment.ACTIVITY_CREATED);
     }
     
     public void dispatchStart() {
         mStateSaved = false;
-        moveToState(Fragment.STARTED, false);
+        moveToState(Fragment.STARTED);
     }
     
     public void dispatchResume() {
         mStateSaved = false;
-        moveToState(Fragment.RESUMED, false);
+        moveToState(Fragment.RESUMED);
     }
     
     public void dispatchPause() {
-        moveToState(Fragment.STARTED, false);
+        moveToState(Fragment.STARTED);
     }
     
     public void dispatchStop() {
-        moveToState(Fragment.STOPPED, false);
+        moveToState(Fragment.STOPPED);
     }
     
     public void dispatchDestroyView() {
-        moveToState(Fragment.CREATED, false);
+        moveToState(Fragment.CREATED);
     }
 
     public void dispatchDestroy() {
         mDestroyed = true;
         execPendingActions();
-        moveToState(Fragment.INITIALIZING, false);
+        moveToState(Fragment.INITIALIZING);
         mHost = null;
         mContainer = null;
         mParent = null;
@@ -2363,4 +2836,121 @@
     LayoutInflater.Factory2 getLayoutInflaterFactory() {
         return this;
     }
+
+    /**
+     * An add or pop transaction to be scheduled for the UI thread.
+     */
+    interface OpGenerator {
+        /**
+         * Generate transactions to add to {@code records} and whether or not the transaction is
+         * an add or pop to {@code isRecordPop}.
+         *
+         * records and isRecordPop must be added equally so that each transaction in records
+         * matches the boolean for whether or not it is a pop in isRecordPop.
+         *
+         * @param records A list to add transactions to.
+         * @param isRecordPop A list to add whether or not the transactions added to records is
+         *                    a pop transaction.
+         * @return true if something was added or false otherwise.
+         */
+        boolean generateOps(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop);
+    }
+
+    /**
+     * A pop operation OpGenerator. This will be run on the UI thread and will generate the
+     * transactions that will be popped if anything can be popped.
+     */
+    private class PopBackStackState implements OpGenerator {
+        final String mName;
+        final int mId;
+        final int mFlags;
+
+        public PopBackStackState(String name, int id, int flags) {
+            mName = name;
+            mId = id;
+            mFlags = flags;
+        }
+
+        @Override
+        public boolean generateOps(ArrayList<BackStackRecord> records,
+                ArrayList<Boolean> isRecordPop) {
+            return popBackStackState(records, isRecordPop, mName, mId, mFlags);
+        }
+    }
+
+    /**
+     * A listener for a postponed transaction. This waits until
+     * {@link Fragment#startPostponedEnterTransition()} is called or a transaction is started
+     * that interacts with this one, based on interactions with the fragment container.
+     */
+    static class StartEnterTransitionListener
+            implements Fragment.OnStartEnterTransitionListener {
+        private final boolean mIsBack;
+        private final BackStackRecord mRecord;
+        private int mNumPostponed;
+
+        public StartEnterTransitionListener(BackStackRecord record, boolean isBack) {
+            mIsBack = isBack;
+            mRecord = record;
+        }
+
+        /**
+         * Called from {@link Fragment#startPostponedEnterTransition()}, this decreases the
+         * number of Fragments that are postponed. This may cause the transaction to schedule
+         * to finish running and run transitions and animations.
+         */
+        @Override
+        public void onStartEnterTransition() {
+            mNumPostponed--;
+            if (mNumPostponed != 0) {
+                return;
+            }
+            mRecord.mManager.scheduleCommit();
+        }
+
+        /**
+         * Called from {@link Fragment#
+         * setOnStartEnterTransitionListener(Fragment.OnStartEnterTransitionListener)}, this
+         * increases the number of fragments that are postponed as part of this transaction.
+         */
+        @Override
+        public void startListening() {
+            mNumPostponed++;
+        }
+
+        /**
+         * @return true if there are no more postponed fragments as part of the transaction.
+         */
+        public boolean isReady() {
+            return mNumPostponed == 0;
+        }
+
+        /**
+         * Completes the transaction and start the animations and transitions. This may skip
+         * the transitions if this is called before all fragments have called
+         * {@link Fragment#startPostponedEnterTransition()}.
+         */
+        public void completeTransaction() {
+            final boolean canceled;
+            canceled = mNumPostponed > 0;
+            FragmentManagerImpl manager = mRecord.mManager;
+            final int numAdded = manager.mAdded.size();
+            for (int i = 0; i < numAdded; i++) {
+                final Fragment fragment = manager.mAdded.get(i);
+                fragment.setOnStartEnterTransitionListener(null);
+                if (canceled && fragment.isPostponed()) {
+                    fragment.startPostponedEnterTransition();
+                }
+            }
+            mRecord.mManager.completeExecute(mRecord, mIsBack, !canceled, true);
+        }
+
+        /**
+         * Cancels this transaction instead of completing it. That means that the state isn't
+         * changed, so the pop results in no change to the state.
+         */
+        public void cancelTransaction() {
+            mRecord.mManager.completeExecute(mRecord, mIsBack, false, false);
+        }
+    }
 }
diff --git a/core/java/android/app/FragmentTransaction.java b/core/java/android/app/FragmentTransaction.java
index 633e85b..25a7839 100644
--- a/core/java/android/app/FragmentTransaction.java
+++ b/core/java/android/app/FragmentTransaction.java
@@ -260,6 +260,32 @@
     public abstract FragmentTransaction setBreadCrumbShortTitle(CharSequence text);
 
     /**
+     * Sets whether or not to allow optimizing operations within and across
+     * transactions. Optimizing fragment transaction's operations can eliminate
+     * operations that cancel. For example, if two transactions are executed
+     * together, one that adds a fragment A and the next replaces it with fragment B,
+     * the operations will cancel and only fragment B will be added. That means that
+     * fragment A may not go through the creation/destruction lifecycle.
+     * <p>
+     * The side effect of optimization is that fragments may have state changes
+     * out of the expected order. For example, one transaction adds fragment A,
+     * a second adds fragment B, then a third removes fragment A. Without optimization,
+     * fragment B could expect that while it is being created, fragment A will also
+     * exist because fragment A will be removed after fragment B was added.
+     * With optimization, fragment B cannot expect fragment A to exist when
+     * it has been created because fragment A's add/remove will be optimized out.
+     * <p>
+     * The default is {@code false} for applications targeting version
+     * versions prior to O and {@code true} for applications targeting O and
+     * later.
+     *
+     * @param allowOptimization {@code true} to enable optimizing operations
+     *                          or {@code false} to disable optimizing
+     *                          operations on this transaction.
+     */
+    public abstract FragmentTransaction setAllowOptimization(boolean allowOptimization);
+
+    /**
      * Schedules a commit of this transaction.  The commit does
      * not happen immediately; it will be scheduled as work on the main thread
      * to be done the next time that thread is ready.
diff --git a/core/java/android/app/FragmentTransition.java b/core/java/android/app/FragmentTransition.java
new file mode 100644
index 0000000..6f52114
--- /dev/null
+++ b/core/java/android/app/FragmentTransition.java
@@ -0,0 +1,1330 @@
+/*
+ * 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.app;
+
+import android.graphics.Rect;
+import android.os.Build;
+import android.transition.Transition;
+import android.transition.TransitionManager;
+import android.transition.TransitionSet;
+import android.util.ArrayMap;
+import android.util.SparseArray;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.ViewTreeObserver;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Contains the Fragment Transition functionality for both optimized and unoptimized
+ * Fragment Transactions. With optimized fragment transactions, all Views have been
+ * added to the View hierarchy prior to calling startTransitions. With
+ */
+class FragmentTransition {
+    /**
+     * The inverse of all BackStackRecord operation commands. This assumes that
+     * REPLACE operations have already been replaced by add/remove operations.
+     */
+    private static final int[] INVERSE_OPS = {
+            BackStackRecord.OP_NULL,   // inverse of OP_NULL (error)
+            BackStackRecord.OP_REMOVE, // inverse of OP_ADD
+            BackStackRecord.OP_NULL,   // inverse of OP_REPLACE (error)
+            BackStackRecord.OP_ADD,    // inverse of OP_REMOVE
+            BackStackRecord.OP_SHOW,   // inverse of OP_HIDE
+            BackStackRecord.OP_HIDE,   // inverse of OP_SHOW
+            BackStackRecord.OP_ATTACH, // inverse of OP_DETACH
+            BackStackRecord.OP_DETACH, // inverse of OP_ATTACH
+    };
+
+    /**
+     * The main entry point for Fragment Transitions, this starts the transitions
+     * set on the leaving Fragment's {@link Fragment#getExitTransition()}, the
+     * entering Fragment's {@link Fragment#getEnterTransition()} and
+     * {@link Fragment#getSharedElementEnterTransition()}. When popping,
+     * the leaving Fragment's {@link Fragment#getReturnTransition()} and
+     * {@link Fragment#getSharedElementReturnTransition()} and the entering
+     * {@link Fragment#getReenterTransition()} will be run.
+     * <p>
+     * With optimized Fragment Transitions, all Views have been added to the
+     * View hierarchy prior to calling this method. The incoming Fragment's Views
+     * will be INVISIBLE. With unoptimized Fragment Transitions, this method
+     * is called before any change has been made to the hierarchy. That means
+     * that the added Fragments have not created their Views yet and the hierarchy
+     * is unknown.
+     *
+     * @param fragmentManager The executing FragmentManagerImpl
+     * @param records The list of transactions being executed.
+     * @param isRecordPop For each transaction, whether it is a pop transaction or not.
+     * @param startIndex The first index into records and isRecordPop to execute as
+     *                   part of this transition.
+     * @param endIndex One past the last index into records and isRecordPop to execute
+     *                 as part of this transition.
+     * @param isOptimized true if this is an optimized transaction, meaning that the
+     *                    Views of incoming fragments have been added. false if the
+     *                    transaction has yet to be run and Views haven't been created.
+     */
+    static void startTransitions(FragmentManagerImpl fragmentManager,
+            ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop,
+            int startIndex, int endIndex, boolean isOptimized) {
+        if (fragmentManager.mCurState < Fragment.CREATED) {
+            return;
+        }
+        SparseArray<FragmentContainerTransition> transitioningFragments =
+                new SparseArray<>();
+        for (int i = startIndex; i < endIndex; i++) {
+            final BackStackRecord record = records.get(i);
+            final boolean isPop = isRecordPop.get(i);
+            if (isPop) {
+                calculatePopFragments(record, transitioningFragments, isOptimized);
+            } else {
+                calculateFragments(record, transitioningFragments, isOptimized);
+            }
+        }
+
+        if (transitioningFragments.size() != 0) {
+            final View nonExistentView = new View(fragmentManager.mHost.getContext());
+            final int numContainers = transitioningFragments.size();
+            for (int i = 0; i < numContainers; i++) {
+                int containerId = transitioningFragments.keyAt(i);
+                ArrayMap<String, String> nameOverrides = calculateNameOverrides(containerId,
+                        records, isRecordPop, startIndex, endIndex);
+
+                FragmentContainerTransition containerTransition = transitioningFragments.valueAt(i);
+
+                if (isOptimized) {
+                    configureTransitionsOptimized(fragmentManager, containerId,
+                            containerTransition, nonExistentView, nameOverrides);
+                } else {
+                    configureTransitionsUnoptimized(fragmentManager, containerId,
+                            containerTransition, nonExistentView, nameOverrides);
+                }
+            }
+        }
+    }
+
+    /**
+     * Iterates through the transactions that affect a given fragment container
+     * and tracks the shared element names across transactions. This is most useful
+     * in pop transactions where the names of shared elements are known.
+     *
+     * @param containerId The container ID that is executing the transition.
+     * @param records The list of transactions being executed.
+     * @param isRecordPop For each transaction, whether it is a pop transaction or not.
+     * @param startIndex The first index into records and isRecordPop to execute as
+     *                   part of this transition.
+     * @param endIndex One past the last index into records and isRecordPop to execute
+     *                 as part of this transition.
+     * @return A map from the initial shared element name to the final shared element name
+     * before any onMapSharedElements is run.
+     */
+    private static ArrayMap<String, String> calculateNameOverrides(int containerId,
+            ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop,
+            int startIndex, int endIndex) {
+        ArrayMap<String, String> nameOverrides = new ArrayMap<>();
+        for (int recordNum = endIndex - 1; recordNum >= startIndex; recordNum--) {
+            final BackStackRecord record = records.get(recordNum);
+            if (!record.interactsWith(containerId)) {
+                continue;
+            }
+            final boolean isPop = isRecordPop.get(recordNum);
+            if (record.mSharedElementSourceNames != null) {
+                final int numSharedElements = record.mSharedElementSourceNames.size();
+                final ArrayList<String> sources;
+                final ArrayList<String> targets;
+                if (isPop) {
+                    targets = record.mSharedElementSourceNames;
+                    sources = record.mSharedElementTargetNames;
+                } else {
+                    sources = record.mSharedElementSourceNames;
+                    targets = record.mSharedElementTargetNames;
+                }
+                for (int i = 0; i < numSharedElements; i++) {
+                    String sourceName = sources.get(i);
+                    String targetName = targets.get(i);
+                    String previousTarget = nameOverrides.remove(targetName);
+                    if (previousTarget != null) {
+                        nameOverrides.put(sourceName, previousTarget);
+                    } else {
+                        nameOverrides.put(sourceName, targetName);
+                    }
+                }
+            }
+        }
+        return nameOverrides;
+    }
+
+    /**
+     * Configures a transition for a single fragment container for which the transaction was
+     * optimized. That means that all Fragment Views have been added and incoming fragment
+     * Views are marked invisible.
+     *
+     * @param fragmentManager The executing FragmentManagerImpl
+     * @param containerId The container ID that is executing the transition.
+     * @param fragments A structure holding the transitioning fragments in this container.
+     * @param nonExistentView A View that does not exist in the hierarchy. This is used to
+     *                        prevent transitions from acting on other Views when there is no
+     *                        other target.
+     * @param nameOverrides A map of the shared element names from the starting fragment to
+     *                      the final fragment's Views as given in
+     *                      {@link FragmentTransaction#addSharedElement(View, String)}.
+     */
+    private static void configureTransitionsOptimized(FragmentManagerImpl fragmentManager,
+            int containerId, FragmentContainerTransition fragments,
+            View nonExistentView, ArrayMap<String, String> nameOverrides) {
+        ViewGroup sceneRoot = (ViewGroup) fragmentManager.mContainer.onFindViewById(containerId);
+        if (sceneRoot == null) {
+            return;
+        }
+        final Fragment inFragment = fragments.lastIn;
+        final Fragment outFragment = fragments.firstOut;
+        final boolean inIsPop = fragments.lastInIsPop;
+        final boolean outIsPop = fragments.firstOutIsPop;
+
+        ArrayList<View> sharedElementsIn = new ArrayList<>();
+        ArrayList<View> sharedElementsOut = new ArrayList<>();
+        Transition enterTransition = getEnterTransition(inFragment, inIsPop);
+        Transition exitTransition = getExitTransition(outFragment, outIsPop);
+
+        TransitionSet sharedElementTransition = configureSharedElementsOptimized(sceneRoot,
+                nonExistentView, nameOverrides, fragments, sharedElementsOut, sharedElementsIn,
+                enterTransition, exitTransition);
+
+        if (enterTransition == null && sharedElementTransition == null &&
+                exitTransition == null) {
+            return; // no transitions!
+        }
+
+        ArrayList<View> exitingViews = configureEnteringExitingViews(exitTransition,
+                outFragment, sharedElementsOut, nonExistentView);
+
+        ArrayList<View> enteringViews = configureEnteringExitingViews(enterTransition,
+                inFragment, sharedElementsIn, nonExistentView);
+
+        setViewVisibility(enteringViews, View.INVISIBLE);
+
+        Transition transition = mergeTransitions(enterTransition, exitTransition,
+                sharedElementTransition, inFragment, inIsPop);
+
+        if (transition != null) {
+            transition.setNameOverrides(nameOverrides);
+            scheduleRemoveTargets(transition,
+                    enterTransition, enteringViews, exitTransition, exitingViews,
+                    sharedElementTransition, sharedElementsIn);
+            TransitionManager.beginDelayedTransition(sceneRoot, transition);
+            setViewVisibility(enteringViews, View.VISIBLE);
+            // Swap the shared element targets
+            if (sharedElementTransition != null) {
+                sharedElementTransition.getTargets().clear();
+                sharedElementTransition.getTargets().addAll(sharedElementsIn);
+                replaceTargets(sharedElementTransition, sharedElementsOut, sharedElementsIn);
+            }
+        }
+    }
+
+    /**
+     * Configures a transition for a single fragment container for which the transaction was
+     * not optimized. That means that the transaction has not been executed yet, so incoming
+     * Views are not yet known.
+     *
+     * @param fragmentManager The executing FragmentManagerImpl
+     * @param containerId The container ID that is executing the transition.
+     * @param fragments A structure holding the transitioning fragments in this container.
+     * @param nonExistentView A View that does not exist in the hierarchy. This is used to
+     *                        prevent transitions from acting on other Views when there is no
+     *                        other target.
+     * @param nameOverrides A map of the shared element names from the starting fragment to
+     *                      the final fragment's Views as given in
+     *                      {@link FragmentTransaction#addSharedElement(View, String)}.
+     */
+    private static void configureTransitionsUnoptimized(FragmentManagerImpl fragmentManager,
+            int containerId, FragmentContainerTransition fragments,
+            View nonExistentView, ArrayMap<String, String> nameOverrides) {
+        ViewGroup sceneRoot = (ViewGroup) fragmentManager.mContainer.onFindViewById(containerId);
+        if (sceneRoot == null) {
+            return;
+        }
+        final Fragment inFragment = fragments.lastIn;
+        final Fragment outFragment = fragments.firstOut;
+        final boolean inIsPop = fragments.lastInIsPop;
+        final boolean outIsPop = fragments.firstOutIsPop;
+
+        Transition enterTransition = getEnterTransition(inFragment, inIsPop);
+        Transition exitTransition = getExitTransition(outFragment, outIsPop);
+
+        ArrayList<View> sharedElementsOut = new ArrayList<>();
+        ArrayList<View> sharedElementsIn = new ArrayList<>();
+
+        TransitionSet sharedElementTransition = configureSharedElementsUnoptimized(sceneRoot,
+                nonExistentView, nameOverrides, fragments, sharedElementsOut, sharedElementsIn,
+                enterTransition, exitTransition);
+
+        if (enterTransition == null && sharedElementTransition == null &&
+                exitTransition == null) {
+            return; // no transitions!
+        }
+
+        ArrayList<View> exitingViews = configureEnteringExitingViews(exitTransition,
+                outFragment, sharedElementsOut, nonExistentView);
+
+        if (exitingViews == null || exitingViews.isEmpty()) {
+            exitTransition = null;
+        }
+
+        if (enterTransition != null) {
+            // Ensure the entering transition doesn't target anything until the views are made
+            // visible
+            enterTransition.addTarget(nonExistentView);
+        }
+
+        Transition transition = mergeTransitions(enterTransition, exitTransition,
+                sharedElementTransition, inFragment, fragments.lastInIsPop);
+
+        if (transition != null) {
+            transition.setNameOverrides(nameOverrides);
+            final ArrayList<View> enteringViews = new ArrayList<>();
+            scheduleRemoveTargets(transition,
+                    enterTransition, enteringViews, exitTransition, exitingViews,
+                    sharedElementTransition, sharedElementsIn);
+            scheduleTargetChange(sceneRoot, inFragment, nonExistentView, sharedElementsIn,
+                    enterTransition, enteringViews, exitTransition, exitingViews);
+
+            TransitionManager.beginDelayedTransition(sceneRoot, transition);
+        }
+    }
+
+    /**
+     * This method is used for fragment transitions for unoptimized transactions to change the
+     * enter and exit transition targets after the call to
+     * {@link TransitionManager#beginDelayedTransition(ViewGroup, Transition)}. The exit transition
+     * must ensure that it does not target any Views and the enter transition must start targeting
+     * the Views of the incoming Fragment.
+     *
+     * @param sceneRoot The fragment container View
+     * @param inFragment The last fragment that is entering
+     * @param nonExistentView A view that does not exist in the hierarchy that is used as a
+     *                        transition target to ensure no View is targeted.
+     * @param sharedElementsIn The shared element Views of the incoming fragment
+     * @param enterTransition The enter transition of the incoming fragment
+     * @param enteringViews The entering Views of the incoming fragment
+     * @param exitTransition The exit transition of the outgoing fragment
+     * @param exitingViews The exiting views of the outgoing fragment
+     */
+    private static void scheduleTargetChange(final ViewGroup sceneRoot,
+            final Fragment inFragment, final View nonExistentView,
+            final ArrayList<View> sharedElementsIn,
+            final Transition enterTransition, final ArrayList<View> enteringViews,
+            final Transition exitTransition, final ArrayList<View> exitingViews) {
+
+        sceneRoot.getViewTreeObserver().addOnPreDrawListener(
+                new ViewTreeObserver.OnPreDrawListener() {
+                    @Override
+                    public boolean onPreDraw() {
+                        sceneRoot.getViewTreeObserver().removeOnPreDrawListener(this);
+
+                        if (enterTransition != null) {
+                            enterTransition.removeTarget(nonExistentView);
+                            ArrayList<View> views = configureEnteringExitingViews(
+                                    enterTransition, inFragment, sharedElementsIn, nonExistentView);
+                            enteringViews.addAll(views);
+                        }
+
+                        if (exitingViews != null) {
+                            ArrayList<View> tempExiting = new ArrayList<>();
+                            tempExiting.add(nonExistentView);
+                            replaceTargets(exitTransition, exitingViews, tempExiting);
+                            exitingViews.clear();
+                            exitingViews.add(nonExistentView);
+                        }
+
+                        return true;
+                    }
+                });
+    }
+
+    /**
+     * Returns a TransitionSet containing the shared element transition. The wrapping TransitionSet
+     * targets all shared elements to ensure that no other Views are targeted. The shared element
+     * transition can then target any or all shared elements without worrying about accidentally
+     * targeting entering or exiting Views.
+     *
+     * @param inFragment The incoming fragment
+     * @param outFragment the outgoing fragment
+     * @param isPop True if this is a pop transaction or false if it is a normal (add) transaction.
+     * @return A TransitionSet wrapping the shared element transition or null if no such transition
+     * exists.
+     */
+    private static TransitionSet getSharedElementTransition(Fragment inFragment,
+            Fragment outFragment, boolean isPop) {
+        if (inFragment == null || outFragment == null) {
+            return null;
+        }
+        Transition transition = cloneTransition(isPop
+                ? outFragment.getSharedElementReturnTransition()
+                : inFragment.getSharedElementEnterTransition());
+        if (transition == null) {
+            return null;
+        }
+        TransitionSet transitionSet = new TransitionSet();
+        transitionSet.addTransition(transition);
+        return transitionSet;
+    }
+
+    /**
+     * Returns a clone of the enter transition or null if no such transition exists.
+     */
+    private static Transition getEnterTransition(Fragment inFragment, boolean isPop) {
+        if (inFragment == null) {
+            return null;
+        }
+        return cloneTransition(isPop ? inFragment.getReenterTransition() :
+                inFragment.getEnterTransition());
+    }
+
+    /**
+     * Returns a clone of the exit transition or null if no such transition exists.
+     */
+    private static Transition getExitTransition(Fragment outFragment, boolean isPop) {
+        if (outFragment == null) {
+            return null;
+        }
+        return cloneTransition(isPop ? outFragment.getReturnTransition() :
+                outFragment.getExitTransition());
+    }
+
+    /**
+     * Returns a clone of a transition or null if it is null
+     */
+    private static Transition cloneTransition(Transition transition) {
+        if (transition != null) {
+            transition = transition.clone();
+        }
+        return transition;
+    }
+
+    /**
+     * Configures the shared elements of an optimized fragment transaction's transition.
+     * This retrieves the shared elements of the outgoing and incoming fragments, maps the
+     * views, and sets up the epicenter on the transitions.
+     * <p>
+     * The epicenter of exit and shared element transitions is the first shared element
+     * in the outgoing fragment. The epicenter of the entering transition is the first shared
+     * element in the incoming fragment.
+     *
+     * @param sceneRoot The fragment container View
+     * @param nonExistentView A View that does not exist in the hierarchy. This is used to
+     *                        prevent transitions from acting on other Views when there is no
+     *                        other target.
+     * @param nameOverrides A map of the shared element names from the starting fragment to
+     *                      the final fragment's Views as given in
+     *                      {@link FragmentTransaction#addSharedElement(View, String)}.
+     * @param fragments A structure holding the transitioning fragments in this container.
+     * @param sharedElementsOut A list modified to contain the shared elements in the outgoing
+     *                          fragment
+     * @param sharedElementsIn A list modified to contain the shared elements in the incoming
+     *                         fragment
+     * @param enterTransition The transition used for entering Views, modified by applying the
+     *                        epicenter
+     * @param exitTransition The transition used for exiting Views, modified by applying the
+     *                       epicenter
+     * @return The shared element transition or null if no shared elements exist
+     */
+    private static TransitionSet configureSharedElementsOptimized(final ViewGroup sceneRoot,
+            final View nonExistentView, ArrayMap<String, String> nameOverrides,
+            final FragmentContainerTransition fragments,
+            final ArrayList<View> sharedElementsOut,
+            final ArrayList<View> sharedElementsIn,
+            final Transition enterTransition, final Transition exitTransition) {
+        final Fragment inFragment = fragments.lastIn;
+        final Fragment outFragment = fragments.firstOut;
+        if (inFragment != null) {
+            inFragment.getView().setVisibility(View.VISIBLE);
+        }
+        if (inFragment == null || outFragment == null) {
+            return null; // no shared element without a fragment
+        }
+
+        final boolean inIsPop = fragments.lastInIsPop;
+        TransitionSet sharedElementTransition = nameOverrides.isEmpty() ? null
+                : getSharedElementTransition(inFragment, outFragment, inIsPop);
+
+        ArrayMap<String, View> outSharedElements = captureOutSharedElements(nameOverrides,
+                sharedElementTransition, fragments);
+
+        ArrayMap<String, View> inSharedElements = captureInSharedElements(nameOverrides,
+                sharedElementTransition, fragments);
+
+        if (nameOverrides.isEmpty()) {
+            sharedElementTransition = null;
+        } else {
+            sharedElementsOut.addAll(outSharedElements.values());
+            sharedElementsIn.addAll(inSharedElements.values());
+        }
+
+        if (enterTransition == null && exitTransition == null && sharedElementTransition == null) {
+            // don't call onSharedElementStart/End since there is no transition
+            return null;
+        }
+
+        callSharedElementStartEnd(inFragment, outFragment, inIsPop, outSharedElements, true);
+
+        final Rect epicenter;
+        final View epicenterView;
+        if (sharedElementTransition != null) {
+            sharedElementsIn.add(nonExistentView);
+            setSharedElementTargets(sharedElementTransition, nonExistentView, sharedElementsOut);
+            final boolean outIsPop = fragments.firstOutIsPop;
+            final BackStackRecord outTransaction = fragments.firstOutTransaction;
+            setOutEpicenter(sharedElementTransition, exitTransition, outSharedElements, outIsPop,
+                    outTransaction);
+            epicenter = new Rect();
+            epicenterView = getInEpicenterView(inSharedElements, fragments,
+                    enterTransition, inIsPop);
+            if (epicenterView != null) {
+                enterTransition.setEpicenterCallback(new Transition.EpicenterCallback() {
+                    @Override
+                    public Rect onGetEpicenter(Transition transition) {
+                        return epicenter;
+                    }
+                });
+            }
+        } else {
+            epicenter = null;
+            epicenterView = null;
+        }
+
+        sceneRoot.getViewTreeObserver().addOnPreDrawListener(
+                new ViewTreeObserver.OnPreDrawListener() {
+                    @Override
+                    public boolean onPreDraw() {
+                        sceneRoot.getViewTreeObserver().removeOnPreDrawListener(this);
+                        callSharedElementStartEnd(inFragment, outFragment, inIsPop,
+                                inSharedElements, false);
+                        if (epicenterView != null) {
+                            epicenterView.getBoundsOnScreen(epicenter);
+                        }
+                        return true;
+                    }
+                });
+        return sharedElementTransition;
+    }
+
+    /**
+     * Configures the shared elements of an unoptimized fragment transaction's transition.
+     * This retrieves the shared elements of the incoming fragments, and schedules capturing
+     * the incoming fragment's shared elements. It also maps the views, and sets up the epicenter
+     * on the transitions.
+     * <p>
+     * The epicenter of exit and shared element transitions is the first shared element
+     * in the outgoing fragment. The epicenter of the entering transition is the first shared
+     * element in the incoming fragment.
+     *
+     * @param sceneRoot The fragment container View
+     * @param nonExistentView A View that does not exist in the hierarchy. This is used to
+     *                        prevent transitions from acting on other Views when there is no
+     *                        other target.
+     * @param nameOverrides A map of the shared element names from the starting fragment to
+     *                      the final fragment's Views as given in
+     *                      {@link FragmentTransaction#addSharedElement(View, String)}.
+     * @param fragments A structure holding the transitioning fragments in this container.
+     * @param sharedElementsOut A list modified to contain the shared elements in the outgoing
+     *                          fragment
+     * @param sharedElementsIn A list modified to contain the shared elements in the incoming
+     *                         fragment
+     * @param enterTransition The transition used for entering Views, modified by applying the
+     *                        epicenter
+     * @param exitTransition The transition used for exiting Views, modified by applying the
+     *                       epicenter
+     * @return The shared element transition or null if no shared elements exist
+     */
+    private static TransitionSet configureSharedElementsUnoptimized(final ViewGroup sceneRoot,
+            final View nonExistentView, ArrayMap<String, String> nameOverrides,
+            final FragmentContainerTransition fragments,
+            final ArrayList<View> sharedElementsOut,
+            final ArrayList<View> sharedElementsIn,
+            final Transition enterTransition, final Transition exitTransition) {
+        final Fragment inFragment = fragments.lastIn;
+        final Fragment outFragment = fragments.firstOut;
+
+        if (inFragment == null || outFragment == null) {
+            return null; // no transition
+        }
+
+        final boolean inIsPop = fragments.lastInIsPop;
+        TransitionSet sharedElementTransition = nameOverrides.isEmpty() ? null
+                : getSharedElementTransition(inFragment, outFragment, inIsPop);
+
+        ArrayMap<String, View> outSharedElements = captureOutSharedElements(nameOverrides,
+                sharedElementTransition, fragments);
+
+        if (nameOverrides.isEmpty()) {
+            sharedElementTransition = null;
+        } else {
+            sharedElementsOut.addAll(outSharedElements.values());
+        }
+
+        if (enterTransition == null && exitTransition == null && sharedElementTransition == null) {
+            // don't call onSharedElementStart/End since there is no transition
+            return null;
+        }
+
+        callSharedElementStartEnd(inFragment, outFragment, inIsPop, outSharedElements, true);
+
+        final Rect inEpicenter;
+        if (sharedElementTransition != null) {
+            inEpicenter = new Rect();
+            setSharedElementTargets(sharedElementTransition, nonExistentView, sharedElementsOut);
+            final boolean outIsPop = fragments.firstOutIsPop;
+            final BackStackRecord outTransaction = fragments.firstOutTransaction;
+            setOutEpicenter(sharedElementTransition, exitTransition, outSharedElements, outIsPop,
+                    outTransaction);
+            if (enterTransition != null) {
+                enterTransition.setEpicenterCallback(new Transition.EpicenterCallback() {
+                    @Override
+                    public Rect onGetEpicenter(Transition transition) {
+                        if (inEpicenter.isEmpty()) {
+                            return null;
+                        }
+                        return inEpicenter;
+                    }
+                });
+            }
+        } else {
+            inEpicenter = null;
+        }
+
+        TransitionSet finalSharedElementTransition = sharedElementTransition;
+
+        sceneRoot.getViewTreeObserver().addOnPreDrawListener(
+                new ViewTreeObserver.OnPreDrawListener() {
+                    @Override
+                    public boolean onPreDraw() {
+                        sceneRoot.getViewTreeObserver().removeOnPreDrawListener(this);
+                        ArrayMap<String, View> inSharedElements = captureInSharedElements(
+                                nameOverrides, finalSharedElementTransition, fragments);
+
+                        if (inSharedElements != null) {
+                            sharedElementsIn.addAll(inSharedElements.values());
+                            sharedElementsIn.add(nonExistentView);
+                        }
+
+                        callSharedElementStartEnd(inFragment, outFragment, inIsPop,
+                                inSharedElements, false);
+                        if (finalSharedElementTransition != null) {
+                            finalSharedElementTransition.getTargets().clear();
+                            finalSharedElementTransition.getTargets().addAll(sharedElementsIn);
+                            replaceTargets(finalSharedElementTransition, sharedElementsOut,
+                                    sharedElementsIn);
+
+                            final View inEpicenterView = getInEpicenterView(inSharedElements,
+                                    fragments, enterTransition, inIsPop);
+                            if (inEpicenterView != null) {
+                                inEpicenterView.getBoundsOnScreen(inEpicenter);
+                            }
+                        }
+                        return true;
+                    }
+                });
+        return sharedElementTransition;
+    }
+
+    /**
+     * Finds the shared elements in the outgoing fragment. It also calls
+     * {@link SharedElementCallback#onMapSharedElements(List, Map)} to allow more control
+     * of the shared element mapping. {@code nameOverrides} is updated to match the
+     * actual transition name of the mapped shared elements.
+     *
+     * @param nameOverrides A map of the shared element names from the starting fragment to
+     *                      the final fragment's Views as given in
+     *                      {@link FragmentTransaction#addSharedElement(View, String)}.
+     * @param sharedElementTransition The shared element transition
+     * @param fragments A structure holding the transitioning fragments in this container.
+     * @return The mapping of shared element names to the Views in the hierarchy or null
+     * if there is no shared element transition.
+     */
+    private static ArrayMap<String, View> captureOutSharedElements(
+            ArrayMap<String, String> nameOverrides, TransitionSet sharedElementTransition,
+            FragmentContainerTransition fragments) {
+        if (nameOverrides.isEmpty() || sharedElementTransition == null) {
+            nameOverrides.clear();
+            return null;
+        }
+        final Fragment outFragment = fragments.firstOut;
+        final ArrayMap<String, View> outSharedElements = new ArrayMap<>();
+        outFragment.getView().findNamedViews(outSharedElements);
+
+        final SharedElementCallback sharedElementCallback;
+        final ArrayList<String> names;
+        final BackStackRecord outTransaction = fragments.firstOutTransaction;
+        if (fragments.firstOutIsPop) {
+            sharedElementCallback = outFragment.getEnterTransitionCallback();
+            names = outTransaction.mSharedElementTargetNames;
+        } else {
+            sharedElementCallback = outFragment.getExitTransitionCallback();
+            names = outTransaction.mSharedElementSourceNames;
+        }
+
+        outSharedElements.retainAll(names);
+        if (sharedElementCallback != null) {
+            sharedElementCallback.onMapSharedElements(names, outSharedElements);
+            for (int i = names.size() - 1; i >= 0; i--) {
+                String name = names.get(i);
+                View view = outSharedElements.get(name);
+                if (view == null) {
+                    nameOverrides.remove(name);
+                } else if (!name.equals(view.getTransitionName())) {
+                    String targetValue = nameOverrides.remove(name);
+                    nameOverrides.put(view.getTransitionName(), targetValue);
+                }
+            }
+        } else {
+            nameOverrides.retainAll(outSharedElements.keySet());
+        }
+        return outSharedElements;
+    }
+
+    /**
+     * Finds the shared elements in the incoming fragment. It also calls
+     * {@link SharedElementCallback#onMapSharedElements(List, Map)} to allow more control
+     * of the shared element mapping. {@code nameOverrides} is updated to match the
+     * actual transition name of the mapped shared elements.
+     *
+     * @param nameOverrides A map of the shared element names from the starting fragment to
+     *                      the final fragment's Views as given in
+     *                      {@link FragmentTransaction#addSharedElement(View, String)}.
+     * @param sharedElementTransition The shared element transition
+     * @param fragments A structure holding the transitioning fragments in this container.
+     * @return The mapping of shared element names to the Views in the hierarchy or null
+     * if there is no shared element transition.
+     */
+    private static ArrayMap<String, View> captureInSharedElements(
+            ArrayMap<String, String> nameOverrides, TransitionSet sharedElementTransition,
+            FragmentContainerTransition fragments) {
+        Fragment inFragment = fragments.lastIn;
+        final View fragmentView = inFragment.getView();
+        if (nameOverrides.isEmpty() || sharedElementTransition == null || fragmentView == null) {
+            nameOverrides.clear();
+            return null;
+        }
+        final ArrayMap<String, View> inSharedElements = new ArrayMap<>();
+        fragmentView.findNamedViews(inSharedElements);
+
+        final SharedElementCallback sharedElementCallback;
+        final ArrayList<String> names;
+        final BackStackRecord inTransaction = fragments.lastInTransaction;
+        if (fragments.lastInIsPop) {
+            sharedElementCallback = inFragment.getExitTransitionCallback();
+            names = inTransaction.mSharedElementSourceNames;
+        } else {
+            sharedElementCallback = inFragment.getEnterTransitionCallback();
+            names = inTransaction.mSharedElementTargetNames;
+        }
+
+        inSharedElements.retainAll(names);
+        if (sharedElementCallback != null) {
+            sharedElementCallback.onMapSharedElements(names, inSharedElements);
+            for (int i = names.size() - 1; i >= 0; i--) {
+                String name = names.get(i);
+                View view = inSharedElements.get(name);
+                if (view == null) {
+                    String key = findKeyForValue(nameOverrides, name);
+                    if (key != null) {
+                        nameOverrides.remove(key);
+                    }
+                } else if (!name.equals(view.getTransitionName())) {
+                    String key = findKeyForValue(nameOverrides, name);
+                    if (key != null) {
+                        nameOverrides.put(key, view.getTransitionName());
+                    }
+                }
+            }
+        } else {
+            retainValues(nameOverrides, inSharedElements);
+        }
+        return inSharedElements;
+    }
+
+    /**
+     * Utility to find the String key in {@code map} that maps to {@code value}.
+     */
+    private static String findKeyForValue(ArrayMap<String, String> map, String value) {
+        final int numElements = map.size();
+        for (int i = 0; i < numElements; i++) {
+            if (value.equals(map.valueAt(i))) {
+                return map.keyAt(i);
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Returns the View in the incoming Fragment that should be used as the epicenter.
+     *
+     * @param inSharedElements The mapping of shared element names to Views in the
+     *                         incoming fragment.
+     * @param fragments A structure holding the transitioning fragments in this container.
+     * @param enterTransition The transition used for the incoming Fragment's views
+     * @param inIsPop Is the incoming fragment being added as a pop transaction?
+     */
+    private static View getInEpicenterView(ArrayMap<String, View> inSharedElements,
+            FragmentContainerTransition fragments,
+            Transition enterTransition, boolean inIsPop) {
+        BackStackRecord inTransaction = fragments.lastInTransaction;
+        if (enterTransition != null && inTransaction.mSharedElementSourceNames != null &&
+                !inTransaction.mSharedElementSourceNames.isEmpty()) {
+            final String targetName = inIsPop
+                    ? inTransaction.mSharedElementSourceNames.get(0)
+                    : inTransaction.mSharedElementTargetNames.get(0);
+            return inSharedElements.get(targetName);
+        }
+        return null;
+    }
+
+    /**
+     * Sets the epicenter for the exit transition.
+     *
+     * @param sharedElementTransition The shared element transition
+     * @param exitTransition The transition for the outgoing fragment's views
+     * @param outSharedElements Shared elements in the outgoing fragment
+     * @param outIsPop Is the outgoing fragment being removed as a pop transaction?
+     * @param outTransaction The transaction that caused the fragment to be removed.
+     */
+    private static void setOutEpicenter(TransitionSet sharedElementTransition,
+            Transition exitTransition, ArrayMap<String, View> outSharedElements, boolean outIsPop,
+            BackStackRecord outTransaction) {
+        if (outTransaction.mSharedElementSourceNames != null &&
+                !outTransaction.mSharedElementSourceNames.isEmpty()) {
+            final String sourceName = outIsPop
+                    ? outTransaction.mSharedElementTargetNames.get(0)
+                    : outTransaction.mSharedElementSourceNames.get(0);
+            final View outEpicenterView = outSharedElements.get(sourceName);
+            setEpicenter(sharedElementTransition, outEpicenterView);
+
+            if (exitTransition != null) {
+                setEpicenter(exitTransition, outEpicenterView);
+            }
+        }
+    }
+
+    /**
+     * Sets a transition epicenter to the rectangle of a given View.
+     */
+    private static void setEpicenter(Transition transition, View view) {
+        if (view != null) {
+            final Rect epicenter = new Rect();
+            view.getBoundsOnScreen(epicenter);
+
+            transition.setEpicenterCallback(new Transition.EpicenterCallback() {
+                @Override
+                public Rect onGetEpicenter(Transition transition) {
+                    return epicenter;
+                }
+            });
+        }
+    }
+
+    /**
+     * A utility to retain only the mappings in {@code nameOverrides} that have a value
+     * that has a key in {@code namedViews}. This is a useful equivalent to
+     * {@link ArrayMap#retainAll(Collection)} for values.
+     */
+    private static void retainValues(ArrayMap<String, String> nameOverrides,
+            ArrayMap<String, View> namedViews) {
+        for (int i = nameOverrides.size() - 1; i >= 0; i--) {
+            final String targetName = nameOverrides.valueAt(i);
+            if (!namedViews.containsKey(targetName)) {
+                nameOverrides.removeAt(i);
+            }
+        }
+    }
+
+    /**
+     * Calls the {@link SharedElementCallback#onSharedElementStart(List, List, List)} or
+     * {@link SharedElementCallback#onSharedElementEnd(List, List, List)} on the appropriate
+     * incoming or outgoing fragment.
+     *
+     * @param inFragment The incoming fragment
+     * @param outFragment The outgoing fragment
+     * @param isPop Is the incoming fragment part of a pop transaction?
+     * @param sharedElements The shared element Views
+     * @param isStart Call the start or end call on the SharedElementCallback
+     */
+    private static void callSharedElementStartEnd(Fragment inFragment, Fragment outFragment,
+            boolean isPop, ArrayMap<String, View> sharedElements, boolean isStart) {
+        SharedElementCallback sharedElementCallback = isPop
+                ? outFragment.getEnterTransitionCallback()
+                : inFragment.getEnterTransitionCallback();
+        if (sharedElementCallback != null) {
+            ArrayList<View> views = new ArrayList<>();
+            ArrayList<String> names = new ArrayList<>();
+            final int count = sharedElements == null ? 0 : sharedElements.size();
+            for (int i = 0; i < count; i++) {
+                names.add(sharedElements.keyAt(i));
+                views.add(sharedElements.valueAt(i));
+            }
+            if (isStart) {
+                sharedElementCallback.onSharedElementStart(names, views, null);
+            } else {
+                sharedElementCallback.onSharedElementEnd(names, views, null);
+            }
+        }
+    }
+
+    /**
+     * Finds all children of the shared elements and sets the wrapping TransitionSet
+     * targets to point to those. It also limits transitions that have no targets to the
+     * specific shared elements. This allows developers to target child views of the
+     * shared elements specifically, but this doesn't happen by default.
+     */
+    private static void setSharedElementTargets(TransitionSet transition,
+            View nonExistentView, ArrayList<View> sharedViews) {
+        final List<View> views = transition.getTargets();
+        views.clear();
+        final int count = sharedViews.size();
+        for (int i = 0; i < count; i++) {
+            final View view = sharedViews.get(i);
+            bfsAddViewChildren(views, view);
+        }
+        views.add(nonExistentView);
+        sharedViews.add(nonExistentView);
+        addTargets(transition, sharedViews);
+    }
+
+    /**
+     * Uses a breadth-first scheme to add startView and all of its children to views.
+     * It won't add a child if it is already in views.
+     */
+    private static void bfsAddViewChildren(final List<View> views, final View startView) {
+        final int startIndex = views.size();
+        if (containedBeforeIndex(views, startView, startIndex)) {
+            return; // This child is already in the list, so all its children are also.
+        }
+        views.add(startView);
+        for (int index = startIndex; index < views.size(); index++) {
+            final View view = views.get(index);
+            if (view instanceof ViewGroup) {
+                ViewGroup viewGroup = (ViewGroup) view;
+                final int childCount =  viewGroup.getChildCount();
+                for (int childIndex = 0; childIndex < childCount; childIndex++) {
+                    final View child = viewGroup.getChildAt(childIndex);
+                    if (!containedBeforeIndex(views, child, startIndex)) {
+                        views.add(child);
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * Does a linear search through views for view, limited to maxIndex.
+     */
+    private static boolean containedBeforeIndex(final List<View> views, final View view,
+            final int maxIndex) {
+        for (int i = 0; i < maxIndex; i++) {
+            if (views.get(i) == view) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * After the transition has started, remove all targets that we added to the transitions
+     * so that the transitions are left in a clean state.
+     */
+    private static void scheduleRemoveTargets(final Transition overalTransition,
+            final Transition enterTransition, final ArrayList<View> enteringViews,
+            final Transition exitTransition, final ArrayList<View> exitingViews,
+            final TransitionSet sharedElementTransition, final ArrayList<View> sharedElementsIn) {
+        overalTransition.addListener(new Transition.TransitionListenerAdapter() {
+            @Override
+            public void onTransitionStart(Transition transition) {
+                if (enterTransition != null) {
+                    replaceTargets(enterTransition, enteringViews, null);
+                }
+                if (exitTransition != null) {
+                    replaceTargets(exitTransition, exitingViews, null);
+                }
+                if (sharedElementTransition != null) {
+                    replaceTargets(sharedElementTransition, sharedElementsIn, null);
+                }
+            }
+        });
+    }
+
+    /**
+     * This method removes the views from transitions that target ONLY those views and
+     * replaces them with the new targets list.
+     * The views list should match those added in addTargets and should contain
+     * one view that is not in the view hierarchy (state.nonExistentView).
+     */
+    public static void replaceTargets(Transition transition, ArrayList<View> oldTargets,
+            ArrayList<View> newTargets) {
+        if (transition instanceof TransitionSet) {
+            TransitionSet set = (TransitionSet) transition;
+            int numTransitions = set.getTransitionCount();
+            for (int i = 0; i < numTransitions; i++) {
+                Transition child = set.getTransitionAt(i);
+                replaceTargets(child, oldTargets, newTargets);
+            }
+        } else if (!hasSimpleTarget(transition)) {
+            List<View> targets = transition.getTargets();
+            if (targets != null && targets.size() == oldTargets.size() &&
+                    targets.containsAll(oldTargets)) {
+                // We have an exact match. We must have added these earlier in addTargets
+                final int targetCount = newTargets == null ? 0 : newTargets.size();
+                for (int i = 0; i < targetCount; i++) {
+                    transition.addTarget(newTargets.get(i));
+                }
+                for (int i = oldTargets.size() - 1; i >= 0; i--) {
+                    transition.removeTarget(oldTargets.get(i));
+                }
+            }
+        }
+    }
+
+    /**
+     * This method adds views as targets to the transition, but only if the transition
+     * doesn't already have a target. It is best for views to contain one View object
+     * that does not exist in the view hierarchy (state.nonExistentView) so that
+     * when they are removed later, a list match will suffice to remove the targets.
+     * Otherwise, if you happened to have targeted the exact views for the transition,
+     * the replaceTargets call will remove them unexpectedly.
+     */
+    public static void addTargets(Transition transition, ArrayList<View> views) {
+        if (transition == null) {
+            return;
+        }
+        if (transition instanceof TransitionSet) {
+            TransitionSet set = (TransitionSet) transition;
+            int numTransitions = set.getTransitionCount();
+            for (int i = 0; i < numTransitions; i++) {
+                Transition child = set.getTransitionAt(i);
+                addTargets(child, views);
+            }
+        } else if (!hasSimpleTarget(transition)) {
+            List<View> targets = transition.getTargets();
+            if (isNullOrEmpty(targets)) {
+                // We can just add the target views
+                int numViews = views.size();
+                for (int i = 0; i < numViews; i++) {
+                    transition.addTarget(views.get(i));
+                }
+            }
+        }
+    }
+
+    /**
+     * Returns true if there are any targets based on ID, transition or type.
+     */
+    private static boolean hasSimpleTarget(Transition transition) {
+        return !isNullOrEmpty(transition.getTargetIds()) ||
+                !isNullOrEmpty(transition.getTargetNames()) ||
+                !isNullOrEmpty(transition.getTargetTypes());
+    }
+
+    /**
+     * Simple utility to detect if a list is null or has no elements.
+     */
+    private static boolean isNullOrEmpty(List list) {
+        return list == null || list.isEmpty();
+    }
+
+    private static ArrayList<View> configureEnteringExitingViews(Transition transition,
+            Fragment fragment, ArrayList<View> sharedElements, View nonExistentView) {
+        ArrayList<View> viewList = null;
+        if (transition != null) {
+            viewList = new ArrayList<>();
+            View root = fragment.getView();
+            root.captureTransitioningViews(viewList);
+            if (sharedElements != null) {
+                viewList.removeAll(sharedElements);
+            }
+            if (!viewList.isEmpty()) {
+                viewList.add(nonExistentView);
+                addTargets(transition, viewList);
+            }
+        }
+        return viewList;
+    }
+
+    /**
+     * Sets the visibility of all Views in {@code views} to {@code visibility}.
+     */
+    private static void setViewVisibility(ArrayList<View> views, @View.Visibility int visibility) {
+        if (views == null) {
+            return;
+        }
+        for (int i = views.size() - 1; i >= 0; i--) {
+            final View view = views.get(i);
+            view.setVisibility(visibility);
+        }
+    }
+
+    /**
+     * Merges exit, shared element, and enter transitions so that they act together or
+     * sequentially as defined in the fragments.
+     */
+    private static Transition mergeTransitions(Transition enterTransition,
+            Transition exitTransition, Transition sharedElementTransition, Fragment inFragment,
+            boolean isPop) {
+        boolean overlap = true;
+        if (enterTransition != null && exitTransition != null && inFragment != null) {
+            overlap = isPop ? inFragment.getAllowReturnTransitionOverlap() :
+                    inFragment.getAllowEnterTransitionOverlap();
+        }
+
+        // Wrap the transitions. Explicit targets like in enter and exit will cause the
+        // views to be targeted regardless of excluded views. If that happens, then the
+        // excluded fragments views (hidden fragments) will still be in the transition.
+
+        Transition transition;
+        if (overlap) {
+            // Regular transition -- do it all together
+            TransitionSet transitionSet = new TransitionSet();
+            if (enterTransition != null) {
+                transitionSet.addTransition(enterTransition);
+            }
+            if (exitTransition != null) {
+                transitionSet.addTransition(exitTransition);
+            }
+            if (sharedElementTransition != null) {
+                transitionSet.addTransition(sharedElementTransition);
+            }
+            transition = transitionSet;
+        } else {
+            // First do exit, then enter, but allow shared element transition to happen
+            // during both.
+            Transition staggered = null;
+            if (exitTransition != null && enterTransition != null) {
+                staggered = new TransitionSet()
+                        .addTransition(exitTransition)
+                        .addTransition(enterTransition)
+                        .setOrdering(TransitionSet.ORDERING_SEQUENTIAL);
+            } else if (exitTransition != null) {
+                staggered = exitTransition;
+            } else if (enterTransition != null) {
+                staggered = enterTransition;
+            }
+            if (sharedElementTransition != null) {
+                TransitionSet together = new TransitionSet();
+                if (staggered != null) {
+                    together.addTransition(staggered);
+                }
+                together.addTransition(sharedElementTransition);
+                transition = together;
+            } else {
+                transition = staggered;
+            }
+        }
+        return transition;
+    }
+
+    /**
+     * Finds the first removed fragment and last added fragments when going forward.
+     * If none of the fragments have transitions, then both lists will be empty.
+     *
+     * @param transitioningFragments Keyed on the container ID, the first fragments to be removed,
+     *                               and last fragments to be added. This will be modified by
+     *                               this method.
+     */
+    public static void calculateFragments(BackStackRecord transaction,
+            SparseArray<FragmentContainerTransition> transitioningFragments,
+            boolean isOptimized) {
+        final int numOps = transaction.mOps.size();
+        for (int opNum = 0; opNum < numOps; opNum++) {
+            final BackStackRecord.Op op = transaction.mOps.get(opNum);
+            addToFirstInLastOut(transaction, op, transitioningFragments, false, isOptimized);
+        }
+    }
+
+    /**
+     * Finds the first removed fragment and last added fragments when popping the back stack.
+     * If none of the fragments have transitions, then both lists will be empty.
+     *
+     * @param transitioningFragments Keyed on the container ID, the first fragments to be removed,
+     *                               and last fragments to be added. This will be modified by
+     *                               this method.
+     */
+    public static void calculatePopFragments(BackStackRecord transaction,
+            SparseArray<FragmentContainerTransition> transitioningFragments, boolean isOptimized) {
+        if (!transaction.mManager.mContainer.onHasView()) {
+            return; // nothing to see, so no transitions
+        }
+        final int numOps = transaction.mOps.size();
+        for (int opNum = numOps - 1; opNum >= 0; opNum--) {
+            final BackStackRecord.Op op = transaction.mOps.get(opNum);
+            addToFirstInLastOut(transaction, op, transitioningFragments, true, isOptimized);
+        }
+    }
+
+    /**
+     * Examines the {@code command} and may set the first out or last in fragment for the fragment's
+     * container.
+     *
+     * @param transaction The executing transaction
+     * @param op The operation being run.
+     * @param transitioningFragments A structure holding the first in and last out fragments
+     *                               for each fragment container.
+     * @param isPop Is the operation a pop?
+     * @param isOptimizedTransaction True if the operations have been partially executed and the
+     *                               added fragments have Views in the hierarchy or false if the
+     *                               operations haven't been executed yet.
+     */
+    private static void addToFirstInLastOut(BackStackRecord transaction, BackStackRecord.Op op,
+            SparseArray<FragmentContainerTransition> transitioningFragments, boolean isPop,
+            boolean isOptimizedTransaction) {
+        final Fragment fragment = op.fragment;
+        final int containerId = fragment.mContainerId;
+        if (containerId == 0) {
+            return; // no container, no transition
+        }
+        final int command = isPop ? INVERSE_OPS[op.cmd] : op.cmd;
+        boolean setLastIn = false;
+        boolean wasRemoved = false;
+        boolean setFirstOut = false;
+        boolean wasAdded = false;
+        switch (command) {
+            case BackStackRecord.OP_SHOW:
+                if (isOptimizedTransaction) {
+                    setLastIn = fragment.mHiddenChanged && !fragment.mHidden &&
+                            fragment.mAdded;
+                } else {
+                    setLastIn = fragment.mHidden;
+                }
+                wasAdded = true;
+                break;
+            case BackStackRecord.OP_ADD:
+            case BackStackRecord.OP_ATTACH:
+                if (isOptimizedTransaction) {
+                    setLastIn = fragment.mIsNewlyAdded;
+                } else {
+                    setLastIn = !fragment.mAdded && !fragment.mHidden;
+                }
+                wasAdded = true;
+                break;
+            case BackStackRecord.OP_HIDE:
+                if (isOptimizedTransaction) {
+                    setFirstOut = fragment.mHiddenChanged && fragment.mAdded &&
+                            fragment.mHidden;
+                } else {
+                    setFirstOut = fragment.mAdded && !fragment.mHidden;
+                }
+                wasRemoved = true;
+                break;
+            case BackStackRecord.OP_REMOVE:
+            case BackStackRecord.OP_DETACH:
+                if (isOptimizedTransaction) {
+                    setFirstOut = !fragment.mAdded && fragment.mView != null &&
+                            fragment.mView.getVisibility() == View.VISIBLE;
+                } else {
+                    setFirstOut = fragment.mAdded && !fragment.mHidden;
+                }
+                wasRemoved = true;
+                break;
+        }
+        FragmentContainerTransition containerTransition = transitioningFragments.get(containerId);
+        if (setLastIn) {
+            containerTransition =
+                    ensureContainer(containerTransition, transitioningFragments, containerId);
+            containerTransition.lastIn = fragment;
+            containerTransition.lastInIsPop = isPop;
+            containerTransition.lastInTransaction = transaction;
+        }
+        if (!isOptimizedTransaction && wasAdded) {
+            if (containerTransition != null && containerTransition.firstOut == fragment) {
+                containerTransition.firstOut = null;
+            }
+
+            /**
+             * Ensure that fragments that are entering are at least at the CREATED state
+             * so that they may load Transitions using TransitionInflater.
+             */
+            FragmentManagerImpl manager = transaction.mManager;
+            if (fragment.mState < Fragment.CREATED && manager.mCurState >= Fragment.CREATED &&
+                    manager.mHost.getContext().getApplicationInfo().targetSdkVersion >=
+                            Build.VERSION_CODES.N && !transaction.mAllowOptimization) {
+                manager.makeActive(fragment);
+                manager.moveToState(fragment, Fragment.CREATED, 0, 0, false);
+            }
+        }
+        if (setFirstOut && (containerTransition == null || containerTransition.firstOut == null)) {
+            containerTransition =
+                    ensureContainer(containerTransition, transitioningFragments, containerId);
+            containerTransition.firstOut = fragment;
+            containerTransition.firstOutIsPop = isPop;
+            containerTransition.firstOutTransaction = transaction;
+        }
+
+        if (!isOptimizedTransaction && wasRemoved &&
+                (containerTransition != null && containerTransition.lastIn == fragment)) {
+            containerTransition.lastIn = null;
+        }
+    }
+
+    /**
+     * Ensures that a FragmentContainerTransition has been added to the SparseArray. If so,
+     * it returns the existing one. If not, one is created and added to the SparseArray and
+     * returned.
+     */
+    private static FragmentContainerTransition ensureContainer(
+            FragmentContainerTransition containerTransition,
+            SparseArray<FragmentContainerTransition> transitioningFragments, int containerId) {
+        if (containerTransition == null) {
+            containerTransition = new FragmentContainerTransition();
+            transitioningFragments.put(containerId, containerTransition);
+        }
+        return containerTransition;
+    }
+
+    /**
+     * Tracks the last fragment added and first fragment removed for fragment transitions.
+     * This also tracks which fragments are changed by push or pop transactions.
+     */
+    public static class FragmentContainerTransition {
+        /**
+         * The last fragment added/attached/shown in its container
+         */
+        public Fragment lastIn;
+
+        /**
+         * true when lastIn was added during a pop transaction or false if added with a push
+         */
+        public boolean lastInIsPop;
+
+        /**
+         * The transaction that included the last in fragment
+         */
+        public BackStackRecord lastInTransaction;
+
+        /**
+         * The first fragment with a View that was removed/detached/hidden in its container.
+         */
+        public Fragment firstOut;
+
+        /**
+         * true when firstOut was removed during a pop transaction or false otherwise
+         */
+        public boolean firstOutIsPop;
+
+        /**
+         * The transaction that included the first out fragment
+         */
+        public BackStackRecord firstOutTransaction;
+    }
+}
diff --git a/core/java/android/app/IActivityManager.java b/core/java/android/app/IActivityManager.java
index 1253e69..5edd03f 100644
--- a/core/java/android/app/IActivityManager.java
+++ b/core/java/android/app/IActivityManager.java
@@ -274,12 +274,24 @@
 
     /**
      * Updates global configuration and applies changes to the entire system.
-     * @param values Update values for global configuration.
+     * @param values Update values for global configuration. If null is passed it will request the
+     *               Window Manager to compute new config for the default display.
      * @throws RemoteException
      * @return Returns true if the configuration was updated.
      */
     public boolean updateConfiguration(Configuration values) throws RemoteException;
 
+    /**
+     * Updates override configuration applied to specific display.
+     * @param values Update values for display configuration. If null is passed it will request the
+     *               Window Manager to compute new config for the specified display.
+     * @param displayId Id of the display to apply the config to.
+     * @throws RemoteException
+     * @return Returns true if the configuration was updated.
+     */
+    public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId)
+            throws RemoteException;
+
     public void setRequestedOrientation(IBinder token,
             int requestedOrientation) throws RemoteException;
     public int getRequestedOrientation(IBinder token) throws RemoteException;
@@ -1103,4 +1115,5 @@
     int REQUEST_ACTIVITY_RELAUNCH = IBinder.FIRST_CALL_TRANSACTION+400;
     int GET_DEFAULT_PICTURE_IN_PICTURE_BOUNDS_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 401;
     int GET_PICTURE_IN_PICTURE_MOVEMENT_BOUNDS_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 402;
+    int UPDATE_DISPLAY_OVERRIDE_CONFIGURATION_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 403;
 }
diff --git a/core/java/android/app/IApplicationThread.aidl b/core/java/android/app/IApplicationThread.aidl
index 2dd3b1a..e2f6fb5 100644
--- a/core/java/android/app/IApplicationThread.aidl
+++ b/core/java/android/app/IApplicationThread.aidl
@@ -155,6 +155,7 @@
     void scheduleLocalVoiceInteractionStarted(IBinder token,
             IVoiceInteractor voiceInteractor) = 61;
     void handleTrustStorageUpdate() = 62;
+    void attachAgent(String path) = 63;
     /**
      * Don't change the existing transaction Ids as they could be used in the native code.
      * When adding a new method, assign the next available transaction id.
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 4ddcfe5..9ce9dec 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -26,6 +26,7 @@
 import android.annotation.UserIdInt;
 import android.annotation.WorkerThread;
 import android.app.Activity;
+import android.app.admin.PasswordMetrics;
 import android.app.admin.SecurityLog.SecurityEvent;
 import android.content.ComponentName;
 import android.content.Context;
@@ -3523,12 +3524,10 @@
     /**
      * @hide
      */
-    public void setActivePasswordState(int quality, int length, int letters, int uppercase,
-            int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
+    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
         if (mService != null) {
             try {
-                mService.setActivePasswordState(quality, length, letters, uppercase, lowercase,
-                        numbers, symbols, nonletter, userHandle);
+                mService.setActivePasswordState(metrics, userHandle);
             } catch (RemoteException e) {
                 throw e.rethrowFromSystemServer();
             }
diff --git a/core/java/android/app/admin/IDevicePolicyManager.aidl b/core/java/android/app/admin/IDevicePolicyManager.aidl
index 8c376bb..22219d7 100644
--- a/core/java/android/app/admin/IDevicePolicyManager.aidl
+++ b/core/java/android/app/admin/IDevicePolicyManager.aidl
@@ -18,6 +18,7 @@
 package android.app.admin;
 
 import android.app.admin.SystemUpdatePolicy;
+import android.app.admin.PasswordMetrics;
 import android.content.ComponentName;
 import android.content.Intent;
 import android.content.IntentFilter;
@@ -29,6 +30,7 @@
 import android.os.PersistableBundle;
 import android.os.RemoteCallback;
 import android.os.UserHandle;
+
 import java.util.List;
 
 /**
@@ -117,8 +119,7 @@
     void forceRemoveActiveAdmin(in ComponentName policyReceiver, int userHandle);
     boolean hasGrantedPolicy(in ComponentName policyReceiver, int usesPolicy, int userHandle);
 
-    void setActivePasswordState(int quality, int length, int letters, int uppercase, int lowercase,
-        int numbers, int symbols, int nonletter, int userHandle);
+    void setActivePasswordState(in PasswordMetrics metrics, int userHandle);
     void reportFailedPasswordAttempt(int userHandle);
     void reportSuccessfulPasswordAttempt(int userHandle);
     void reportFailedFingerprintAttempt(int userHandle);
diff --git a/core/java/android/app/admin/PasswordMetrics.aidl b/core/java/android/app/admin/PasswordMetrics.aidl
new file mode 100644
index 0000000..90d7c69
--- /dev/null
+++ b/core/java/android/app/admin/PasswordMetrics.aidl
@@ -0,0 +1,20 @@
+/*
+**
+** 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.
+*/
+
+package android.app.admin;
+
+parcelable PasswordMetrics;
diff --git a/core/java/android/app/admin/PasswordMetrics.java b/core/java/android/app/admin/PasswordMetrics.java
new file mode 100644
index 0000000..ea3f560
--- /dev/null
+++ b/core/java/android/app/admin/PasswordMetrics.java
@@ -0,0 +1,238 @@
+/*
+ * 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.app.admin;
+
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.app.admin.DevicePolicyManager;
+import android.os.Parcelable;
+import android.os.Parcel;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.io.IOException;
+
+/**
+ * A class that represents the metrics of a password that are used to decide whether or not a
+ * password meets the requirements.
+ *
+ * {@hide}
+ */
+public class PasswordMetrics implements Parcelable {
+    // Maximum allowed number of repeated or ordered characters in a sequence before we'll
+    // consider it a complex PIN/password.
+    public static final int MAX_ALLOWED_SEQUENCE = 3;
+
+    public int quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
+    public int length = 0;
+    public int letters = 0;
+    public int upperCase = 0;
+    public int lowerCase = 0;
+    public int numeric = 0;
+    public int symbols = 0;
+    public int nonLetter = 0;
+
+    public PasswordMetrics() {}
+
+    public PasswordMetrics(int quality, int length) {
+        this.quality = quality;
+        this.length = length;
+    }
+
+    public PasswordMetrics(int quality, int length, int letters, int upperCase, int lowerCase,
+            int numeric, int symbols, int nonLetter) {
+        this(quality, length);
+        this.letters = letters;
+        this.upperCase = upperCase;
+        this.lowerCase = lowerCase;
+        this.numeric = numeric;
+        this.symbols = symbols;
+        this.nonLetter = nonLetter;
+    }
+
+    private PasswordMetrics(Parcel in) {
+        quality = in.readInt();
+        length = in.readInt();
+        letters = in.readInt();
+        upperCase = in.readInt();
+        lowerCase = in.readInt();
+        numeric = in.readInt();
+        symbols = in.readInt();
+        nonLetter = in.readInt();
+    }
+
+    public boolean isDefault() {
+        return quality == DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED
+                && length == 0 && letters == 0 && upperCase == 0 && lowerCase == 0
+                && numeric == 0 && symbols == 0 && nonLetter == 0;
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeInt(quality);
+        dest.writeInt(length);
+        dest.writeInt(letters);
+        dest.writeInt(upperCase);
+        dest.writeInt(lowerCase);
+        dest.writeInt(numeric);
+        dest.writeInt(symbols);
+        dest.writeInt(nonLetter);
+    }
+
+    public static final Parcelable.Creator<PasswordMetrics> CREATOR
+            = new Parcelable.Creator<PasswordMetrics>() {
+        public PasswordMetrics createFromParcel(Parcel in) {
+            return new PasswordMetrics(in);
+        }
+
+        public PasswordMetrics[] newArray(int size) {
+            return new PasswordMetrics[size];
+        }
+    };
+
+    public static PasswordMetrics computeForPassword(@NonNull String password) {
+        // Analyse the characters used
+        int letters = 0;
+        int upperCase = 0;
+        int lowerCase = 0;
+        int numeric = 0;
+        int symbols = 0;
+        int nonLetter = 0;
+        final int length = password.length();
+        for (int i = 0; i < length; i++) {
+            switch (categoryChar(password.charAt(i))) {
+                case CHAR_LOWER_CASE:
+                    letters++;
+                    lowerCase++;
+                    break;
+                case CHAR_UPPER_CASE:
+                    letters++;
+                    upperCase++;
+                    break;
+                case CHAR_DIGIT:
+                    numeric++;
+                    nonLetter++;
+                    break;
+                case CHAR_SYMBOL:
+                    symbols++;
+                    nonLetter++;
+                    break;
+            }
+        }
+
+        // Determine the quality of the password
+        final boolean hasNumeric = numeric > 0;
+        final boolean hasNonNumeric = (letters + symbols) > 0;
+        final int quality;
+        if (hasNonNumeric && hasNumeric) {
+            quality = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
+        } else if (hasNonNumeric) {
+            quality = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
+        } else if (hasNumeric) {
+            quality = maxLengthSequence(password) > MAX_ALLOWED_SEQUENCE
+                    ? DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
+                    : DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
+        } else {
+            quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
+        }
+
+        return new PasswordMetrics(
+                quality, length, letters, upperCase, lowerCase, numeric, symbols, nonLetter);
+    }
+
+    /*
+     * Returns the maximum length of a sequential characters. A sequence is defined as
+     * monotonically increasing characters with a constant interval or the same character repeated.
+     *
+     * For example:
+     * maxLengthSequence("1234") == 4
+     * maxLengthSequence("13579") == 5
+     * maxLengthSequence("1234abc") == 4
+     * maxLengthSequence("aabc") == 3
+     * maxLengthSequence("qwertyuio") == 1
+     * maxLengthSequence("@ABC") == 3
+     * maxLengthSequence(";;;;") == 4 (anything that repeats)
+     * maxLengthSequence(":;<=>") == 1  (ordered, but not composed of alphas or digits)
+     *
+     * @param string the pass
+     * @return the number of sequential letters or digits
+     */
+    public static int maxLengthSequence(@NonNull String string) {
+        if (string.length() == 0) return 0;
+        char previousChar = string.charAt(0);
+        @CharacterCatagory int category = categoryChar(previousChar); //current sequence category
+        int diff = 0; //difference between two consecutive characters
+        boolean hasDiff = false; //if we are currently targeting a sequence
+        int maxLength = 0; //maximum length of a sequence already found
+        int startSequence = 0; //where the current sequence started
+        for (int current = 1; current < string.length(); current++) {
+            char currentChar = string.charAt(current);
+            @CharacterCatagory int categoryCurrent = categoryChar(currentChar);
+            int currentDiff = (int) currentChar - (int) previousChar;
+            if (categoryCurrent != category || Math.abs(currentDiff) > maxDiffCategory(category)) {
+                maxLength = Math.max(maxLength, current - startSequence);
+                startSequence = current;
+                hasDiff = false;
+                category = categoryCurrent;
+            }
+            else {
+                if(hasDiff && currentDiff != diff) {
+                    maxLength = Math.max(maxLength, current - startSequence);
+                    startSequence = current - 1;
+                }
+                diff = currentDiff;
+                hasDiff = true;
+            }
+            previousChar = currentChar;
+        }
+        maxLength = Math.max(maxLength, string.length() - startSequence);
+        return maxLength;
+    }
+
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef({CHAR_UPPER_CASE, CHAR_LOWER_CASE, CHAR_DIGIT, CHAR_SYMBOL})
+    private @interface CharacterCatagory {}
+    private static final int CHAR_LOWER_CASE = 0;
+    private static final int CHAR_UPPER_CASE = 1;
+    private static final int CHAR_DIGIT = 2;
+    private static final int CHAR_SYMBOL = 3;
+
+    @CharacterCatagory
+    private static int categoryChar(char c) {
+        if ('a' <= c && c <= 'z') return CHAR_LOWER_CASE;
+        if ('A' <= c && c <= 'Z') return CHAR_UPPER_CASE;
+        if ('0' <= c && c <= '9') return CHAR_DIGIT;
+        return CHAR_SYMBOL;
+    }
+
+    private static int maxDiffCategory(@CharacterCatagory int category) {
+        switch (category) {
+            case CHAR_LOWER_CASE:
+            case CHAR_UPPER_CASE:
+                return 1;
+            case CHAR_DIGIT:
+                return 10;
+            default:
+                return 0;
+        }
+    }
+}
diff --git a/core/java/android/bluetooth/BluetoothUuid.java b/core/java/android/bluetooth/BluetoothUuid.java
index 2ded4c8..243579a 100644
--- a/core/java/android/bluetooth/BluetoothUuid.java
+++ b/core/java/android/bluetooth/BluetoothUuid.java
@@ -275,6 +275,48 @@
     }
 
     /**
+     * Parse UUID to bytes. The returned value is shortest representation, a 16-bit, 32-bit or 128-bit UUID,
+     * Note returned value is little endian (Bluetooth).
+     *
+     * @param uuid uuid to parse.
+     * @return shortest representation of {@code uuid} as bytes.
+     * @throws IllegalArgumentException If the {@code uuid} is null.
+     */
+    public static byte[] uuidToBytes(ParcelUuid uuid) {
+        if (uuid == null) {
+            throw new IllegalArgumentException("uuid cannot be null");
+        }
+
+        if (is16BitUuid(uuid)) {
+            byte[] uuidBytes = new byte[UUID_BYTES_16_BIT];
+            int uuidVal = getServiceIdentifierFromParcelUuid(uuid);
+            uuidBytes[0] = (byte)(uuidVal & 0xFF);
+            uuidBytes[1] = (byte)((uuidVal & 0xFF00) >> 8);
+            return uuidBytes;
+        }
+
+        if (is32BitUuid(uuid)) {
+            byte[] uuidBytes = new byte[UUID_BYTES_32_BIT];
+            int uuidVal = getServiceIdentifierFromParcelUuid(uuid);
+            uuidBytes[0] = (byte)(uuidVal & 0xFF);
+            uuidBytes[1] = (byte)((uuidVal & 0xFF00) >> 8);
+            uuidBytes[2] = (byte)((uuidVal & 0xFF0000) >> 16);
+            uuidBytes[3] = (byte)((uuidVal & 0xFF000000) >> 24);
+            return uuidBytes;
+        }
+
+        // Construct a 128 bit UUID.
+        long msb = uuid.getUuid().getMostSignificantBits();
+        long lsb = uuid.getUuid().getLeastSignificantBits();
+
+        byte[] uuidBytes = new byte[UUID_BYTES_128_BIT];
+        ByteBuffer buf = ByteBuffer.wrap(uuidBytes).order(ByteOrder.LITTLE_ENDIAN);
+        buf.putLong(8, msb);
+        buf.putLong(0, lsb);
+        return uuidBytes;
+    }
+
+    /**
      * Check whether the given parcelUuid can be converted to 16 bit bluetooth uuid.
      *
      * @param parcelUuid
diff --git a/core/java/android/os/ShellCommand.java b/core/java/android/os/ShellCommand.java
index dbb9650..e4a12e8 100644
--- a/core/java/android/os/ShellCommand.java
+++ b/core/java/android/os/ShellCommand.java
@@ -302,7 +302,7 @@
     /**
      * Implement parsing and execution of a command.  If it isn't a command you understand,
      * call {@link #handleDefaultCommands(String)} and return its result as a last resort.
-     * User {@link #getNextOption()}, {@link #getNextArg()}, and {@link #getNextArgRequired()}
+     * Use {@link #getNextOption()}, {@link #getNextArg()}, and {@link #getNextArgRequired()}
      * to process additional command line arguments.  Command output can be written to
      * {@link #getOutPrintWriter()} and errors to {@link #getErrPrintWriter()}.
      *
diff --git a/core/java/android/util/Half.java b/core/java/android/util/Half.java
new file mode 100644
index 0000000..f4eb132
--- /dev/null
+++ b/core/java/android/util/Half.java
@@ -0,0 +1,367 @@
+/*
+ * 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.util;
+
+/**
+ * <p>Half is a utility class to manipulate half-precision 16-bit
+ * <a href="https://en.wikipedia.org/wiki/Half-precision_floating-point_format">IEEE 754</a>
+ * floating point data types (also called fp16 or binary16). A half-precision
+ * float is stored in a short data type. A half-precision float can be
+ * created from or converted to single-precision floats.</p>
+ *
+ * <p>The IEEE 754 standard specifies an fp16 as having the following format:</p>
+ * <ul>
+ * <li>Sign bit: 1 bit</li>
+ * <li>Exponent width: 5 bits</li>
+ * <li>Mantissa: 10 bits</li>
+ * </ul>
+ *
+ * <p>The format is laid out thusly:</p>
+ * <pre>
+ * 1   11111   1111111111
+ * ^   --^--   -----^----
+ * sign  |          |_______ mantissa
+ *       |
+ *       -- exponent
+ * </pre>
+ *
+ * @hide
+ */
+public final class Half {
+    /**
+     * The number of bits used to represent a half-precision float value.
+     */
+    public static final int SIZE = 16;
+
+    /**
+     * Epsilon is the difference between 1.0 and the next value representable
+     * by a half-precision floating-point.
+     */
+    public static final short EPSILON            = (short) 0x1400;
+    /**
+     * Smallest negative value a half-precision float may have.
+     */
+    public static final short LOWEST_VALUE       = (short) 0xfbff;
+    /**
+     * Maximum exponent a finite half-precision float may have.
+     */
+    public static final short MAX_EXPONENT       = 15;
+    /**
+     * Maximum positive finite value a half-precision float may have.
+     */
+    public static final short MAX_VALUE          = (short) 0x7bff;
+    /**
+     * Minimum exponent a normalized half-precision float may have.
+     */
+    public static final short MIN_EXPONENT       = -14;
+    /**
+     * Smallest positive normal value a half-precision float may have.
+     */
+    public static final short MIN_NORMAL         = (short) 0x0400;
+    /**
+     * Smallest positive non-zero value a half-precision float may have.
+     */
+    public static final short MIN_VALUE          = (short) 0x0001;
+    /**
+     * A Not-a-Number representation of a half-precision float.
+     */
+    public static final short NaN                = (short) 0x7e00;
+    /**
+     * Negative infinity of type half-precision float.
+     */
+    public static final short NEGATIVE_INFINITY  = (short) 0xfc00;
+    /**
+     * Negative 0 of type half-precision float.
+     */
+    public static final short NEGATIVE_ZERO      = (short) 0x8000;
+    /**
+     * Positive infinity of type half-precision float.
+     */
+    public static final short POSITIVE_INFINITY  = (short) 0x7c00;
+    /**
+     * Positive 0 of type half-precision float.
+     */
+    public static final short POSITIVE_ZERO      = (short) 0x0000;
+
+    private static final int FP16_SIGN_SHIFT     = 15;
+    private static final int FP16_EXPONENT_SHIFT = 10;
+    private static final int FP16_EXPONENT_MASK  = 0x1f;
+    private static final int FP16_MANTISSA_MASK  = 0x3ff;
+    private static final int FP16_EXPONENT_BIAS  = 15;
+
+    private static final int FP32_SIGN_SHIFT     = 31;
+    private static final int FP32_EXPONENT_SHIFT = 23;
+    private static final int FP32_EXPONENT_MASK  = 0xff;
+    private static final int FP32_MANTISSA_MASK  = 0x7fffff;
+    private static final int FP32_EXPONENT_BIAS  = 127;
+
+    private static final int   FP32_DENORMAL_MAGIC = 126 << 23;
+    private static final float FP32_DENORMAL_FLOAT =
+            Float.intBitsToFloat(FP32_DENORMAL_MAGIC);
+
+    private Half() {
+    }
+
+    /**
+     * Returns the sign of the specified half-precision float.
+     *
+     * @param h A half-precision float value
+     * @return 1 if the value is positive, -1 if the value is negative
+     */
+    public static int getSign(short h) {
+        return (h >>> FP16_SIGN_SHIFT) == 0 ? 1 : -1;
+    }
+
+    /**
+     * Returns the unbiased exponent used in the representation of
+     * the specified  half-precision float value. if the value is NaN
+     * or infinite, this* method returns {@link #MAX_EXPONENT} + 1.
+     * If the argument is* 0 or denormal, this method returns
+     * {@link #MIN_EXPONENT} - 1.
+     *
+     * @param h A half-precision float value
+     * @return The unbiased exponent of the specified value
+     */
+    public static int getExponent(short h) {
+        return ((h >>> FP16_EXPONENT_SHIFT) & FP16_EXPONENT_MASK) - FP16_EXPONENT_BIAS;
+    }
+
+    /**
+     * Returns the mantissa, or significand, used in the representation
+     * of the specified half-precision float value.
+     *
+     * @param h A half-precision float value
+     * @return The mantissa, or significand, of the specified vlaue
+     */
+    public static int getMantissa(short h) {
+        return h & FP16_MANTISSA_MASK;
+    }
+
+    /**
+     * Returns true if the specified half-precision float value represents
+     * infinity, false otherwise.
+     *
+     * @param h A half-precision float value
+     * @return true if the value is positive infinity or negative infinity,
+     *         false otherwise
+     */
+    public static boolean isInfinite(short h) {
+        int e = (h >>> FP16_EXPONENT_SHIFT) & FP16_EXPONENT_MASK;
+        int m = (h                        ) & FP16_MANTISSA_MASK;
+        return e == 0x1f && m == 0;
+    }
+
+    /**
+     * Returns true if the specified half-precision float value represents
+     * a Not-a-Number, false otherwise.
+     *
+     * @param h A half-precision float value
+     * @return true if the value is a NaN, false otherwise
+     */
+    public static boolean isNaN(short h) {
+        int e = (h >>> FP16_EXPONENT_SHIFT) & FP16_EXPONENT_MASK;
+        int m = (h                        ) & FP16_MANTISSA_MASK;
+        return e == 0x1f && m != 0;
+    }
+
+    /**
+     * <p>Converts the specified half-precision float value into a
+     * single-precision float value with the following special cases:</p>
+     * <ul>
+     * <li>If the input is {@link #NaN}, the returned* value is {@link Float#NaN}</li>
+     * <li>If the input is {@link #POSITIVE_INFINITY} or
+     * {@link #NEGATIVE_INFINITY}, the returned value is respectively
+     * {@link Float#POSITIVE_INFINITY} or {@link Float#NEGATIVE_INFINITY}</li>
+     * <li>If the input is 0 (positive or negative), the returned value is +/-0.0f</li>
+     * <li>Otherwise, the returned value is a normalized single-precision float value</li>
+     * </ul>
+     *
+     * @param h The half-precision float value to convert to single-precision
+     * @return A normalized single-precision float value
+     */
+    public static float toFloat(short h) {
+        int bits = h & 0xffff;
+        int s = (bits >>> FP16_SIGN_SHIFT    );
+        int e = (bits >>> FP16_EXPONENT_SHIFT) & FP16_EXPONENT_MASK;
+        int m = (bits                        ) & FP16_MANTISSA_MASK;
+
+        int outE = 0;
+        int outM = 0;
+
+        if (e == 0) { // Denormal or 0
+            if (m != 0) {
+                // Convert denorm fp16 into normalized fp32
+                float o = Float.intBitsToFloat(FP32_DENORMAL_MAGIC + m);
+                o -= FP32_DENORMAL_FLOAT;
+                return s == 0 ? o : -o;
+            }
+        } else {
+            outM = m << 13;
+            if (e == 0x1f) { // Infinite or NaN
+                outE = 0xff;
+            } else {
+                outE = e - FP16_EXPONENT_BIAS + FP32_EXPONENT_BIAS;
+            }
+        }
+
+        int out = (s << FP32_SIGN_SHIFT) | (outE << FP32_EXPONENT_SHIFT) | outM;
+        return Float.intBitsToFloat(out);
+    }
+
+    /**
+     * <p>Converts the specified single-precision float value into a
+     * half-precision float value with the following special cases:</p>
+     * <ul>
+     * <li>If the input is NaN (see {@link Float#isNaN(float)}), the returned
+     * value is {@link #NaN}</li>
+     * <li>If the input is {@link Float#POSITIVE_INFINITY} or
+     * {@link Float#NEGATIVE_INFINITY}, the returned value is respectively
+     * {@link #POSITIVE_INFINITY} or {@link #NEGATIVE_INFINITY}</li>
+     * <li>If the input is 0 (positive or negative), the returned value is
+     * {@link #POSITIVE_ZERO} or {@link #NEGATIVE_ZERO}</li>
+     * <li>If the input is a less than {@link #MIN_VALUE}, the returned value
+     * is flushed to {@link #POSITIVE_ZERO} or {@link #NEGATIVE_ZERO}</li>
+     * <li>If the input is a less than {@link #MIN_NORMAL}, the returned value
+     * is a denorm half-precision float</li>
+     * <li>Otherwise, the returned value is rounded to the nearest
+     * representable half-precision float value</li>
+     * </ul>
+     *
+     * @param f The single-precision float value to convert to half-precision
+     * @return A half-precision float value
+     */
+    @SuppressWarnings("StatementWithEmptyBody")
+    public static short valueOf(float f) {
+        int bits = Float.floatToRawIntBits(f);
+        int s = (bits >>> FP32_SIGN_SHIFT    );
+        int e = (bits >>> FP32_EXPONENT_SHIFT) & FP32_EXPONENT_MASK;
+        int m = (bits                        ) & FP32_MANTISSA_MASK;
+
+        int outE = 0;
+        int outM = 0;
+
+        if (e == 0xff) { // Infinite or NaN
+            outE = 0x1f;
+            outM = m != 0 ? 0x200 : 0;
+        } else {
+            e = e - FP32_EXPONENT_BIAS + FP16_EXPONENT_BIAS;
+            if (e >= 0x1f) { // Overflow
+                outE = 0x31;
+            } else if (e <= 0) { // Underflow
+                if (e < -10) {
+                    // The absolute fp32 value is less than MIN_VALUE, flush to +/-0
+                } else {
+                    // The fp32 value is a normalized float less than MIN_NORMAL,
+                    // we convert to a denorm fp16
+                    m = (m | 0x800000) >> (1 - e);
+                    if ((m & 0x1000) != 0) m += 0x2000;
+                    outM = m >> 13;
+                }
+            } else {
+                outE = e;
+                outM = m >> 13;
+                if ((m & 0x1000) != 0) {
+                    // Round to nearest "0.5" up
+                    int out = (outE << FP16_EXPONENT_SHIFT) | outM;
+                    out++;
+                    out |= (s << FP16_SIGN_SHIFT);
+                    return (short) out;
+                }
+            }
+        }
+
+        int out = (s << FP16_SIGN_SHIFT) | (outE << FP16_EXPONENT_SHIFT) | outM;
+        return (short) out;
+    }
+
+    /**
+     * Returns a string representation of the specified half-precision
+     * float value. Calling this method is equivalent to calling
+     * <code>Float.toString(toFloat(h))</code>. See {@link Float#toString(float)}
+     * for more information on the format of the string representation.
+     *
+     * @param h A half-precision float value
+     * @return A string representation of the specified value
+     */
+    public static String toString(short h) {
+        return Float.toString(toFloat(h));
+    }
+
+    /**
+     * <p>Returns a hexadecimal string representation of the specified half-precision
+     * float value. If the value is a NaN, the result is <code>"NaN"</code>,
+     * otherwise the result follows this format:</p>
+     * <ul>
+     * <li>If the sign is positive, no sign character appears in the result</li>
+     * <li>If the sign is negative, the first character is <code>'-'</code></li>
+     * <li>If the value is inifinity, the string is <code>"Infinity"</code></li>
+     * <li>If the value is 0, the string is <code>"0x0.0p0"</code></li>
+     * <li>If the value has a normalized representation, the exponent and
+     * mantissa are represented in the string in two fields. The mantissa starts
+     * with <code>"0x1."</code> followed by its lowercase hexadecimal
+     * representation. Trailing zeroes are removed unless all digits are 0, then
+     * a single zero is used. The mantissa representation is followed by the
+     * exponent, represented by <code>"p"</code>, itself followed by a decimal
+     * string of the unbiased exponent</li>
+     * <li>If the value has a denormal representation, the mantissa starts
+     * with <code>"0x0."</code> followed by its lowercase hexadecimal
+     * representation. Trailing zeroes are removed unless all digits are 0, then
+     * a single zero is used. The mantissa representation is followed by the
+     * exponent, represented by <code>"p-14"</code></li>
+     * </ul>
+     *
+     * @param h A half-precision float value
+     * @return A hexadecimal string representation of the specified value
+     */
+    public static String toHexString(short h) {
+        StringBuilder o = new StringBuilder();
+
+        int bits = h & 0xffff;
+        int s = (bits >>> FP16_SIGN_SHIFT    );
+        int e = (bits >>> FP16_EXPONENT_SHIFT) & FP16_EXPONENT_MASK;
+        int m = (bits                        ) & FP16_MANTISSA_MASK;
+
+        if (e == 0x1f) { // Infinite or NaN
+            if (m == 0) {
+                if (s == 1) o.append('-');
+                o.append("Infinity");
+            } else {
+                o.append("NaN");
+            }
+        } else {
+            if (s == 1) o.append('-');
+            if (e == 0) {
+                if (m == 0) {
+                    o.append("0x0.0p0");
+                } else {
+                    o.append("0x0.");
+                    String mantissa = Integer.toHexString(m);
+                    o.append(mantissa.replaceFirst("0{2,}$", ""));
+                    o.append("p-14");
+                }
+            } else {
+                o.append("0x1.");
+                String mantissa = Integer.toHexString(m);
+                o.append(mantissa.replaceFirst("0{2,}$", ""));
+                o.append('p');
+                o.append(Integer.toString(e - FP16_EXPONENT_BIAS));
+            }
+        }
+
+        return o.toString();
+    }
+}
diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl
index 717b675..7917041 100644
--- a/core/java/android/view/IWindowManager.aidl
+++ b/core/java/android/view/IWindowManager.aidl
@@ -191,10 +191,10 @@
     // If there is a change, the new Configuration is returned and the
     // caller must call setNewConfiguration() sometime later.
     Configuration updateOrientationFromAppTokens(in Configuration currentConfig,
-            IBinder freezeThisOneIfNeeded);
-    // Notify window manager of the new configuration. Returns an array of stack ids that's
-    // affected by the update, ActivityManager should resize these stacks.
-    int[] setNewConfiguration(in Configuration config);
+            IBinder freezeThisOneIfNeeded, int displayId);
+    // Notify window manager of the new display override configuration. Returns an array of stack
+    // ids that were affected by the update, ActivityManager should resize these stacks.
+    int[] setNewDisplayOverrideConfiguration(in Configuration overrideConfig, int displayId);
 
     // Retrieves the new bounds after the configuration update evaluated by window manager.
     Rect getBoundsForNewConfiguration(int stackId);
diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java
index bf49048..5eaabe7 100644
--- a/core/java/android/widget/Editor.java
+++ b/core/java/android/widget/Editor.java
@@ -2345,7 +2345,7 @@
         }
 
         mCorrectionHighlighter.highlight(info);
-        mUndoInputFilter.onCommitCorrection();
+        mUndoInputFilter.freezeLastEdit();
     }
 
     void onScrollChanged() {
@@ -2477,6 +2477,7 @@
         }
 
         mTextView.beginBatchEdit();
+        mUndoInputFilter.freezeLastEdit();
         try {
             final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
             Object localState = event.getLocalState();
@@ -2526,6 +2527,7 @@
             }
         } finally {
             mTextView.endBatchEdit();
+            mUndoInputFilter.freezeLastEdit();
         }
     }
 
@@ -5477,10 +5479,12 @@
                 // Expanding with start handle.
                 offset = getWordStart(offset);
                 startOffset = getWordEnd(mStartOffset);
+                if (startOffset == offset) {
+                    offset = getNextCursorOffset(offset, false);
+                }
             }
             mLineSelectionIsOn = currLine;
-            Selection.setSelection((Spannable) mTextView.getText(),
-                    startOffset, offset);
+            Selection.setSelection((Spannable) mTextView.getText(), startOffset, offset);
         }
 
         private void updateParagraphBasedSelection(MotionEvent event) {
@@ -5843,7 +5847,7 @@
             return null;
         }
 
-        void onCommitCorrection() {
+        void freezeLastEdit() {
             mEditor.mUndoManager.beginUpdate("Edit text");
             EditOperation lastEdit = getLastEdit();
             if (lastEdit != null) {
@@ -5904,7 +5908,6 @@
                 // Add this as the first edit.
                 if (DEBUG_UNDO) Log.d(TAG, "filter: adding first op " + edit);
                 um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
-                mPreviousOperationWasInSameBatchEdit = mIsUserEdit;
             } else if (mergeMode == MERGE_EDIT_MODE_FORCE_MERGE) {
                 // Forced merges take priority because they could be the result of a non-user-edit
                 // change and this case should not create a new undo operation.
@@ -5916,7 +5919,6 @@
                 if (DEBUG_UNDO) Log.d(TAG, "non-user edit, new op " + edit);
                 um.commitState(mEditor.mUndoOwner);
                 um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
-                mPreviousOperationWasInSameBatchEdit = mIsUserEdit;
             } else if (mergeMode == MERGE_EDIT_MODE_NORMAL && lastEdit.mergeWith(edit)) {
                 // Merge succeeded, nothing else to do.
                 if (DEBUG_UNDO) Log.d(TAG, "filter: merge succeeded, created " + lastEdit);
@@ -5925,8 +5927,8 @@
                 if (DEBUG_UNDO) Log.d(TAG, "filter: merge failed, adding " + edit);
                 um.commitState(mEditor.mUndoOwner);
                 um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
-                mPreviousOperationWasInSameBatchEdit = mIsUserEdit;
             }
+            mPreviousOperationWasInSameBatchEdit = mIsUserEdit;
             um.endUpdate();
         }
 
diff --git a/core/java/android/widget/Toast.java b/core/java/android/widget/Toast.java
index 4efcb09..789e60b 100644
--- a/core/java/android/widget/Toast.java
+++ b/core/java/android/widget/Toast.java
@@ -100,13 +100,13 @@
      */
     public Toast(Context context) {
         mContext = context;
-        mTN = new TN();
+        mTN = new TN(context.getPackageName());
         mTN.mY = context.getResources().getDimensionPixelSize(
                 com.android.internal.R.dimen.toast_y_offset);
         mTN.mGravity = context.getResources().getInteger(
                 com.android.internal.R.integer.config_toastDefaultGravity);
     }
-    
+
     /**
      * Show the view for the specified duration.
      */
@@ -133,15 +133,9 @@
      * after the appropriate duration.
      */
     public void cancel() {
-        mTN.hide();
-
-        try {
-            getService().cancelToast(mContext.getPackageName(), mTN);
-        } catch (RemoteException e) {
-            // Empty
-        }
+        mTN.cancel();
     }
-    
+
     /**
      * Set the view to show.
      * @see #getView
@@ -328,21 +322,37 @@
     }
 
     private static class TN extends ITransientNotification.Stub {
-        final Runnable mHide = new Runnable() {
-            @Override
-            public void run() {
-                handleHide();
-                // Don't do this in handleHide() because it is also invoked by handleShow()
-                mNextView = null;
-            }
-        };
-
         private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
+
+        private static final int SHOW = 0;
+        private static final int HIDE = 1;
+        private static final int CANCEL = 2;
         final Handler mHandler = new Handler() {
             @Override
             public void handleMessage(Message msg) {
-                IBinder token = (IBinder) msg.obj;
-                handleShow(token);
+                switch (msg.what) {
+                    case SHOW: {
+                        IBinder token = (IBinder) msg.obj;
+                        handleShow(token);
+                        break;
+                    }
+                    case HIDE: {
+                        handleHide();
+                        // Don't do this in handleHide() because it is also invoked by handleShow()
+                        mNextView = null;
+                        break;
+                    }
+                    case CANCEL: {
+                        handleHide();
+                        // Don't do this in handleHide() because it is also invoked by handleShow()
+                        mNextView = null;
+                        try {
+                            getService().cancelToast(mPackageName, TN.this);
+                        } catch (RemoteException e) {
+                        }
+                        break;
+                    }
+                }
             }
         };
 
@@ -358,10 +368,12 @@
 
         WindowManager mWM;
 
+        String mPackageName;
+
         static final long SHORT_DURATION_TIMEOUT = 4000;
         static final long LONG_DURATION_TIMEOUT = 7000;
 
-        TN() {
+        TN(String packageName) {
             // XXX This should be changed to use a Dialog, with a Theme.Toast
             // defined that sets up the layout params appropriately.
             final WindowManager.LayoutParams params = mParams;
@@ -374,6 +386,8 @@
             params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                     | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                     | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
+
+            mPackageName = packageName;
         }
 
         /**
@@ -382,7 +396,7 @@
         @Override
         public void show(IBinder windowToken) {
             if (localLOGV) Log.v(TAG, "SHOW: " + this);
-            mHandler.obtainMessage(0, windowToken).sendToTarget();
+            mHandler.obtainMessage(SHOW, windowToken).sendToTarget();
         }
 
         /**
@@ -391,7 +405,12 @@
         @Override
         public void hide() {
             if (localLOGV) Log.v(TAG, "HIDE: " + this);
-            mHandler.post(mHide);
+            mHandler.obtainMessage(HIDE).sendToTarget();
+        }
+
+        public void cancel() {
+            if (localLOGV) Log.v(TAG, "CANCEL: " + this);
+            mHandler.obtainMessage(CANCEL).sendToTarget();
         }
 
         public void handleShow(IBinder windowToken) {
diff --git a/core/java/com/android/internal/widget/LockPatternUtils.java b/core/java/com/android/internal/widget/LockPatternUtils.java
index 0e07bf8..71252fb 100644
--- a/core/java/com/android/internal/widget/LockPatternUtils.java
+++ b/core/java/com/android/internal/widget/LockPatternUtils.java
@@ -19,6 +19,7 @@
 import android.annotation.IntDef;
 import android.annotation.Nullable;
 import android.app.admin.DevicePolicyManager;
+import android.app.admin.PasswordMetrics;
 import android.app.trust.IStrongAuthTracker;
 import android.app.trust.TrustManager;
 import android.content.ComponentName;
@@ -137,10 +138,6 @@
     private static final String ENABLED_TRUST_AGENTS = "lockscreen.enabledtrustagents";
     private static final String IS_TRUST_USUALLY_MANAGED = "lockscreen.istrustusuallymanaged";
 
-    // Maximum allowed number of repeated or ordered characters in a sequence before we'll
-    // consider it a complex PIN/password.
-    public static final int MAX_ALLOWED_SEQUENCE = 3;
-
     public static final String PROFILE_KEY_NAME_ENCRYPT = "profile_key_name_encrypt_";
     public static final String PROFILE_KEY_NAME_DECRYPT = "profile_key_name_decrypt_";
 
@@ -593,8 +590,7 @@
             setCredentialRequiredToDecrypt(false);
         }
 
-        getDevicePolicyManager().setActivePasswordState(
-                DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, 0, 0, 0, 0, 0, 0, 0, userHandle);
+        getDevicePolicyManager().setActivePasswordState(new PasswordMetrics(), userHandle);
 
         onAfterChangingPassword(userHandle);
     }
@@ -665,8 +661,8 @@
             setBoolean(PATTERN_EVER_CHOSEN_KEY, true, userId);
 
             setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, userId);
-            dpm.setActivePasswordState(DevicePolicyManager.PASSWORD_QUALITY_SOMETHING,
-                    pattern.size(), 0, 0, 0, 0, 0, 0, userId);
+            dpm.setActivePasswordState(new PasswordMetrics(
+                    DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, pattern.size()), userId);
             onAfterChangingPassword(userId);
         } catch (RemoteException re) {
             Log.e(TAG, "Couldn't save lock pattern " + re);
@@ -736,96 +732,6 @@
         return getDeviceOwnerInfo() != null;
     }
 
-    /**
-     * Compute the password quality from the given password string.
-     */
-    static public int computePasswordQuality(String password) {
-        boolean hasDigit = false;
-        boolean hasNonDigit = false;
-        final int len = password.length();
-        for (int i = 0; i < len; i++) {
-            if (Character.isDigit(password.charAt(i))) {
-                hasDigit = true;
-            } else {
-                hasNonDigit = true;
-            }
-        }
-
-        if (hasNonDigit && hasDigit) {
-            return DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
-        }
-        if (hasNonDigit) {
-            return DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
-        }
-        if (hasDigit) {
-            return maxLengthSequence(password) > MAX_ALLOWED_SEQUENCE
-                    ? DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
-                    : DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
-        }
-        return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
-    }
-
-    private static int categoryChar(char c) {
-        if ('a' <= c && c <= 'z') return 0;
-        if ('A' <= c && c <= 'Z') return 1;
-        if ('0' <= c && c <= '9') return 2;
-        return 3;
-    }
-
-    private static int maxDiffCategory(int category) {
-        if (category == 0 || category == 1) return 1;
-        else if (category == 2) return 10;
-        return 0;
-    }
-
-    /*
-     * Returns the maximum length of a sequential characters.  A sequence is defined as
-     * monotonically increasing characters with a constant interval or the same character repeated.
-     *
-     * For example:
-     * maxLengthSequence("1234") == 4
-     * maxLengthSequence("1234abc") == 4
-     * maxLengthSequence("aabc") == 3
-     * maxLengthSequence("qwertyuio") == 1
-     * maxLengthSequence("@ABC") == 3
-     * maxLengthSequence(";;;;") == 4 (anything that repeats)
-     * maxLengthSequence(":;<=>") == 1  (ordered, but not composed of alphas or digits)
-     *
-     * @param string the pass
-     * @return the number of sequential letters or digits
-     */
-    public static int maxLengthSequence(String string) {
-        if (string.length() == 0) return 0;
-        char previousChar = string.charAt(0);
-        int category = categoryChar(previousChar); //current category of the sequence
-        int diff = 0; //difference between two consecutive characters
-        boolean hasDiff = false; //if we are currently targeting a sequence
-        int maxLength = 0; //maximum length of a sequence already found
-        int startSequence = 0; //where the current sequence started
-        for (int current = 1; current < string.length(); current++) {
-            char currentChar = string.charAt(current);
-            int categoryCurrent = categoryChar(currentChar);
-            int currentDiff = (int) currentChar - (int) previousChar;
-            if (categoryCurrent != category || Math.abs(currentDiff) > maxDiffCategory(category)) {
-                maxLength = Math.max(maxLength, current - startSequence);
-                startSequence = current;
-                hasDiff = false;
-                category = categoryCurrent;
-            }
-            else {
-                if(hasDiff && currentDiff != diff) {
-                    maxLength = Math.max(maxLength, current - startSequence);
-                    startSequence = current - 1;
-                }
-                diff = currentDiff;
-                hasDiff = true;
-            }
-            previousChar = currentChar;
-        }
-        maxLength = Math.max(maxLength, string.length() - startSequence);
-        return maxLength;
-    }
-
     /** Update the encryption password if it is enabled **/
     private void updateEncryptionPassword(final int type, final String password) {
         if (!isDeviceEncryptionEnabled()) {
@@ -871,7 +777,8 @@
 
             getLockSettings().setLockPassword(password, savedPassword, userHandle);
             getLockSettings().setSeparateProfileChallengeEnabled(userHandle, true, null);
-            int computedQuality = computePasswordQuality(password);
+            final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password);
+            final int computedQuality = metrics.quality;
 
             // Update the device encryption password.
             if (userHandle == UserHandle.USER_SYSTEM
@@ -891,36 +798,11 @@
 
             setLong(PASSWORD_TYPE_KEY, Math.max(quality, computedQuality), userHandle);
             if (computedQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
-                int letters = 0;
-                int uppercase = 0;
-                int lowercase = 0;
-                int numbers = 0;
-                int symbols = 0;
-                int nonletter = 0;
-                for (int i = 0; i < password.length(); i++) {
-                    char c = password.charAt(i);
-                    if (c >= 'A' && c <= 'Z') {
-                        letters++;
-                        uppercase++;
-                    } else if (c >= 'a' && c <= 'z') {
-                        letters++;
-                        lowercase++;
-                    } else if (c >= '0' && c <= '9') {
-                        numbers++;
-                        nonletter++;
-                    } else {
-                        symbols++;
-                        nonletter++;
-                    }
-                }
-                dpm.setActivePasswordState(Math.max(quality, computedQuality),
-                        password.length(), letters, uppercase, lowercase,
-                        numbers, symbols, nonletter, userHandle);
+                metrics.quality = Math.max(quality, metrics.quality);
+                dpm.setActivePasswordState(metrics, userHandle);
             } else {
                 // The password is not anything.
-                dpm.setActivePasswordState(
-                        DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
-                        0, 0, 0, 0, 0, 0, 0, userHandle);
+                dpm.setActivePasswordState(new PasswordMetrics(), userHandle);
             }
 
             // Add the password to the password history. We assume all
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index c346849..de6f2c5 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -1712,11 +1712,6 @@
     <permission android:name="android.permission.GET_PROCESS_STATE_AND_OOM_SCORE"
         android:protectionLevel="signature|privileged|development" />
 
-    <!-- @SystemApi @hide Allows an application to retrieve a package's importance.
-         This permission is not available to third party applications. -->
-    <permission android:name="android.permission.GET_PACKAGE_IMPORTANCE"
-        android:protectionLevel="signature|privileged" />
-
     <!-- Allows use of PendingIntent.getIntent().
          @hide -->
     <permission android:name="android.permission.GET_INTENT_SENDER_INTENT"
diff --git a/core/res/res/values-fr/strings.xml b/core/res/res/values-fr/strings.xml
index 09b55d9..1e5f6a1 100644
--- a/core/res/res/values-fr/strings.xml
+++ b/core/res/res/values-fr/strings.xml
@@ -1570,7 +1570,7 @@
     <string name="package_deleted_device_owner" msgid="7650577387493101353">"Supprimé par votre administrateur"</string>
     <string name="battery_saver_description" msgid="1960431123816253034">"Pour améliorer l\'autonomie de la batterie, l\'économiseur de batterie réduit les performances et désactive le vibreur, les services de localisation et la plupart des données en arrière-plan. Les messageries électroniques ou autres applications utilisant la synchronisation pourraient ne pas se mettre à jour, sauf si vous les ouvrez.\n\nL\'économiseur de batterie s\'éteint automatiquement lorsque l\'appareil est en charge."</string>
     <string name="data_saver_description" msgid="6015391409098303235">"Pour réduire la consommation des données, l\'économiseur de données empêche certaines applications d\'envoyer ou de recevoir des données en arrière-plan. Ainsi, une application que vous utilisez actuellement peut accéder à des données, mais moins souvent. Par exemple, il se peut que les images ne s\'affichent pas tant que vous n\'appuyez pas dessus."</string>
-    <string name="data_saver_enable_title" msgid="4674073932722787417">"Activer sauvegarde données ?"</string>
+    <string name="data_saver_enable_title" msgid="4674073932722787417">"Activer l\'économiseur de données ?"</string>
     <string name="data_saver_enable_button" msgid="7147735965247211818">"Activer"</string>
     <plurals name="zen_mode_duration_minutes_summary" formatted="false" msgid="4367877408072000848">
       <item quantity="one">Pendant %1$d minute (jusqu\'à <xliff:g id="FORMATTEDTIME_1">%2$s</xliff:g>)</item>
diff --git a/core/res/res/values-hy-rAM/strings.xml b/core/res/res/values-hy-rAM/strings.xml
index 29c3120..5a1ad70 100644
--- a/core/res/res/values-hy-rAM/strings.xml
+++ b/core/res/res/values-hy-rAM/strings.xml
@@ -214,7 +214,7 @@
     <string name="global_actions" product="default" msgid="2406416831541615258">"Հեռախոսի ընտրանքներ"</string>
     <string name="global_action_lock" msgid="2844945191792119712">"Էկրանի փական"</string>
     <string name="global_action_power_off" msgid="4471879440839879722">"Անջատել"</string>
-    <string name="global_action_emergency" msgid="7112311161137421166">"Արտակարգ իրավիճակ"</string>
+    <string name="global_action_emergency" msgid="7112311161137421166">"Շտապ կանչ"</string>
     <string name="global_action_bug_report" msgid="7934010578922304799">"Վրիպակի զեկույց"</string>
     <string name="bugreport_title" msgid="2667494803742548533">"Գրել սխալի զեկույց"</string>
     <string name="bugreport_message" msgid="398447048750350456">"Սա տեղեկություններ կհավաքագրի ձեր սարքի առկա կարգավիճակի մասին և կուղարկի այն էլեկտրոնային նամակով: Որոշակի ժամանակ կպահանջվի վրիպակի մասին զեկուցելու պահից սկսած մինչ ուղարկելը: Խնդրում ենք փոքր-ինչ համբերատար լինել:"</string>
@@ -674,7 +674,7 @@
     <string name="lockscreen_instructions_when_pattern_enabled" msgid="46154051614126049">"Ապակողպելու կամ շտապ կանչ անելու համար սեղմեք «Ընտրացանկ»"</string>
     <string name="lockscreen_instructions_when_pattern_disabled" msgid="686260028797158364">"Ապակողպելու համար սեղմեք Ցանկը:"</string>
     <string name="lockscreen_pattern_instructions" msgid="7478703254964810302">"Հավաքեք սխեման` ապակողպելու համար"</string>
-    <string name="lockscreen_emergency_call" msgid="5298642613417801888">"Արտակարգ իրավիճակ"</string>
+    <string name="lockscreen_emergency_call" msgid="5298642613417801888">"Շտապ կանչ"</string>
     <string name="lockscreen_return_to_call" msgid="5244259785500040021">"Վերադառնալ զանգին"</string>
     <string name="lockscreen_pattern_correct" msgid="9039008650362261237">"Ճիշտ է:"</string>
     <string name="lockscreen_pattern_wrong" msgid="4317955014948108794">"Կրկին փորձեք"</string>
diff --git a/core/res/res/values-ja/strings.xml b/core/res/res/values-ja/strings.xml
index 5305b1f..02736ec 100644
--- a/core/res/res/values-ja/strings.xml
+++ b/core/res/res/values-ja/strings.xml
@@ -512,8 +512,8 @@
     <string name="permdesc_bindCarrierMessagingService" msgid="2762882888502113944">"携帯通信会社のSMSサービスのトップレベルインターフェースにバインドすることを所有者に許可します。通常のアプリでは不要です。"</string>
     <string name="permlab_bindCarrierServices" msgid="3233108656245526783">"携帯通信会社のサービスへのバインド"</string>
     <string name="permdesc_bindCarrierServices" msgid="1391552602551084192">"携帯通信会社のサービスにバインドすることを所有者に許可します。通常のアプリでは不要です。"</string>
-    <string name="permlab_access_notification_policy" msgid="4247510821662059671">"[通知を非表示]へのアクセス"</string>
-    <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"[通知を非表示]の設定の読み取りと書き込みをアプリに許可します。"</string>
+    <string name="permlab_access_notification_policy" msgid="4247510821662059671">"マナーモードへのアクセス"</string>
+    <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"マナーモード設定の読み取りと書き込みをアプリに許可します。"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"パスワードルールの設定"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"画面ロックのパスワードとPINの長さと使用できる文字を制御します。"</string>
     <string name="policylab_watchLogin" msgid="914130646942199503">"画面ロック解除試行の監視"</string>
@@ -1607,10 +1607,10 @@
     <string name="zen_mode_until" msgid="7336308492289875088">"<xliff:g id="FORMATTEDTIME">%1$s</xliff:g>まで"</string>
     <string name="zen_mode_alarm" msgid="9128205721301330797">"<xliff:g id="FORMATTEDTIME">%1$s</xliff:g>(次のアラーム)まで"</string>
     <string name="zen_mode_forever" msgid="7420011936770086993">"ユーザーがOFFにするまで"</string>
-    <string name="zen_mode_forever_dnd" msgid="3792132696572189081">"[通知を非表示]をOFFにするまで"</string>
+    <string name="zen_mode_forever_dnd" msgid="3792132696572189081">"マナーモードを OFF にするまで"</string>
     <string name="zen_mode_rule_name_combination" msgid="191109939968076477">"<xliff:g id="FIRST">%1$s</xliff:g>/<xliff:g id="REST">%2$s</xliff:g>"</string>
     <string name="toolbar_collapse_description" msgid="2821479483960330739">"折りたたむ"</string>
-    <string name="zen_mode_feature_name" msgid="5254089399895895004">"通知を非表示"</string>
+    <string name="zen_mode_feature_name" msgid="5254089399895895004">"マナーモード"</string>
     <string name="zen_mode_downtime_feature_name" msgid="2626974636779860146">"ダウンタイム"</string>
     <string name="zen_mode_default_weeknights_name" msgid="3081318299464998143">"平日の夜"</string>
     <string name="zen_mode_default_weekends_name" msgid="2786495801019345244">"週末"</string>
diff --git a/core/res/res/values-ko/strings.xml b/core/res/res/values-ko/strings.xml
index 4191865..f0cfd0b 100644
--- a/core/res/res/values-ko/strings.xml
+++ b/core/res/res/values-ko/strings.xml
@@ -260,7 +260,7 @@
     <string name="permgrouplab_phone" msgid="5229115638567440675">"전화"</string>
     <string name="permgroupdesc_phone" msgid="6234224354060641055">"통화 상태를 관리하거나 전화를 걸 수 있도록"</string>
     <string name="permgrouplab_sensors" msgid="416037179223226722">"신체 센서"</string>
-    <string name="permgroupdesc_sensors" msgid="7147968539346634043">"생체 신호에 관한 센서 데이터에 접근할 수 있도록"</string>
+    <string name="permgroupdesc_sensors" msgid="7147968539346634043">"생체 신호에 관한 센서 데이터에 액세스"</string>
     <string name="capability_title_canRetrieveWindowContent" msgid="3901717936930170320">"창 콘텐츠 가져오기"</string>
     <string name="capability_desc_canRetrieveWindowContent" msgid="3772225008605310672">"상호작용 중인 창의 콘텐츠를 검사합니다."</string>
     <string name="capability_title_canRequestTouchExploration" msgid="3108723364676667320">"터치하여 탐색 사용"</string>
diff --git a/core/res/res/values-zh-rCN/strings.xml b/core/res/res/values-zh-rCN/strings.xml
index b67d6e2..68e87c2 100644
--- a/core/res/res/values-zh-rCN/strings.xml
+++ b/core/res/res/values-zh-rCN/strings.xml
@@ -195,7 +195,7 @@
     <string name="silent_mode_ring" msgid="8592241816194074353">"振铃器开启"</string>
     <string name="reboot_to_update_title" msgid="6212636802536823850">"Android 系统更新"</string>
     <string name="reboot_to_update_prepare" msgid="6305853831955310890">"正在准备更新…"</string>
-    <string name="reboot_to_update_package" msgid="3871302324500927291">"正在处理更新文件包…"</string>
+    <string name="reboot_to_update_package" msgid="3871302324500927291">"正在处理更新软件包…"</string>
     <string name="reboot_to_update_reboot" msgid="6428441000951565185">"正在重新启动…"</string>
     <string name="reboot_to_reset_title" msgid="4142355915340627490">"恢复出厂设置"</string>
     <string name="reboot_to_reset_message" msgid="2432077491101416345">"正在重新启动…"</string>
diff --git a/core/tests/coretests/src/android/app/admin/PasswordMetricsTest.java b/core/tests/coretests/src/android/app/admin/PasswordMetricsTest.java
new file mode 100644
index 0000000..e9e3a18
--- /dev/null
+++ b/core/tests/coretests/src/android/app/admin/PasswordMetricsTest.java
@@ -0,0 +1,138 @@
+/*
+ * 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.app.admin;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import android.os.Parcel;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/** Unit tests for {@link PasswordMetrics}. */
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class PasswordMetricsTest {
+
+    @Test
+    public void testIsDefault() {
+        final PasswordMetrics metrics = new PasswordMetrics();
+        assertEquals(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, metrics.quality);
+        assertEquals(0, metrics.length);
+        assertEquals(0, metrics.letters);
+        assertEquals(0, metrics.upperCase);
+        assertEquals(0, metrics.lowerCase);
+        assertEquals(0, metrics.numeric);
+        assertEquals(0, metrics.symbols);
+        assertEquals(0, metrics.nonLetter);
+        assertTrue("default constructor does not produce default metrics", metrics.isDefault());
+    }
+
+    @Test
+    public void testIsNotDefault() {
+        final PasswordMetrics metrics = new PasswordMetrics(
+                DevicePolicyManager.PASSWORD_QUALITY_NUMERIC, 12);
+        assertFalse("non-default metrics are repoted as default", metrics.isDefault());
+    }
+
+    @Test
+    public void testComputeForEmptyPassword() {
+        final PasswordMetrics metrics = PasswordMetrics.computeForPassword("");
+        assertTrue("empty password has default metrics", metrics.isDefault());
+    }
+
+    @Test
+    public void testParceling() {
+        final int quality = 0;
+        final int length = 1;
+        final int letters = 2;
+        final int upperCase = 3;
+        final int lowerCase = 4;
+        final int numeric = 5;
+        final int symbols = 6;
+        final int nonLetter = 7;
+
+        final Parcel parcel = Parcel.obtain();
+        final PasswordMetrics metrics;
+        try {
+            new PasswordMetrics(
+                    quality, length, letters, upperCase, lowerCase, numeric, symbols, nonLetter)
+                    .writeToParcel(parcel, 0);
+            parcel.setDataPosition(0);
+            metrics = PasswordMetrics.CREATOR.createFromParcel(parcel);
+        } finally {
+            parcel.recycle();
+        }
+
+        assertEquals(quality, metrics.quality);
+        assertEquals(length, metrics.length);
+        assertEquals(letters, metrics.letters);
+        assertEquals(upperCase, metrics.upperCase);
+        assertEquals(lowerCase, metrics.lowerCase);
+        assertEquals(numeric, metrics.numeric);
+        assertEquals(symbols, metrics.symbols);
+        assertEquals(nonLetter, metrics.nonLetter);
+
+    }
+
+    @Test
+    public void testComputeForPassword_metrics() {
+        final PasswordMetrics metrics = PasswordMetrics.computeForPassword("6B~0z1Z3*8A");
+        assertEquals(11, metrics.length);
+        assertEquals(4, metrics.letters);
+        assertEquals(3, metrics.upperCase);
+        assertEquals(1, metrics.lowerCase);
+        assertEquals(5, metrics.numeric);
+        assertEquals(2, metrics.symbols);
+        assertEquals(7, metrics.nonLetter);
+    }
+
+    @Test
+    public void testComputeForPassword_quality() {
+        assertEquals(DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC,
+                PasswordMetrics.computeForPassword("a1").quality);
+        assertEquals(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC,
+                PasswordMetrics.computeForPassword("a").quality);
+        assertEquals(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC,
+                PasswordMetrics.computeForPassword("*~&%$").quality);
+        assertEquals(DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX,
+                PasswordMetrics.computeForPassword("1").quality);
+        // contains a long sequence so isn't complex
+        assertEquals(DevicePolicyManager.PASSWORD_QUALITY_NUMERIC,
+                PasswordMetrics.computeForPassword("1234").quality);
+        assertEquals(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
+                PasswordMetrics.computeForPassword("").quality);
+    }
+
+    @Test
+    public void testMaxLengthSequence() {
+        assertEquals(4, PasswordMetrics.maxLengthSequence("1234"));
+        assertEquals(5, PasswordMetrics.maxLengthSequence("13579"));
+        assertEquals(4, PasswordMetrics.maxLengthSequence("1234abd"));
+        assertEquals(3, PasswordMetrics.maxLengthSequence("aabc"));
+        assertEquals(1, PasswordMetrics.maxLengthSequence("qwertyuio"));
+        assertEquals(3, PasswordMetrics.maxLengthSequence("@ABC"));
+        // anything that repeats
+        assertEquals(4, PasswordMetrics.maxLengthSequence(";;;;"));
+        // ordered, but not composed of alphas or digits
+        assertEquals(1, PasswordMetrics.maxLengthSequence(":;<=>"));
+    }
+}
diff --git a/core/tests/coretests/src/android/widget/TextViewActivityTest.java b/core/tests/coretests/src/android/widget/TextViewActivityTest.java
index ea22cd1..d0802a0 100644
--- a/core/tests/coretests/src/android/widget/TextViewActivityTest.java
+++ b/core/tests/coretests/src/android/widget/TextViewActivityTest.java
@@ -170,6 +170,21 @@
     }
 
     @SmallTest
+    public void testLongPressAndDragToSelect_emoji() throws Exception {
+        final String text = "\uD83D\uDE00\uD83D\uDE01\uD83D\uDE02\uD83D\uDE03";
+        onView(withId(R.id.textview)).perform(click());
+        onView(withId(R.id.textview)).perform(replaceText(text));
+
+        onView(withId(R.id.textview)).perform(longPressAndDragOnText(4, 6));
+        onView(withId(R.id.textview)).check(hasSelection("\uD83D\uDE02"));
+
+        onView(withId(R.id.textview)).perform(click());
+
+        onView(withId(R.id.textview)).perform(longPressAndDragOnText(4, 2));
+        onView(withId(R.id.textview)).check(hasSelection("\uD83D\uDE01"));
+    }
+
+    @SmallTest
     public void testDragAndDrop() throws Exception {
         final String text = "abc def ghi.";
         onView(withId(R.id.textview)).perform(click());
diff --git a/docs/html/_redirects.yaml b/docs/html/_redirects.yaml
index 6185dab..7daf85c 100644
--- a/docs/html/_redirects.yaml
+++ b/docs/html/_redirects.yaml
@@ -1237,7 +1237,7 @@
 - from: /r/studio-ui/run-with-work-profile.html
   to: /studio/run/index.html?utm_source=android-studio#ir-work-profile
 - from: /r/studio-ui/am-gpu-debugger.html
-  to: /studio/profile/am-gpu.html?utm_source=android-studio
+  to: /studio/debug/am-gpu-debugger.html?utm_source=android-studio
 - from: /r/studio-ui/theme-editor.html
   to: /studio/write/theme-editor.html?utm_source=android-studio
 - from: /r/studio-ui/translations-editor.html
diff --git a/docs/html/google/play/billing/billing_integrate.jd b/docs/html/google/play/billing/billing_integrate.jd
index 5d6b3a8..506a440 100755
--- a/docs/html/google/play/billing/billing_integrate.jd
+++ b/docs/html/google/play/billing/billing_integrate.jd
@@ -9,18 +9,18 @@
   <h2>In this document</h2>
   <ol>
     <li><a href="#billing-add-aidl">Adding the AIDL file</a></li>
-    <li><a href="#billing-permission">Updating Your Manifest</a></li>
+    <li><a href="#billing-permission">Updating your manifest</a></li>
     <li><a href="#billing-service">Creating a ServiceConnection</a></li>
-    <li><a href="#billing-requests">Making In-app Billing Requests</a>
+    <li><a href="#billing-requests">Making In-app Billing requests</a>
        <ol>
-       <li><a href="#QueryDetails">Querying Items Available for Purchase</a><li>
-       <li><a href="#Purchase">Purchasing an Item</a></li>
-       <li><a href="#QueryPurchases">Querying Purchased Items</a></li>
-       <li><a href="#Consume">Consuming a Purchase</a></li>
-       <li><a href="#Subs">Implementing Subscriptions</a></li>
+       <li><a href="#QueryDetails">Querying items available for purchase</a><li>
+       <li><a href="#Purchase">Purchasing an item</a></li>
+       <li><a href="#QueryPurchases">Querying purchased items</a></li>
+       <li><a href="#Consume">Consuming a purchase</a></li>
+       <li><a href="#Subs">Implementing subscriptions</a></li>
        </ol>
     </li>
-    <li><a href="#billing-security">Securing Your App</a>
+    <li><a href="#billing-security">Securing your app</a>
   </ol>
   <h2>Reference</h2>
   <ol>
@@ -42,7 +42,7 @@
   In-app Billing on Google Play provides a straightforward, simple interface
   for sending In-app Billing requests and managing In-app Billing transactions
   using Google Play. The information below covers the basics of how to make
-  calls from your application to the In-app Billing service using the Version 3
+  calls from your application to the In-app Billing service using the In-app Billing Version 3
   API.
 </p>
 
@@ -51,26 +51,25 @@
   your application, see the <a href=
   "{@docRoot}training/in-app-billing/index.html">Selling In-app Products</a>
   training class. The training class provides a complete sample In-app Billing
-  application, including convenience classes to handle key tasks related to
-  setting up your connection, sending billing requests and processing responses
+  application, including convenience classes to handle key tasks that are related to
+  setting up your connection, sending billing requests, processing responses
   from Google Play, and managing background threading so that you can make
   In-app Billing calls from your main activity.
 </p>
 
 <p>
-  Before you start, be sure that you read the <a href=
+  Before you start, read the <a href=
   "{@docRoot}google/play/billing/billing_overview.html">In-app Billing
-  Overview</a> to familiarize yourself with concepts that will make it easier
+  Overview</a> to familiarize yourself with concepts that make it easier
   for you to implement In-app Billing.
 </p>
 
-<p>To implement In-app Billing in your application, you need to do the
-following:</p>
+<p>Complete these steps to implement In-app Billing in your application:</p>
 
 <ol>
   <li>Add the In-app Billing library to your project.</li>
   <li>Update your {@code AndroidManifest.xml} file.</li>
-  <li>Create a {@code ServiceConnection} and bind it to
+  <li>Create a {@code ServiceConnection} and bind it to the
 {@code IInAppBillingService}.</li>
   <li>Send In-app Billing requests from your application to
 {@code IInAppBillingService}.</li>
@@ -79,55 +78,56 @@
 
 <h2 id="billing-add-aidl">Adding the AIDL file to your project</h2>
 
-<p>{@code IInAppBillingService.aidl} is an Android Interface Definition
+<p>The {@code IInAppBillingService.aidl} is an Android Interface Definition
 Language (AIDL) file that defines the interface to the In-app Billing Version
-3 service. You will use this interface to make billing requests by invoking IPC
+3 service. You can use this interface to make billing requests by invoking IPC
 method calls.</p>
-<p>To get the AIDL file:</p>
+
+<p>Complete these steps to get the AIDL file:</p>
 <ol>
 <li>Open the <a href="{@docRoot}tools/help/sdk-manager.html">Android SDK Manager</a>.</li>
 <li>In the SDK Manager, expand the {@code Extras} section.</li>
 <li>Select <strong>Google Play Billing Library</strong>.</li>
 <li>Click <strong>Install packages</strong> to complete the download.</li>
 </ol>
-<p>The {@code IInAppBillingService.aidl} file will be installed to {@code <sdk>/extras/google/play_billing/}.</p>
+<p>The {@code IInAppBillingService.aidl} file will be installed to {@code &lt;sdk&gt;/extras/google/play_billing/}.</p>
 
-<p>To add the AIDL to your project:</p>
+<p>Complete these steps to add the AIDL to your project:</p>
 
 <ol>
-  <li>First, download the Google Play Billing Library to your Android project:
+  <li>Download the Google Play Billing Library to your Android project:
       <ol type="a">
       <li>Select <strong>Tools > Android > SDK Manager</strong>.</li>
       <li>Under <strong>Appearance & Behavior > System Settings > Android SDK</strong>,
           select the <em>SDK Tools</em> tab to select and download <em>Google Play Billing
           Library</em>.</li></ol>
 
-  <li>Next, copy the {@code IInAppBillingService.aidl} file to your project.
+  <li>Copy the {@code IInAppBillingService.aidl} file to your project.
     <ul>
-      <li>If you are using Android Studio:
+      <li>If you are using Android Studio, complete these steps to copy the file:
         <ol type="a">
           <li>Navigate to {@code src/main} in the Project tool window.</li>
 
-          <li>Select <strong>File > New > Directory</strong> and enter {@code aidl} in the
-          <em>New Directory</em> window, then select <strong>OK</strong>.
+          <li>Select <strong>File > New > Directory</strong>, enter {@code aidl} in the
+          <em>New Directory</em> window, and select <strong>OK</strong>.
 
-          <li>Select <strong>File > New > Package</strong> and enter
-          {@code com.android.vending.billing} in the <em>New Package</em> window, then select
+          <li>Select <strong>File > New > Package</strong>, enter
+          {@code com.android.vending.billing} in the <em>New Package</em> window, and select
           <strong>OK</strong>.</li>
 
           <li>Using your operating system file explorer, navigate to
-          {@code <sdk>/extras/google/play_billing/}, copy the
+          {@code &lt;sdk&gt;/extras/google/play_billing/}, copy the
           {@code IInAppBillingService.aidl} file, and paste it into the
           {@code com.android.vending.billing} package in your project.
           </li>
         </ol>
       </li>
 
-      <li>If you are developing in a non-Android Studio environment: Create the
-      following directory {@code /src/com/android/vending/billing} and copy the
-      {@code IInAppBillingService.aidl} file into this directory. Put the AIDL
-      file into your project and use the Gradle tool to build your project so that
-      the <code>IInAppBillingService.java</code> file gets generated.
+      <li>If you are developing in a non-Android Studio environment, create the
+      following directory: {@code /src/com/android/vending/billing}. Copy the
+      {@code IInAppBillingService.aidl} file into this directory. Place the AIDL
+      file in your project and use the Gradle tool to build your project so that
+      the <code>IInAppBillingService.java</code> file is generated.
       </li>
     </ul>
   </li>
@@ -137,16 +137,16 @@
   </li>
 </ol>
 
-<h2 id="billing-permission">Updating Your App's Manifest</h2>
+<h2 id="billing-permission">Updating your app's manifest</h2>
 
 <p>
   In-app billing relies on the Google Play application, which handles all
-  communication between your application and the Google Play server. To use the
+  of the communication between your application and the Google Play server. To use the
   Google Play application, your application must request the proper permission.
   You can do this by adding the {@code com.android.vending.BILLING} permission
   to your AndroidManifest.xml file. If your application does not declare the
   In-app Billing permission, but attempts to send billing requests, Google Play
-  will refuse the requests and respond with an error.
+  refuses the requests and responds with an error.
 </p>
 
 <p>
@@ -182,7 +182,7 @@
   onServiceDisconnected} and {@link
   android.content.ServiceConnection#onServiceConnected onServiceConnected}
   methods to get a reference to the {@code IInAppBillingService} instance after
-  a connection has been established.
+  a connection is established.
 </p>
 
 <pre>
@@ -208,20 +208,25 @@
   bindService} method. Pass the method an {@link android.content.Intent} that
   references the In-app Billing service and an instance of the {@link
   android.content.ServiceConnection} that you created, and explicitly set the
-  Intent's target package name to <code>com.android.vending</code> — the
+  Intent's target package name to <code>com.android.vending</code>&mdash;the
   package name of Google Play app.
 </p>
 
 <p class="caution">
   <strong>Caution:</strong> To protect the security of billing transactions,
-  always make sure to explicitly set the intent's target package name to
+  always explicitly set the intent's target package name to
   <code>com.android.vending</code>, using {@link
-  android.content.Intent#setPackage(java.lang.String) setPackage()} as shown in
-  the example below. Setting the package name explicitly ensures that
+  android.content.Intent#setPackage(java.lang.String) setPackage()}.
+  Setting the package name explicitly ensures that
   <em>only</em> the Google Play app can handle billing requests from your app,
   preventing other apps from intercepting those requests.
 </p>
 
+<p>
+  The following code sample demonstrates how to set the intent's target package
+  to protect the security of transactions:
+</p>
+
 <pre>&#64;Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
@@ -233,6 +238,13 @@
 }
 </pre>
 
+<p class="caution"><strong>Caution</strong>: To ensure that your app is secure, always use an
+explicit intent when starting a {@link android.app.Service} and do not declare intent filters for
+your services. Using an implicit intent to start a service is a security hazard because you cannot
+be certain of the service that will respond to the intent, and the user cannot see which service
+starts. Beginning with Android 5.0 (API level 21), the system throws an exception if you call
+{@link android.content.Context#bindService bindService()} with an implicit intent.</p>
+
 <p>
   You can now use the mService reference to communicate with the Google Play
   service.
@@ -242,10 +254,14 @@
   <strong>Important:</strong> Remember to unbind from the In-app Billing
   service when you are done with your {@link android.app.Activity}. If you
   don’t unbind, the open service connection could cause your device’s
-  performance to degrade. This example shows how to perform the unbind
+  performance to degrade.
+</p>
+
+<p>
+  This example shows how to perform the unbind
   operation on a service connection to In-app Billing called {@code
   mServiceConn} by overriding the activity’s {@link
-  android.app.Activity#onDestroy onDestroy} method.
+  android.app.Activity#onDestroy onDestroy} method:
 </p>
 
 <pre>
@@ -264,29 +280,29 @@
   "{@docRoot}training/in-app-billing/preparing-iab-app.html">Selling In-app
   Products</a> training class and associated sample.
 </p>
-<h2 id="billing-requests">Making In-app Billing Requests</h2>
+<h2 id="billing-requests">Making In-app Billing requests</h2>
 <p>
-  Once your application is connected to Google Play, you can initiate purchase
+  After your application is connected to Google Play, you can initiate purchase
   requests for in-app products. Google Play provides a checkout interface for
-  users to enter their payment method, so your application does not need to
+  users to enter their payment method, so your application doesn't need to
   handle payment transactions directly. When an item is purchased, Google Play
   recognizes that the user has ownership of that item and prevents the user
   from purchasing another item with the same product ID until it is consumed.
-  You can control how the item is consumed in your application, and notify
+  You can control how the item is consumed in your application and notify
   Google Play to make the item available for purchase again. You can also query
-  Google Play to quickly retrieve the list of purchases that were made by the
-  user. This is useful, for example, when you want to restore the user's
+  Google Play to quickly retrieve the list of purchases that the
+  user made. This is useful, for example, when you want to restore the user's
   purchases when your user launches your app.
 </p>
 
-<h3 id="QueryDetails">Querying for Items Available for Purchase</h3>
+<h3 id="QueryDetails">Querying for items available for purchase</h3>
 
 <p>
   In your application, you can query the item details from Google Play using
   the In-app Billing Version 3 API. To pass a request to the In-app Billing
-  service, first create a {@link android.os.Bundle} that contains a String
+  service, create a {@link android.os.Bundle} that contains a String
   {@link java.util.ArrayList} of product IDs with key "ITEM_ID_LIST", where
-  each string is a product ID for an purchasable item.
+  each string is a product ID for an purchasable item. Here is an example:
 </p>
 
 <pre>
@@ -299,9 +315,9 @@
 
 <p>
   To retrieve this information from Google Play, call the {@code getSkuDetails}
-  method on the In-app Billing Version 3 API, and pass the method the In-app
+  method on the In-app Billing Version 3 API and pass the In-app
   Billing API version (“3”), the package name of your calling app, the purchase
-  type (“inapp”), and the {@link android.os.Bundle} that you created.
+  type (“inapp”), and the {@link android.os.Bundle} that you created, into the method:
 </p>
 
 <pre>
@@ -310,35 +326,35 @@
 </pre>
 
 <p>
-  If the request is successful, the returned {@link android.os.Bundle}has a
+  If the request is successful, the returned {@link android.os.Bundle} has a
   response code of {@code BILLING_RESPONSE_RESULT_OK} (0).
 </p>
 
 <p class="note">
-  <strong>Warning:</strong> Do not call the {@code getSkuDetails} method on the
-  main thread. Calling this method triggers a network request which could block
+  <strong>Warning:</strong> Don't call the {@code getSkuDetails} method on the
+  main thread. Calling this method triggers a network request that could block
   your main thread. Instead, create a separate thread and call the {@code
-  getSkuDetails} method from inside that thread.
+  getSkuDetails} method from inside of that thread.
 </p>
 
 <p>
-  To see all the possible response codes from Google Play, see <a href=
+  To view all of the possible response codes from Google Play, see <a href=
   "{@docRoot}google/play/billing/billing_reference.html#billing-codes">In-app
   Billing Reference</a>.
 </p>
 
 <p>
   The query results are stored in a String ArrayList with key {@code
-  DETAILS_LIST}. The purchase information is stored in the String in JSON
-  format. To see the types of product detail information that are returned, see
+  DETAILS_LIST}. The purchase information is stored within the String in JSON
+  format. To view the types of product detail information that are returned, see
   <a href=
   "{@docRoot}google/play/billing/billing_reference.html#getSkuDetails">In-app
   Billing Reference</a>.
 </p>
 
 <p>
-  In this example, you are retrieving the prices for your in-app items from the
-  skuDetails {@link android.os.Bundle} returned from the previous code snippet.
+  In this example shows how to retrieve the prices for your in-app items from the
+  skuDetails {@link android.os.Bundle} that is returned from the previous code snippet:
 </p>
 
 <pre>
@@ -357,15 +373,15 @@
 }
 </pre>
 
-<h3 id="Purchase">Purchasing an Item</h3>
+<h3 id="Purchase">Purchasing an item</h3>
 <p>
   To start a purchase request from your app, call the {@code getBuyIntent}
-  method on the In-app Billing service. Pass in to the method the In-app
+  method on the In-app Billing service. Pass the In-app
   Billing API version (“3”), the package name of your calling app, the product
   ID for the item to purchase, the purchase type (“inapp” or "subs"), and a
-  {@code developerPayload} String. The {@code developerPayload} String is used
+  {@code developerPayload} String into the method. The {@code developerPayload} String is used
   to specify any additional arguments that you want Google Play to send back
-  along with the purchase information.
+  along with the purchase information. Here is an example:
 </p>
 
 <pre>
@@ -377,10 +393,13 @@
   If the request is successful, the returned {@link android.os.Bundle} has a
   response code of {@code BILLING_RESPONSE_RESULT_OK} (0) and a {@link
   android.app.PendingIntent} that you can use to start the purchase flow. To
-  see all the possible response codes from Google Play, see <a href=
+  view all of the possible response codes from Google Play, see <a href=
   "{@docRoot}google/play/billing/billing_reference.html#billing-codes">In-app
-  Billing Reference</a>. Next, extract a {@link android.app.PendingIntent} from
-  the response {@link android.os.Bundle} with key {@code BUY_INTENT}.
+  Billing Reference</a>.
+
+<p>
+  The next step is to extract a {@link android.app.PendingIntent} from
+  the response {@link android.os.Bundle} with key {@code BUY_INTENT}, as shown here:
 </p>
 
 <pre>
@@ -390,8 +409,8 @@
 <p>
   To complete the purchase transaction, call the {@link
   android.app.Activity#startIntentSenderForResult startIntentSenderForResult}
-  method and use the {@link android.app.PendingIntent} that you created. In
-  this example, you are using an arbitrary value of 1001 for the request code.
+  method and use the {@link android.app.PendingIntent} that you created. This
+  example uses an arbitrary value of 1001 for the request code:
 </p>
 
 <pre>
@@ -404,9 +423,9 @@
   Google Play sends a response to your {@link android.app.PendingIntent} to the
   {@link android.app.Activity#onActivityResult onActivityResult} method of your
   application. The {@link android.app.Activity#onActivityResult
-  onActivityResult} method will have a result code of {@code
-  Activity.RESULT_OK} (1) or {@code Activity.RESULT_CANCELED} (0). To see the
-  types of order information that is returned in the response {@link
+  onActivityResult} method has a result code of {@code
+  Activity.RESULT_OK} (1) or {@code Activity.RESULT_CANCELED} (0). To view the
+  types of order information that are returned in the response {@link
   android.content.Intent}, see <a href=
   "{@docRoot}google/play/billing/billing_reference.html#getBuyIntent">In-app
   Billing Reference</a>.
@@ -415,7 +434,7 @@
 <p>
   The purchase data for the order is a String in JSON format that is mapped to
   the {@code INAPP_PURCHASE_DATA} key in the response {@link
-  android.content.Intent}, for example:
+  android.content.Intent}. Here is an example:
 </p>
 
 <pre>
@@ -436,13 +455,13 @@
   long. Pass this entire token to other methods, such as when you consume the
   purchase, as described in <a href=
   "{@docRoot}training/in-app-billing/purchase-iab-products.html#Consume">Consume
-  a Purchase</a>. Do not abbreviate or truncate this token; you must save and
+  a Purchase</a>. Don't abbreviate or truncate this token; you must save and
   return the entire token.
 </p>
 
 <p>
-  Continuing from the previous example, you get the response code, purchase
-  data, and signature from the response {@link android.content.Intent}.
+  Continuing from the previous example, you receive the response code, purchase
+  data, and signature from the response {@link android.content.Intent}:
 </p>
 
 <pre>
@@ -472,23 +491,23 @@
 <p class="note">
   <strong>Security Recommendation:</strong> When you send a purchase request,
   create a String token that uniquely identifies this purchase request and
-  include this token in the {@code developerPayload}.You can use a randomly
-  generated string as the token. When you receive the purchase response from
-  Google Play, make sure to check the returned data signature, the {@code
+  include this token in the {@code developerPayload}. You can use a randomly-generated
+  string as the token. When you receive the purchase response from
+  Google Play, ensure that you check the returned data signature, the {@code
   orderId}, and the {@code developerPayload} String. For added security, you
-  should perform the checking on your own secure server. Make sure to verify
+  should perform the checking on your own secure server. Verify
   that the {@code orderId} is a unique value that you have not previously
-  processed, and the {@code developerPayload} String matches the token that you
+  processed and that the {@code developerPayload} String matches the token that you
   sent previously with the purchase request.
 </p>
 
-<h3 id="QueryPurchases">Querying for Purchased Items</h3>
+<h3 id="QueryPurchases">Querying for purchased items</h3>
 
 <p>
-  To retrieve information about purchases made by a user from your app, call
+  To retrieve information about purchases that are made by a user from your app, call
   the {@code getPurchases} method on the In-app Billing Version 3 service. Pass
-  in to the method the In-app Billing API version (“3”), the package name of
-  your calling app, and the purchase type (“inapp” or "subs").
+  the In-app Billing API version (“3”), the package name of
+  your calling app, and the purchase type (“inapp” or "subs") into the method. Here is an example:
 </p>
 
 <pre>
@@ -507,18 +526,18 @@
   To improve performance, the In-app Billing service returns only up to 700
   products that are owned by the user when {@code getPurchase} is first called.
   If the user owns a large number of products, Google Play includes a String
-  token mapped to the key {@code INAPP_CONTINUATION_TOKEN} in the response
+  token that is mapped to the key {@code INAPP_CONTINUATION_TOKEN} in the response
   {@link android.os.Bundle} to indicate that more products can be retrieved.
-  Your application can then make a subsequent {@code getPurchases} call, and
+  Your application can then make a subsequent {@code getPurchases} call and
   pass in this token as an argument. Google Play continues to return a
   continuation token in the response {@link android.os.Bundle} until all
-  products that are owned by the user has been sent to your app.
+  of the products that are owned by the user are sent to your app.
 </p>
 
-<p>For more information about the data returned by {@code getPurchases}, see
+<p>For more information about the data that is returned by {@code getPurchases}, see
   <a href="{@docRoot}google/play/billing/billing_reference.html#getPurchases">
   In-app Billing Reference</a>. The following example shows how you can
-  retrieve this data from the response.
+  retrieve this data from the response:
 </p>
 
 <pre>
@@ -548,26 +567,26 @@
 </pre>
 
 
-<h3 id="Consume">Consuming a Purchase</h3>
+<h3 id="Consume">Consuming a purchase</h3>
 
 <p>
   You can use the In-app Billing Version 3 API to track the ownership of
   purchased in-app products in Google Play. Once an in-app product is
-  purchased, it is considered to be "owned" and cannot be purchased from Google
+  purchased, it is considered to be <em>owned</em> and cannot be purchased from Google
   Play. You must send a consumption request for the in-app product before
   Google Play makes it available for purchase again.
 </p>
 
-<p class="caution">
+<p class="note">
   <strong>Important</strong>: Managed in-app products are consumable, but
   subscriptions are not.
 </p>
 
 <p>
-  How you use the consumption mechanism in your app is up to you. Typically,
-  you would implement consumption for in-app products with temporary benefits
+  The way that you use the consumption mechanism in your app is up to you. Typically,
+  you implement consumption for in-app products with temporary benefits
   that users may want to purchase multiple times (for example, in-game currency
-  or equipment). You would typically not want to implement consumption for
+  or equipment). You typically don't want to implement consumption for
   in-app products that are purchased once and provide a permanent effect (for
   example, a premium upgrade).
 </p>
@@ -576,21 +595,21 @@
   To record a purchase consumption, send the {@code consumePurchase} method to
   the In-app Billing service and pass in the {@code purchaseToken} String value
   that identifies the purchase to be removed. The {@code purchaseToken} is part
-  of the data returned in the {@code INAPP_PURCHASE_DATA} String by the Google
-  Play service following a successful purchase request. In this example, you
-  are recording the consumption of a product that is identified with the {@code
-  purchaseToken} in the {@code token} variable.
+  of the data that is returned in the {@code INAPP_PURCHASE_DATA} String by the Google
+  Play service following a successful purchase request. This example
+  records the consumption of a product that is identified with the {@code
+  purchaseToken} in the {@code token} variable:
 </p>
 
 <pre>
 int response = mService.consumePurchase(3, getPackageName(), token);
 </pre>
 
-<p class="note">
-  <strong>Warning:</strong> Do not call the {@code consumePurchase} method on
-  the main thread. Calling this method triggers a network request which could
+<p class="caution">
+  <strong>Warning:</strong> Don't call the {@code consumePurchase} method on
+  the main thread. Calling this method triggers a network request that could
   block your main thread. Instead, create a separate thread and call the {@code
-  consumePurchase} method from inside that thread.
+  consumePurchase} method from inside of that thread.
 </p>
 
 <p>
@@ -600,20 +619,20 @@
   purchased.
 </p>
 
-<p class="note">
-  <strong>Security Recommendation:</strong> You must send a consumption request
+<p class="caution">
+  <strong>Security Recommendation:</strong> Send a consumption request
   before provisioning the benefit of the consumable in-app purchase to the
-  user. Make sure that you have received a successful consumption response from
+  user. Ensure that you receive a successful consumption response from
   Google Play before you provision the item.
 </p>
 
-<h3 id="Subs">Implementing Subscriptions</h3>
+<h3 id="Subs">Implementing subscriptions</h3>
 
 <p>Launching a purchase flow for a subscription is similar to launching the
 purchase flow for a product, with the exception that the product type must be set
 to "subs". The purchase result is delivered to your Activity's
 {@link android.app.Activity#onActivityResult onActivityResult} method, exactly
-as in the case of in-app products.</p>
+as in the case of in-app products. Here is an example:</p>
 
 <pre>
 Bundle bundle = mService.getBuyIntent(3, "com.example.myapp",
@@ -629,18 +648,18 @@
 </pre>
 
 <p>To query for active subscriptions, use the {@code getPurchases} method, again
-with the product type parameter set to "subs".</p>
+with the product type parameter set to "subs":</p>
 
 <pre>
 Bundle activeSubs = mService.getPurchases(3, "com.example.myapp",
                    "subs", continueToken);
 </pre>
 
-<p>The call returns a {@code Bundle} with all the active subscriptions owned by
-the user. Once a subscription expires without renewal, it will no longer appear
+<p>The call returns a {@code Bundle} with all of the active subscriptions that are owned by
+the user. When a subscription expires without renewal, it no longer appears
 in the returned {@code Bundle}.</p>
 
-<h2 id="billing-security">Securing Your Application</h2>
+<h2 id="billing-security">Securing your application</h2>
 
 <p>To help ensure the integrity of the transaction information that is sent to
 your application, Google Play signs the JSON string that contains the response
@@ -648,21 +667,21 @@
 with your application in the Developer Console to create this signature. The
 Developer Console generates an RSA key pair for each application.<p>
 
-<p class="note"><strong>Note:</strong>To find the public key portion of this key
-pair, open your application's details in the Developer Console, then click on
-<strong>Services &amp; APIs</strong>, and look at the field titled
+<p class="note"><strong>Note:</strong> To find the public key portion of this key
+pair, open your application's details in the Developer Console, click
+<strong>Services &amp; APIs</strong>, and review the field titled
 <strong>Your License Key for This Application</strong>.</p>
 
-<p>The Base64-encoded RSA public key generated by Google Play is in binary
+<p>The Base64-encoded RSA public key that is generated by Google Play is in binary
 encoded, X.509 subjectPublicKeyInfo DER SEQUENCE format. It is the same public
 key that is used with Google Play licensing.</p>
 
-<p>When your application receives this signed response you can
+<p>When your application receives this signed response, you can
 use the public key portion of your RSA key pair to verify the signature.
-By performing signature verification you can detect responses that have
+By performing signature verification, you can detect any responses that have
 been tampered with or that have been spoofed. You can perform this signature
 verification step in your application; however, if your application connects
-to a secure remote server then we recommend that you perform the signature
+to a secure remote server, Google recommends that you perform the signature
 verification on that server.</p>
 
 <p>For more information about best practices for security and design, see <a
diff --git a/docs/html/guide/components/bound-services.jd b/docs/html/guide/components/bound-services.jd
index f71ba87..2ee2061 100644
--- a/docs/html/guide/components/bound-services.jd
+++ b/docs/html/guide/components/bound-services.jd
@@ -8,19 +8,19 @@
 <ol id="qv">
 <h2>In this document</h2>
 <ol>
-  <li><a href="#Basics">The Basics</a></li>
-  <li><a href="#Creating">Creating a Bound Service</a>
+  <li><a href="#Basics">The basics</a></li>
+  <li><a href="#Creating">Creating a bound service</a>
     <ol>
       <li><a href="#Binder">Extending the Binder class</a></li>
       <li><a href="#Messenger">Using a Messenger</a></li>
     </ol>
   </li>
-  <li><a href="#Binding">Binding to a Service</a>
+  <li><a href="#Binding">Binding to a service</a>
     <ol>
       <li><a href="#Additional_Notes">Additional notes</a></li>
     </ol>
   </li>
-  <li><a href="#Lifecycle">Managing the Lifecycle of a Bound Service</a></li>
+  <li><a href="#Lifecycle">Managing the lifecycle of a bound service</a></li>
 </ol>
 
 <h2>Key classes</h2>
@@ -32,9 +32,13 @@
 
 <h2>Samples</h2>
 <ol>
-  <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">{@code
+  <li><a
+ href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">
+  {@code
       RemoteService}</a></li>
-  <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">{@code
+  <li><a
+ href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">
+ {@code
       LocalService}</a></li>
 </ol>
 
@@ -45,19 +49,23 @@
 </div>
 
 
-<p>A bound service is the server in a client-server interface. A bound service allows components
-(such as activities) to bind to the service, send requests, receive responses, and even perform
+<p>A bound service is the server in a client-server interface. It allows components
+(such as activities) to bind to the service, send requests, receive responses, and perform
 interprocess communication (IPC). A bound service typically lives only while it serves another
 application component and does not run in the background indefinitely.</p>
 
-<p>This document shows you how to create a bound service, including how to bind
-to the service from other application components. However, you should also refer to the <a
-href="{@docRoot}guide/components/services.html">Services</a> document for additional
-information about services in general, such as how to deliver notifications from a service, set
-the service to run in the foreground, and more.</p>
+<p class="note"><strong>Note:</strong> If your app targets Android 5.0 (API level 21) or later,
+it's recommended that you use the {@link android.app.job.JobScheduler} to execute background
+ services. For more information about {@link android.app.job.JobScheduler}, see its
+ {@link android.app.job.JobScheduler API-reference documentation}.</p>
 
+<p>This document describes how to create a bound service, including how to bind
+to the service from other application components. For additional information about services in
+ general, such as how to deliver notifications from a service and set the service to run
+ in the foreground, refer to the <a href="{@docRoot}guide/components/services.html">
+ Services</a> document.</p>
 
-<h2 id="Basics">The Basics</h2>
+<h2 id="Basics">The basics</h2>
 
 <p>A bound service is an implementation of the {@link android.app.Service} class that allows
 other applications to bind to it and interact with it. To provide binding for a
@@ -67,57 +75,61 @@
 
 <div class="sidebox-wrapper">
 <div class="sidebox">
-  <h3>Binding to a Started Service</h3>
+  <h3>Binding to a started service</h3>
 
 <p>As discussed in the <a href="{@docRoot}guide/components/services.html">Services</a>
-document, you can create a service that is both started and bound. That is, the service can be
-started by calling {@link android.content.Context#startService startService()}, which allows the
-service to run indefinitely, and also allow a client to bind to the service by calling {@link
+document, you can create a service that is both started and bound. That is, you can start a
+ service by calling {@link android.content.Context#startService startService()}, which allows the
+service to run indefinitely, and you can also allow a client to bind to the service by
+ calling {@link
 android.content.Context#bindService bindService()}.
   <p>If you do allow your service to be started and bound, then when the service has been
-started, the system does <em>not</em> destroy the service when all clients unbind. Instead, you must
-explicitly stop the service, by calling {@link android.app.Service#stopSelf stopSelf()} or {@link
+started, the system does <em>not</em> destroy the service when all clients unbind.
+ Instead, you must
+explicitly stop the service by calling {@link android.app.Service#stopSelf stopSelf()} or {@link
 android.content.Context#stopService stopService()}.</p>
 
-<p>Although you should usually implement either {@link android.app.Service#onBind onBind()}
-<em>or</em> {@link android.app.Service#onStartCommand onStartCommand()}, it's sometimes necessary to
+<p>Although you usually implement either {@link android.app.Service#onBind onBind()}
+<em>or</em> {@link android.app.Service#onStartCommand onStartCommand()}, it's sometimes
+ necessary to
 implement both. For example, a music player might find it useful to allow its service to run
 indefinitely and also provide binding. This way, an activity can start the service to play some
 music and the music continues to play even if the user leaves the application. Then, when the user
-returns to the application, the activity can bind to the service to regain control of playback.</p>
+returns to the application, the activity can bind to the service to regain control of
+ playback.</p>
 
-<p>Be sure to read the section about <a href="#Lifecycle">Managing the Lifecycle of a Bound
-Service</a>, for more information about the service lifecycle when adding binding to a
-started service.</p>
+<p>For more information about the service lifecycle when adding binding to a started service,
+ see <a href="#Lifecycle">Managing the lifecycle of a bound Service</a>.</p>
 </div>
 </div>
 
-<p>A client can bind to the service by calling {@link android.content.Context#bindService
+<p>A client can bind to a service by calling {@link android.content.Context#bindService
 bindService()}. When it does, it must provide an implementation of {@link
 android.content.ServiceConnection}, which monitors the connection with the service. The {@link
-android.content.Context#bindService bindService()} method returns immediately without a value, but
+android.content.Context#bindService bindService()} method returns immediately without a
+ value, but
 when the Android system creates the connection between the
 client and service, it calls {@link
 android.content.ServiceConnection#onServiceConnected onServiceConnected()} on the {@link
 android.content.ServiceConnection}, to deliver the {@link android.os.IBinder} that
 the client can use to communicate with the service.</p>
 
-<p>Multiple clients can connect to the service at once. However, the system calls your service's
-{@link android.app.Service#onBind onBind()} method to retrieve the {@link android.os.IBinder} only
+<p>Multiple clients can connect to a service simultaneously. However, the system calls your service's
+{@link android.app.Service#onBind onBind()} method to retrieve the
+ {@link android.os.IBinder} only
 when the first client binds. The system then delivers the same {@link android.os.IBinder} to any
-additional clients that bind, without calling {@link android.app.Service#onBind onBind()} again.</p>
+additional clients that bind, without calling {@link android.app.Service#onBind onBind()}
+ again.</p>
 
-<p>When the last client unbinds from the service, the system destroys the service (unless the
-service was also started by {@link android.content.Context#startService startService()}).</p>
+<p>When the last client unbinds from the service, the system destroys the service, unless the
+service was also started by {@link android.content.Context#startService startService()}.</p>
 
-<p>When you implement your bound service, the most important part is defining the interface
-that your {@link android.app.Service#onBind onBind()} callback method returns. There are a few
-different ways you can define your service's {@link android.os.IBinder} interface and the following
-section discusses each technique.</p>
+<p>The most important part of your bound service implementation is defining the interface
+that your {@link android.app.Service#onBind onBind()} callback method returns. The following
+section discusses several different ways that you can define your service's
+ {@link android.os.IBinder} interface.</p>
 
-
-
-<h2 id="Creating">Creating a Bound Service</h2>
+<h2 id="Creating">Creating a bound service</h2>
 
 <p>When creating a service that provides binding, you must provide an {@link android.os.IBinder}
 that provides the programming interface that clients can use to interact with the service. There
@@ -125,12 +137,14 @@
 
 <dl>
   <dt><a href="#Binder">Extending the Binder class</a></dt>
-  <dd>If your service is private to your own application and runs in the same process as the client
-(which is common), you should create your interface by extending the {@link android.os.Binder} class
+  <dd>If your service is private to your own application and runs in the same process
+  as the client
+(which is common), you should create your interface by extending the {@link android.os.Binder}
+ class
 and returning an instance of it from
 {@link android.app.Service#onBind onBind()}. The client receives the {@link android.os.Binder} and
 can use it to directly access public methods available in either the {@link android.os.Binder}
-implementation or even the {@link android.app.Service}.
+implementation or the {@link android.app.Service}.
   <p>This is the preferred technique when your service is merely a background worker for your own
 application. The only reason you would not create your interface this way is because
 your service is used by other applications or across separate processes.</dd>
@@ -143,20 +157,20 @@
 is the basis for a {@link android.os.Messenger} that can then share an {@link android.os.IBinder}
 with the client, allowing the client to send commands to the service using {@link
 android.os.Message} objects. Additionally, the client can define a {@link android.os.Messenger} of
-its own so the service can send messages back.
+its own, so the service can send messages back.
   <p>This is the simplest way to perform interprocess communication (IPC), because the {@link
 android.os.Messenger} queues all requests into a single thread so that you don't have to design
 your service to be thread-safe.</p>
   </dd>
 
-  <dt>Using AIDL</dt>
-  <dd>AIDL (Android Interface Definition Language) performs all the work to decompose objects into
-primitives that the operating system can understand and marshall them across processes to perform
+  <dt><a href="{@docRoot}guide/components/aidl.html">Using AIDL</a></dt>
+  <dd>Android Interface Definition Language (AIDL) decomposes objects into
+primitives that the operating system can understand and marshals them across processes to perform
 IPC. The previous technique, using a {@link android.os.Messenger}, is actually based on AIDL as
 its underlying structure. As mentioned above, the {@link android.os.Messenger} creates a queue of
 all the client requests in a single thread, so the service receives requests one at a time. If,
 however, you want your service to handle multiple requests simultaneously, then you can use AIDL
-directly. In this case, your service must be capable of multi-threading and be built thread-safe.
+directly. In this case, your service must be thread-safe and capable of multi-threading.
   <p>To use AIDL directly, you must
 create an {@code .aidl} file that defines the programming interface. The Android SDK tools use
 this file to generate an abstract class that implements the interface and handles IPC, which you
@@ -164,19 +178,18 @@
   </dd>
 </dl>
 
-  <p class="note"><strong>Note:</strong> Most applications <strong>should not</strong> use AIDL to
+  <p class="note"><strong>Note:</strong> Most applications <em>shouldn't</em> use AIDL to
 create a bound service, because it may require multithreading capabilities and
-can result in a more complicated implementation. As such, AIDL is not suitable for most applications
+can result in a more complicated implementation. As such, AIDL is not suitable for
+ most applications
 and this document does not discuss how to use it for your service. If you're certain that you need
 to use AIDL directly, see the <a href="{@docRoot}guide/components/aidl.html">AIDL</a>
 document.</p>
 
-
-
-
 <h3 id="Binder">Extending the Binder class</h3>
 
-<p>If your service is used only by the local application and does not need to work across processes,
+<p>If your service is used only by the local application and does not need to
+ work across processes,
 then you can implement your own {@link android.os.Binder} class that provides your client direct
 access to public methods in the service.</p>
 
@@ -187,13 +200,14 @@
 
 <p>Here's how to set it up:</p>
 <ol>
-  <li>In your service, create an instance of {@link android.os.Binder} that either:
+  <li>In your service, create an instance of {@link android.os.Binder} that does
+  one of the following:
     <ul>
-      <li>contains public methods that the client can call</li>
-      <li>returns the current {@link android.app.Service} instance, which has public methods the
-client can call</li>
-      <li>or, returns an instance of another class hosted by the service with public methods the
-client can call</li>
+      <li>Contains public methods that the client can call.</li>
+      <li>Returns the current {@link android.app.Service} instance, which has public methods the
+client can call.</li>
+      <li>Returns an instance of another class hosted by the service with public methods the
+client can call.</li>
     </ul>
   <li>Return this instance of {@link android.os.Binder} from the {@link
 android.app.Service#onBind onBind()} callback method.</li>
@@ -202,12 +216,13 @@
 make calls to the bound service using the methods provided.</li>
 </ol>
 
-<p class="note"><strong>Note:</strong> The reason the service and client must be in the same
-application is so the client can cast the returned object and properly call its APIs. The service
+<p class="note"><strong>Note:</strong> The service and client must be in the same
+application so that the client can cast the returned object and properly call its APIs.
+ The service
 and client must also be in the same process, because this technique does not perform any
-marshalling across processes.</p>
+marshaling across processes.</p>
 
-<p>For example, here's a service that provides clients access to methods in the service through
+<p>For example, here's a service that provides clients with access to methods in the service through
 a {@link android.os.Binder} implementation:</p>
 
 <pre>
@@ -316,32 +331,30 @@
 <p class="note"><strong>Note:</strong> In the example above, the
 {@link android.app.Activity#onStop onStop()} method unbinds the client from the service. Clients
 should unbind from services at appropriate times, as discussed in
-<a href="#Additional_Notes">Additional Notes</a>.
+<a href="#Additional_Notes">Additional notes</a>.
 </p>
 
 <p>For more sample code, see the <a
-href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">{@code
+href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">
+{@code
 LocalService.java}</a> class and the <a
-href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceActivities.html">{@code
+href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceActivities.html">
+{@code
 LocalServiceActivities.java}</a> class in <a
 href="{@docRoot}resources/samples/ApiDemos/index.html">ApiDemos</a>.</p>
 
-
-
-
-
 <h3 id="Messenger">Using a Messenger</h3>
 
 <div class="sidebox-wrapper">
 <div class="sidebox">
   <h4>Compared to AIDL</h4>
   <p>When you need to perform IPC, using a {@link android.os.Messenger} for your interface is
-simpler than implementing it with AIDL, because {@link android.os.Messenger} queues
-all calls to the service, whereas, a pure AIDL interface sends simultaneous requests to the
+simpler than using AIDL, because {@link android.os.Messenger} queues
+all calls to the service. A pure AIDL interface sends simultaneous requests to the
 service, which must then handle multi-threading.</p>
   <p>For most applications, the service doesn't need to perform multi-threading, so using a {@link
 android.os.Messenger} allows the service to handle one call at a time. If it's important
-that your service be multi-threaded, then you should use <a
+that your service be multi-threaded, use <a
 href="{@docRoot}guide/components/aidl.html">AIDL</a> to define your interface.</p>
 </div>
 </div>
@@ -352,10 +365,11 @@
 
 <p>Here's a summary of how to use a {@link android.os.Messenger}:</p>
 
-<ul>
+<ol>
   <li>The service implements a {@link android.os.Handler} that receives a callback for each
 call from a client.</li>
-  <li>The {@link android.os.Handler} is used to create a {@link android.os.Messenger} object
+  <li>The service uses the {@link android.os.Handler} to create a {@link android.os.Messenger}
+  object
 (which is a reference to the {@link android.os.Handler}).</li>
   <li>The {@link android.os.Messenger} creates an {@link android.os.IBinder} that the service
 returns to clients from {@link android.app.Service#onBind onBind()}.</li>
@@ -365,11 +379,12 @@
   <li>The service receives each {@link android.os.Message} in its {@link
 android.os.Handler}&mdash;specifically, in the {@link android.os.Handler#handleMessage
 handleMessage()} method.</li>
-</ul>
+</ol>
 
 
-<p>In this way, there are no "methods" for the client to call on the service. Instead, the
-client delivers "messages" ({@link android.os.Message} objects) that the service receives in
+<p>In this way, there are no <em>methods</em> for the client to call on the service. Instead, the
+client delivers <em>messages</em> ({@link android.os.Message} objects) that the service
+ receives in
 its {@link android.os.Handler}.</p>
 
 <p>Here's a simple example service that uses a {@link android.os.Messenger} interface:</p>
@@ -488,41 +503,42 @@
 }
 </pre>
 
-<p>Notice that this example does not show how the service can respond to the client. If you want the
-service to respond, then you need to also create a {@link android.os.Messenger} in the client. Then
-when the client receives the {@link android.content.ServiceConnection#onServiceConnected
+<p>Notice that this example does not show how the service can respond to the client.
+ If you want the
+service to respond, you need to also create a {@link android.os.Messenger} in the client.
+When the client receives the {@link android.content.ServiceConnection#onServiceConnected
 onServiceConnected()} callback, it sends a {@link android.os.Message} to the service that includes
 the client's {@link android.os.Messenger} in the {@link android.os.Message#replyTo} parameter
 of the {@link android.os.Messenger#send send()} method.</p>
 
 <p>You can see an example of how to provide two-way messaging in the <a
-href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.html">{@code
+href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.html">
+{@code
 MessengerService.java}</a> (service) and <a
-href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.html">{@code
+href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.html">
+{@code
 MessengerServiceActivities.java}</a> (client) samples.</p>
 
-
-
-
-
-<h2 id="Binding">Binding to a Service</h2>
+<h2 id="Binding">Binding to a service</h2>
 
 <p>Application components (clients) can bind to a service by calling
 {@link android.content.Context#bindService bindService()}. The Android
 system then calls the service's {@link android.app.Service#onBind
-onBind()} method, which returns an {@link android.os.IBinder} for interacting with the service.</p>
+onBind()} method, which returns an {@link android.os.IBinder} for interacting with
+ the service.</p>
 
-<p>The binding is asynchronous. {@link android.content.Context#bindService
-bindService()} returns immediately and does <em>not</em> return the {@link android.os.IBinder} to
-the client. To receive the {@link android.os.IBinder}, the client must create an instance of {@link
+<p>The binding is asynchronous, and {@link android.content.Context#bindService
+bindService()} returns immediately without <em>not</em> returning the {@link android.os.IBinder} to
+the client. To receive the {@link android.os.IBinder}, the client must create an
+ instance of {@link
 android.content.ServiceConnection} and pass it to {@link android.content.Context#bindService
 bindService()}. The {@link android.content.ServiceConnection} includes a callback method that the
 system calls to deliver the {@link android.os.IBinder}.</p>
 
 <p class="note"><strong>Note:</strong> Only activities, services, and content providers can bind
-to a service&mdash;you <strong>cannot</strong> bind to a service from a broadcast receiver.</p>
+to a service&mdash;you <strong>can't</strong> bind to a service from a broadcast receiver.</p>
 
-<p>So, to bind to a service from your client, you must: </p>
+<p>To bind to a service from your client, follow these steps: </p>
 <ol>
   <li>Implement {@link android.content.ServiceConnection}.
     <p>Your implementation must override two callback methods:</p>
@@ -533,7 +549,8 @@
       <dt>{@link android.content.ServiceConnection#onServiceDisconnected
 onServiceDisconnected()}</dt>
         <dd>The Android system calls this when the connection to the service is unexpectedly
-lost, such as when the service has crashed or has been killed. This is <em>not</em> called when the
+lost, such as when the service has crashed or has been killed. This is <em>not</em>
+ called when the
 client unbinds.</dd>
     </dl>
   </li>
@@ -548,12 +565,12 @@
   <p>If your client is still bound to a service when your app destroys the client, destruction
 causes the client to unbind. It is better practice to unbind the client as soon as it is done
 interacting with the service. Doing so allows the idle service to shut down. For more information
-about appropriate times to bind and unbind, see <a href="#Additional_Notes">Additional Notes</a>.
+about appropriate times to bind and unbind, see <a href="#Additional_Notes">Additional notes</a>.
 </p>
   </li>
 </ol>
 
-<p>For example, the following snippet connects the client to the service created above by
+<p>The following example connects the client to the service created above by
 <a href="#Binder">extending the Binder class</a>, so all it must do is cast the returned
 {@link android.os.IBinder} to the {@code LocalService} class and request the {@code
 LocalService} instance:</p>
@@ -579,8 +596,9 @@
 };
 </pre>
 
-<p>With this {@link android.content.ServiceConnection}, the client can bind to a service by passing
-it to {@link android.content.Context#bindService bindService()}. For example:</p>
+<p>With this {@link android.content.ServiceConnection}, the client can bind to a service
+ by passing
+it to {@link android.content.Context#bindService bindService()}, as shown in the following example:</p>
 
 <pre>
 Intent intent = new Intent(this, LocalService.class);
@@ -589,11 +607,21 @@
 
 <ul>
   <li>The first parameter of {@link android.content.Context#bindService bindService()} is an
-{@link android.content.Intent} that explicitly names the service to bind (thought the intent
-could be implicit).</li>
+{@link android.content.Intent} that explicitly names the service to bind.
+<p class="caution"><strong>Caution:</strong> If you use an intent to bind to a
+ {@link android.app.Service}, ensure that your app is secure by using an <a href="{@docRoot}guide/components/intents-filters.html#Types">explicit</a>
+intent. Using an implicit intent to start a service is a
+security hazard because you can't be certain what service will respond to the intent,
+and the user can't see which service starts. Beginning with Android 5.0 (API level 21),
+ the system
+throws an exception if you call {@link android.content.Context#bindService bindService()}
+with an implicit intent.</p>
+</li>
+
 <li>The second parameter is the {@link android.content.ServiceConnection} object.</li>
 <li>The third parameter is a flag indicating options for the binding. It should usually be {@link
-android.content.Context#BIND_AUTO_CREATE} in order to create the service if its not already alive.
+android.content.Context#BIND_AUTO_CREATE} in order to create the service if it's not already
+ alive.
 Other possible values are {@link android.content.Context#BIND_DEBUG_UNBIND}
 and {@link android.content.Context#BIND_NOT_FOREGROUND}, or {@code 0} for none.</li>
 </ul>
@@ -606,10 +634,11 @@
   <li>You should always trap {@link android.os.DeadObjectException} exceptions, which are thrown
 when the connection has broken. This is the only exception thrown by remote methods.</li>
   <li>Objects are reference counted across processes. </li>
-  <li>You should usually pair the binding and unbinding during
-matching bring-up and tear-down moments of the client's lifecycle. For example:
+  <li>You usually pair the binding and unbinding during
+matching bring-up and tear-down moments of the client's lifecycle, as described in the
+ following examples:
     <ul>
-      <li>If you only need to interact with the service while your activity is visible, you
+      <li>If you need to interact with the service only while your activity is visible, you
 should bind during {@link android.app.Activity#onStart onStart()} and unbind during {@link
 android.app.Activity#onStop onStop()}.</li>
       <li>If you want your activity to receive responses even while it is stopped in the
@@ -619,33 +648,34 @@
 the service is in another process, then you increase the weight of the process and it becomes
 more likely that the system will kill it.</li>
     </ul>
-    <p class="note"><strong>Note:</strong> You should usually <strong>not</strong> bind and unbind
+    <p class="note"><strong>Note:</strong> You <em>don't</em> usually bind and unbind
 during your activity's {@link android.app.Activity#onResume onResume()} and {@link
-android.app.Activity#onPause onPause()}, because these callbacks occur at every lifecycle transition
+android.app.Activity#onPause onPause()}, because these callbacks occur at every
+ lifecycle transition
 and you should keep the processing that occurs at these transitions to a minimum. Also, if
-multiple activities in your application bind to the same service and there is a transition between
-two of those activities, the service may be destroyed and recreated as the current activity unbinds
-(during pause) before the next one binds (during resume). (This activity transition for how
+multiple activities in your application bind to the same service and there is a
+ transition between
+two of those activities, the service may be destroyed and recreated as the current
+ activity unbinds
+(during pause) before the next one binds (during resume). This activity transition for how
 activities coordinate their lifecycles is described in the <a
 href="{@docRoot}guide/components/activities.html#CoordinatingActivities">Activities</a>
-document.)</p>
+document.</p>
 </ul>
 
 <p>For more sample code, showing how to bind to a service, see the <a
-href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">{@code
+href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">
+{@code
 RemoteService.java}</a> class in <a
 href="{@docRoot}resources/samples/ApiDemos/index.html">ApiDemos</a>.</p>
 
-
-
-
-
-<h2 id="Lifecycle">Managing the Lifecycle of a Bound Service</h2>
+<h2 id="Lifecycle">Managing the lifecycle of a bound service</h2>
 
 <p>When a service is unbound from all clients, the Android system destroys it (unless it was also
 started with {@link android.app.Service#onStartCommand onStartCommand()}). As such, you don't have
 to manage the lifecycle of your service if it's purely a bound
-service&mdash;the Android system manages it for you based on whether it is bound to any clients.</p>
+service&mdash;the Android system manages it for you based on whether it is bound to
+ any clients.</p>
 
 <p>However, if you choose to implement the {@link android.app.Service#onStartCommand
 onStartCommand()} callback method, then you must explicitly stop the service, because the
@@ -660,17 +690,11 @@
 onRebind()} the next time a client binds to the service. {@link android.app.Service#onRebind
 onRebind()} returns void, but the client still receives the {@link android.os.IBinder} in its
 {@link android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback.
-Below, figure 1 illustrates the logic for this kind of lifecycle.</p>
-
+The following figure illustrates the logic for this kind of lifecycle.</p>
 
 <img src="{@docRoot}images/fundamentals/service_binding_tree_lifecycle.png" alt="" />
 <p class="img-caption"><strong>Figure 1.</strong> The lifecycle for a service that is started
 and also allows binding.</p>
 
-
 <p>For more information about the lifecycle of a started service, see the <a
 href="{@docRoot}guide/components/services.html#Lifecycle">Services</a> document.</p>
-
-
-
-
diff --git a/docs/html/guide/components/fundamentals.jd b/docs/html/guide/components/fundamentals.jd
index ed3ba7d..eaa82c8 100644
--- a/docs/html/guide/components/fundamentals.jd
+++ b/docs/html/guide/components/fundamentals.jd
@@ -6,28 +6,29 @@
 
 <h2>In this document</h2>
 <ol>
-<li><a href="#Components">App Components</a>
+<li><a href="#Components">App components</a>
   <ol>
     <li><a href="#ActivatingComponents">Activating components</a></li>
   </ol>
 </li>
-<li><a href="#Manifest">The Manifest File</a>
+<li><a href="#Manifest">The manifest file</a>
   <ol>
     <li><a href="#DeclaringComponents">Declaring components</a></li>
     <li><a href="#DeclaringRequirements">Declaring app requirements</a></li>
   </ol>
 </li>
-<li><a href="#Resources">App Resources</a></li>
+<li><a href="#Resources">App resources</a></li>
 </ol>
 </div>
 </div>
 
 <p>Android apps are written in the Java programming language. The Android SDK tools compile
-your code&mdash;along with any data and resource files&mdash;into an APK: an <i>Android package</i>,
+your code along with any data and resource files into an APK, an <i>Android package</i>,
 which is an archive file with an {@code .apk} suffix. One APK file contains all the contents
 of an Android app and is the file that Android-powered devices use to install the app.</p>
 
-<p>Once installed on a device, each Android app lives in its own security sandbox: </p>
+<p>Each Android app lives in its own security sandbox, protected by
+ the following Android security features: </p>
 
 <ul>
  <li>The Android operating system is a multi-user Linux system in which each app is a
@@ -40,54 +41,61 @@
 <li>Each process has its own virtual machine (VM), so an app's code runs in isolation from
 other apps.</li>
 
-<li>By default, every app runs in its own Linux process. Android starts the process when any
-of the app's components need to be executed, then shuts down the process when it's no longer
+<li>By default, every app runs in its own Linux process. The Android system starts
+ the process when any
+of the app's components need to be executed, and then shuts down the process
+ when it's no longer
 needed or when the system must recover memory for other apps.</li>
 </ul>
 
-<p>In this way, the Android system implements the <em>principle of least privilege</em>. That is,
+<p>The Android system implements the <em>principle of least privilege</em>. That is,
 each app, by default, has access only to the components that it requires to do its work and
 no more. This creates a very secure environment in which an app cannot access parts of
-the system for which it is not given permission.</p>
-
-<p>However, there are ways for an app to share data with other apps and for an
+the system for which it is not given permission. However, there are ways for an app to share
+ data with other apps and for an
 app to access system services:</p>
 
 <ul>
   <li>It's possible to arrange for two apps to share the same Linux user ID, in which case
 they are able to access each other's files.  To conserve system resources, apps with the
-same user ID can also arrange to run in the same Linux process and share the same VM (the
-apps must also be signed with the same certificate).</li>
+same user ID can also arrange to run in the same Linux process and share the same VM. The
+apps must also be signed with the same certificate.</li>
   <li>An app can request permission to access device data such as the user's
-contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and more. The user has
+contacts, SMS messages, the mountable storage (SD card), camera, and Bluetooth. The user has
 to explicitly grant these permissions. For more information, see
 <a href="{@docRoot}training/permissions/index.html">Working with System Permissions</a>.</li>
 </ul>
 
-<p>That covers the basics regarding how an Android app exists within the system. The rest of
-this document introduces you to:</p>
+<p>The rest of this document introduces the following concepts:</p>
 <ul>
   <li>The core framework components that define your app.</li>
-  <li>The manifest file in which you declare components and required device features for your
+  <li>The manifest file in which you declare the components and the required device
+  features for your
 app.</li>
-  <li>Resources that are separate from the app code and allow your app to
+  <li>Resources that are separate from the app code and that allow your app to
 gracefully optimize its behavior for a variety of device configurations.</li>
 </ul>
 
 
 
-<h2 id="Components">App Components</h2>
+<h2 id="Components">App components</h2>
 
 <p>App components are the essential building blocks of an Android app. Each
 component is a different point through which the system can enter your app. Not all
-components are actual entry points for the user and some depend on each other, but each one exists
-as its own entity and plays a specific role&mdash;each one is a unique building block that
-helps define your app's overall behavior.</p>
+components are actual entry points for the user and some depend on each other,
+ but each one exists
+as its own entity and plays a specific role.</p>
 
-<p>There are four different types of app components. Each type serves a distinct purpose
-and has a distinct lifecycle that defines how the component is created and destroyed.</p>
-
-<p>Here are the four types of app components:</p>
+<p>There are four different types of app components:
+<ul>
+<li>Activities.</li>
+<li>Services.</li>
+<li>Content providers.</li>
+<li>Broadcast receivers.</li>
+</ul></p>
+Each type serves a distinct purpose
+and has a distinct lifecycle that defines how the component is created and destroyed.
+ The following sections describe the four types of app components.</p>
 
 <dl>
 
@@ -98,11 +106,12 @@
 emails, another activity to compose an email, and another activity for reading emails. Although
 the activities work together to form a cohesive user experience in the email app, each one
 is independent of the others. As such, a different app can start any one of these
-activities (if the email app allows it). For example, a camera app can start the
-activity in the email app that composes new mail, in order for the user to share a picture.
+activities if the email app allows it. For example, a camera app can start the
+activity in the email app that composes new mail to allow the user to share a picture.
 
-<p>An activity is implemented as a subclass of {@link android.app.Activity} and you can learn more
-about it in the <a href="{@docRoot}guide/components/activities.html">Activities</a>
+<p>An activity is implemented as a subclass of {@link android.app.Activity}. You can learn more
+about  {@link android.app.Activity} in the
+ <a href="{@docRoot}guide/components/activities.html">Activities</a>
 developer guide.</p>
 </dd>
 
@@ -111,13 +120,16 @@
 
 <dd>A <i>service</i> is a component that runs in the background to perform long-running
 operations or to perform work for remote processes. A service
-does not provide a user interface. For example, a service might play music in the background while
+does not provide a user interface. For example, a service might play music in the
+ background while
 the user is in a different app, or it might fetch data over the network without
-blocking user interaction with an activity. Another component, such as an activity, can start the
+blocking user interaction with an activity. Another component, such as an activity,
+ can start the
 service and let it run or bind to it in order to interact with it.
 
-<p>A service is implemented as a subclass of {@link android.app.Service} and you can learn more
-about it in the <a href="{@docRoot}guide/components/services.html">Services</a> developer
+<p>A service is implemented as a subclass of {@link android.app.Service}. You can learn more
+about  {@link android.app.Service} in the <a href="{@docRoot}guide/components/services.html">
+Services</a> developer
 guide.</p>
 </dd>
 
@@ -125,12 +137,14 @@
 <dt><b>Content providers</b></dt>
 
 <dd>A <i>content provider</i> manages a shared set of app data. You can store the data in
-the file system, an SQLite database, on the web, or any other persistent storage location your
-app can access. Through the content provider, other apps can query or even modify
-the data (if the content provider allows it). For example, the Android system provides a content
+the file system, in a SQLite database, on the web, or on any other persistent storage
+ location that your
+app can access. Through the content provider, other apps can query or modify
+the data if the content provider allows it. For example, the Android system provides a content
 provider that manages the user's contact information. As such, any app with the proper
-permissions can query part of the content provider (such as {@link
-android.provider.ContactsContract.Data}) to read and write information about a particular person.
+permissions can query part of the content provider, such as {@link
+android.provider.ContactsContract.Data}, to read and write information about
+ a particular person.
 
 <p>Content providers are also useful for reading and writing data that is private to your
 app and not shared. For example, the <a
@@ -148,15 +162,17 @@
 <dt><b>Broadcast receivers</b></dt>
 
 <dd>A <i>broadcast receiver</i> is a component that responds to system-wide broadcast
-announcements.  Many broadcasts originate from the system&mdash;for example, a broadcast announcing
+announcements.  Many broadcasts originate from the system&mdash;for example,
+ a broadcast announcing
 that the screen has turned off, the battery is low, or a picture was captured.
 Apps can also initiate broadcasts&mdash;for example, to let other apps know that
-some data has been downloaded to the device and is available for them to use. Although broadcast
+some data has been downloaded to the device and is available for them to use.
+ Although broadcast
 receivers don't display a user interface, they may <a
 href="{@docRoot}guide/topics/ui/notifiers/notifications.html">create a status bar notification</a>
 to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is
-just a "gateway" to other components and is intended to do a very minimal amount of work. For
-instance, it might initiate a service to perform some work based on the event.
+just a <em>gateway</em> to other components and is intended to do a very minimal amount of work.
+ For instance, it might initiate a service to perform some work based on the event.
 
 <p>A broadcast receiver is implemented as a subclass of {@link android.content.BroadcastReceiver}
 and each broadcast is delivered as an {@link android.content.Intent} object. For more information,
@@ -170,52 +186,59 @@
 <p>A unique aspect of the Android system design is that any app can start another
 app’s component. For example, if you want the user to capture a
 photo with the device camera, there's probably another app that does that and your
-app can use it, instead of developing an activity to capture a photo yourself. You don't
+app can use it instead of developing an activity to capture a photo yourself. You don't
 need to incorporate or even link to the code from the camera app.
 Instead, you can simply start the activity in the camera app that captures a
 photo. When complete, the photo is even returned to your app so you can use it. To the user,
 it seems as if the camera is actually a part of your app.</p>
 
-<p>When the system starts a component, it starts the process for that app (if it's not
-already running) and instantiates the classes needed for the component. For example, if your
+<p>When the system starts a component, it starts the process for that app if it's not
+already running and instantiates the classes needed for the component. For example, if your
 app starts the activity in the camera app that captures a photo, that activity
 runs in the process that belongs to the camera app, not in your app's process.
 Therefore, unlike apps on most other systems, Android apps don't have a single entry
-point (there's no {@code main()} function, for example).</p>
+point (there's no {@code main()} function).</p>
 
 <p>Because the system runs each app in a separate process with file permissions that
 restrict access to other apps, your app cannot directly activate a component from
-another app. The Android system, however, can. So, to activate a component in
-another app, you must deliver a message to the system that specifies your <em>intent</em> to
+another app. However, the Android system can. To activate a component in
+another app, deliver a message to the system that specifies your <em>intent</em> to
 start a particular component. The system then activates the component for you.</p>
 
 
-<h3 id="ActivatingComponents">Activating Components</h3>
+<h3 id="ActivatingComponents">Activating components</h3>
 
 <p>Three of the four component types&mdash;activities, services, and
 broadcast receivers&mdash;are activated by an asynchronous message called an <em>intent</em>.
-Intents bind individual components to each other at runtime (you can think of them
-as the messengers that request an action from other components), whether the component belongs
+Intents bind individual components to each other at runtime. You can think of them
+as the messengers that request an action from other components, whether the component belongs
 to your app or another.</p>
 
-<p>An intent is created with an {@link android.content.Intent} object, which defines a message to
-activate either a specific component or a specific <em>type</em> of component&mdash;an intent
-can be either explicit or implicit, respectively.</p>
+<p class="note"><strong>Note:</strong> If your app targets Android 5.0 (API level 21) or later,
+ use the {@link android.app.job.JobScheduler} to execute background
+ services. For more information about using this class, see the
+ {@link android.app.job.JobScheduler} reference documentation.</p>
 
-<p>For activities and services, an intent defines the action to perform (for example, to "view" or
-"send" something) and may specify the URI of the data to act on (among other things that the
-component being started might need to know). For example, an intent might convey a request for an
+<p>An intent is created with an {@link android.content.Intent} object, which defines a message to
+activate either a specific component (explicit intent) or a specific <em>type</em> of component
+ (implicit intent).</p>
+
+<p>For activities and services, an intent defines the action to perform (for example, to
+ <em>view</em> or
+<em>send</em> something) and may specify the URI of the data to act on, among other things that the
+component being started might need to know. For example, an intent might convey a request for an
 activity to show an image or to open a web page. In some cases, you can start an
-activity to receive a result, in which case, the activity also returns
-the result in an {@link android.content.Intent} (for example, you can issue an intent to let
-the user pick a personal contact and have it returned to you&mdash;the return intent includes a
-URI pointing to the chosen contact).</p>
+activity to receive a result, in which case the activity also returns
+the result in an {@link android.content.Intent}. For example, you can issue an intent to let
+the user pick a personal contact and have it returned to you. The return intent includes a
+URI pointing to the chosen contact.</p>
 
 <p>For broadcast receivers, the intent simply defines the
-announcement being broadcast (for example, a broadcast to indicate the device battery is low
-includes only a known action string that indicates "battery is low").</p>
+announcement being broadcast. For example, a broadcast to indicate the device battery is low
+includes only a known action string that indicates <em>battery is low</em>.</p>
 
-<p>The other component type, content provider, is not activated by intents. Rather, it is
+<p>Unlike activities, services, and broadcast receivers, content providers are not activated
+ by intents. Rather, they are
 activated when targeted by a request from a {@link android.content.ContentResolver}. The content
 resolver handles all direct transactions with the content provider so that the component that's
 performing transactions with the provider doesn't need to and instead calls methods on the {@link
@@ -224,15 +247,19 @@
 
 <p>There are separate methods for activating each type of component:</p>
 <ul>
-  <li>You can start an activity (or give it something new to do) by
+  <li>You can start an activity or give it something new to do by
 passing an {@link android.content.Intent} to {@link android.content.Context#startActivity
 startActivity()} or {@link android.app.Activity#startActivityForResult startActivityForResult()}
 (when you want the activity to return a result).</li>
-  <li>You can start a service (or give new instructions to an ongoing service) by
+
+
+  <li>With Android 5.0 (API level 21) and later, you can start a service with
+  {@link android.app.job.JobScheduler}. For earlier Android versions, you can start
+  a service (or give new instructions to an ongoing service) by
 passing an {@link android.content.Intent} to {@link android.content.Context#startService
-startService()}. Or you can bind to the service by passing an {@link android.content.Intent} to
-{@link android.content.Context#bindService bindService()}.</li>
-  <li>You can initiate a broadcast by passing an {@link android.content.Intent} to methods like
+startService()}. You can bind to the service by passing an {@link android.content.Intent} to
+{@link android.content.Context#bindService bindService()}. </li>
+  <li>You can initiate a broadcast by passing an {@link android.content.Intent} to methods such as
 {@link android.content.Context#sendBroadcast(Intent) sendBroadcast()}, {@link
 android.content.Context#sendOrderedBroadcast(Intent, String) sendOrderedBroadcast()}, or {@link
 android.content.Context#sendStickyBroadcast sendStickyBroadcast()}.</li>
@@ -242,35 +269,35 @@
 
 <p>For more information about using intents, see the <a
 href="{@docRoot}guide/components/intents-filters.html">Intents and
-Intent Filters</a> document. More information about activating specific components is also provided
-in the following documents: <a
-href="{@docRoot}guide/components/activities.html">Activities</a>, <a
-href="{@docRoot}guide/components/services.html">Services</a>, {@link
-android.content.BroadcastReceiver} and <a
-href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>.</p>
+Intent Filters</a> document.
+ The following documents provide more information about activating specifc components:
+ <a href="{@docRoot}guide/components/activities.html">Activities</a>,
+ <a href="{@docRoot}guide/components/services.html">Services
+ {@link android.content.BroadcastReceiver}, and
+ <a ref="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>.</p>
 
-
-<h2 id="Manifest">The Manifest File</h2>
+<h2 id="Manifest">The manifest file</h2>
 
 <p>Before the Android system can start an app component, the system must know that the
-component exists by reading the app's {@code AndroidManifest.xml} file (the "manifest"
-file). Your app must declare all its components in this file, which must be at the root of
-the app project directory.</p>
+component exists by reading the app's <em>manifest file</em>, {@code AndroidManifest.xml}.
+ Your app must declare all its components in this file, which must be at the root of the
+ app project directory.</p>
 
 <p>The manifest does a number of things in addition to declaring the app's components,
-such as:</p>
+such as the following:</p>
 <ul>
-  <li>Identify any user permissions the app requires, such as Internet access or
+  <li>Identifies any user permissions the app requires, such as Internet access or
 read-access to the user's contacts.</li>
-  <li>Declare the minimum <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">API Level</a>
+  <li>Declares the minimum
+  <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">API Level</a>
 required by the app, based on which APIs the app uses.</li>
-  <li>Declare hardware and software features used or required by the app, such as a camera,
+  <li>Declares hardware and software features used or required by the app, such as a camera,
 bluetooth services, or a multitouch screen.</li>
-  <li>API libraries the app needs to be linked against (other than the Android framework
+  <li>Declares API libraries the app needs to be linked against (other than the Android framework
 APIs), such as the <a
-href="http://code.google.com/android/add-ons/google-apis/maps-overview.html">Google Maps
-library</a>.</li>
-  <li>And more</li>
+href="http://code.google.com/android/add-ons/google-apis/maps-overview.html">
+Google Maps library</a>.</li>
+
 </ul>
 
 
@@ -301,47 +328,59 @@
 android.app.Activity} subclass and the {@code android:label} attribute specifies a string
 to use as the user-visible label for the activity.</p>
 
-<p>You must declare all app components this way:</p>
+<p>You must declare all app components using the following elements:</p>
 <ul>
   <li><code><a
 href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></code> elements
-for activities</li>
+for activities.</li>
   <li><code><a
 href="{@docRoot}guide/topics/manifest/service-element.html">&lt;service&gt;</a></code> elements for
-services</li>
+services.</li>
   <li><code><a
 href="{@docRoot}guide/topics/manifest/receiver-element.html">&lt;receiver&gt;</a></code> elements
-for broadcast receivers</li>
+for broadcast receivers.</li>
   <li><code><a
 href="{@docRoot}guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></code> elements
-for content providers</li>
+for content providers.</li>
 </ul>
 
 <p>Activities, services, and content providers that you include in your source but do not declare
 in the manifest are not visible to the system and, consequently, can never run.  However,
 broadcast
-receivers can be either declared in the manifest or created dynamically in code (as
-{@link android.content.BroadcastReceiver} objects) and registered with the system by calling
+receivers can be either declared in the manifest or created dynamically in code as
+{@link android.content.BroadcastReceiver} objects and registered with the system by calling
 {@link android.content.Context#registerReceiver registerReceiver()}.</p>
 
 <p>For more about how to structure the manifest file for your app, see <a
 href="{@docRoot}guide/topics/manifest/manifest-intro.html">The AndroidManifest.xml File</a>
 documentation. </p>
 
-
-
 <h3 id="DeclaringComponentCapabilities">Declaring component capabilities</h3>
 
-<p>As discussed above, in <a href="#ActivatingComponents">Activating Components</a>, you can use an
-{@link android.content.Intent} to start activities, services, and broadcast receivers. You can do so
-by explicitly naming the target component (using the component class name) in the intent. However,
-the real power of intents lies in the concept of <em>implicit intents</em>. An implicit intent
-simply describes the type of action to perform (and, optionally, the data upon which you’d like to
-perform the action) and allows the system to find a component on the device that can perform the
-action and start it. If there are multiple components that can perform the action described by the
-intent, then the user selects which one to use.</p>
+<p>As discussed above, in <a href="#ActivatingComponents">Activating components</a>, you can use an
+{@link android.content.Intent} to start activities, services, and broadcast receivers.
 
-<p>The way the system identifies the components that can respond to an intent is by comparing the
+
+
+You can use an {@link android.content.Intent}
+ by explicitly naming the target component (using the component class name) in the intent.
+ You can also use an implicit intent, which
+describes the type of action to perform and, optionally, the data upon which you’d like to
+perform the action. The implicit intent allows the system to find a component on the device
+ that can perform the
+action and start it. If there are multiple components that can perform the action described by the
+intent, the user selects which one to use.</p>
+
+<p class="caution"><strong>Caution:</strong> If you use an intent to start a
+ {@link android.app.Service}, ensure that your app is secure by using an
+ <a href="{@docRoot}guide/components/intents-filters.html#Types">explicit</a>
+intent. Using an implicit intent to start a service is a
+security hazard because you cannot be certain what service will respond to the intent,
+and the user cannot see which service starts. Beginning with Android 5.0 (API level 21), the system
+throws an exception if you call {@link android.content.Context#bindService bindService()}
+with an implicit intent. Do not declare intent filters for your services. </p>
+
+<p>The system identifies the components that can respond to an intent by comparing the
 intent received to the <i>intent filters</i> provided in the manifest file of other apps on
 the device.</p>
 
@@ -351,8 +390,9 @@
 adding an <a href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code
 <intent-filter>}</a> element as a child of the component's declaration element.</p>
 
-<p>For example, if you've built an email app with an activity for composing a new email, you can
-declare an intent filter to respond to "send" intents (in order to send a new email) like this:</p>
+<p>For example, if you build an email app with an activity for composing a new email, you can
+declare an intent filter to respond to "send" intents (in order to send a new email),
+ as shown in the following example:</p>
 <pre>
 &lt;manifest ... >
     ...
@@ -368,8 +408,9 @@
 &lt;/manifest>
 </pre>
 
-<p>Then, if another app creates an intent with the {@link
-android.content.Intent#ACTION_SEND} action and passes it to {@link android.app.Activity#startActivity
+<p>If another app creates an intent with the {@link
+android.content.Intent#ACTION_SEND} action and passes it to
+ {@link android.app.Activity#startActivity
 startActivity()}, the system may start your activity so the user can draft and send an
 email.</p>
 
@@ -382,7 +423,7 @@
 <h3 id="DeclaringRequirements">Declaring app requirements</h3>
 
 <p>There are a variety of devices powered by Android and not all of them provide the
-same features and capabilities. In order to prevent your app from being installed on devices
+same features and capabilities. To prevent your app from being installed on devices
 that lack features needed by your app, it's important that you clearly define a profile for
 the types of devices your app supports by declaring device and software requirements in your
 manifest file. Most of these declarations are informational only and the system does not read
@@ -391,7 +432,7 @@
 
 <p>For example, if your app requires a camera and uses APIs introduced in Android 2.1 (<a
 href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">API Level</a> 7),
-you should declare these as requirements in your manifest file like this:</p>
+you must declare these as requirements in your manifest file as shown in the following example:</p>
 
 <pre>
 &lt;manifest ... >
@@ -402,10 +443,10 @@
 &lt;/manifest>
 </pre>
 
-<p>Now, devices that do <em>not</em> have a camera and have an
-Android version <em>lower</em> than 2.1 cannot install your app from Google Play.</p>
-
-<p>However, you can also declare that your app uses the camera, but does not
+<p>With the declarations shown in the example, devices that do <em>not</em> have a
+ camera and have an
+Android version <em>lower</em> than 2.1 cannot install your app from Google Play.
+ However, you can declare that your app uses the camera, but does not
 <em>require</em> it. In that case, your app must set the <a href=
 "{@docRoot}guide/topics/manifest/uses-feature-element.html#required">{@code required}</a>
 attribute to {@code "false"} and check at runtime whether
@@ -417,15 +458,15 @@
 
 
 
-<h2 id="Resources">App Resources</h2>
+<h2 id="Resources">App resources</h2>
 
 <p>An Android app is composed of more than just code&mdash;it requires resources that are
 separate from the source code, such as images, audio files, and anything relating to the visual
-presentation of the app. For example, you should define animations, menus, styles, colors,
+presentation of the app. For example, you can define animations, menus, styles, colors,
 and the layout of activity user interfaces with XML files. Using app resources makes it easy
-to update various characteristics of your app without modifying code and&mdash;by providing
-sets of alternative resources&mdash;enables you to optimize your app for a  variety of
-device configurations (such as different languages and screen sizes).</p>
+to update various characteristics of your app without modifying code. Providing
+sets of alternative resources enables you to optimize your app for a variety of
+device configurations, such as different languages and screen sizes.</p>
 
 <p>For every resource that you include in your Android project, the SDK build tools define a unique
 integer ID, which you can use to reference the resource from your app code or from
@@ -435,20 +476,22 @@
 user interface.</p>
 
 <p>One of the most important aspects of providing resources separate from your source code
-is the ability for you to provide alternative resources for different device
-configurations. For example, by defining UI strings in XML, you can translate the strings into other
-languages and save those strings in separate files. Then, based on a language <em>qualifier</em>
+is the ability to provide alternative resources for different device
+configurations. For example, by defining UI strings in XML, you can translate
+ the strings into other
+languages and save those strings in separate files. Then Android applies the
+ appropriate language strings
+to your UI based on a language <em>qualifier</em>
 that you append to the resource directory's name (such as {@code res/values-fr/} for French string
-values) and the user's language setting, the Android system applies the appropriate language strings
-to your UI.</p>
+values) and the user's language setting.</p>
 
 <p>Android supports many different <em>qualifiers</em> for your alternative resources. The
 qualifier is a short string that you include in the name of your resource directories in order to
-define the device configuration for which those resources should be used. As another
-example, you should often create different layouts for your activities, depending on the
-device's screen orientation and size. For example, when the device screen is in portrait
+define the device configuration for which those resources should be used. For
+example, you should create different layouts for your activities, depending on the
+device's screen orientation and size. When the device screen is in portrait
 orientation (tall), you might want a layout with buttons to be vertical, but when the screen is in
-landscape orientation (wide), the buttons should be aligned horizontally. To change the layout
+landscape orientation (wide), the buttons could be aligned horizontally. To change the layout
 depending on the orientation, you can define two different layouts and apply the appropriate
 qualifier to each layout's directory name. Then, the system automatically applies the appropriate
 layout depending on the current device orientation.</p>
@@ -465,15 +508,15 @@
   <dl>
     <dt><a href="{@docRoot}guide/components/intents-filters.html">Intents and Intent Filters</a>
     </dt>
-    <dd>Information about how to use the {@link android.content.Intent} APIs to
+    <dd>How to use the {@link android.content.Intent} APIs to
     activate app components, such as activities and services, and how to make your app components
     available for use by other apps.</dd>
     <dt><a href="{@docRoot}guide/components/activities.html">Activities</a></dt>
-    <dd>Information about how to create an instance of the {@link android.app.Activity} class,
+    <dd>How to create an instance of the {@link android.app.Activity} class,
     which provides a distinct screen in your application with a user interface.</dd>
     <dt><a
 href="{@docRoot}guide/topics/resources/providing-resources.html">Providing Resources</a></dt>
-    <dd>Information about how Android apps are structured to separate app resources from the
+    <dd>How Android apps are structured to separate app resources from the
    app code, including how you can provide alternative resources for specific device
    configurations.
     </dd>
@@ -484,14 +527,13 @@
   <dl>
     <dt><a href="{@docRoot}guide/practices/compatibility.html"
         >Device Compatibility</a></dt>
-    <dd>Information about Android works on different types of devices and an introduction
+    <dd>How Android works on different types of devices and an introduction
     to how you can optimize your app for each device or restrict your app's availability
     to different devices.</dd>
     <dt><a href="{@docRoot}guide/topics/security/permissions.html"
         >System Permissions</a></dt>
-    <dd>Information about how Android restricts app access to certain APIs with a permission
+    <dd>How Android restricts app access to certain APIs with a permission
     system that requires the user's consent for your app to use those APIs.</dd>
   </dl>
 </div>
 </div>
-
diff --git a/docs/html/guide/components/intents-filters.jd b/docs/html/guide/components/intents-filters.jd
index d1d8c78..8f41bc3 100644
--- a/docs/html/guide/components/intents-filters.jd
+++ b/docs/html/guide/components/intents-filters.jd
@@ -7,21 +7,21 @@
 
 <h2>In this document</h2>
 <ol>
-  <li><a href="#Types">Intent Types</a></li>
-  <li><a href="#Building">Building an Intent</a>
+  <li><a href="#Types">Intent types</a></li>
+  <li><a href="#Building">Building an intent</a>
     <ol>
       <li><a href="#ExampleExplicit">Example explicit intent</a></li>
       <li><a href="#ExampleSend">Example implicit intent</a></li>
       <li><a href="#ForceChooser">Forcing an app chooser</a></li>
     </ol>
   </li>
-  <li><a href="#Receiving">Receiving an Implicit Intent</a>
+  <li><a href="#Receiving">Receiving an implicit intent</a>
     <ol>
       <li><a href="#ExampleFilters">Example filters</a></li>
     </ol>
   </li>
-  <li><a href="#PendingIntent">Using a Pending Intent</a></li>
-  <li><a href="#Resolution">Intent Resolution</a>
+  <li><a href="#PendingIntent">Using a pending intent</a></li>
+  <li><a href="#Resolution">Intent resolution</a>
     <ol>
       <li><a href="#ActionTest">Action test</a></li>
       <li><a href="#CategoryTest">Category test</a></li>
@@ -46,13 +46,14 @@
 <p>An {@link android.content.Intent} is a messaging object you can use to request an action
 from another <a href="{@docRoot}guide/components/fundamentals.html#Components">app component</a>.
 Although intents facilitate communication between components in several ways, there are three
-fundamental use-cases:</p>
+fundamental use cases:</p>
 
 <ul>
-<li><b>To start an activity:</b>
+<li><b>Starting an activity</b>
 <p>An {@link android.app.Activity} represents a single screen in an app. You can start a new
 instance of an {@link android.app.Activity} by passing an {@link android.content.Intent}
-to {@link android.content.Context#startActivity startActivity()}. The {@link android.content.Intent}
+to {@link android.content.Context#startActivity startActivity()}.
+ The {@link android.content.Intent}
 describes the activity to start and carries any necessary data.</p>
 
 <p>If you want to receive a result from the activity when it finishes,
@@ -63,10 +64,16 @@
 For more information, see the <a
 href="{@docRoot}guide/components/activities.html">Activities</a> guide.</p></li>
 
-<li><b>To start a service:</b>
+<li><b>Starting a service</b>
 <p>A {@link android.app.Service} is a component that performs operations in the background
-without a user interface. You can start a service to perform a one-time operation
-(such as download a file) by passing an {@link android.content.Intent}
+without a user interface. With Android 5.0 (API level 21) and later, you can start a service
+ with {@link android.app.job.JobScheduler}. For more information
+ about {@link android.app.job.JobScheduler}, see its
+    {@link android.app.job.JobScheduler API-reference documentation}.</p>
+<p>For versions earlier than Android 5.0 (API level 21), you can start a service by using
+methods of the  {@link android.app.Service} class. You can start a service
+ to perform a one-time operation
+(such as downloading a file) by passing an {@link android.content.Intent}
 to {@link android.content.Context#startService startService()}. The {@link android.content.Intent}
 describes the service to start and carries any necessary data.</p>
 
@@ -75,7 +82,7 @@
 android.content.Context#bindService bindService()}</code>. For more information, see the <a
 href="{@docRoot}guide/components/services.html">Services</a> guide.</p></li>
 
-<li><b>To deliver a broadcast:</b>
+<li><b>Delivering a broadcast</b>
 <p>A broadcast is a message that any app can receive. The system delivers various
 broadcasts for system events, such as when the system boots up or the device starts charging.
 You can deliver a broadcast to other apps by passing an {@link android.content.Intent}
@@ -89,7 +96,7 @@
 
 
 
-<h2 id="Types">Intent Types</h2>
+<h2 id="Types">Intent types</h2>
 
 <p>There are two types of intents:</p>
 
@@ -97,7 +104,7 @@
 <li><b>Explicit intents</b> specify the component to start by name (the
 fully-qualified class name). You'll typically use an explicit intent to start a component in
 your own app, because you know the class name of the activity or service you want to start. For
-example, start a new activity in response to a user action or start a service to download
+example, you can start a new activity in response to a user action or start a service to download
 a file in the background.</li>
 
 <li><b>Implicit intents</b> do not name a specific component, but instead declare a general action
@@ -106,12 +113,13 @@
 app show a specified location on a map.</li>
 </ul>
 
-<p>When you create an explicit intent to start an activity or service, the system immediately
+<p>Figure 1 shows how an intent is delivered to start an activity. When you create an
+ explicit intent to start an activity or service, the system immediately
 starts the app component specified in the {@link android.content.Intent} object.</p>
 
 <div class="figure" style="width:446px">
 <img src="{@docRoot}images/components/intent-filters@2x.png" width="446" alt=""/>
-<p class="img-caption"><strong>Figure 1.</strong> Illustration of how an implicit intent is
+<p class="img-caption"><strong>Figure 1.</strong> How an implicit intent is
 delivered through the system to start another activity: <b>[1]</b> <em>Activity A</em> creates an
 {@link android.content.Intent} with an action description and passes it to {@link
 android.content.Context#startActivity startActivity()}. <b>[2]</b> The Android System searches all
@@ -135,11 +143,12 @@
 Likewise, if you do <em>not</em> declare any intent filters for an activity, then it can be started
 only with an explicit intent.</p>
 
-<p class="caution"><strong>Caution:</strong> To ensure your app is secure, always use an explicit
+<p class="caution"><strong>Caution:</strong> To ensure that your app is secure, always
+ use an explicit
 intent when starting a {@link android.app.Service} and do not
 declare intent filters for your services. Using an implicit intent to start a service is a
-security hazard because you cannot be certain what service will respond to the intent,
-and the user cannot see which service starts. Beginning with Android 5.0 (API level 21), the system
+security hazard because you can't be certain what service will respond to the intent,
+and the user can't see which service starts. Beginning with Android 5.0 (API level 21), the system
 throws an exception if you call {@link android.content.Context#bindService bindService()}
 with an implicit intent.</p>
 
@@ -147,7 +156,7 @@
 
 
 
-<h2 id="Building">Building an Intent</h2>
+<h2 id="Building">Building an intent</h2>
 
 <p>An {@link android.content.Intent} object carries information that the Android system uses
 to determine which component to start (such as the exact component name or component
@@ -163,22 +172,23 @@
 <dd>The name of the component to start.
 
 <p>This is optional, but it's the critical piece of information that makes an intent
-<b>explicit</b>, meaning that the intent should be delivered only to the app component
-defined by the component name. Without a component name, the intent is <b>implicit</b> and the
+<em>explicit</em>, meaning that the intent should be delivered only to the app component
+defined by the component name. Without a component name, the intent is <em>implicit</em> and the
 system decides which component should receive the intent based on the other intent information
-(such as the action, data, and category&mdash;described below). So if you need to start a specific
+(such as the action, data, and category&mdash;described below). If you need to start a specific
 component in your app, you should specify the component name.</p>
 
-<p class="note"><strong>Note:</strong> When starting a {@link android.app.Service}, you should
-<strong>always specify the component name</strong>. Otherwise, you cannot be certain what service
+<p class="note"><strong>Note:</strong> When starting a {@link android.app.Service},
+ <em>always specify the component name</em>. Otherwise, you cannot be certain what service
 will respond to the intent, and the user cannot see which service starts.</p>
 
 <p>This field of the {@link android.content.Intent} is a
 {@link android.content.ComponentName} object, which you can specify using a fully
-qualified class name of the target component, including the package name of the app. For example,
+qualified class name of the target component, including the package name of the app, for example,
 {@code com.example.ExampleActivity}. You can set the component name with {@link
 android.content.Intent#setComponent setComponent()}, {@link android.content.Intent#setClass
-setClass()}, {@link android.content.Intent#setClassName(String, String) setClassName()}, or with the
+setClass()}, {@link android.content.Intent#setClassName(String, String) setClassName()},
+ or with the
 {@link android.content.Intent} constructor.</p>
 
 </dd>
@@ -188,10 +198,10 @@
 
 <p>In the case of a broadcast intent, this is the action that took place and is being reported.
 The action largely determines how the rest of the intent is structured&mdash;particularly
-what is contained in the data and extras.
+the information that is contained in the data and extras.
 
 <p>You can specify your own actions for use by intents within your app (or for use by other
-apps to invoke components in your app), but you should usually use action constants
+apps to invoke components in your app), but you usually specify action constants
 defined by the {@link android.content.Intent} class or other framework classes. Here are some
 common actions for starting an activity:</p>
 
@@ -203,7 +213,7 @@
    view in a map app.</dd>
 
 <dt>{@link android.content.Intent#ACTION_SEND}</dt>
-   <dd>Also known as the "share" intent, you should use this in an intent with {@link
+   <dd>Also known as the <em>share</em> intent, you should use this in an intent with {@link
    android.content.Context#startActivity startActivity()} when you have some data that the user can
    share through another app, such as an email app or social sharing app.</dd>
 </dl>
@@ -217,12 +227,13 @@
 setAction()} or with an {@link android.content.Intent} constructor.</p>
 
 <p>If you define your own actions, be sure to include your app's package name
-as a prefix. For example:</p>
+as a prefix, as shown in the following example:</p>
 <pre>static final String ACTION_TIMETRAVEL = "com.example.action.TIMETRAVEL";</pre>
 </dd>
 
 <dt><b>Data</b></dt>
-<dd>The URI (a {@link android.net.Uri} object) that references the data to be acted on and/or the
+<dd>The URI (a {@link android.net.Uri} object) that references the data to
+ be acted on and/or the
 MIME type of that data. The type of data supplied is generally dictated by the intent's action. For
 example, if the action is {@link android.content.Intent#ACTION_EDIT}, the data should contain the
 URI of the document to edit.
@@ -231,10 +242,11 @@
 it's often important to specify the type of data (its MIME type) in addition to its URI.
 For example, an activity that's able to display images probably won't be able
 to play an audio file, even though the URI formats could be similar.
-So specifying the MIME type of your data helps the Android
+Specifying the MIME type of your data helps the Android
 system find the best component to receive your intent.
 However, the MIME type can sometimes be inferred from the URI&mdash;particularly when the data is a
-{@code content:} URI, which indicates the data is located on the device and controlled by a
+{@code content:} URI. A {@code content:} URI indicates the data is located on the device
+ and controlled by a
 {@link android.content.ContentProvider}, which makes the data MIME type visible to the system.</p>
 
 <p>To set only the data URI, call {@link android.content.Intent#setData setData()}.
@@ -243,7 +255,7 @@
 android.content.Intent#setDataAndType setDataAndType()}.</p>
 
 <p class="caution"><strong>Caution:</strong> If you want to set both the URI and MIME type,
-<strong>do not</strong> call {@link android.content.Intent#setData setData()} and
+<em>don't</em> call {@link android.content.Intent#setData setData()} and
 {@link android.content.Intent#setType setType()} because they each nullify the value of the other.
 Always use {@link android.content.Intent#setDataAndType setDataAndType()} to set both
 URI and MIME type.</p>
@@ -258,7 +270,7 @@
 <dl>
 <dt>{@link android.content.Intent#CATEGORY_BROWSABLE}</dt>
   <dd>The target activity allows itself to be started by a web browser to display data
-       referenced by a link&mdash;such as an image or an e-mail message.
+       referenced by a link, such as an image or an e-mail message.
   </dd>
 <dt>{@link android.content.Intent#CATEGORY_LAUNCHER}</dt>
   <dd>The activity is the initial activity of a task and is listed in
@@ -276,14 +288,14 @@
 
 <p>These properties listed above (component name, action, data, and category) represent the
 defining characteristics of an intent. By reading these properties, the Android system
-is able to resolve which app component it should start.</p>
-
-<p>However, an intent can carry additional information that does not affect
-how it is resolved to an app component. An intent can also supply:</p>
+is able to resolve which app component it should start. However, an intent can carry
+ additional information that does not affect
+how it is resolved to an app component. An intent can also supply the following information:</p>
 
 <dl>
 <dt><b>Extras</b></dt>
-<dd>Key-value pairs that carry additional information required to accomplish the requested action.
+<dd>Key-value pairs that carry additional information required to accomplish
+ the requested action.
 Just as some actions use particular kinds of data URIs, some actions also use particular extras.
 
 <p>You can add extra data with various {@link android.content.Intent#putExtra putExtra()} methods,
@@ -293,21 +305,22 @@
 android.content.Intent#putExtras putExtras()}.</p>
 
 <p>For example, when creating an intent to send an email with
-{@link android.content.Intent#ACTION_SEND}, you can specify the "to" recipient with the
-{@link android.content.Intent#EXTRA_EMAIL} key, and specify the "subject" with the
+{@link android.content.Intent#ACTION_SEND}, you can specify the <em>to</em> recipient with the
+{@link android.content.Intent#EXTRA_EMAIL} key, and specify the <em>subject</em> with the
 {@link android.content.Intent#EXTRA_SUBJECT} key.</p>
 
 <p>The {@link android.content.Intent} class specifies many {@code EXTRA_*} constants
 for standardized data types. If you need to declare your own extra keys (for intents that
 your app receives), be sure to include your app's package name
-as a prefix. For example:</p>
+as a prefix, as shown in the following example:</p>
 <pre>static final String EXTRA_GIGAWATTS = "com.example.EXTRA_GIGAWATTS";</pre>
 </dd>
 
 <dt><b>Flags</b></dt>
-<dd>Flags defined in the {@link android.content.Intent} class that function as metadata for the
+<dd>Flags are defined in the {@link android.content.Intent} class that function as metadata for the
 intent. The flags may instruct the Android system how to launch an activity (for example, which
-<a href="{@docRoot}guide/components/tasks-and-back-stack.html">task</a> the activity should belong
+<a href="{@docRoot}guide/components/tasks-and-back-stack.html">task</a>
+ the activity should belong
 to) and how to treat it after it's launched (for example, whether it belongs in the list of recent
 activities).
 
@@ -354,7 +367,8 @@
 to perform the action. Using an implicit intent is useful when your app cannot perform the
 action, but other apps probably can and you'd like the user to pick which app to use.</p>
 
-<p>For example, if you have content you want the user to share with other people, create an intent
+<p>For example, if you have content that you want the user to share with other people,
+ create an intent
 with the {@link android.content.Intent#ACTION_SEND} action
 and add extras that specify the content to share. When you call
 {@link android.content.Context#startActivity startActivity()} with that intent, the user can
@@ -362,13 +376,15 @@
 
 <p class="caution"><strong>Caution:</strong> It's possible that a user won't have <em>any</em>
 apps that handle the implicit intent you send to {@link android.content.Context#startActivity
-startActivity()}. If that happens, the call will fail and your app will crash. To verify
+startActivity()}. If that happens, the call fails and your app crashes. To verify
 that an activity will receive the intent, call {@link android.content.Intent#resolveActivity
 resolveActivity()} on your {@link android.content.Intent} object. If the result is non-null,
-then there is at least one app that can handle the intent and it's safe to call
+ there is at least one app that can handle the intent and it's safe to call
 {@link android.content.Context#startActivity startActivity()}. If the result is null,
-you should not use the intent and, if possible, you should disable the feature that issues
-the intent.</p>
+ do not use the intent and, if possible, you should disable the feature that issues
+the intent. The following example shows how to verify that the intent resolves
+to an activity. This example doesn't use a URI, but the intent's data type
+is declared to specify the content carried by the extras.</p>
 
 
 <pre>
@@ -384,8 +400,7 @@
 }
 </pre>
 
-<p class="note"><strong>Note:</strong> In this case, a URI is not used, but the intent's data type
-is declared to specify the content carried by the extras.</p>
+
 
 
 <p>When {@link android.content.Context#startActivity startActivity()} is called, the system
@@ -393,7 +408,7 @@
 intent with the {@link android.content.Intent#ACTION_SEND} action and that carries "text/plain"
 data). If there's only one app that can handle it, that app opens immediately and is given the
 intent. If multiple activities accept the intent, the system
-displays a dialog so the user can pick which app to use..</p>
+displays a dialog such as the one shown in Figure 2, so the user can pick which app to use.</p>
 
 
 <div class="figure" style="width:200px">
@@ -405,23 +420,26 @@
 
 <p>When there is more than one app that responds to your implicit intent,
 the user can select which app to use and make that app the default choice for the
-action. This is nice when performing an action for which the user
-probably wants to use the same app from now on, such as when opening a web page (users
-often prefer just one web browser) .</p>
+action. The ability to select a default is helpful when performing an action for which the user
+probably wants to use the same app every time, such as when opening a web page (users
+often prefer just one web browser).</p>
 
 <p>However, if multiple apps can respond to the intent and the user might want to use a different
 app each time, you should explicitly show a chooser dialog. The chooser dialog asks the
-user to select which app to use for the action every time (the user cannot select a default app for
+user to select which app to use for the action (the user cannot select a default app for
 the action). For example, when your app performs "share" with the {@link
 android.content.Intent#ACTION_SEND} action, users may want to share using a different app depending
-on their current situation, so you should always use the chooser dialog, as shown in figure 2.</p>
+on their current situation, so you should always use the chooser dialog, as shown in Figure 2.</p>
 
 
 
 
 <p>To show the chooser, create an {@link android.content.Intent} using {@link
 android.content.Intent#createChooser createChooser()} and pass it to {@link
-android.app.Activity#startActivity startActivity()}. For example:</p>
+android.app.Activity#startActivity startActivity()}, as shown in the following example.
+ This example displays a dialog with a list of apps that respond to the intent passed to the {@link
+android.content.Intent#createChooser createChooser()} method and uses the supplied text as the
+dialog title.</p>
 
 <pre>
 Intent sendIntent = new Intent(Intent.ACTION_SEND);
@@ -439,26 +457,16 @@
 }
 </pre>
 
-<p>This displays a dialog with a list of apps that respond to the intent passed to the {@link
-android.content.Intent#createChooser createChooser()} method and uses the supplied text as the
-dialog title.</p>
 
 
-
-
-
-
-
-
-
-<h2 id="Receiving">Receiving an Implicit Intent</h2>
+<h2 id="Receiving">Receiving an implicit intent</h2>
 
 <p>To advertise which implicit intents your app can receive, declare one or more intent filters for
 each of your app components with an <a href=
-"{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code <intent-filter>}</a>
+"{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code &lt;intent-filter&gt;}</a>
 element in your <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest file</a>.
 Each intent filter specifies the type of intents it accepts based on the intent's action,
-data, and category. The system will deliver an implicit intent to your app component only if the
+data, and category. The system delivers an implicit intent to your app component only if the
 intent can pass through one of your intent filters.</p>
 
 <p class="note"><strong>Note:</strong> An explicit intent is always delivered to its target,
@@ -471,28 +479,28 @@
 in the {@link android.content.Intent} (such as to show the editor controls or not).</p>
 
 <p>Each intent filter is defined by an <a
-href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code <intent-filter>}</a>
+href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code &lt;intent-filter>}</a>
 element in the app's manifest file, nested in the corresponding app component (such
-as an <a href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a>
+as an <a href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity>}</a>
 element). Inside the <a
-href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code <intent-filter>}</a>,
+href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code &lt;intent-filter>}</a>,
 you can specify the type of intents to accept using one or more
 of these three elements:</p>
 
 <dl>
-<dt><a href="{@docRoot}guide/topics/manifest/action-element.html">{@code <action>}</a></dt>
+<dt><a href="{@docRoot}guide/topics/manifest/action-element.html">{@code &lt;action>}</a></dt>
   <dd>Declares the intent action accepted, in the {@code name} attribute. The value
   must be the literal string value of an action, not the class constant.</dd>
-<dt><a href="{@docRoot}guide/topics/manifest/data-element.html">{@code <data>}</a></dt>
+<dt><a href="{@docRoot}guide/topics/manifest/data-element.html">{@code &lt;data>}</a></dt>
   <dd>Declares the type of data accepted, using one or more attributes that specify various
   aspects of the data URI (<code>scheme</code>, <code>host</code>, <code>port</code>,
-  <code>path</code>, etc.) and MIME type.</dd>
-<dt><a href="{@docRoot}guide/topics/manifest/category-element.html">{@code <category>}</a></dt>
+  <code>path</code>) and MIME type.</dd>
+<dt><a href="{@docRoot}guide/topics/manifest/category-element.html">{@code &lt;category>}</a></dt>
   <dd>Declares the intent category accepted, in the {@code name} attribute. The value
   must be the literal string value of an action, not the class constant.
 
-  <p class="note"><strong>Note:</strong> In order to receive implicit intents, you
-  <strong>must include</strong> the
+  <p class="note"><strong>Note:</strong> To receive implicit intents, you
+  <em>must include</em> the
   {@link android.content.Intent#CATEGORY_DEFAULT} category in the intent filter. The methods
   {@link android.app.Activity#startActivity startActivity()} and
   {@link android.app.Activity#startActivityForResult startActivityForResult()} treat all intents
@@ -515,12 +523,12 @@
 &lt;/activity>
 </pre>
 
-<p>It's okay to create a filter that includes more than one instance of
-<a href="{@docRoot}guide/topics/manifest/action-element.html">{@code <action>}</a>,
-<a href="{@docRoot}guide/topics/manifest/data-element.html">{@code <data>}</a>, or
-<a href="{@docRoot}guide/topics/manifest/category-element.html">{@code <category>}</a>.
-If you do, you simply need to be certain that the component can handle any and all combinations
-of those filter elements.</p>
+<p>You can create a filter that includes more than one instance of
+<a href="{@docRoot}guide/topics/manifest/action-element.html">{@code &lt;action>}</a>,
+<a href="{@docRoot}guide/topics/manifest/data-element.html">{@code &lt;data>}</a>, or
+<a href="{@docRoot}guide/topics/manifest/category-element.html">{@code &lt;category>}</a>.
+If you do, you need to be certain that the component can handle any and all
+combinations of those filter elements.</p>
 
 <p>When you want to handle multiple kinds of intents, but only in specific combinations of
 action, data, and category type, then you need to create multiple intent filters.</p>
@@ -569,8 +577,8 @@
 
 <h3 id="ExampleFilters">Example filters</h3>
 
-<p>To better understand some of the intent filter behaviors, look at the following snippet
-from the manifest file of a social-sharing app.</p>
+<p>To demonstrate some of the intent filter behaviors, here is an example
+from the manifest file of a social-sharing app:</p>
 
 <pre>
 &lt;activity android:name="MainActivity">
@@ -607,9 +615,9 @@
   indicates this is the main entry point and does not expect any intent data.</li>
   <li>The {@link android.content.Intent#CATEGORY_LAUNCHER} category indicates that this activity's
   icon should be placed in the system's app launcher. If the <a
-  href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element
+  href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity>}</a> element
   does not specify an icon with {@code icon}, then the system uses the icon from the <a
-  href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>}</a>
+  href="{@docRoot}guide/topics/manifest/application-element.html">{@code &lt;application>}</a>
   element.</li>
 </ul>
 <p>These two must be paired together in order for the activity to appear in the app launcher.</p>
@@ -620,7 +628,7 @@
 intent matching one of the two intent filters.</p>
 
 <p class="note"><strong>Note:</strong> The MIME type,
-<a href="https://developers.google.com/panorama/android/">{@code
+<a href="https://developers.google.com/panorama/android/" class="external-link">{@code
 application/vnd.google.panorama360+jpg}</a>, is a special data type that specifies
 panoramic photos, which you can handle with the <a
 href="{@docRoot}reference/com/google/android/gms/panorama/package-summary.html">Google
@@ -638,7 +646,7 @@
 
 
 
-<h2 id="PendingIntent">Using a Pending Intent</h2>
+<h2 id="PendingIntent">Using a pending intent</h2>
 
 <p>A {@link android.app.PendingIntent} object is a wrapper around an {@link
 android.content.Intent} object. The primary purpose of a {@link android.app.PendingIntent}
@@ -646,25 +654,25 @@
 to use the contained {@link android.content.Intent} as if it were executed from your
 app's own process.</p>
 
-<p>Major use cases for a pending intent include:</p>
+<p>Major use cases for a pending intent include the following:</p>
 <ul>
-  <li>Declare an intent to be executed when the user performs an action with your <a
+  <li>Declaring an intent to be executed when the user performs an action with your <a
   href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Notification</a>
   (the Android system's {@link android.app.NotificationManager}
   executes the {@link android.content.Intent}).
-  <li>Declare an intent to be executed when the user performs an action with your
+  <li>Declaring an intent to be executed when the user performs an action with your
   <a href="{@docRoot}guide/topics/appwidgets/index.html">App Widget</a>
   (the Home screen app executes the {@link android.content.Intent}).
-  <li>Declare an intent to be executed at a specified time in the future (the Android
+  <li>Declaring an intent to be executed at a specified future time (the Android
   system's {@link android.app.AlarmManager} executes the {@link android.content.Intent}).
 </ul>
 
-<p>Because each {@link android.content.Intent} object is designed to be handled by a specific
+<p>Just as each {@link android.content.Intent} object is designed to be handled by a specific
 type of app component (either an {@link android.app.Activity}, a {@link android.app.Service}, or
 a {@link android.content.BroadcastReceiver}), so too must a {@link android.app.PendingIntent} be
-created with the same consideration. When using a pending intent, your app will not
+created with the same consideration. When using a pending intent, your app doesn't
 execute the intent with a call such as {@link android.content.Context#startActivity
-startActivity()}. You must instead declare the intended component type when you create the
+startActivity()}. Instead, you must declare the intended component type when you create the
 {@link android.app.PendingIntent} by calling the respective creator method:</p>
 
 <ul>
@@ -677,14 +685,14 @@
 </ul>
 
 <p>Unless your app is <em>receiving</em> pending intents from other apps,
-the above methods to create a {@link android.app.PendingIntent} are the only
-{@link android.app.PendingIntent} methods you'll probably ever need.</p>
+the above methods to create a {@link android.app.PendingIntent} are probably the only
+{@link android.app.PendingIntent} methods you'll ever need.</p>
 
 <p>Each method takes the current app {@link android.content.Context}, the
 {@link android.content.Intent} you want to wrap, and one or more flags that specify
 how the intent should be used (such as whether the intent can be used more than once).</p>
 
-<p>More information about using pending intents is provided with the documentation for each
+<p>For more information about using pending intents, see the documentation for each
 of the respective use cases, such as in the <a
 href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Notifications</a>
 and <a href="{@docRoot}guide/topics/appwidgets/index.html">App Widgets</a> API guides.</p>
@@ -695,27 +703,27 @@
 
 
 
-<h2 id="Resolution">Intent Resolution</h2>
+<h2 id="Resolution">Intent resolution</h2>
 
 
 <p>When the system receives an implicit intent to start an activity, it searches for the
-best activity for the intent by comparing the intent to intent filters based on three aspects:</p>
+best activity for the intent by comparing the it to intent filters based on three aspects:</p>
 
 <ul>
-  <li>The intent action
-  <li>The intent data (both URI and data type)
-  <li>The intent category
+  <li>Action.
+  <li>Data (both URI and data type).
+  <li>Category.
 </ul>
 
-<p>The following sections describe how intents are matched to the appropriate component(s)
-in terms of how the intent filter is declared in an app's manifest file.</p>
+<p>The following sections describe how intents are matched to the appropriate components
+according to the intent filter declaration in an app's manifest file.</p>
 
 
 <h3 id="ActionTest">Action test</h3>
 
 <p>To specify accepted intent actions, an intent filter can declare zero or more
 <a href="{@docRoot}guide/topics/manifest/action-element.html">{@code
-<action>}</a> elements.  For example:</p>
+&lt;action&gt;}</a> elements, as shown in the following example:</p>
 
 <pre>
 &lt;intent-filter&gt;
@@ -725,13 +733,13 @@
 &lt;/intent-filter&gt;
 </pre>
 
-<p>To get through this filter, the action specified in the {@link android.content.Intent}
+<p>To pass this filter, the action specified in the {@link android.content.Intent}
   must match one of the actions listed in the filter.</p>
 
 <p>If the filter does not list any actions, there is nothing for an
 intent to match, so all intents fail the test. However, if an {@link android.content.Intent}
-does not specify an action, it will pass the test (as long as the filter
-contains at least one action).</p>
+does not specify an action, it passes the test as long as the filter
+contains at least one action.</p>
 
 
 
@@ -739,7 +747,7 @@
 
 <p>To specify accepted intent categories, an intent filter can declare zero or more
 <a href="{@docRoot}guide/topics/manifest/category-element.html">{@code
-<category>}</a> elements.  For example:</p>
+<category>}</a> elements, as shown in the following example:</p>
 
 <pre>
 &lt;intent-filter&gt;
@@ -752,17 +760,17 @@
 <p>For an intent to pass the category test, every category in the {@link android.content.Intent}
 must match a category in the filter. The reverse is not necessary&mdash;the intent filter may
 declare more categories than are specified in the {@link android.content.Intent} and the
-{@link android.content.Intent} will still pass. Therefore, an intent with no categories should
-always pass this test, regardless of what categories are declared in the filter.</p>
+{@link android.content.Intent} still passes. Therefore, an intent with no categories
+always passes this test, regardless of what categories are declared in the filter.</p>
 
 <p class="note"><strong>Note:</strong>
-Android automatically applies the the {@link android.content.Intent#CATEGORY_DEFAULT} category
+Android automatically applies the {@link android.content.Intent#CATEGORY_DEFAULT} category
 to all implicit intents passed to {@link
 android.content.Context#startActivity startActivity()} and {@link
 android.app.Activity#startActivityForResult startActivityForResult()}.
-So if you want your activity to receive implicit intents, it must
-include a category for {@code "android.intent.category.DEFAULT"} in its intent filters (as
-shown in the previous {@code <intent-filter>} example.</p>
+If you want your activity to receive implicit intents, it must
+include a category for {@code "android.intent.category.DEFAULT"} in its intent filters, as
+shown in the previous {@code &lt;intent-filter>} example.</p>
 
 
 
@@ -770,7 +778,7 @@
 
 <p>To specify accepted intent data, an intent filter can declare zero or more
 <a href="{@docRoot}guide/topics/manifest/data-element.html">{@code
-<data>}</a> elements.  For example:</p>
+&lt;data&gt;}</a> elements, as shown in the following example:</p>
 
 <pre>
 &lt;intent-filter&gt;
@@ -781,15 +789,16 @@
 </pre>
 
 <p>Each <code><a href="{@docRoot}guide/topics/manifest/data-element.html">&lt;data&gt;</a></code>
-element can specify a URI structure and a data type (MIME media type).  There are separate
-attributes &mdash; {@code scheme}, {@code host}, {@code port},
-and {@code path} &mdash; for each part of the URI:
+element can specify a URI structure and a data type (MIME media type).
+ Each part of the URI is a separate
+attribute: {@code scheme}, {@code host}, {@code port},
+and {@code path}:
 </p>
 
-<p style="margin-left: 2em">{@code <scheme>://<host>:<port>/<path>}</p>
+<p style="margin-left: 2em">{@code &lt;scheme>://&lt;host>:&lt;port>/&lt;path>}</p>
 
 <p>
-For example:
+The following example shows possible values for these attributes:
 </p>
 
 <p style="margin-left: 2em">{@code content://com.example.project:200/folder/subfolder/etc}</p>
@@ -799,7 +808,7 @@
 </p>
 
 <p>Each of these attributes is optional in a <a
-href="{@docRoot}guide/topics/manifest/data-element.html">{@code <data>}</a> element,
+href="{@docRoot}guide/topics/manifest/data-element.html">{@code &lt;data>}</a> element,
 but there are linear dependencies:</p>
 <ul>
   <li>If a scheme is not specified, the host is ignored.</li>
@@ -842,17 +851,17 @@
 either if its URI matches a URI in the filter or if it has a {@code content:}
 or {@code file:} URI and the filter does not specify a URI.  In other words,
 a component is presumed to support {@code content:} and {@code file:} data if
-its filter lists <em>only</em> a MIME type.</p></li>
+its filter lists <em>only</em> a MIME type.</li>
 </ol>
 
 <p>
 This last rule, rule (d), reflects the expectation
 that components are able to get local data from a file or content provider.
-Therefore, their filters can list just a data type and do not need to explicitly
+Therefore, their filters can list just a data type and don't need to explicitly
 name the {@code content:} and {@code file:} schemes.
-This is a typical case.  A <a
-href="{@docRoot}guide/topics/manifest/data-element.html">{@code <data>}</a> element
-like the following, for example, tells Android that the component can get image data from a content
+The following example shows a typical case in which a <a
+href="{@docRoot}guide/topics/manifest/data-element.html">{@code &lt;data>}</a> element
+ tells Android that the component can get image data from a content
 provider and display it:
 </p>
 
@@ -863,14 +872,15 @@
 &lt;/intent-filter&gt;</pre>
 
 <p>
-Because most available data is dispensed by content providers, filters that
-specify a data type but not a URI are perhaps the most common.
+Filters that
+specify a data type but not a URI are perhaps the most common because most available
+ data is dispensed by content providers.
 </p>
 
 <p>
-Another common configuration is filters with a scheme and a data type.  For
+Another common configuration is a filter with a scheme and a data type.  For
 example, a <a
-href="{@docRoot}guide/topics/manifest/data-element.html">{@code <data>}</a>
+href="{@docRoot}guide/topics/manifest/data-element.html">{@code &lt;data>}</a>
 element like the following tells Android that
 the component can retrieve video data from the network in order to perform the action:
 </p>
@@ -894,7 +904,7 @@
 
 <p>Your application can use intent matching in a similar way.
 The {@link android.content.pm.PackageManager} has a set of {@code query...()}
-methods that return all components that can accept a particular intent, and
+methods that return all components that can accept a particular intent and
 a similar series of {@code resolve...()} methods that determine the best
 component to respond to an intent.  For example,
 {@link android.content.pm.PackageManager#queryIntentActivities
@@ -907,7 +917,3 @@
 {@link android.content.pm.PackageManager#queryBroadcastReceivers
 queryBroadcastReceivers()}, for broadcast receivers.
 </p>
-
-
-
-
diff --git a/docs/html/guide/components/services.jd b/docs/html/guide/components/services.jd
index e646a17..a7ed718 100644
--- a/docs/html/guide/components/services.jd
+++ b/docs/html/guide/components/services.jd
@@ -5,11 +5,11 @@
 <ol id="qv">
 <h2>In this document</h2>
 <ol>
-<li><a href="#Basics">The Basics</a></li>
+<li><a href="#Basics">The basics</a></li>
 <ol>
   <li><a href="#Declaring">Declaring a service in the manifest</a></li>
 </ol>
-<li><a href="#CreatingAService">Creating a Started Service</a>
+<li><a href="#CreatingAService">Creating a started service</a>
   <ol>
     <li><a href="#ExtendingIntentService">Extending the IntentService class</a></li>
     <li><a href="#ExtendingService">Extending the Service class</a></li>
@@ -17,10 +17,10 @@
     <li><a href="#Stopping">Stopping a service</a></li>
   </ol>
 </li>
-<li><a href="#CreatingBoundService">Creating a Bound Service</a></li>
-<li><a href="#Notifications">Sending Notifications to the User</a></li>
-<li><a href="#Foreground">Running a Service in the Foreground</a></li>
-<li><a href="#Lifecycle">Managing the Lifecycle of a Service</a>
+<li><a href="#CreatingBoundService">Creating a bound service</a></li>
+<li><a href="#Notifications">Sending notifications to the user</a></li>
+<li><a href="#Foreground">Running a service in the foreground</a></li>
+<li><a href="#Lifecycle">Managing the lifecycle of a service</a>
 <ol>
   <li><a href="#LifecycleCallbacks">Implementing the lifecycle callbacks</a></li>
 </ol>
@@ -48,70 +48,80 @@
 
 </div>
 
-
 <p>A {@link android.app.Service} is an application component that can perform
-long-running operations in the background and does not provide a user interface. Another
-application component can start a service and it will continue to run in the background even if the
+long-running operations in the background, and it does not provide a user interface. Another
+application component can start a service, and it continues to run in the background even if the
 user switches to another application. Additionally, a component can bind to a service to
-interact with it and even perform interprocess communication (IPC). For example, a service might
+interact with it and even perform interprocess communication (IPC). For example, a service can
 handle network transactions, play music, perform file I/O, or interact with a content provider, all
 from the background.</p>
 
-<p>A service can essentially take two forms:</p>
+<p>These are the three different types of services:</p>
 
 <dl>
+  <dt>Scheduled</dt>
+  <dd>A service is <em>scheduled</em> when an API such as the {@link android.app.job.JobScheduler},
+  introduced in Android 5.0 (API level 21), launches the service. You can use the
+  {@link android.app.job.JobScheduler} by registering jobs and specifying their requirements for
+  network and timing. The system then gracefully schedules the jobs for execution at the
+  appropriate times. The {@link android.app.job.JobScheduler} provides many methods to define
+  service-execution conditions.
+    <p class="note"><strong>Note:</strong> If your app targets Android 5.0 (API level 21), Google
+    recommends that you use the {@link android.app.job.JobScheduler} to execute background
+    services. For more information about using this class, see the
+    {@link android.app.job.JobScheduler} reference documentation.</p></dd>
   <dt>Started</dt>
-  <dd>A service is "started" when an application component (such as an activity) starts it by
-calling {@link android.content.Context#startService startService()}. Once started, a service
-can run in the background indefinitely, even if the component that started it is destroyed. Usually,
-a started service performs a single operation and does not return a result to the caller.
-For example, it might download or upload a file over the network. When the operation is done, the
-service should stop itself.</dd>
+  <dd>A service is <em>started</em> when an application component (such as an activity)
+  calls {@link android.content.Context#startService startService()}. After it's started, a
+  service can run in the background indefinitely, even if the component that started it is
+  destroyed. Usually, a started service performs a single operation and does not return a result to
+  the caller. For example, it can download or upload a file over the network. When the operation is
+  complete, the service should stop itself.</dd>
   <dt>Bound</dt>
-  <dd>A service is "bound" when an application component binds to it by calling {@link
-android.content.Context#bindService bindService()}. A bound service offers a client-server
-interface that allows components to interact with the service, send requests, get results, and even
-do so across processes with interprocess communication (IPC). A bound service runs only as long as
-another application component is bound to it. Multiple components can bind to the service at once,
-but when all of them unbind, the service is destroyed.</dd>
+  <dd>A service is <em>bound</em> when an application component binds to it by calling {@link
+  android.content.Context#bindService bindService()}. A bound service offers a client-server
+  interface that allows components to interact with the service, send requests, receive results,
+  and even do so across processes with interprocess communication (IPC). A bound service runs only
+  as long as another application component is bound to it. Multiple components can bind to the
+  service at once, but when all of them unbind, the service is destroyed.</dd>
 </dl>
 
-<p>Although this documentation generally discusses these two types of services separately, your
-service can work both ways&mdash;it can be started (to run indefinitely) and also allow binding.
-It's simply a matter of whether you implement a couple callback methods: {@link
+<p>Although this documentation generally discusses started and bound services separately,
+your service can work both ways&mdash;it can be started (to run indefinitely) and also allow
+binding. It's simply a matter of whether you implement a couple of callback methods: {@link
 android.app.Service#onStartCommand onStartCommand()} to allow components to start it and {@link
 android.app.Service#onBind onBind()} to allow binding.</p>
 
 <p>Regardless of whether your application is started, bound, or both, any application component
-can use the service (even from a separate application), in the same way that any component can use
+can use the service (even from a separate application) in the same way that any component can use
 an activity&mdash;by starting it with an {@link android.content.Intent}. However, you can declare
-the service as private, in the manifest file, and block access from other applications. This is
-discussed more in the section about <a href="#Declaring">Declaring the service in the
+the service as <em>private</em> in the manifest file and block access from other applications.
+This is discussed more in the section about <a href="#Declaring">Declaring the service in the
 manifest</a>.</p>
 
 <p class="caution"><strong>Caution:</strong> A service runs in the
-main thread of its hosting process&mdash;the service does <strong>not</strong> create its own thread
-and does <strong>not</strong> run in a separate process (unless you specify otherwise). This means
-that, if your service is going to do any CPU intensive work or blocking operations (such as MP3
-playback or networking), you should create a new thread within the service to do that work. By using
-a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the
-application's main thread can remain dedicated to user interaction with your activities.</p>
+main thread of its hosting process; the service does <strong>not</strong> create its own
+thread and does <strong>not</strong> run in a separate process unless you specify otherwise. If
+your service is going to perform any CPU-intensive work or blocking operations, such as MP3
+playback or networking, you should create a new thread within the service to complete that work.
+By using a separate thread, you can reduce the risk of Application Not Responding (ANR) errors,
+and the application's main thread can remain dedicated to user interaction with your
+activities.</p>
 
-
-<h2 id="Basics">The Basics</h2>
+<h2 id="Basics">The basics</h2>
 
 <div class="sidebox-wrapper">
 <div class="sidebox">
   <h3>Should you use a service or a thread?</h3>
-  <p>A service is simply a component that can run in the background even when the user is not
-interacting with your application. Thus, you should create a service only if that is what you
+  <p>A service is simply a component that can run in the background, even when the user is not
+interacting with your application, so you should create a service only if that is what you
 need.</p>
-  <p>If you need to perform work outside your main thread, but only while the user is interacting
-with your application, then you should probably instead create a new thread and not a service. For
-example, if you want to play some music, but only while your activity is running, you might create
+  <p>If you must perform work outside of your main thread, but only while the user is interacting
+with your application, you should instead create a new thread. For example, if you want to
+play some music, but only while your activity is running, you might create
 a thread in {@link android.app.Activity#onCreate onCreate()}, start running it in {@link
-android.app.Activity#onStart onStart()}, then stop it in {@link android.app.Activity#onStop
-onStop()}. Also consider using {@link android.os.AsyncTask} or {@link android.os.HandlerThread},
+android.app.Activity#onStart onStart()}, and stop it in {@link android.app.Activity#onStop
+onStop()}. Also consider using {@link android.os.AsyncTask} or {@link android.os.HandlerThread}
 instead of the traditional {@link java.lang.Thread} class. See the <a
 href="{@docRoot}guide/components/processes-and-threads.html#Threads">Processes and
 Threading</a> document for more information about threads.</p>
@@ -121,78 +131,81 @@
 </div>
 </div>
 
-<p>To create a service, you must create a subclass of {@link android.app.Service} (or one
-of its existing subclasses). In your implementation, you need to override some callback methods that
-handle key aspects of the service lifecycle and provide a mechanism for components to bind to
-the service, if appropriate. The most important callback methods you should override are:</p>
+<p>To create a service, you must create a subclass of {@link android.app.Service} or use one
+of its existing subclasses. In your implementation, you must override some callback methods that
+handle key aspects of the service lifecycle and provide a mechanism that allows the components to
+bind to the service, if appropriate. These are the most important callback methods that you should
+override:</p>
 
 <dl>
   <dt>{@link android.app.Service#onStartCommand onStartCommand()}</dt>
-    <dd>The system calls this method when another component, such as an activity,
-requests that the service be started, by calling {@link android.content.Context#startService
-startService()}. Once this method executes, the service is started and can run in the
+    <dd>The system invokes this method by calling {@link android.content.Context#startService
+startService()} when another component (such as an activity) requests that the service be started.
+When this method executes, the service is started and can run in the
 background indefinitely. If you implement this, it is your responsibility to stop the service when
-its work is done, by calling {@link android.app.Service#stopSelf stopSelf()} or {@link
-android.content.Context#stopService stopService()}. (If you only want to provide binding, you don't
-need to implement this method.)</dd>
+its work is complete by calling {@link android.app.Service#stopSelf stopSelf()} or {@link
+android.content.Context#stopService stopService()}. If you only want to provide binding, you don't
+need to implement this method.</dd>
   <dt>{@link android.app.Service#onBind onBind()}</dt>
-    <dd>The system calls this method when another component wants to bind with the
-service (such as to perform RPC), by calling {@link android.content.Context#bindService
-bindService()}. In your implementation of this method, you must provide an interface that clients
-use to communicate with the service, by returning an {@link android.os.IBinder}. You must always
-implement this method, but if you don't want to allow binding, then you should return null.</dd>
+    <dd>The system invokes this method by calling {@link android.content.Context#bindService
+bindService()} when another component wants to bind with the service (such as to perform RPC).
+In your implementation of this method, you must provide an interface that clients
+use to communicate with the service by returning an {@link android.os.IBinder}. You must always
+implement this method; however, if you don't want to allow binding, you should return
+null.</dd>
   <dt>{@link android.app.Service#onCreate()}</dt>
-    <dd>The system calls this method when the service is first created, to perform one-time setup
-procedures (before it calls either {@link android.app.Service#onStartCommand onStartCommand()} or
+    <dd>The system invokes this method to perform one-time setup procedures when the service is
+initially created (before it calls either
+{@link android.app.Service#onStartCommand onStartCommand()} or
 {@link android.app.Service#onBind onBind()}). If the service is already running, this method is not
 called.</dd>
   <dt>{@link android.app.Service#onDestroy()}</dt>
-    <dd>The system calls this method when the service is no longer used and is being destroyed.
+    <dd>The system invokes this method when the service is no longer used and is being destroyed.
 Your service should implement this to clean up any resources such as threads, registered
-listeners, receivers, etc. This is the last call the service receives.</dd>
+listeners, or receivers. This is the last call that the service receives.</dd>
 </dl>
 
 <p>If a component starts the service by calling {@link
 android.content.Context#startService startService()} (which results in a call to {@link
-android.app.Service#onStartCommand onStartCommand()}), then the service
-remains running until it stops itself with {@link android.app.Service#stopSelf()} or another
+android.app.Service#onStartCommand onStartCommand()}), the service
+continues to run until it stops itself with {@link android.app.Service#stopSelf()} or another
 component stops it by calling {@link android.content.Context#stopService stopService()}.</p>
 
 <p>If a component calls
-{@link android.content.Context#bindService bindService()} to create the service (and {@link
-android.app.Service#onStartCommand onStartCommand()} is <em>not</em> called), then the service runs
-only as long as the component is bound to it. Once the service is unbound from all clients, the
-system destroys it.</p>
+{@link android.content.Context#bindService bindService()} to create the service and {@link
+android.app.Service#onStartCommand onStartCommand()} is <em>not</em> called, the service runs
+only as long as the component is bound to it. After the service is unbound from all of its clients,
+the system destroys it.</p>
 
-<p>The Android system will force-stop a service only when memory is low and it must recover system
+<p>The Android system force-stops a service only when memory is low and it must recover system
 resources for the activity that has user focus. If the service is bound to an activity that has user
-focus, then it's less likely to be killed, and if the service is declared to <a
-href="#Foreground">run in the foreground</a> (discussed later), then it will almost never be killed.
-Otherwise, if the service was started and is long-running, then the system will lower its position
-in the list of background tasks over time and the service will become highly susceptible to
-killing&mdash;if your service is started, then you must design it to gracefully handle restarts
+focus, it's less likely to be killed; if the service is declared to <a
+href="#Foreground">run in the foreground</a>, it's rarely killed.
+If the service is started and is long-running, the system lowers its position
+in the list of background tasks over time, and the service becomes highly susceptible to
+killing&mdash;if your service is started, you must design it to gracefully handle restarts
 by the system. If the system kills your service, it restarts it as soon as resources become
-available again (though this also depends on the value you return from {@link
-android.app.Service#onStartCommand onStartCommand()}, as discussed later). For more information
+available, but this also depends on the value that you return from {@link
+android.app.Service#onStartCommand onStartCommand()}. For more information
 about when the system might destroy a service, see the <a
 href="{@docRoot}guide/components/processes-and-threads.html">Processes and Threading</a>
 document.</p>
 
-<p>In the following sections, you'll see how you can create each type of service and how to use
-it from other application components.</p>
-
-
+<p>In the following sections, you'll see how you can create the
+{@link android.content.Context#startService startService()} and
+{@link android.content.Context#bindService bindService()} service methods, as well as how to use
+them from other application components.</p>
 
 <h3 id="Declaring">Declaring a service in the manifest</h3>
 
-<p>Like activities (and other components), you must declare all services in your application's
-manifest file.</p>
+<p>You must declare all services in your application's
+manifest file, just as you do for activities and other components.</p>
 
 <p>To declare your service, add a <a
-href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> element
+href="{@docRoot}guide/topics/manifest/service-element.html">{@code &lt;service&gt;}</a> element
 as a child of the <a
-href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>}</a>
-element. For example:</p>
+href="{@docRoot}guide/topics/manifest/application-element.html">{@code &lt;application&gt;}</a>
+element. Here is an example:</p>
 
 <pre>
 &lt;manifest ... &gt;
@@ -205,48 +218,44 @@
 </pre>
 
 <p>See the <a
-href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> element
+href="{@docRoot}guide/topics/manifest/service-element.html">{@code &lt;service&gt;}</a> element
 reference for more information about declaring your service in the manifest.</p>
 
-<p>There are other attributes you can include in the <a
-href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> element to
-define properties such as permissions required to start the service and the process in
+<p>There are other attributes that you can include in the <a
+href="{@docRoot}guide/topics/manifest/service-element.html">{@code &lt;service&gt;}</a> element to
+define properties such as the permissions that are required to start the service and the process in
 which the service should run. The <a
 href="{@docRoot}guide/topics/manifest/service-element.html#nm">{@code android:name}</a>
-attribute is the only required attribute&mdash;it specifies the class name of the service. Once
-you publish your application, you should not change this name, because if you do, you risk breaking
+attribute is the only required attribute&mdash;it specifies the class name of the service. After
+you publish your application, leave this name unchanged to avoid the risk of breaking
 code due to dependence on explicit intents to start or bind the service (read the blog post, <a
 href="http://android-developers.blogspot.com/2011/06/things-that-cannot-change.html">Things
 That Cannot Change</a>).
 
-<p>To ensure your app is secure, <strong>always use an explicit intent when starting or binding
-your {@link android.app.Service}</strong> and do not declare intent filters for the service. If
-it's critical that you allow for some amount of ambiguity as to which service starts, you can
-supply intent filters for your services and exclude the component name from the {@link
-android.content.Intent}, but you then must set the package for the intent with {@link
-android.content.Intent#setPackage setPackage()}, which provides sufficient disambiguation for the
-target service.</p>
+<p class="caution"><strong>Caution</strong>: To ensure that your app is secure, always use an
+explicit intent when starting a {@link android.app.Service} and do not declare intent filters for
+your services. Using an implicit intent to start a service is a security hazard because you cannot
+be certain of the service that will respond to the intent, and the user cannot see which service
+starts. Beginning with Android 5.0 (API level 21), the system throws an exception if you call
+{@link android.content.Context#bindService bindService()} with an implicit intent.</p>
 
-<p>Additionally, you can ensure that your service is available to only your app by
+<p>You can ensure that your service is available to only your app by
 including the <a
 href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code android:exported}</a>
-attribute and setting it to {@code "false"}. This effectively stops other apps from starting your
+attribute and setting it to {@code false}. This effectively stops other apps from starting your
 service, even when using an explicit intent.</p>
 
-
-
-
-<h2 id="CreatingStartedService">Creating a Started Service</h2>
+<h2 id="CreatingStartedService">Creating a started service</h2>
 
 <p>A started service is one that another component starts by calling {@link
-android.content.Context#startService startService()}, resulting in a call to the service's
+android.content.Context#startService startService()}, which results in a call to the service's
 {@link android.app.Service#onStartCommand onStartCommand()} method.</p>
 
 <p>When a service is started, it has a lifecycle that's independent of the
-component that started it and the service can run in the background indefinitely, even if
+component that started it. The service can run in the background indefinitely, even if
 the component that started it is destroyed. As such, the service should stop itself when its job
-is done by calling {@link android.app.Service#stopSelf stopSelf()}, or another component can stop it
-by calling {@link android.content.Context#stopService stopService()}.</p>
+is complete by calling {@link android.app.Service#stopSelf stopSelf()}, or another component can
+stop it by calling {@link android.content.Context#stopService stopService()}.</p>
 
 <p>An application component such as an activity can start the service by calling {@link
 android.content.Context#startService startService()} and passing an {@link android.content.Intent}
@@ -254,65 +263,65 @@
 this {@link android.content.Intent} in the {@link android.app.Service#onStartCommand
 onStartCommand()} method.</p>
 
-<p>For instance, suppose an activity needs to save some data to an online database. The activity can
-start a companion service and deliver it the data to save by passing an intent to {@link
+<p>For instance, suppose an activity needs to save some data to an online database. The activity
+can start a companion service and deliver it the data to save by passing an intent to {@link
 android.content.Context#startService startService()}. The service receives the intent in {@link
-android.app.Service#onStartCommand onStartCommand()}, connects to the Internet and performs the
-database transaction. When the transaction is done, the service stops itself and it is
+android.app.Service#onStartCommand onStartCommand()}, connects to the Internet, and performs the
+database transaction. When the transaction is complete, the service stops itself and is
 destroyed.</p>
 
 <p class="caution"><strong>Caution:</strong> A service runs in the same process as the application
-in which it is declared and in the main thread of that application, by default. So, if your service
+in which it is declared and in the main thread of that application by default. If your service
 performs intensive or blocking operations while the user interacts with an activity from the same
-application, the service will slow down activity performance. To avoid impacting application
-performance, you should start a new thread inside the service.</p>
+application, the service slows down activity performance. To avoid impacting application
+performance, start a new thread inside the service.</p>
 
 <p>Traditionally, there are two classes you can extend to create a started service:</p>
+
 <dl>
   <dt>{@link android.app.Service}</dt>
-  <dd>This is the base class for all services. When you extend this class, it's important that
-you create a new thread in which to do all the service's work, because the service uses your
-application's main thread, by default, which could slow the performance of any activity your
+  <dd>This is the base class for all services. When you extend this class, it's important to
+create a new thread in which the service can complete all of its work; the service uses your
+application's main thread by default, which can slow the performance of any activity that your
 application is running.</dd>
   <dt>{@link android.app.IntentService}</dt>
-  <dd>This is a subclass of {@link android.app.Service} that uses a worker thread to handle all
-start requests, one at a time. This is the best option if you don't require that your service
-handle multiple requests simultaneously. All you need to do is implement {@link
+  <dd>This is a subclass of {@link android.app.Service} that uses a worker thread to handle all of
+the start requests, one at a time. This is the best option if you don't require that your service
+handle multiple requests simultaneously. Implement {@link
 android.app.IntentService#onHandleIntent onHandleIntent()}, which receives the intent for each
-start request so you can do the background work.</dd>
+start request so that you can complete the background work.</dd>
 </dl>
 
 <p>The following sections describe how you can implement your service using either one for these
 classes.</p>
 
-
 <h3 id="ExtendingIntentService">Extending the IntentService class</h3>
 
-<p>Because most started services don't need to handle multiple requests simultaneously
-(which can actually be a dangerous multi-threading scenario), it's probably best if you
+<p>Because most of the started services don't need to handle multiple requests simultaneously
+(which can actually be a dangerous multi-threading scenario), it's best that you
 implement your service using the {@link android.app.IntentService} class.</p>
 
-<p>The {@link android.app.IntentService} does the following:</p>
+<p>The {@link android.app.IntentService} class does the following:</p>
 
 <ul>
-  <li>Creates a default worker thread that executes all intents delivered to {@link
-android.app.Service#onStartCommand onStartCommand()} separate from your application's main
+  <li>It creates a default worker thread that executes all of the intents that are delivered to
+{@link android.app.Service#onStartCommand onStartCommand()}, separate from your application's main
 thread.</li>
   <li>Creates a work queue that passes one intent at a time to your {@link
 android.app.IntentService#onHandleIntent onHandleIntent()} implementation, so you never have to
 worry about multi-threading.</li>
-  <li>Stops the service after all start requests have been handled, so you never have to call
+  <li>Stops the service after all of the start requests are handled, so you never have to call
 {@link android.app.Service#stopSelf}.</li>
-  <li>Provides default implementation of {@link android.app.IntentService#onBind onBind()} that
-returns null.</li>
+  <li>Provides a default implementation of {@link android.app.IntentService#onBind onBind()}
+  that returns null.</li>
   <li>Provides a default implementation of {@link android.app.IntentService#onStartCommand
 onStartCommand()} that sends the intent to the work queue and then to your {@link
 android.app.IntentService#onHandleIntent onHandleIntent()} implementation.</li>
 </ul>
 
-<p>All this adds up to the fact that all you need to do is implement {@link
-android.app.IntentService#onHandleIntent onHandleIntent()} to do the work provided by the
-client. (Though, you also need to provide a small constructor for the service.)</p>
+<p>To complete the work that is provided by the client, implement {@link
+android.app.IntentService#onHandleIntent onHandleIntent()}.
+However, you also need to provide a small constructor for the service.</p>
 
 <p>Here's an example implementation of {@link android.app.IntentService}:</p>
 
@@ -352,12 +361,12 @@
 <p>If you decide to also override other callback methods, such as {@link
 android.app.IntentService#onCreate onCreate()}, {@link
 android.app.IntentService#onStartCommand onStartCommand()}, or {@link
-android.app.IntentService#onDestroy onDestroy()}, be sure to call the super implementation, so
+android.app.IntentService#onDestroy onDestroy()}, be sure to call the super implementation so
 that the {@link android.app.IntentService} can properly handle the life of the worker thread.</p>
 
 <p>For example, {@link android.app.IntentService#onStartCommand onStartCommand()} must return
-the default implementation (which is how the intent gets delivered to {@link
-android.app.IntentService#onHandleIntent onHandleIntent()}):</p>
+the default implementation, which is how the intent is delivered to {@link
+android.app.IntentService#onHandleIntent onHandleIntent()}:</p>
 
 <pre>
 &#64;Override
@@ -369,22 +378,21 @@
 
 <p>Besides {@link android.app.IntentService#onHandleIntent onHandleIntent()}, the only method
 from which you don't need to call the super class is {@link android.app.IntentService#onBind
-onBind()} (but you only need to implement that if your service allows binding).</p>
+onBind()}. You need to implement this only if your service allows binding.</p>
 
 <p>In the next section, you'll see how the same kind of service is implemented when extending
-the base {@link android.app.Service} class, which is a lot more code, but which might be
+the base {@link android.app.Service} class, which uses more code, but might be
 appropriate if you need to handle simultaneous start requests.</p>
 
-
 <h3 id="ExtendingService">Extending the Service class</h3>
 
-<p>As you saw in the previous section, using {@link android.app.IntentService} makes your
+<p>Using {@link android.app.IntentService} makes your
 implementation of a started service very simple. If, however, you require your service to
-perform multi-threading (instead of processing start requests through a work queue), then you
+perform multi-threading (instead of processing start requests through a work queue), you
 can extend the {@link android.app.Service} class to handle each intent.</p>
 
-<p>For comparison, the following example code is an implementation of the {@link
-android.app.Service} class that performs the exact same work as the example above using {@link
+<p>For comparison, the following example code shows an implementation of the {@link
+android.app.Service} class that performs the same work as the previous example using {@link
 android.app.IntentService}. That is, for each start request, it uses a worker thread to perform the
 job and processes only one request at a time.</p>
 
@@ -460,20 +468,20 @@
 
 <p>However, because you handle each call to {@link android.app.Service#onStartCommand
 onStartCommand()} yourself, you can perform multiple requests simultaneously. That's not what
-this example does, but if that's what you want, then you can create a new thread for each
-request and run them right away (instead of waiting for the previous request to finish).</p>
+this example does, but if that's what you want, you can create a new thread for each
+request and run them right away instead of waiting for the previous request to finish.</p>
 
 <p>Notice that the {@link android.app.Service#onStartCommand onStartCommand()} method must return an
 integer. The integer is a value that describes how the system should continue the service in the
-event that the system kills it (as discussed above, the default implementation for {@link
-android.app.IntentService} handles this for you, though you are able to modify it). The return value
+event that the system kills it. The default implementation for {@link
+android.app.IntentService} handles this for you, but you are able to modify it. The return value
 from {@link android.app.Service#onStartCommand onStartCommand()} must be one of the following
 constants:</p>
 
 <dl>
   <dt>{@link android.app.Service#START_NOT_STICKY}</dt>
     <dd>If the system kills the service after {@link android.app.Service#onStartCommand
-onStartCommand()} returns, <em>do not</em> recreate the service, unless there are pending
+onStartCommand()} returns, <em>do not</em> recreate the service unless there are pending
 intents to deliver. This is the safest option to avoid running your service when not necessary
 and when your application can simply restart any unfinished jobs.</dd>
   <dt>{@link android.app.Service#START_STICKY}</dt>
@@ -481,9 +489,9 @@
 onStartCommand()} returns, recreate the service and call {@link
 android.app.Service#onStartCommand onStartCommand()}, but <em>do not</em> redeliver the last intent.
 Instead, the system calls {@link android.app.Service#onStartCommand onStartCommand()} with a
-null intent, unless there were pending intents to start the service, in which case,
+null intent unless there are pending intents to start the service. In that case,
 those intents are delivered. This is suitable for media players (or similar services) that are not
-executing commands, but running indefinitely and waiting for a job.</dd>
+executing commands but are running indefinitely and waiting for a job.</dd>
   <dt>{@link android.app.Service#START_REDELIVER_INTENT}</dt>
     <dd>If the system kills the service after {@link android.app.Service#onStartCommand
 onStartCommand()} returns, recreate the service and call {@link
@@ -494,35 +502,35 @@
 <p>For more details about these return values, see the linked reference documentation for each
 constant.</p>
 
-
-
-<h3 id="StartingAService">Starting a Service</h3>
+<h3 id="StartingAService">Starting a service</h3>
 
 <p>You can start a service from an activity or other application component by passing an
 {@link android.content.Intent} (specifying the service to start) to {@link
 android.content.Context#startService startService()}. The Android system calls the service's {@link
 android.app.Service#onStartCommand onStartCommand()} method and passes it the {@link
-android.content.Intent}. (You should never call {@link android.app.Service#onStartCommand
-onStartCommand()} directly.)</p>
+android.content.Intent}.
+
+<p class="note"><strong>Note</strong>: Never call
+{@link android.app.Service#onStartCommand onStartCommand()} directly.</p>
 
 <p>For example, an activity can start the example service in the previous section ({@code
 HelloService}) using an explicit intent with {@link android.content.Context#startService
-startService()}:</p>
+startService()}, as shown here:</p>
 
 <pre>
 Intent intent = new Intent(this, HelloService.class);
 startService(intent);
 </pre>
 
-<p>The {@link android.content.Context#startService startService()} method returns immediately and
+<p>The {@link android.content.Context#startService startService()} method returns immediately, and
 the Android system calls the service's {@link android.app.Service#onStartCommand
 onStartCommand()} method. If the service is not already running, the system first calls {@link
-android.app.Service#onCreate onCreate()}, then calls {@link android.app.Service#onStartCommand
-onStartCommand()}.</p>
+android.app.Service#onCreate onCreate()}, and then it calls
+{@link android.app.Service#onStartCommand onStartCommand()}.</p>
 
-<p>If the service does not also provide binding, the intent delivered with {@link
+<p>If the service does not also provide binding, the intent that is delivered with {@link
 android.content.Context#startService startService()} is the only mode of communication between the
-application component and the service. However, if you want the service to send a result back, then
+application component and the service. However, if you want the service to send a result back,
 the client that starts the service can create a {@link android.app.PendingIntent} for a broadcast
 (with {@link android.app.PendingIntent#getBroadcast getBroadcast()}) and deliver it to the service
 in the {@link android.content.Intent} that starts the service. The service can then use the
@@ -533,109 +541,102 @@
 the service (with {@link android.app.Service#stopSelf stopSelf()} or {@link
 android.content.Context#stopService stopService()}) is required to stop it.</p>
 
-
 <h3 id="Stopping">Stopping a service</h3>
 
 <p>A started service must manage its own lifecycle. That is, the system does not stop or
 destroy the service unless it must recover system memory and the service
-continues to run after {@link android.app.Service#onStartCommand onStartCommand()} returns. So,
-the service must stop itself by calling {@link android.app.Service#stopSelf stopSelf()} or another
+continues to run after {@link android.app.Service#onStartCommand onStartCommand()} returns. The
+service must stop itself by calling {@link android.app.Service#stopSelf stopSelf()}, or another
 component can stop it by calling {@link android.content.Context#stopService stopService()}.</p>
 
 <p>Once requested to stop with {@link android.app.Service#stopSelf stopSelf()} or {@link
 android.content.Context#stopService stopService()}, the system destroys the service as soon as
 possible.</p>
 
-<p>However, if your service handles multiple requests to {@link
-android.app.Service#onStartCommand onStartCommand()} concurrently, then you shouldn't stop the
-service when you're done processing a start request, because you might have since received a new
+<p>If your service handles multiple requests to {@link
+android.app.Service#onStartCommand onStartCommand()} concurrently, you shouldn't stop the
+service when you're done processing a start request, as you might have received a new
 start request (stopping at the end of the first request would terminate the second one). To avoid
 this problem, you can use {@link android.app.Service#stopSelf(int)} to ensure that your request to
 stop the service is always based on the most recent start request. That is, when you call {@link
 android.app.Service#stopSelf(int)}, you pass the ID of the start request (the <code>startId</code>
 delivered to {@link android.app.Service#onStartCommand onStartCommand()}) to which your stop request
-corresponds. Then if the service received a new start request before you were able to call {@link
-android.app.Service#stopSelf(int)}, then the ID will not match and the service will not stop.</p>
+corresponds. Then, if the service receives a new start request before you are able to call {@link
+android.app.Service#stopSelf(int)}, the ID does not match and the service does not stop.</p>
 
-<p class="caution"><strong>Caution:</strong> It's important that your application stops its services
-when it's done working, to avoid wasting system resources and consuming battery power. If necessary,
-other components can stop the service by calling {@link
+<p class="caution"><strong>Caution:</strong> To avoid wasting system resources and consuming
+battery power, ensure that your application stops its services when it's done working.
+If necessary, other components can stop the service by calling {@link
 android.content.Context#stopService stopService()}. Even if you enable binding for the service,
-you must always stop the service yourself if it ever received a call to {@link
+you must always stop the service yourself if it ever receives a call to {@link
 android.app.Service#onStartCommand onStartCommand()}.</p>
 
 <p>For more information about the lifecycle of a service, see the section below about <a
 href="#Lifecycle">Managing the Lifecycle of a Service</a>.</p>
 
-
-
-<h2 id="CreatingBoundService">Creating a Bound Service</h2>
+<h2 id="CreatingBoundService">Creating a bound service</h2>
 
 <p>A bound service is one that allows application components to bind to it by calling {@link
-android.content.Context#bindService bindService()} in order to create a long-standing connection
-(and generally does not allow components to <em>start</em> it by calling {@link
-android.content.Context#startService startService()}).</p>
+android.content.Context#bindService bindService()} to create a long-standing connection.
+It generally doesn't allow components to <em>start</em> it by calling {@link
+android.content.Context#startService startService()}.</p>
 
-<p>You should create a bound service when you want to interact with the service from activities
+<p>Create a bound service when you want to interact with the service from activities
 and other components in your application or to expose some of your application's functionality to
-other applications, through interprocess communication (IPC).</p>
+other applications through interprocess communication (IPC).</p>
 
-<p>To create a bound service, you must implement the {@link
+<p>To create a bound service, implement the {@link
 android.app.Service#onBind onBind()} callback method to return an {@link android.os.IBinder} that
 defines the interface for communication with the service. Other application components can then call
 {@link android.content.Context#bindService bindService()} to retrieve the interface and
 begin calling methods on the service. The service lives only to serve the application component that
-is bound to it, so when there are no components bound to the service, the system destroys it
-(you do <em>not</em> need to stop a bound service in the way you must when the service is started
-through {@link android.app.Service#onStartCommand onStartCommand()}).</p>
+is bound to it, so when there are no components bound to the service, the system destroys it.
+You do <em>not</em> need to stop a bound service in the same way that you must when the service is
+started through {@link android.app.Service#onStartCommand onStartCommand()}.</p>
 
-<p>To create a bound service, the first thing you must do is define the interface that specifies
-how a client can communicate with the service. This interface between the service
+<p>To create a bound service, you must define the interface that specifies how a client can
+communicate with the service. This interface between the service
 and a client must be an implementation of {@link android.os.IBinder} and is what your service must
 return from the {@link android.app.Service#onBind
-onBind()} callback method. Once the client receives the {@link android.os.IBinder}, it can begin
+onBind()} callback method. After the client receives the {@link android.os.IBinder}, it can begin
 interacting with the service through that interface.</p>
 
-<p>Multiple clients can bind to the service at once. When a client is done interacting with the
-service, it calls {@link android.content.Context#unbindService unbindService()} to unbind. Once
-there are no clients bound to the service, the system destroys the service.</p>
+<p>Multiple clients can bind to the service simultaneously. When a client is done interacting with
+the service, it calls {@link android.content.Context#unbindService unbindService()} to unbind.
+When there are no clients bound to the service, the system destroys the service.</p>
 
-<p>There are multiple ways to implement a bound service and the implementation is more
-complicated than a started service, so the bound service discussion appears in a separate
-document about <a
+<p>There are multiple ways to implement a bound service, and the implementation is more
+complicated than a started service. For these reasons, the bound service discussion appears in a
+separate document about <a
 href="{@docRoot}guide/components/bound-services.html">Bound Services</a>.</p>
 
+<h2 id="Notifications">Sending notifications to the user</h2>
 
-
-<h2 id="Notifications">Sending Notifications to the User</h2>
-
-<p>Once running, a service can notify the user of events using <a
+<p>When a service is running, it can notify the user of events using <a
 href="{@docRoot}guide/topics/ui/notifiers/toasts.html">Toast Notifications</a> or <a
 href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>.</p>
 
-<p>A toast notification is a message that appears on the surface of the current window for a
-moment then disappears, while a status bar notification provides an icon in the status bar with a
+<p>A toast notification is a message that appears on the surface of the current window for only a
+moment before disappearing. A status bar notification provides an icon in the status bar with a
 message, which the user can select in order to take an action (such as start an activity).</p>
 
-<p>Usually, a status bar notification is the best technique when some background work has completed
-(such as a file completed
-downloading) and the user can now act on it. When the user selects the notification from the
-expanded view, the notification can start an activity (such as to view the downloaded file).</p>
+<p>Usually, a status bar notification is the best technique to use when background work such as
+a file download has completed, and the user can now act on it. When the user
+selects the notification from the expanded view, the notification can start an activity
+(such as to display the downloaded file).</p>
 
 <p>See the <a
 href="{@docRoot}guide/topics/ui/notifiers/toasts.html">Toast Notifications</a> or <a
 href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
 developer guides for more information.</p>
 
+<h2 id="Foreground">Running a service in the foreground</h2>
 
-
-<h2 id="Foreground">Running a Service in the Foreground</h2>
-
-<p>A foreground service is a service that's considered to be something the
-user is actively aware of and thus not a candidate for the system to kill when low on memory. A
+<p>A foreground service is a service that the
+user is actively aware of and is not a candidate for the system to kill when low on memory. A
 foreground service must provide a notification for the status bar, which is placed under the
-"Ongoing" heading, which means that the notification cannot be dismissed unless the service is
-either stopped or removed from the foreground.</p>
+<em>Ongoing</em> heading. This means that the notification cannot be dismissed unless the service
+is either stopped or removed from the foreground.</p>
 
 <p>For example, a music player that plays music from a service should be set to run in the
 foreground, because the user is explicitly aware
@@ -643,9 +644,9 @@
 the user to launch an activity to interact with the music player.</p>
 
 <p>To request that your service run in the foreground, call {@link
-android.app.Service#startForeground startForeground()}. This method takes two parameters: an integer
-that uniquely identifies the notification and the {@link
-android.app.Notification} for the status bar. For example:</p>
+android.app.Service#startForeground startForeground()}. This method takes two parameters: an
+integer that uniquely identifies the notification and the {@link
+android.app.Notification} for the status bar. Here is an example:</p>
 
 <pre>
 Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
@@ -657,30 +658,27 @@
 startForeground(ONGOING_NOTIFICATION_ID, notification);
 </pre>
 
-<p class="caution"><strong>Caution:</strong> The integer ID you give to {@link
+<p class="caution"><strong>Caution:</strong> The integer ID that you give to {@link
 android.app.Service#startForeground startForeground()} must not be 0.</p>
 
-
 <p>To remove the service from the foreground, call {@link
-android.app.Service#stopForeground stopForeground()}. This method takes a boolean, indicating
+android.app.Service#stopForeground stopForeground()}. This method takes a boolean, which indicates
 whether to remove the status bar notification as well. This method does <em>not</em> stop the
-service. However, if you stop the service while it's still running in the foreground, then the
+service. However, if you stop the service while it's still running in the foreground, the
 notification is also removed.</p>
 
 <p>For more information about notifications, see <a
 href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Creating Status Bar
 Notifications</a>.</p>
 
+<h2 id="Lifecycle">Managing the lifecycle of a service</h2>
 
+<p>The lifecycle of a service is much simpler than that of an activity. However, it's even more
+important that you pay close attention to how your service is created and destroyed because a
+service can run in the background without the user being aware.</p>
 
-<h2 id="Lifecycle">Managing the Lifecycle of a Service</h2>
-
-<p>The lifecycle of a service is much simpler than that of an activity. However, it's even more important
-that you pay close attention to how your service is created and destroyed, because a service
-can run in the background without the user being aware.</p>
-
-<p>The service lifecycle&mdash;from when it's created to when it's destroyed&mdash;can follow two
-different paths:</p>
+<p>The service lifecycle&mdash;from when it's created to when it's destroyed&mdash;can follow
+either of these two paths:</p>
 
 <ul>
 <li>A started service
@@ -689,27 +687,26 @@
 stop itself by calling {@link
 android.app.Service#stopSelf() stopSelf()}. Another component can also stop the
 service by calling {@link android.content.Context#stopService
-stopService()}. When the service is stopped, the system destroys it..</p></li>
+stopService()}. When the service is stopped, the system destroys it.</p></li>
 
 <li>A bound service
   <p>The service is created when another component (a client) calls {@link
 android.content.Context#bindService bindService()}. The client then communicates with the service
 through an {@link android.os.IBinder} interface. The client can close the connection by calling
 {@link android.content.Context#unbindService unbindService()}. Multiple clients can bind to
-the same service and when all of them unbind, the system destroys the service. (The service
-does <em>not</em> need to stop itself.)</p></li>
+the same service and when all of them unbind, the system destroys the service. The service
+does <em>not</em> need to stop itself.</p></li>
 </ul>
 
-<p>These two paths are not entirely separate. That is, you can bind to a service that was already
-started with {@link android.content.Context#startService startService()}. For example, a background
-music service could be started by calling {@link android.content.Context#startService
+<p>These two paths are not entirely separate. You can bind to a service that is already
+started with {@link android.content.Context#startService startService()}. For example, you can
+start a background music service by calling {@link android.content.Context#startService
 startService()} with an {@link android.content.Intent} that identifies the music to play. Later,
 possibly when the user wants to exercise some control over the player or get information about the
 current song, an activity can bind to the service by calling {@link
-android.content.Context#bindService bindService()}. In cases like this, {@link
+android.content.Context#bindService bindService()}. In cases such as this, {@link
 android.content.Context#stopService stopService()} or {@link android.app.Service#stopSelf
-stopSelf()} does not actually stop the service until all clients unbind. </p>
-
+stopSelf()} doesn't actually stop the service until all of the clients unbind.</p>
 
 <h3 id="LifecycleCallbacks">Implementing the lifecycle callbacks</h3>
 
@@ -763,20 +760,30 @@
 startService()} and the diagram on the right shows the lifecycle when the service is created
 with {@link android.content.Context#bindService bindService()}.</p>
 
-<p>By implementing these methods, you can monitor two nested loops of the service's lifecycle: </p>
+<p>Figure 2 illustrates the typical callback methods for a service. Although the figure separates
+services that are created by {@link android.content.Context#startService startService()} from those
+created by {@link android.content.Context#bindService bindService()}, keep
+in mind that any service, no matter how it's started, can potentially allow clients to bind to it.
+A service that was initially started with {@link android.app.Service#onStartCommand
+onStartCommand()} (by a client calling {@link android.content.Context#startService startService()})
+can still receive a call to {@link android.app.Service#onBind onBind()} (when a client calls
+{@link android.content.Context#bindService bindService()}).</p>
+
+<p>By implementing these methods, you can monitor these two nested loops of the service's
+lifecycle:</p>
 
 <ul>
-<li>The <strong>entire lifetime</strong> of a service happens between the time {@link
-android.app.Service#onCreate onCreate()} is called and the time {@link
+<li>The <strong>entire lifetime</strong> of a service occurs between the time that {@link
+android.app.Service#onCreate onCreate()} is called and the time that {@link
 android.app.Service#onDestroy} returns. Like an activity, a service does its initial setup in
 {@link android.app.Service#onCreate onCreate()} and releases all remaining resources in {@link
-android.app.Service#onDestroy onDestroy()}.  For example, a
-music playback service could create the thread where the music will be played in {@link
-android.app.Service#onCreate onCreate()}, then stop the thread in {@link
+android.app.Service#onDestroy onDestroy()}. For example, a
+music playback service can create the thread where the music is played in {@link
+android.app.Service#onCreate onCreate()}, and then it can stop the thread in {@link
 android.app.Service#onDestroy onDestroy()}.
 
-<p>The {@link android.app.Service#onCreate onCreate()} and {@link android.app.Service#onDestroy
-onDestroy()} methods are called for all services, whether
+<p class="note"><strong>Note</strong>: The {@link android.app.Service#onCreate onCreate()}
+and {@link android.app.Service#onDestroy onDestroy()} methods are called for all services, whether
 they're created by {@link android.content.Context#startService startService()} or {@link
 android.content.Context#bindService bindService()}.</p></li>
 
@@ -784,8 +791,8 @@
 android.app.Service#onStartCommand onStartCommand()} or {@link android.app.Service#onBind onBind()}.
 Each method is handed the {@link
 android.content.Intent} that was passed to either {@link android.content.Context#startService
-startService()} or {@link android.content.Context#bindService bindService()}, respectively.
-<p>If the service is started, the active lifetime ends the same time that the entire lifetime
+startService()} or {@link android.content.Context#bindService bindService()}.
+<p>If the service is started, the active lifetime ends at the same time that the entire lifetime
 ends (the service is still active even after {@link android.app.Service#onStartCommand
 onStartCommand()} returns). If the service is bound, the active lifetime ends when {@link
 android.app.Service#onUnbind onUnbind()} returns.</p>
@@ -795,26 +802,16 @@
 <p class="note"><strong>Note:</strong> Although a started service is stopped by a call to
 either {@link android.app.Service#stopSelf stopSelf()} or {@link
 android.content.Context#stopService stopService()}, there is not a respective callback for the
-service (there's no {@code onStop()} callback). So, unless the service is bound to a client,
+service (there's no {@code onStop()} callback). Unless the service is bound to a client,
 the system destroys it when the service is stopped&mdash;{@link
 android.app.Service#onDestroy onDestroy()} is the only callback received.</p>
 
-<p>Figure 2 illustrates the typical callback methods for a service. Although the figure separates
-services that are created by {@link android.content.Context#startService startService()} from those
-created by {@link android.content.Context#bindService bindService()}, keep
-in mind that any service, no matter how it's started, can potentially allow clients to bind to it.
-So, a service that was initially started with {@link android.app.Service#onStartCommand
-onStartCommand()} (by a client calling {@link android.content.Context#startService startService()})
-can still receive a call to {@link android.app.Service#onBind onBind()} (when a client calls
-{@link android.content.Context#bindService bindService()}).</p>
-
 <p>For more information about creating a service that provides binding, see the <a
 href="{@docRoot}guide/components/bound-services.html">Bound Services</a> document,
 which includes more information about the {@link android.app.Service#onRebind onRebind()}
 callback method in the section about <a
-href="{@docRoot}guide/components/bound-services.html#Lifecycle">Managing the Lifecycle of
-a Bound Service</a>.</p>
-
+href="{@docRoot}guide/components/bound-services.html#Lifecycle">Managing the lifecycle of
+a bound service</a>.</p>
 
 <!--
 <h2>Beginner's Path</h2>
diff --git a/docs/html/training/articles/security-tips.jd b/docs/html/training/articles/security-tips.jd
index abf6711..9796d9a 100644
--- a/docs/html/training/articles/security-tips.jd
+++ b/docs/html/training/articles/security-tips.jd
@@ -6,34 +6,32 @@
 <div id="tb">
 <h2>In this document</h2>
 <ol class="nolist">
-  <li><a href="#StoringData">Storing Data</a></li>
-  <li><a href="#Permissions">Using Permissions</a></li>
-  <li><a href="#Networking">Using Networking</a></li>
-  <li><a href="#InputValidation">Performing Input Validation</a></li>
-  <li><a href="#UserData">Handling User Data</a></li>
+  <li><a href="#StoringData">Storing data</a></li>
+  <li><a href="#Permissions">Using permissions</a></li>
+  <li><a href="#Networking">Using networking</a></li>
+  <li><a href="#InputValidation">Performing input validation</a></li>
+  <li><a href="#UserData">Handling user data</a></li>
   <li><a href="#WebView">Using WebView</a></li>
-  <li><a href="#Crypto">Using Cryptography</a></li>
-  <li><a href="#IPC">Using Interprocess Communication</a></li>
-  <li><a href="#DynamicCode">Dynamically Loading Code</a></li>
-  <li><a href="#Dalvik">Security in a Virtual Machine</a></li>
-  <li><a href="#Native">Security in Native Code</a></li>
+  <li><a href="#Crypto">Using cryptography</a></li>
+  <li><a href="#IPC">Using interprocess communication</a></li>
+  <li><a href="#DynamicCode">Dynamically loading code</a></li>
+  <li><a href="#Dalvik">Security in a virtual machine</a></li>
+  <li><a href="#Native">Security in native code</a></li>
 </ol>
 <h2>See also</h2>
 <ul>
 <li><a href="http://source.android.com/tech/security/index.html">Android
-Security Overview</a></li>
+  Security Overview</a></li>
 <li><a href="{@docRoot}guide/topics/security/permissions.html">Permissions</a></li>
 </ul>
 </div></div>
 
 
-<p>Android has security features built
-into the operating system that significantly reduce the frequency and impact of
-application security issues. The system is designed so you can typically build your apps with
-default system and file permissions and avoid difficult decisions about security.</p>
+<p>Android has built-in security features that significantly reduce the frequency and impact of
+application security issues. The system is designed so that you can typically build your apps with
+the default system and file permissions and avoid difficult decisions about security.</p>
 
-<p>Some of the core security features that help you build secure apps
-include:
+<p>The following core security features help you build secure apps:
 <ul>
 <li>The Android Application Sandbox, which isolates your app data and code execution
 from other apps.</li>
@@ -43,47 +41,54 @@
 <li>Technologies like ASLR, NX, ProPolice, safe_iop, OpenBSD dlmalloc, OpenBSD
 calloc, and Linux mmap_min_addr to mitigate risks associated with common memory
 management errors.</li>
-<li>An encrypted filesystem that can be enabled to protect data on lost or
+<li>An encrypted file system that can be enabled to protect data on lost or
 stolen devices.</li>
 <li>User-granted permissions to restrict access to system features and user data.</li>
 <li>Application-defined permissions to control application data on a per-app basis.</li>
 </ul>
 
-<p>Nevertheless, it is important that you be familiar with the Android
+<p>It is important that you be familiar with the Android
 security best practices in this document. Following these practices as general coding habits
-will reduce the likelihood of inadvertently introducing security issues that
+ reduces the likelihood of inadvertently introducing security issues that
 adversely affect your users.</p>
 
 
 
-<h2 id="StoringData">Storing Data</h2>
+<h2 id="StoringData">Storing data</h2>
 
 <p>The most common security concern for an application on Android is whether the data
 that you save on the device is accessible to other apps. There are three fundamental
 ways to save data on the device:</p>
 
+<ul>
+<li>Internal storage.</li>
+<li>External storage.</li>
+<li>Content providers.</li>
+</ul>
+
+The following paragraphs describe the security issues associated with each approach.
+
 <h3 id="InternalStorage">Using internal storage</h3>
 
 <p>By default, files that you create on <a
 href="{@docRoot}guide/topics/data/data-storage.html#filesInternal">internal
-storage</a> are accessible only to your app. This
-protection is implemented by Android and is sufficient for most
-applications.</p>
+storage</a> are accessible only to your app.
+ Android implements this protection, and it's sufficient for most applications.</p>
 
-<p>You should generally avoid using the {@link android.content.Context#MODE_WORLD_WRITEABLE} or
+<p>Generally, avoid the {@link android.content.Context#MODE_WORLD_WRITEABLE} or
 {@link android.content.Context#MODE_WORLD_READABLE} modes for
 <acronym title="Interprocess Communication">IPC</acronym> files because they do not provide
 the ability to limit data access to particular applications, nor do they
-provide any control on data format. If you want to share your data with other
-app processes, you might instead consider using a
+provide any control of data format. If you want to share your data with other
+app processes, instead consider using a
 <a href="{@docRoot}guide/topics/providers/content-providers.html">content provider</a>, which
 offers read and write permissions to other apps and can make
 dynamic permission grants on a case-by-case basis.</p>
 
-<p>To provide additional protection for sensitive data, you might
-choose to encrypt local files using a key that is not directly accessible to the
-application. For example, a key can be placed in a {@link java.security.KeyStore}
-and protected with a user password that is not stored on the device.  While this
+<p>To provide additional protection for sensitive data, you can
+ encrypt local files using a key that is not directly accessible to the
+application. For example, you can place a key in a {@link java.security.KeyStore}
+and protect it with a user password that is not stored on the device.  While this
 does not protect data from a root compromise that can monitor the user
 inputting the password,  it can provide protection for a lost device without <a
 href="http://source.android.com/tech/encryption/index.html">file system
@@ -94,14 +99,14 @@
 
 <p>Files created on <a
 href="{@docRoot}guide/topics/data/data-storage.html#filesExternal">external
-storage</a>, such as SD Cards, are globally readable and writable.  Because
+storage</a>, such as SD cards, are globally readable and writable. Because
 external storage can be removed by the user and also modified by any
-application,  you should not store sensitive information using
+application, don't store sensitive information using
 external storage.</p>
 
-<p>As with data from any untrusted source, you should <a href="#InputValidation">perform input
-validation</a> when handling data from external storage.
-We strongly recommend that you not store executables or
+<p>You should <a href="#InputValidation">Perform input validation</a> when handling
+data from external storage as you would with data from any untrusted source.
+You should not store executables or
 class files on external storage prior to dynamic loading.  If your app
 does retrieve executable files from external storage, the files should be signed and
 cryptographically verified prior to dynamic loading.</p>
@@ -117,22 +122,22 @@
 href="{@docRoot}guide/topics/manifest/provider-element.html#exported">
 android:exported=false</a></code> in the application manifest. Otherwise, set the <code><a
 href="{@docRoot}guide/topics/manifest/provider-element.html#exported">android:exported</a></code>
-attribute {@code "true"} to allow other apps to access the stored data.
+attribute to {@code true} to allow other apps to access the stored data.
 </p>
 
 <p>When creating a {@link android.content.ContentProvider}
-that will be exported for use by other applications, you can specify a single
+that is exported for use by other applications, you can specify a single
 <a href="{@docRoot}guide/topics/manifest/provider-element.html#prmsn">permission
-</a> for reading and writing, or distinct permissions for reading and writing
-within the manifest. We recommend that you limit your permissions to those
+</a> for reading and writing, or you can specify distinct permissions for reading and writing.
+You should limit your permissions to those
 required to accomplish the task at hand. Keep in mind that it’s usually
 easier to add permissions later to expose new functionality than it is to take
-them away and break existing users.</p>
+them away and impact existing users.</p>
 
 <p>If you are using a content provider
 for sharing data between only your own apps, it is preferable to use the
 <a href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">{@code
-android:protectionLevel}</a> attribute set to {@code "signature"} protection.
+android:protectionLevel}</a> attribute set to {@code signature} protection.
 Signature permissions do not require user confirmation,
 so they provide a better user experience and more controlled access to the
 content provider data when the apps accessing the data are
@@ -148,7 +153,7 @@
 that activates the component.  The scope of these permissions can be further
 limited by the <code><a
 href="{@docRoot}guide/topics/manifest/grant-uri-permission-element.html">
-&lt;grant-uri-permission element&gt;</a></code>.</p>
+&lt;grant-uri-permission&gt;</a></code> element.</p>
 
 <p>When accessing a content provider, use parameterized query methods such as
 {@link android.content.ContentProvider#query(Uri,String[],String,String[],String) query()},
@@ -158,11 +163,11 @@
 sufficient if the <code>selection</code> argument is built by concatenating user data
 prior to submitting it to the method.</p>
 
-<p>Do not have a false sense of security about the write permission.  Consider
-that the write permission allows SQL statements which make it possible for some
+<p>Don't have a false sense of security about the write permission.
+ The write permission allows SQL statements that make it possible for some
 data to be confirmed using creative <code>WHERE</code> clauses and parsing the
-results. For example, an attacker might probe for presence of a specific phone
-number in a call-log by modifying a row only if that phone number already
+results. For example, an attacker might probe for the presence of a specific phone
+number in a call log by modifying a row only if that phone number already
 exists. If the content provider data has predictable structure, the write
 permission may be equivalent to providing both reading and writing.</p>
 
@@ -172,7 +177,7 @@
 
 
 
-<h2 id="Permissions">Using Permissions</h2>
+<h2 id="Permissions">Using permissions</h2>
 
 <p>Because Android sandboxes applications from each other, applications must explicitly
 share resources and data. They do this by declaring the permissions they need for additional
@@ -180,25 +185,25 @@
 the camera.</p>
 
 
-<h3 id="RequestingPermissions">Requesting Permissions</h3>
+<h3 id="RequestingPermissions">Requesting permissions</h3>
 
-<p>We recommend minimizing the number of permissions that your app requests.
-Not having access to sensitive permissions reduces the risk of
-inadvertently misusing those permissions, can improve user adoption, and makes
+<p>You should minimize the number of permissions that your app requests.
+Restricting access to sensitive permissions reduces the risk of
+inadvertently misusing those permissions, improves user adoption, and makes
 your app less vulnerable for attackers. Generally,
-if a permission is not required for your app to function, do not request it.</p>
+if a permission is not required for your app to function, don't request it.</p>
 
 <p>If it's possible to design your application in a way that does not require
 any permissions, that is preferable.  For example, rather than requesting access
 to device information to create a unique identifier, create a <a
 href="{@docRoot}reference/java/util/UUID.html">GUID</a> for your application
-(see the section about <a href="#UserData">Handling User Data</a>). Or, rather than
+(see the section about <a href="#UserData">Handling user data</a>). Or, rather than
 using external storage (which requires permission), store data
 on the internal storage.</p>
 
 <p>In addition to requesting permissions, your application can use the <a
-href="{@docRoot}guide/topics/manifest/permission-element.html">{@code <permissions>}</a>
-to protect IPC that is security sensitive and will be exposed to other
+href="{@docRoot}guide/topics/manifest/permission-element.html">{@code &lt;permission&gt;}</a>
+ element to protect IPC that is security sensitive and is exposed to other
 applications, such as a {@link android.content.ContentProvider}.
 In general, we recommend using access controls
 other than user confirmed permissions where possible because permissions can
@@ -211,13 +216,14 @@
 data over IPC that is available only because your app has permission to access
 that data. The clients of your app's IPC interface may not have that same
 data-access permission. More details on the frequency and potential effects
-of this issue appear in <a class="external-link"
-href="https://www.usenix.org/legacy/event/sec11/tech/full_papers/Felt.pdf"> this
-research paper</a>, published at USENIX.
+of this issue appear in the research paper <a
+href="https://www.usenix.org/legacy/event/sec11/tech/full_papers/Felt.pdf" class="external-link">
+Permission Re-Delegation: Attacks and Defenses
+</a>, published at USENIX.
 
 
 
-<h3 id="CreatingPermissions">Creating Permissions</h3>
+<h3 id="CreatingPermissions">Creating permissions</h3>
 
 <p>Generally, you should strive to define as few permissions as possible while
 satisfying your security requirements.  Creating a new permission is relatively
@@ -228,18 +234,18 @@
 
 <p>If you must create a new permission, consider whether you can accomplish
 your task with a <a
-href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">"signature"
+href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">signature
 protection level</a>.  Signature permissions are transparent
-to the user and only allow access by applications signed by the same developer
-as application performing the permission check.</p>
+to the user and allow access only by applications signed by the same developer
+as the application performing the permission check.</p>
 
 <p>If you create a permission with the <a
-href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">"dangerous"
+href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">dangerous
 protection level</a>, there are a number of complexities
 that you need to consider:
 <ul>
 <li>The permission must have a string that concisely expresses to a user the
-security decision they will be required to make.</li>
+security decision they are required to make.</li>
 <li>The permission string must be localized to many different languages.</li>
 <li>Users may choose not to install an application because a permission is
 confusing or perceived as risky.</li>
@@ -247,28 +253,28 @@
 has not been installed.</li>
 </ul>
 
-<p>Each of these poses a significant non-technical challenge for you as the developer
+<p>Each of these poses a significant nontechnical challenge for you as the developer
 while also confusing your users,
-which is why we discourage the use of the "dangerous" permission level.</p>
+which is why we discourages the use of the <em>dangerous</em> permission level.</p>
 
 
 
 
 
-<h2 id="Networking">Using Networking</h2>
+<h2 id="Networking">Using networking</h2>
 
-<p>Network transactions are inherently risky for security, because it involves transmitting
+<p>Network transactions are inherently risky for security, because they involve transmitting
 data that is potentially private to the user. People are increasingly aware of the privacy
 concerns of a mobile device, especially when the device performs network transactions,
 so it's very important that your app implement all best practices toward keeping the user's
 data secure at all times.</p>
 
-<h3 id="IPNetworking">Using IP Networking</h3>
+<h3 id="IPNetworking">Using IP networking</h3>
 
 <p>Networking on Android is not significantly different from other Linux
 environments.  The key consideration is making sure that appropriate protocols
 are used for sensitive data, such as {@link javax.net.ssl.HttpsURLConnection} for
-secure web traffic.   We prefer use of HTTPS over HTTP anywhere that HTTPS is
+secure web traffic. You should use HTTPS over HTTP anywhere that HTTPS is
 supported on the server, because mobile devices frequently connect on networks
 that are not secured, such as public Wi-Fi hotspots.</p>
 
@@ -278,32 +284,32 @@
 wireless networks using Wi-Fi, the use of secure networking is strongly
 encouraged for all applications that communicate over the network.</p>
 
-<p>We have seen some applications use <a
-href="http://en.wikipedia.org/wiki/Localhost">localhost</a> network ports for
-handling sensitive IPC.  We discourage this approach since these interfaces are
-accessible by other applications on the device.  Instead, you should use an Android IPC
-mechanism where authentication is possible such as with a {@link android.app.Service}.  (Even
-worse than using loopback is to bind to INADDR_ANY since then your application
-may receive requests from anywhere.)</p>
+<p>Some applications use <a
+href="http://en.wikipedia.org/wiki/Localhost" class="external-link">localhost</a> network ports for
+handling sensitive IPC.  You should not use this approach because these interfaces are
+accessible by other applications on the device. Instead, use an Android IPC
+mechanism where authentication is possible, such as with a {@link android.app.Service}.
+Binding to INADDR_ANY is worse than using loopback because then your application
+may receive requests from anywhere.</p>
 
-<p>Also, one common issue that warrants repeating is to make sure that you do
-not trust data downloaded from HTTP or other insecure protocols.  This includes
+<p>Make sure that you don't
+ trust data downloaded from HTTP or other insecure protocols.  This includes
 validation of input in {@link android.webkit.WebView} and
 any responses to intents issued against HTTP.</p>
 
 
-<h3>Using Telephony Networking</h3>
+<h3>Using telephony networking</h3>
 
 <p>The <acronym title="Short Message Service">SMS</acronym> protocol was primarily designed for
 user-to-user communication and is not well-suited for apps that want to transfer data.
-Due to the limitations of SMS, we strongly recommend the use of <a
+Due to the limitations of SMS, you should use <a
 href="{@docRoot}google/gcm/index.html">Google Cloud Messaging</a> (GCM)
 and IP networking for sending data messages from a web server to your app on a user device.</p>
 
 <p>Beware that SMS is neither encrypted nor strongly
-authenticated on either the network or the device.  In particular, any SMS receiver
-should expect that a malicious user may have sent the SMS to your application&mdash;Do
-not rely on unauthenticated SMS data to perform sensitive commands.
+authenticated on either the network or the device. In particular, any SMS receiver
+should expect that a malicious user may have sent the SMS to your application. Don't
+ rely on unauthenticated SMS data to perform sensitive commands.
 Also, you should be aware that SMS may be subject to spoofing and/or
 interception on the network.  On the Android-powered device itself, SMS
 messages are transmitted as broadcast intents, so they may be read or captured
@@ -314,32 +320,32 @@
 
 
 
-<h2 id="InputValidation">Performing Input Validation</h2>
+<h2 id="InputValidation">Performing input validation</h2>
 
 <p>Insufficient input validation is one of the most common security problems
-affecting applications, regardless of what platform they run on. Android does
-have platform-level countermeasures that reduce the exposure of applications to
-input validation issues and you should use those features where possible. Also
-note that selection of type-safe languages tends to reduce the likelihood of
+affecting applications, regardless of what platform they run on. Android
+has platform-level countermeasures that reduce the exposure of applications to
+input validation issues, and you should use those features where possible. Also
+note that the selection of type-safe languages tends to reduce the likelihood of
 input validation issues.</p>
 
-<p>If you are using native code, then any data read from files, received over
+<p>If you are using native code, any data read from files, received over
 the network, or received from an IPC has the potential to introduce a security
 issue.  The most common problems are <a
-href="http://en.wikipedia.org/wiki/Buffer_overflow">buffer overflows</a>, <a
-href="http://en.wikipedia.org/wiki/Double_free#Use_after_free">use after
+href="http://en.wikipedia.org/wiki/Buffer_overflow" class="external-link">buffer overflows</a>, <a
+href="http://en.wikipedia.org/wiki/Double_free#Use_after_free" class="external-link">use after
 free</a>, and <a
-href="http://en.wikipedia.org/wiki/Off-by-one_error">off-by-one errors</a>.
+href="http://en.wikipedia.org/wiki/Off-by-one_error" class="external-link">off-by-one errors</a>.
 Android provides a number of technologies like <acronym
 title="Address Space Layout Randomization">ASLR</acronym> and <acronym
 title="Data Execution Prevention">DEP</acronym> that reduce the
-exploitability of these errors, but they do not solve the underlying problem.
-You can prevent these vulneratbilities by careful handling pointers and managing
+exploitability of these errors, but they don't solve the underlying problem.
+You can prevent these vulnerabilities by carefully handling pointers and managing
 buffers.</p>
 
-<p>Dynamic, string based languages such as JavaScript and SQL are also subject
+<p>Dynamic, string-based languages such as JavaScript and SQL are also subject
 to input validation problems due to escape characters and <a
-href="http://en.wikipedia.org/wiki/Code_injection">script injection</a>.</p>
+href="http://en.wikipedia.org/wiki/Code_injection" class="external-link">script injection</a>.</p>
 
 <p>If you are using data within queries that are submitted to an SQL database or a
 content provider, SQL injection may be an issue.  The best defense is to use
@@ -348,60 +354,59 @@
 Limiting permissions to read-only or write-only can also reduce the potential
 for harm related to SQL injection.</p>
 
-<p>If you cannot use the security features above, we strongly recommend the use
-of well-structured data formats and verifying that the data conforms to the
+<p>If you can't use the security features above, you should make sure to use
+well-structured data formats and verify that the data conforms to the
 expected format. While blacklisting of characters or character-replacement can
-be an effective strategy, these techniques are error-prone in practice and
+be an effective strategy, these techniques are error prone in practice and
 should be avoided when possible.</p>
 
 
 
 
 
-<h2 id="UserData">Handling User Data</h2>
+<h2 id="UserData">Handling user data</h2>
 
 <p>In general, the best approach for user data security is to minimize the use of APIs that access
 sensitive or personal user data. If you have access to user data and can avoid
-storing or transmitting the information, do not store or transmit the data.
-Finally, consider if there is a way that your application logic can be
+storing or transmitting it, don't store or transmit the data.
+Consider if there is a way that your application logic can be
 implemented using a hash or non-reversible form of the data.  For example, your
-application might use the hash of an an email address as a primary key, to
+application might use the hash of an email address as a primary key to
 avoid transmitting or storing the email address.  This reduces the chances of
 inadvertently exposing data, and it also reduces the chance of attackers
 attempting to exploit your application.</p>
 
 <p>If your application accesses personal information such as passwords or
-usernames, keep in mind that some jurisdictions may require you to provide a
-privacy policy explaining your use and storage of that data.  So following the
+user names, keep in mind that some jurisdictions may require you to provide a
+privacy policy explaining your use and storage of that data. Following the
 security best practice of minimizing access to user data may also simplify
 compliance.</p>
 
 <p>You should also consider whether your application might be inadvertently
 exposing personal information to other parties such as third-party components
 for advertising or third-party services used by your application. If you don't
-know why a component or service requires a personal information, don’t
+know why a component or service requires personal information, don’t
 provide it.  In general, reducing the access to personal information by your
-application will reduce the potential for problems in this area.</p>
+application reduces the potential for problems in this area.</p>
 
-<p>If access to sensitive data is required, evaluate whether that information
-must be transmitted to a server, or whether the operation can be performed on
-the client.  Consider running any code using sensitive data on the client to
-avoid transmitting user data.</p>
-
-<p>Also, make sure that you do not inadvertently expose user data to other
-application on the device through overly permissive IPC, world writable files,
-or network sockets. This is a special case of leaking permission-protected data,
+<p>If your app requires access to sensitive data, evaluate whether you need to
+ transmit it to a server or you can run the operation on
+the client. Consider running any code using sensitive data on the client to
+avoid transmitting user data. Also, make sure that you do not inadvertently expose user
+ data to other
+applications on the device through overly permissive IPC, world-writable files,
+or network sockets. Overly permissive IPC is a special case of leaking permission-protected data,
 discussed in the <a href="#RequestingPermissions">Requesting Permissions</a> section.</p>
 
 <p>If a <acronym title="Globally Unique Identifier">GUID</acronym>
-is required, create a large, unique number and store it.  Do not
-use phone identifiers such as the phone number or IMEI which may be associated
+is required, create a large, unique number and store it.  Don't
+use phone identifiers such as the phone number or IMEI, which may be associated
 with personal information.  This topic is discussed in more detail in the <a
-href="http://android-developers.blogspot.com/2011/03/identifying-app-installations.html">Android
-Developer Blog</a>.</p>
+href="http://android-developers.blogspot.com/2011/03/identifying-app-installations.html"
+>Android Developer Blog</a>.</p>
 
 <p>Be careful when writing to on-device logs.
-In Android, logs are a shared resource, and are available
+In Android, logs are a shared resource and are available
 to an application with the {@link android.Manifest.permission#READ_LOGS} permission.
 Even though the phone log data
 is temporary and erased on reboot, inappropriate logging of user information
@@ -414,19 +419,23 @@
 
 <h2 id="WebView">Using WebView</h2>
 
-<p>Because {@link android.webkit.WebView} consumes web content that can include HTML and JavaScript,
+<p>Because {@link android.webkit.WebView} consumes web content that can include HTML
+ and JavaScript,
 improper use can introduce common web security issues such as <a
-href="http://en.wikipedia.org/wiki/Cross_site_scripting">cross-site-scripting</a>
+href="http://en.wikipedia.org/wiki/Cross_site_scripting" class="external-link">
+cross-site-scripting</a>
 (JavaScript injection).  Android includes a number of mechanisms to reduce
-the scope of these potential issues by limiting the capability of {@link android.webkit.WebView} to
+the scope of these potential issues by limiting the capability of
+ {@link android.webkit.WebView} to
 the minimum functionality required by your application.</p>
 
-<p>If your application does not directly use JavaScript within a {@link android.webkit.WebView}, do
-<em>not</em> call {@link android.webkit.WebSettings#setJavaScriptEnabled setJavaScriptEnabled()}.
+<p>If your application doesn't directly use JavaScript within a {@link android.webkit.WebView},
+ <em>do not</em> call
+ {@link android.webkit.WebSettings#setJavaScriptEnabled setJavaScriptEnabled()}.
 Some sample code uses this method, which you might repurpose in production
 application, so remove that method call if it's not required. By default,
 {@link android.webkit.WebView} does
-not execute JavaScript so cross-site-scripting is not possible.</p>
+not execute JavaScript, so cross-site-scripting is not possible.</p>
 
 <p>Use {@link android.webkit.WebView#addJavascriptInterface
 addJavaScriptInterface()} with
@@ -441,55 +450,55 @@
 <p>If your application accesses sensitive data with a
 {@link android.webkit.WebView}, you may want to use the
 {@link android.webkit.WebView#clearCache clearCache()} method to delete any files stored
-locally. Server-side
-headers like <code>no-cache</code> can also be used to indicate that an application should
+locally. You can also use server-side
+headers such as <code>no-cache</code> to indicate that an application should
 not cache particular content.</p>
 
 <p>Devices running platforms older than Android 4.4 (API level 19)
 use a version of {@link android.webkit webkit} that has a number of security issues.
 As a workaround, if your app is running on these devices, it
-should confirm that {@link android.webkit.WebView} objects display only trusted
-content. You should also use the updatable security {@link
-java.security.Provider Provider} object to make sure your app isn’t exposed to
-potential vulnerabilities in SSL, as described in <a
+must confirm that {@link android.webkit.WebView} objects display only trusted
+content. To make sure your app isn’t exposed to
+potential vulnerabilities in SSL, use the updatable security {@link
+java.security.Provider Provider} object as described in <a
 href="{@docRoot}training/articles/security-gms-provider.html">Updating Your
 Security Provider to Protect Against SSL Exploits</a>. If your application must
 render content from the open web, consider providing your own renderer so
 you can keep it up to date with the latest security patches.</p>
 
 
-<h3 id="Credentials">Handling Credentials</h3>
+<h3 id="Credentials">Handling credentials</h3>
 
-<p>In general, we recommend minimizing the frequency of asking for user
-credentials&mdash;to make phishing attacks more conspicuous, and less likely to be
-successful.  Instead use an authorization token and refresh it.</p>
+<p>To make phishing attacks more conspicuous and less likely to be
+successful, minimize the frequency of asking for user
+credentials. Instead use an authorization token and refresh it.</p>
 
-<p>Where possible, username and password should not be stored on the device.
-Instead, perform initial authentication using the username and password
-supplied by the user, and then use a short-lived, service-specific
+<p>Where possible, don't store user names and passwords on the device.
+Instead, perform initial authentication using the user name and password
+ supplied by the user, and then use a short-lived, service-specific
 authorization token.</p>
 
-<p>Services that will be accessible to multiple applications should be accessed
+<p>Services that are accessible to multiple applications should be accessed
 using {@link android.accounts.AccountManager}. If possible, use the
-{@link android.accounts.AccountManager} class to invoke a cloud-based service and do not store
+{@link android.accounts.AccountManager} class to invoke a cloud-based service and don't store
 passwords on the device.</p>
 
 <p>After using {@link android.accounts.AccountManager} to retrieve an
-{@link android.accounts.Account}, {@link android.accounts.Account#CREATOR}
-before passing in any credentials, so that you do not inadvertently pass
+{@link android.accounts.Account}, use {@link android.accounts.Account#CREATOR}
+before passing in any credentials so that you do not inadvertently pass
 credentials to the wrong application.</p>
 
-<p>If credentials are to be used only by applications that you create, then you
-can verify the application which accesses the {@link android.accounts.AccountManager} using
+<p>If credentials are used only by applications that you create, you
+can verify the application that accesses the {@link android.accounts.AccountManager} using
 {@link android.content.pm.PackageManager#checkSignatures checkSignature()}.
-Alternatively, if only one application will use the credential, you might use a
+Alternatively, if only one application uses the credential, you might use a
 {@link java.security.KeyStore} for storage.</p>
 
 
 
 
 
-<h2 id="Crypto">Using Cryptography</h2>
+<h2 id="Crypto">Using cryptography</h2>
 
 <p>In addition to providing data isolation, supporting full-filesystem
 encryption, and providing secure communications channels, Android provides a
@@ -500,21 +509,21 @@
 retrieve a file from a known location, a simple HTTPS URI may be adequate and
 requires no knowledge of cryptography.  If you need a secure
 tunnel, consider using {@link javax.net.ssl.HttpsURLConnection} or
-{@link javax.net.ssl.SSLSocket}, rather than writing your own protocol.</p>
+{@link javax.net.ssl.SSLSocket} rather than writing your own protocol.</p>
 
-<p>If you do find yourself needing to implement your own protocol, we strongly
-recommend that you <em>not</em> implement your own cryptographic algorithms. Use
+<p>If you do need to implement your own protocol, you should <em>not</em>
+implement your own cryptographic algorithms. Use
 existing cryptographic algorithms such as those in the implementation of AES or
 RSA provided in the {@link javax.crypto.Cipher} class.</p>
 
 <p>Use a secure random number generator, {@link java.security.SecureRandom},
-to initialize any cryptographic keys, {@link javax.crypto.KeyGenerator}.
+to initialize any cryptographic keys generated by {@link javax.crypto.KeyGenerator}.
 Use of a key that is not generated with a secure random
-number generator significantly weakens the strength of the algorithm, and may
+number generator significantly weakens the strength of the algorithm and may
 allow offline attacks.</p>
 
-<p>If you need to store a key for repeated use, use a mechanism like
-  {@link java.security.KeyStore} that
+<p>If you need to store a key for repeated use, use a mechanism, such as
+  {@link java.security.KeyStore}, that
 provides a mechanism for long term storage and retrieval of cryptographic
 keys.</p>
 
@@ -522,10 +531,10 @@
 
 
 
-<h2 id="IPC">Using Interprocess Communication</h2>
+<h2 id="IPC">Using interprocess communication</h2>
 
 <p>Some apps attempt to implement IPC using traditional Linux
-techniques such as network sockets and shared files.  We strongly encourage you to instead
+techniques such as network sockets and shared files. However, you should instead
 use Android system functionality for IPC such as {@link android.content.Intent},
 {@link android.os.Binder} or {@link android.os.Messenger} with a {@link
 android.app.Service}, and {@link android.content.BroadcastReceiver}.
@@ -535,19 +544,19 @@
 
 <p>Many of the security elements are shared across IPC mechanisms.
 If your IPC mechanism is not intended for use by other applications, set the
-{@code android:exported} attribute to {@code "false"} in the component's manifest element,
+{@code android:exported} attribute to {@code false} in the component's manifest element,
 such as for the <a
-href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code <service>}</a>
+href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code &lt;service&gt;}</a>
 element.  This is useful for applications that consist of multiple processes
-within the same UID, or if you decide late in development that you do not
-actually want to expose functionality as IPC but you don’t want to rewrite
+within the same UID or if you decide late in development that you don't
+actually want to expose functionality as IPC, but you don’t want to rewrite
 the code.</p>
 
-<p>If your IPC is intended to be accessible to other applications, you can
+<p>If your IPC is accessible to other applications, you can
 apply a security policy by using the <a
-href="{@docRoot}guide/topics/manifest/permission-element.html">{@code <permission>}</a>
+href="{@docRoot}guide/topics/manifest/permission-element.html">{@code &lt;permission>}</a>
 element. If IPC is between your own separate apps that are signed with the same key,
-it is preferable to use {@code "signature"} level permission in the <a
+it is preferable to use {@code signature} level permission in the <a
 href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">{@code
 android:protectionLevel}</a>.</p>
 
@@ -556,31 +565,42 @@
 
 <h3>Using intents</h3>
 
-<p>Intents are the preferred mechanism for asynchronous IPC in Android.
+<p>For activities and broadcast receivers, intents are the preferred mechanism for
+ asynchronous IPC in Android.
 Depending on your application requirements, you might use {@link
 android.content.Context#sendBroadcast sendBroadcast()}, {@link
 android.content.Context#sendOrderedBroadcast sendOrderedBroadcast()},
 or an explicit intent to a specific application component.</p>
 
-<p>Note that ordered broadcasts can be “consumed” by a recipient, so they
-may not be delivered to all applications.  If you are sending an intent that must be delivered
-to a specific receiver, then you must use an explicit intent that declares the receiver
-by nameintent.</p>
+<p class="caution"><strong>Caution:</strong> If you use an intent to bind to a
+ {@link android.app.Service}, ensure that your app is secure by using an
+ <a href="{@docRoot}guide/components/intents-filters.html#Types">explicit</a>
+intent. Using an implicit intent to start a service is a
+security hazard because you can't be certain what service will respond to the intent,
+and the user can't see which service starts. Beginning with Android 5.0 (API level 21),
+ the system
+throws an exception if you call {@link android.content.Context#bindService bindService()}
+with an implicit intent.</p>
 
-<p>Senders of an intent can verify that the recipient has a permission
-specifying a non-Null permission with the method call.  Only applications with that
-permission will receive the intent.  If data within a broadcast intent may be
+<p>Note that ordered broadcasts can be <em>consumed</em> by a recipient, so they
+may not be delivered to all applications.  If you are sending an intent that must be delivered
+to a specific receiver, you must use an explicit intent that declares the receiver
+by name.</p>
+
+<p>Senders of an intent can verify that the recipient has permission
+ by specifying a non-null permission with the method call.  Only applications with that
+permission receive the intent. If data within a broadcast intent may be
 sensitive, you should consider applying a permission to make sure that
-malicious applications cannot register to receive those messages without
-appropriate permissions.  In those circumstances, you may also consider
+malicious applications can't register to receive those messages without
+appropriate permissions. In those circumstances, you may also consider
 invoking the receiver directly, rather than raising a broadcast.</p>
 
 <p class="note"><strong>Note:</strong> Intent filters should not be considered
-a security feature&mdash;components
+a security feature. Components
 can be invoked with explicit intents and may not have data that would conform to the intent
-filter. You should perform input validation within your intent receiver to
+filter. To
 confirm that it is properly formatted for the invoked receiver, service, or
-activity.</p>
+activity, perform input validation within your intent receiver.</p>
 
 
 
@@ -589,26 +609,32 @@
 
 <p>A {@link android.app.Service} is often used to supply functionality for other applications to
 use. Each service class must have a corresponding <a
-href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> declaration in its
+href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a>
+ declaration in its
 manifest file.</p>
 
 <p>By default, services are not exported and cannot be invoked by any other
-application. However, if you add any intent filters to the service declaration, then it is exported
+application. However, if you add any intent filters to the service declaration, it is exported
 by default. It's best if you explicitly declare the <a
 href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code
 android:exported}</a> attribute to be sure it behaves as you'd like.
 Services can also be protected using the <a
 href="{@docRoot}guide/topics/manifest/service-element.html#prmsn">{@code android:permission}</a>
-attribute. By doing so, other applications will need to declare
+attribute. By doing so, other applications need to declare
 a corresponding <code><a
 href="{@docRoot}guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a>
 </code> element in their own manifest to be
 able to start, stop, or bind to the service.</p>
 
+<p class="note"><strong>Note:</strong> If your app targets Android 5.0 (API level 21) or later,
+ you should use the {@link android.app.job.JobScheduler} to execute background
+ services. For more information about {@link android.app.job.JobScheduler}, see its
+ {@link android.app.job.JobScheduler API-reference documentation}.</p>
+
 <p>A service can protect individual IPC calls into it with permissions, by
 calling {@link android.content.Context#checkCallingPermission
 checkCallingPermission()} before executing
-the implementation of that call.  We generally recommend using the
+the implementation of that call. You should use the
 declarative permissions in the manifest, since those are less prone to
 oversight.</p>
 
@@ -620,24 +646,24 @@
 preferred mechanism for RPC-style IPC in Android. They provide a well-defined
 interface that enables mutual authentication of the endpoints, if required.</p>
 
-<p>We strongly encourage designing interfaces in a manner that does not require
-interface specific permission checks. {@link android.os.Binder} and
+<p>You should design your app interfaces in a manner that does not require
+interface-specific permission checks. {@link android.os.Binder} and
 {@link android.os.Messenger} objects are not declared within the
 application manifest, and therefore you cannot apply declarative permissions
 directly to them.  They generally inherit permissions declared in the
 application manifest for the {@link android.app.Service} or {@link
 android.app.Activity} within which they are
 implemented.  If you are creating an interface that requires authentication
-and/or access controls, those controls must be
-explicitly added as code in the {@link android.os.Binder} or {@link android.os.Messenger}
+and/or access controls, you must explicitly add those controls
+ as code in the {@link android.os.Binder} or {@link android.os.Messenger}
 interface.</p>
 
-<p>If providing an interface that does require access controls, use {@link
+<p>If you are providing an interface that does require access controls, use {@link
 android.content.Context#checkCallingPermission checkCallingPermission()}
 to verify whether the
 caller has a required permission. This is especially important
 before accessing a service on behalf of the caller, as the identify of your
-application is passed to other interfaces.  If invoking an interface provided
+application is passed to other interfaces.  If you are invoking an interface provided
 by a {@link android.app.Service}, the {@link
 android.content.Context#bindService bindService()}
  invocation may fail if you do not have permission to access the given service.
@@ -660,8 +686,8 @@
 is intended for use by other applications, you
 may want to apply security permissions to receivers using the <code><a
 href="{@docRoot}guide/topics/manifest/receiver-element.html">
-&lt;receiver&gt;</a></code> element within the application manifest.  This will
-prevent applications without appropriate permissions from sending an intent to
+&lt;receiver&gt;</a></code> element within the application manifest.  This
+prevents applications without appropriate permissions from sending an intent to
 the {@link android.content.BroadcastReceiver}.</p>
 
 
@@ -671,57 +697,58 @@
 
 
 
-<h2 id="DynamicCode">Dynamically Loading Code</h2>
+<h2 id="DynamicCode">Dynamically loading code</h2>
 
 <p>We strongly discourage loading code from outside of your application APK.
 Doing so significantly increases the likelihood of application compromise due
-to code injection or code tampering.  It also adds complexity around version
-management and application testing.  Finally, it can make it impossible to
+to code injection or code tampering. It also adds complexity around version
+management and application testing. It can also make it impossible to
 verify the behavior of an application, so it may be prohibited in some
 environments.</p>
 
 <p>If your application does dynamically load code, the most important thing to
-keep in mind about dynamically loaded code is that it runs with the same
-security permissions as the application APK.  The user made a decision to
-install your application based on your identity, and they are expecting that
+keep in mind about dynamically-loaded code is that it runs with the same
+security permissions as the application APK.  The user makes a decision to
+install your application based on your identity, and the user expects that
 you provide any code run within the application, including code that is
 dynamically loaded.</p>
 
 <p>The major security risk associated with dynamically loading code is that the
 code needs to come from a verifiable source. If the modules are included
-directly within your APK, then they cannot be modified by other applications.
+directly within your APK, they cannot be modified by other applications.
 This is true whether the code is a native library or a class being loaded using
-{@link dalvik.system.DexClassLoader}.  We have seen many instances of applications
-attempting to load code from insecure locations, such as downloaded from the
-network over unencrypted protocols or from world writable locations such as
+{@link dalvik.system.DexClassLoader}.  Many applications
+attempt to load code from insecure locations, such as downloaded from the
+network over unencrypted protocols or from world-writable locations such as
 external storage. These locations could allow someone on the network to modify
-the content in transit, or another application on a users device to modify the
-content on the device, respectively.</p>
+the content in transit or another application on a user's device to modify the
+content on the device.</p>
 
 
 
 
 
-<h2 id="Dalvik">Security in a Virtual Machine</h2>
+<h2 id="Dalvik">Security in a virtual machine</h2>
 
 <p>Dalvik is Android's runtime virtual machine (VM). Dalvik was built specifically for Android,
 but many of the concerns regarding secure code in other virtual machines also apply to Android.
 In general, you shouldn't concern yourself with security issues relating to the virtual machine.
-Your application runs in a secure sandbox environment, so other processes on the system cannnot
+Your application runs in a secure sandbox environment, so other processes on the system can't
 access your code or private data.</p>
 
-<p>If you're interested in diving deeper on the subject of virtual machine security,
-we recommend that you familiarize yourself with some
+<p>If you're interested in learning more about virtual machine security,
+ familiarize yourself with some
 existing literature on the subject. Two of the more popular resources are:
 <ul>
-<li><a href="http://www.securingjava.com/toc.html">
-http://www.securingjava.com/toc.html</a></li>
+<li><a href="http://www.securingjava.com/toc.html" class="external-link">
+Securing Java</a></li>
 <li><a
-href="https://www.owasp.org/index.php/Java_Security_Resources">
-https://www.owasp.org/index.php/Java_Security_Resources</a></li>
+href="https://www.owasp.org/index.php/Category:Java#tab=Related_3rd_Party_Projects"
+ class="external-link">
+Related 3rd party Projects</a></li>
 </ul></p>
 
-<p>This document is focused on the areas which are Android specific or
+<p>This document focuses on areas that are Android specific or
 different from other VM environments.  For developers experienced with VM
 programming in other environments, there are two broad issues that may be
 different about writing apps for Android:
@@ -742,21 +769,19 @@
 
 
 
-<h2 id="Native">Security in Native Code</h2>
+<h2 id="Native">Security in native code</h2>
 
-<p>In general, we encourage developers to use the Android SDK for
+<p>In general, you should use the Android SDK for
 application development, rather than using native code with the
 <a href="{@docRoot}tools/sdk/ndk/index.html">Android NDK</a>.  Applications built
 with native code are more complex, less portable, and more like to include
-common memory corruption errors such as buffer overflows.</p>
+common memory-corruption errors such as buffer overflows.</p>
 
-<p>Android is built using the Linux kernel and being familiar with Linux
-development security best practices is especially useful if you are going to
-use native code. Linux security practices are beyond the scope of this document,
-but one of the most popular resources is “Secure Programming for
-Linux and Unix HOWTO”, available at <a
-href="http://www.dwheeler.com/secure-programs">
-http://www.dwheeler.com/secure-programs</a>.</p>
+<p>Android is built using the Linux kernel, and being familiar with Linux
+development security best practices is especially useful if you are
+using native code. Linux security practices are beyond the scope of this document,
+but one of the most popular resources is <a href="http://www.dwheeler.com/secure-programs"
+ class="external-link">Secure Programming HOWTO - Creating Secure Software</a>.</p>
 
 <p>An important difference between Android and most Linux environments is the
 Application Sandbox.  On Android, all applications run in the Application
@@ -765,6 +790,5 @@
 every application is given a unique <acronym title="User Identifier">UID</acronym>
 with very limited permissions. This is discussed in more detail in the <a
 href="http://source.android.com/tech/security/index.html">Android Security
-Overview</a> and you should be familiar with application permissions even if
+Overview</a>, and you should be familiar with application permissions even if
 you are using native code.</p>
-
diff --git a/docs/html/training/location/display-address.jd b/docs/html/training/location/display-address.jd
index daa6fd3..088e926 100644
--- a/docs/html/training/location/display-address.jd
+++ b/docs/html/training/location/display-address.jd
@@ -7,11 +7,11 @@
 
     <h2>This lesson teaches you how to</h2>
     <ol>
-      <li><a href="#connect">Get a Geographic Location</a></li>
-      <li><a href="#fetch-address">Define an Intent Service to Fetch the
-        Address</a></li>
-      <li><a href="#start-intent">Start the Intent Service</a></li>
-      <li><a href="#result-receiver">Receive the Geocoding Results</a></li>
+      <li><a href="#connect">Get a geographic location</a></li>
+      <li><a href="#fetch-address">Define an intent service to fetch the
+        address</a></li>
+      <li><a href="#start-intent">Start the intent service</a></li>
+      <li><a href="#result-receiver">Receive the geocoding results</a></li>
     </ol>
 
     <h2>You should also read</h2>
@@ -58,7 +58,7 @@
   convert a geographic location to an address. The method returns an estimated
   street address corresponding to a given latitude and longitude.</p>
 
-<h2 id="connect">Get a Geographic Location</h2>
+<h2 id="connect">Get a geographic location</h2>
 
 <p>The last known location of the device is a useful starting point for the
   address lookup feature. The lesson on
@@ -69,12 +69,12 @@
   <a href="{@docRoot}reference/com/google/android/gms/location/FusedLocationProviderApi.html">fused
   location provider</a> to find the latest location of the device.</p>
 
-<p>To access the fused location provider, you need to create an instance of the
+<p>To access the fused location provider, create an instance of the
   Google Play services API client. To learn how to connect your client, see
   <a href="{@docRoot}training/location/retrieve-current.html#play-services">Connect
   to Google Play Services</a>.</p>
 
-<p>In order for the fused location provider to retrieve a precise street
+<p>To enable the fused location provider to retrieve a precise street
   address, set the location permission in your app manifest to
   {@code ACCESS_FINE_LOCATION}, as shown in the following example:</p>
 
@@ -86,12 +86,12 @@
 &lt;/manifest&gt;
 </pre>
 
-<h2 id="fetch-address">Define an Intent Service to Fetch the Address</h2>
+<h2 id="fetch-address">Define an intent service to fetch the address</h2>
 
 <p>The {@link android.location.Geocoder#getFromLocation getFromLocation()}
   method provided by the {@link android.location.Geocoder} class accepts a
-  latitude and longitude, and returns a list of addresses. The method is
-  synchronous, and may take a long time to do its work, so you should not call
+  latitude and longitude and returns a list of addresses. The method is
+  synchronous and may take a long time to do its work, so you should not call
   it from the main, user interface (UI) thread of your app.</p>
 
 <p>The {@link android.app.IntentService IntentService} class provides a
@@ -100,23 +100,23 @@
   Note that the {@link android.os.AsyncTask AsyncTask} class also allows you to
   perform background operations, but it's designed for short operations. An
   {@link android.os.AsyncTask AsyncTask} shouldn't keep a reference to the UI if
-  the activity is recreated, for example when the device is rotated. In
+  the activity is re-created, such as when the device is rotated. In
   contrast, an {@link android.app.IntentService IntentService} doesn't need to
   be cancelled when the activity is rebuilt.</p>
 
 <p>Define a {@code FetchAddressIntentService} class that extends
   {@link android.app.IntentService}. This class is your address lookup service.
-  The intent service handles an intent asynchronously on a worker thread, and
+  The intent service handles an intent asynchronously on a worker thread and
   stops itself when it runs out of work. The intent extras provide the data
   needed by the service, including a {@link android.location.Location} object
-  for conversion to an address, and a {@link android.os.ResultReceiver} object
+  for conversion to an address and a {@link android.os.ResultReceiver} object
   to handle the results of the address lookup. The service uses a {@link
-  android.location.Geocoder} to fetch the address for the location, and sends
+  android.location.Geocoder} to fetch the address for the location and sends
   the results to the {@link android.os.ResultReceiver}.</p>
 
-<h3>Define the Intent Service in your App Manifest</h3>
+<h3>Define the intent service in your app manifest</h3>
 
-<p>Add an entry to your app manifest defining the intent service:</p>
+<p>Add an entry to your app manifest that defines the intent service, as shown here:</p>
 
 <pre>
 &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
@@ -131,26 +131,26 @@
 &lt;/manifest&gt;
 </pre>
 
-<p class="note"><strong>Note:</strong> The {@code <service>} element in
-  the manifest doesn't need to include an intent filter, because your main
+<p class="note"><strong>Note:</strong> The {@code &lt;service&gt;} element in
+  the manifest doesn't need to include an intent filter because your main
   activity creates an explicit intent by specifying the name of the class to use
   for the intent.</p>
 
-<h3>Create a Geocoder</h3>
+<h3>Create a geocoder</h3>
 
 <p>The process of converting a geographic location to an address is called
-  <em>reverse geocoding</em>. To perform the main work of the intent service,
-  that is, your reverse geocoding request, implement
+  <em>reverse geocoding</em>. To perform the main work of the intent service (your reverse
+  geocoding request), implement
   {@link android.app.IntentService#onHandleIntent onHandleIntent()} within the
   {@code FetchAddressIntentService} class. Create a
   {@link android.location.Geocoder} object to handle the reverse geocoding.</p>
 
 <p>A locale represents a specific geographical or linguistic region. Locale
-  objects are used to adjust the presentation of information, such as numbers or
-  dates, to suit the conventions in the region represented by the locale. Pass a
+  objects adjust the presentation of information, such as numbers or
+  dates, to suit the conventions in the region that is represented by the locale. Pass a
   <a href="{@docRoot}reference/java/util/Locale.html">{@code Locale}</a> object
-  to the {@link android.location.Geocoder} object, to ensure that the resulting
-  address is localized to the user's geographic region.</p>
+  to the {@link android.location.Geocoder} object to ensure that the resulting
+  address is localized to the user's geographic region. Here is an example:</p>
 
 <pre>
 &#64;Override
@@ -162,7 +162,7 @@
 
 <h3 id="retrieve-street-address">Retrieve the street address data</h3>
 
-<p>The next step is to retrieve the street address from the geocoder, handle
+<p>You can now retrieve the street address from the geocoder, handle
   any errors that may occur, and send the results back to the activity that
   requested the address. To report the results of the geocoding
   process, you need two numeric constants that indicate success or failure.
@@ -185,32 +185,34 @@
 
 <p>To get a street address corresponding to a geographical location, call
   {@link android.location.Geocoder#getFromLocation getFromLocation()},
-  passing it the latitude and longitude from the location object, and the
-  maximum number of addresses you want returned. In this case, you want just one
-  address. The geocoder returns an array of addresses. If no addresses were
+  passing it the latitude and longitude from the location object and the
+  maximum number of addresses that you want returned. In this case, you want just one
+  address. The geocoder returns an array of addresses. If no addresses are
   found to match the given location, it returns an empty list. If there is no
   backend geocoding service available, the geocoder returns null.</p>
 
-<p>Check for the following errors as shown in the code sample below. If an error
-  occurs, place the corresponding error message in the {@code errorMessage}
-  variable, so you can send it back to the requesting activity:</p>
+<p>Check for the following errors, as shown in the code sample below:</p>
 
 <ul>
-  <li><strong>No location data provided</strong> - The intent extras do not
-    include the {@link android.location.Location} object required for reverse
+  <li><strong>No location data provided</strong> &ndash; The intent extras do not
+    include the {@link android.location.Location} object that is required for reverse
     geocoding.</li>
-  <li><strong>Invalid latitude or longitude used</strong> - The latitude
-    and/or longitude values provided in the {@link android.location.Location}
+  <li><strong>Invalid latitude or longitude used</strong> &ndash; The latitude
+    and/or longitude values that are provided in the {@link android.location.Location}
     object are invalid.</li>
-  <li><strong>No geocoder available</strong> - The background geocoding service
-    is not available, due to a network error or IO exception.</li>
-  <li><strong>Sorry, no address found</strong> - The geocoder could not find an
+  <li><strong>No geocoder available</strong> &ndash; The background geocoding service
+    is not available due to a network error or IO exception.</li>
+  <li><strong>Sorry, no address found</strong> &ndash; The geocoder can't find an
     address for the given latitude/longitude.</li>
 </ul>
 
+<p>If an error
+  occurs, place the corresponding error message in the {@code errorMessage}
+  variable so that you can send it back to the requesting activity.
+
 <p>To get the individual lines of an address object, use the
   {@link android.location.Address#getAddressLine getAddressLine()}
-  method provided by the {@link android.location.Address} class. Then join the
+  method that is provided by the {@link android.location.Address} class. Join the
   lines into a list of address fragments ready to return to the activity that
   requested the address.</p>
 
@@ -220,7 +222,7 @@
   results consist of the previously-mentioned numeric success/failure code and
   a string. In the case of a successful reverse geocoding, the string contains
   the address. In the case of a failure, the string contains the error message,
-  as shown in the code sample below:</p>
+  as shown in this code sample:</p>
 
 <pre>
 &#64;Override
@@ -280,18 +282,18 @@
 
 <h3 id="return-address">Return the address to the requestor</h3>
 
-<p>The final thing the intent service must do is send the address back to a
+<p>The final action that the intent service must complete is sending the address back to a
   {@link android.os.ResultReceiver} in the activity that started the service.
   The {@link android.os.ResultReceiver} class allows you to send a
   numeric result code as well as a message containing the result data. The
   numeric code is useful for reporting the success or failure of the geocoding
   request. In the case of a successful reverse geocoding, the message contains
   the address. In the case of a failure, the message contains some text
-  describing the reason for failure.</p>
+  describing the reason for the failure.</p>
 
 <p>You have already retrieved the address from the geocoder, trapped any errors
-  that may occur, and called the {@code deliverResultToReceiver()} method. Now
-  you need to define the {@code deliverResultToReceiver()} method that sends
+  that may occur, and called the {@code deliverResultToReceiver()} method, so now
+  you must define the {@code deliverResultToReceiver()} method that sends
   a result code and message bundle to the result receiver.</p>
 
 <p>For the result code, use the value that you've passed to the
@@ -299,7 +301,7 @@
   To construct the message bundle, concatenate the {@code RESULT_DATA_KEY}
   constant from your {@code Constants} class (defined in
   <a href="#retrieve-street-address">Retrieve the street address data</a>) and
-  the value in the {@code message} parameter passed to the
+  the value in the {@code message} parameter that is passed to the
   {@code deliverResultToReceiver()} method, as shown in the following sample:
 </p>
 
@@ -315,26 +317,26 @@
 }
 </pre>
 
-<h2 id="start-intent">Start the Intent Service</h2>
+<h2 id="start-intent">Start the intent service</h2>
 
 <p>The intent service, as defined in the previous section, runs in the
-  background and is responsible for fetching the address corresponding to a
+  background and fetches the address corresponding to a
   given geographic location. When you start the service, the Android framework
-  instantiates and starts the service if it isn't already running, and creates a
-  process if needed. If the service is already running then it remains running.
+  instantiates and starts the service if it isn't already running, and it creates a
+  process if needed. If the service is already running, it remains running.
   Because the service extends {@link android.app.IntentService IntentService},
-  it shuts down automatically when all intents have been processed.</p>
+  it shuts down automatically after all intents are processed.</p>
 
-<p>Start the service from your app's main activity,
+<p>Start the service from your app's main activity
   and create an {@link android.content.Intent} to pass data to the service. You
-  need an <em>explicit</em> intent, because you want only your service
+  need an <em>explicit</em> intent because you want only your service
   to respond to the intent. For more information, see
   <a href="{@docRoot}guide/components/intents-filters.html#Types">Intent
   Types</a>.</p>
 
 <p>To create an explicit intent, specify the name of the
   class to use for the service: {@code FetchAddressIntentService.class}.
-  Pass two pieces of information in the intent extras:</p>
+  Pass this information in the intent extras:</p>
 
 <ul>
   <li>A {@link android.os.ResultReceiver} to handle the results of the address
@@ -362,6 +364,12 @@
 }
 </pre>
 
+<p class="caution"><strong>Caution</strong>: To ensure that your app is secure, always use an
+explicit intent when starting a {@link android.app.Service} and do not declare intent filters for
+your services. Using an implicit intent to start a service is a security hazard because you cannot
+be certain of the service that will respond to the intent, and the user cannot see which service
+starts.</p>
+
 <p>Call the above {@code startIntentService()} method when the
   user takes an action that requires a geocoding address lookup. For example,
   the user may press a <em>Fetch address</em> button on your app's UI. Before
@@ -391,7 +399,7 @@
   app's UI. The following code snippet shows the call to the
   {@code startIntentService()} method in the
   <a href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.ConnectionCallbacks.html#onConnected(android.os.Bundle)">{@code onConnected()}</a>
-  callback provided by the Google API Client:</p>
+  callback that is provided by the Google API Client:</p>
 
 <pre>
 public class MainActivity extends ActionBarActivity implements
@@ -420,9 +428,9 @@
 }
 </pre>
 
-<h2 id="result-receiver">Receive the Geocoding Results</h2>
+<h2 id="result-receiver">Receive the geocoding results</h2>
 
-<p>The intent service has handled the geocoding request, and uses a
+<p>After the intent service handles the geocoding request, it uses a
   {@link android.os.ResultReceiver} to return the results to the activity that
   made the request. In the activity that makes the request, define an
   {@code AddressResultReceiver} that extends {@link android.os.ResultReceiver}
@@ -430,14 +438,14 @@
 
 <p>The result includes a numeric result code (<code>resultCode</code>) as well
   as a message containing the result data (<code>resultData</code>). If the
-  reverse geocoding process was successful, the <code>resultData</code> contains
+  reverse geocoding process is successful, the <code>resultData</code> contains
   the address. In the case of a failure, the <code>resultData</code> contains
-  text describing the reason for failure. For details of the possible errors,
+  text describing the reason for the failure. For details of the possible errors,
   see <a href="#return-address">Return the address to the requestor</a>.</p>
 
 <p>Override the
   {@link android.os.ResultReceiver#onReceiveResult onReceiveResult()} method
-  to handle the results delivered to the result receiver, as shown in the
+  to handle the results that are delivered to the result receiver, as shown in the
   following code sample:</p>
 
 <pre>
diff --git a/docs/html/training/run-background-service/index.jd b/docs/html/training/run-background-service/index.jd
index 22f3fc8..c48c681 100644
--- a/docs/html/training/run-background-service/index.jd
+++ b/docs/html/training/run-background-service/index.jd
@@ -35,16 +35,22 @@
 <!-- ------------------------------------------------------------------------------------------- -->
 <p>
     Unless you specify otherwise, most of the operations you do in an app run in the foreground on
-    a special thread called the UI thread. This can cause problems, because long-running operations
-    will interfere with the responsiveness of your user interface. This annoys your users, and can
+    a special thread called the UI thread. Long-running foreground operations can cause problems
+    and interfere with the responsiveness of your user interface, which annoys your users and can
     even cause system errors. To avoid this, the Android framework offers several classes that
-    help you off-load operations onto a separate thread running in the background. The most useful
-    of these is {@link android.app.IntentService}.
+    help you off-load operations onto a separate thread that runs in the background. The most
+    useful of these is {@link android.app.IntentService}.
 </p>
 <p>
     This class describes how to implement an {@link android.app.IntentService}, send it work
     requests, and report its results to other components.
 </p>
+
+<p class="note"><strong>Note:</strong> If your app targets Android 5.0 (API level 21),
+    you should use {@link android.app.job.JobScheduler} to execute background
+    services. For more information about this class,
+    see the {@link android.app.job.JobScheduler} reference documentation.</p>
+
 <h2>Lessons</h2>
 <dl>
     <dt>
diff --git a/libs/hwui/Android.mk b/libs/hwui/Android.mk
index 0aa7808..5069a9a 100644
--- a/libs/hwui/Android.mk
+++ b/libs/hwui/Android.mk
@@ -80,6 +80,7 @@
     PathParser.cpp \
     PathTessellator.cpp \
     PixelBuffer.cpp \
+    ProfileRenderer.cpp \
     Program.cpp \
     ProgramCache.cpp \
     Properties.cpp \
diff --git a/libs/hwui/FrameInfoVisualizer.cpp b/libs/hwui/FrameInfoVisualizer.cpp
index 570322d..d3adc32 100644
--- a/libs/hwui/FrameInfoVisualizer.cpp
+++ b/libs/hwui/FrameInfoVisualizer.cpp
@@ -16,6 +16,7 @@
 #include "FrameInfoVisualizer.h"
 
 #include "BakedOpRenderer.h"
+#include "IProfileRenderer.h"
 #include "utils/Color.h"
 
 #include <cutils/compiler.h>
@@ -88,7 +89,7 @@
     }
 }
 
-void FrameInfoVisualizer::draw(ContentRenderer* renderer) {
+void FrameInfoVisualizer::draw(IProfileRenderer& renderer) {
     RETURN_IF_DISABLED();
 
     if (mShowDirtyRegions) {
@@ -96,8 +97,8 @@
         if (mFlashToggle) {
             SkPaint paint;
             paint.setColor(0x7fff0000);
-            renderer->drawRect(mDirtyRegion.fLeft, mDirtyRegion.fTop,
-                    mDirtyRegion.fRight, mDirtyRegion.fBottom, &paint);
+            renderer.drawRect(mDirtyRegion.fLeft, mDirtyRegion.fTop,
+                    mDirtyRegion.fRight, mDirtyRegion.fBottom, paint);
         }
     }
 
@@ -111,7 +112,7 @@
         info.markSwapBuffers();
         info.markFrameCompleted();
 
-        initializeRects(renderer->getViewportHeight(), renderer->getViewportWidth());
+        initializeRects(renderer.getViewportHeight(), renderer.getViewportWidth());
         drawGraph(renderer);
         drawThreshold(renderer);
     }
@@ -194,26 +195,26 @@
     }
 }
 
-void FrameInfoVisualizer::drawGraph(ContentRenderer* renderer) {
+void FrameInfoVisualizer::drawGraph(IProfileRenderer& renderer) {
     SkPaint paint;
     for (size_t i = 0; i < Bar.size(); i++) {
         nextBarSegment(Bar[i].start, Bar[i].end);
         paint.setColor(Bar[i].color & BAR_FAST_MASK);
-        renderer->drawRects(mFastRects.get(), mNumFastRects * 4, &paint);
+        renderer.drawRects(mFastRects.get(), mNumFastRects * 4, paint);
         paint.setColor(Bar[i].color & BAR_JANKY_MASK);
-        renderer->drawRects(mJankyRects.get(), mNumJankyRects * 4, &paint);
+        renderer.drawRects(mJankyRects.get(), mNumJankyRects * 4, paint);
     }
 }
 
-void FrameInfoVisualizer::drawThreshold(ContentRenderer* renderer) {
+void FrameInfoVisualizer::drawThreshold(IProfileRenderer& renderer) {
     SkPaint paint;
     paint.setColor(THRESHOLD_COLOR);
-    float yLocation = renderer->getViewportHeight() - (FRAME_THRESHOLD * mVerticalUnit);
-    renderer->drawRect(0.0f,
+    float yLocation = renderer.getViewportHeight() - (FRAME_THRESHOLD * mVerticalUnit);
+    renderer.drawRect(0.0f,
             yLocation - mThresholdStroke/2,
-            renderer->getViewportWidth(),
+            renderer.getViewportWidth(),
             yLocation + mThresholdStroke/2,
-            &paint);
+            paint);
 }
 
 bool FrameInfoVisualizer::consumeProperties() {
diff --git a/libs/hwui/FrameInfoVisualizer.h b/libs/hwui/FrameInfoVisualizer.h
index d60c002..b98f501 100644
--- a/libs/hwui/FrameInfoVisualizer.h
+++ b/libs/hwui/FrameInfoVisualizer.h
@@ -28,8 +28,7 @@
 namespace android {
 namespace uirenderer {
 
-class BakedOpRenderer;
-typedef BakedOpRenderer ContentRenderer;
+class IProfileRenderer;
 
 // TODO: This is a bit awkward as it needs to match the thing in CanvasContext
 // A better abstraction here would be nice but iterators are painful
@@ -47,7 +46,7 @@
     void setDensity(float density);
 
     void unionDirty(SkRect* dirty);
-    void draw(ContentRenderer* renderer);
+    void draw(IProfileRenderer& renderer);
 
     void dumpData(int fd);
 
@@ -57,8 +56,8 @@
 
     void initializeRects(const int baseline, const int width);
     void nextBarSegment(FrameInfoIndex start, FrameInfoIndex end);
-    void drawGraph(ContentRenderer* renderer);
-    void drawThreshold(ContentRenderer* renderer);
+    void drawGraph(IProfileRenderer& renderer);
+    void drawThreshold(IProfileRenderer& renderer);
 
     inline float durationMS(size_t index, FrameInfoIndex start, FrameInfoIndex end) {
         float duration = mFrameSource[index].duration(start, end) * 0.000001f;
diff --git a/libs/hwui/IProfileRenderer.h b/libs/hwui/IProfileRenderer.h
new file mode 100644
index 0000000..947ed34
--- /dev/null
+++ b/libs/hwui/IProfileRenderer.h
@@ -0,0 +1,34 @@
+/*
+ * 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.
+ */
+
+#include "SkPaint.h"
+
+namespace android {
+namespace uirenderer {
+
+class IProfileRenderer {
+public:
+    virtual void drawRect(float left, float top, float right, float bottom,
+            const SkPaint& paint) = 0;
+    virtual void drawRects(const float* rects, int count, const SkPaint& paint) = 0;
+    virtual uint32_t getViewportWidth() = 0;
+    virtual uint32_t getViewportHeight() = 0;
+
+    virtual ~IProfileRenderer() {}
+};
+
+} /* namespace uirenderer */
+} /* namespace android */
diff --git a/libs/hwui/ProfileRenderer.cpp b/libs/hwui/ProfileRenderer.cpp
new file mode 100644
index 0000000..0ad484c
--- /dev/null
+++ b/libs/hwui/ProfileRenderer.cpp
@@ -0,0 +1,40 @@
+/*
+ * 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.
+ */
+
+#include "ProfileRenderer.h"
+
+namespace android {
+namespace uirenderer {
+
+void ProfileRenderer::drawRect(float left, float top, float right, float bottom,
+        const SkPaint& paint) {
+    mRenderer.drawRect(left, top, right, bottom, &paint);
+}
+
+void ProfileRenderer::drawRects(const float* rects, int count, const SkPaint& paint) {
+    mRenderer.drawRects(rects, count, &paint);
+}
+
+uint32_t ProfileRenderer::getViewportWidth() {
+    return mRenderer.getViewportWidth();
+}
+
+uint32_t ProfileRenderer::getViewportHeight() {
+    return mRenderer.getViewportHeight();
+}
+
+} /* namespace uirenderer */
+} /* namespace android */
diff --git a/libs/hwui/ProfileRenderer.h b/libs/hwui/ProfileRenderer.h
new file mode 100644
index 0000000..b9e586f
--- /dev/null
+++ b/libs/hwui/ProfileRenderer.h
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+#include "IProfileRenderer.h"
+
+#include "BakedOpRenderer.h"
+
+namespace android {
+namespace uirenderer {
+
+class ProfileRenderer : public IProfileRenderer {
+public:
+    ProfileRenderer(BakedOpRenderer& renderer)
+            : mRenderer(renderer) {
+    }
+
+    void drawRect(float left, float top, float right, float bottom, const SkPaint& paint) override;
+    void drawRects(const float* rects, int count, const SkPaint& paint) override;
+    uint32_t getViewportWidth() override;
+    uint32_t getViewportHeight() override;
+
+    virtual ~ProfileRenderer() {}
+
+private:
+    BakedOpRenderer& mRenderer;
+};
+
+} /* namespace uirenderer */
+} /* namespace android */
diff --git a/libs/hwui/hwui/MinikinSkia.cpp b/libs/hwui/hwui/MinikinSkia.cpp
index f172473..a52abfc 100644
--- a/libs/hwui/hwui/MinikinSkia.cpp
+++ b/libs/hwui/hwui/MinikinSkia.cpp
@@ -65,6 +65,23 @@
     bounds->mBottom = skBounds.fBottom;
 }
 
+const void* MinikinFontSkia::GetTable(uint32_t tag, size_t* size,
+        minikin::MinikinDestroyFunc* destroy) {
+    // we don't have a buffer to the font data, copy to own buffer
+    const size_t tableSize = mTypeface->getTableSize(tag);
+    *size = tableSize;
+    if (tableSize == 0) {
+        return nullptr;
+    }
+    void* buf = malloc(tableSize);
+    if (buf == nullptr) {
+        return nullptr;
+    }
+    mTypeface->getTableData(tag, 0, tableSize, buf);
+    *destroy = free;
+    return buf;
+}
+
 SkTypeface *MinikinFontSkia::GetSkTypeface() const {
     return mTypeface.get();
 }
diff --git a/libs/hwui/hwui/MinikinSkia.h b/libs/hwui/hwui/MinikinSkia.h
index 3ee916c..1ea99fd 100644
--- a/libs/hwui/hwui/MinikinSkia.h
+++ b/libs/hwui/hwui/MinikinSkia.h
@@ -37,6 +37,8 @@
     void GetBounds(minikin::MinikinRect* bounds, uint32_t glyph_id,
         const minikin::MinikinPaint &paint) const;
 
+    const void* GetTable(uint32_t tag, size_t* size, minikin::MinikinDestroyFunc* destroy);
+
     SkTypeface* GetSkTypeface() const;
     sk_sp<SkTypeface> RefSkTypeface() const;
 
diff --git a/libs/hwui/renderthread/OpenGLPipeline.cpp b/libs/hwui/renderthread/OpenGLPipeline.cpp
index c758f6c..1ad3803 100644
--- a/libs/hwui/renderthread/OpenGLPipeline.cpp
+++ b/libs/hwui/renderthread/OpenGLPipeline.cpp
@@ -18,6 +18,7 @@
 
 #include "DeferredLayerUpdater.h"
 #include "EglManager.h"
+#include "ProfileRenderer.h"
 #include "renderstate/RenderState.h"
 #include "Readback.h"
 
@@ -76,7 +77,8 @@
     BakedOpRenderer renderer(caches, mRenderThread.renderState(),
             opaque, lightInfo);
     frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer);
-    profiler->draw(&renderer);
+    ProfileRenderer profileRenderer(renderer);
+    profiler->draw(profileRenderer);
     drew = renderer.didDraw();
 
     // post frame cleanup
diff --git a/location/java/android/location/LocationManager.java b/location/java/android/location/LocationManager.java
index 2b3ed87..da0e515 100644
--- a/location/java/android/location/LocationManager.java
+++ b/location/java/android/location/LocationManager.java
@@ -1465,7 +1465,7 @@
             mGpsNmeaListener = null;
             mNmeaBuffer = null;
             mOldGnssCallback = null;
-            mGnssCallback = new GnssStatus.Callback() {
+            mGnssCallback = mGpsListener != null ? new GnssStatus.Callback() {
                 @Override
                 public void onStarted() {
                     mGpsListener.onGpsStatusChanged(GpsStatus.GPS_EVENT_STARTED);
@@ -1485,7 +1485,7 @@
                 public void onSatelliteStatusChanged(GnssStatus status) {
                     mGpsListener.onGpsStatusChanged(GpsStatus.GPS_EVENT_SATELLITE_STATUS);
                 }
-            };
+            } : null;
             mOldGnssNmeaListener = null;
             mGnssNmeaListener = null;
         }
@@ -1502,12 +1502,12 @@
             mOldGnssCallback = null;
             mGnssCallback = null;
             mOldGnssNmeaListener = null;
-            mGnssNmeaListener = new OnNmeaMessageListener() {
+            mGnssNmeaListener = mGpsNmeaListener != null ? new OnNmeaMessageListener() {
                 @Override
                 public void onNmeaMessage(String nmea, long timestamp) {
                     mGpsNmeaListener.onNmeaReceived(timestamp, nmea);
                 }
-            };
+            } : null;
         }
 
         GnssStatusListenerTransport(GnssStatusCallback callback) {
@@ -1516,7 +1516,7 @@
 
         GnssStatusListenerTransport(GnssStatusCallback callback, Handler handler) {
             mOldGnssCallback = callback;
-            mGnssCallback = new GnssStatus.Callback() {
+            mGnssCallback = mOldGnssCallback != null ? new GnssStatus.Callback() {
                 @Override
                 public void onStarted() {
                     mOldGnssCallback.onStarted();
@@ -1536,7 +1536,7 @@
                 public void onSatelliteStatusChanged(GnssStatus status) {
                     mOldGnssCallback.onSatelliteStatusChanged(status);
                 }
-            };
+            } : null;
             mGnssHandler = new GnssHandler(handler);
             mOldGnssNmeaListener = null;
             mGnssNmeaListener = null;
@@ -1569,12 +1569,12 @@
             mOldGnssCallback = null;
             mGnssHandler = new GnssHandler(handler);
             mOldGnssNmeaListener = listener;
-            mGnssNmeaListener = new OnNmeaMessageListener() {
+            mGnssNmeaListener = mOldGnssNmeaListener != null ? new OnNmeaMessageListener() {
                 @Override
                 public void onNmeaMessage(String message, long timestamp) {
                     mOldGnssNmeaListener.onNmeaReceived(timestamp, message);
                 }
-            };
+            } : null;
             mGpsListener = null;
             mGpsNmeaListener = null;
             mNmeaBuffer = new ArrayList<Nmea>();
@@ -1597,7 +1597,7 @@
 
         @Override
         public void onGnssStarted() {
-            if (mGpsListener != null) {
+            if (mGnssCallback != null) {
                 Message msg = Message.obtain();
                 msg.what = GpsStatus.GPS_EVENT_STARTED;
                 mGnssHandler.sendMessage(msg);
@@ -1606,7 +1606,7 @@
 
         @Override
         public void onGnssStopped() {
-            if (mGpsListener != null) {
+            if (mGnssCallback != null) {
                 Message msg = Message.obtain();
                 msg.what = GpsStatus.GPS_EVENT_STOPPED;
                 mGnssHandler.sendMessage(msg);
@@ -1615,7 +1615,7 @@
 
         @Override
         public void onFirstFix(int ttff) {
-            if (mGpsListener != null) {
+            if (mGnssCallback != null) {
                 mTimeToFirstFix = ttff;
                 Message msg = Message.obtain();
                 msg.what = GpsStatus.GPS_EVENT_FIRST_FIX;
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiTracker.java b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiTracker.java
index bfe8c07..77a45b3 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiTracker.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiTracker.java
@@ -484,7 +484,8 @@
         mMainHandler.scheduleAPCopyingAndCloseWriteLock();
     }
 
-    private AccessPoint getCachedOrCreate(ScanResult result, List<AccessPoint> cache) {
+    @VisibleForTesting
+    AccessPoint getCachedOrCreate(ScanResult result, List<AccessPoint> cache) {
         final int N = cache.size();
         for (int i = 0; i < N; i++) {
             if (cache.get(i).matches(result)) {
@@ -493,10 +494,13 @@
                 return ret;
             }
         }
-        return new AccessPoint(mContext, result);
+        final AccessPoint accessPoint = new AccessPoint(mContext, result);
+        accessPoint.setListener(mAccessPointListenerAdapter);
+        return accessPoint;
     }
 
-    private AccessPoint getCachedOrCreate(WifiConfiguration config, List<AccessPoint> cache) {
+    @VisibleForTesting
+    AccessPoint getCachedOrCreate(WifiConfiguration config, List<AccessPoint> cache) {
         final int N = cache.size();
         for (int i = 0; i < N; i++) {
             if (cache.get(i).matches(config)) {
@@ -505,7 +509,7 @@
                 return ret;
             }
         }
-        AccessPoint accessPoint = new AccessPoint(mContext, config);
+        final AccessPoint accessPoint = new AccessPoint(mContext, config);
         accessPoint.setListener(mAccessPointListenerAdapter);
         return accessPoint;
     }
diff --git a/packages/SettingsLib/tests/AndroidManifest.xml b/packages/SettingsLib/tests/AndroidManifest.xml
index 9fd5a41..00b2164 100644
--- a/packages/SettingsLib/tests/AndroidManifest.xml
+++ b/packages/SettingsLib/tests/AndroidManifest.xml
@@ -21,6 +21,8 @@
     <uses-permission android:name="android.permission.MANAGE_USERS" />
     <uses-permission android:name="android.permission.MANAGE_NETWORK_POLICY"/>
     <uses-permission android:name="android.permission.SET_TIME_ZONE" />
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+
 
     <application>
         <uses-library android:name="android.test.runner" />
diff --git a/packages/SettingsLib/tests/src/com/android/settingslib/wifi/WifiTrackerTest.java b/packages/SettingsLib/tests/src/com/android/settingslib/wifi/WifiTrackerTest.java
new file mode 100644
index 0000000..c650190
--- /dev/null
+++ b/packages/SettingsLib/tests/src/com/android/settingslib/wifi/WifiTrackerTest.java
@@ -0,0 +1,71 @@
+/*
+ * 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.settingslib.wifi;
+
+
+import static org.junit.Assert.assertTrue;
+
+import android.net.wifi.ScanResult;
+import android.net.wifi.WifiConfiguration;
+import android.os.SystemClock;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.BitSet;
+import java.util.List;
+
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class WifiTrackerTest {
+
+    @Test
+    public void testAccessPointListenerSetWhenLookingUpUsingScanResults() {
+        ScanResult scanResult = new ScanResult();
+        scanResult.level = 123;
+        scanResult.BSSID = "bssid-" + 111;
+        scanResult.timestamp = SystemClock.elapsedRealtime() * 1000;
+        scanResult.capabilities = "";
+
+        WifiTracker tracker = new WifiTracker(
+                InstrumentationRegistry.getTargetContext(), null, true, true);
+
+        AccessPoint result = tracker.getCachedOrCreate(scanResult, new ArrayList<AccessPoint>());
+        assertTrue(result.mAccessPointListener != null);
+    }
+
+    @Test
+    public void testAccessPointListenerSetWhenLookingUpUsingWifiConfiguration() {
+        WifiConfiguration configuration = new WifiConfiguration();
+        configuration.SSID = "test123";
+        configuration.BSSID="bssid";
+        configuration.networkId = 123;
+        configuration.allowedKeyManagement = new BitSet();
+        configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
+
+        WifiTracker tracker = new WifiTracker(
+                InstrumentationRegistry.getTargetContext(), null, true, true);
+
+        AccessPoint result = tracker.getCachedOrCreate(configuration, new ArrayList<AccessPoint>());
+        assertTrue(result.mAccessPointListener != null);
+    }
+}
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 3084b9b..e7f5f4f 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -2137,7 +2137,7 @@
         }
 
         private final class UpgradeController {
-            private static final int SETTINGS_VERSION = 133;
+            private static final int SETTINGS_VERSION = 134;
 
             private final int mUserId;
 
@@ -2452,6 +2452,21 @@
                 }
 
                 if (currentVersion == 130) {
+                    // Split Ambient settings
+                    final SettingsState secureSettings = getSecureSettingsLocked(userId);
+                    boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
+                            getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
+
+                    if (dozeExplicitlyDisabled) {
+                        secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
+                                "0", SettingsState.SYSTEM_PACKAGE_NAME);
+                        secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
+                                "0", SettingsState.SYSTEM_PACKAGE_NAME);
+                    }
+                    currentVersion = 131;
+                }
+
+                if (currentVersion == 131) {
                     // Initialize new multi-press timeout to default value
                     final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
                     final String oldValue = systemSecureSettings.getSettingLocked(
@@ -2464,11 +2479,11 @@
                                 SettingsState.SYSTEM_PACKAGE_NAME);
                     }
 
-                    currentVersion = 131;
+                    currentVersion = 132;
                 }
 
-                if (currentVersion == 131) {
-                    // Version 131: Allow managed profile to optionally use the parent's ringtones
+                if (currentVersion == 132) {
+                    // Version 132: Allow managed profile to optionally use the parent's ringtones
                     final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
                     String defaultSyncParentSounds = (getContext().getResources()
                             .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
@@ -2476,11 +2491,11 @@
                             Settings.Secure.SYNC_PARENT_SOUNDS,
                             defaultSyncParentSounds,
                             SettingsState.SYSTEM_PACKAGE_NAME);
-                    currentVersion = 132;
+                    currentVersion = 133;
                 }
 
-                if (currentVersion == 132) {
-                    // Version 132: Add default end button behavior
+                if (currentVersion == 133) {
+                    // Version 133: Add default end button behavior
                     final SettingsState systemSettings = getSystemSettingsLocked(userId);
                     if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
                             null) {
@@ -2489,7 +2504,7 @@
                         systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
                                 defaultEndButtonBehavior, SettingsState.SYSTEM_PACKAGE_NAME);
                     }
-                    currentVersion = 133;
+                    currentVersion = 134;
                 }
 
                 if (currentVersion != newVersion) {
diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml
index 02518f2..4d59d57 100644
--- a/packages/SystemUI/AndroidManifest.xml
+++ b/packages/SystemUI/AndroidManifest.xml
@@ -389,7 +389,7 @@
 
         <!-- started from PipUI -->
         <activity
-            android:name="com.android.systemui.tv.pip.PipMenuActivity"
+            android:name=".pip.tv.PipMenuActivity"
             android:exported="true"
             android:theme="@style/PipTheme"
             android:launchMode="singleTop"
@@ -400,7 +400,7 @@
             androidprv:alwaysFocusable="true"
             android:excludeFromRecents="true" />
         <activity
-            android:name="com.android.systemui.tv.pip.PipOverlayActivity"
+            android:name=".pip.tv.PipOverlayActivity"
             android:exported="true"
             android:theme="@style/PipTheme"
             android:taskAffinity=""
@@ -409,7 +409,7 @@
             android:supportsPictureInPicture="true"
             android:excludeFromRecents="true" />
         <activity
-            android:name="com.android.systemui.tv.pip.PipOnboardingActivity"
+            android:name=".pip.tv.PipOnboardingActivity"
             android:exported="true"
             android:theme="@style/PipTheme"
             android:launchMode="singleTop"
diff --git a/packages/SystemUI/res/drawable/pip_dismiss.xml b/packages/SystemUI/res/drawable/pip_dismiss.xml
new file mode 100644
index 0000000..f656eeb
--- /dev/null
+++ b/packages/SystemUI/res/drawable/pip_dismiss.xml
@@ -0,0 +1,24 @@
+<!--
+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.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="42.0dp"
+        android:height="42.0dp"
+        android:viewportWidth="48.0"
+        android:viewportHeight="48.0">
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M38.000000,12.800000l-2.799999,-2.800000 -11.200001,11.200001 -11.200000,-11.200001 -2.800000,2.800000 11.200001,11.200000 -11.200001,11.200001 2.800000,2.799999 11.200000,-11.200001 11.200001,11.200001 2.799999,-2.799999 -11.200001,-11.200001z"/>
+</vector>
\ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/pip_dismiss_background.xml b/packages/SystemUI/res/drawable/pip_dismiss_background.xml
new file mode 100644
index 0000000..3a75296
--- /dev/null
+++ b/packages/SystemUI/res/drawable/pip_dismiss_background.xml
@@ -0,0 +1,22 @@
+<!--
+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.
+-->
+<shape xmlns:android="http://schemas.android.com/apk/res/android"
+    android:shape="oval">
+    <corners
+        android:radius="100dp" />
+    <solid
+        android:color="#66000000" />
+</shape>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/car_navigation_bar.xml b/packages/SystemUI/res/layout/car_navigation_bar.xml
index f7f673d..4b6929f 100644
--- a/packages/SystemUI/res/layout/car_navigation_bar.xml
+++ b/packages/SystemUI/res/layout/car_navigation_bar.xml
@@ -28,7 +28,8 @@
     -->
     <LinearLayout
         android:layout_height="match_parent"
-        android:layout_width="match_parent"
+        android:layout_width="@dimen/car_navigation_bar_width"
+        android:layout_gravity="center"
         android:orientation="horizontal"
         android:clipChildren="false"
         android:clipToPadding="false"
diff --git a/packages/SystemUI/res/layout/pip_dismiss_view.xml b/packages/SystemUI/res/layout/pip_dismiss_view.xml
new file mode 100644
index 0000000..141e610
--- /dev/null
+++ b/packages/SystemUI/res/layout/pip_dismiss_view.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<FrameLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/pip_dismiss_view"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:background="@drawable/pip_dismiss_background"
+    android:foreground="@drawable/pip_dismiss"
+    android:alpha="0"
+    android:forceHasOverlappingRendering="false" />
diff --git a/packages/SystemUI/res/layout/tv_pip_control_button.xml b/packages/SystemUI/res/layout/tv_pip_control_button.xml
index 096dda8..b9b0154 100644
--- a/packages/SystemUI/res/layout/tv_pip_control_button.xml
+++ b/packages/SystemUI/res/layout/tv_pip_control_button.xml
@@ -17,7 +17,7 @@
 */
 -->
 
-<!-- Layout for {@link com.android.systemui.tv.pip.PipControlButtonView}. -->
+<!-- Layout for {@link com.android.systemui.pip.tv.PipControlButtonView}. -->
 <merge xmlns:android="http://schemas.android.com/apk/res/android">
 
     <ImageView android:id="@+id/button"
diff --git a/packages/SystemUI/res/layout/tv_pip_controls.xml b/packages/SystemUI/res/layout/tv_pip_controls.xml
index 49119fb..c6bcd32 100644
--- a/packages/SystemUI/res/layout/tv_pip_controls.xml
+++ b/packages/SystemUI/res/layout/tv_pip_controls.xml
@@ -17,17 +17,17 @@
 */
 -->
 
-<!-- Layout for {@link com.android.systemui.tv.pip.PipControlsView}. -->
+<!-- Layout for {@link com.android.systemui.pip.tv.PipControlsView}. -->
 <merge xmlns:android="http://schemas.android.com/apk/res/android">
 
-    <com.android.systemui.tv.pip.PipControlButtonView
+    <com.android.systemui.pip.tv.PipControlButtonView
         android:id="@+id/full_button"
         android:layout_width="100dp"
         android:layout_height="wrap_content"
         android:src="@drawable/ic_fullscreen_white_24dp"
         android:text="@string/pip_fullscreen" />
 
-    <com.android.systemui.tv.pip.PipControlButtonView
+    <com.android.systemui.pip.tv.PipControlButtonView
         android:id="@+id/close_button"
         android:layout_width="100dp"
         android:layout_height="wrap_content"
@@ -35,7 +35,7 @@
         android:src="@drawable/ic_close_white"
         android:text="@string/pip_close" />
 
-    <com.android.systemui.tv.pip.PipControlButtonView
+    <com.android.systemui.pip.tv.PipControlButtonView
         android:id="@+id/play_pause_button"
         android:layout_width="100dp"
         android:layout_height="wrap_content"
diff --git a/packages/SystemUI/res/layout/tv_pip_menu.xml b/packages/SystemUI/res/layout/tv_pip_menu.xml
index 72a4929..35f2af4 100644
--- a/packages/SystemUI/res/layout/tv_pip_menu.xml
+++ b/packages/SystemUI/res/layout/tv_pip_menu.xml
@@ -26,7 +26,7 @@
     android:gravity="top|center_horizontal"
     android:clipChildren="false">
 
-    <com.android.systemui.tv.pip.PipControlsView
+    <com.android.systemui.pip.tv.PipControlsView
         android:id="@+id/pip_controls"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
diff --git a/packages/SystemUI/res/layout/tv_pip_recents_overlay.xml b/packages/SystemUI/res/layout/tv_pip_recents_overlay.xml
index f157fd5..949400c 100644
--- a/packages/SystemUI/res/layout/tv_pip_recents_overlay.xml
+++ b/packages/SystemUI/res/layout/tv_pip_recents_overlay.xml
@@ -20,7 +20,7 @@
     android:gravity="top|center_horizontal"
     android:orientation="vertical">
 
-    <com.android.systemui.tv.pip.PipRecentsControlsView
+    <com.android.systemui.pip.tv.PipRecentsControlsView
         android:id="@+id/pip_controls"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
@@ -35,13 +35,13 @@
             android:layout_gravity="top|center_horizontal"
             android:background="@drawable/tv_pip_recents_overlay_scrim"
             android:alpha="0" />
-        <com.android.systemui.tv.pip.PipControlsView
+        <com.android.systemui.pip.tv.PipControlsView
             android:id="@+id/pip_control_contents"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_marginTop="10dp"
             android:layout_gravity="top|center_horizontal" />
-    </com.android.systemui.tv.pip.PipRecentsControlsView>
+    </com.android.systemui.pip.tv.PipRecentsControlsView>
 
     <!-- Placeholder view to handle focus change between Recents row and PIP controls
         in talkback mode -->
diff --git a/packages/SystemUI/res/values-ja/strings.xml b/packages/SystemUI/res/values-ja/strings.xml
index c1862a6..c45fa4f 100644
--- a/packages/SystemUI/res/values-ja/strings.xml
+++ b/packages/SystemUI/res/values-ja/strings.xml
@@ -196,13 +196,13 @@
     <string name="accessibility_quick_settings_airplane_on" msgid="6406141469157599296">"機内モードがONです。"</string>
     <string name="accessibility_quick_settings_airplane_changed_off" msgid="66846307818850664">"機内モードをOFFにしました。"</string>
     <string name="accessibility_quick_settings_airplane_changed_on" msgid="8983005603505087728">"機内モードをONにしました。"</string>
-    <string name="accessibility_quick_settings_dnd_priority_on" msgid="1448402297221249355">"[通知を非表示]はONで、優先する通知のみです。"</string>
-    <string name="accessibility_quick_settings_dnd_none_on" msgid="6882582132662613537">"[通知を非表示]はONで、サイレントです。"</string>
-    <string name="accessibility_quick_settings_dnd_alarms_on" msgid="9152834845587554157">"[通知を非表示]はONで、アラームのみです。"</string>
-    <string name="accessibility_quick_settings_dnd" msgid="6607873236717185815">"通知を非表示"</string>
-    <string name="accessibility_quick_settings_dnd_off" msgid="2371832603753738581">"[通知を非表示]はOFFです。"</string>
-    <string name="accessibility_quick_settings_dnd_changed_off" msgid="898107593453022935">"[通知を非表示]をOFFにしました。"</string>
-    <string name="accessibility_quick_settings_dnd_changed_on" msgid="4483780856613561039">"[通知を非表示]をONにしました。"</string>
+    <string name="accessibility_quick_settings_dnd_priority_on" msgid="1448402297221249355">"マナーモードは ON で、優先する通知のみ許可します。"</string>
+    <string name="accessibility_quick_settings_dnd_none_on" msgid="6882582132662613537">"マナーモードは ON で、サイレント モードです。"</string>
+    <string name="accessibility_quick_settings_dnd_alarms_on" msgid="9152834845587554157">"マナーモードは ON で、アラームのみ許可します。"</string>
+    <string name="accessibility_quick_settings_dnd" msgid="6607873236717185815">"マナーモード"</string>
+    <string name="accessibility_quick_settings_dnd_off" msgid="2371832603753738581">"マナーモードは OFF です。"</string>
+    <string name="accessibility_quick_settings_dnd_changed_off" msgid="898107593453022935">"マナーモードを OFF にしました。"</string>
+    <string name="accessibility_quick_settings_dnd_changed_on" msgid="4483780856613561039">"マナーモードを ON にしました。"</string>
     <string name="accessibility_quick_settings_bluetooth" msgid="6341675755803320038">"Bluetooth"</string>
     <string name="accessibility_quick_settings_bluetooth_off" msgid="2133631372372064339">"BluetoothがOFFです。"</string>
     <string name="accessibility_quick_settings_bluetooth_on" msgid="7681999166216621838">"BluetoothがONです。"</string>
@@ -263,7 +263,7 @@
     <string name="dessert_case" msgid="1295161776223959221">"デザートケース"</string>
     <string name="start_dreams" msgid="5640361424498338327">"スクリーン セーバー"</string>
     <string name="ethernet_label" msgid="7967563676324087464">"イーサネット"</string>
-    <string name="quick_settings_dnd_label" msgid="8735855737575028208">"通知を非表示"</string>
+    <string name="quick_settings_dnd_label" msgid="8735855737575028208">"マナーモード"</string>
     <string name="quick_settings_dnd_priority_label" msgid="483232950670692036">"優先する通知のみ"</string>
     <string name="quick_settings_dnd_alarms_label" msgid="2559229444312445858">"アラームのみ"</string>
     <string name="quick_settings_dnd_none_label" msgid="5025477807123029478">"サイレント"</string>
@@ -569,9 +569,9 @@
     <string name="keyboard_shortcut_group_applications_youtube" msgid="6555453761294723317">"YouTube"</string>
     <string name="keyboard_shortcut_group_applications_calendar" msgid="9043614299194991263">"カレンダー"</string>
     <string name="tuner_full_zen_title" msgid="4540823317772234308">"音量調節を表示"</string>
-    <string name="volume_and_do_not_disturb" msgid="3373784330208603030">"通知の非表示"</string>
+    <string name="volume_and_do_not_disturb" msgid="3373784330208603030">"マナーモード"</string>
     <string name="volume_dnd_silent" msgid="4363882330723050727">"音量ボタンのショートカット"</string>
-    <string name="volume_up_silent" msgid="7141255269783588286">"音量上げボタンで [通知を非表示] を OFF にする"</string>
+    <string name="volume_up_silent" msgid="7141255269783588286">"音量上げボタンでマナーモードを OFF にする"</string>
     <string name="battery" msgid="7498329822413202973">"電池"</string>
     <string name="clock" msgid="7416090374234785905">"時計"</string>
     <string name="headset" msgid="4534219457597457353">"ヘッドセット"</string>
diff --git a/packages/SystemUI/res/values-ko/strings.xml b/packages/SystemUI/res/values-ko/strings.xml
index d5292a7..3827dba 100644
--- a/packages/SystemUI/res/values-ko/strings.xml
+++ b/packages/SystemUI/res/values-ko/strings.xml
@@ -464,7 +464,7 @@
     <string name="show_battery_percentage_summary" msgid="3215025775576786037">"충전 중이 아닌 경우 상태 표시줄 아이콘 내에 배터리 잔량 비율 표시"</string>
     <string name="quick_settings" msgid="10042998191725428">"빠른 설정"</string>
     <string name="status_bar" msgid="4877645476959324760">"상태 표시줄"</string>
-    <string name="overview" msgid="4018602013895926956">"개요"</string>
+    <string name="overview" msgid="4018602013895926956">"최근 사용"</string>
     <string name="demo_mode" msgid="2389163018533514619">"데모 모드"</string>
     <string name="enable_demo_mode" msgid="4844205668718636518">"데모 모드 사용"</string>
     <string name="show_demo_mode" msgid="2018336697782464029">"데모 모드 표시"</string>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 549d50e..12f7881 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -694,4 +694,7 @@
 
     <!-- The alpha to apply to the recents row when it doesn't have focus -->
     <item name="recents_recents_row_dim_alpha" format="float" type="dimen">0.5</item>
+
+    <!-- The size of the PIP dismiss target. -->
+    <dimen name="pip_dismiss_target_size">48dp</dimen>
 </resources>
diff --git a/packages/SystemUI/res/values/dimens_car.xml b/packages/SystemUI/res/values/dimens_car.xml
index 04402b7..988caf5 100644
--- a/packages/SystemUI/res/values/dimens_car.xml
+++ b/packages/SystemUI/res/values/dimens_car.xml
@@ -29,4 +29,5 @@
     <dimen name="car_fullscreen_user_pod_image_avatar_height">128dp</dimen>
     <dimen name="car_fullscreen_user_pod_text_size">24sp</dimen>
     <dimen name="car_navigation_button_width">64dp</dimen>
+    <dimen name="car_navigation_bar_width">760dp</dimen>
 </resources>
diff --git a/packages/SystemUI/src/com/android/systemui/SystemUIApplication.java b/packages/SystemUI/src/com/android/systemui/SystemUIApplication.java
index bfc8642..99e7876 100644
--- a/packages/SystemUI/src/com/android/systemui/SystemUIApplication.java
+++ b/packages/SystemUI/src/com/android/systemui/SystemUIApplication.java
@@ -42,7 +42,7 @@
 import com.android.systemui.statusbar.SystemBars;
 import com.android.systemui.statusbar.phone.PhoneStatusBar;
 import com.android.systemui.tuner.TunerService;
-import com.android.systemui.tv.pip.PipUI;
+import com.android.systemui.pip.PipUI;
 import com.android.systemui.usb.StorageNotification;
 import com.android.systemui.volume.VolumeUI;
 
diff --git a/packages/SystemUI/src/com/android/systemui/pip/PipUI.java b/packages/SystemUI/src/com/android/systemui/pip/PipUI.java
new file mode 100644
index 0000000..617d8ad
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/pip/PipUI.java
@@ -0,0 +1,62 @@
+/*
+ * 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.systemui.pip;
+
+import static android.content.pm.PackageManager.FEATURE_LEANBACK_ONLY;
+import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
+
+import android.content.pm.PackageManager;
+import android.content.res.Configuration;
+
+import com.android.systemui.SystemUI;
+
+/**
+ * Controls the picture-in-picture window.
+ */
+public class PipUI extends SystemUI {
+
+    private boolean mSupportsPip;
+    private boolean mIsLeanBackOnly;
+
+    @Override
+    public void start() {
+        PackageManager pm = mContext.getPackageManager();
+        mSupportsPip = pm.hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
+        mIsLeanBackOnly = pm.hasSystemFeature(FEATURE_LEANBACK_ONLY);
+        if (!mSupportsPip) {
+            return;
+        }
+        if (mIsLeanBackOnly) {
+            com.android.systemui.pip.tv.PipManager.getInstance().initialize(mContext);
+        } else {
+            com.android.systemui.pip.phone.PipManager.getInstance().initialize(mContext);
+        }
+    }
+
+    @Override
+    protected void onConfigurationChanged(Configuration newConfig) {
+        super.onConfigurationChanged(newConfig);
+        if (!mSupportsPip) {
+            return;
+        }
+        if (mIsLeanBackOnly) {
+            com.android.systemui.pip.tv.PipManager.getInstance().onConfigurationChanged();
+        } else {
+            com.android.systemui.pip.phone.PipManager.getInstance().onConfigurationChanged();
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipDismissViewController.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipDismissViewController.java
new file mode 100644
index 0000000..a7ac719
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipDismissViewController.java
@@ -0,0 +1,124 @@
+/*
+ * 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.systemui.pip.phone;
+
+import android.content.Context;
+import android.graphics.PixelFormat;
+import android.graphics.Rect;
+import android.view.Gravity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.View.OnLayoutChangeListener;
+import android.view.WindowManager;
+
+import com.android.systemui.Interpolators;
+import com.android.systemui.R;
+
+public class PipDismissViewController {
+
+    // This delay controls how long to wait before we show the target when the user first moves
+    // the PIP, to prevent the target from animating if the user just wants to fling the PIP
+    private static final int SHOW_TARGET_DELAY = 100;
+    private static final int SHOW_TARGET_DURATION = 200;
+
+    private Context mContext;
+    private WindowManager mWindowManager;
+
+    private View mDismissView;
+    private Rect mDismissTargetScreenBounds = new Rect();
+
+    public PipDismissViewController(Context context) {
+        mContext = context;
+        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
+    }
+
+    /**
+     * Creates the dismiss target for showing via {@link #showDismissTarget()}.
+     */
+    public void createDismissTarget() {
+        if (mDismissView == null) {
+            // Create a new view for the dismiss target
+            int dismissTargetSize = mContext.getResources().getDimensionPixelSize(
+                    R.dimen.pip_dismiss_target_size);
+            LayoutInflater inflater = LayoutInflater.from(mContext);
+            mDismissView = inflater.inflate(R.layout.pip_dismiss_view, null);
+            mDismissView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
+                @Override
+                public void onLayoutChange(View v, int left, int top, int right, int bottom,
+                        int oldLeft, int oldTop, int oldRight, int oldBottom) {
+                    if (mDismissView != null) {
+                        mDismissView.getBoundsOnScreen(mDismissTargetScreenBounds);
+                    }
+                }
+            });
+
+            // Add the target to the window
+            WindowManager.LayoutParams lp =  new WindowManager.LayoutParams(
+                    dismissTargetSize,
+                    dismissTargetSize,
+                    WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG,
+                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
+                            | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
+                            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
+                    PixelFormat.TRANSLUCENT);
+            lp.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
+            mWindowManager.addView(mDismissView, lp);
+        }
+        mDismissView.animate().cancel();
+    }
+
+    /**
+     * Shows the dismiss target.
+     */
+    public void showDismissTarget() {
+        mDismissView.animate()
+                .alpha(1f)
+                .setInterpolator(Interpolators.LINEAR_OUT_SLOW_IN)
+                .setStartDelay(SHOW_TARGET_DELAY)
+                .setDuration(SHOW_TARGET_DURATION)
+                .start();
+    }
+
+    /**
+     * Hides and destroys the dismiss target.
+     */
+    public void destroyDismissTarget() {
+        if (mDismissView != null) {
+            mDismissView.animate()
+                    .alpha(0f)
+                    .setInterpolator(Interpolators.FAST_OUT_LINEAR_IN)
+                    .setStartDelay(0)
+                    .setDuration(SHOW_TARGET_DURATION)
+                    .withEndAction(new Runnable() {
+                        @Override
+                        public void run() {
+                            mWindowManager.removeView(mDismissView);
+                            mDismissView = null;
+                        }
+                    })
+                    .start();
+        }
+    }
+
+    /**
+     * @return the dismiss target screen bounds.
+     */
+    public Rect getDismissBounds() {
+        return mDismissTargetScreenBounds;
+    }
+
+}
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipManager.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipManager.java
new file mode 100644
index 0000000..53a4868
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipManager.java
@@ -0,0 +1,66 @@
+/*
+ * 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.systemui.pip.phone;
+
+import android.app.ActivityManagerNative;
+import android.app.IActivityManager;
+import android.content.Context;
+import android.view.IWindowManager;
+import android.view.WindowManagerGlobal;
+
+/**
+ * Manages the picture-in-picture (PIP) UI and states for Phones.
+ */
+public class PipManager {
+    private static final String TAG = "PipManager";
+
+    private static PipManager sPipController;
+
+    private Context mContext;
+    private IActivityManager mActivityManager;
+    private IWindowManager mWindowManager;
+
+    private PipTouchHandler mTouchHandler;
+
+    private PipManager() {}
+
+    /**
+     * Initializes {@link PipManager}.
+     */
+    public void initialize(Context context) {
+        mContext = context;
+        mActivityManager = ActivityManagerNative.getDefault();
+        mWindowManager = WindowManagerGlobal.getWindowManagerService();
+
+        mTouchHandler = new PipTouchHandler(context, mActivityManager, mWindowManager);
+    }
+
+    /**
+     * Updates the PIP per configuration changed.
+     */
+    public void onConfigurationChanged() {}
+
+    /**
+     * Gets an instance of {@link PipManager}.
+     */
+    public static PipManager getInstance() {
+        if (sPipController == null) {
+            sPipController = new PipManager();
+        }
+        return sPipController;
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
new file mode 100644
index 0000000..7aa9aa5
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
@@ -0,0 +1,440 @@
+/*
+ * 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.systemui.pip.phone;
+
+import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
+import static android.view.WindowManager.INPUT_CONSUMER_PIP;
+
+import static com.android.systemui.Interpolators.FAST_OUT_LINEAR_IN;
+import static com.android.systemui.Interpolators.FAST_OUT_SLOW_IN;
+import static com.android.systemui.recents.misc.Utilities.RECT_EVALUATOR;
+
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
+import android.animation.ValueAnimator;
+import android.app.ActivityManager.StackInfo;
+import android.app.IActivityManager;
+import android.content.Context;
+import android.content.res.Configuration;
+import android.graphics.Point;
+import android.graphics.PointF;
+import android.graphics.Rect;
+import android.os.Looper;
+import android.os.RemoteException;
+import android.util.Log;
+import android.view.IWindowManager;
+import android.view.InputChannel;
+import android.view.InputEvent;
+import android.view.InputEventReceiver;
+import android.view.MotionEvent;
+import android.view.VelocityTracker;
+import android.view.ViewConfiguration;
+import android.view.animation.Interpolator;
+import android.widget.Scroller;
+
+import com.android.internal.os.BackgroundThread;
+import com.android.systemui.statusbar.FlingAnimationUtils;
+
+/**
+ * Manages all the touch handling for PIP on the Phone, including moving, dismissing and expanding
+ * the PIP.
+ */
+public class PipTouchHandler {
+    private static final String TAG = "PipTouchHandler";
+    private static final boolean DEBUG_ALLOW_OUT_OF_BOUNDS_STACK = false;
+
+    private static final int SNAP_STACK_DURATION = 225;
+    private static final int DISMISS_STACK_DURATION = 375;
+    private static final int EXPAND_STACK_DURATION = 225;
+
+    private static final float SCROLL_FRICTION_MULTIPLIER = 8f;
+
+    private final Context mContext;
+    private final IActivityManager mActivityManager;
+    private final ViewConfiguration mViewConfig;
+    private final InputChannel mInputChannel = new InputChannel();
+
+    private final PipInputEventReceiver mInputEventReceiver;
+    private final PipDismissViewController mDismissViewController;
+
+    private final Rect mPinnedStackBounds = new Rect();
+    private final Rect mBoundedPinnedStackBounds = new Rect();
+    private ValueAnimator mPinnedStackBoundsAnimator = null;
+
+    private final PointF mDownTouch = new PointF();
+    private final PointF mLastTouch = new PointF();
+    private boolean mIsDragging;
+    private int mActivePointerId;
+
+    private final FlingAnimationUtils mFlingAnimationUtils;
+    private final Scroller mScroller;
+    private VelocityTracker mVelocityTracker;
+
+    /**
+     * Input handler used for Pip windows.
+     */
+    private final class PipInputEventReceiver extends InputEventReceiver {
+        public PipInputEventReceiver(InputChannel inputChannel, Looper looper) {
+            super(inputChannel, looper);
+        }
+
+        @Override
+        public void onInputEvent(InputEvent event) {
+            boolean handled = true;
+            try {
+                // To be implemented for input handling over Pip windows
+                if (event instanceof MotionEvent) {
+                    MotionEvent ev = (MotionEvent) event;
+                    handleTouchEvent(ev);
+                }
+            } finally {
+                finishInputEvent(event, handled);
+            }
+        }
+    }
+
+    public PipTouchHandler(Context context, IActivityManager activityManager,
+            IWindowManager windowManager) {
+
+        // Initialize the Pip input consumer
+        try {
+            windowManager.destroyInputConsumer(INPUT_CONSUMER_PIP);
+            windowManager.createInputConsumer(INPUT_CONSUMER_PIP, mInputChannel);
+        } catch (RemoteException e) {
+            Log.e(TAG, "Failed to create PIP input consumer", e);
+        }
+        mContext = context;
+        mActivityManager = activityManager;
+        mViewConfig = ViewConfiguration.get(context);
+        mInputEventReceiver = new PipInputEventReceiver(mInputChannel, Looper.myLooper());
+        mDismissViewController = new PipDismissViewController(context);
+        mScroller = new Scroller(context);
+        mScroller.setFriction(mViewConfig.getScrollFriction() * SCROLL_FRICTION_MULTIPLIER);
+        mFlingAnimationUtils = new FlingAnimationUtils(context, 2f);
+    }
+
+    private void handleTouchEvent(MotionEvent ev) {
+        switch (ev.getAction()) {
+            case MotionEvent.ACTION_DOWN: {
+                // Cancel any existing animations on the pinned stack
+                if (mPinnedStackBoundsAnimator != null) {
+                    mPinnedStackBoundsAnimator.cancel();
+                }
+
+                updateBoundedPinnedStackBounds();
+                initOrResetVelocityTracker();
+                mVelocityTracker.addMovement(ev);
+                mActivePointerId = ev.getPointerId(0);
+                mLastTouch.set(ev.getX(), ev.getY());
+                mDownTouch.set(mLastTouch);
+                mIsDragging = false;
+                // TODO: Consider setting a timer such at after X time, we show the dismiss target
+                //       if the user hasn't already dragged some distance
+                mDismissViewController.createDismissTarget();
+                break;
+            }
+            case MotionEvent.ACTION_MOVE: {
+                // Update the velocity tracker
+                mVelocityTracker.addMovement(ev);
+
+                int activePointerIndex = ev.findPointerIndex(mActivePointerId);
+                if (!mIsDragging) {
+                    // Check if the pointer has moved far enough
+                    float movement = PointF.length(mDownTouch.x - ev.getX(activePointerIndex),
+                            mDownTouch.y - ev.getY(activePointerIndex));
+                    if (movement > mViewConfig.getScaledTouchSlop()) {
+                        mIsDragging = true;
+                        mDismissViewController.showDismissTarget();
+                    }
+                }
+
+                if (mIsDragging) {
+                    // Move the pinned stack
+                    float dx = ev.getX(activePointerIndex) - mLastTouch.x;
+                    float dy = ev.getY(activePointerIndex) - mLastTouch.y;
+                    float left = Math.max(mBoundedPinnedStackBounds.left, Math.min(
+                            mBoundedPinnedStackBounds.right, mPinnedStackBounds.left + dx));
+                    float top = Math.max(mBoundedPinnedStackBounds.top, Math.min(
+                            mBoundedPinnedStackBounds.bottom, mPinnedStackBounds.top + dy));
+                    if (DEBUG_ALLOW_OUT_OF_BOUNDS_STACK) {
+                        left = mPinnedStackBounds.left + dx;
+                        top = mPinnedStackBounds.top + dy;
+                    }
+                    movePinnedStack(left, top);
+                }
+                mLastTouch.set(ev.getX(), ev.getY());
+                break;
+            }
+            case MotionEvent.ACTION_POINTER_UP: {
+                // Update the velocity tracker
+                mVelocityTracker.addMovement(ev);
+
+                int pointerIndex = ev.getActionIndex();
+                int pointerId = ev.getPointerId(pointerIndex);
+                if (pointerId == mActivePointerId) {
+                    // Select a new active pointer id and reset the movement state
+                    final int newPointerIndex = (pointerIndex == 0) ? 1 : 0;
+                    mActivePointerId = ev.getPointerId(newPointerIndex);
+                    mLastTouch.set(ev.getX(newPointerIndex), ev.getY(newPointerIndex));
+                }
+                break;
+            }
+            case MotionEvent.ACTION_UP: {
+                // Update the velocity tracker
+                mVelocityTracker.addMovement(ev);
+
+                if (mIsDragging) {
+                    mVelocityTracker.computeCurrentVelocity(1000,
+                            ViewConfiguration.get(mContext).getScaledMaximumFlingVelocity());
+                    float velocityX = mVelocityTracker.getXVelocity();
+                    float velocityY = mVelocityTracker.getYVelocity();
+                    float velocity = PointF.length(velocityX, velocityY);
+                    if (velocity > mFlingAnimationUtils.getMinVelocityPxPerSecond()) {
+                        flingToSnapTarget(velocity, velocityX, velocityY);
+                    } else {
+                        int activePointerIndex = ev.findPointerIndex(mActivePointerId);
+                        int x = (int) ev.getX(activePointerIndex);
+                        int y = (int) ev.getY(activePointerIndex);
+                        Rect dismissBounds = mDismissViewController.getDismissBounds();
+                        if (dismissBounds.contains(x, y)) {
+                            animateDismissPinnedStack(dismissBounds);
+                        } else {
+                            animateToSnapTarget();
+                        }
+                    }
+                } else {
+                    expandPinnedStackToFullscreen();
+                }
+                mDismissViewController.destroyDismissTarget();
+
+                // Fall through to clean up
+            }
+            case MotionEvent.ACTION_CANCEL: {
+                mIsDragging = false;
+                recycleVelocityTracker();
+                break;
+            }
+        }
+    }
+
+    private void initOrResetVelocityTracker() {
+        if (mVelocityTracker == null) {
+            mVelocityTracker = VelocityTracker.obtain();
+        } else {
+            mVelocityTracker.clear();
+        }
+    }
+
+    private void recycleVelocityTracker() {
+        if (mVelocityTracker != null) {
+            mVelocityTracker.recycle();
+            mVelocityTracker = null;
+        }
+    }
+
+    /**
+     * Creates an animation that continues the fling to a snap target.
+     */
+    private void flingToSnapTarget(float velocity, float velocityX, float velocityY) {
+        mScroller.fling(mPinnedStackBounds.left, mPinnedStackBounds.top,
+            (int) velocityX, (int) velocityY,
+            mBoundedPinnedStackBounds.left, mBoundedPinnedStackBounds.right,
+            mBoundedPinnedStackBounds.top, mBoundedPinnedStackBounds.bottom);
+        Rect toBounds = findClosestBoundedPinnedStackSnapTarget(
+            mScroller.getFinalX(), mScroller.getFinalY());
+        mScroller.abortAnimation();
+        if (!mPinnedStackBounds.equals(toBounds)) {
+            mPinnedStackBoundsAnimator = createResizePinnedStackAnimation(
+                toBounds, 0, FAST_OUT_SLOW_IN);
+            mFlingAnimationUtils.apply(mPinnedStackBoundsAnimator, 0,
+                distanceBetweenRectOffsets(mPinnedStackBounds, toBounds),
+                velocity);
+            mPinnedStackBoundsAnimator.start();
+        }
+    }
+
+    /**
+     * Animates the pinned stack to the closest snap target.
+     */
+    private void animateToSnapTarget() {
+        Rect toBounds = findClosestBoundedPinnedStackSnapTarget(
+            mPinnedStackBounds.left, mPinnedStackBounds.top);
+        if (!mPinnedStackBounds.equals(toBounds)) {
+            mPinnedStackBoundsAnimator = createResizePinnedStackAnimation(
+                toBounds, SNAP_STACK_DURATION, FAST_OUT_SLOW_IN);
+            mPinnedStackBoundsAnimator.start();
+        }
+    }
+
+    /**
+     * Animates the dismissal of the pinned stack into the given bounds.
+     */
+    private void animateDismissPinnedStack(Rect dismissBounds) {
+        Rect toBounds = new Rect(dismissBounds.centerX(),
+            dismissBounds.centerY(),
+            dismissBounds.centerX() + 1,
+            dismissBounds.centerY() + 1);
+        mPinnedStackBoundsAnimator = createResizePinnedStackAnimation(
+            toBounds, DISMISS_STACK_DURATION, FAST_OUT_LINEAR_IN);
+        mPinnedStackBoundsAnimator.addListener(new AnimatorListenerAdapter() {
+            @Override
+            public void onAnimationEnd(Animator animation) {
+                BackgroundThread.getHandler().post(() -> {
+                    try {
+                        mActivityManager.removeStack(PINNED_STACK_ID);
+                    } catch (RemoteException e) {
+                        Log.e(TAG, "Failed to remove PIP", e);
+                    }
+                });
+            }
+        });
+        mPinnedStackBoundsAnimator.start();
+    }
+
+    /**
+     * Resizes the pinned stack back to fullscreen.
+     */
+    private void expandPinnedStackToFullscreen() {
+        BackgroundThread.getHandler().post(() -> {
+            try {
+                mActivityManager.resizeStack(PINNED_STACK_ID, null /* bounds */,
+                        true /* allowResizeInDockedMode */, true /* preserveWindows */,
+                        true /* animate */, EXPAND_STACK_DURATION);
+            } catch (RemoteException e) {
+                Log.e(TAG, "Error showing PIP menu activity", e);
+            }
+        });
+    }
+
+    /**
+     * Updates the movement bounds of the pinned stack.
+     */
+    private void updateBoundedPinnedStackBounds() {
+        try {
+            StackInfo info = mActivityManager.getStackInfo(PINNED_STACK_ID);
+            mPinnedStackBounds.set(info.bounds);
+            mBoundedPinnedStackBounds.set(mActivityManager.getPictureInPictureMovementBounds());
+        } catch (RemoteException e) {
+            Log.e(TAG, "Could not fetch PIP movement bounds.", e);
+        }
+    }
+
+    /**
+     * Moves the pinned stack to the given {@param left} and {@param top} offsets.
+     */
+    private void movePinnedStack(float left, float top) {
+        if ((int) left != mPinnedStackBounds.left || (int) top != mPinnedStackBounds.top) {
+            mPinnedStackBounds.offsetTo((int) left, (int) top);
+            BackgroundThread.getHandler().post(() -> {
+                try {
+                    mActivityManager.resizePinnedStack(mPinnedStackBounds,
+                            null /* tempPinnedBounds */);
+                } catch (RemoteException e) {
+                    Log.e(TAG, "Could not move pinned stack to offset: (" + left + ", " + top + ")",
+                            e);
+                }
+            });
+        }
+    }
+
+    /**
+     * Resizes the pinned stack to the given {@param bounds}.
+     */
+    private void resizePinnedStack(Rect bounds) {
+        if (!mPinnedStackBounds.equals(bounds)) {
+            mPinnedStackBounds.set(bounds);
+            BackgroundThread.getHandler().post(() -> {
+                try {
+                    mActivityManager.resizePinnedStack(bounds, null);
+                } catch (RemoteException e) {
+                    Log.e(TAG, "Could not resize pinned stack to bounds: (" + bounds + ")");
+                }
+            });
+        }
+    }
+
+    /**
+     * Creates a resize-stack animation.
+     */
+    private ValueAnimator createResizePinnedStackAnimation(Rect toBounds, int duration,
+            Interpolator interpolator) {
+        ValueAnimator anim = ValueAnimator.ofObject(RECT_EVALUATOR,
+                mPinnedStackBounds, toBounds);
+        anim.setDuration(duration);
+        anim.setInterpolator(interpolator);
+        anim.addUpdateListener(
+                new ValueAnimator.AnimatorUpdateListener() {
+                    @Override
+                    public void onAnimationUpdate(ValueAnimator animation) {
+                        resizePinnedStack((Rect) animation.getAnimatedValue());
+                    }
+                });
+        return anim;
+    }
+
+    /**
+     * @return the closest absolute bounded stack left/top to the given {@param x} and {@param y}.
+     */
+    private Rect findClosestBoundedPinnedStackSnapTarget(int x, int y) {
+        Point[] snapTargets;
+        int orientation = mContext.getResources().getConfiguration().orientation;
+        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
+            snapTargets = new Point[] {
+                new Point(mBoundedPinnedStackBounds.left, mBoundedPinnedStackBounds.top),
+                new Point(mBoundedPinnedStackBounds.right, mBoundedPinnedStackBounds.top),
+                new Point(mBoundedPinnedStackBounds.left, mBoundedPinnedStackBounds.bottom),
+                new Point(mBoundedPinnedStackBounds.right, mBoundedPinnedStackBounds.bottom)
+            };
+        } else {
+            snapTargets = new Point[] {
+                new Point(mBoundedPinnedStackBounds.left, mBoundedPinnedStackBounds.top),
+                new Point(mBoundedPinnedStackBounds.right, mBoundedPinnedStackBounds.top),
+                new Point(mBoundedPinnedStackBounds.left, mBoundedPinnedStackBounds.bottom),
+                new Point(mBoundedPinnedStackBounds.right, mBoundedPinnedStackBounds.bottom)
+            };
+        }
+
+        Point closestSnapTarget = null;
+        float minDistance = Float.MAX_VALUE;
+        for (Point p : snapTargets) {
+            float distance = distanceToPoint(p, x, y);
+            if (distance < minDistance) {
+                closestSnapTarget = p;
+                minDistance = distance;
+            }
+        }
+
+        Rect toBounds = new Rect(mPinnedStackBounds);
+        toBounds.offsetTo(closestSnapTarget.x, closestSnapTarget.y);
+        return toBounds;
+    }
+
+    /**
+     * @return the distance between point {@param p} and the given {@param x} and {@param y}.
+     */
+    private float distanceToPoint(Point p, int x, int y) {
+        return PointF.length(p.x - x, p.y - y);
+    }
+
+
+    /**
+     * @return the distance between points {@param p1} and {@param p2}.
+     */
+    private float distanceBetweenRectOffsets(Rect r1, Rect r2) {
+        return PointF.length(r1.left - r2.left, r1.top - r2.top);
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipControlButtonView.java b/packages/SystemUI/src/com/android/systemui/pip/tv/PipControlButtonView.java
similarity index 98%
rename from packages/SystemUI/src/com/android/systemui/tv/pip/PipControlButtonView.java
rename to packages/SystemUI/src/com/android/systemui/pip/tv/PipControlButtonView.java
index 80c593c..59cb086 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipControlButtonView.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/tv/PipControlButtonView.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.systemui.tv.pip;
+package com.android.systemui.pip.tv;
 
 import android.animation.Animator;
 import android.animation.AnimatorInflater;
@@ -22,7 +22,6 @@
 import android.content.res.TypedArray;
 import android.util.AttributeSet;
 import android.view.LayoutInflater;
-import android.view.View.OnFocusChangeListener;
 import android.view.View;
 import android.widget.ImageView;
 import android.widget.RelativeLayout;
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipControlsView.java b/packages/SystemUI/src/com/android/systemui/pip/tv/PipControlsView.java
similarity index 91%
rename from packages/SystemUI/src/com/android/systemui/tv/pip/PipControlsView.java
rename to packages/SystemUI/src/com/android/systemui/pip/tv/PipControlsView.java
index 71740ce..a2aff2d 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipControlsView.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/tv/PipControlsView.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.systemui.tv.pip;
+package com.android.systemui.pip.tv;
 
 import android.content.Context;
 import android.media.session.MediaController;
@@ -22,9 +22,6 @@
 import android.view.View;
 import android.view.Gravity;
 import android.view.LayoutInflater;
-import android.view.View.OnFocusChangeListener;
-import android.widget.ImageView;
-import android.widget.TextView;
 import android.widget.LinearLayout;
 import android.util.AttributeSet;
 
@@ -33,10 +30,6 @@
 import static android.media.session.PlaybackState.ACTION_PAUSE;
 import static android.media.session.PlaybackState.ACTION_PLAY;
 
-import static com.android.systemui.tv.pip.PipManager.PLAYBACK_STATE_PLAYING;
-import static com.android.systemui.tv.pip.PipManager.PLAYBACK_STATE_PAUSED;
-import static com.android.systemui.tv.pip.PipManager.PLAYBACK_STATE_UNAVAILABLE;
-
 
 /**
  * A view containing PIP controls including fullscreen, close, and media controls.
@@ -145,9 +138,9 @@
                 }
                 long actions = mMediaController.getPlaybackState().getActions();
                 int state = mMediaController.getPlaybackState().getState();
-                if (mPipManager.getPlaybackState() == PLAYBACK_STATE_PAUSED) {
+                if (mPipManager.getPlaybackState() == PipManager.PLAYBACK_STATE_PAUSED) {
                     mMediaController.getTransportControls().play();
-                } else if (mPipManager.getPlaybackState() == PLAYBACK_STATE_PLAYING) {
+                } else if (mPipManager.getPlaybackState() == PipManager.PLAYBACK_STATE_PLAYING) {
                     mMediaController.getTransportControls().pause();
                 }
                 // View will be updated later in {@link mMediaControllerCallback}
@@ -188,11 +181,11 @@
 
     private void updatePlayPauseView() {
         int state = mPipManager.getPlaybackState();
-        if (state == PLAYBACK_STATE_UNAVAILABLE) {
+        if (state == PipManager.PLAYBACK_STATE_UNAVAILABLE) {
             mPlayPauseButtonView.setVisibility(View.GONE);
         } else {
             mPlayPauseButtonView.setVisibility(View.VISIBLE);
-            if (state == PLAYBACK_STATE_PLAYING) {
+            if (state == PipManager.PLAYBACK_STATE_PLAYING) {
                 mPlayPauseButtonView.setImageResource(R.drawable.ic_pause_white_24dp);
                 mPlayPauseButtonView.setText(R.string.pip_pause);
             } else {
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipManager.java b/packages/SystemUI/src/com/android/systemui/pip/tv/PipManager.java
similarity index 92%
rename from packages/SystemUI/src/com/android/systemui/tv/pip/PipManager.java
rename to packages/SystemUI/src/com/android/systemui/pip/tv/PipManager.java
index cd98d19..5ee825c 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipManager.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/tv/PipManager.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.systemui.tv.pip;
+package com.android.systemui.pip.tv;
 
 import android.app.ActivityManager.RunningTaskInfo;
 import android.app.ActivityManager.StackInfo;
@@ -25,7 +25,6 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.content.pm.PackageManager;
 import android.content.res.Resources;
 import android.graphics.Rect;
 import android.media.session.MediaController;
@@ -33,17 +32,12 @@
 import android.media.session.PlaybackState;
 import android.os.Debug;
 import android.os.Handler;
-import android.os.Looper;
 import android.os.RemoteException;
 import android.os.SystemProperties;
 import android.text.TextUtils;
 import android.util.Log;
 import android.util.Pair;
 import android.view.IWindowManager;
-import android.view.InputChannel;
-import android.view.InputEvent;
-import android.view.InputEventReceiver;
-import android.view.WindowManagerGlobal;
 import com.android.systemui.Prefs;
 import com.android.systemui.R;
 import com.android.systemui.recents.misc.SystemServicesProxy;
@@ -53,7 +47,6 @@
 import java.util.List;
 
 import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
-import static android.view.WindowManager.INPUT_CONSUMER_PIP;
 import static com.android.systemui.Prefs.Key.TV_PICTURE_IN_PICTURE_ONBOARDING_SHOWN;
 
 /**
@@ -67,8 +60,6 @@
 
     private static PipManager sPipManager;
 
-    private static final int MAX_RUNNING_TASKS_COUNT = 10;
-
     /**
      * List of package and class name which are considered as Settings,
      * so PIP location should be adjusted to the left of the side panel.
@@ -163,9 +154,6 @@
     private boolean mOnboardingShown;
     private String[] mLastPackagesResourceGranted;
 
-    private InputChannel mInputChannel;
-    private PipInputEventReceiver mInputEventReceiver;
-
     private final Runnable mResizePinnedStackRunnable = new Runnable() {
         @Override
         public void run() {
@@ -203,25 +191,6 @@
                 }
             };
 
-    /**
-     * Input handler used for Pip windows.  Currently eats all the input events.
-     */
-    private final class PipInputEventReceiver extends InputEventReceiver {
-        public PipInputEventReceiver(InputChannel inputChannel, Looper looper) {
-            super(inputChannel, looper);
-        }
-
-        @Override
-        public void onInputEvent(InputEvent event) {
-            boolean handled = true;
-            try {
-                // To be implemented for input handling over Pip windows
-            } finally {
-                finishInputEvent(event, handled);
-            }
-        }
-    }
-
     private PipManager() { }
 
     /**
@@ -246,20 +215,6 @@
         mPipRecentsOverlayManager = new PipRecentsOverlayManager(context);
         mMediaSessionManager =
                 (MediaSessionManager) mContext.getSystemService(Context.MEDIA_SESSION_SERVICE);
-
-        PackageManager pm = mContext.getPackageManager();
-        if (!pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK_ONLY)) {
-            // Initialize the Pip input consumer
-            mInputChannel = new InputChannel();
-            try {
-                IWindowManager wm = WindowManagerGlobal.getWindowManagerService();
-                wm.destroyInputConsumer(INPUT_CONSUMER_PIP);
-                wm.createInputConsumer(INPUT_CONSUMER_PIP, mInputChannel);
-                mInputEventReceiver = new PipInputEventReceiver(mInputChannel, Looper.myLooper());
-            } catch (RemoteException e) {
-                Log.e(TAG, "Failed to create PIP input consumer", e);
-            }
-        }
     }
 
     private void loadConfigurationsAndApply() {
@@ -290,7 +245,7 @@
     /**
      * Updates the PIP per configuration changed.
      */
-    void onConfigurationChanged() {
+    public void onConfigurationChanged() {
         loadConfigurationsAndApply();
         mPipRecentsOverlayManager.onConfigurationChanged(mContext);
     }
@@ -350,11 +305,7 @@
      */
     private void showPipOverlay() {
         if (DEBUG) Log.d(TAG, "showPipOverlay()");
-        // Temporary workaround to prevent the overlay on phones
-        PackageManager pm = mContext.getPackageManager();
-        if (pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK_ONLY)) {
-            PipOverlayActivity.showPipOverlay(mContext);
-        }
+        PipOverlayActivity.showPipOverlay(mContext);
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipMenuActivity.java b/packages/SystemUI/src/com/android/systemui/pip/tv/PipMenuActivity.java
similarity index 97%
rename from packages/SystemUI/src/com/android/systemui/tv/pip/PipMenuActivity.java
rename to packages/SystemUI/src/com/android/systemui/pip/tv/PipMenuActivity.java
index 542a935..01d86b6 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipMenuActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/tv/PipMenuActivity.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.systemui.tv.pip;
+package com.android.systemui.pip.tv;
 
 import android.animation.Animator;
 import android.animation.AnimatorInflater;
@@ -23,7 +23,6 @@
 import android.view.View;
 
 import com.android.systemui.R;
-import com.android.systemui.Interpolators;
 
 /**
  * Activity to show the PIP menu to control PIP.
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipOnboardingActivity.java b/packages/SystemUI/src/com/android/systemui/pip/tv/PipOnboardingActivity.java
similarity index 98%
rename from packages/SystemUI/src/com/android/systemui/tv/pip/PipOnboardingActivity.java
rename to packages/SystemUI/src/com/android/systemui/pip/tv/PipOnboardingActivity.java
index 9a87cfc..57952f4 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipOnboardingActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/tv/PipOnboardingActivity.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.systemui.tv.pip;
+package com.android.systemui.pip.tv;
 
 import android.animation.Animator;
 import android.animation.AnimatorInflater;
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipOverlayActivity.java b/packages/SystemUI/src/com/android/systemui/pip/tv/PipOverlayActivity.java
similarity index 98%
rename from packages/SystemUI/src/com/android/systemui/tv/pip/PipOverlayActivity.java
rename to packages/SystemUI/src/com/android/systemui/pip/tv/PipOverlayActivity.java
index 011e159..f52121f 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipOverlayActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/tv/PipOverlayActivity.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.systemui.tv.pip;
+package com.android.systemui.pip.tv;
 
 import android.animation.Animator;
 import android.animation.AnimatorInflater;
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsControlsView.java b/packages/SystemUI/src/com/android/systemui/pip/tv/PipRecentsControlsView.java
similarity index 93%
rename from packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsControlsView.java
rename to packages/SystemUI/src/com/android/systemui/pip/tv/PipRecentsControlsView.java
index ffe96afa..a891d12 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsControlsView.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/tv/PipRecentsControlsView.java
@@ -14,26 +14,20 @@
  * limitations under the License.
  */
 
-package com.android.systemui.tv.pip;
+package com.android.systemui.pip.tv;
 
 import android.animation.Animator;
 import android.animation.AnimatorInflater;
-import android.animation.AnimatorListenerAdapter;
 import android.animation.AnimatorSet;
 import android.content.Context;
 import android.graphics.Rect;
 import android.util.AttributeSet;
 import android.view.KeyEvent;
 import android.view.View;
-import android.view.View.OnFocusChangeListener;
 import android.widget.FrameLayout;
 
 import com.android.systemui.R;
 
-import static com.android.systemui.tv.pip.PipManager.PLAYBACK_STATE_PLAYING;
-import static com.android.systemui.tv.pip.PipManager.PLAYBACK_STATE_PAUSED;
-import static com.android.systemui.tv.pip.PipManager.PLAYBACK_STATE_UNAVAILABLE;
-
 /**
  * An FrameLayout that contains {@link PipControlsView} with its scrim.
  */
@@ -49,7 +43,6 @@
     }
 
     private final PipManager mPipManager = PipManager.getInstance();
-    private Listener mListener;
     private PipControlsView mPipControlsView;
     private View mScrim;
     private Animator mFocusGainAnimator;
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsOverlayManager.java b/packages/SystemUI/src/com/android/systemui/pip/tv/PipRecentsOverlayManager.java
similarity index 93%
rename from packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsOverlayManager.java
rename to packages/SystemUI/src/com/android/systemui/pip/tv/PipRecentsOverlayManager.java
index 895b8a2..835bcbc 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsOverlayManager.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/tv/PipRecentsOverlayManager.java
@@ -14,11 +14,10 @@
  * limitations under the License.
  */
 
-package com.android.systemui.tv.pip;
+package com.android.systemui.pip.tv;
 
 import android.content.Context;
 import android.graphics.PixelFormat;
-import android.graphics.Rect;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -32,9 +31,6 @@
 import static android.view.Gravity.CENTER_HORIZONTAL;
 import static android.view.Gravity.TOP;
 import static android.view.View.MeasureSpec.UNSPECIFIED;
-import static com.android.systemui.tv.pip.PipManager.STATE_PIP_OVERLAY;
-import static com.android.systemui.tv.pip.PipManager.STATE_PIP_RECENTS;
-import static com.android.systemui.tv.pip.PipManager.STATE_PIP_RECENTS_FOCUSED;
 
 public class PipRecentsOverlayManager {
     private static final String TAG = "PipRecentsOverlayManager";
@@ -158,7 +154,7 @@
         mIsPipFocusedInRecent = true;
         mPipControlsView.startFocusGainAnimation();
         mWindowManager.updateViewLayout(mOverlayView, mPipRecentsControlsViewFocusedLayoutParams);
-        mPipManager.resizePinnedStack(STATE_PIP_RECENTS_FOCUSED);
+        mPipManager.resizePinnedStack(PipManager.STATE_PIP_RECENTS_FOCUSED);
         if (mTalkBackEnabled) {
             mPipControlsView.requestFocus();
             mPipControlsView.sendAccessibilityEvent(
@@ -177,7 +173,7 @@
         mIsPipFocusedInRecent = false;
         mPipControlsView.startFocusLossAnimation();
         mWindowManager.updateViewLayout(mOverlayView, mPipRecentsControlsViewLayoutParams);
-        mPipManager.resizePinnedStack(STATE_PIP_RECENTS);
+        mPipManager.resizePinnedStack(PipManager.STATE_PIP_RECENTS);
         if (mCallback != null) {
             mCallback.onRecentsFocused();
         }
@@ -198,7 +194,7 @@
         }
         mIsRecentsShown = true;
         mIsPipFocusedInRecent = true;
-        mPipManager.resizePinnedStack(STATE_PIP_RECENTS_FOCUSED);
+        mPipManager.resizePinnedStack(PipManager.STATE_PIP_RECENTS_FOCUSED);
         // Overlay view will be added after the resize animation ends, if any.
     }
 
@@ -212,7 +208,7 @@
         removePipRecentsOverlayView();
 
         if (mPipManager.isPipShown()) {
-            mPipManager.resizePinnedStack(STATE_PIP_OVERLAY);
+            mPipManager.resizePinnedStack(PipManager.STATE_PIP_OVERLAY);
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java b/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java
index e0cdb1a..d5218ed 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java
@@ -79,6 +79,8 @@
 import com.android.internal.app.AssistUtils;
 import com.android.internal.os.BackgroundThread;
 import com.android.systemui.R;
+import com.android.systemui.pip.tv.PipMenuActivity;
+import com.android.systemui.pip.tv.PipOnboardingActivity;
 import com.android.systemui.recents.RecentsDebugFlags;
 import com.android.systemui.recents.RecentsImpl;
 import com.android.systemui.recents.model.Task;
@@ -109,8 +111,8 @@
     final static List<String> sRecentsBlacklist;
     static {
         sRecentsBlacklist = new ArrayList<>();
-        sRecentsBlacklist.add("com.android.systemui.tv.pip.PipOnboardingActivity");
-        sRecentsBlacklist.add("com.android.systemui.tv.pip.PipMenuActivity");
+        sRecentsBlacklist.add(PipOnboardingActivity.class.getName());
+        sRecentsBlacklist.add(PipMenuActivity.class.getName());
     }
 
     private static SystemServicesProxy sSystemServicesProxy;
diff --git a/packages/SystemUI/src/com/android/systemui/recents/tv/RecentsTvActivity.java b/packages/SystemUI/src/com/android/systemui/recents/tv/RecentsTvActivity.java
index ecb12d3..a2a8199 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/tv/RecentsTvActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/tv/RecentsTvActivity.java
@@ -58,8 +58,8 @@
 import com.android.systemui.recents.tv.views.TaskStackHorizontalGridView;
 import com.android.systemui.recents.tv.views.TaskStackHorizontalViewAdapter;
 import com.android.systemui.statusbar.BaseStatusBar;
-import com.android.systemui.tv.pip.PipManager;
-import com.android.systemui.tv.pip.PipRecentsOverlayManager;
+import com.android.systemui.pip.tv.PipManager;
+import com.android.systemui.pip.tv.PipRecentsOverlayManager;
 
 import java.util.ArrayList;
 import java.util.Collections;
diff --git a/packages/SystemUI/src/com/android/systemui/recents/tv/RecentsTvImpl.java b/packages/SystemUI/src/com/android/systemui/recents/tv/RecentsTvImpl.java
index ef9de53..ac9a217 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/tv/RecentsTvImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/tv/RecentsTvImpl.java
@@ -25,7 +25,6 @@
 import android.os.SystemClock;
 import android.os.UserHandle;
 
-import com.android.systemui.SystemUIApplication;
 import com.android.systemui.recents.Recents;
 import com.android.systemui.recents.RecentsActivityLaunchState;
 import com.android.systemui.recents.RecentsConfiguration;
@@ -37,8 +36,7 @@
 import com.android.systemui.recents.model.TaskStack;
 import com.android.systemui.recents.model.ThumbnailData;
 import com.android.systemui.recents.tv.views.TaskCardView;
-import com.android.systemui.statusbar.tv.TvStatusBar;
-import com.android.systemui.tv.pip.PipManager;
+import com.android.systemui.pip.tv.PipManager;
 
 public class RecentsTvImpl extends RecentsImpl{
     public final static String RECENTS_TV_ACTIVITY =
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
index a7331d8..8a5a8a0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
@@ -248,6 +248,11 @@
         }
     }
 
+    @Override
+    public void updateMediaMetaData(boolean metaDataChanged, boolean allowEnterAnimation) {
+        // Do nothing, we don't want to display media art in the lock screen for a car.
+    }
+
     private int startActivityWithOptions(Intent intent, Bundle options) {
         int result = ActivityManager.START_CANCELED;
         try {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tv/TvStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/tv/TvStatusBar.java
index 3c83921..f5c60a0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tv/TvStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tv/TvStatusBar.java
@@ -27,7 +27,7 @@
 import com.android.systemui.statusbar.ActivatableNotificationView;
 import com.android.systemui.statusbar.BaseStatusBar;
 import com.android.systemui.statusbar.NotificationData;
-import com.android.systemui.tv.pip.PipManager;
+import com.android.systemui.pip.tv.PipManager;
 
 /**
  * Status bar implementation for "large screen" products that mostly present no on-screen nav
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipUI.java b/packages/SystemUI/src/com/android/systemui/tv/pip/PipUI.java
deleted file mode 100644
index 3306cb3..0000000
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipUI.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * 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.systemui.tv.pip;
-
-import android.content.pm.PackageManager;
-import android.content.res.Configuration;
-
-import com.android.systemui.SystemUI;
-
-import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
-
-/**
- * Controls the picture-in-picture window.
- */
-public class PipUI extends SystemUI {
-    private boolean mSupportPip;
-
-    @Override
-    public void start() {
-        PackageManager pm = mContext.getPackageManager();
-        mSupportPip = pm.hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
-        if (!mSupportPip) {
-            return;
-        }
-        PipManager pipManager = PipManager.getInstance();
-        pipManager.initialize(mContext);
-    }
-
-    @Override
-    protected void onConfigurationChanged(Configuration newConfig) {
-        super.onConfigurationChanged(newConfig);
-        if (!mSupportPip) {
-            return;
-        }
-        PipManager.getInstance().onConfigurationChanged();
-    }
-}
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 8883c4b..de70026 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -132,6 +132,7 @@
 import com.android.server.am.BatteryStatsService;
 import com.android.server.connectivity.DataConnectionStats;
 import com.android.server.connectivity.KeepaliveTracker;
+import com.android.server.connectivity.MockableSystemProperties;
 import com.android.server.connectivity.Nat464Xlat;
 import com.android.server.connectivity.LingerMonitor;
 import com.android.server.connectivity.NetworkAgentInfo;
@@ -815,7 +816,8 @@
         mTestMode = SystemProperties.get("cm.test.mode").equals("true")
                 && SystemProperties.get("ro.build.type").equals("eng");
 
-        mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager);
+        mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
+                                   IoThread.get().getLooper(), new MockableSystemProperties());
 
         mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
 
diff --git a/services/core/java/com/android/server/UiModeManagerService.java b/services/core/java/com/android/server/UiModeManagerService.java
index bb5f62b..2825cf9 100644
--- a/services/core/java/com/android/server/UiModeManagerService.java
+++ b/services/core/java/com/android/server/UiModeManagerService.java
@@ -466,9 +466,8 @@
         if (mCarModeEnabled) {
             if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
                 adjustStatusBarCarModeLocked();
-
                 if (oldAction != null) {
-                    getContext().sendBroadcastAsUser(new Intent(oldAction), UserHandle.ALL);
+                    sendForegroundBroadcastToAllUsers(oldAction);
                 }
                 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
                 action = UiModeManager.ACTION_ENTER_CAR_MODE;
@@ -476,7 +475,7 @@
         } else if (isDeskDockState(mDockState)) {
             if (!isDeskDockState(mLastBroadcastState)) {
                 if (oldAction != null) {
-                    getContext().sendBroadcastAsUser(new Intent(oldAction), UserHandle.ALL);
+                    sendForegroundBroadcastToAllUsers(oldAction);
                 }
                 mLastBroadcastState = mDockState;
                 action = UiModeManager.ACTION_ENTER_DESK_MODE;
@@ -502,6 +501,7 @@
             Intent intent = new Intent(action);
             intent.putExtra("enableFlags", enableFlags);
             intent.putExtra("disableFlags", disableFlags);
+            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
             getContext().sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT, null,
                     mResultReceiver, null, Activity.RESULT_OK, null, null);
 
@@ -550,6 +550,11 @@
         }
     }
 
+    private void sendForegroundBroadcastToAllUsers(String action) {
+        getContext().sendBroadcastAsUser(new Intent(action)
+                .addFlags(Intent.FLAG_RECEIVER_FOREGROUND), UserHandle.ALL);
+    }
+
     private void updateAfterBroadcastLocked(String action, int enableFlags, int disableFlags) {
         // Launch a dock activity
         String category = null;
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 9a638a2..1edc8d2 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -219,7 +219,6 @@
 import android.util.SparseArray;
 import android.util.TimeUtils;
 import android.util.Xml;
-import android.view.Display;
 import android.view.Gravity;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -256,6 +255,7 @@
 import libcore.io.IoUtils;
 import libcore.util.EmptyArray;
 
+import static android.Manifest.permission.CHANGE_CONFIGURATION;
 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
 import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
@@ -279,6 +279,7 @@
 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
 import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
+import static android.os.Build.VERSION_CODES.N;
 import static android.os.Process.PROC_CHAR;
 import static android.os.Process.PROC_OUT_LONG;
 import static android.os.Process.PROC_PARENS;
@@ -293,6 +294,7 @@
 import static android.provider.Settings.System.FONT_SCALE;
 import static android.util.TypedValue.COMPLEX_UNIT_DIP;
 import static android.view.Display.DEFAULT_DISPLAY;
+
 import static com.android.internal.util.XmlUtils.readBooleanAttribute;
 import static com.android.internal.util.XmlUtils.readIntAttribute;
 import static com.android.internal.util.XmlUtils.readLongAttribute;
@@ -1130,10 +1132,11 @@
     private int mConfigurationSeq;
 
     /**
-     * Temp object used when global configuration is updated. It is also sent to outer world
-     * instead of {@link #getGlobalConfiguration} because we don't trust anyone...
+     * Temp object used when global and/or display override configuration is updated. It is also
+     * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
+     * anyone...
      */
-    private Configuration mTempGlobalConfig = new Configuration();
+    private Configuration mTempConfig = new Configuration();
 
     private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
             new UpdateConfigurationResult();
@@ -2717,14 +2720,14 @@
 
         mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
 
-        mTempGlobalConfig.setToDefaults();
-        mTempGlobalConfig.setLocales(LocaleList.getDefault());
-        mConfigurationSeq = mTempGlobalConfig.seq = 1;
+        mTempConfig.setToDefaults();
+        mTempConfig.setLocales(LocaleList.getDefault());
+        mConfigurationSeq = mTempConfig.seq = 1;
 
         mProcessCpuTracker.init();
 
         mStackSupervisor = new ActivityStackSupervisor(this);
-        mStackSupervisor.onConfigurationChanged(mTempGlobalConfig);
+        mStackSupervisor.onConfigurationChanged(mTempConfig);
         mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
         mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
         mActivityStarter = new ActivityStarter(this, mStackSupervisor);
@@ -4069,7 +4072,7 @@
     @Override
     public int getPackageProcessState(String packageName, String callingPackage) {
         if (!hasUsageStatsPermission(callingPackage)) {
-            enforceCallingPermission(android.Manifest.permission.GET_PACKAGE_IMPORTANCE,
+            enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
                     "getPackageProcessState");
         }
 
@@ -4079,20 +4082,12 @@
                 final ProcessRecord proc = mLruProcesses.get(i);
                 if (procState == ActivityManager.PROCESS_STATE_NONEXISTENT
                         || procState > proc.setProcState) {
-                    boolean found = false;
-                    for (int j=proc.pkgList.size()-1; j>=0 && !found; j--) {
-                        if (proc.pkgList.keyAt(j).equals(packageName)) {
-                            procState = proc.setProcState;
-                            found = true;
-                        }
+                    if (proc.pkgList.containsKey(packageName)) {
+                        procState = proc.setProcState;
+                        break;
                     }
-                    if (proc.pkgDeps != null && !found) {
-                        for (int j=proc.pkgDeps.size()-1; j>=0; j--) {
-                            if (proc.pkgDeps.valueAt(j).equals(packageName)) {
-                                procState = proc.setProcState;
-                                break;
-                            }
-                        }
+                    if (proc.pkgDeps != null && proc.pkgDeps.contains(packageName)) {
+                        procState = proc.setProcState;
                     }
                 }
             }
@@ -4762,23 +4757,12 @@
             if (r == null) {
                 return;
             }
-            TaskRecord task = r.task;
-            if (task != null && (!task.mFullscreen || !task.getStack().mFullscreen)) {
-                // Fixed screen orientation isn't supported when activities aren't in full screen
-                // mode.
-                return;
-            }
             final long origId = Binder.clearCallingIdentity();
-            mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
-            Configuration config = mWindowManager.updateOrientationFromAppTokens(
-                    getGlobalConfiguration(), r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
-            if (config != null) {
-                r.frozenBeforeDestroy = true;
-                if (!updateConfigurationLocked(config, r, false)) {
-                    mStackSupervisor.resumeFocusedStackTopActivityLocked();
-                }
+            try {
+                r.setRequestedOrientation(requestedOrientation);
+            } finally {
+                Binder.restoreCallingIdentity(origId);
             }
-            Binder.restoreCallingIdentity(origId);
         }
     }
 
@@ -14877,6 +14861,7 @@
         }
         if (dumpPackage == null) {
             pw.println("  mGlobalConfiguration: " + getGlobalConfiguration());
+            mStackSupervisor.dumpDisplayConfigs(pw, "  ");
         }
         if (dumpAll) {
             pw.println("  mConfigWillChange: " + getFocusedStack().mConfigWillChange);
@@ -18939,8 +18924,7 @@
 
     @Override
     public void updatePersistentConfiguration(Configuration values) {
-        enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
-                "updatePersistentConfiguration()");
+        enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()");
         enforceWriteSettingsPermission("updatePersistentConfiguration()");
         if (values == null) {
             throw new NullPointerException("Configuration must not be null");
@@ -18965,12 +18949,16 @@
     private void updateFontScaleIfNeeded(@UserIdInt int userId) {
         final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
                 FONT_SCALE, 1.0f, userId);
-        if (getGlobalConfiguration().fontScale != scaleFactor) {
-            final Configuration configuration = mWindowManager.computeNewConfiguration();
-            configuration.fontScale = scaleFactor;
-            synchronized (this) {
-                updatePersistentConfigurationLocked(configuration, userId);
+
+        synchronized (this) {
+            if (getGlobalConfiguration().fontScale == scaleFactor) {
+                return;
             }
+
+            final Configuration configuration
+                    = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
+            configuration.fontScale = scaleFactor;
+            updatePersistentConfigurationLocked(configuration, userId);
         }
     }
 
@@ -18995,21 +18983,20 @@
 
     @Override
     public boolean updateConfiguration(Configuration values) {
-        enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
-                "updateConfiguration()");
+        enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
 
         synchronized(this) {
             if (values == null && mWindowManager != null) {
                 // sentinel: fetch the current configuration from the window manager
-                values = mWindowManager.computeNewConfiguration();
+                values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
             }
 
             if (mWindowManager != null) {
+                // Update OOM levels based on display size.
                 mProcessList.applyDisplaySize(mWindowManager);
             }
 
             final long origId = Binder.clearCallingIdentity();
-
             try {
                 if (values != null) {
                     Settings.System.clearConfiguration(values);
@@ -19096,8 +19083,8 @@
     /** Update default (global) configuration and notify listeners about changes. */
     private int updateGlobalConfiguration(@NonNull Configuration values, boolean initLocale,
             boolean persistent, int userId, boolean deferResume) {
-        mTempGlobalConfig.setTo(getGlobalConfiguration());
-        final int changes = mTempGlobalConfig.updateFrom(values);
+        mTempConfig.setTo(getGlobalConfiguration());
+        final int changes = mTempConfig.updateFrom(values);
         if (changes == 0) {
             return 0;
         }
@@ -19124,33 +19111,33 @@
         }
 
         mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
-        mTempGlobalConfig.seq = mConfigurationSeq;
+        mTempConfig.seq = mConfigurationSeq;
 
         // Update stored global config and notify everyone about the change.
-        mStackSupervisor.onConfigurationChanged(mTempGlobalConfig);
+        mStackSupervisor.onConfigurationChanged(mTempConfig);
 
-        Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempGlobalConfig);
+        Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
         // TODO(multi-display): Update UsageEvents#Event to include displayId.
-        mUsageStatsService.reportConfigurationChange(mTempGlobalConfig,
+        mUsageStatsService.reportConfigurationChange(mTempConfig,
                 mUserController.getCurrentUserIdLocked());
 
         // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
-        mShowDialogs = shouldShowDialogs(mTempGlobalConfig, mInVrMode);
+        mShowDialogs = shouldShowDialogs(mTempConfig, mInVrMode);
 
         AttributeCache ac = AttributeCache.instance();
         if (ac != null) {
-            ac.updateConfiguration(mTempGlobalConfig);
+            ac.updateConfiguration(mTempConfig);
         }
 
         // Make sure all resources in our process are updated right now, so that anyone who is going
         // to retrieve resource values after we return will be sure to get the new ones. This is
         // especially important during boot, where the first config change needs to guarantee all
         // resources have that config before following boot code is executed.
-        mSystemThread.applyConfigurationToResources(mTempGlobalConfig);
+        mSystemThread.applyConfigurationToResources(mTempConfig);
 
         // We need another copy of global config because we're scheduling some calls instead of
         // running them in place. We need to be sure that object we send will be handled unchanged.
-        final Configuration configCopy = new Configuration(mTempGlobalConfig);
+        final Configuration configCopy = new Configuration(mTempConfig);
         if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
             Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
             msg.obj = configCopy;
@@ -19158,16 +19145,6 @@
             mHandler.sendMessage(msg);
         }
 
-        // TODO(multi-display): Clear also on secondary display density change?
-        final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
-        if (isDensityChange) {
-            // Reset the unsupported display size dialog.
-            mUiHandler.sendEmptyMessage(SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG);
-
-            killAllBackgroundProcessesExcept(Build.VERSION_CODES.N,
-                    ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
-        }
-
         for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
             ProcessRecord app = mLruProcesses.get(i);
             try {
@@ -19197,13 +19174,116 @@
                     UserHandle.USER_ALL);
         }
 
+        // Override configuration of the default display duplicates global config, so we need to
+        // update it also. This will also notify WindowManager about changes.
+        performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
+                DEFAULT_DISPLAY);
+
+        return changes;
+    }
+
+    @Override
+    public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
+        enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
+
+        synchronized (this) {
+            if (values == null && mWindowManager != null) {
+                // sentinel: fetch the current configuration from the window manager
+                values = mWindowManager.computeNewConfiguration(displayId);
+            }
+
+            if (mWindowManager != null) {
+                // Update OOM levels based on display size.
+                mProcessList.applyDisplaySize(mWindowManager);
+            }
+
+            final long origId = Binder.clearCallingIdentity();
+            try {
+                if (values != null) {
+                    Settings.System.clearConfiguration(values);
+                }
+                updateDisplayOverrideConfigurationLocked(values, null /* starting */,
+                        false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
+                return mTmpUpdateConfigurationResult.changes != 0;
+            } finally {
+                Binder.restoreCallingIdentity(origId);
+            }
+        }
+    }
+
+    boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
+            boolean deferResume, int displayId) {
+        return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
+                displayId, null /* result */);
+    }
+
+    /**
+     * Updates override configuration specific for the selected display. If no config is provided,
+     * new one will be computed in WM based on current display info.
+     */
+    private boolean updateDisplayOverrideConfigurationLocked(Configuration values,
+            ActivityRecord starting, boolean deferResume, int displayId,
+            UpdateConfigurationResult result) {
+        int changes = 0;
+        boolean kept = true;
+
+        if (mWindowManager != null) {
+            mWindowManager.deferSurfaceLayout();
+        }
+        try {
+            if (values != null) {
+                if (displayId == DEFAULT_DISPLAY) {
+                    // Override configuration of the default display duplicates global config, so
+                    // we're calling global config update instead for default display. It will also
+                    // apply the correct override config.
+                    changes = updateGlobalConfiguration(values, false /* initLocale */,
+                            false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
+                } else {
+                    changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
+                }
+            }
+
+            kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
+        } finally {
+            if (mWindowManager != null) {
+                mWindowManager.continueSurfaceLayout();
+            }
+        }
+
+        if (result != null) {
+            result.changes = changes;
+            result.activityRelaunched = !kept;
+        }
+        return kept;
+    }
+
+    private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
+            int displayId) {
+        mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
+        final int changes = mTempConfig.updateFrom(values);
+        if (changes == 0) {
+            return 0;
+        }
+
+        Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " " + mTempConfig
+                + " for displayId=" + displayId);
+        mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
+
+        final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
+        if (isDensityChange) {
+            // Reset the unsupported display size dialog.
+            mUiHandler.sendEmptyMessage(SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG);
+
+            killAllBackgroundProcessesExcept(N, ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
+        }
+
         // Update the configuration with WM first and check if any of the stacks need to be resized
         // due to the configuration change. If so, resize the stacks now and do any relaunches if
         // necessary. This way we don't need to relaunch again afterwards in
         // ensureActivityConfigurationLocked().
         if (mWindowManager != null) {
             final int[] resizedStacks =
-                    mWindowManager.setNewConfiguration(mTempGlobalConfig);
+                    mWindowManager.setNewDisplayOverrideConfiguration(mTempConfig, displayId);
             if (resizedStacks != null) {
                 for (int stackId : resizedStacks) {
                     resizeStackWithBoundsFromWindowManager(stackId, deferResume);
@@ -22403,4 +22483,29 @@
         // before the profile user is unlocked.
         return rInfo != null && rInfo.activityInfo != null;
     }
+
+    /**
+     * Attach an agent to the specified process (proces name or PID)
+     */
+    public void attachAgent(String process, String path) {
+        try {
+            synchronized (this) {
+                ProcessRecord proc = findProcessLocked(process, UserHandle.USER_SYSTEM, "attachAgent");
+                if (proc == null || proc.thread == null) {
+                    throw new IllegalArgumentException("Unknown process: " + process);
+                }
+
+                boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
+                if (!isDebuggable) {
+                    if ((proc.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
+                        throw new SecurityException("Process not debuggable: " + proc);
+                    }
+                }
+
+                proc.thread.attachAgent(path);
+            }
+        } catch (RemoteException e) {
+            throw new IllegalStateException("Process disappeared");
+        }
+    }
 }
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index c7a04c1..7a692b6 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -220,6 +220,8 @@
                     return runTask(pw);
                 case "write":
                     return runWrite(pw);
+                case "attach-agent":
+                    return runAttachAgent(pw);
                 default:
                     return handleDefaultCommands(cmd);
             }
@@ -2462,6 +2464,21 @@
         return 0;
     }
 
+    int runAttachAgent(PrintWriter pw) {
+        // TODO: revisit the permissions required for attaching agents
+        mInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
+                "attach-agent");
+        String process = getNextArgRequired();
+        String agent = getNextArgRequired();
+        String opt;
+        if ((opt = getNextArg()) != null) {
+            pw.println("Error: Unknown option: " + opt);
+            return -1;
+        }
+        mInternal.attachAgent(process, agent);
+        return 0;
+    }
+
     @Override
     public void onHelp() {
         PrintWriter pw = getOutPrintWriter();
@@ -2619,6 +2636,8 @@
             pw.println("      Optionally controls lenient background check mode, returns current mode.");
             pw.println("  get-uid-state <UID>");
             pw.println("      Gets the process state of an app given its <UID>.");
+            pw.println("  attach-agent <PROCESS> <FILE>");
+            pw.println("    Attach an agent to the specified <PROCESS>, which may be either a process name or a PID.");
             pw.println("  get-config");
             pw.println("      Rtrieve the configuration and any recent configurations of the device.");
             pw.println("  suppress-resize-config-changes <true|false>");
diff --git a/services/core/java/com/android/server/am/ActivityRecord.java b/services/core/java/com/android/server/am/ActivityRecord.java
index b7618a1..abe4f30 100644
--- a/services/core/java/com/android/server/am/ActivityRecord.java
+++ b/services/core/java/com/android/server/am/ActivityRecord.java
@@ -1646,6 +1646,17 @@
         return null;
     }
 
+    /**
+     * @return display id to which this record is attached, -1 if not attached.
+     */
+    int getDisplayId() {
+        final ActivityStack stack = getStack();
+        if (stack == null) {
+            return -1;
+        }
+        return stack.mDisplayId;
+    }
+
     final boolean isDestroyable() {
         if (finishing || app == null || state == ActivityState.DESTROYING
                 || state == ActivityState.DESTROYED) {
@@ -1704,6 +1715,26 @@
         }
     }
 
+    void setRequestedOrientation(int requestedOrientation) {
+        if (task != null && (!task.mFullscreen || !task.getStack().mFullscreen)) {
+            // Fixed screen orientation isn't supported when activities aren't in full screen mode.
+            return;
+        }
+
+        service.mWindowManager.setAppOrientation(appToken, requestedOrientation);
+        final int displayId = getDisplayId();
+        final Configuration config = service.mWindowManager.updateOrientationFromAppTokens(
+                mStackSupervisor.getDisplayOverrideConfiguration(displayId),
+                mayFreezeScreenLocked(app) ? appToken : null, displayId);
+        if (config != null) {
+            frozenBeforeDestroy = true;
+            if (!service.updateDisplayOverrideConfigurationLocked(config, this,
+                    false /* deferResume */, displayId)) {
+                mStackSupervisor.resumeFocusedStackTopActivityLocked();
+            }
+        }
+    }
+
     // TODO: now used only in one place to address race-condition. Remove when that will be fixed.
     void setLastReportedConfiguration(@NonNull Configuration config) {
         mLastReportedConfiguration.setTo(config);
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index 55066fd..22d8078 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/am/ActivityStack.java
@@ -2285,13 +2285,14 @@
             // the screen based on the new activity order.
             boolean notUpdated = true;
             if (mStackSupervisor.isFocusedStack(this)) {
-                Configuration config = mWindowManager.updateOrientationFromAppTokens(
-                        mService.getGlobalConfiguration(),
-                        next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
+                final Configuration config = mWindowManager.updateOrientationFromAppTokens(
+                        mStackSupervisor.getDisplayOverrideConfiguration(mDisplayId),
+                        next.mayFreezeScreenLocked(next.app) ? next.appToken : null, mDisplayId);
                 if (config != null) {
                     next.frozenBeforeDestroy = true;
                 }
-                notUpdated = !mService.updateConfigurationLocked(config, next, false);
+                notUpdated = !mService.updateDisplayOverrideConfigurationLocked(config, next,
+                        false /* deferResume */, mDisplayId);
             }
 
             if (notUpdated) {
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index a111230..ca36908 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -419,7 +419,7 @@
     }
 
     @Override
-    protected ConfigurationContainer getChildAt(int index) {
+    protected ActivityDisplay getChildAt(int index) {
         return mActivityDisplays.valueAt(index);
     }
 
@@ -428,6 +428,24 @@
         return null;
     }
 
+    Configuration getDisplayOverrideConfiguration(int displayId) {
+        final ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
+        if (activityDisplay == null) {
+            throw new IllegalArgumentException("No display found with id: " + displayId);
+        }
+
+        return activityDisplay.getOverrideConfiguration();
+    }
+
+    void setDisplayOverrideConfiguration(Configuration overrideConfiguration, int displayId) {
+        final ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
+        if (activityDisplay == null) {
+            throw new IllegalArgumentException("No display found with id: " + displayId);
+        }
+
+        activityDisplay.onOverrideConfigurationChanged(overrideConfiguration);
+    }
+
     static class FindTaskResult {
         ActivityRecord r;
         boolean matchedByRootAffinity;
@@ -1190,20 +1208,20 @@
             r.startLaunchTickingLocked();
         }
 
-        // Have the window manager re-evaluate the orientation of
-        // the screen based on the new activity order.  Note that
-        // as a result of this, it can call back into the activity
-        // manager with a new orientation.  We don't care about that,
-        // because the activity is not currently running so we are
-        // just restarting it anyway.
+        // Have the window manager re-evaluate the orientation of the screen based on the new
+        // activity order.  Note that as a result of this, it can call back into the activity
+        // manager with a new orientation.  We don't care about that, because the activity is not
+        // currently running so we are just restarting it anyway.
         if (checkConfig) {
-            Configuration config = mWindowManager.updateOrientationFromAppTokens(
-                    mService.getGlobalConfiguration(),
-                    r.mayFreezeScreenLocked(app) ? r.appToken : null);
+            final int displayId = r.getDisplayId();
+            final Configuration config = mWindowManager.updateOrientationFromAppTokens(
+                    getDisplayOverrideConfiguration(displayId),
+                    r.mayFreezeScreenLocked(app) ? r.appToken : null, displayId);
             // Deferring resume here because we're going to launch new activity shortly.
             // We don't want to perform a redundant launch of the same record while ensuring
             // configurations and trying to resume top activity of focused stack.
-            mService.updateConfigurationLocked(config, r, false, true /* deferResume */);
+            mService.updateDisplayOverrideConfigurationLocked(config, r, true /* deferResume */,
+                    displayId);
         }
 
         r.app = app;
@@ -3156,6 +3174,20 @@
     }
 
     /**
+     * Dump all connected displays' configurations.
+     * @param prefix Prefix to apply to each line of the dump.
+     */
+    void dumpDisplayConfigs(PrintWriter pw, String prefix) {
+        pw.print(prefix); pw.println("Display override configurations:");
+        final int displayCount = mActivityDisplays.size();
+        for (int i = 0; i < displayCount; i++) {
+            final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(i);
+            pw.print(prefix); pw.print("  "); pw.print(activityDisplay.mDisplayId); pw.print(": ");
+                    pw.println(activityDisplay.getOverrideConfiguration());
+        }
+    }
+
+    /**
      * Dumps the activities matching the given {@param name} in the either the focused stack
      * or all visible stacks if {@param dumpVisibleStacks} is true.
      */
diff --git a/services/core/java/com/android/server/connectivity/MockableSystemProperties.java b/services/core/java/com/android/server/connectivity/MockableSystemProperties.java
new file mode 100644
index 0000000..4f68652
--- /dev/null
+++ b/services/core/java/com/android/server/connectivity/MockableSystemProperties.java
@@ -0,0 +1,25 @@
+/*
+ * 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.connectivity;
+
+import android.os.SystemProperties;
+
+public class MockableSystemProperties {
+    public boolean getBoolean(String key, boolean def) {
+        return SystemProperties.getBoolean(key, def);
+    }
+}
diff --git a/services/core/java/com/android/server/connectivity/Tethering.java b/services/core/java/com/android/server/connectivity/Tethering.java
index 921fd23..0beb227 100644
--- a/services/core/java/com/android/server/connectivity/Tethering.java
+++ b/services/core/java/com/android/server/connectivity/Tethering.java
@@ -52,7 +52,6 @@
 import android.os.Parcel;
 import android.os.RemoteException;
 import android.os.ResultReceiver;
-import android.os.SystemProperties;
 import android.os.UserHandle;
 import android.provider.Settings;
 import android.telephony.CarrierConfigManager;
@@ -62,6 +61,7 @@
 import android.util.Log;
 import android.util.SparseArray;
 
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.telephony.IccCardConstants;
 import com.android.internal.telephony.TelephonyIntents;
 import com.android.internal.util.IndentingPrintWriter;
@@ -69,7 +69,6 @@
 import com.android.internal.util.Protocol;
 import com.android.internal.util.State;
 import com.android.internal.util.StateMachine;
-import com.android.server.IoThread;
 import com.android.server.connectivity.tethering.IControlsTethering;
 import com.android.server.connectivity.tethering.IPv6TetheringCoordinator;
 import com.android.server.connectivity.tethering.TetherInterfaceStateMachine;
@@ -100,6 +99,8 @@
     private final static boolean DBG = false;
     private final static boolean VDBG = false;
 
+    protected static final String DISABLE_PROVISIONING_SYSPROP_KEY = "net.tethering.noprovisioning";
+
     private static final Class[] messageClasses = {
             Tethering.class, TetherMasterSM.class, TetherInterfaceStateMachine.class
     };
@@ -127,6 +128,7 @@
     private final INetworkStatsService mStatsService;
     private final INetworkPolicyManager mPolicyManager;
     private final Looper mLooper;
+    private final MockableSystemProperties mSystemProperties;
 
     private static class TetherState {
         public final TetherInterfaceStateMachine mStateMachine;
@@ -180,18 +182,19 @@
     private boolean mWifiTetherRequested;
 
     public Tethering(Context context, INetworkManagementService nmService,
-            INetworkStatsService statsService, INetworkPolicyManager policyManager) {
+            INetworkStatsService statsService, INetworkPolicyManager policyManager,
+            Looper looper, MockableSystemProperties systemProperties) {
         mContext = context;
         mNMService = nmService;
         mStatsService = statsService;
         mPolicyManager = policyManager;
+        mLooper = looper;
+        mSystemProperties = systemProperties;
 
         mPublicSync = new Object();
 
         mTetherStates = new ArrayMap<>();
 
-        // make our own thread so we don't anr the system
-        mLooper = IoThread.get().getLooper();
         mTetherMasterSM = new TetherMasterSM("TetherMaster", mLooper);
         mTetherMasterSM.start();
 
@@ -394,10 +397,11 @@
      *
      * @return a boolean - {@code true} indicating tether provisioning is required by the carrier.
      */
-    private boolean isTetherProvisioningRequired() {
+    @VisibleForTesting
+    protected boolean isTetherProvisioningRequired() {
         String[] provisionApp = mContext.getResources().getStringArray(
                 com.android.internal.R.array.config_mobile_hotspot_provision_app);
-        if (SystemProperties.getBoolean("net.tethering.noprovisioning", false)
+        if (mSystemProperties.getBoolean(DISABLE_PROVISIONING_SYSPROP_KEY, false)
                 || provisionApp == null) {
             return false;
         }
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index b8b16d5..6e5c025 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -5408,18 +5408,15 @@
                 }
             } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
                 mKeyguardHidden = false;
-                boolean willDismiss = false;
+                boolean dismissKeyguard = false;
+                final boolean trusted = mKeyguardDelegate.isTrusted();
                 if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
-                    final boolean trusted = mKeyguardDelegate.isTrusted();
-                    willDismiss = trusted && mKeyguardOccluded && mKeyguardDelegate != null
-                            && mKeyguardDelegate.isShowing();
+                    final boolean willDismiss = trusted && mKeyguardOccluded
+                            && mKeyguardDelegate != null && mKeyguardDelegate.isShowing();
                     if (willDismiss) {
                         mCurrentlyDismissingKeyguard = true;
                     }
-
-                    // Only launch the next keyguard unlock window once per window.
-                    mHandler.post(() -> mKeyguardDelegate.dismiss(
-                            trusted /* allowWhileOccluded */));
+                    dismissKeyguard = true;
                 }
 
                 // If we are currently dismissing Keyguard, there is no need to unocclude it.
@@ -5430,6 +5427,12 @@
                                 | FINISH_LAYOUT_REDO_WALLPAPER;
                     }
                 }
+
+                if (dismissKeyguard) {
+                    // Only launch the next keyguard unlock window once per window.
+                    mHandler.post(() -> mKeyguardDelegate.dismiss(
+                            trusted /* allowWhileOccluded */));
+                }
             } else {
                 mWinDismissingKeyguard = null;
                 mSecureDismissingKeyguard = false;
diff --git a/services/core/java/com/android/server/wm/AppWindowToken.java b/services/core/java/com/android/server/wm/AppWindowToken.java
index 56eaa83..d46b535 100644
--- a/services/core/java/com/android/server/wm/AppWindowToken.java
+++ b/services/core/java/com/android/server/wm/AppWindowToken.java
@@ -949,7 +949,7 @@
 
             mService.updateFocusedWindowLocked(
                     UPDATE_FOCUS_WILL_PLACE_SURFACES, true /*updateInputWindows*/);
-            mService.getDefaultDisplayContentLocked().setLayoutNeeded();
+            getDisplayContent().setLayoutNeeded();
             mService.mWindowPlacerLocked.performSurfacePlacement();
             Binder.restoreCallingIdentity(origId);
             return true;
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 10fecf4..7cd9971 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -2256,6 +2256,8 @@
     }
 
     void updateWallpaperForAnimator(WindowAnimator animator) {
+        resetAnimationBackgroundAnimator();
+
         final WindowList windows = mWindows;
         WindowState detachedWallpaper = null;
 
diff --git a/services/core/java/com/android/server/wm/DockedStackDividerController.java b/services/core/java/com/android/server/wm/DockedStackDividerController.java
index 8b5f62e..f75f224 100644
--- a/services/core/java/com/android/server/wm/DockedStackDividerController.java
+++ b/services/core/java/com/android/server/wm/DockedStackDividerController.java
@@ -371,6 +371,7 @@
     }
 
     void notifyDockedStackExistsChanged(boolean exists) {
+        // TODO(multi-display): Perform all actions only for current display.
         final int size = mDockedStackListeners.beginBroadcast();
         for (int i = 0; i < size; ++i) {
             final IDockedStackListener listener = mDockedStackListeners.getBroadcastItem(i);
diff --git a/services/core/java/com/android/server/wm/InputMonitor.java b/services/core/java/com/android/server/wm/InputMonitor.java
index 065a3dc..6a06ef3 100644
--- a/services/core/java/com/android/server/wm/InputMonitor.java
+++ b/services/core/java/com/android/server/wm/InputMonitor.java
@@ -16,6 +16,7 @@
 
 package com.android.server.wm;
 
+import static android.view.Display.DEFAULT_DISPLAY;
 import static android.view.WindowManager.INPUT_CONSUMER_PIP;
 import static android.view.WindowManager.INPUT_CONSUMER_WALLPAPER;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DRAG;
@@ -384,7 +385,8 @@
     /* Notifies that the input device configuration has changed. */
     @Override
     public void notifyConfigurationChanged() {
-        mService.sendNewConfiguration();
+        // TODO(multi-display): Notify proper displays that are associated with this input device.
+        mService.sendNewConfiguration(DEFAULT_DISPLAY);
 
         synchronized (mInputDevicesReadyMonitor) {
             if (!mInputDevicesReady) {
diff --git a/services/core/java/com/android/server/wm/RootWindowContainer.java b/services/core/java/com/android/server/wm/RootWindowContainer.java
index 24a0d1a..90e27ea 100644
--- a/services/core/java/com/android/server/wm/RootWindowContainer.java
+++ b/services/core/java/com/android/server/wm/RootWindowContainer.java
@@ -236,7 +236,7 @@
             mService.configureDisplayPolicyLocked(dc);
 
             // TODO(multi-display): Create an input channel for each display with touch capability.
-            if (displayId == Display.DEFAULT_DISPLAY) {
+            if (displayId == DEFAULT_DISPLAY) {
                 dc.mTapDetector = new TaskTapPointerEventListener(
                         mService, dc);
                 mService.registerPointerEventListener(dc.mTapDetector);
@@ -274,8 +274,7 @@
 
             mService.mStackIdToStack.put(stackId, stack);
             if (stackId == DOCKED_STACK_ID) {
-                mService.getDefaultDisplayContentLocked().mDividerControllerLocked
-                        .notifyDockedStackExistsChanged(true);
+                dc.mDividerControllerLocked.notifyDockedStackExistsChanged(true);
             }
         }
 
@@ -569,8 +568,33 @@
         }
     }
 
-    /** Set new config and return array of ids of stacks that were changed during update. */
-    int[] setGlobalConfigurationIfNeeded(Configuration newConfiguration) {
+    /**
+     * Set new display override config and return array of ids of stacks that were changed during
+     * update. If called for the default display, global configuration will also be updated.
+     */
+    int[] setDisplayOverrideConfigurationIfNeeded(Configuration newConfiguration, int displayId) {
+        final DisplayContent displayContent = getDisplayContent(displayId);
+        if (displayContent == null) {
+            throw new IllegalArgumentException("Display not found for id: " + displayId);
+        }
+
+        final Configuration currentConfig = displayContent.getOverrideConfiguration();
+        final boolean configChanged = currentConfig.diff(newConfiguration) != 0;
+        if (!configChanged) {
+            return null;
+        }
+        displayContent.onOverrideConfigurationChanged(currentConfig);
+
+        if (displayId == DEFAULT_DISPLAY) {
+            // Override configuration of the default display duplicates global config. In this case
+            // we also want to update the global config.
+            return setGlobalConfigurationIfNeeded(newConfiguration);
+        } else {
+            return updateStackBoundsAfterConfigChange(displayId);
+        }
+    }
+
+    private int[] setGlobalConfigurationIfNeeded(Configuration newConfiguration) {
         final boolean configChanged = getConfiguration().diff(newConfiguration) != 0;
         if (!configChanged) {
             return null;
@@ -603,6 +627,16 @@
         return mChangedStackList.isEmpty() ? null : ArrayUtils.convertToIntArray(mChangedStackList);
     }
 
+    /** Same as {@link #updateStackBoundsAfterConfigChange()} but only for a specific display. */
+    private int[] updateStackBoundsAfterConfigChange(int displayId) {
+        mChangedStackList.clear();
+
+        final DisplayContent dc = getDisplayContent(displayId);
+        dc.updateStackBoundsAfterConfigChange(mChangedStackList);
+
+        return mChangedStackList.isEmpty() ? null : ArrayUtils.convertToIntArray(mChangedStackList);
+    }
+
     private void prepareFreezingTaskBounds() {
         for (int i = mChildren.size() - 1; i >= 0; i--) {
             mChildren.get(i).prepareFreezingTaskBounds();
@@ -1145,8 +1179,10 @@
 
         if (mUpdateRotation) {
             if (DEBUG_ORIENTATION) Slog.d(TAG, "Performing post-rotate rotation");
-            if (mService.updateRotationUncheckedLocked(false)) {
-                mService.mH.sendEmptyMessage(SEND_NEW_CONFIGURATION);
+            // TODO(multi-display): Update rotation for different displays separately.
+            final int displayId = defaultDisplay.getDisplayId();
+            if (mService.updateRotationUncheckedLocked(false, displayId)) {
+                mService.mH.obtainMessage(SEND_NEW_CONFIGURATION, displayId).sendToTarget();
             } else {
                 mUpdateRotation = false;
             }
@@ -1231,7 +1267,7 @@
             final int displayId = dc.getDisplayId();
             final int dw = displayInfo.logicalWidth;
             final int dh = displayInfo.logicalHeight;
-            final boolean isDefaultDisplay = (displayId == Display.DEFAULT_DISPLAY);
+            final boolean isDefaultDisplay = (displayId == DEFAULT_DISPLAY);
             final WindowSurfacePlacer surfacePlacer = mService.mWindowPlacerLocked;
 
             // Reset for each display.
@@ -1259,9 +1295,9 @@
                 if (isDefaultDisplay
                         && (dc.pendingLayoutChanges & FINISH_LAYOUT_REDO_CONFIG) != 0) {
                     if (DEBUG_LAYOUT) Slog.v(TAG, "Computing new config from layout");
-                    if (mService.updateOrientationFromAppTokensLocked(true)) {
+                    if (mService.updateOrientationFromAppTokensLocked(true, displayId)) {
                         dc.setLayoutNeeded();
-                        mService.mH.sendEmptyMessage(SEND_NEW_CONFIGURATION);
+                        mService.mH.obtainMessage(SEND_NEW_CONFIGURATION, displayId).sendToTarget();
                     }
                 }
 
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 19c9b7d..7f543f9 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -327,8 +327,9 @@
      *                    the adjusted bounds's top.
      */
     void alignToAdjustedBounds(Rect adjustedBounds, Rect tempInsetBounds, boolean alignBottom) {
-        final Configuration overrideConfig = getOverrideConfiguration();
-        if (!isResizeable() || Configuration.EMPTY.equals(overrideConfig)) {
+        // Task override config might be empty, while display or stack override config isn't, so
+        // we have to check merged override config here.
+        if (!isResizeable() || Configuration.EMPTY.equals(getMergedOverrideConfiguration())) {
             return;
         }
 
@@ -340,7 +341,7 @@
             mTmpRect2.offsetTo(adjustedBounds.left, adjustedBounds.top);
         }
         setTempInsetBounds(tempInsetBounds);
-        resizeLocked(mTmpRect2, overrideConfig, false /* forced */);
+        resizeLocked(mTmpRect2, getOverrideConfiguration(), false /* forced */);
     }
 
     /** Return true if the current bound can get outputted to the rest of the system as-is. */
diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java
index 9effb8d..5402f0a 100644
--- a/services/core/java/com/android/server/wm/TaskStack.java
+++ b/services/core/java/com/android/server/wm/TaskStack.java
@@ -448,8 +448,7 @@
 
         // Calculate the current position.
         final DisplayInfo displayInfo = mDisplayContent.getDisplayInfo();
-        final int dividerSize = mService.getDefaultDisplayContentLocked()
-                .getDockedDividerController().getContentWidth();
+        final int dividerSize = mDisplayContent.getDockedDividerController().getContentWidth();
         final int dockSide = getDockSide(outBounds);
         final int dividerPosition = DockedDividerUtils.calculatePositionForBounds(outBounds,
                 dockSide, dividerSize);
@@ -783,13 +782,14 @@
             mAnimationBackgroundSurface.destroySurface();
             mAnimationBackgroundSurface = null;
         }
+        final DockedStackDividerController dividerController =
+                mDisplayContent.mDividerControllerLocked;
         mDisplayContent = null;
 
         mService.mWindowPlacerLocked.requestTraversal();
 
         if (mStackId == DOCKED_STACK_ID) {
-            mService.getDefaultDisplayContentLocked().mDividerControllerLocked
-                    .notifyDockedStackExistsChanged(false);
+            dividerController.notifyDockedStackExistsChanged(false);
         }
     }
 
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 40001b2..e6c9512 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -1413,7 +1413,7 @@
             win.applyAdjustForImeIfNeeded();
 
             if (type == TYPE_DOCK_DIVIDER) {
-                getDefaultDisplayContentLocked().getDockedDividerController().setWindow(win);
+                mRoot.getDisplayContent(displayId).getDockedDividerController().setWindow(win);
             }
 
             final WindowStateAnimator winAnimator = win.mWinAnimator;
@@ -1480,13 +1480,13 @@
             if (localLOGV || DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "addWindow: New client "
                     + client.asBinder() + ": window=" + win + " Callers=" + Debug.getCallers(5));
 
-            if (win.isVisibleOrAdding() && updateOrientationFromAppTokensLocked(false)) {
+            if (win.isVisibleOrAdding() && updateOrientationFromAppTokensLocked(false, displayId)) {
                 reportNewConfig = true;
             }
         }
 
         if (reportNewConfig) {
-            sendNewConfiguration();
+            sendNewConfiguration(displayId);
         }
 
         Binder.restoreCallingIdentity(origId);
@@ -1881,11 +1881,13 @@
                         == PackageManager.PERMISSION_GRANTED;
 
         long origId = Binder.clearCallingIdentity();
+        final int displayId;
         synchronized(mWindowMap) {
             WindowState win = windowForClientLocked(session, client, false);
             if (win == null) {
                 return 0;
             }
+            displayId = win.getDisplayId();
 
             WindowStateAnimator winAnimator = win.mWinAnimator;
             if (viewVisibility != View.GONE) {
@@ -2066,16 +2068,16 @@
             }
 
             if (wallpaperMayMove) {
-                getDefaultDisplayContentLocked().pendingLayoutChanges |=
+                win.getDisplayContent().pendingLayoutChanges |=
                         WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
             }
 
             win.setDisplayLayoutNeeded();
             win.mGivenInsetsPending = (flags&WindowManagerGlobal.RELAYOUT_INSETS_PENDING) != 0;
-            configChanged = updateOrientationFromAppTokensLocked(false);
+            configChanged = updateOrientationFromAppTokensLocked(false, displayId);
             mWindowPlacerLocked.performSurfacePlacement();
             if (toBeDisplayed && win.mIsWallpaper) {
-                DisplayInfo displayInfo = getDefaultDisplayInfoLocked();
+                DisplayInfo displayInfo = win.getDisplayContent().getDisplayInfo();
                 dc.mWallpaperController.updateWallpaperOffset(
                         win, displayInfo.logicalWidth, displayInfo.logicalHeight, false);
             }
@@ -2121,7 +2123,7 @@
         }
 
         if (configChanged) {
-            sendNewConfiguration();
+            sendNewConfiguration(displayId);
         }
         Binder.restoreCallingIdentity(origId);
         return result;
@@ -2156,9 +2158,8 @@
             }
             win.destroyOrSaveSurface();
         }
-        //TODO (multidisplay): Magnification is supported only for the default
-        if (mAccessibilityController != null
-                && win.getDisplayId() == DEFAULT_DISPLAY) {
+        // TODO(multidisplay): Magnification is supported only for the default display.
+        if (mAccessibilityController != null && win.getDisplayId() == DEFAULT_DISPLAY) {
             mAccessibilityController.onWindowTransitionLocked(win, transit);
         }
         return focusMayChange;
@@ -2278,7 +2279,7 @@
         }
     }
 
-    public void finishDrawingWindow(Session session, IWindow client) {
+    void finishDrawingWindow(Session session, IWindow client) {
         final long origId = Binder.clearCallingIdentity();
         try {
             synchronized (mWindowMap) {
@@ -2287,7 +2288,7 @@
                         + (win != null ? win.mWinAnimator.drawStateToString() : "null"));
                 if (win != null && win.mWinAnimator.finishDrawingLocked()) {
                     if ((win.mAttrs.flags & FLAG_SHOW_WALLPAPER) != 0) {
-                        getDefaultDisplayContentLocked().pendingLayoutChanges |=
+                        win.getDisplayContent().pendingLayoutChanges |=
                                 WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
                     }
                     win.setDisplayLayoutNeeded();
@@ -2530,32 +2531,34 @@
     }
 
     @Override
-    public Configuration updateOrientationFromAppTokens(
-            Configuration currentConfig, IBinder freezeThisOneIfNeeded) {
+    public Configuration updateOrientationFromAppTokens(Configuration currentConfig,
+            IBinder freezeThisOneIfNeeded, int displayId) {
         if (!checkCallingPermission(MANAGE_APP_TOKENS, "updateOrientationFromAppTokens()")) {
             throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
         }
 
-        Configuration config = null;
-        long ident = Binder.clearCallingIdentity();
-
-        synchronized(mWindowMap) {
-            config = updateOrientationFromAppTokensLocked(currentConfig,
-                    freezeThisOneIfNeeded);
+        final Configuration config;
+        final long ident = Binder.clearCallingIdentity();
+        try {
+            synchronized(mWindowMap) {
+                config = updateOrientationFromAppTokensLocked(currentConfig, freezeThisOneIfNeeded,
+                        displayId);
+            }
+        } finally {
+            Binder.restoreCallingIdentity(ident);
         }
 
-        Binder.restoreCallingIdentity(ident);
         return config;
     }
 
-    private Configuration updateOrientationFromAppTokensLocked(
-            Configuration currentConfig, IBinder freezeThisOneIfNeeded) {
+    private Configuration updateOrientationFromAppTokensLocked(Configuration currentConfig,
+            IBinder freezeThisOneIfNeeded, int displayId) {
         if (!mDisplayReady) {
             return null;
         }
         Configuration config = null;
 
-        if (updateOrientationFromAppTokensLocked(false)) {
+        if (updateOrientationFromAppTokensLocked(false, displayId)) {
             // If we changed the orientation but mOrientationChangeComplete is already true,
             // we used seamless rotation, and we don't need to freeze the screen.
             if (freezeThisOneIfNeeded != null && !mRoot.mOrientationChangeComplete) {
@@ -2564,7 +2567,7 @@
                     atoken.startFreezingScreen();
                 }
             }
-            config = computeNewConfigurationLocked();
+            config = computeNewConfigurationLocked(displayId);
 
         } else if (currentConfig != null) {
             // No obvious action we need to take, but if our current state mismatches the activity
@@ -2574,10 +2577,10 @@
             // to keep override configs clear of non-empty values (e.g. fontSize).
             mTempConfiguration.unset();
             mTempConfiguration.updateFrom(currentConfig);
-            computeScreenConfigurationLocked(mTempConfiguration);
+            computeScreenConfigurationLocked(mTempConfiguration, displayId);
             if (currentConfig.diff(mTempConfiguration) != 0) {
                 mWaitingForConfig = true;
-                final DisplayContent displayContent = getDefaultDisplayContentLocked();
+                final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
                 displayContent.setLayoutNeeded();
                 int anim[] = new int[2];
                 if (displayContent.isDimming()) {
@@ -2593,31 +2596,28 @@
         return config;
     }
 
-    /*
-     * Determine the new desired orientation of the display, returning
-     * a non-null new Configuration if it has changed from the current
-     * orientation.  IF TRUE IS RETURNED SOMEONE MUST CALL
-     * setNewConfiguration() TO TELL THE WINDOW MANAGER IT CAN UNFREEZE THE
-     * SCREEN.  This will typically be done for you if you call
-     * sendNewConfiguration().
+    /**
+     * Determine the new desired orientation of the display, returning a non-null new Configuration
+     * if it has changed from the current orientation.  IF TRUE IS RETURNED SOMEONE MUST CALL
+     * {@link #setNewDisplayOverrideConfiguration(Configuration, int)} TO TELL THE WINDOW MANAGER IT
+     * CAN UNFREEZE THE SCREEN.  This will typically be done for you if you call
+     * {@link #sendNewConfiguration(int)}.
      *
-     * The orientation is computed from non-application windows first. If none of
-     * the non-application windows specify orientation, the orientation is computed from
-     * application tokens.
-     * @see android.view.IWindowManager#updateOrientationFromAppTokens(
-     * android.os.IBinder)
+     * The orientation is computed from non-application windows first. If none of the
+     * non-application windows specify orientation, the orientation is computed from application
+     * tokens.
+     * @see android.view.IWindowManager#updateOrientationFromAppTokens(Configuration, IBinder, int)
      */
-    boolean updateOrientationFromAppTokensLocked(boolean inTransaction) {
+    boolean updateOrientationFromAppTokensLocked(boolean inTransaction, int displayId) {
         long ident = Binder.clearCallingIdentity();
         try {
-            // TODO: multi-display
-            int req = getDefaultDisplayContentLocked().getOrientation();
+            final int req = mRoot.getDisplayContent(displayId).getOrientation();
             if (req != mLastOrientation) {
                 mLastOrientation = req;
                 //send a message to Policy indicating orientation change to take
                 //action like disabling/enabling sensors etc.,
                 mPolicy.setCurrentOrientationLw(req);
-                if (updateRotationUncheckedLocked(inTransaction)) {
+                if (updateRotationUncheckedLocked(inTransaction, displayId)) {
                     // changed
                     return true;
                 }
@@ -2643,8 +2643,8 @@
     }
 
     @Override
-    public int[] setNewConfiguration(Configuration config) {
-        if (!checkCallingPermission(MANAGE_APP_TOKENS, "setNewConfiguration()")) {
+    public int[] setNewDisplayOverrideConfiguration(Configuration overrideConfig, int displayId) {
+        if (!checkCallingPermission(MANAGE_APP_TOKENS, "setNewDisplayOverrideConfiguration()")) {
             throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
         }
 
@@ -2653,7 +2653,7 @@
                 mWaitingForConfig = false;
                 mLastFinishedFreezeSource = "new-config";
             }
-            return mRoot.setGlobalConfigurationIfNeeded(config);
+            return mRoot.setDisplayOverrideConfigurationIfNeeded(overrideConfig, displayId);
         }
     }
 
@@ -4436,8 +4436,9 @@
         }
         try {
             Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "screenshotWallpaper");
-            return screenshotApplicationsInner(null, DEFAULT_DISPLAY, -1, -1, true, 1f,
-                    Bitmap.Config.ARGB_8888, true);
+            return screenshotApplicationsInner(null /* appToken */, DEFAULT_DISPLAY, -1 /* width */,
+                    -1 /* height */, true /* includeFullDisplay */, 1f /* frameScale */,
+                    Bitmap.Config.ARGB_8888, true /* wallpaperOnly */);
         } finally {
             Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
         }
@@ -4455,15 +4456,13 @@
             throw new SecurityException("Requires READ_FRAME_BUFFER permission");
         }
 
-        FgThread.getHandler().post(new Runnable() {
-            @Override
-            public void run() {
-                Bitmap bm = screenshotApplicationsInner(null, DEFAULT_DISPLAY, -1, -1,
-                        true, 1f, Bitmap.Config.ARGB_8888, false);
-                try {
-                    receiver.send(bm);
-                } catch (RemoteException e) {
-                }
+        FgThread.getHandler().post(() -> {
+            Bitmap bm = screenshotApplicationsInner(null /* appToken */, DEFAULT_DISPLAY,
+                    -1 /* width */, -1 /* height */, true /* includeFullDisplay */,
+                    1f /* frameScale */, Bitmap.Config.ARGB_8888, false /* wallpaperOnly */);
+            try {
+                receiver.send(bm);
+            } catch (RemoteException e) {
             }
         });
 
@@ -4864,16 +4863,17 @@
         if (mDeferredRotationPauseCount > 0) {
             mDeferredRotationPauseCount -= 1;
             if (mDeferredRotationPauseCount == 0) {
-                boolean changed = updateRotationUncheckedLocked(false);
+                // TODO(multi-display): Update rotation for different displays separately.
+                final int displayId = DEFAULT_DISPLAY;
+                final boolean changed = updateRotationUncheckedLocked(false, displayId);
                 if (changed) {
-                    mH.sendEmptyMessage(H.SEND_NEW_CONFIGURATION);
+                    mH.obtainMessage(H.SEND_NEW_CONFIGURATION, displayId).sendToTarget();
                 }
             }
         }
     }
 
-    private void updateRotationUnchecked(boolean alwaysSendConfiguration,
-            boolean forceRelayout) {
+    private void updateRotationUnchecked(boolean alwaysSendConfiguration, boolean forceRelayout) {
         if(DEBUG_ORIENTATION) Slog.v(TAG_WM, "updateRotationUnchecked:"
                 + " alwaysSendConfiguration=" + alwaysSendConfiguration
                 + " forceRelayout=" + forceRelayout);
@@ -4882,8 +4882,10 @@
 
         try {
             final boolean rotationChanged;
+            // TODO(multi-display): Update rotation for different displays separately.
+            int displayId = DEFAULT_DISPLAY;
             synchronized (mWindowMap) {
-                rotationChanged = updateRotationUncheckedLocked(false);
+                rotationChanged = updateRotationUncheckedLocked(false, displayId);
                 if (!rotationChanged || forceRelayout) {
                     getDefaultDisplayContentLocked().setLayoutNeeded();
                     mWindowPlacerLocked.performSurfacePlacement();
@@ -4891,22 +4893,20 @@
             }
 
             if (rotationChanged || alwaysSendConfiguration) {
-                sendNewConfiguration();
+                sendNewConfiguration(displayId);
             }
         } finally {
             Binder.restoreCallingIdentity(origId);
         }
     }
 
-
-    // TODO(multidisplay): Rotate any display?
     /**
-     * Updates the current rotation.
+     * Updates the current rotation of the specified display.
      *
-     * Returns true if the rotation has been changed.  In this case YOU
-     * MUST CALL sendNewConfiguration() TO UNFREEZE THE SCREEN.
+     * Returns true if the rotation has been changed.  In this case YOU MUST CALL
+     * {@link #sendNewConfiguration(int)} TO UNFREEZE THE SCREEN.
      */
-    boolean updateRotationUncheckedLocked(boolean inTransaction) {
+    boolean updateRotationUncheckedLocked(boolean inTransaction, int displayId) {
         if (mDeferredRotationPauseCount > 0) {
             // Rotation updates have been paused temporarily.  Defer the update until
             // updates have been resumed.
@@ -4915,7 +4915,7 @@
         }
 
         ScreenRotationAnimation screenRotationAnimation =
-                mAnimator.getScreenRotationAnimationLocked(DEFAULT_DISPLAY);
+                mAnimator.getScreenRotationAnimationLocked(displayId);
         if (screenRotationAnimation != null && screenRotationAnimation.isAnimating()) {
             // Rotation updates cannot be performed while the previous rotation change
             // animation is still in progress.  Skip this update.  We will try updating
@@ -4937,7 +4937,7 @@
             return false;
         }
 
-        final DisplayContent displayContent = getDefaultDisplayContentLocked();
+        final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
         final WindowList windows = displayContent.getWindowList();
 
         final int oldRotation = mRotation;
@@ -5017,7 +5017,7 @@
             startFreezingDisplayLocked(inTransaction, anim[0], anim[1]);
             // startFreezingDisplayLocked can reset the ScreenRotationAnimation.
             screenRotationAnimation =
-                mAnimator.getScreenRotationAnimationLocked(DEFAULT_DISPLAY);
+                mAnimator.getScreenRotationAnimationLocked(displayId);
         } else {
             // The screen rotation animation uses a screenshot to freeze the screen
             // while windows resize underneath.
@@ -5035,7 +5035,7 @@
         // the top of the method, the caller is obligated to call computeNewConfigurationLocked().
         // By updating the Display info here it will be available to
         // computeScreenConfigurationLocked later.
-        updateDisplayAndOrientationLocked(mRoot.getConfiguration().uiMode);
+        updateDisplayAndOrientationLocked(displayContent.getConfiguration().uiMode, displayId);
 
         final DisplayInfo displayInfo = displayContent.getDisplayInfo();
         if (!inTransaction) {
@@ -5568,13 +5568,14 @@
     }
 
     /**
-     * Instruct the Activity Manager to fetch new configurations, update global configuration
-     * and broadcast changes to config-changed listeners if appropriate.
+     * Instruct the Activity Manager to fetch and update the current display's configuration and
+     * broadcast them to config-changed listeners if appropriate.
      * NOTE: Can't be called with the window manager lock held since it call into activity manager.
      */
-    void sendNewConfiguration() {
+    void sendNewConfiguration(int displayId) {
         try {
-            final boolean configUpdated = mActivityManager.updateConfiguration(null);
+            final boolean configUpdated = mActivityManager.updateDisplayOverrideConfiguration(
+                    null /* values */, displayId);
             if (!configUpdated) {
                 // Something changed (E.g. device rotation), but no configuration update is needed.
                 // E.g. changing device rotation by 180 degrees. Go ahead and perform surface
@@ -5584,7 +5585,7 @@
                     if (mWaitingForConfig) {
                         mWaitingForConfig = false;
                         mLastFinishedFreezeSource = "config-unchanged";
-                        getDefaultDisplayContentLocked().setLayoutNeeded();
+                        mRoot.getDisplayContent(displayId).setLayoutNeeded();
                         mWindowPlacerLocked.performSurfacePlacement();
                     }
                 }
@@ -5593,18 +5594,18 @@
         }
     }
 
-    public Configuration computeNewConfiguration() {
+    public Configuration computeNewConfiguration(int displayId) {
         synchronized (mWindowMap) {
-            return computeNewConfigurationLocked();
+            return computeNewConfigurationLocked(displayId);
         }
     }
 
-    private Configuration computeNewConfigurationLocked() {
+    private Configuration computeNewConfigurationLocked(int displayId) {
         if (!mDisplayReady) {
             return null;
         }
-        Configuration config = new Configuration();
-        computeScreenConfigurationLocked(config);
+        final Configuration config = new Configuration();
+        computeScreenConfigurationLocked(config, displayId);
         return config;
     }
 
@@ -5713,9 +5714,8 @@
     }
 
     /** Do not call if mDisplayReady == false */
-    DisplayInfo updateDisplayAndOrientationLocked(int uiMode) {
-        // TODO(multidisplay): For now, apply Configuration to main screen only.
-        final DisplayContent displayContent = getDefaultDisplayContentLocked();
+    private DisplayInfo updateDisplayAndOrientationLocked(int uiMode, int displayId) {
+        final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
 
         // Use the effective "visual" dimensions based on current rotation
         final boolean rotated = (mRotation == Surface.ROTATION_90
@@ -5776,9 +5776,8 @@
     }
 
     /** Do not call if mDisplayReady == false */
-    void computeScreenConfigurationLocked(Configuration config) {
-        final DisplayInfo displayInfo = updateDisplayAndOrientationLocked(
-                config.uiMode);
+    private void computeScreenConfigurationLocked(Configuration config, int displayId) {
+        final DisplayInfo displayInfo = updateDisplayAndOrientationLocked(config.uiMode, displayId);
 
         final int dw = displayInfo.logicalWidth;
         final int dh = displayInfo.logicalHeight;
@@ -6417,11 +6416,9 @@
 
                     View view = null;
                     try {
-                        final Configuration overrideConfig =
-                                wtoken != null ? wtoken.getMergedOverrideConfiguration() : null;
                         view = mPolicy.addStartingWindow(wtoken.token, sd.pkg, sd.theme,
                             sd.compatInfo, sd.nonLocalizedLabel, sd.labelRes, sd.icon, sd.logo,
-                            sd.windowFlags, overrideConfig);
+                            sd.windowFlags, wtoken.getMergedOverrideConfiguration());
                     } catch (Exception e) {
                         Slog.w(TAG_WM, "Exception when adding starting window", e);
                     }
@@ -6668,8 +6665,9 @@
                 }
 
                 case SEND_NEW_CONFIGURATION: {
-                    removeMessages(SEND_NEW_CONFIGURATION);
-                    sendNewConfiguration();
+                    removeMessages(SEND_NEW_CONFIGURATION, msg.obj);
+                    final int displayId = (Integer) msg.obj;
+                    sendNewConfiguration(displayId);
                     break;
                 }
 
@@ -7317,16 +7315,19 @@
         configureDisplayPolicyLocked(displayContent);
         displayContent.setLayoutNeeded();
 
-        boolean configChanged = updateOrientationFromAppTokensLocked(false);
-        final Configuration globalConfig = mRoot.getConfiguration();
-        mTempConfiguration.setTo(globalConfig);
-        computeScreenConfigurationLocked(mTempConfiguration);
-        configChanged |= globalConfig.diff(mTempConfiguration) != 0;
+        final int displayId = displayContent.getDisplayId();
+        boolean configChanged = updateOrientationFromAppTokensLocked(false /* inTransaction */,
+                displayId);
+        final Configuration currentDisplayConfig = displayContent.getConfiguration();
+        mTempConfiguration.setTo(currentDisplayConfig);
+        computeScreenConfigurationLocked(mTempConfiguration, displayId);
+        configChanged |= currentDisplayConfig.diff(mTempConfiguration) != 0;
 
         if (configChanged) {
             mWaitingForConfig = true;
-            startFreezingDisplayLocked(false, 0, 0);
-            mH.sendEmptyMessage(H.SEND_NEW_CONFIGURATION);
+            startFreezingDisplayLocked(false /* inTransaction */, 0 /* exitAnim */,
+                    0 /* enterAnim */);
+            mH.obtainMessage(H.SEND_NEW_CONFIGURATION, displayId).sendToTarget();
         }
 
         mWindowPlacerLocked.performSurfacePlacement();
@@ -7744,7 +7745,7 @@
         // to avoid inconsistent states.  However, something interesting
         // could have actually changed during that time so re-evaluate it
         // now to catch that.
-        configChanged = updateOrientationFromAppTokensLocked(false);
+        configChanged = updateOrientationFromAppTokensLocked(false, displayId);
 
         // A little kludge: a lot could have happened while the
         // display was frozen, so now that we are coming back we
@@ -7758,11 +7759,11 @@
 
         if (updateRotation) {
             if (DEBUG_ORIENTATION) Slog.d(TAG_WM, "Performing post-rotate rotation");
-            configChanged |= updateRotationUncheckedLocked(false);
+            configChanged |= updateRotationUncheckedLocked(false, displayId);
         }
 
         if (configChanged) {
-            mH.sendEmptyMessage(H.SEND_NEW_CONFIGURATION);
+            mH.obtainMessage(H.SEND_NEW_CONFIGURATION, displayId).sendToTarget();
         }
     }
 
@@ -8887,8 +8888,9 @@
             if (DEBUG_ORIENTATION) {
                 Slog.i(TAG, "Performing post-rotate rotation after seamless rotation");
             }
-            if (updateRotationUncheckedLocked(false)) {
-                mH.sendEmptyMessage(H.SEND_NEW_CONFIGURATION);
+            final int displayId = w.getDisplayId();
+            if (updateRotationUncheckedLocked(false, displayId)) {
+                mH.obtainMessage(H.SEND_NEW_CONFIGURATION, displayId).sendToTarget();
             }
         }
     }
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index f80e085..a7b46111 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -38,7 +38,6 @@
 import android.util.DisplayMetrics;
 import android.util.Slog;
 import android.util.TimeUtils;
-import android.view.Display;
 import android.view.DisplayInfo;
 import android.view.Gravity;
 import android.view.IApplicationToken;
@@ -1670,7 +1669,7 @@
 
         //TODO (multidisplay): Accessibility supported only for the default display.
         if (mService.mAccessibilityController != null
-                && getDisplayContent().getDisplayId() == Display.DEFAULT_DISPLAY) {
+                && getDisplayContent().getDisplayId() == DEFAULT_DISPLAY) {
             mService.mAccessibilityController.onSomeWindowResizedOrMovedLocked();
         }
 
@@ -1831,6 +1830,8 @@
         // Visibility of the removed window. Will be used later to update orientation later on.
         boolean wasVisible = false;
 
+        final int displayId = getDisplayId();
+
         // First, see if we need to run an animation. If we do, we have to hold off on removing the
         // window until the animation is done. If the display is frozen, just remove immediately,
         // since the animation wouldn't be seen.
@@ -1891,8 +1892,7 @@
                     mAnimatingExit = true;
                 }
                 //TODO (multidisplay): Magnification is supported only for the default display.
-                if (mService.mAccessibilityController != null
-                        && getDisplayId() == Display.DEFAULT_DISPLAY) {
+                if (mService.mAccessibilityController != null && displayId == DEFAULT_DISPLAY) {
                     mService.mAccessibilityController.onWindowTransitionLocked(this, transit);
                 }
             }
@@ -1922,8 +1922,8 @@
         removeImmediately();
         // Removing a visible window will effect the computed orientation
         // So just update orientation if needed.
-        if (wasVisible && mService.updateOrientationFromAppTokensLocked(false)) {
-            mService.mH.sendEmptyMessage(SEND_NEW_CONFIGURATION);
+        if (wasVisible && mService.updateOrientationFromAppTokensLocked(false, displayId)) {
+            mService.mH.obtainMessage(SEND_NEW_CONFIGURATION, displayId).sendToTarget();
         }
         mService.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL, true /*updateInputWindows*/);
         Binder.restoreCallingIdentity(origId);
@@ -3037,8 +3037,7 @@
             }
 
             //TODO (multidisplay): Accessibility supported only for the default display.
-            if (mService.mAccessibilityController != null
-                    && getDisplayId() == Display.DEFAULT_DISPLAY) {
+            if (mService.mAccessibilityController != null && getDisplayId() == DEFAULT_DISPLAY) {
                 mService.mAccessibilityController.onSomeWindowResizedOrMovedLocked();
             }
 
diff --git a/services/core/java/com/android/server/wm/WindowSurfaceController.java b/services/core/java/com/android/server/wm/WindowSurfaceController.java
index 368484a..c48a585 100644
--- a/services/core/java/com/android/server/wm/WindowSurfaceController.java
+++ b/services/core/java/com/android/server/wm/WindowSurfaceController.java
@@ -58,6 +58,12 @@
     private float mSurfaceW = 0;
     private float mSurfaceH = 0;
 
+    // Initialize to the identity matrix.
+    private float mLastDsdx = 1;
+    private float mLastDtdx = 0;
+    private float mLastDsdy = 0;
+    private float mLastDtdy = 1;
+
     private float mSurfaceAlpha = 0;
 
     private int mSurfaceLayer = 0;
@@ -285,6 +291,17 @@
 
     void setMatrixInTransaction(float dsdx, float dtdx, float dsdy, float dtdy,
             boolean recoveringMemory) {
+        final boolean matrixChanged = mLastDsdx != dsdx || mLastDtdx != dtdx ||
+                                      mLastDsdy != dsdy || mLastDtdy != dtdy;
+        if (!matrixChanged) {
+            return;
+        }
+
+        mLastDsdx = dsdx;
+        mLastDtdx = dtdx;
+        mLastDsdy = dsdy;
+        mLastDtdy = dtdy;
+
         try {
             if (SHOW_TRANSACTIONS) logSurface(
                     "MATRIX [" + dsdx + "," + dtdx + "," + dsdy + "," + dtdy + "]", null);
@@ -300,7 +317,6 @@
                 mAnimator.reclaimSomeSurfaceMemory("matrix", true);
             }
         }
-        return;
     }
 
     boolean setSizeInTransaction(int width, int height, boolean recoveringMemory) {
@@ -337,6 +353,10 @@
                 mSurfaceControl.setAlpha(alpha);
                 mSurfaceLayer = layer;
                 mSurfaceControl.setLayer(layer);
+                mLastDsdx = dsdx;
+                mLastDtdx = dtdx;
+                mLastDsdy = dsdy;
+                mLastDtdy = dtdy;
                 mSurfaceControl.setMatrix(
                         dsdx, dtdx, dsdy, dtdy);
 
diff --git a/services/core/jni/Android.mk b/services/core/jni/Android.mk
index 121067a..2c46413 100644
--- a/services/core/jni/Android.mk
+++ b/services/core/jni/Android.mk
@@ -71,3 +71,5 @@
     android.hardware.vibrator@1.0 \
     android.hardware.light@2.0 \
     android.hardware.vr@1.0 \
+    android.hardware.audio.common@2.0 \
+    android.hardware.tv.input@1.0 \
diff --git a/services/core/jni/com_android_server_tv_TvInputHal.cpp b/services/core/jni/com_android_server_tv_TvInputHal.cpp
index e34a8e8..179fba0 100644
--- a/services/core/jni/com_android_server_tv_TvInputHal.cpp
+++ b/services/core/jni/com_android_server_tv_TvInputHal.cpp
@@ -24,6 +24,9 @@
 #include "JNIHelp.h"
 #include "jni.h"
 
+#include <android/hardware/tv/input/1.0/ITvInputCallback.h>
+#include <android/hardware/tv/input/1.0/ITvInput.h>
+#include <android/hardware/tv/input/1.0/types.h>
 #include <gui/Surface.h>
 #include <utils/Errors.h>
 #include <utils/KeyedVector.h>
@@ -32,6 +35,20 @@
 #include <utils/NativeHandle.h>
 #include <hardware/tv_input.h>
 
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::tv::input::V1_0::ITvInput;
+using ::android::hardware::tv::input::V1_0::ITvInputCallback;
+using ::android::hardware::tv::input::V1_0::Result;
+using ::android::hardware::tv::input::V1_0::TvInputDeviceInfo;
+using ::android::hardware::tv::input::V1_0::TvInputEvent;
+using ::android::hardware::tv::input::V1_0::TvInputEventType;
+using ::android::hardware::tv::input::V1_0::TvInputType;
+using ::android::hardware::tv::input::V1_0::TvStreamConfig;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+
 namespace android {
 
 static struct {
@@ -239,9 +256,9 @@
 
     int addOrUpdateStream(int deviceId, int streamId, const sp<Surface>& surface);
     int removeStream(int deviceId, int streamId);
-    const tv_stream_config_t* getStreamConfigs(int deviceId, int* numConfigs);
+    const hidl_vec<TvStreamConfig> getStreamConfigs(int deviceId);
 
-    void onDeviceAvailable(const tv_input_device_info_t& info);
+    void onDeviceAvailable(const TvInputDeviceInfo& info);
     void onDeviceUnavailable(int deviceId);
     void onStreamConfigurationsChanged(int deviceId);
     void onCaptured(int deviceId, int streamId, uint32_t seq, bool succeeded);
@@ -263,73 +280,60 @@
 
     class NotifyHandler : public MessageHandler {
     public:
-        NotifyHandler(JTvInputHal* hal, const tv_input_event_t* event);
-        ~NotifyHandler();
+        NotifyHandler(JTvInputHal* hal, const TvInputEvent& event);
 
         virtual void handleMessage(const Message& message);
 
     private:
-        tv_input_event_t mEvent;
+        TvInputEvent mEvent;
         JTvInputHal* mHal;
     };
 
-    JTvInputHal(JNIEnv* env, jobject thiz, tv_input_device_t* dev, const sp<Looper>& looper);
+    class TvInputCallback : public ITvInputCallback {
+    public:
+        TvInputCallback(JTvInputHal* hal);
+        Return<void> notify(const TvInputEvent& event) override;
+    private:
+        JTvInputHal* mHal;
+    };
 
-    static void notify(
-            tv_input_device_t* dev, tv_input_event_t* event, void* data);
-
-    static void cloneTvInputEvent(
-            tv_input_event_t* dstEvent, const tv_input_event_t* srcEvent);
+    JTvInputHal(JNIEnv* env, jobject thiz, sp<ITvInput> tvInput, const sp<Looper>& looper);
 
     Mutex mLock;
     jweak mThiz;
-    tv_input_device_t* mDevice;
-    tv_input_callback_ops_t mCallback;
     sp<Looper> mLooper;
 
     KeyedVector<int, KeyedVector<int, Connection> > mConnections;
+
+    sp<ITvInput> mTvInput;
+    sp<ITvInputCallback> mTvInputCallback;
 };
 
-JTvInputHal::JTvInputHal(JNIEnv* env, jobject thiz, tv_input_device_t* device,
+JTvInputHal::JTvInputHal(JNIEnv* env, jobject thiz, sp<ITvInput> tvInput,
         const sp<Looper>& looper) {
     mThiz = env->NewWeakGlobalRef(thiz);
-    mDevice = device;
-    mCallback.notify = &JTvInputHal::notify;
+    mTvInput = tvInput;
     mLooper = looper;
-
-    mDevice->initialize(mDevice, &mCallback, this);
+    mTvInputCallback = new TvInputCallback(this);
+    mTvInput->setCallback(mTvInputCallback);
 }
 
 JTvInputHal::~JTvInputHal() {
-    mDevice->common.close((hw_device_t*)mDevice);
-
+    mTvInput->setCallback(nullptr);
     JNIEnv* env = AndroidRuntime::getJNIEnv();
     env->DeleteWeakGlobalRef(mThiz);
     mThiz = NULL;
 }
 
 JTvInputHal* JTvInputHal::createInstance(JNIEnv* env, jobject thiz, const sp<Looper>& looper) {
-    tv_input_module_t* module = NULL;
-    status_t err = hw_get_module(TV_INPUT_HARDWARE_MODULE_ID,
-            (hw_module_t const**)&module);
-    if (err) {
-        ALOGE("Couldn't load %s module (%s)",
-                TV_INPUT_HARDWARE_MODULE_ID, strerror(-err));
-        return 0;
+    // TODO(b/31632518)
+    sp<ITvInput> tvInput = ITvInput::getService("tv.input");
+    if (tvInput == nullptr) {
+        ALOGE("Couldn't get tv.input service.");
+        return nullptr;
     }
 
-    tv_input_device_t* device = NULL;
-    err = module->common.methods->open(
-            (hw_module_t*)module,
-            TV_INPUT_DEFAULT_DEVICE,
-            (hw_device_t**)&device);
-    if (err) {
-        ALOGE("Couldn't open %s device (%s)",
-                TV_INPUT_DEFAULT_DEVICE, strerror(-err));
-        return 0;
-    }
-
-    return new JTvInputHal(env, thiz, device, looper);
+    return new JTvInputHal(env, thiz, tvInput, looper);
 }
 
 int JTvInputHal::addOrUpdateStream(int deviceId, int streamId, const sp<Surface>& surface) {
@@ -353,16 +357,22 @@
     }
     if (connection.mSourceHandle == NULL && connection.mThread == NULL) {
         // Need to configure stream
-        int numConfigs = 0;
-        const tv_stream_config_t* configs = NULL;
-        if (mDevice->get_stream_configurations(
-                mDevice, deviceId, &numConfigs, &configs) != 0) {
-            ALOGE("Couldn't get stream configs");
+        Result result = Result::UNKNOWN;
+        hidl_vec<TvStreamConfig> list;
+        mTvInput->getStreamConfigurations(deviceId,
+                [&result, &list](Result res, hidl_vec<TvStreamConfig> configs) {
+                    result = res;
+                    if (res == Result::OK) {
+                        list = configs;
+                    }
+                });
+        if (result != Result::OK) {
+            ALOGE("Couldn't get stream configs for device id:%d result:%d", deviceId, result);
             return UNKNOWN_ERROR;
         }
         int configIndex = -1;
-        for (int i = 0; i < numConfigs; ++i) {
-            if (configs[i].stream_id == streamId) {
+        for (size_t i = 0; i < list.size(); ++i) {
+            if (list[i].streamId == streamId) {
                 configIndex = i;
                 break;
             }
@@ -371,34 +381,27 @@
             ALOGE("Cannot find a config with given stream ID: %d", streamId);
             return BAD_VALUE;
         }
-        connection.mStreamType = configs[configIndex].type;
+        connection.mStreamType = TV_STREAM_TYPE_INDEPENDENT_VIDEO_SOURCE;
 
-        tv_stream_t stream;
-        stream.stream_id = configs[configIndex].stream_id;
-        if (connection.mStreamType == TV_STREAM_TYPE_BUFFER_PRODUCER) {
-            stream.buffer_producer.width = configs[configIndex].max_video_width;
-            stream.buffer_producer.height = configs[configIndex].max_video_height;
-        }
-        if (mDevice->open_stream(mDevice, deviceId, &stream) != 0) {
-            ALOGE("Couldn't add stream");
+        result = Result::UNKNOWN;
+        const native_handle_t* sidebandStream;
+        mTvInput->openStream(deviceId, streamId,
+                [&result, &sidebandStream](Result res, const native_handle_t* handle) {
+                    result = res;
+                    if (res == Result::OK) {
+                        sidebandStream = handle;
+                    }
+                });
+        if (result != Result::OK) {
+            ALOGE("Couldn't open stream. device id:%d stream id:%d result:%d", deviceId, streamId,
+                    result);
             return UNKNOWN_ERROR;
         }
-        if (connection.mStreamType == TV_STREAM_TYPE_INDEPENDENT_VIDEO_SOURCE) {
-            connection.mSourceHandle = NativeHandle::create(
-                    stream.sideband_stream_source_handle, false);
-        } else if (connection.mStreamType == TV_STREAM_TYPE_BUFFER_PRODUCER) {
-            if (connection.mThread != NULL) {
-                connection.mThread->shutdown();
-            }
-            connection.mThread = new BufferProducerThread(mDevice, deviceId, &stream);
-            connection.mThread->run("BufferProducerThread");
-        }
+        connection.mSourceHandle = NativeHandle::create((native_handle_t*)sidebandStream, false);
     }
     connection.mSurface = surface;
-    if (connection.mStreamType == TV_STREAM_TYPE_INDEPENDENT_VIDEO_SOURCE) {
+    if (connection.mSurface != nullptr) {
         connection.mSurface->setSidebandStream(connection.mSourceHandle);
-    } else if (connection.mStreamType == TV_STREAM_TYPE_BUFFER_PRODUCER) {
-        connection.mThread->setSurface(surface);
     }
     return NO_ERROR;
 }
@@ -421,8 +424,8 @@
         connection.mThread->shutdown();
         connection.mThread.clear();
     }
-    if (mDevice->close_stream(mDevice, deviceId, streamId) != 0) {
-        ALOGE("Couldn't remove stream");
+    if (mTvInput->closeStream(deviceId, streamId) != Result::OK) {
+        ALOGE("Couldn't close stream. device id:%d stream id:%d", deviceId, streamId);
         return BAD_VALUE;
     }
     if (connection.mSourceHandle != NULL) {
@@ -431,41 +434,26 @@
     return NO_ERROR;
 }
 
-const tv_stream_config_t* JTvInputHal::getStreamConfigs(int deviceId, int* numConfigs) {
-    const tv_stream_config_t* configs = NULL;
-    if (mDevice->get_stream_configurations(
-            mDevice, deviceId, numConfigs, &configs) != 0) {
-        ALOGE("Couldn't get stream configs");
-        return NULL;
+const hidl_vec<TvStreamConfig> JTvInputHal::getStreamConfigs(int deviceId) {
+    Result result = Result::UNKNOWN;
+    hidl_vec<TvStreamConfig> list;
+    mTvInput->getStreamConfigurations(deviceId,
+            [&result, &list](Result res, hidl_vec<TvStreamConfig> configs) {
+                result = res;
+                if (res == Result::OK) {
+                    list = configs;
+                }
+            });
+    if (result != Result::OK) {
+        ALOGE("Couldn't get stream configs for device id:%d result:%d", deviceId, result);
     }
-    return configs;
+    return list;
 }
 
-// static
-void JTvInputHal::notify(
-        tv_input_device_t* dev, tv_input_event_t* event, void* data) {
-    JTvInputHal* thiz = (JTvInputHal*)data;
-    thiz->mLooper->sendMessage(new NotifyHandler(thiz, event), event->type);
-}
-
-// static
-void JTvInputHal::cloneTvInputEvent(
-        tv_input_event_t* dstEvent, const tv_input_event_t* srcEvent) {
-    memcpy(dstEvent, srcEvent, sizeof(tv_input_event_t));
-    if ((srcEvent->type == TV_INPUT_EVENT_DEVICE_AVAILABLE ||
-            srcEvent->type == TV_INPUT_EVENT_DEVICE_UNAVAILABLE ||
-            srcEvent->type == TV_INPUT_EVENT_STREAM_CONFIGURATIONS_CHANGED) &&
-            srcEvent->device_info.audio_address != NULL){
-        char* audio_address = new char[strlen(srcEvent->device_info.audio_address) + 1];
-        strcpy(audio_address, srcEvent->device_info.audio_address);
-        dstEvent->device_info.audio_address = audio_address;
-    }
-}
-
-void JTvInputHal::onDeviceAvailable(const tv_input_device_info_t& info) {
+void JTvInputHal::onDeviceAvailable(const TvInputDeviceInfo& info) {
     {
         Mutex::Autolock autoLock(&mLock);
-        mConnections.add(info.device_id, KeyedVector<int, Connection>());
+        mConnections.add(info.deviceId, KeyedVector<int, Connection>());
     }
     JNIEnv* env = AndroidRuntime::getJNIEnv();
 
@@ -473,17 +461,20 @@
             gTvInputHardwareInfoBuilderClassInfo.clazz,
             gTvInputHardwareInfoBuilderClassInfo.constructor);
     env->CallObjectMethod(
-            builder, gTvInputHardwareInfoBuilderClassInfo.deviceId, info.device_id);
+            builder, gTvInputHardwareInfoBuilderClassInfo.deviceId, info.deviceId);
     env->CallObjectMethod(
             builder, gTvInputHardwareInfoBuilderClassInfo.type, info.type);
-    if (info.type == TV_INPUT_TYPE_HDMI) {
+    if (info.type == TvInputType::HDMI) {
         env->CallObjectMethod(
-                builder, gTvInputHardwareInfoBuilderClassInfo.hdmiPortId, info.hdmi.port_id);
+                builder, gTvInputHardwareInfoBuilderClassInfo.hdmiPortId, info.portId);
     }
     env->CallObjectMethod(
-            builder, gTvInputHardwareInfoBuilderClassInfo.audioType, info.audio_type);
-    if (info.audio_type != AUDIO_DEVICE_NONE) {
-        jstring audioAddress = env->NewStringUTF(info.audio_address);
+            builder, gTvInputHardwareInfoBuilderClassInfo.audioType, info.audioType);
+    if (info.audioType != AudioDevice::NONE) {
+        uint8_t buffer[info.audioAddress.size() + 1];
+        memcpy(buffer, info.audioAddress.data(), info.audioAddress.size());
+        buffer[info.audioAddress.size()] = '\0';
+        jstring audioAddress = env->NewStringUTF(reinterpret_cast<const char *>(buffer));
         env->CallObjectMethod(
                 builder, gTvInputHardwareInfoBuilderClassInfo.audioAddress, audioAddress);
         env->DeleteLocalRef(audioAddress);
@@ -556,48 +547,37 @@
     }
 }
 
-JTvInputHal::NotifyHandler::NotifyHandler(JTvInputHal* hal, const tv_input_event_t* event) {
+JTvInputHal::NotifyHandler::NotifyHandler(JTvInputHal* hal, const TvInputEvent& event) {
     mHal = hal;
-    cloneTvInputEvent(&mEvent, event);
-}
-
-JTvInputHal::NotifyHandler::~NotifyHandler() {
-    if ((mEvent.type == TV_INPUT_EVENT_DEVICE_AVAILABLE ||
-            mEvent.type == TV_INPUT_EVENT_DEVICE_UNAVAILABLE ||
-            mEvent.type == TV_INPUT_EVENT_STREAM_CONFIGURATIONS_CHANGED) &&
-            mEvent.device_info.audio_address != NULL) {
-        delete mEvent.device_info.audio_address;
-    }
+    mEvent = event;
 }
 
 void JTvInputHal::NotifyHandler::handleMessage(const Message& message) {
     switch (mEvent.type) {
-        case TV_INPUT_EVENT_DEVICE_AVAILABLE: {
-            mHal->onDeviceAvailable(mEvent.device_info);
+        case TvInputEventType::DEVICE_AVAILABLE: {
+            mHal->onDeviceAvailable(mEvent.deviceInfo);
         } break;
-        case TV_INPUT_EVENT_DEVICE_UNAVAILABLE: {
-            mHal->onDeviceUnavailable(mEvent.device_info.device_id);
+        case TvInputEventType::DEVICE_UNAVAILABLE: {
+            mHal->onDeviceUnavailable(mEvent.deviceInfo.deviceId);
         } break;
-        case TV_INPUT_EVENT_STREAM_CONFIGURATIONS_CHANGED: {
-            mHal->onStreamConfigurationsChanged(mEvent.device_info.device_id);
-        } break;
-        case TV_INPUT_EVENT_CAPTURE_SUCCEEDED: {
-            mHal->onCaptured(mEvent.capture_result.device_id,
-                             mEvent.capture_result.stream_id,
-                             mEvent.capture_result.seq,
-                             true /* succeeded */);
-        } break;
-        case TV_INPUT_EVENT_CAPTURE_FAILED: {
-            mHal->onCaptured(mEvent.capture_result.device_id,
-                             mEvent.capture_result.stream_id,
-                             mEvent.capture_result.seq,
-                             false /* succeeded */);
+        case TvInputEventType::STREAM_CONFIGURATIONS_CHANGED: {
+            mHal->onStreamConfigurationsChanged(mEvent.deviceInfo.deviceId);
         } break;
         default:
             ALOGE("Unrecognizable event");
     }
 }
 
+JTvInputHal::TvInputCallback::TvInputCallback(JTvInputHal* hal) {
+    mHal = hal;
+}
+
+Return<void> JTvInputHal::TvInputCallback::notify(const TvInputEvent& event) {
+    // TODO(b/32200867): Ensure the event type values are in sync with the framework code.
+    mHal->mLooper->sendMessage(new NotifyHandler(mHal, event), static_cast<int>(event.type));
+    return Void();
+}
+
 ////////////////////////////////////////////////////////////////////////////////
 
 static jlong nativeOpen(JNIEnv* env, jobject thiz, jobject messageQueueObj) {
@@ -628,22 +608,22 @@
 static jobjectArray nativeGetStreamConfigs(JNIEnv* env, jclass clazz,
         jlong ptr, jint deviceId, jint generation) {
     JTvInputHal* tvInputHal = (JTvInputHal*)ptr;
-    int numConfigs = 0;
-    const tv_stream_config_t* configs = tvInputHal->getStreamConfigs(deviceId, &numConfigs);
+    const hidl_vec<TvStreamConfig> configs = tvInputHal->getStreamConfigs(deviceId);
 
-    jobjectArray result = env->NewObjectArray(numConfigs, gTvStreamConfigClassInfo.clazz, NULL);
-    for (int i = 0; i < numConfigs; ++i) {
+    jobjectArray result = env->NewObjectArray(configs.size(), gTvStreamConfigClassInfo.clazz, NULL);
+    for (size_t i = 0; i < configs.size(); ++i) {
         jobject builder = env->NewObject(
                 gTvStreamConfigBuilderClassInfo.clazz,
                 gTvStreamConfigBuilderClassInfo.constructor);
         env->CallObjectMethod(
-                builder, gTvStreamConfigBuilderClassInfo.streamId, configs[i].stream_id);
+                builder, gTvStreamConfigBuilderClassInfo.streamId, configs[i].streamId);
         env->CallObjectMethod(
-                builder, gTvStreamConfigBuilderClassInfo.type, configs[i].type);
+                builder, gTvStreamConfigBuilderClassInfo.type,
+                        TV_STREAM_TYPE_INDEPENDENT_VIDEO_SOURCE);
         env->CallObjectMethod(
-                builder, gTvStreamConfigBuilderClassInfo.maxWidth, configs[i].max_video_width);
+                builder, gTvStreamConfigBuilderClassInfo.maxWidth, configs[i].maxVideoWidth);
         env->CallObjectMethod(
-                builder, gTvStreamConfigBuilderClassInfo.maxHeight, configs[i].max_video_height);
+                builder, gTvStreamConfigBuilderClassInfo.maxHeight, configs[i].maxVideoHeight);
         env->CallObjectMethod(
                 builder, gTvStreamConfigBuilderClassInfo.generation, generation);
 
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index 5106c32..eb85e89 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -51,6 +51,7 @@
 import android.app.admin.DevicePolicyManager;
 import android.app.admin.DevicePolicyManagerInternal;
 import android.app.admin.IDevicePolicyManager;
+import android.app.admin.PasswordMetrics;
 import android.app.admin.SecurityLog;
 import android.app.admin.SecurityLog.SecurityEvent;
 import android.app.admin.SystemUpdatePolicy;
@@ -425,14 +426,7 @@
     }
 
     public static class DevicePolicyData {
-        int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
-        int mActivePasswordLength = 0;
-        int mActivePasswordUpperCase = 0;
-        int mActivePasswordLowerCase = 0;
-        int mActivePasswordLetters = 0;
-        int mActivePasswordNumeric = 0;
-        int mActivePasswordSymbols = 0;
-        int mActivePasswordNonLetter = 0;
+        @NonNull PasswordMetrics mActivePasswordMetrics = new PasswordMetrics();
         int mFailedPasswordAttempts = 0;
 
         int mUserHandle;
@@ -598,31 +592,23 @@
 
         final DeviceAdminInfo info;
 
-        int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
-
-        static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
-        int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
 
         static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
         int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
 
-        static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
-        int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
-
-        static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
-        int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
-
+        static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
         static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
-        int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
-
+        static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
+        static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
         static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
-        int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
-
         static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
-        int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
-
         static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
-        int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
+        @NonNull
+        PasswordMetrics minimumPasswordMetrics = new PasswordMetrics(
+                DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, DEF_MINIMUM_PASSWORD_LENGTH,
+                DEF_MINIMUM_PASSWORD_LETTERS, DEF_MINIMUM_PASSWORD_UPPER_CASE,
+                DEF_MINIMUM_PASSWORD_LOWER_CASE, DEF_MINIMUM_PASSWORD_NUMERIC,
+                DEF_MINIMUM_PASSWORD_SYMBOLS, DEF_MINIMUM_PASSWORD_NON_LETTER);
 
         static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
         long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
@@ -728,13 +714,15 @@
             out.startTag(null, TAG_POLICIES);
             info.writePoliciesToXml(out);
             out.endTag(null, TAG_POLICIES);
-            if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
+            if (minimumPasswordMetrics.quality
+                    != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
                 out.startTag(null, TAG_PASSWORD_QUALITY);
-                out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
+                out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.quality));
                 out.endTag(null, TAG_PASSWORD_QUALITY);
-                if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
+                if (minimumPasswordMetrics.length != DEF_MINIMUM_PASSWORD_LENGTH) {
                     out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
-                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
+                    out.attribute(
+                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.length));
                     out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
                 }
                 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
@@ -742,34 +730,40 @@
                     out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
                     out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
                 }
-                if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
+                if (minimumPasswordMetrics.upperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
                     out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
-                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
+                    out.attribute(
+                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.upperCase));
                     out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
                 }
-                if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
+                if (minimumPasswordMetrics.lowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
                     out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
-                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
+                    out.attribute(
+                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.lowerCase));
                     out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
                 }
-                if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
+                if (minimumPasswordMetrics.letters != DEF_MINIMUM_PASSWORD_LETTERS) {
                     out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
-                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
+                    out.attribute(
+                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.letters));
                     out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
                 }
-                if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
+                if (minimumPasswordMetrics.numeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
                     out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
-                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
+                    out.attribute(
+                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.numeric));
                     out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
                 }
-                if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
+                if (minimumPasswordMetrics.symbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
                     out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
-                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
+                    out.attribute(
+                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.symbols));
                     out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
                 }
-                if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
+                if (minimumPasswordMetrics.nonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
                     out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
-                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
+                    out.attribute(
+                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.nonLetter));
                     out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
                 }
             }
@@ -968,31 +962,31 @@
                 if (TAG_POLICIES.equals(tag)) {
                     info.readPoliciesFromXml(parser);
                 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
-                    passwordQuality = Integer.parseInt(
+                    minimumPasswordMetrics.quality = Integer.parseInt(
                             parser.getAttributeValue(null, ATTR_VALUE));
                 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
-                    minimumPasswordLength = Integer.parseInt(
+                    minimumPasswordMetrics.length = Integer.parseInt(
                             parser.getAttributeValue(null, ATTR_VALUE));
                 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
                     passwordHistoryLength = Integer.parseInt(
                             parser.getAttributeValue(null, ATTR_VALUE));
                 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
-                    minimumPasswordUpperCase = Integer.parseInt(
+                    minimumPasswordMetrics.upperCase = Integer.parseInt(
                             parser.getAttributeValue(null, ATTR_VALUE));
                 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
-                    minimumPasswordLowerCase = Integer.parseInt(
+                    minimumPasswordMetrics.lowerCase = Integer.parseInt(
                             parser.getAttributeValue(null, ATTR_VALUE));
                 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
-                    minimumPasswordLetters = Integer.parseInt(
+                    minimumPasswordMetrics.letters = Integer.parseInt(
                             parser.getAttributeValue(null, ATTR_VALUE));
                 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
-                    minimumPasswordNumeric = Integer.parseInt(
+                    minimumPasswordMetrics.numeric = Integer.parseInt(
                             parser.getAttributeValue(null, ATTR_VALUE));
                 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
-                    minimumPasswordSymbols = Integer.parseInt(
+                    minimumPasswordMetrics.symbols = Integer.parseInt(
                             parser.getAttributeValue(null, ATTR_VALUE));
                 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
-                    minimumPasswordNonLetter = Integer.parseInt(
+                    minimumPasswordMetrics.nonLetter = Integer.parseInt(
                             parser.getAttributeValue(null, ATTR_VALUE));
                 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
                     maximumTimeToUnlock = Long.parseLong(
@@ -1232,23 +1226,23 @@
                 }
             }
             pw.print(prefix); pw.print("passwordQuality=0x");
-                    pw.println(Integer.toHexString(passwordQuality));
+                    pw.println(Integer.toHexString(minimumPasswordMetrics.quality));
             pw.print(prefix); pw.print("minimumPasswordLength=");
-                    pw.println(minimumPasswordLength);
+                    pw.println(minimumPasswordMetrics.length);
             pw.print(prefix); pw.print("passwordHistoryLength=");
                     pw.println(passwordHistoryLength);
             pw.print(prefix); pw.print("minimumPasswordUpperCase=");
-                    pw.println(minimumPasswordUpperCase);
+                    pw.println(minimumPasswordMetrics.upperCase);
             pw.print(prefix); pw.print("minimumPasswordLowerCase=");
-                    pw.println(minimumPasswordLowerCase);
+                    pw.println(minimumPasswordMetrics.lowerCase);
             pw.print(prefix); pw.print("minimumPasswordLetters=");
-                    pw.println(minimumPasswordLetters);
+                    pw.println(minimumPasswordMetrics.letters);
             pw.print(prefix); pw.print("minimumPasswordNumeric=");
-                    pw.println(minimumPasswordNumeric);
+                    pw.println(minimumPasswordMetrics.numeric);
             pw.print(prefix); pw.print("minimumPasswordSymbols=");
-                    pw.println(minimumPasswordSymbols);
+                    pw.println(minimumPasswordMetrics.symbols);
             pw.print(prefix); pw.print("minimumPasswordNonLetter=");
-                    pw.println(minimumPasswordNonLetter);
+                    pw.println(minimumPasswordMetrics.nonLetter);
             pw.print(prefix); pw.print("maximumTimeToUnlock=");
                     pw.println(maximumTimeToUnlock);
             pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
@@ -2281,20 +2275,17 @@
                 out.endTag(null, "failed-password-attempts");
             }
 
-            if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
-                    || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
-                    || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
-                    || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
+            final PasswordMetrics metrics = policy.mActivePasswordMetrics;
+            if (!metrics.isDefault()) {
                 out.startTag(null, "active-password");
-                out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
-                out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
-                out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
-                out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
-                out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
-                out.attribute(null, "numeric", Integer
-                        .toString(policy.mActivePasswordNumeric));
-                out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
-                out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
+                out.attribute(null, "quality", Integer.toString(metrics.quality));
+                out.attribute(null, "length", Integer.toString(metrics.length));
+                out.attribute(null, "uppercase", Integer.toString(metrics.upperCase));
+                out.attribute(null, "lowercase", Integer.toString(metrics.lowerCase));
+                out.attribute(null, "letters", Integer.toString(metrics.letters));
+                out.attribute(null, "numeric", Integer.toString(metrics.numeric));
+                out.attribute(null, "symbols", Integer.toString(metrics.symbols));
+                out.attribute(null, "nonletter", Integer.toString(metrics.nonLetter));
                 out.endTag(null, "active-password");
             }
 
@@ -2464,22 +2455,15 @@
                     policy.mPasswordOwner = Integer.parseInt(
                             parser.getAttributeValue(null, "value"));
                 } else if ("active-password".equals(tag)) {
-                    policy.mActivePasswordQuality = Integer.parseInt(
-                            parser.getAttributeValue(null, "quality"));
-                    policy.mActivePasswordLength = Integer.parseInt(
-                            parser.getAttributeValue(null, "length"));
-                    policy.mActivePasswordUpperCase = Integer.parseInt(
-                            parser.getAttributeValue(null, "uppercase"));
-                    policy.mActivePasswordLowerCase = Integer.parseInt(
-                            parser.getAttributeValue(null, "lowercase"));
-                    policy.mActivePasswordLetters = Integer.parseInt(
-                            parser.getAttributeValue(null, "letters"));
-                    policy.mActivePasswordNumeric = Integer.parseInt(
-                            parser.getAttributeValue(null, "numeric"));
-                    policy.mActivePasswordSymbols = Integer.parseInt(
-                            parser.getAttributeValue(null, "symbols"));
-                    policy.mActivePasswordNonLetter = Integer.parseInt(
-                            parser.getAttributeValue(null, "nonletter"));
+                    final PasswordMetrics m = policy.mActivePasswordMetrics;
+                    m.quality = Integer.parseInt(parser.getAttributeValue(null, "quality"));
+                    m.length = Integer.parseInt(parser.getAttributeValue(null, "length"));
+                    m.upperCase = Integer.parseInt(parser.getAttributeValue(null, "uppercase"));
+                    m.lowerCase = Integer.parseInt(parser.getAttributeValue(null, "lowercase"));
+                    m.letters = Integer.parseInt(parser.getAttributeValue(null, "letters"));
+                    m.numeric = Integer.parseInt(parser.getAttributeValue(null, "numeric"));
+                    m.symbols = Integer.parseInt(parser.getAttributeValue(null, "symbols"));
+                    m.nonLetter = Integer.parseInt(parser.getAttributeValue(null, "nonletter"));
                 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
                     policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
                 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
@@ -2525,19 +2509,12 @@
         final long identity = mInjector.binderClearCallingIdentity();
         try {
             int actualPasswordQuality = mLockPatternUtils.getActivePasswordQuality(userHandle);
-            if (actualPasswordQuality < policy.mActivePasswordQuality) {
+            if (actualPasswordQuality < policy.mActivePasswordMetrics.quality) {
                 Slog.w(LOG_TAG, "Active password quality 0x"
-                        + Integer.toHexString(policy.mActivePasswordQuality)
+                        + Integer.toHexString(policy.mActivePasswordMetrics.quality)
                         + " does not match actual quality 0x"
                         + Integer.toHexString(actualPasswordQuality));
-                policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
-                policy.mActivePasswordLength = 0;
-                policy.mActivePasswordUpperCase = 0;
-                policy.mActivePasswordLowerCase = 0;
-                policy.mActivePasswordLetters = 0;
-                policy.mActivePasswordNumeric = 0;
-                policy.mActivePasswordSymbols = 0;
-                policy.mActivePasswordNonLetter = 0;
+                policy.mActivePasswordMetrics = new PasswordMetrics();
             }
         } finally {
             mInjector.binderRestoreCallingIdentity(identity);
@@ -3127,8 +3104,8 @@
         synchronized (this) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
-            if (ap.passwordQuality != quality) {
-                ap.passwordQuality = quality;
+            if (ap.minimumPasswordMetrics.quality != quality) {
+                ap.minimumPasswordMetrics.quality = quality;
                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
             }
         }
@@ -3145,7 +3122,7 @@
 
             if (who != null) {
                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
-                return admin != null ? admin.passwordQuality : mode;
+                return admin != null ? admin.minimumPasswordMetrics.quality : mode;
             }
 
             // Return the strictest policy across all participating admins.
@@ -3154,8 +3131,8 @@
             final int N = admins.size();
             for (int i = 0; i < N; i++) {
                 ActiveAdmin admin = admins.get(i);
-                if (mode < admin.passwordQuality) {
-                    mode = admin.passwordQuality;
+                if (mode < admin.minimumPasswordMetrics.quality) {
+                    mode = admin.minimumPasswordMetrics.quality;
                 }
             }
             return mode;
@@ -3214,8 +3191,8 @@
         synchronized (this) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
-            if (ap.minimumPasswordLength != length) {
-                ap.minimumPasswordLength = length;
+            if (ap.minimumPasswordMetrics.length != length) {
+                ap.minimumPasswordMetrics.length = length;
                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
             }
         }
@@ -3232,7 +3209,7 @@
 
             if (who != null) {
                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
-                return admin != null ? admin.minimumPasswordLength : length;
+                return admin != null ? admin.minimumPasswordMetrics.length : length;
             }
 
             // Return the strictest policy across all participating admins.
@@ -3241,8 +3218,8 @@
             final int N = admins.size();
             for (int i = 0; i < N; i++) {
                 ActiveAdmin admin = admins.get(i);
-                if (length < admin.minimumPasswordLength) {
-                    length = admin.minimumPasswordLength;
+                if (length < admin.minimumPasswordMetrics.length) {
+                    length = admin.minimumPasswordMetrics.length;
                 }
             }
             return length;
@@ -3469,8 +3446,8 @@
         synchronized (this) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
-            if (ap.minimumPasswordUpperCase != length) {
-                ap.minimumPasswordUpperCase = length;
+            if (ap.minimumPasswordMetrics.upperCase != length) {
+                ap.minimumPasswordMetrics.upperCase = length;
                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
             }
         }
@@ -3487,7 +3464,7 @@
 
             if (who != null) {
                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
-                return admin != null ? admin.minimumPasswordUpperCase : length;
+                return admin != null ? admin.minimumPasswordMetrics.upperCase : length;
             }
 
             // Return the strictest policy across all participating admins.
@@ -3496,8 +3473,8 @@
             final int N = admins.size();
             for (int i = 0; i < N; i++) {
                 ActiveAdmin admin = admins.get(i);
-                if (length < admin.minimumPasswordUpperCase) {
-                    length = admin.minimumPasswordUpperCase;
+                if (length < admin.minimumPasswordMetrics.upperCase) {
+                    length = admin.minimumPasswordMetrics.upperCase;
                 }
             }
             return length;
@@ -3510,8 +3487,8 @@
         synchronized (this) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
-            if (ap.minimumPasswordLowerCase != length) {
-                ap.minimumPasswordLowerCase = length;
+            if (ap.minimumPasswordMetrics.lowerCase != length) {
+                ap.minimumPasswordMetrics.lowerCase = length;
                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
             }
         }
@@ -3528,7 +3505,7 @@
 
             if (who != null) {
                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
-                return admin != null ? admin.minimumPasswordLowerCase : length;
+                return admin != null ? admin.minimumPasswordMetrics.lowerCase : length;
             }
 
             // Return the strictest policy across all participating admins.
@@ -3537,8 +3514,8 @@
             final int N = admins.size();
             for (int i = 0; i < N; i++) {
                 ActiveAdmin admin = admins.get(i);
-                if (length < admin.minimumPasswordLowerCase) {
-                    length = admin.minimumPasswordLowerCase;
+                if (length < admin.minimumPasswordMetrics.lowerCase) {
+                    length = admin.minimumPasswordMetrics.lowerCase;
                 }
             }
             return length;
@@ -3554,8 +3531,8 @@
         synchronized (this) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
-            if (ap.minimumPasswordLetters != length) {
-                ap.minimumPasswordLetters = length;
+            if (ap.minimumPasswordMetrics.letters != length) {
+                ap.minimumPasswordMetrics.letters = length;
                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
             }
         }
@@ -3572,7 +3549,7 @@
 
             if (who != null) {
                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
-                return admin != null ? admin.minimumPasswordLetters : length;
+                return admin != null ? admin.minimumPasswordMetrics.letters : length;
             }
 
             // Return the strictest policy across all participating admins.
@@ -3584,8 +3561,8 @@
                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
                     continue;
                 }
-                if (length < admin.minimumPasswordLetters) {
-                    length = admin.minimumPasswordLetters;
+                if (length < admin.minimumPasswordMetrics.letters) {
+                    length = admin.minimumPasswordMetrics.letters;
                 }
             }
             return length;
@@ -3601,8 +3578,8 @@
         synchronized (this) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
-            if (ap.minimumPasswordNumeric != length) {
-                ap.minimumPasswordNumeric = length;
+            if (ap.minimumPasswordMetrics.numeric != length) {
+                ap.minimumPasswordMetrics.numeric = length;
                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
             }
         }
@@ -3619,7 +3596,7 @@
 
             if (who != null) {
                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
-                return admin != null ? admin.minimumPasswordNumeric : length;
+                return admin != null ? admin.minimumPasswordMetrics.numeric : length;
             }
 
             // Return the strictest policy across all participating admins.
@@ -3631,8 +3608,8 @@
                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
                     continue;
                 }
-                if (length < admin.minimumPasswordNumeric) {
-                    length = admin.minimumPasswordNumeric;
+                if (length < admin.minimumPasswordMetrics.numeric) {
+                    length = admin.minimumPasswordMetrics.numeric;
                 }
             }
             return length;
@@ -3648,8 +3625,8 @@
         synchronized (this) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
-            if (ap.minimumPasswordSymbols != length) {
-                ap.minimumPasswordSymbols = length;
+            if (ap.minimumPasswordMetrics.symbols != length) {
+                ap.minimumPasswordMetrics.symbols = length;
                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
             }
         }
@@ -3666,7 +3643,7 @@
 
             if (who != null) {
                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
-                return admin != null ? admin.minimumPasswordSymbols : length;
+                return admin != null ? admin.minimumPasswordMetrics.symbols : length;
             }
 
             // Return the strictest policy across all participating admins.
@@ -3678,8 +3655,8 @@
                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
                     continue;
                 }
-                if (length < admin.minimumPasswordSymbols) {
-                    length = admin.minimumPasswordSymbols;
+                if (length < admin.minimumPasswordMetrics.symbols) {
+                    length = admin.minimumPasswordMetrics.symbols;
                 }
             }
             return length;
@@ -3695,8 +3672,8 @@
         synchronized (this) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
-            if (ap.minimumPasswordNonLetter != length) {
-                ap.minimumPasswordNonLetter = length;
+            if (ap.minimumPasswordMetrics.nonLetter != length) {
+                ap.minimumPasswordMetrics.nonLetter = length;
                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
             }
         }
@@ -3713,7 +3690,7 @@
 
             if (who != null) {
                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
-                return admin != null ? admin.minimumPasswordNonLetter : length;
+                return admin != null ? admin.minimumPasswordMetrics.nonLetter : length;
             }
 
             // Return the strictest policy across all participating admins.
@@ -3725,8 +3702,8 @@
                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
                     continue;
                 }
-                if (length < admin.minimumPasswordNonLetter) {
-                    length = admin.minimumPasswordNonLetter;
+                if (length < admin.minimumPasswordMetrics.nonLetter) {
+                    length = admin.minimumPasswordMetrics.nonLetter;
                 }
             }
             return length;
@@ -3767,28 +3744,28 @@
     private boolean isActivePasswordSufficientForUserLocked(
             DevicePolicyData policy, int userHandle, boolean parent) {
         final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
-        if (policy.mActivePasswordQuality < requiredPasswordQuality) {
+        if (policy.mActivePasswordMetrics.quality < requiredPasswordQuality) {
             return false;
         }
         if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
-                && policy.mActivePasswordLength < getPasswordMinimumLength(
+                && policy.mActivePasswordMetrics.length < getPasswordMinimumLength(
                         null, userHandle, parent)) {
             return false;
         }
         if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
             return true;
         }
-        return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
+        return policy.mActivePasswordMetrics.upperCase >= getPasswordMinimumUpperCase(
                     null, userHandle, parent)
-                && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
+                && policy.mActivePasswordMetrics.lowerCase >= getPasswordMinimumLowerCase(
                         null, userHandle, parent)
-                && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
+                && policy.mActivePasswordMetrics.letters >= getPasswordMinimumLetters(
                         null, userHandle, parent)
-                && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
+                && policy.mActivePasswordMetrics.numeric >= getPasswordMinimumNumeric(
                         null, userHandle, parent)
-                && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
+                && policy.mActivePasswordMetrics.symbols >= getPasswordMinimumSymbols(
                         null, userHandle, parent)
-                && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
+                && policy.mActivePasswordMetrics.nonLetter >= getPasswordMinimumNonLetter(
                         null, userHandle, parent);
     }
 
@@ -3982,8 +3959,9 @@
             if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
                 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
             }
+            final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password);
             if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
-                int realQuality = LockPatternUtils.computePasswordQuality(password);
+                final int realQuality = metrics.quality;
                 if (realQuality < quality
                         && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
                     Slog.w(LOG_TAG, "resetPassword: password quality 0x"
@@ -4001,67 +3979,48 @@
                 return false;
             }
             if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
-                int letters = 0;
-                int uppercase = 0;
-                int lowercase = 0;
-                int numbers = 0;
-                int symbols = 0;
-                int nonletter = 0;
-                for (int i = 0; i < password.length(); i++) {
-                    char c = password.charAt(i);
-                    if (c >= 'A' && c <= 'Z') {
-                        letters++;
-                        uppercase++;
-                    } else if (c >= 'a' && c <= 'z') {
-                        letters++;
-                        lowercase++;
-                    } else if (c >= '0' && c <= '9') {
-                        numbers++;
-                        nonletter++;
-                    } else {
-                        symbols++;
-                        nonletter++;
-                    }
-                }
                 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
-                if(letters < neededLetters) {
-                    Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
+                if(metrics.letters < neededLetters) {
+                    Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters
                             + " does not meet required number of letters " + neededLetters);
                     return false;
                 }
-                int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
-                if (numbers < neededNumbers) {
-                    Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
+                int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
+                if (metrics.numeric < neededNumeric) {
+                    Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric
                             + " does not meet required number of numerical digits "
-                            + neededNumbers);
+                            + neededNumeric);
                     return false;
                 }
                 int neededLowerCase = getPasswordMinimumLowerCase(
                         null, userHandle, /* parent */ false);
-                if (lowercase < neededLowerCase) {
-                    Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
+                if (metrics.lowerCase < neededLowerCase) {
+                    Slog.w(LOG_TAG, "resetPassword: number of lowercase letters "
+                            + metrics.lowerCase
                             + " does not meet required number of lowercase letters "
                             + neededLowerCase);
                     return false;
                 }
                 int neededUpperCase = getPasswordMinimumUpperCase(
                         null, userHandle, /* parent */ false);
-                if (uppercase < neededUpperCase) {
-                    Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
+                if (metrics.upperCase < neededUpperCase) {
+                    Slog.w(LOG_TAG, "resetPassword: number of uppercase letters "
+                            + metrics.upperCase
                             + " does not meet required number of uppercase letters "
                             + neededUpperCase);
                     return false;
                 }
                 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
-                if (symbols < neededSymbols) {
-                    Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
+                if (metrics.symbols < neededSymbols) {
+                    Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols
                             + " does not meet required number of special symbols " + neededSymbols);
                     return false;
                 }
                 int neededNonLetter = getPasswordMinimumNonLetter(
                         null, userHandle, /* parent */ false);
-                if (nonletter < neededNonLetter) {
-                    Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
+                if (metrics.nonLetter < neededNonLetter) {
+                    Slog.w(LOG_TAG, "resetPassword: number of non-letter characters "
+                            + metrics.nonLetter
                             + " does not meet required number of non-letter characters "
                             + neededNonLetter);
                     return false;
@@ -4850,8 +4809,7 @@
     }
 
     @Override
-    public void setActivePasswordState(int quality, int length, int letters, int uppercase,
-            int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
+    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
         if (!mHasFeature) {
             return;
         }
@@ -4864,21 +4822,14 @@
 
         mContext.enforceCallingOrSelfPermission(
                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
-        validateQualityConstant(quality);
+        validateQualityConstant(metrics.quality);
 
         DevicePolicyData policy = getUserData(userHandle);
 
         long ident = mInjector.binderClearCallingIdentity();
         try {
             synchronized (this) {
-                policy.mActivePasswordQuality = quality;
-                policy.mActivePasswordLength = length;
-                policy.mActivePasswordLetters = letters;
-                policy.mActivePasswordLowerCase = lowercase;
-                policy.mActivePasswordUpperCase = uppercase;
-                policy.mActivePasswordNumeric = numbers;
-                policy.mActivePasswordSymbols = symbols;
-                policy.mActivePasswordNonLetter = nonletter;
+                policy.mActivePasswordMetrics = metrics;
                 policy.mFailedPasswordAttempts = 0;
                 saveSettingsLocked(userHandle);
                 updatePasswordExpirationsLocked(userHandle);
@@ -8437,10 +8388,10 @@
 
     /**
      * Returns true if specified admin is allowed to limit passwords and has a
-     * {@code passwordQuality} of at least {@code minPasswordQuality}
+     * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality}
      */
     private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
-        if (admin.passwordQuality < minPasswordQuality) {
+        if (admin.minimumPasswordMetrics.quality < minPasswordQuality) {
             return false;
         }
         return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 85b0d96..62947eb 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -118,6 +118,8 @@
 import java.util.Timer;
 import java.util.TimerTask;
 
+import static android.view.Display.DEFAULT_DISPLAY;
+
 public final class SystemServer {
     private static final String TAG = "SystemServer";
 
@@ -1403,7 +1405,7 @@
         // Update the configuration for this context by hand, because we're going
         // to start using it before the config change done in wm.systemReady() will
         // propagate to it.
-        Configuration config = wm.computeNewConfiguration();
+        final Configuration config = wm.computeNewConfiguration(DEFAULT_DISPLAY);
         DisplayMetrics metrics = new DisplayMetrics();
         WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
         w.getDefaultDisplay().getMetrics(metrics);
diff --git a/services/net/java/android/net/dhcp/DhcpClient.java b/services/net/java/android/net/dhcp/DhcpClient.java
index ffbea9f..8dd05b1 100644
--- a/services/net/java/android/net/dhcp/DhcpClient.java
+++ b/services/net/java/android/net/dhcp/DhcpClient.java
@@ -40,6 +40,7 @@
 import android.system.ErrnoException;
 import android.system.Os;
 import android.system.PacketSocketAddress;
+import android.util.EventLog;
 import android.util.Log;
 import android.util.SparseArray;
 import android.util.TimeUtils;
@@ -369,6 +370,13 @@
                     if (PACKET_DBG) {
                         Log.d(TAG, HexDump.dumpHexString(mPacket, 0, length));
                     }
+                    if (e.errorCode == DhcpErrorEvent.DHCP_NO_COOKIE) {
+                        int snetTagId = 0x534e4554;
+                        String bugId = "31850211";
+                        int uid = -1;
+                        String data = DhcpPacket.ParseException.class.getName();
+                        EventLog.writeEvent(snetTagId, bugId, uid, data);
+                    }
                     logError(e.errorCode);
                 }
             }
diff --git a/services/tests/runtests.py b/services/tests/runtests.py
new file mode 100755
index 0000000..35fec90f
--- /dev/null
+++ b/services/tests/runtests.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python
+
+# 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.
+
+import os
+import subprocess
+import sys
+
+INSTRUMENTED_PACKAGE_RUNNER = ('com.android.frameworks.servicestests/'
+                               'android.support.test.runner.AndroidJUnitRunner')
+
+PACKAGE_WHITELIST = (
+    'android.net',
+    'com.android.server.connectivity',
+)
+
+COLOR_RED = '\033[0;31m'
+COLOR_NONE ='\033[0m'
+
+def run(shell_command, echo=True):
+    if echo:
+        print '%s + %s%s' % (
+                COLOR_RED,
+                echo if isinstance(echo, str) else shell_command,
+                COLOR_NONE)
+    return subprocess.check_call(shell_command, shell=True)
+
+
+def main():
+    build_top = os.environ.get('ANDROID_BUILD_TOP', None)
+    out_dir = os.environ.get('OUT', None)
+    if build_top is None or out_dir is None:
+        print 'You need to source and lunch before you can use this script'
+        return 1
+
+    print 'Building tests...'
+    run('make -j32 -C %s -f build/core/main.mk '
+        'MODULES-IN-frameworks-base-services-tests-servicestests' % build_top,
+        echo='mmma -j32 %s/frameworks/base/services/tests/servicestests' %
+             build_top)
+
+    print 'Installing tests...'
+    run('adb root')
+    run('adb wait-for-device')
+    apk_path = (
+            '%s/data/app/FrameworksServicesTests/FrameworksServicesTests.apk' %
+            out_dir)
+    run('adb install -r -g "%s"' % apk_path)
+
+    print 'Running tests...'
+    if len(sys.argv) != 1:
+        run('adb shell am instrument -w "%s" %s' %
+            (INSTRUMENTED_PACKAGE_RUNNER, ' '.join(sys.argv[1:])))
+        return 0
+
+    # It would be nice if the activity manager accepted a list of packages, but
+    # in lieu of that...
+    for package in PACKAGE_WHITELIST:
+        run('adb shell am instrument -w -e package %s %s' %
+            (package, INSTRUMENTED_PACKAGE_RUNNER))
+
+    return 0
+
+
+if __name__ == '__main__':
+    sys.exit(main())
diff --git a/services/tests/servicestests/src/com/android/server/connectivity/TetheringTest.java b/services/tests/servicestests/src/com/android/server/connectivity/TetheringTest.java
new file mode 100644
index 0000000..a9f68c8
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/connectivity/TetheringTest.java
@@ -0,0 +1,129 @@
+/*
+ * 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.connectivity;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.net.INetworkPolicyManager;
+import android.net.INetworkStatsService;
+import android.os.INetworkManagementService;
+import android.os.PersistableBundle;
+import android.os.test.TestLooper;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.telephony.CarrierConfigManager;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class TetheringTest {
+    private static final String[] PROVISIONING_APP_NAME = {"some", "app"};
+
+    @Mock private Context mContext;
+    @Mock private INetworkManagementService mNMService;
+    @Mock private INetworkStatsService mStatsService;
+    @Mock private INetworkPolicyManager mPolicyManager;
+    @Mock private MockableSystemProperties mSystemProperties;
+    @Mock private Resources mResources;
+    @Mock private CarrierConfigManager mCarrierConfigManager;
+
+    // Like so many Android system APIs, these cannot be mocked because it is marked final.
+    // We have to use the real versions.
+    private final PersistableBundle mCarrierConfig = new PersistableBundle();
+    private final TestLooper mLooper = new TestLooper();
+
+    private Tethering mTethering;
+
+    @Before public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        when(mContext.getResources()).thenReturn(mResources);
+        when(mResources.getStringArray(com.android.internal.R.array.config_tether_dhcp_range))
+                .thenReturn(new String[0]);
+        when(mResources.getStringArray(com.android.internal.R.array.config_tether_usb_regexs))
+                .thenReturn(new String[0]);
+        when(mResources.getStringArray(com.android.internal.R.array.config_tether_wifi_regexs))
+                .thenReturn(new String[0]);
+        when(mResources.getStringArray(com.android.internal.R.array.config_tether_bluetooth_regexs))
+                .thenReturn(new String[0]);
+        when(mResources.getIntArray(com.android.internal.R.array.config_tether_upstream_types))
+                .thenReturn(new int[0]);
+        mTethering = new Tethering(mContext, mNMService, mStatsService, mPolicyManager,
+                                   mLooper.getLooper(), mSystemProperties);
+    }
+
+    private void setupForRequiredProvisioning() {
+        // Produce some acceptable looking provision app setting if requested.
+        when(mResources.getStringArray(
+                com.android.internal.R.array.config_mobile_hotspot_provision_app))
+                .thenReturn(PROVISIONING_APP_NAME);
+        // Don't disable tethering provisioning unless requested.
+        when(mSystemProperties.getBoolean(eq(Tethering.DISABLE_PROVISIONING_SYSPROP_KEY),
+                                          anyBoolean())).thenReturn(false);
+        // Act like the CarrierConfigManager is present and ready unless told otherwise.
+        when(mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE))
+                .thenReturn(mCarrierConfigManager);
+        when(mCarrierConfigManager.getConfig()).thenReturn(mCarrierConfig);
+        mCarrierConfig.putBoolean(CarrierConfigManager.KEY_REQUIRE_ENTITLEMENT_CHECKS_BOOL, true);
+    }
+
+    @Test
+    public void canRequireProvisioning() {
+        setupForRequiredProvisioning();
+        assertTrue(mTethering.isTetherProvisioningRequired());
+    }
+
+    @Test
+    public void toleratesCarrierConfigManagerMissing() {
+        setupForRequiredProvisioning();
+        when(mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE))
+                .thenReturn(null);
+        // Couldn't get the CarrierConfigManager, but still had a declared provisioning app.
+        // We therefore still require provisioning.
+        assertTrue(mTethering.isTetherProvisioningRequired());
+    }
+
+    @Test
+    public void toleratesCarrierConfigMissing() {
+        setupForRequiredProvisioning();
+        when(mCarrierConfigManager.getConfig()).thenReturn(null);
+        // We still have a provisioning app configured, so still require provisioning.
+        assertTrue(mTethering.isTetherProvisioningRequired());
+    }
+
+    @Test
+    public void provisioningNotRequiredWhenAppNotFound() {
+        setupForRequiredProvisioning();
+        when(mResources.getStringArray(
+                com.android.internal.R.array.config_mobile_hotspot_provision_app))
+                .thenReturn(null);
+        assertTrue(!mTethering.isTetherProvisioningRequired());
+        when(mResources.getStringArray(
+                com.android.internal.R.array.config_mobile_hotspot_provision_app))
+                .thenReturn(new String[] {"malformedApp"});
+        assertTrue(!mTethering.isTetherProvisioningRequired());
+    }
+}
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index 5b63199..fe9d41a 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -3161,7 +3161,10 @@
      * methods may return true.
      *
      * <p>This method returns valid data for registered cells on devices with
-     * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY}.
+     * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY}. In cases where only
+     * partial information is available for a particular CellInfo entry, unavailable fields
+     * will be reported as Integer.MAX_VALUE. All reported cells will include at least a
+     * valid set of technology-specific identification info and a power level measurement.
      *
      *<p>
      * This method is preferred over using {@link
diff --git a/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java b/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
index 8424344..f737b24 100644
--- a/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
+++ b/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
@@ -25,6 +25,7 @@
 import junit.framework.TestCase;
 
 import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
+import static android.view.Display.DEFAULT_DISPLAY;
 
 /**
  * TODO: Remove this. This is only a placeholder, need to implement this.
@@ -113,7 +114,8 @@
         }
 
         try {
-            mWm.updateOrientationFromAppTokens(new Configuration(), null);
+            mWm.updateOrientationFromAppTokens(new Configuration(),
+                    null /* freezeThisOneIfNeeded */, DEFAULT_DISPLAY);
             fail("IWindowManager.updateOrientationFromAppTokens did not throw SecurityException as"
                     + " expected");
         } catch (SecurityException e) {
diff --git a/tools/layoutlib/bridge/src/android/view/IWindowManagerImpl.java b/tools/layoutlib/bridge/src/android/view/IWindowManagerImpl.java
index 09ab657..6b4db42 100644
--- a/tools/layoutlib/bridge/src/android/view/IWindowManagerImpl.java
+++ b/tools/layoutlib/bridge/src/android/view/IWindowManagerImpl.java
@@ -413,7 +413,8 @@
     }
 
     @Override
-    public int[] setNewConfiguration(Configuration arg0) throws RemoteException {
+    public int[] setNewDisplayOverrideConfiguration(Configuration arg0, int displayId)
+            throws RemoteException {
         // TODO Auto-generated method stub
         return null;
     }
@@ -487,7 +488,7 @@
     }
 
     @Override
-    public Configuration updateOrientationFromAppTokens(Configuration arg0, IBinder arg1)
+    public Configuration updateOrientationFromAppTokens(Configuration arg0, IBinder arg1, int arg2)
             throws RemoteException {
         // TODO Auto-generated method stub
         return null;