Merge "Media API: Using context's classloader in MediaBrowser"
diff --git a/Android.mk b/Android.mk
index cca87ca..8fd8a2e 100644
--- a/Android.mk
+++ b/Android.mk
@@ -71,8 +71,6 @@
 	core/java/android/accounts/IAccountManagerResponse.aidl \
 	core/java/android/accounts/IAccountAuthenticator.aidl \
 	core/java/android/accounts/IAccountAuthenticatorResponse.aidl \
-	core/java/android/app/IActivityContainer.aidl \
-	core/java/android/app/IActivityContainerCallback.aidl \
 	core/java/android/app/IActivityController.aidl \
 	core/java/android/app/IActivityManager.aidl \
 	core/java/android/app/IActivityPendingResult.aidl \
@@ -84,6 +82,7 @@
 	core/java/android/app/ITaskStackListener.aidl \
 	core/java/android/app/IBackupAgent.aidl \
 	core/java/android/app/IEphemeralResolver.aidl \
+	core/java/android/app/IInputForwarder.aidl \
 	core/java/android/app/IInstantAppResolver.aidl \
 	core/java/android/app/IInstrumentationWatcher.aidl \
 	core/java/android/app/INotificationManager.aidl \
@@ -501,7 +500,7 @@
 	telecomm/java/com/android/internal/telecom/RemoteServiceCallback.aidl \
         telephony/java/android/telephony/mbms/IMbmsDownloadManagerCallback.aidl \
 	telephony/java/android/telephony/mbms/IMbmsStreamingManagerCallback.aidl \
-	telephony/java/android/telephony/mbms/IDownloadCallback.aidl \
+	telephony/java/android/telephony/mbms/IDownloadProgressListener.aidl \
         telephony/java/android/telephony/mbms/IStreamingServiceCallback.aidl \
 	telephony/java/android/telephony/mbms/vendor/IMbmsDownloadService.aidl \
 	telephony/java/android/telephony/mbms/vendor/IMbmsStreamingService.aidl \
diff --git a/api/current.txt b/api/current.txt
index 65935ae..e149797 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -22170,6 +22170,8 @@
     field public static final int AVCLevel51 = 32768; // 0x8000
     field public static final int AVCLevel52 = 65536; // 0x10000
     field public static final int AVCProfileBaseline = 1; // 0x1
+    field public static final int AVCProfileConstrainedBaseline = 65536; // 0x10000
+    field public static final int AVCProfileConstrainedHigh = 524288; // 0x80000
     field public static final int AVCProfileExtended = 4; // 0x4
     field public static final int AVCProfileHigh = 8; // 0x8
     field public static final int AVCProfileHigh10 = 16; // 0x10
@@ -30607,6 +30609,7 @@
     field public static final int N = 24; // 0x18
     field public static final int N_MR1 = 25; // 0x19
     field public static final int O = 26; // 0x1a
+    field public static final int O_MR1 = 10000; // 0x2710
   }
 
   public final class Bundle extends android.os.BaseBundle implements java.lang.Cloneable android.os.Parcelable {
@@ -40261,6 +40264,7 @@
     field public static final java.lang.String EXTRA_CALL_VOICEMAIL_INTENT = "android.telephony.extra.CALL_VOICEMAIL_INTENT";
     field public static final java.lang.String EXTRA_HIDE_PUBLIC_SETTINGS = "android.telephony.extra.HIDE_PUBLIC_SETTINGS";
     field public static final java.lang.String EXTRA_INCOMING_NUMBER = "incoming_number";
+    field public static final java.lang.String EXTRA_IS_REFRESH = "android.telephony.extra.IS_REFRESH";
     field public static final java.lang.String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT = "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
     field public static final java.lang.String EXTRA_NOTIFICATION_COUNT = "android.telephony.extra.NOTIFICATION_COUNT";
     field public static final java.lang.String EXTRA_PHONE_ACCOUNT_HANDLE = "android.telephony.extra.PHONE_ACCOUNT_HANDLE";
diff --git a/api/system-current.txt b/api/system-current.txt
index 9e4bad8..ff3069a 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -11639,6 +11639,7 @@
     field public int flags;
     field public java.lang.CharSequence nonLocalizedDescription;
     field public int priority;
+    field public int requestRes;
   }
 
   public class PermissionInfo extends android.content.pm.PackageItemInfo implements android.os.Parcelable {
@@ -11672,6 +11673,7 @@
     field public java.lang.String group;
     field public java.lang.CharSequence nonLocalizedDescription;
     field public int protectionLevel;
+    field public int requestRes;
   }
 
   public final class ProviderInfo extends android.content.pm.ComponentInfo implements android.os.Parcelable {
@@ -17386,7 +17388,7 @@
     method public java.lang.String getProduct();
     method public java.lang.String getSerial();
     method public java.lang.String getServiceName();
-    method public java.lang.String getVendorExension();
+    method public java.lang.String getVendorInfo();
     method public java.lang.String getVersion();
     method public boolean isBackgroundScanningSupported();
     method public boolean isCaptureSupported();
@@ -17403,7 +17405,7 @@
     method public android.hardware.radio.ProgramSelector getSelector();
     method public int getSignalStrength();
     method public deprecated int getSubChannel();
-    method public java.lang.String getVendorExension();
+    method public java.lang.String getVendorInfo();
     method public boolean isDigital();
     method public boolean isLive();
     method public boolean isMuted();
@@ -17418,7 +17420,7 @@
   public final class RadioMetadata implements android.os.Parcelable {
     method public boolean containsKey(java.lang.String);
     method public int describeContents();
-    method public android.graphics.Bitmap getBitmap(java.lang.String);
+    method public deprecated android.graphics.Bitmap getBitmap(java.lang.String);
     method public android.hardware.radio.RadioMetadata.Clock getClock(java.lang.String);
     method public int getInt(java.lang.String);
     method public java.lang.String getString(java.lang.String);
@@ -24111,6 +24113,8 @@
     field public static final int AVCLevel51 = 32768; // 0x8000
     field public static final int AVCLevel52 = 65536; // 0x10000
     field public static final int AVCProfileBaseline = 1; // 0x1
+    field public static final int AVCProfileConstrainedBaseline = 65536; // 0x10000
+    field public static final int AVCProfileConstrainedHigh = 524288; // 0x80000
     field public static final int AVCProfileExtended = 4; // 0x4
     field public static final int AVCProfileHigh = 8; // 0x8
     field public static final int AVCProfileHigh10 = 16; // 0x10
@@ -33417,6 +33421,7 @@
     field public static final int N = 24; // 0x18
     field public static final int N_MR1 = 25; // 0x19
     field public static final int O = 26; // 0x1a
+    field public static final int O_MR1 = 10000; // 0x2710
   }
 
   public final class Bundle extends android.os.BaseBundle implements java.lang.Cloneable android.os.Parcelable {
@@ -43878,6 +43883,7 @@
     field public static final java.lang.String EXTRA_CALL_VOICEMAIL_INTENT = "android.telephony.extra.CALL_VOICEMAIL_INTENT";
     field public static final java.lang.String EXTRA_HIDE_PUBLIC_SETTINGS = "android.telephony.extra.HIDE_PUBLIC_SETTINGS";
     field public static final java.lang.String EXTRA_INCOMING_NUMBER = "incoming_number";
+    field public static final java.lang.String EXTRA_IS_REFRESH = "android.telephony.extra.IS_REFRESH";
     field public static final java.lang.String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT = "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
     field public static final java.lang.String EXTRA_NOTIFICATION_COUNT = "android.telephony.extra.NOTIFICATION_COUNT";
     field public static final java.lang.String EXTRA_PHONE_ACCOUNT_HANDLE = "android.telephony.extra.PHONE_ACCOUNT_HANDLE";
diff --git a/api/test-current.txt b/api/test-current.txt
index f089362..08df809 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -22281,6 +22281,8 @@
     field public static final int AVCLevel51 = 32768; // 0x8000
     field public static final int AVCLevel52 = 65536; // 0x10000
     field public static final int AVCProfileBaseline = 1; // 0x1
+    field public static final int AVCProfileConstrainedBaseline = 65536; // 0x10000
+    field public static final int AVCProfileConstrainedHigh = 524288; // 0x80000
     field public static final int AVCProfileExtended = 4; // 0x4
     field public static final int AVCProfileHigh = 8; // 0x8
     field public static final int AVCProfileHigh10 = 16; // 0x10
@@ -30718,6 +30720,7 @@
     field public static final int N = 24; // 0x18
     field public static final int N_MR1 = 25; // 0x19
     field public static final int O = 26; // 0x1a
+    field public static final int O_MR1 = 10000; // 0x2710
   }
 
   public final class Bundle extends android.os.BaseBundle implements java.lang.Cloneable android.os.Parcelable {
@@ -37122,7 +37125,7 @@
   }
 
   public final class CharSequenceTransformation implements android.os.Parcelable android.service.autofill.Transformation {
-    method public void apply(android.service.autofill.ValueFinder, android.widget.RemoteViews, int);
+    method public void apply(android.service.autofill.ValueFinder, android.widget.RemoteViews, int) throws java.lang.Exception;
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.service.autofill.CharSequenceTransformation> CREATOR;
@@ -37220,7 +37223,7 @@
   }
 
   public final class ImageTransformation implements android.os.Parcelable android.service.autofill.Transformation {
-    method public void apply(android.service.autofill.ValueFinder, android.widget.RemoteViews, int);
+    method public void apply(android.service.autofill.ValueFinder, android.widget.RemoteViews, int) throws java.lang.Exception;
     method public int describeContents();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.service.autofill.ImageTransformation> CREATOR;
@@ -40487,6 +40490,7 @@
     field public static final java.lang.String EXTRA_CALL_VOICEMAIL_INTENT = "android.telephony.extra.CALL_VOICEMAIL_INTENT";
     field public static final java.lang.String EXTRA_HIDE_PUBLIC_SETTINGS = "android.telephony.extra.HIDE_PUBLIC_SETTINGS";
     field public static final java.lang.String EXTRA_INCOMING_NUMBER = "incoming_number";
+    field public static final java.lang.String EXTRA_IS_REFRESH = "android.telephony.extra.IS_REFRESH";
     field public static final java.lang.String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT = "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
     field public static final java.lang.String EXTRA_NOTIFICATION_COUNT = "android.telephony.extra.NOTIFICATION_COUNT";
     field public static final java.lang.String EXTRA_PHONE_ACCOUNT_HANDLE = "android.telephony.extra.PHONE_ACCOUNT_HANDLE";
@@ -41717,6 +41721,13 @@
     field public static final java.lang.Object SELECTION_START;
   }
 
+  public static final class Selection.MemoryTextWatcher implements android.text.TextWatcher {
+    ctor public Selection.MemoryTextWatcher();
+    method public void afterTextChanged(android.text.Editable);
+    method public void beforeTextChanged(java.lang.CharSequence, int, int, int);
+    method public void onTextChanged(java.lang.CharSequence, int, int, int);
+  }
+
   public abstract interface SpanWatcher implements android.text.NoCopySpan {
     method public abstract void onSpanAdded(android.text.Spannable, java.lang.Object, int, int);
     method public abstract void onSpanChanged(android.text.Spannable, java.lang.Object, int, int, int, int);
diff --git a/cmds/am/src/com/android/commands/am/Am.java b/cmds/am/src/com/android/commands/am/Am.java
index f003061..ab075ee 100644
--- a/cmds/am/src/com/android/commands/am/Am.java
+++ b/cmds/am/src/com/android/commands/am/Am.java
@@ -16,70 +16,25 @@
 
 package com.android.commands.am;
 
-import static android.app.ActivityManager.RESIZE_MODE_SYSTEM;
-import static android.app.ActivityManager.RESIZE_MODE_USER;
-import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
-import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
-
 import android.app.ActivityManager;
-import android.app.ActivityManager.StackInfo;
-import android.app.IActivityContainer;
-import android.app.IActivityController;
 import android.app.IActivityManager;
-import android.app.IInstrumentationWatcher;
-import android.app.Instrumentation;
-import android.app.IStopUserCallback;
-import android.app.ProfilerInfo;
-import android.app.UiAutomationConnection;
-import android.app.usage.ConfigurationStats;
-import android.app.usage.IUsageStatsManager;
-import android.app.usage.UsageStatsManager;
-import android.content.ComponentCallbacks2;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.IIntentReceiver;
-import android.content.Intent;
 import android.content.pm.IPackageManager;
-import android.content.pm.InstrumentationInfo;
-import android.content.pm.ParceledListSlice;
-import android.content.pm.UserInfo;
-import android.content.res.Configuration;
-import android.graphics.Rect;
-import android.os.Binder;
-import android.os.Build;
-import android.os.Bundle;
 import android.os.ParcelFileDescriptor;
 import android.os.RemoteException;
 import android.os.ResultReceiver;
 import android.os.SELinux;
 import android.os.ServiceManager;
 import android.os.ShellCallback;
-import android.os.ShellCommand;
-import android.os.SystemProperties;
 import android.os.UserHandle;
-import android.text.TextUtils;
 import android.util.AndroidException;
-import android.util.ArrayMap;
-import android.util.Log;
-import android.view.IWindowManager;
 
 import com.android.internal.os.BaseCommand;
-import com.android.internal.util.HexDump;
-import com.android.internal.util.Preconditions;
 
-import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileDescriptor;
 import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.io.InputStreamReader;
 import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
 
 public class Am extends BaseCommand {
 
diff --git a/core/java/android/app/ActivityView.java b/core/java/android/app/ActivityView.java
index 29b83dc..5dd47ac 100644
--- a/core/java/android/app/ActivityView.java
+++ b/core/java/android/app/ActivityView.java
@@ -1,5 +1,5 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
+/**
+ * Copyright (c) 2017 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -16,17 +16,12 @@
 
 package android.app;
 
-import static android.app.ActivityManager.START_CANCELED;
-
+import android.annotation.NonNull;
 import android.content.Context;
-import android.content.ContextWrapper;
-import android.content.IIntentSender;
 import android.content.Intent;
-import android.content.IntentSender;
-import android.graphics.SurfaceTexture;
-import android.os.IBinder;
-import android.os.Message;
-import android.os.OperationCanceledException;
+import android.hardware.display.DisplayManager;
+import android.hardware.display.VirtualDisplay;
+import android.hardware.input.InputManager;
 import android.os.RemoteException;
 import android.util.AttributeSet;
 import android.util.DisplayMetrics;
@@ -35,163 +30,177 @@
 import android.view.InputEvent;
 import android.view.MotionEvent;
 import android.view.Surface;
-import android.view.TextureView;
-import android.view.TextureView.SurfaceTextureListener;
-import android.view.View;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
 import android.view.ViewGroup;
 import android.view.WindowManager;
+
 import dalvik.system.CloseGuard;
 
-import java.lang.ref.WeakReference;
-import java.util.ArrayDeque;
-import java.util.concurrent.Executor;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import com.android.internal.annotations.GuardedBy;
-
-
-/** @hide */
+/**
+ * Activity container that allows launching activities into itself and does input forwarding.
+ * <p>Creation of this view is only allowed to callers who have
+ * {@link android.Manifest.permission#INJECT_EVENTS} permission.
+ * <p>Activity launching into this container is restricted by the same rules that apply to launching
+ * on VirtualDisplays.
+ * @hide
+ */
 public class ActivityView extends ViewGroup {
+
+    private static final String DISPLAY_NAME = "ActivityViewVirtualDisplay";
     private static final String TAG = "ActivityView";
-    private static final boolean DEBUG = false;
 
-    private static final int MSG_SET_SURFACE = 1;
-
-    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
-    private static final int MINIMUM_POOL_SIZE = 1;
-    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
-    private static final int KEEP_ALIVE = 1;
-
-    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
-        private final AtomicInteger mCount = new AtomicInteger(1);
-
-        public Thread newThread(Runnable r) {
-            return new Thread(r, "ActivityView #" + mCount.getAndIncrement());
-        }
-    };
-
-    private static final BlockingQueue<Runnable> sPoolWorkQueue =
-            new LinkedBlockingQueue<Runnable>(128);
-
-    /**
-     * An {@link Executor} that can be used to execute tasks in parallel.
-     */
-    private static final Executor sExecutor = new ThreadPoolExecutor(MINIMUM_POOL_SIZE,
-            MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
-
-
-    private static class SerialExecutor implements Executor {
-        private final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
-        private Runnable mActive;
-
-        public synchronized void execute(final Runnable r) {
-            mTasks.offer(new Runnable() {
-                public void run() {
-                    try {
-                        r.run();
-                    } finally {
-                        scheduleNext();
-                    }
-                }
-            });
-            if (mActive == null) {
-                scheduleNext();
-            }
-        }
-
-        protected synchronized void scheduleNext() {
-            if ((mActive = mTasks.poll()) != null) {
-                sExecutor.execute(mActive);
-            }
-        }
-    }
-
-    private final SerialExecutor mExecutor = new SerialExecutor();
-
-    private final int mDensityDpi;
-    private final TextureView mTextureView;
-
-    @GuardedBy("mActivityContainerLock")
-    private ActivityContainerWrapper mActivityContainer;
-    private Object mActivityContainerLock = new Object();
-
-    private Activity mActivity;
-    private int mWidth;
-    private int mHeight;
+    private VirtualDisplay mVirtualDisplay;
+    private final SurfaceView mSurfaceView;
     private Surface mSurface;
-    private int mLastVisibility;
-    private ActivityViewCallback mActivityViewCallback;
 
+    private final SurfaceCallback mSurfaceCallback;
+    private StateCallback mActivityViewCallback;
+
+    private IInputForwarder mInputForwarder;
+
+    private final CloseGuard mGuard = CloseGuard.get();
+    private boolean mOpened; // Protected by mGuard.
 
     public ActivityView(Context context) {
-        this(context, null);
+        this(context, null /* attrs */);
     }
 
     public ActivityView(Context context, AttributeSet attrs) {
-        this(context, attrs, 0);
+        this(context, attrs, 0 /* defStyle */);
     }
 
     public ActivityView(Context context, AttributeSet attrs, int defStyle) {
         super(context, attrs, defStyle);
 
-        while (context instanceof ContextWrapper) {
-            if (context instanceof Activity) {
-                mActivity = (Activity)context;
-                break;
-            }
-            context = ((ContextWrapper)context).getBaseContext();
-        }
-        if (mActivity == null) {
-            throw new IllegalStateException("The ActivityView's Context is not an Activity.");
-        }
+        mSurfaceView = new SurfaceView(context);
+        mSurfaceCallback = new SurfaceCallback();
+        mSurfaceView.getHolder().addCallback(mSurfaceCallback);
+        addView(mSurfaceView);
 
+        mOpened = true;
+        mGuard.open("release");
+    }
+
+    /** Callback that notifies when the container is ready or destroyed. */
+    public abstract static class StateCallback {
+        /**
+         * Called when the container is ready for launching activities. Calling
+         * {@link #startActivity(Intent)} prior to this callback will result in an
+         * {@link IllegalStateException}.
+         *
+         * @see #startActivity(Intent)
+         */
+        public abstract void onActivityViewReady(ActivityView view);
+        /**
+         * Called when the container can no longer launch activities. Calling
+         * {@link #startActivity(Intent)} after this callback will result in an
+         * {@link IllegalStateException}.
+         *
+         * @see #startActivity(Intent)
+         */
+        public abstract void onActivityViewDestroyed(ActivityView view);
+    }
+
+    /**
+     * Set the callback to be notified about state changes.
+     * <p>This class must finish initializing before {@link #startActivity(Intent)} can be called.
+     * <p>Note: If the instance was ready prior to this call being made, then
+     * {@link StateCallback#onActivityViewReady(ActivityView)} will be called from within
+     * this method call.
+     *
+     * @param callback The callback to report events to.
+     *
+     * @see StateCallback
+     * @see #startActivity(Intent)
+     */
+    public void setCallback(StateCallback callback) {
+        mActivityViewCallback = callback;
+
+        if (mVirtualDisplay != null && mActivityViewCallback != null) {
+            mActivityViewCallback.onActivityViewReady(this);
+        }
+    }
+
+    /**
+     * Launch a new activity into this container.
+     * <p>Activity resolved by the provided {@link Intent} must have
+     * {@link android.R.attr#resizeableActivity} attribute set to {@code true} in order to be
+     * launched here. Also, if activity is not owned by the owner of this container, it must allow
+     * embedding and the caller must have permission to embed.
+     * <p>Note: This class must finish initializing and
+     * {@link StateCallback#onActivityViewReady(ActivityView)} callback must be triggered before
+     * this method can be called.
+     *
+     * @param intent Intent used to launch an activity.
+     *
+     * @see StateCallback
+     * @see #startActivity(PendingIntent)
+     */
+    public void startActivity(@NonNull Intent intent) {
+        final ActivityOptions options = prepareActivityOptions();
+        getContext().startActivity(intent, options.toBundle());
+    }
+
+    /**
+     * Launch a new activity into this container.
+     * <p>Activity resolved by the provided {@link PendingIntent} must have
+     * {@link android.R.attr#resizeableActivity} attribute set to {@code true} in order to be
+     * launched here. Also, if activity is not owned by the owner of this container, it must allow
+     * embedding and the caller must have permission to embed.
+     * <p>Note: This class must finish initializing and
+     * {@link StateCallback#onActivityViewReady(ActivityView)} callback must be triggered before
+     * this method can be called.
+     *
+     * @param pendingIntent Intent used to launch an activity.
+     *
+     * @see StateCallback
+     * @see #startActivity(Intent)
+     */
+    public void startActivity(@NonNull PendingIntent pendingIntent) {
+        final ActivityOptions options = prepareActivityOptions();
         try {
-            mActivityContainer = new ActivityContainerWrapper(
-                    ActivityManager.getService().createVirtualActivityContainer(
-                            mActivity.getActivityToken(), new ActivityContainerCallback(this)));
-        } catch (RemoteException e) {
-            throw new RuntimeException("ActivityView: Unable to create ActivityContainer. "
-                    + e);
+            pendingIntent.send(null /* context */, 0 /* code */, null /* intent */,
+                    null /* onFinished */, null /* handler */, null /* requiredPermission */,
+                    options.toBundle());
+        } catch (PendingIntent.CanceledException e) {
+            throw new RuntimeException(e);
         }
+    }
 
-        mTextureView = new TextureView(context);
-        mTextureView.setSurfaceTextureListener(new ActivityViewSurfaceTextureListener());
-        addView(mTextureView);
+    /**
+     * Check if container is ready to launch and create {@link ActivityOptions} to target the
+     * virtual display.
+     */
+    private ActivityOptions prepareActivityOptions() {
+        if (mVirtualDisplay == null) {
+            throw new IllegalStateException(
+                    "Trying to start activity before ActivityView is ready.");
+        }
+        final ActivityOptions options = ActivityOptions.makeBasic();
+        options.setLaunchDisplayId(mVirtualDisplay.getDisplay().getDisplayId());
+        return options;
+    }
 
-        WindowManager wm = (WindowManager)mActivity.getSystemService(Context.WINDOW_SERVICE);
-        DisplayMetrics metrics = new DisplayMetrics();
-        wm.getDefaultDisplay().getMetrics(metrics);
-        mDensityDpi = metrics.densityDpi;
-
-        mLastVisibility = getVisibility();
-
-        if (DEBUG) Log.v(TAG, "ctor()");
+    /**
+     * Release this container. Activity launching will no longer be permitted.
+     * <p>Note: Calling this method is allowed after
+     * {@link StateCallback#onActivityViewReady(ActivityView)} callback was triggered and before
+     * {@link StateCallback#onActivityViewDestroyed(ActivityView)}.
+     *
+     * @see StateCallback
+     */
+    public void release() {
+        if (mVirtualDisplay == null) {
+            throw new IllegalStateException(
+                    "Trying to release container that is not initialized.");
+        }
+        performRelease();
     }
 
     @Override
-    protected void onLayout(boolean changed, int l, int t, int r, int b) {
-        mTextureView.layout(0, 0, r - l, b - t);
-    }
-
-    @Override
-    protected void onVisibilityChanged(View changedView, final int visibility) {
-        super.onVisibilityChanged(changedView, visibility);
-
-        if (mSurface != null && (visibility == View.GONE || mLastVisibility == View.GONE)) {
-            if (DEBUG) Log.v(TAG, "visibility changed; enqueing runnable");
-            final Surface surface = (visibility == View.GONE) ? null : mSurface;
-            setSurfaceAsync(surface, mWidth, mHeight, mDensityDpi, false);
-        }
-        mLastVisibility = visibility;
-    }
-
-    private boolean injectInputEvent(InputEvent event) {
-        return mActivityContainer != null && mActivityContainer.injectEvent(event);
+    public void onLayout(boolean changed, int l, int t, int r, int b) {
+        mSurfaceView.layout(0 /* left */, 0 /* top */, r - l /* right */, b - t /* bottom */);
     }
 
     @Override
@@ -209,76 +218,86 @@
         return super.onGenericMotionEvent(event);
     }
 
-    @Override
-    public void onAttachedToWindow() {
-        if (DEBUG) Log.v(TAG, "onAttachedToWindow(): mActivityContainer=" + mActivityContainer +
-                " mSurface=" + mSurface);
-    }
-
-    @Override
-    public void onDetachedFromWindow() {
-        if (DEBUG) Log.v(TAG, "onDetachedFromWindow(): mActivityContainer=" + mActivityContainer +
-                " mSurface=" + mSurface);
-    }
-
-    public boolean isAttachedToDisplay() {
-        return mSurface != null;
-    }
-
-    public void startActivity(Intent intent) {
-        if (mActivityContainer == null) {
-            throw new IllegalStateException("Attempt to call startActivity after release");
+    private boolean injectInputEvent(InputEvent event) {
+        if (mInputForwarder != null) {
+            try {
+                return mInputForwarder.forwardEvent(event);
+            } catch (RemoteException e) {
+                e.rethrowAsRuntimeException();
+            }
         }
-        if (mSurface == null) {
-            throw new IllegalStateException("Surface not yet created.");
+        return false;
+    }
+
+    private class SurfaceCallback implements SurfaceHolder.Callback {
+        @Override
+        public void surfaceCreated(SurfaceHolder surfaceHolder) {
+            if (mVirtualDisplay == null) {
+                mSurface = mSurfaceView.getHolder().getSurface();
+                initVirtualDisplay();
+                if (mVirtualDisplay != null && mActivityViewCallback != null) {
+                    mActivityViewCallback.onActivityViewReady(ActivityView.this);
+                }
+            } else {
+                mVirtualDisplay.setSurface(surfaceHolder.getSurface());
+            }
         }
-        if (DEBUG) Log.v(TAG, "startActivity(): intent=" + intent + " " +
-                (isAttachedToDisplay() ? "" : "not") + " attached");
-        if (mActivityContainer.startActivity(intent) == START_CANCELED) {
-            throw new OperationCanceledException();
+
+        @Override
+        public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
+            if (mVirtualDisplay != null) {
+                mVirtualDisplay.resize(width, height, getBaseDisplayDensity());
+            }
+        }
+
+        @Override
+        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
+            mSurface.release();
+            mSurface = null;
+            if (mVirtualDisplay != null) {
+                mVirtualDisplay.setSurface(null);
+            }
         }
     }
 
-    public void startActivity(IntentSender intentSender) {
-        if (mActivityContainer == null) {
-            throw new IllegalStateException("Attempt to call startActivity after release");
+    private void initVirtualDisplay() {
+        if (mVirtualDisplay != null) {
+            throw new IllegalStateException("Trying to initialize for the second time.");
         }
-        if (mSurface == null) {
-            throw new IllegalStateException("Surface not yet created.");
-        }
-        if (DEBUG) Log.v(TAG, "startActivityIntentSender(): intentSender=" + intentSender + " " +
-                (isAttachedToDisplay() ? "" : "not") + " attached");
-        final IIntentSender iIntentSender = intentSender.getTarget();
-        if (mActivityContainer.startActivityIntentSender(iIntentSender) == START_CANCELED) {
-            throw new OperationCanceledException();
-        }
-    }
 
-    public void startActivity(PendingIntent pendingIntent) {
-        if (mActivityContainer == null) {
-            throw new IllegalStateException("Attempt to call startActivity after release");
-        }
-        if (mSurface == null) {
-            throw new IllegalStateException("Surface not yet created.");
-        }
-        if (DEBUG) Log.v(TAG, "startActivityPendingIntent(): PendingIntent=" + pendingIntent + " "
-                + (isAttachedToDisplay() ? "" : "not") + " attached");
-        final IIntentSender iIntentSender = pendingIntent.getTarget();
-        if (mActivityContainer.startActivityIntentSender(iIntentSender) == START_CANCELED) {
-            throw new OperationCanceledException();
-        }
-    }
-
-    public void release() {
-        if (DEBUG) Log.v(TAG, "release() mActivityContainer=" + mActivityContainer +
-                " mSurface=" + mSurface);
-        if (mActivityContainer == null) {
-            Log.e(TAG, "Duplicate call to release");
+        final int width = mSurfaceView.getWidth();
+        final int height = mSurfaceView.getHeight();
+        final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
+        mVirtualDisplay = displayManager.createVirtualDisplay(
+                DISPLAY_NAME + "@" + System.identityHashCode(this),
+                width, height, getBaseDisplayDensity(), mSurface, 0 /* flags */);
+        if (mVirtualDisplay == null) {
+            Log.e(TAG, "Failed to initialize ActivityView");
             return;
         }
-        synchronized (mActivityContainerLock) {
-            mActivityContainer.release();
-            mActivityContainer = null;
+
+        mInputForwarder = InputManager.getInstance().createInputForwarder(
+                mVirtualDisplay.getDisplay().getDisplayId());
+    }
+
+    private void performRelease() {
+        if (!mOpened) {
+            return;
+        }
+
+        mSurfaceView.getHolder().removeCallback(mSurfaceCallback);
+
+        if (mInputForwarder != null) {
+            mInputForwarder = null;
+        }
+
+        final boolean displayReleased;
+        if (mVirtualDisplay != null) {
+            mVirtualDisplay.release();
+            mVirtualDisplay = null;
+            displayReleased = true;
+        } else {
+            displayReleased = false;
         }
 
         if (mSurface != null) {
@@ -286,232 +305,31 @@
             mSurface = null;
         }
 
-        mTextureView.setSurfaceTextureListener(null);
+        if (displayReleased && mActivityViewCallback != null) {
+            mActivityViewCallback.onActivityViewDestroyed(this);
+        }
+
+        mGuard.close();
+        mOpened = false;
     }
 
-    private void setSurfaceAsync(final Surface surface, final int width, final int height,
-            final int densityDpi, final boolean callback) {
-        mExecutor.execute(new Runnable() {
-            public void run() {
-                try {
-                    synchronized (mActivityContainerLock) {
-                        if (mActivityContainer != null) {
-                            mActivityContainer.setSurface(surface, width, height, densityDpi);
-                        }
-                    }
-                } catch (RemoteException e) {
-                    throw new RuntimeException(
-                        "ActivityView: Unable to set surface of ActivityContainer. ",
-                        e);
-                }
-                if (callback) {
-                    post(new Runnable() {
-                        @Override
-                        public void run() {
-                            if (mActivityViewCallback != null) {
-                                if (surface != null) {
-                                    mActivityViewCallback.onSurfaceAvailable(ActivityView.this);
-                                } else {
-                                    mActivityViewCallback.onSurfaceDestroyed(ActivityView.this);
-                                }
-                            }
-                        }
-                    });
-                }
-            }
-        });
+    /** Get density of the hosting display. */
+    private int getBaseDisplayDensity() {
+        final WindowManager wm = mContext.getSystemService(WindowManager.class);
+        final DisplayMetrics metrics = new DisplayMetrics();
+        wm.getDefaultDisplay().getMetrics(metrics);
+        return metrics.densityDpi;
     }
 
-    /**
-     * Set the callback to use to report certain state changes.
-     *
-     * Note: If the surface has been created prior to this call being made, then
-     * ActivityViewCallback.onSurfaceAvailable will be called from within setCallback.
-     *
-     *  @param callback The callback to report events to.
-     *
-     * @see ActivityViewCallback
-     */
-    public void setCallback(ActivityViewCallback callback) {
-        mActivityViewCallback = callback;
-
-        if (mSurface != null) {
-            mActivityViewCallback.onSurfaceAvailable(this);
-        }
-    }
-
-    public static abstract class ActivityViewCallback {
-        /**
-         * Called when all activities in the ActivityView have completed and been removed. Register
-         * using {@link ActivityView#setCallback(ActivityViewCallback)}. Each ActivityView may
-         * have at most one callback registered.
-         */
-        public abstract void onAllActivitiesComplete(ActivityView view);
-        /**
-         * Called when the surface is ready to be drawn to. Calling startActivity prior to this
-         * callback will result in an IllegalStateException.
-         */
-        public abstract void onSurfaceAvailable(ActivityView view);
-        /**
-         * Called when the surface has been removed. Calling startActivity after this callback
-         * will result in an IllegalStateException.
-         */
-        public abstract void onSurfaceDestroyed(ActivityView view);
-    }
-
-    private class ActivityViewSurfaceTextureListener implements SurfaceTextureListener {
-        @Override
-        public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width,
-                int height) {
-            if (mActivityContainer == null) {
-                return;
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            if (mGuard != null) {
+                mGuard.warnIfOpen();
+                performRelease();
             }
-            if (DEBUG) Log.d(TAG, "onSurfaceTextureAvailable: width=" + width + " height="
-                    + height);
-            mWidth = width;
-            mHeight = height;
-            mSurface = new Surface(surfaceTexture);
-            setSurfaceAsync(mSurface, mWidth, mHeight, mDensityDpi, true);
+        } finally {
+            super.finalize();
         }
-
-        @Override
-        public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width,
-                int height) {
-            if (mActivityContainer == null) {
-                return;
-            }
-            if (DEBUG) Log.d(TAG, "onSurfaceTextureSizeChanged: w=" + width + " h=" + height);
-        }
-
-        @Override
-        public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
-            if (mActivityContainer == null) {
-                return true;
-            }
-            if (DEBUG) Log.d(TAG, "onSurfaceTextureDestroyed");
-            mSurface.release();
-            mSurface = null;
-            setSurfaceAsync(null, mWidth, mHeight, mDensityDpi, true);
-            return true;
-        }
-
-        @Override
-        public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
-//            Log.d(TAG, "onSurfaceTextureUpdated");
-        }
-
-    }
-
-    private static class ActivityContainerCallback extends IActivityContainerCallback.Stub {
-        private final WeakReference<ActivityView> mActivityViewWeakReference;
-
-        ActivityContainerCallback(ActivityView activityView) {
-            mActivityViewWeakReference = new WeakReference<>(activityView);
-        }
-
-        @Override
-        public void setVisible(IBinder container, boolean visible) {
-            if (DEBUG) Log.v(TAG, "setVisible(): container=" + container + " visible=" + visible +
-                    " ActivityView=" + mActivityViewWeakReference.get());
-        }
-
-        @Override
-        public void onAllActivitiesComplete(IBinder container) {
-            final ActivityView activityView = mActivityViewWeakReference.get();
-            if (activityView != null) {
-                final ActivityViewCallback callback = activityView.mActivityViewCallback;
-                if (callback != null) {
-                    final WeakReference<ActivityViewCallback> callbackRef =
-                            new WeakReference<>(callback);
-                    activityView.post(new Runnable() {
-                        @Override
-                        public void run() {
-                            ActivityViewCallback callback = callbackRef.get();
-                            if (callback != null) {
-                                callback.onAllActivitiesComplete(activityView);
-                            }
-                        }
-                    });
-                }
-            }
-        }
-    }
-
-    private static class ActivityContainerWrapper {
-        private final IActivityContainer mIActivityContainer;
-        private final CloseGuard mGuard = CloseGuard.get();
-        boolean mOpened; // Protected by mGuard.
-
-        ActivityContainerWrapper(IActivityContainer container) {
-            mIActivityContainer = container;
-            mOpened = true;
-            mGuard.open("release");
-        }
-
-        void setSurface(Surface surface, int width, int height, int density)
-                throws RemoteException {
-            mIActivityContainer.setSurface(surface, width, height, density);
-        }
-
-        int startActivity(Intent intent) {
-            try {
-                return mIActivityContainer.startActivity(intent);
-            } catch (RemoteException e) {
-                throw new RuntimeException("ActivityView: Unable to startActivity. " + e);
-            }
-        }
-
-        int startActivityIntentSender(IIntentSender intentSender) {
-            try {
-                return mIActivityContainer.startActivityIntentSender(intentSender);
-            } catch (RemoteException e) {
-                throw new RuntimeException(
-                        "ActivityView: Unable to startActivity from IntentSender. " + e);
-            }
-        }
-
-        int getDisplayId() {
-            try {
-                return mIActivityContainer.getDisplayId();
-            } catch (RemoteException e) {
-                return -1;
-            }
-        }
-
-        boolean injectEvent(InputEvent event) {
-            try {
-                return mIActivityContainer.injectEvent(event);
-            } catch (RemoteException e) {
-                return false;
-            }
-        }
-
-        void release() {
-            synchronized (mGuard) {
-                if (mOpened) {
-                    if (DEBUG) Log.v(TAG, "ActivityContainerWrapper: release called");
-                    try {
-                        mIActivityContainer.release();
-                        mGuard.close();
-                    } catch (RemoteException e) {
-                    }
-                    mOpened = false;
-                }
-            }
-        }
-
-        @Override
-        protected void finalize() throws Throwable {
-            if (DEBUG) Log.v(TAG, "ActivityContainerWrapper: finalize called");
-            try {
-                if (mGuard != null) {
-                    mGuard.warnIfOpen();
-                    release();
-                }
-            } finally {
-                super.finalize();
-            }
-        }
-
     }
 }
diff --git a/core/java/android/app/Fragment.java b/core/java/android/app/Fragment.java
index 66dc6a1..9377345 100644
--- a/core/java/android/app/Fragment.java
+++ b/core/java/android/app/Fragment.java
@@ -42,7 +42,6 @@
 import android.util.ArrayMap;
 import android.util.AttributeSet;
 import android.util.DebugUtils;
-import android.util.Log;
 import android.util.SparseArray;
 import android.util.SuperNotCalledException;
 import android.view.ContextMenu;
@@ -406,6 +405,11 @@
     // getLayoutInflater()
     LayoutInflater mLayoutInflater;
 
+    // Keep track of whether or not this Fragment has run performCreate(). Retained instance
+    // fragments can have mRetaining set to true without going through creation, so we must
+    // track it separately.
+    boolean mIsCreated;
+
     /**
      * State information that has been retrieved from a fragment instance
      * through {@link FragmentManager#saveFragmentInstanceState(Fragment)
@@ -2483,6 +2487,7 @@
         mState = CREATED;
         mCalled = false;
         onCreate(savedInstanceState);
+        mIsCreated = true;
         if (!mCalled) {
             throw new SuperNotCalledException("Fragment " + this
                     + " did not call through to super.onCreate()");
@@ -2759,6 +2764,7 @@
         }
         mState = INITIALIZING;
         mCalled = false;
+        mIsCreated = false;
         onDestroy();
         if (!mCalled) {
             throw new SuperNotCalledException("Fragment " + this
diff --git a/core/java/android/app/FragmentManager.java b/core/java/android/app/FragmentManager.java
index 7b6b4b4..ba5ea21 100644
--- a/core/java/android/app/FragmentManager.java
+++ b/core/java/android/app/FragmentManager.java
@@ -1232,7 +1232,7 @@
                         }
                         dispatchOnFragmentAttached(f, mHost.getContext(), false);
 
-                        if (!f.mRetaining) {
+                        if (!f.mIsCreated) {
                             dispatchOnFragmentPreCreated(f, f.mSavedFragmentState, false);
                             f.performCreate(f.mSavedFragmentState);
                             dispatchOnFragmentCreated(f, f.mSavedFragmentState, false);
diff --git a/core/java/android/app/IActivityContainer.aidl b/core/java/android/app/IActivityContainer.aidl
deleted file mode 100644
index 1ff3c87..0000000
--- a/core/java/android/app/IActivityContainer.aidl
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Copyright (c) 2013, 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.app.IActivityContainerCallback;
-import android.content.Intent;
-import android.content.IIntentSender;
-import android.os.IBinder;
-import android.view.InputEvent;
-import android.view.Surface;
-
-/** @hide */
-interface IActivityContainer {
-    void addToDisplay(int displayId);
-    void setSurface(in Surface surface, int width, int height, int density);
-    int startActivity(in Intent intent);
-    int startActivityIntentSender(in IIntentSender intentSender);
-    int getDisplayId();
-    int getStackId();
-    boolean injectEvent(in InputEvent event);
-    void release();
-}
diff --git a/core/java/android/app/IActivityManager.aidl b/core/java/android/app/IActivityManager.aidl
index df1a412..fa9d7ca 100644
--- a/core/java/android/app/IActivityManager.aidl
+++ b/core/java/android/app/IActivityManager.aidl
@@ -20,8 +20,6 @@
 import android.app.ApplicationErrorReport;
 import android.app.ContentProviderHolder;
 import android.app.IApplicationThread;
-import android.app.IActivityContainer;
-import android.app.IActivityContainerCallback;
 import android.app.IActivityController;
 import android.app.IAppTask;
 import android.app.IInstrumentationWatcher;
@@ -355,8 +353,6 @@
     void killUid(int appId, int userId, in String reason);
     void setUserIsMonkey(boolean monkey);
     void hang(in IBinder who, boolean allowRestart);
-    IActivityContainer createVirtualActivityContainer(in IBinder parentActivityToken,
-            in IActivityContainerCallback callback);
     void moveTaskToStack(int taskId, int stackId, boolean toTop);
     /**
      * Resizes the input stack id to the given bounds.
@@ -436,7 +432,7 @@
 
     // Start of M transactions
     void notifyCleartextNetwork(int uid, in byte[] firstPacket);
-    IActivityContainer createStackOnDisplay(int displayId);
+    int createStackOnDisplay(int displayId);
     int getFocusedStackId();
     void setTaskResizeable(int taskId, int resizeableMode);
     boolean requestAssistContextExtras(int requestType, in IResultReceiver receiver,
diff --git a/core/java/android/app/IActivityContainerCallback.aidl b/core/java/android/app/IInputForwarder.aidl
similarity index 60%
rename from core/java/android/app/IActivityContainerCallback.aidl
rename to core/java/android/app/IInputForwarder.aidl
index 99d0a6f..d6be63e 100644
--- a/core/java/android/app/IActivityContainerCallback.aidl
+++ b/core/java/android/app/IInputForwarder.aidl
@@ -1,5 +1,5 @@
 /**
- * Copyright (c) 2013, The Android Open Source Project
+ * Copyright (c) 2017, The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -16,10 +16,14 @@
 
 package android.app;
 
-import android.os.IBinder;
+import android.view.InputEvent;
 
-/** @hide */
-interface IActivityContainerCallback {
-    oneway void setVisible(IBinder container, boolean visible);
-    oneway void onAllActivitiesComplete(IBinder container);
-}
+/**
+ * Forwards input events into owned activity container, used in {@link android.app.ActivityView}.
+ * To forward input to other apps {@link android.Manifest.permission.INJECT_EVENTS} permission is
+ * required.
+ * @hide
+ */
+interface IInputForwarder {
+    boolean forwardEvent(in InputEvent event);
+}
\ No newline at end of file
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index a3377d7..f4277ce 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -1092,6 +1092,11 @@
     public static final String EXTRA_CONTAINS_CUSTOM_VIEW = "android.contains.customView";
 
     /**
+     * @hide
+     */
+    public static final String EXTRA_REDUCED_IMAGES = "android.reduced.images";
+
+    /**
      * {@link #extras} key: the audio contents of this notification.
      *
      * This is for use when rendering the notification on an audio-focused interface;
@@ -4956,8 +4961,12 @@
             buildUnstyled();
 
             if (mStyle != null) {
+                mStyle.reduceImageSizes(mContext);
+                mStyle.purgeResources();
                 mStyle.buildStyled(mN);
             }
+            mN.reduceImageSizes(mContext);
+
             if (mContext.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N
                     && (useExistingRemoteView())) {
                 if (mN.contentView == null) {
@@ -5159,6 +5168,52 @@
     }
 
     /**
+     * Reduces the image sizes to conform to a maximum allowed size. This also processes all custom
+     * remote views.
+     *
+     * @hide
+     */
+    void reduceImageSizes(Context context) {
+        if (extras.getBoolean(EXTRA_REDUCED_IMAGES)) {
+            return;
+        }
+        if (mLargeIcon != null || largeIcon != null) {
+            Resources resources = context.getResources();
+            Class<? extends Style> style = getNotificationStyle();
+            int maxWidth = resources.getDimensionPixelSize(R.dimen.notification_right_icon_size);
+            int maxHeight = maxWidth;
+            if (MediaStyle.class.equals(style)
+                    || DecoratedMediaCustomViewStyle.class.equals(style)) {
+                maxHeight = resources.getDimensionPixelSize(
+                        R.dimen.notification_media_image_max_height);
+                maxWidth = resources.getDimensionPixelSize(
+                        R.dimen.notification_media_image_max_width);
+            }
+            if (mLargeIcon != null) {
+                mLargeIcon.scaleDownIfNecessary(maxWidth, maxHeight);
+            }
+            if (largeIcon != null) {
+                largeIcon = Icon.scaleDownIfNecessary(largeIcon, maxWidth, maxHeight);
+            }
+        }
+        reduceImageSizesForRemoteView(contentView, context);
+        reduceImageSizesForRemoteView(headsUpContentView, context);
+        reduceImageSizesForRemoteView(bigContentView, context);
+        extras.putBoolean(EXTRA_REDUCED_IMAGES, true);
+    }
+
+    private void reduceImageSizesForRemoteView(RemoteViews remoteView, Context context) {
+        if (remoteView != null) {
+            Resources resources = context.getResources();
+            int maxWidth = resources.getDimensionPixelSize(
+                    R.dimen.notification_custom_view_max_image_width);
+            int maxHeight = resources.getDimensionPixelSize(
+                    R.dimen.notification_custom_view_max_image_height);
+            remoteView.reduceImageSizes(maxWidth, maxHeight);
+        }
+    }
+
+    /**
      * @return whether this notification is a foreground service notification
      */
     private boolean isForegroundService() {
@@ -5459,6 +5514,14 @@
         public boolean displayCustomViewInline() {
             return false;
         }
+
+        /**
+         * Reduces the image sizes contained in this style.
+         *
+         * @hide
+         */
+        public void reduceImageSizes(Context context) {
+        }
     }
 
     /**
@@ -5557,6 +5620,27 @@
         /**
          * @hide
          */
+        @Override
+        public void reduceImageSizes(Context context) {
+            super.reduceImageSizes(context);
+            Resources resources = context.getResources();
+            if (mPicture != null) {
+                int maxPictureWidth = resources.getDimensionPixelSize(
+                        R.dimen.notification_big_picture_max_height);
+                int maxPictureHeight = resources.getDimensionPixelSize(
+                        R.dimen.notification_big_picture_max_width);
+                mPicture = Icon.scaleDownIfNecessary(mPicture, maxPictureWidth, maxPictureHeight);
+            }
+            if (mBigLargeIcon != null) {
+                int rightIconSize = resources.getDimensionPixelSize(
+                        R.dimen.notification_right_icon_size);
+                mBigLargeIcon.scaleDownIfNecessary(rightIconSize, rightIconSize);
+            }
+        }
+
+        /**
+         * @hide
+         */
         public RemoteViews makeBigContentView() {
             // Replace mN.mLargeIcon with mBigLargeIcon if mBigLargeIconSet
             // This covers the following cases:
diff --git a/core/java/android/app/NotificationManager.java b/core/java/android/app/NotificationManager.java
index 26889a1..0f0c4ba 100644
--- a/core/java/android/app/NotificationManager.java
+++ b/core/java/android/app/NotificationManager.java
@@ -307,6 +307,7 @@
             }
         }
         if (localLOGV) Log.v(TAG, pkg + ": notify(" + id + ", " + notification + ")");
+        notification.reduceImageSizes(mContext);
         ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
         boolean isLowRam = am.isLowRamDevice();
         final Notification copy = Builder.maybeCloneStrippedForDelivery(notification, isLowRam);
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index afb798c..9b795aa 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -508,21 +508,13 @@
              in boolean isSharedModule, IDexModuleRegisterCallback callback);
 
     /**
-     * Ask the package manager to perform a dex-opt for the given reason. The package
-     * manager will map the reason to a compiler filter according to the current system
-     * configuration.
-     */
-    boolean performDexOpt(String packageName, boolean checkProfiles,
-            int compileReason, boolean force, boolean bootComplete, boolean downgrade);
-
-    /**
      * Ask the package manager to perform a dex-opt with the given compiler filter.
      *
      * Note: exposed only for the shell command to allow moving packages explicitly to a
      *       definite state.
      */
     boolean performDexOptMode(String packageName, boolean checkProfiles,
-            String targetCompilerFilter, boolean force, boolean bootComplete);
+            String targetCompilerFilter, boolean force, boolean bootComplete, String splitName);
 
     /**
      * Ask the package manager to perform a dex-opt with the given compiler filter on the
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index c76ca6d..640eee6 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -3145,6 +3145,8 @@
         perm.info.descriptionRes = sa.getResourceId(
                 com.android.internal.R.styleable.AndroidManifestPermissionGroup_description,
                 0);
+        perm.info.requestRes = sa.getResourceId(
+                com.android.internal.R.styleable.AndroidManifestPermissionGroup_request, 0);
         perm.info.flags = sa.getInt(
                 com.android.internal.R.styleable.AndroidManifestPermissionGroup_permissionGroupFlags, 0);
         perm.info.priority = sa.getInt(
@@ -3199,6 +3201,9 @@
                 com.android.internal.R.styleable.AndroidManifestPermission_description,
                 0);
 
+        perm.info.requestRes = sa.getResourceId(
+                com.android.internal.R.styleable.AndroidManifestPermission_request, 0);
+
         perm.info.protectionLevel = sa.getInt(
                 com.android.internal.R.styleable.AndroidManifestPermission_protectionLevel,
                 PermissionInfo.PROTECTION_NORMAL);
@@ -3273,6 +3278,7 @@
         }
 
         perm.info.descriptionRes = 0;
+        perm.info.requestRes = 0;
         perm.info.protectionLevel = PermissionInfo.PROTECTION_NORMAL;
         perm.tree = true;
 
diff --git a/core/java/android/content/pm/PermissionGroupInfo.java b/core/java/android/content/pm/PermissionGroupInfo.java
index 452bf0d..7c4478d 100644
--- a/core/java/android/content/pm/PermissionGroupInfo.java
+++ b/core/java/android/content/pm/PermissionGroupInfo.java
@@ -16,6 +16,8 @@
 
 package android.content.pm;
 
+import android.annotation.StringRes;
+import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.text.TextUtils;
@@ -34,6 +36,15 @@
     public int descriptionRes;
 
     /**
+     * A string resource identifier (in the package's resources) used to request the permissions.
+     * From the "request" attribute or, if not set, 0.
+     *
+     * @hide
+     */
+    @SystemApi
+    public @StringRes int requestRes;
+
+    /**
      * The description string provided in the AndroidManifest file, if any.  You
      * probably don't want to use this, since it will be null if the description
      * is in a resource.  You probably want
@@ -64,6 +75,7 @@
     public PermissionGroupInfo(PermissionGroupInfo orig) {
         super(orig);
         descriptionRes = orig.descriptionRes;
+        requestRes = orig.requestRes;
         nonLocalizedDescription = orig.nonLocalizedDescription;
         flags = orig.flags;
         priority = orig.priority;
@@ -106,6 +118,7 @@
     public void writeToParcel(Parcel dest, int parcelableFlags) {
         super.writeToParcel(dest, parcelableFlags);
         dest.writeInt(descriptionRes);
+        dest.writeInt(requestRes);
         TextUtils.writeToParcel(nonLocalizedDescription, dest, parcelableFlags);
         dest.writeInt(flags);
         dest.writeInt(priority);
@@ -124,6 +137,7 @@
     private PermissionGroupInfo(Parcel source) {
         super(source);
         descriptionRes = source.readInt();
+        requestRes = source.readInt();
         nonLocalizedDescription = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
         flags = source.readInt();
         priority = source.readInt();
diff --git a/core/java/android/content/pm/PermissionInfo.java b/core/java/android/content/pm/PermissionInfo.java
index 694e607..71a6321 100644
--- a/core/java/android/content/pm/PermissionInfo.java
+++ b/core/java/android/content/pm/PermissionInfo.java
@@ -198,6 +198,15 @@
     public int descriptionRes;
 
     /**
+     * A string resource identifier (in the package's resources) used to request the permissions.
+     * From the "request" attribute or, if not set, 0.
+     *
+     * @hide
+     */
+    @SystemApi
+    public int requestRes;
+
+    /**
      * The description string provided in the AndroidManifest file, if any.  You
      * probably don't want to use this, since it will be null if the description
      * is in a resource.  You probably want
@@ -272,6 +281,7 @@
         flags = orig.flags;
         group = orig.group;
         descriptionRes = orig.descriptionRes;
+        requestRes = orig.requestRes;
         nonLocalizedDescription = orig.nonLocalizedDescription;
     }
 
@@ -315,6 +325,7 @@
         dest.writeInt(flags);
         dest.writeString(group);
         dest.writeInt(descriptionRes);
+        dest.writeInt(requestRes);
         TextUtils.writeToParcel(nonLocalizedDescription, dest, parcelableFlags);
     }
 
@@ -334,6 +345,7 @@
         flags = source.readInt();
         group = source.readString();
         descriptionRes = source.readInt();
+        requestRes = source.readInt();
         nonLocalizedDescription = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
     }
 }
diff --git a/core/java/android/hardware/fingerprint/FingerprintManager.java b/core/java/android/hardware/fingerprint/FingerprintManager.java
index 5030865..a5bf639 100644
--- a/core/java/android/hardware/fingerprint/FingerprintManager.java
+++ b/core/java/android/hardware/fingerprint/FingerprintManager.java
@@ -110,6 +110,10 @@
     /**
      * Hardware vendors may extend this list if there are conditions that do not fall under one of
      * the above categories. Vendors are responsible for providing error strings for these errors.
+     * These messages are typically reserved for internal operations such as enrollment, but may be
+     * used to express vendor errors not covered by the ones in fingerprint.h. Applications are
+     * expected to show the error message string if they happen, but are advised not to rely on the
+     * message id since they will be device and vendor-specific
      */
     public static final int FINGERPRINT_ERROR_VENDOR = 8;
 
diff --git a/core/java/android/hardware/input/IInputManager.aidl b/core/java/android/hardware/input/IInputManager.aidl
index 4586316..9e0c680 100644
--- a/core/java/android/hardware/input/IInputManager.aidl
+++ b/core/java/android/hardware/input/IInputManager.aidl
@@ -16,6 +16,7 @@
 
 package android.hardware.input;
 
+import android.app.IInputForwarder;
 import android.hardware.input.InputDeviceIdentifier;
 import android.hardware.input.KeyboardLayout;
 import android.hardware.input.IInputDevicesChangedListener;
@@ -88,4 +89,7 @@
     void setCustomPointerIcon(in PointerIcon icon);
 
     void requestPointerCapture(IBinder windowToken, boolean enabled);
+
+    /** Create input forwarder to deliver touch events to owned display. */
+    IInputForwarder createInputForwarder(int displayId);
 }
diff --git a/core/java/android/hardware/input/InputManager.java b/core/java/android/hardware/input/InputManager.java
index 4898c1a..c531a89 100644
--- a/core/java/android/hardware/input/InputManager.java
+++ b/core/java/android/hardware/input/InputManager.java
@@ -19,8 +19,9 @@
 import android.annotation.IntDef;
 import android.annotation.Nullable;
 import android.annotation.SdkConstant;
-import android.annotation.SystemService;
 import android.annotation.SdkConstant.SdkConstantType;
+import android.annotation.SystemService;
+import android.app.IInputForwarder;
 import android.content.Context;
 import android.media.AudioAttributes;
 import android.os.Binder;
@@ -971,6 +972,25 @@
         }
     }
 
+
+    /**
+     * Create an {@link IInputForwarder} targeted to provided display.
+     * {@link android.Manifest.permission.INJECT_EVENTS} permission is required to call this method.
+     *
+     * @param displayId Id of the target display where input events should be forwarded.
+     *                  Display must exist and must be owned by the caller.
+     * @return The forwarder instance.
+     *
+     * @hide
+     */
+    public IInputForwarder createInputForwarder(int displayId) {
+        try {
+            return mIm.createInputForwarder(displayId);
+        } catch (RemoteException ex) {
+            throw ex.rethrowFromSystemServer();
+        }
+    }
+
     private void populateInputDevicesLocked() {
         if (mInputDevicesChangedListener == null) {
             final InputDevicesChangedListener listener = new InputDevicesChangedListener();
diff --git a/core/java/android/hardware/radio/ITuner.aidl b/core/java/android/hardware/radio/ITuner.aidl
index 2dc6601..7f470ef 100644
--- a/core/java/android/hardware/radio/ITuner.aidl
+++ b/core/java/android/hardware/radio/ITuner.aidl
@@ -16,6 +16,7 @@
 
 package android.hardware.radio;
 
+import android.graphics.Bitmap;
 import android.hardware.radio.ProgramSelector;
 import android.hardware.radio.RadioManager;
 
@@ -64,6 +65,8 @@
 
     RadioManager.ProgramInfo getProgramInformation();
 
+    Bitmap getImage(int id);
+
     /**
      * @returns {@code true} if the scan was properly scheduled,
      *          {@code false} if the scan feature is unavailable
diff --git a/core/java/android/hardware/radio/RadioManager.java b/core/java/android/hardware/radio/RadioManager.java
index 6a59be0..d5b72aa 100644
--- a/core/java/android/hardware/radio/RadioManager.java
+++ b/core/java/android/hardware/radio/RadioManager.java
@@ -47,7 +47,7 @@
 @SystemApi
 @SystemService(Context.RADIO_SERVICE)
 public class RadioManager {
-    private static final String TAG = "RadioManager";
+    private static final String TAG = "BroadcastRadio.manager";
 
     /** Method return status: successful operation */
     public static final int STATUS_OK = 0;
@@ -136,14 +136,14 @@
         private final boolean mIsBgScanSupported;
         private final Set<Integer> mSupportedProgramTypes;
         private final Set<Integer> mSupportedIdentifierTypes;
-        private final String mVendorExension;
+        private final String mVendorInfo;
 
         ModuleProperties(int id, String serviceName, int classId, String implementor,
                 String product, String version, String serial, int numTuners, int numAudioSources,
                 boolean isCaptureSupported, BandDescriptor[] bands, boolean isBgScanSupported,
                 @ProgramSelector.ProgramType int[] supportedProgramTypes,
                 @ProgramSelector.IdentifierType int[] supportedIdentifierTypes,
-                String vendorExension) {
+                String vendorInfo) {
             mId = id;
             mServiceName = TextUtils.isEmpty(serviceName) ? "default" : serviceName;
             mClassId = classId;
@@ -158,7 +158,7 @@
             mIsBgScanSupported = isBgScanSupported;
             mSupportedProgramTypes = arrayToSet(supportedProgramTypes);
             mSupportedIdentifierTypes = arrayToSet(supportedIdentifierTypes);
-            mVendorExension = vendorExension;
+            mVendorInfo = vendorInfo;
         }
 
         private static Set<Integer> arrayToSet(int[] arr) {
@@ -294,8 +294,8 @@
          * Client application MUST verify vendor/product name from the
          * ModuleProperties class before doing any interpretation of this value.
          */
-        public @NonNull String getVendorExension() {
-            return mVendorExension == null ? "" : mVendorExension;
+        public @NonNull String getVendorInfo() {
+            return mVendorInfo == null ? "" : mVendorInfo;
         }
 
         /** List of descriptors for all bands supported by this module.
@@ -325,7 +325,7 @@
             mIsBgScanSupported = in.readInt() == 1;
             mSupportedProgramTypes = arrayToSet(in.createIntArray());
             mSupportedIdentifierTypes = arrayToSet(in.createIntArray());
-            mVendorExension = in.readString();
+            mVendorInfo = in.readString();
         }
 
         public static final Parcelable.Creator<ModuleProperties> CREATOR
@@ -355,7 +355,7 @@
             dest.writeInt(mIsBgScanSupported ? 1 : 0);
             dest.writeIntArray(setToArray(mSupportedProgramTypes));
             dest.writeIntArray(setToArray(mSupportedIdentifierTypes));
-            dest.writeString(mVendorExension);
+            dest.writeString(mVendorInfo);
         }
 
         @Override
@@ -392,7 +392,7 @@
             result = prime * result + (mIsCaptureSupported ? 1 : 0);
             result = prime * result + Arrays.hashCode(mBands);
             result = prime * result + (mIsBgScanSupported ? 1 : 0);
-            result = prime * result + ((mVendorExension == null) ? 0 : mVendorExension.hashCode());
+            result = prime * result + ((mVendorInfo == null) ? 0 : mVendorInfo.hashCode());
             return result;
         }
 
@@ -438,8 +438,7 @@
                 return false;
             if (mIsBgScanSupported != other.isBackgroundScanningSupported())
                 return false;
-            if (!TextUtils.equals(mVendorExension, other.mVendorExension))
-                return false;
+            if (!TextUtils.equals(mVendorInfo, other.mVendorInfo)) return false;
             return true;
         }
     }
@@ -1323,11 +1322,11 @@
         private final int mFlags;
         private final int mSignalStrength;
         private final RadioMetadata mMetadata;
-        private final String mVendorExension;
+        private final String mVendorInfo;
 
         ProgramInfo(@NonNull ProgramSelector selector, boolean tuned, boolean stereo,
                 boolean digital, int signalStrength, RadioMetadata metadata, int flags,
-                String vendorExension) {
+                String vendorInfo) {
             mSelector = selector;
             mTuned = tuned;
             mStereo = stereo;
@@ -1335,7 +1334,7 @@
             mFlags = flags;
             mSignalStrength = signalStrength;
             mMetadata = metadata;
-            mVendorExension = vendorExension;
+            mVendorInfo = vendorInfo;
         }
 
         /**
@@ -1455,8 +1454,8 @@
          * Client application MUST verify vendor/product name from the
          * ModuleProperties class before doing any interpretation of this value.
          */
-        public @NonNull String getVendorExension() {
-            return mVendorExension == null ? "" : mVendorExension;
+        public @NonNull String getVendorInfo() {
+            return mVendorInfo == null ? "" : mVendorInfo;
         }
 
         private ProgramInfo(Parcel in) {
@@ -1471,7 +1470,7 @@
                 mMetadata = null;
             }
             mFlags = in.readInt();
-            mVendorExension = in.readString();
+            mVendorInfo = in.readString();
         }
 
         public static final Parcelable.Creator<ProgramInfo> CREATOR
@@ -1499,7 +1498,7 @@
                 mMetadata.writeToParcel(dest, flags);
             }
             dest.writeInt(mFlags);
-            dest.writeString(mVendorExension);
+            dest.writeString(mVendorInfo);
         }
 
         @Override
@@ -1527,7 +1526,7 @@
             result = prime * result + mFlags;
             result = prime * result + mSignalStrength;
             result = prime * result + ((mMetadata == null) ? 0 : mMetadata.hashCode());
-            result = prime * result + ((mVendorExension == null) ? 0 : mVendorExension.hashCode());
+            result = prime * result + ((mVendorInfo == null) ? 0 : mVendorInfo.hashCode());
             return result;
         }
 
@@ -1554,8 +1553,7 @@
                     return false;
             } else if (!mMetadata.equals(other.getMetadata()))
                 return false;
-            if (!TextUtils.equals(mVendorExension, other.mVendorExension))
-                return false;
+            if (!TextUtils.equals(mVendorInfo, other.mVendorInfo)) return false;
             return true;
         }
     }
diff --git a/core/java/android/hardware/radio/RadioMetadata.java b/core/java/android/hardware/radio/RadioMetadata.java
index d11e8b0..3cc4b56 100644
--- a/core/java/android/hardware/radio/RadioMetadata.java
+++ b/core/java/android/hardware/radio/RadioMetadata.java
@@ -15,6 +15,7 @@
  */
 package android.hardware.radio;
 
+import android.annotation.NonNull;
 import android.annotation.SystemApi;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
@@ -33,7 +34,7 @@
  */
 @SystemApi
 public final class RadioMetadata implements Parcelable {
-    private static final String TAG = "RadioMetadata";
+    private static final String TAG = "BroadcastRadio.metadata";
 
     /**
      * The RDS Program Information.
@@ -240,6 +241,14 @@
         return mBundle.getString(key);
     }
 
+    private static void putInt(Bundle bundle, String key, int value) {
+        int type = METADATA_KEYS_TYPE.getOrDefault(key, METADATA_TYPE_INVALID);
+        if (type != METADATA_TYPE_INT && type != METADATA_TYPE_BITMAP) {
+            throw new IllegalArgumentException("The " + key + " key cannot be used to put an int");
+        }
+        bundle.putInt(key, value);
+    }
+
     /**
      * Returns the value associated with the given key,
      * or 0 if the key is not found in the meta data.
@@ -256,7 +265,9 @@
      *
      * @param key The key the value is stored under
      * @return a {@link Bitmap} or null
+     * @deprecated Use getBitmapId(String) instead
      */
+    @Deprecated
     public Bitmap getBitmap(String key) {
         Bitmap bmp = null;
         try {
@@ -268,6 +279,30 @@
         return bmp;
     }
 
+    /**
+     * Retrieves an identifier for a bitmap.
+     *
+     * The format of an identifier is opaque to the application,
+     * with a special case of value 0 being invalid.
+     * An identifier for a given image-tuner pair is unique, so an application
+     * may cache images and determine if there is a necessity to fetch them
+     * again - if identifier changes, it means the image has changed.
+     *
+     * Only bitmap keys may be used with this method:
+     * <ul>
+     * <li>{@link #METADATA_KEY_ICON}</li>
+     * <li>{@link #METADATA_KEY_ART}</li>
+     * </ul>
+     *
+     * @param key The key the value is stored under.
+     * @return a bitmap identifier or 0 if it's missing.
+     * @hide This API is not thoroughly elaborated yet
+     */
+    public int getBitmapId(@NonNull String key) {
+        if (!METADATA_KEY_ICON.equals(key) && !METADATA_KEY_ART.equals(key)) return 0;
+        return getInt(key);
+    }
+
     public Clock getClock(String key) {
         Clock clock = null;
         try {
@@ -416,18 +451,14 @@
          * <li>{@link #METADATA_KEY_RDS_PTY}</li>
          * <li>{@link #METADATA_KEY_RBDS_PTY}</li>
          * </ul>
+         * or any bitmap represented by its identifier.
          *
          * @param key The key for referencing this value
          * @param value The int value to store
          * @return the same Builder instance
          */
         public Builder putInt(String key, int value) {
-            if (!METADATA_KEYS_TYPE.containsKey(key) ||
-                    METADATA_KEYS_TYPE.get(key) != METADATA_TYPE_INT) {
-                throw new IllegalArgumentException("The " + key
-                        + " key cannot be used to put a long");
-            }
-            mBundle.putInt(key, value);
+            RadioMetadata.putInt(mBundle, key, value);
             return this;
         }
 
@@ -498,12 +529,12 @@
 
     int putIntFromNative(int nativeKey, int value) {
         String key = getKeyFromNativeKey(nativeKey);
-        if (!METADATA_KEYS_TYPE.containsKey(key) ||
-                METADATA_KEYS_TYPE.get(key) != METADATA_TYPE_INT) {
+        try {
+            putInt(mBundle, key, value);
+            return 0;
+        } catch (IllegalArgumentException ex) {
             return -1;
         }
-        mBundle.putInt(key, value);
-        return 0;
     }
 
     int putStringFromNative(int nativeKey, String value) {
diff --git a/core/java/android/hardware/radio/RadioTuner.java b/core/java/android/hardware/radio/RadioTuner.java
index 6637ed2..be37cd0 100644
--- a/core/java/android/hardware/radio/RadioTuner.java
+++ b/core/java/android/hardware/radio/RadioTuner.java
@@ -19,6 +19,7 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.SystemApi;
+import android.graphics.Bitmap;
 import android.os.Handler;
 
 import java.util.List;
@@ -230,6 +231,27 @@
     public abstract int getProgramInformation(RadioManager.ProgramInfo[] info);
 
     /**
+     * Retrieves a {@link Bitmap} for the given image ID or null,
+     * if the image was missing from the tuner.
+     *
+     * This involves doing a call to the tuner, so the bitmap should be cached
+     * on the application side.
+     *
+     * If the method returns null for non-zero ID, it means the image was
+     * updated on the tuner side. There is a race conditon between fetching
+     * image for an old ID and tuner updating the image (and cleaning up the
+     * old image). In such case, a new ProgramInfo with updated image id will
+     * be sent with a {@link onProgramInfoChanged} callback.
+     *
+     * @param id The image identifier, retrieved with
+     *           {@link RadioMetadata#getBitmapId(String)}.
+     * @return A {@link Bitmap} or null.
+     * @throws IllegalArgumentException if id==0
+     * @hide This API is not thoroughly elaborated yet
+     */
+    public abstract @Nullable Bitmap getMetadataImage(int id);
+
+    /**
      * Initiates a background scan to update internally cached program list.
      *
      * It may not be necessary to initiate the scan explicitly - the scan MAY be performed on boot.
diff --git a/core/java/android/hardware/radio/TunerAdapter.java b/core/java/android/hardware/radio/TunerAdapter.java
index 3bc0ac3..c687537 100644
--- a/core/java/android/hardware/radio/TunerAdapter.java
+++ b/core/java/android/hardware/radio/TunerAdapter.java
@@ -18,6 +18,7 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.graphics.Bitmap;
 import android.os.RemoteException;
 import android.util.Log;
 
@@ -27,7 +28,7 @@
  * Implements the RadioTuner interface by forwarding calls to radio service.
  */
 class TunerAdapter extends RadioTuner {
-    private static final String TAG = "radio.TunerAdapter";
+    private static final String TAG = "BroadcastRadio.TunerAdapter";
 
     @NonNull private final ITuner mTuner;
     private boolean mIsClosed = false;
@@ -203,6 +204,15 @@
     }
 
     @Override
+    public @Nullable Bitmap getMetadataImage(int id) {
+        try {
+            return mTuner.getImage(id);
+        } catch (RemoteException e) {
+            throw new RuntimeException("service died", e);
+        }
+    }
+
+    @Override
     public boolean startBackgroundScan() {
         try {
             return mTuner.startBackgroundScan();
diff --git a/core/java/android/hardware/radio/TunerCallbackAdapter.java b/core/java/android/hardware/radio/TunerCallbackAdapter.java
index 8c3826c..00a36c8 100644
--- a/core/java/android/hardware/radio/TunerCallbackAdapter.java
+++ b/core/java/android/hardware/radio/TunerCallbackAdapter.java
@@ -27,7 +27,7 @@
  * Implements the ITunerCallback interface by forwarding calls to RadioTuner.Callback.
  */
 class TunerCallbackAdapter extends ITunerCallback.Stub {
-    private static final String TAG = "radio.TunerCallbackAdapter";
+    private static final String TAG = "BroadcastRadio.TunerCallbackAdapter";
 
     @NonNull private final RadioTuner.Callback mCallback;
     @NonNull private final Handler mHandler;
diff --git a/core/java/android/net/IpSecTransform.java b/core/java/android/net/IpSecTransform.java
index e65f534..8e3a612 100644
--- a/core/java/android/net/IpSecTransform.java
+++ b/core/java/android/net/IpSecTransform.java
@@ -26,6 +26,7 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.util.Log;
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.Preconditions;
 import dalvik.system.CloseGuard;
 import java.io.IOException;
@@ -487,5 +488,14 @@
             mContext = context;
             mConfig = new IpSecConfig();
         }
+
+        /**
+         * Return an {@link IpSecConfig} object for testing purposes.
+         * @hide
+         */
+        @VisibleForTesting
+        public IpSecConfig getIpSecConfig() {
+            return mConfig;
+        }
     }
 }
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index 41f090a..0e26ca2 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -5665,8 +5665,10 @@
                         pw.print(',');
                         if (rec.stepDetails.statPlatformIdleState != null) {
                             pw.print(rec.stepDetails.statPlatformIdleState);
+                            if (rec.stepDetails.statSubsystemPowerState != null) {
+                                pw.print(',');
+                            }
                         }
-                        pw.println();
 
                         if (rec.stepDetails.statSubsystemPowerState != null) {
                             pw.print(rec.stepDetails.statSubsystemPowerState);
diff --git a/core/java/android/os/Build.java b/core/java/android/os/Build.java
index a2fb9db..0541a53 100644
--- a/core/java/android/os/Build.java
+++ b/core/java/android/os/Build.java
@@ -759,6 +759,11 @@
          * O.
          */
         public static final int O = 26;
+
+        /**
+         * O MR1.
+         */
+        public static final int O_MR1 = CUR_DEVELOPMENT; // STOPSHIP Replace with the real version.
     }
 
     /** The type of build, like "user" or "eng". */
diff --git a/core/java/android/os/RecoverySystem.java b/core/java/android/os/RecoverySystem.java
index 7fa1c5a..673a8ba 100644
--- a/core/java/android/os/RecoverySystem.java
+++ b/core/java/android/os/RecoverySystem.java
@@ -24,11 +24,11 @@
 import android.annotation.SystemService;
 import android.app.PendingIntent;
 import android.content.BroadcastReceiver;
+import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.pm.PackageManager;
-import android.os.UserManager;
 import android.provider.Settings;
 import android.telephony.euicc.EuiccManager;
 import android.text.TextUtils;
@@ -751,9 +751,7 @@
         // Block until the ordered broadcast has completed.
         condition.block();
 
-        // TODO(b/63693573): Uncomment this once the pSIM slot is restored as needed
-        // after the ensuing boot. Currently you end up stuck on the eSIM.
-        // wipeEuiccData(context, wipeEuicc);
+        wipeEuiccData(context, wipeEuicc);
 
         String shutdownArg = null;
         if (shutdown) {
@@ -770,6 +768,14 @@
     }
 
     private static void wipeEuiccData(Context context, final boolean isWipeEuicc) {
+        ContentResolver cr = context.getContentResolver();
+        if (Settings.Global.getInt(cr, Settings.Global.EUICC_PROVISIONED, 0) == 0) {
+            // If the eUICC isn't provisioned, there's no reason to either wipe or retain profiles,
+            // as there's nothing to wipe nor retain.
+            Log.d(TAG, "Skipping eUICC wipe/retain as it is not provisioned");
+            return;
+        }
+
         EuiccManager euiccManager = (EuiccManager) context.getSystemService(
                 Context.EUICC_SERVICE);
         if (euiccManager != null && euiccManager.isEnabled()) {
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index 3337def..12013fc 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -389,10 +389,13 @@
     public static final String DISALLOW_ADD_MANAGED_PROFILE = "no_add_managed_profile";
 
     /**
-     * Specifies if a user is disallowed from disabling application verification.
-     * Starting from {@link android.os.Build.VERSION_CODES#O}, application verification
-     * is enforced across all users on the device if a profile owner or device owner sets
-     * this restriction to <code>true</code>. The default value is <code>false</code>.
+     * Specifies if a user is disallowed from disabling application verification. The default
+     * value is <code>false</code>.
+     *
+     * <p>In Android 8.0 ({@linkplain android.os.Build.VERSION_CODES#O API level 26}) and higher,
+     * this is a global user restriction. If a device owner or profile owner sets this restriction,
+     * the system enforces app verification across all users on the device. Running in earlier
+     * Android versions, this restriction affects only the profile that sets it.
      *
      * <p>Key for user restrictions.
      * <p>Type: Boolean
diff --git a/core/java/android/provider/DocumentsContract.java b/core/java/android/provider/DocumentsContract.java
index fa90384..f2e2598 100644
--- a/core/java/android/provider/DocumentsContract.java
+++ b/core/java/android/provider/DocumentsContract.java
@@ -18,6 +18,7 @@
 
 import static android.net.TrafficStats.KB_IN_BYTES;
 import static android.system.OsConstants.SEEK_SET;
+
 import static com.android.internal.util.Preconditions.checkArgument;
 import static com.android.internal.util.Preconditions.checkCollectionElementsNotNull;
 import static com.android.internal.util.Preconditions.checkCollectionNotEmpty;
@@ -28,7 +29,6 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentSender;
-import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.content.res.AssetFileDescriptor;
 import android.database.Cursor;
@@ -44,7 +44,6 @@
 import android.os.OperationCanceledException;
 import android.os.Parcel;
 import android.os.ParcelFileDescriptor;
-import android.os.ParcelFileDescriptor.OnCloseListener;
 import android.os.Parcelable;
 import android.os.ParcelableException;
 import android.os.RemoteException;
@@ -182,6 +181,15 @@
     /** {@hide} */
     public static final String PACKAGE_DOCUMENTS_UI = "com.android.documentsui";
 
+    /** {@hide} */
+    public static final String METADATA_TYPES = "android:documentMetadataType";
+
+    /** {@hide} */
+    public static final String METADATA_EXIF = "android:documentExif";
+
+    /** {@hide} */
+    public static final String EXTRA_METADATA_TAGS = "android:documentMetadataTags";
+
     /**
      * Constants related to a document, including {@link Cursor} column names
      * and flags.
@@ -442,6 +450,13 @@
          * @hide
          */
         public static final int FLAG_PARTIAL = 1 << 16;
+
+        /**
+         * Flag indicating that a document has available metadata that can be read
+         * using DocumentsContract#getDocumentMetadata
+         * @hide
+         */
+        public static final int FLAG_SUPPORTS_METADATA = 1 << 17;
     }
 
     /**
@@ -706,6 +721,8 @@
     public static final String METHOD_FIND_DOCUMENT_PATH = "android:findDocumentPath";
     /** {@hide} */
     public static final String METHOD_CREATE_WEB_LINK_INTENT = "android:createWebLinkIntent";
+    /** {@hide} */
+    public static final String METHOD_GET_DOCUMENT_METADATA = "android:getDocumentMetadata";
 
     /** {@hide} */
     public static final String EXTRA_PARENT_URI = "parentUri";
@@ -1378,6 +1395,89 @@
     }
 
     /**
+     * Returns metadata associated with the document. The type of metadata returned
+     * is specific to the document type. For example image files will largely return EXIF
+     * metadata.
+     *
+     * <p>The returned {@link Bundle} will contain zero or more entries.
+     * <p>Each entry represents a specific type of metadata.
+     *
+     * <p>if tags == null, then a list of default tags will be used.
+     *
+     * @param documentUri a Document URI
+     * @param tags an array of keys to choose which data are added to the Bundle. If the Document
+     *             is a JPG or ExifInterface compatible, send keys from {@link ExifInterface}.
+     *             If tags are null, a set of default tags will be used. If the tags don't
+     *             match with any relevant data, they will not be added to the Bundle.
+     * @return a Bundle of Bundles. If metadata exists within the Bundle, there will also
+     * be a String under DocumentsContract.METADATA_TYPES that will return a String[] of the
+     * types of metadata gathered.
+     *
+     * <pre><code>
+     *     Bundle metadata = DocumentsContract.getDocumentMetadata(resolver, imageDocUri, tags);
+     *     int imageLength = metadata.getInt(ExifInterface.TAG_IMAGE_LENGTH);
+     * </code></pre>
+     *
+     * {@hide}
+     */
+    public static Bundle getDocumentMetadata(ContentResolver resolver, Uri documentUri,
+            @Nullable String[] tags)
+            throws FileNotFoundException {
+        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
+                documentUri.getAuthority());
+
+        try {
+            return getDocumentMetadata(client, documentUri, tags);
+        } catch (Exception e) {
+            Log.w(TAG, "Failed to get document metadata");
+            rethrowIfNecessary(resolver, e);
+            return null;
+        } finally {
+            ContentProviderClient.releaseQuietly(client);
+        }
+    }
+
+    /**
+     * Returns metadata associated with the document. The type of metadata returned
+     * is specific to the document type. For example image files will largely return EXIF
+     * metadata.
+     *
+     * <p>The returned {@link Bundle} will contain zero or more entries.
+     * <p>Each entry represents a specific type of metadata.
+     *
+     * <p>if tags == null, then a list of default tags will be used.
+     *
+     * @param documentUri a Document URI
+     * @param tags an array of keys to choose which data are added to the Bundle. If the Document
+     *             is a JPG or ExifInterface compatible, send keys from {@link ExifInterface}.
+     *             If tags are null, a set of default tags will be used. If the tags don't
+     *             match with any relevant data, they will not be added to the Bundle.
+     * @return a Bundle of Bundles. If metadata exists within the Bundle, there will also
+     * be a String under DocumentsContract.METADATA_TYPES that will return a String[] of the
+     * types of metadata gathered.
+     *
+     * <pre><code>
+     *     Bundle metadata = DocumentsContract.getDocumentMetadata(client, imageDocUri, tags);
+     *     int imageLength = metadata.getInt(ExifInterface.TAG_IMAGE_LENGTH);
+     * </code></pre>
+     *
+     * {@hide}
+     */
+    public static Bundle getDocumentMetadata(ContentProviderClient client,
+            Uri documentUri, @Nullable String[] tags) throws RemoteException {
+        final Bundle in = new Bundle();
+        in.putParcelable(EXTRA_URI, documentUri);
+        in.putStringArray(EXTRA_METADATA_TAGS, tags);
+
+        final Bundle out = client.call(METHOD_GET_DOCUMENT_METADATA, null, in);
+
+        if (out == null) {
+            throw new RemoteException("Failed to get a response from getDocumentMetadata");
+        }
+        return out;
+    }
+
+    /**
      * Finds the canonical path from the top of the document tree.
      *
      * The {@link Path#getPath()} of the return value contains the document ID
diff --git a/core/java/android/provider/DocumentsProvider.java b/core/java/android/provider/DocumentsProvider.java
index 3eef31a..4bdcdb0 100644
--- a/core/java/android/provider/DocumentsProvider.java
+++ b/core/java/android/provider/DocumentsProvider.java
@@ -22,6 +22,7 @@
 import static android.provider.DocumentsContract.METHOD_DELETE_DOCUMENT;
 import static android.provider.DocumentsContract.METHOD_EJECT_ROOT;
 import static android.provider.DocumentsContract.METHOD_FIND_DOCUMENT_PATH;
+import static android.provider.DocumentsContract.METHOD_GET_DOCUMENT_METADATA;
 import static android.provider.DocumentsContract.METHOD_IS_CHILD_DOCUMENT;
 import static android.provider.DocumentsContract.METHOD_MOVE_DOCUMENT;
 import static android.provider.DocumentsContract.METHOD_REMOVE_DOCUMENT;
@@ -55,9 +56,7 @@
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.CancellationSignal;
-import android.os.OperationCanceledException;
 import android.os.ParcelFileDescriptor;
-import android.os.ParcelFileDescriptor.OnCloseListener;
 import android.os.ParcelableException;
 import android.provider.DocumentsContract.Document;
 import android.provider.DocumentsContract.Path;
@@ -627,6 +626,12 @@
         throw new UnsupportedOperationException("Eject not supported");
     }
 
+    /** {@hide} */
+    public @Nullable Bundle getDocumentMetadata(String documentId, @Nullable String[] tags)
+            throws FileNotFoundException {
+        throw new UnsupportedOperationException("Metadata not supported");
+    }
+
     /**
      * Return concrete MIME type of the requested document. Must match the value
      * of {@link Document#COLUMN_MIME_TYPE} for this document. The default
@@ -1136,6 +1141,9 @@
             }
 
             out.putParcelable(DocumentsContract.EXTRA_RESULT, path);
+        } else if (METHOD_GET_DOCUMENT_METADATA.equals(method)) {
+            return getDocumentMetadata(
+                    documentId, extras.getStringArray(DocumentsContract.EXTRA_METADATA_TAGS));
         } else {
             throw new UnsupportedOperationException("Method not supported " + method);
         }
diff --git a/core/java/android/provider/MetadataReader.java b/core/java/android/provider/MetadataReader.java
new file mode 100644
index 0000000..2d1fca0
--- /dev/null
+++ b/core/java/android/provider/MetadataReader.java
@@ -0,0 +1,285 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.provider;
+
+import android.annotation.Nullable;
+import android.media.ExifInterface;
+import android.os.Bundle;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Class providing support for extracting metadata from a file as a
+ * {@link Bundle} suitable for use with {@link DocumentsContract#getDocumentMetadata}.
+ * <p>Currently only EXIF data is supported.
+ * <p>TODO: Add support for common video and audio types, as well as PDF files.
+ * {@hide}
+ */
+public final class MetadataReader {
+
+    private MetadataReader() {
+    }
+
+    private static final String[] DEFAULT_EXIF_TAGS = {
+            ExifInterface.TAG_IMAGE_WIDTH,
+            ExifInterface.TAG_IMAGE_LENGTH,
+            ExifInterface.TAG_DATETIME,
+            ExifInterface.TAG_GPS_LATITUDE,
+            ExifInterface.TAG_GPS_LONGITUDE,
+            ExifInterface.TAG_MAKE,
+            ExifInterface.TAG_MODEL,
+            ExifInterface.TAG_APERTURE,
+            ExifInterface.TAG_SHUTTER_SPEED_VALUE
+    };
+
+    private static final Map<String, Integer> TYPE_MAPPING = new HashMap<>();
+    private static final String[] ALL_KNOWN_EXIF_KEYS;
+    private static final int TYPE_INT = 0;
+    private static final int TYPE_DOUBLE = 1;
+    private static final int TYPE_STRING = 2;
+
+    static {
+        // TODO: Move this over to ExifInterface.java
+        // Since each ExifInterface item has a type, and there's currently no way to get the type
+        // from the tag, here we identify the tag to the type so that we can call the correct
+        // ExifInterface method
+        TYPE_MAPPING.put(ExifInterface.TAG_ARTIST, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_BITS_PER_SAMPLE, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_COMPRESSION, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_COPYRIGHT, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_DATETIME, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_IMAGE_DESCRIPTION, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_IMAGE_LENGTH, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_IMAGE_WIDTH, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_MAKE, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_MODEL, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_ORIENTATION, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_PHOTOMETRIC_INTERPRETATION, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_PLANAR_CONFIGURATION, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_PRIMARY_CHROMATICITIES, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_REFERENCE_BLACK_WHITE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_RESOLUTION_UNIT, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_ROWS_PER_STRIP, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_SAMPLES_PER_PIXEL, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_SOFTWARE, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_STRIP_BYTE_COUNTS, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_STRIP_OFFSETS, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_TRANSFER_FUNCTION, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_WHITE_POINT, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_X_RESOLUTION, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_Y_CB_CR_COEFFICIENTS, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_Y_CB_CR_POSITIONING, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_Y_CB_CR_SUB_SAMPLING, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_Y_RESOLUTION, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_APERTURE_VALUE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_BRIGHTNESS_VALUE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_CFA_PATTERN, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_COLOR_SPACE, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_COMPONENTS_CONFIGURATION, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_COMPRESSED_BITS_PER_PIXEL, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_CONTRAST, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_CUSTOM_RENDERED, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_DATETIME_DIGITIZED, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_DATETIME_ORIGINAL, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_DEVICE_SETTING_DESCRIPTION, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_DIGITAL_ZOOM_RATIO, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_EXIF_VERSION, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_EXPOSURE_BIAS_VALUE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_EXPOSURE_INDEX, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_EXPOSURE_MODE, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_EXPOSURE_PROGRAM, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_EXPOSURE_TIME, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_F_NUMBER, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_FILE_SOURCE, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_FLASH, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_FLASH_ENERGY, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_FLASHPIX_VERSION, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_FOCAL_LENGTH, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_FOCAL_PLANE_RESOLUTION_UNIT, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_FOCAL_PLANE_X_RESOLUTION, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_FOCAL_PLANE_Y_RESOLUTION, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_GAIN_CONTROL, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_ISO_SPEED_RATINGS, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_IMAGE_UNIQUE_ID, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_LIGHT_SOURCE, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_MAKER_NOTE, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_MAX_APERTURE_VALUE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_METERING_MODE, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_NEW_SUBFILE_TYPE, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_OECF, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_PIXEL_X_DIMENSION, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_PIXEL_Y_DIMENSION, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_RELATED_SOUND_FILE, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_SATURATION, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_SCENE_CAPTURE_TYPE, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_SCENE_TYPE, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_SENSING_METHOD, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_SHARPNESS, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_SHUTTER_SPEED_VALUE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_SPATIAL_FREQUENCY_RESPONSE, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_SPECTRAL_SENSITIVITY, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_SUBFILE_TYPE, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_SUBSEC_TIME, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_SUBSEC_TIME_DIGITIZED, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_SUBJECT_AREA, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_SUBJECT_DISTANCE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_SUBJECT_DISTANCE_RANGE, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_SUBJECT_LOCATION, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_USER_COMMENT, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_WHITE_BALANCE, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_ALTITUDE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_ALTITUDE_REF, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_AREA_INFORMATION, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_DOP, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_DATESTAMP, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_DEST_BEARING, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_DEST_BEARING_REF, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_DEST_DISTANCE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_DEST_DISTANCE_REF, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_DEST_LATITUDE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_DEST_LATITUDE_REF, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_DEST_LONGITUDE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_DEST_LONGITUDE_REF, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_DIFFERENTIAL, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_IMG_DIRECTION, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_IMG_DIRECTION_REF, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_LATITUDE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_LATITUDE_REF, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_LONGITUDE, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_LONGITUDE_REF, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_MAP_DATUM, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_MEASURE_MODE, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_PROCESSING_METHOD, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_SATELLITES, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_SPEED, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_SPEED_REF, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_STATUS, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_TIMESTAMP, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_TRACK, TYPE_DOUBLE);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_TRACK_REF, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_GPS_VERSION_ID, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_INTEROPERABILITY_INDEX, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_THUMBNAIL_IMAGE_LENGTH, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_THUMBNAIL_IMAGE_WIDTH, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_DNG_VERSION, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_DEFAULT_CROP_SIZE, TYPE_INT);
+        //I don't know how to represent this. Type is unknown
+        //TYPE_MAPPING.put(ExifInterface.TAG_ORF_THUMBNAIL_IMAGE, TYPE_STRING);
+        TYPE_MAPPING.put(ExifInterface.TAG_ORF_PREVIEW_IMAGE_START, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_ORF_PREVIEW_IMAGE_LENGTH, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_ORF_ASPECT_FRAME, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_RW2_SENSOR_BOTTOM_BORDER, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_RW2_SENSOR_LEFT_BORDER, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_RW2_SENSOR_RIGHT_BORDER, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_RW2_SENSOR_TOP_BORDER, TYPE_INT);
+        TYPE_MAPPING.put(ExifInterface.TAG_RW2_ISO, TYPE_INT);
+        ALL_KNOWN_EXIF_KEYS = TYPE_MAPPING.keySet().toArray(new String[TYPE_MAPPING.size()]);
+    }
+    private static final String JPG_MIME_TYPE = "image/jpg";
+    private static final String JPEG_MIME_TYPE = "image/jpeg";
+
+    /**
+     * Generic metadata retrieval method that can retrieve any available metadata from a given doc
+     * Currently only functions for exifdata
+     *
+     * @param metadata the bundle to which we add any relevant metadata
+     * @param stream InputStream containing a file
+     * @param mimeType type of the given file
+     * @param tags a variable amount of keys to differentiate which tags the user wants
+     *             if null, returns a default set of data from the following keys:
+     *             Exif data:
+     *             ExifInterface.TAG_IMAGE_WIDTH,
+     *             ExifInterface.TAG_IMAGE_LENGTH,
+     *             ExifInterface.TAG_DATETIME,
+     *             ExifInterface.TAG_GPS_LATITUDE,
+     *             ExifInterface.TAG_GPS_LONGITUDE,
+     *             ExifInterface.TAG_MAKE,
+     *             ExifInterface.TAG_MODEL,
+     *             ExifInterface.TAG_APERTURE,
+     *             ExifInterface.TAG_SHUTTER_SPEED_VALUE
+     * @throws IOException when the file doesn't exist
+     */
+    public static void getMetadata(Bundle metadata, InputStream stream, String mimeType,
+            @Nullable String[] tags) throws IOException {
+        List<String> metadataTypes = new ArrayList();
+        if (mimeType.equals(JPG_MIME_TYPE) || mimeType.equals(JPEG_MIME_TYPE)) {
+            ExifInterface exifInterface = new ExifInterface(stream);
+            Bundle exifData = getExifData(exifInterface, tags);
+            if (exifData.size() > 0) {
+                metadata.putBundle(DocumentsContract.METADATA_EXIF, exifData);
+                metadataTypes.add(DocumentsContract.METADATA_EXIF);
+            }
+        }
+        metadata.putStringArray(DocumentsContract.METADATA_TYPES,
+                metadataTypes.toArray(new String[metadataTypes.size()]));
+        // TODO: Add support for PDF and Video metadata
+        // TODO: Broaden image support to all images
+    }
+
+    /**
+     * Helper method that is called if getMetadata is called for an image mimeType.
+     *
+     * @param exif the bundle to which we add exif data.
+     * @param exifInterface an ExifInterface for an image
+     * @param tags a list of ExifInterface tags that are used to retrieve data.
+     *             if null, returns a default set of data from the following keys:
+     *             ExifInterface.TAG_IMAGE_WIDTH,
+     *             ExifInterface.TAG_IMAGE_LENGTH,
+     *             ExifInterface.TAG_DATETIME,
+     *             ExifInterface.TAG_GPS_LATITUDE,
+     *             ExifInterface.TAG_GPS_LONGITUDE,
+     *             ExifInterface.TAG_MAKE,
+     *             ExifInterface.TAG_MODEL,
+     *             ExifInterface.TAG_APERTURE,
+     *             ExifInterface.TAG_SHUTTER_SPEED_VALUE
+     */
+    private static Bundle getExifData(ExifInterface exifInterface, @Nullable String[] tags)
+            throws IOException {
+        if (tags == null) {
+            tags = DEFAULT_EXIF_TAGS;
+        }
+        Bundle exif = new Bundle();
+        for (int i = 0; i < tags.length; i++) {
+            if (TYPE_MAPPING.get(tags[i]).equals(TYPE_INT)) {
+                int data = exifInterface.getAttributeInt(tags[i], Integer.MIN_VALUE);
+                if (data != Integer.MIN_VALUE) {
+                    exif.putInt(tags[i], data);
+                }
+            } else if (TYPE_MAPPING.get(tags[i]).equals(TYPE_DOUBLE)) {
+                double data = exifInterface.getAttributeDouble(tags[i], Double.MIN_VALUE);
+                if (data != Double.MIN_VALUE) {
+                    exif.putDouble(tags[i], data);
+                }
+            } else if (TYPE_MAPPING.get(tags[i]).equals(TYPE_STRING)) {
+                String data = exifInterface.getAttribute(tags[i]);
+                if (data != null) {
+                    exif.putString(tags[i], data);
+                }
+            }
+        }
+        return exif;
+    }
+}
diff --git a/core/java/android/service/autofill/CharSequenceTransformation.java b/core/java/android/service/autofill/CharSequenceTransformation.java
index 77555fe..dfb30b9 100644
--- a/core/java/android/service/autofill/CharSequenceTransformation.java
+++ b/core/java/android/service/autofill/CharSequenceTransformation.java
@@ -70,13 +70,13 @@
     @Override
     @TestApi
     public void apply(@NonNull ValueFinder finder, @NonNull RemoteViews parentTemplate,
-            int childViewId) {
+            int childViewId) throws Exception {
         final StringBuilder converted = new StringBuilder();
         final int size = mFields.size();
         if (sDebug) Log.d(TAG, size + " multiple fields on id " + childViewId);
         for (int i = 0; i < size; i++) {
             final AutofillId id = mFields.keyAt(i);
-            final Pair<Pattern, String> regex = mFields.valueAt(i);
+            final Pair<Pattern, String> field = mFields.valueAt(i);
             final String value = finder.findByAutofillId(id);
             if (value == null) {
                 Log.w(TAG, "No value for id " + id);
@@ -84,12 +84,13 @@
             }
             try {
                 // replaceAll throws an exception if the subst is invalid
-                final String convertedValue = regex.first.matcher(value).replaceAll(regex.second);
+                final String convertedValue = field.first.matcher(value).replaceAll(field.second);
                 converted.append(convertedValue);
             } catch (Exception e) {
-                // Do not log full exception to avoid leaks
-                Log.w(TAG, "Cannot apply " + regex.first.pattern() + "->" + regex.second + " to "
+                // Do not log full exception to avoid PII leaking
+                Log.w(TAG, "Cannot apply " + field.first.pattern() + "->" + field.second + " to "
                         + "field with autofill id" + id + ": " + e.getClass());
+                throw e;
             }
         }
         parentTemplate.setCharSequence(childViewId, "setText", converted);
diff --git a/core/java/android/service/autofill/CustomDescription.java b/core/java/android/service/autofill/CustomDescription.java
index e97c364..0edb154 100644
--- a/core/java/android/service/autofill/CustomDescription.java
+++ b/core/java/android/service/autofill/CustomDescription.java
@@ -103,8 +103,10 @@
                 try {
                     transformation.apply(finder, mPresentation, id);
                 } catch (Exception e) {
-                    Log.e(TAG, "Could not apply transformation " + transformation + ". "
+                    // Do not log full exception to avoid PII leaking
+                    Log.e(TAG, "Could not apply transformation " + transformation + ": "
                             + e.getClass());
+                    return null;
                 }
             }
         }
diff --git a/core/java/android/service/autofill/ImageTransformation.java b/core/java/android/service/autofill/ImageTransformation.java
index 9eb52f6..3627189 100644
--- a/core/java/android/service/autofill/ImageTransformation.java
+++ b/core/java/android/service/autofill/ImageTransformation.java
@@ -70,7 +70,7 @@
     @TestApi
     @Override
     public void apply(@NonNull ValueFinder finder, @NonNull RemoteViews parentTemplate,
-            int childViewId) {
+            int childViewId) throws Exception {
         final String value = finder.findByAutofillId(mId);
         if (value == null) {
             Log.w(TAG, "No view for id " + mId);
@@ -83,14 +83,22 @@
         }
 
         for (int i = 0; i < size; i++) {
-            Pair<Pattern, Integer> regex = mOptions.get(i);
-            if (regex.first.matcher(value).matches()) {
-                Log.d(TAG, "Found match at " + i + ": " + regex);
-                parentTemplate.setImageViewResource(childViewId, regex.second);
-                return;
+            final Pair<Pattern, Integer> option = mOptions.get(i);
+            try {
+                if (option.first.matcher(value).matches()) {
+                    Log.d(TAG, "Found match at " + i + ": " + option);
+                    parentTemplate.setImageViewResource(childViewId, option.second);
+                    return;
+                }
+            } catch (Exception e) {
+                // Do not log full exception to avoid PII leaking
+                Log.w(TAG, "Error matching regex #" + i + "(" + option.first.pattern() + ") on id "
+                        + option.second + ": " + e.getClass());
+                throw e;
+
             }
         }
-        Log.w(TAG, "No match for " + value);
+        if (sDebug) Log.d(TAG, "No match for " + value);
     }
 
     /**
diff --git a/core/java/android/service/autofill/InternalTransformation.java b/core/java/android/service/autofill/InternalTransformation.java
index e8ac14a..974397b 100644
--- a/core/java/android/service/autofill/InternalTransformation.java
+++ b/core/java/android/service/autofill/InternalTransformation.java
@@ -38,5 +38,5 @@
      * @hide
      */
     abstract void apply(@NonNull ValueFinder finder, @NonNull RemoteViews template,
-            int childViewId);
+            int childViewId) throws Exception;
 }
diff --git a/core/java/android/service/notification/ZenModeConfig.java b/core/java/android/service/notification/ZenModeConfig.java
index b225018..6ba11b9 100644
--- a/core/java/android/service/notification/ZenModeConfig.java
+++ b/core/java/android/service/notification/ZenModeConfig.java
@@ -85,7 +85,7 @@
     private static final boolean DEFAULT_ALLOW_SCREEN_ON = true;
 
     private static final int XML_VERSION = 2;
-    private static final String ZEN_TAG = "zen";
+    public static final String ZEN_TAG = "zen";
     private static final String ZEN_ATT_VERSION = "version";
     private static final String ZEN_ATT_USER = "user";
     private static final String ALLOW_TAG = "allow";
diff --git a/core/java/android/text/Selection.java b/core/java/android/text/Selection.java
index 3222dbf..3445658 100644
--- a/core/java/android/text/Selection.java
+++ b/core/java/android/text/Selection.java
@@ -16,6 +16,8 @@
 
 package android.text;
 
+import android.annotation.TestApi;
+
 import java.text.BreakIterator;
 
 
@@ -35,10 +37,10 @@
      * there is no selection or cursor.
      */
     public static final int getSelectionStart(CharSequence text) {
-        if (text instanceof Spanned)
+        if (text instanceof Spanned) {
             return ((Spanned) text).getSpanStart(SELECTION_START);
-        else
-            return -1;
+        }
+        return -1;
     }
 
     /**
@@ -46,10 +48,17 @@
      * there is no selection or cursor.
      */
     public static final int getSelectionEnd(CharSequence text) {
-        if (text instanceof Spanned)
+        if (text instanceof Spanned) {
             return ((Spanned) text).getSpanStart(SELECTION_END);
-        else
-            return -1;
+        }
+        return -1;
+    }
+
+    private static int getSelectionMemory(CharSequence text) {
+        if (text instanceof Spanned) {
+            return ((Spanned) text).getSpanStart(SELECTION_MEMORY);
+        }
+        return -1;
     }
 
     /*
@@ -65,6 +74,14 @@
      * to <code>stop</code>.
      */
     public static void setSelection(Spannable text, int start, int stop) {
+        setSelection(text, start, stop, -1);
+    }
+
+    /**
+     * Set the selection anchor to <code>start</code>, the selection edge
+     * to <code>stop</code> and the memory horizontal to <code>memory</code>.
+     */
+    private static void setSelection(Spannable text, int start, int stop, int memory) {
         // int len = text.length();
         // start = pin(start, 0, len);  XXX remove unless we really need it
         // stop = pin(stop, 0, len);
@@ -74,9 +91,57 @@
 
         if (ostart != start || oend != stop) {
             text.setSpan(SELECTION_START, start, start,
-                         Spanned.SPAN_POINT_POINT|Spanned.SPAN_INTERMEDIATE);
-            text.setSpan(SELECTION_END, stop, stop,
-                         Spanned.SPAN_POINT_POINT);
+                    Spanned.SPAN_POINT_POINT | Spanned.SPAN_INTERMEDIATE);
+            text.setSpan(SELECTION_END, stop, stop, Spanned.SPAN_POINT_POINT);
+            updateMemory(text, memory);
+        }
+    }
+
+    /**
+     * Update the memory position for text. This is used to ensure vertical navigation of lines
+     * with different lengths behaves as expected and remembers the longest horizontal position
+     * seen during a vertical traversal.
+     */
+    private static void updateMemory(Spannable text, int memory) {
+        if (memory > -1) {
+            int currentMemory = getSelectionMemory(text);
+            if (memory != currentMemory) {
+                text.setSpan(SELECTION_MEMORY, memory, memory, Spanned.SPAN_POINT_POINT);
+                if (currentMemory == -1) {
+                    // This is the first value, create a watcher.
+                    final TextWatcher watcher = new MemoryTextWatcher();
+                    text.setSpan(watcher, 0, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
+                }
+            }
+        } else {
+            removeMemory(text);
+        }
+    }
+
+    private static void removeMemory(Spannable text) {
+        text.removeSpan(SELECTION_MEMORY);
+        MemoryTextWatcher[] watchers = text.getSpans(0, text.length(), MemoryTextWatcher.class);
+        for (MemoryTextWatcher watcher : watchers) {
+            text.removeSpan(watcher);
+        }
+    }
+
+    /**
+     * @hide
+     */
+    @TestApi
+    public static final class MemoryTextWatcher implements TextWatcher {
+
+        @Override
+        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
+
+        @Override
+        public void onTextChanged(CharSequence s, int start, int before, int count) {}
+
+        @Override
+        public void afterTextChanged(Editable s) {
+            s.removeSpan(SELECTION_MEMORY);
+            s.removeSpan(this);
         }
     }
 
@@ -98,8 +163,17 @@
      * Move the selection edge to offset <code>index</code>.
      */
     public static final void extendSelection(Spannable text, int index) {
-        if (text.getSpanStart(SELECTION_END) != index)
+        extendSelection(text, index, -1);
+    }
+
+    /**
+     * Move the selection edge to offset <code>index</code> and update the memory horizontal.
+     */
+    private static void extendSelection(Spannable text, int index, int memory) {
+        if (text.getSpanStart(SELECTION_END) != index) {
             text.setSpan(SELECTION_END, index, index, Spanned.SPAN_POINT_POINT);
+        }
+        updateMemory(text, memory);
     }
 
     /**
@@ -108,6 +182,7 @@
     public static final void removeSelection(Spannable text) {
         text.removeSpan(SELECTION_START);
         text.removeSpan(SELECTION_END);
+        removeMemory(text);
     }
 
     /*
@@ -138,17 +213,8 @@
             int line = layout.getLineForOffset(end);
 
             if (line > 0) {
-                int move;
-
-                if (layout.getParagraphDirection(line) ==
-                    layout.getParagraphDirection(line - 1)) {
-                    float h = layout.getPrimaryHorizontal(end);
-                    move = layout.getOffsetForHorizontal(line - 1, h);
-                } else {
-                    move = layout.getLineStart(line - 1);
-                }
-
-                setSelection(text, move);
+                setSelectionAndMemory(
+                        text, layout, line, end, -1 /* direction */, false /* extend */);
                 return true;
             } else if (end != 0) {
                 setSelection(text, 0);
@@ -160,6 +226,40 @@
     }
 
     /**
+     * Calculate the movement and memory positions needed, and set or extend the selection.
+     */
+    private static void setSelectionAndMemory(Spannable text, Layout layout, int line, int end,
+            int direction, boolean extend) {
+        int move;
+        int newMemory;
+
+        if (layout.getParagraphDirection(line)
+                == layout.getParagraphDirection(line + direction)) {
+            int memory = getSelectionMemory(text);
+            if (memory > -1) {
+                // We have a memory position
+                float h = layout.getPrimaryHorizontal(memory);
+                move = layout.getOffsetForHorizontal(line + direction, h);
+                newMemory = memory;
+            } else {
+                // Create a new memory position
+                float h = layout.getPrimaryHorizontal(end);
+                move = layout.getOffsetForHorizontal(line + direction, h);
+                newMemory = end;
+            }
+        } else {
+            move = layout.getLineStart(line + direction);
+            newMemory = -1;
+        }
+
+        if (extend) {
+            extendSelection(text, move, newMemory);
+        } else {
+            setSelection(text, move, move, newMemory);
+        }
+    }
+
+    /**
      * Move the cursor to the buffer offset physically below the current
      * offset, to the end of the buffer if it is on the bottom line but
      * not at the end, or return false if the cursor is already at the
@@ -184,17 +284,8 @@
             int line = layout.getLineForOffset(end);
 
             if (line < layout.getLineCount() - 1) {
-                int move;
-
-                if (layout.getParagraphDirection(line) ==
-                    layout.getParagraphDirection(line + 1)) {
-                    float h = layout.getPrimaryHorizontal(end);
-                    move = layout.getOffsetForHorizontal(line + 1, h);
-                } else {
-                    move = layout.getLineStart(line + 1);
-                }
-
-                setSelection(text, move);
+                setSelectionAndMemory(
+                        text, layout, line, end, 1 /* direction */, false /* extend */);
                 return true;
             } else if (end != text.length()) {
                 setSelection(text, text.length());
@@ -263,17 +354,7 @@
         int line = layout.getLineForOffset(end);
 
         if (line > 0) {
-            int move;
-
-            if (layout.getParagraphDirection(line) ==
-                layout.getParagraphDirection(line - 1)) {
-                float h = layout.getPrimaryHorizontal(end);
-                move = layout.getOffsetForHorizontal(line - 1, h);
-            } else {
-                move = layout.getLineStart(line - 1);
-            }
-
-            extendSelection(text, move);
+            setSelectionAndMemory(text, layout, line, end, -1 /* direction */, true /* extend */);
             return true;
         } else if (end != 0) {
             extendSelection(text, 0);
@@ -292,20 +373,10 @@
         int line = layout.getLineForOffset(end);
 
         if (line < layout.getLineCount() - 1) {
-            int move;
-
-            if (layout.getParagraphDirection(line) ==
-                layout.getParagraphDirection(line + 1)) {
-                float h = layout.getPrimaryHorizontal(end);
-                move = layout.getOffsetForHorizontal(line + 1, h);
-            } else {
-                move = layout.getLineStart(line + 1);
-            }
-
-            extendSelection(text, move);
+            setSelectionAndMemory(text, layout, line, end, 1 /* direction */, true /* extend */);
             return true;
         } else if (end != text.length()) {
-            extendSelection(text, text.length());
+            extendSelection(text, text.length(), -1);
             return true;
         }
 
@@ -466,6 +537,8 @@
 
     private static final class START implements NoCopySpan { }
     private static final class END implements NoCopySpan { }
+    private static final class MEMORY implements NoCopySpan { }
+    private static final Object SELECTION_MEMORY = new MEMORY();
 
     /*
      * Public constants
diff --git a/core/java/android/view/WindowManagerPolicy.java b/core/java/android/view/WindowManagerPolicy.java
index ba9e05c..668d25e 100644
--- a/core/java/android/view/WindowManagerPolicy.java
+++ b/core/java/android/view/WindowManagerPolicy.java
@@ -74,7 +74,6 @@
 import android.os.Bundle;
 import android.os.IBinder;
 import android.os.Looper;
-import android.os.PowerManager;
 import android.os.RemoteException;
 import android.util.Slog;
 import android.view.animation.Animation;
@@ -1317,12 +1316,12 @@
     public boolean isScreenOn();
 
     /**
-     * @return whether the device is currently {@link PowerManager#isInteractive() interactive}.
+     * @return whether the device is currently allowed to animate.
      *
-     * Note: the screen can be on while the device is not interactive, e.g. when the device is
-     * showing Ambient Display.
+     * Note: this can be true even if it is not appropriate to animate for reasons that are outside
+     *       of the policy's authority.
      */
-    boolean isInteractive();
+    boolean okToAnimate();
 
     /**
      * Tell the policy that the lid switch has changed state.
diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java
index 454f5b7..b77aa1c 100644
--- a/core/java/android/widget/RemoteViews.java
+++ b/core/java/android/widget/RemoteViews.java
@@ -199,6 +199,22 @@
     }
 
     /**
+     * Reduces all images and ensures that they are all below the given sizes.
+     *
+     * @param maxWidth the maximum width allowed
+     * @param maxHeight the maximum height allowed
+     *
+     * @hide
+     */
+    public void reduceImageSizes(int maxWidth, int maxHeight) {
+        ArrayList<Bitmap> cache = mBitmapCache.mBitmaps;
+        for (int i = 0; i < cache.size(); i++) {
+            Bitmap bitmap = cache.get(i);
+            cache.set(i, Icon.scaleDownIfNecessary(bitmap, maxWidth, maxHeight));
+        }
+    }
+
+    /**
      * Handle with care!
      */
     static class MutablePair<F, S> {
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 69edbbb..6f65502 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -4848,8 +4848,9 @@
     }
 
     /**
-     * Sets line spacing for this TextView.  Each line will have its height
-     * multiplied by <code>mult</code> and have <code>add</code> added to it.
+     * Sets line spacing for this TextView.  Each line other than the last line will have its height
+     * multiplied by {@code mult} and have {@code add} added to it.
+     *
      *
      * @attr ref android.R.styleable#TextView_lineSpacingExtra
      * @attr ref android.R.styleable#TextView_lineSpacingMultiplier
diff --git a/core/java/com/android/internal/app/MediaRouteControllerDialog.java b/core/java/com/android/internal/app/MediaRouteControllerDialog.java
index 3341df9..61e63d1 100644
--- a/core/java/com/android/internal/app/MediaRouteControllerDialog.java
+++ b/core/java/com/android/internal/app/MediaRouteControllerDialog.java
@@ -143,7 +143,11 @@
                     @Override
                     public void onClick(DialogInterface dialogInterface, int id) {
                         if (mRoute.isSelected()) {
-                            mRouter.getDefaultRoute().select();
+                            if (mRoute.isBluetooth()) {
+                                mRouter.getDefaultRoute().select();
+                            } else {
+                                mRouter.getFallbackRoute().select();
+                            }
                         }
                         dismiss();
                     }
diff --git a/core/java/com/android/internal/content/FileSystemProvider.java b/core/java/com/android/internal/content/FileSystemProvider.java
index 04874bd..17a598a 100644
--- a/core/java/com/android/internal/content/FileSystemProvider.java
+++ b/core/java/com/android/internal/content/FileSystemProvider.java
@@ -29,6 +29,7 @@
 import android.net.Uri;
 import android.os.Binder;
 import android.os.Build;
+import android.os.Bundle;
 import android.os.CancellationSignal;
 import android.os.FileObserver;
 import android.os.FileUtils;
@@ -38,6 +39,7 @@
 import android.provider.DocumentsContract.Document;
 import android.provider.DocumentsProvider;
 import android.provider.MediaStore;
+import android.provider.MetadataReader;
 import android.text.TextUtils;
 import android.util.ArrayMap;
 import android.util.Log;
@@ -45,7 +47,10 @@
 
 import com.android.internal.annotations.GuardedBy;
 
+import libcore.io.IoUtils;
+
 import java.io.File;
+import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.util.LinkedList;
@@ -71,6 +76,12 @@
 
     private static final String MIMETYPE_PDF = "application/pdf";
 
+    private static final String MIMETYPE_JPEG = "image/jpeg";
+
+    private static final String MIMETYPE_JPG = "image/jpg";
+
+
+
     protected abstract File getFileForDocId(String docId, boolean visible)
             throws FileNotFoundException;
 
@@ -102,6 +113,30 @@
         }
     }
 
+    @Override
+    public @Nullable Bundle getDocumentMetadata(String documentId, @Nullable String[] tags)
+            throws FileNotFoundException {
+        File file = getFileForDocId(documentId);
+        if (!(file.exists() && file.isFile() && file.canRead())) {
+            return Bundle.EMPTY;
+        }
+        String filePath = file.getAbsolutePath();
+        Bundle metadata = new Bundle();
+        if (getTypeForFile(file).equals(MIMETYPE_JPEG)
+                || getTypeForFile(file).equals(MIMETYPE_JPG)) {
+            FileInputStream stream = new FileInputStream(filePath);
+            try {
+                MetadataReader.getMetadata(metadata, stream, getTypeForFile(file), tags);
+                return metadata;
+            } catch (IOException e) {
+                Log.e(TAG, "An error occurred retrieving the metadata", e);
+            } finally {
+                IoUtils.closeQuietly(stream);
+            }
+        }
+        return null;
+    }
+
     protected final List<String> findDocumentPath(File parent, File doc)
             throws FileNotFoundException {
 
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 398fb25..5129cf5 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -3497,26 +3497,31 @@
 
     public void updateTimeBasesLocked(boolean unplugged, boolean screenOff, long uptime,
             long realtime) {
-        boolean batteryStatusChanged = mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
+        final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
+        final boolean updateOnBatteryScreenOffTimeBase =
+                (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
 
-        if (batteryStatusChanged) {
-            for (int i = 0; i < mUidStats.size(); i++) {
-                mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
+        if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
+            if (updateOnBatteryScreenOffTimeBase) {
+                updateKernelWakelocksLocked();
+                updateBatteryPropertiesLocked();
             }
-        }
-
-        boolean unpluggedScreenOff = unplugged && screenOff;
-        if (unpluggedScreenOff != mOnBatteryScreenOffTimeBase.isRunning()) {
-            updateKernelWakelocksLocked();
-            updateBatteryPropertiesLocked();
             if (DEBUG_ENERGY_CPU) {
-                Slog.d(TAG, "Updating cpu time because screen is now " +
-                        (unpluggedScreenOff ? "off" : "on"));
+                Slog.d(TAG, "Updating cpu time because screen is now " + (screenOff ? "off" : "on")
+                        + " and battery is " + (unplugged ? "on" : "off"));
             }
             updateCpuTimeLocked(true /* updateCpuFreqData */);
-            mOnBatteryScreenOffTimeBase.setRunning(unpluggedScreenOff, uptime, realtime);
-            for (int i = 0; i < mUidStats.size(); i++) {
-                mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
+
+            mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
+            mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
+            for (int i = mUidStats.size() - 1; i >= 0; --i) {
+                final Uid u = mUidStats.valueAt(i);
+                if (updateOnBatteryTimeBase) {
+                    u.updateOnBatteryBgTimeBase(uptime, realtime);
+                }
+                if (updateOnBatteryScreenOffTimeBase) {
+                    u.updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
+                }
             }
         }
     }
diff --git a/core/java/com/android/internal/os/ClassLoaderFactory.java b/core/java/com/android/internal/os/ClassLoaderFactory.java
index 0c041f2..61c57c8 100644
--- a/core/java/com/android/internal/os/ClassLoaderFactory.java
+++ b/core/java/com/android/internal/os/ClassLoaderFactory.java
@@ -39,8 +39,24 @@
      * binary name of a class, as defined by {@code Class.getName}.
      */
     public static boolean isValidClassLoaderName(String name) {
-        return PATH_CLASS_LOADER_NAME.equals(name) ||
-                DELEGATE_LAST_CLASS_LOADER_NAME.equals(name);
+        // This method is used to parse package data and does not accept null names.
+        return name != null && (isPathClassLoaderName(name) || isDelegateLastClassLoaderName(name));
+    }
+
+    /**
+     * Returns true if {@code name} is the encoding for the PathClassLoader.
+     */
+    public static boolean isPathClassLoaderName(String name) {
+        // For null values we default to PathClassLoader. This cover the case when packages
+        // don't specify any value for their class loaders.
+        return name == null || PATH_CLASS_LOADER_NAME.equals(name);
+    }
+
+    /**
+     * Returns true if {@code name} is the encoding for the DelegateLastClassLoader.
+     */
+    public static boolean isDelegateLastClassLoaderName(String name) {
+        return DELEGATE_LAST_CLASS_LOADER_NAME.equals(name);
     }
 
     /**
@@ -49,9 +65,9 @@
      */
     public static ClassLoader createClassLoader(String dexPath,
             String librarySearchPath, ClassLoader parent, String classloaderName) {
-        if (classloaderName == null || PATH_CLASS_LOADER_NAME.equals(classloaderName)) {
+        if (isPathClassLoaderName(classloaderName)) {
             return new PathClassLoader(dexPath, librarySearchPath, parent);
-        } else if (DELEGATE_LAST_CLASS_LOADER_NAME.equals(classloaderName)) {
+        } else if (isPathClassLoaderName(classloaderName)) {
             return new DelegateLastClassLoader(dexPath, librarySearchPath, parent);
         }
 
diff --git a/core/java/com/android/internal/policy/IKeyguardService.aidl b/core/java/com/android/internal/policy/IKeyguardService.aidl
index 3f35c91..69184c3 100644
--- a/core/java/com/android/internal/policy/IKeyguardService.aidl
+++ b/core/java/com/android/internal/policy/IKeyguardService.aidl
@@ -64,6 +64,11 @@
     void onStartedWakingUp();
 
     /**
+     * Called when the device has finished waking up.
+     */
+    void onFinishedWakingUp();
+
+    /**
      * Called when the device screen is turning on.
      */
     void onScreenTurningOn(IKeyguardDrawnCallback callback);
@@ -74,6 +79,11 @@
     void onScreenTurnedOn();
 
     /**
+     * Called when the screen starts turning off.
+     */
+    void onScreenTurningOff();
+
+    /**
      * Called when the screen has turned off.
      */
     void onScreenTurnedOff();
diff --git a/core/java/com/android/internal/statusbar/IStatusBar.aidl b/core/java/com/android/internal/statusbar/IStatusBar.aidl
index 4138b33a..45a8654 100644
--- a/core/java/com/android/internal/statusbar/IStatusBar.aidl
+++ b/core/java/com/android/internal/statusbar/IStatusBar.aidl
@@ -115,5 +115,5 @@
     void addQsTile(in ComponentName tile);
     void remQsTile(in ComponentName tile);
     void clickQsTile(in ComponentName tile);
-    void handleSystemNavigationKey(in int key);
+    void handleSystemKey(in int key);
 }
diff --git a/core/java/com/android/internal/statusbar/IStatusBarService.aidl b/core/java/com/android/internal/statusbar/IStatusBarService.aidl
index 4c2c3ae..82eb1ab 100644
--- a/core/java/com/android/internal/statusbar/IStatusBarService.aidl
+++ b/core/java/com/android/internal/statusbar/IStatusBarService.aidl
@@ -76,5 +76,5 @@
     void addTile(in ComponentName tile);
     void remTile(in ComponentName tile);
     void clickTile(in ComponentName tile);
-    void handleSystemNavigationKey(in int key);
+    void handleSystemKey(in int key);
 }
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index 5b40cd0..1ad8541 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -32,8 +32,8 @@
 #include <SkGraphics.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
-#include "JniInvocation.h"
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JniInvocation.h>
 #include "android_util_Binder.h"
 
 #include <stdio.h>
diff --git a/core/jni/android/graphics/BitmapFactory.cpp b/core/jni/android/graphics/BitmapFactory.cpp
index 358c5ba..94edde1 100644
--- a/core/jni/android/graphics/BitmapFactory.cpp
+++ b/core/jni/android/graphics/BitmapFactory.cpp
@@ -14,7 +14,7 @@
 #include "Utils.h"
 #include "core_jni_helpers.h"
 
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <androidfw/Asset.h>
 #include <androidfw/ResourceTypes.h>
 #include <cutils/compiler.h>
diff --git a/core/jni/android/graphics/BitmapRegionDecoder.cpp b/core/jni/android/graphics/BitmapRegionDecoder.cpp
index 9355cfc..3b081ef 100644
--- a/core/jni/android/graphics/BitmapRegionDecoder.cpp
+++ b/core/jni/android/graphics/BitmapRegionDecoder.cpp
@@ -33,7 +33,7 @@
 #include "android_util_Binder.h"
 #include "core_jni_helpers.h"
 
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <androidfw/Asset.h>
 #include <binder/Parcel.h>
 #include <jni.h>
diff --git a/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp b/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp
index 067489a..0e907c3 100644
--- a/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp
+++ b/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp
@@ -5,7 +5,7 @@
 #include "SkTypes.h"
 #include "Utils.h"
 
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <memory>
 
 static jmethodID    gInputStream_readMethodID;
diff --git a/core/jni/android/graphics/FontFamily.cpp b/core/jni/android/graphics/FontFamily.cpp
index 9ad57b1..4cf2b56 100644
--- a/core/jni/android/graphics/FontFamily.cpp
+++ b/core/jni/android/graphics/FontFamily.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "Minikin"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <core_jni_helpers.h>
 
 #include "SkData.h"
@@ -24,8 +24,8 @@
 #include "SkRefCnt.h"
 #include "SkTypeface.h"
 #include "GraphicsJNI.h"
-#include <ScopedPrimitiveArray.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/android_util_AssetManager.h>
 #include <androidfw/AssetManager.h>
diff --git a/core/jni/android/graphics/Graphics.cpp b/core/jni/android/graphics/Graphics.cpp
index b936432..7c75ff4 100644
--- a/core/jni/android/graphics/Graphics.cpp
+++ b/core/jni/android/graphics/Graphics.cpp
@@ -4,7 +4,7 @@
 #include <sys/mman.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "GraphicsJNI.h"
 #include "core_jni_helpers.h"
 
diff --git a/core/jni/android/graphics/Movie.cpp b/core/jni/android/graphics/Movie.cpp
index 776ed66..b243817 100644
--- a/core/jni/android/graphics/Movie.cpp
+++ b/core/jni/android/graphics/Movie.cpp
@@ -1,6 +1,6 @@
 #include "CreateJavaOutputStreamAdaptor.h"
 #include "GraphicsJNI.h"
-#include "ScopedLocalRef.h"
+#include <nativehelper/ScopedLocalRef.h>
 #include "SkFrontBufferedStream.h"
 #include "Movie.h"
 #include "SkStream.h"
diff --git a/core/jni/android/graphics/NinePatch.cpp b/core/jni/android/graphics/NinePatch.cpp
index 116800a..460a0d7 100644
--- a/core/jni/android/graphics/NinePatch.cpp
+++ b/core/jni/android/graphics/NinePatch.cpp
@@ -31,7 +31,7 @@
 #include "GraphicsJNI.h"
 #include "NinePatchUtils.h"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 using namespace android;
diff --git a/core/jni/android/graphics/Paint.cpp b/core/jni/android/graphics/Paint.cpp
index 3ecbcc3..7c7a1c7 100644
--- a/core/jni/android/graphics/Paint.cpp
+++ b/core/jni/android/graphics/Paint.cpp
@@ -22,8 +22,8 @@
 #include "jni.h"
 #include "GraphicsJNI.h"
 #include "core_jni_helpers.h"
-#include <ScopedStringChars.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedStringChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 #include "SkBlurDrawLooper.h"
 #include "SkColorFilter.h"
diff --git a/core/jni/android/graphics/Typeface.cpp b/core/jni/android/graphics/Typeface.cpp
index eb2ca5d..e4540c0 100644
--- a/core/jni/android/graphics/Typeface.cpp
+++ b/core/jni/android/graphics/Typeface.cpp
@@ -19,7 +19,7 @@
 
 #include "FontUtils.h"
 #include "GraphicsJNI.h"
-#include "ScopedPrimitiveArray.h"
+#include <nativehelper/ScopedPrimitiveArray.h>
 #include "SkTypeface.h"
 #include <android_runtime/android_util_AssetManager.h>
 #include <androidfw/AssetManager.h>
diff --git a/core/jni/android/graphics/pdf/PdfEditor.cpp b/core/jni/android/graphics/pdf/PdfEditor.cpp
index c727519..e75712c 100644
--- a/core/jni/android/graphics/pdf/PdfEditor.cpp
+++ b/core/jni/android/graphics/pdf/PdfEditor.cpp
@@ -26,7 +26,7 @@
 #include "PdfUtils.h"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #pragma GCC diagnostic push
 #pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor"
diff --git a/core/jni/android/graphics/pdf/PdfRenderer.cpp b/core/jni/android/graphics/pdf/PdfRenderer.cpp
index 33bbdc4..95cdbb5 100644
--- a/core/jni/android/graphics/pdf/PdfRenderer.cpp
+++ b/core/jni/android/graphics/pdf/PdfRenderer.cpp
@@ -17,7 +17,7 @@
 #include "PdfUtils.h"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "GraphicsJNI.h"
 #include "SkBitmap.h"
 #include "SkMatrix.h"
diff --git a/core/jni/android/opengl/util.cpp b/core/jni/android/opengl/util.cpp
index 0573937..1522c20 100644
--- a/core/jni/android/opengl/util.cpp
+++ b/core/jni/android/opengl/util.cpp
@@ -15,7 +15,7 @@
  */
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "GraphicsJNI.h"
 
 #include <math.h>
diff --git a/core/jni/android_app_NativeActivity.cpp b/core/jni/android_app_NativeActivity.cpp
index ee74ef0..18f3177 100644
--- a/core/jni/android_app_NativeActivity.cpp
+++ b/core/jni/android_app_NativeActivity.cpp
@@ -35,7 +35,7 @@
 
 #include <utils/Looper.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_os_MessageQueue.h"
 #include "android_view_InputChannel.h"
 #include "android_view_KeyEvent.h"
@@ -45,7 +45,7 @@
 
 #include "core_jni_helpers.h"
 
-#include "ScopedUtfChars.h"
+#include <nativehelper/ScopedUtfChars.h>
 
 #define LOG_TRACE(...)
 //#define LOG_TRACE(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
diff --git a/core/jni/android_app_admin_SecurityLog.cpp b/core/jni/android_app_admin_SecurityLog.cpp
index e8ca793..5c45b4b 100644
--- a/core/jni/android_app_admin_SecurityLog.cpp
+++ b/core/jni/android_app_admin_SecurityLog.cpp
@@ -16,7 +16,7 @@
 
 #include <fcntl.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 #include "jni.h"
 #include <private/android_logger.h>
diff --git a/core/jni/android_app_backup_FullBackup.cpp b/core/jni/android_app_backup_FullBackup.cpp
index 63b2e2a..3e39989 100644
--- a/core/jni/android_app_backup_FullBackup.cpp
+++ b/core/jni/android_app_backup_FullBackup.cpp
@@ -20,7 +20,7 @@
 #include <utils/Log.h>
 #include <utils/String8.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 
 #include <androidfw/BackupHelpers.h>
diff --git a/core/jni/android_backup_BackupDataInput.cpp b/core/jni/android_backup_BackupDataInput.cpp
index 096a784..aa8acc16 100644
--- a/core/jni/android_backup_BackupDataInput.cpp
+++ b/core/jni/android_backup_BackupDataInput.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "FileBackupHelper_native"
 #include <utils/Log.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 
 #include <androidfw/BackupHelpers.h>
diff --git a/core/jni/android_backup_BackupDataOutput.cpp b/core/jni/android_backup_BackupDataOutput.cpp
index a7894f4..4f5d1f80 100644
--- a/core/jni/android_backup_BackupDataOutput.cpp
+++ b/core/jni/android_backup_BackupDataOutput.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "FileBackupHelper_native"
 #include <utils/Log.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <androidfw/BackupHelpers.h>
diff --git a/core/jni/android_backup_BackupHelperDispatcher.cpp b/core/jni/android_backup_BackupHelperDispatcher.cpp
index 80bdaf8..fac7eba 100644
--- a/core/jni/android_backup_BackupHelperDispatcher.cpp
+++ b/core/jni/android_backup_BackupHelperDispatcher.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "BackupHelperDispatcher_native"
 #include <utils/Log.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 
 #include <sys/types.h>
diff --git a/core/jni/android_backup_FileBackupHelperBase.cpp b/core/jni/android_backup_FileBackupHelperBase.cpp
index 6d6ac1b..65840ee 100644
--- a/core/jni/android_backup_FileBackupHelperBase.cpp
+++ b/core/jni/android_backup_FileBackupHelperBase.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "FileBackupHelper_native"
 #include <utils/Log.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <androidfw/BackupHelpers.h>
diff --git a/core/jni/android_content_res_ObbScanner.cpp b/core/jni/android_content_res_ObbScanner.cpp
index 36d78cf..de429a0 100644
--- a/core/jni/android_content_res_ObbScanner.cpp
+++ b/core/jni/android_content_res_ObbScanner.cpp
@@ -21,7 +21,7 @@
 #include <androidfw/ObbFile.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "utils/misc.h"
 #include "android_runtime/AndroidRuntime.h"
 
diff --git a/core/jni/android_database_CursorWindow.cpp b/core/jni/android_database_CursorWindow.cpp
index f1fa76a..0d09b56 100644
--- a/core/jni/android_database_CursorWindow.cpp
+++ b/core/jni/android_database_CursorWindow.cpp
@@ -20,7 +20,7 @@
 
 #include <inttypes.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 
 #include <utils/Log.h>
diff --git a/core/jni/android_database_SQLiteCommon.h b/core/jni/android_database_SQLiteCommon.h
index 0cac176..81164ef 100644
--- a/core/jni/android_database_SQLiteCommon.h
+++ b/core/jni/android_database_SQLiteCommon.h
@@ -18,7 +18,7 @@
 #define _ANDROID_DATABASE_SQLITE_COMMON_H
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #include <sqlite3.h>
 
diff --git a/core/jni/android_database_SQLiteConnection.cpp b/core/jni/android_database_SQLiteConnection.cpp
index 62240ea..c3f9bf7 100644
--- a/core/jni/android_database_SQLiteConnection.cpp
+++ b/core/jni/android_database_SQLiteConnection.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "SQLiteConnection"
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/Log.h>
 
diff --git a/core/jni/android_database_SQLiteDebug.cpp b/core/jni/android_database_SQLiteDebug.cpp
index 4e4c36c..3ba9b91 100644
--- a/core/jni/android_database_SQLiteDebug.cpp
+++ b/core/jni/android_database_SQLiteDebug.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "SQLiteDebug"
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 
 #include <stdio.h>
diff --git a/core/jni/android_database_SQLiteGlobal.cpp b/core/jni/android_database_SQLiteGlobal.cpp
index 03e2387..ec5dc4a 100644
--- a/core/jni/android_database_SQLiteGlobal.cpp
+++ b/core/jni/android_database_SQLiteGlobal.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "SQLiteGlobal"
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <sqlite3.h>
diff --git a/core/jni/android_ddm_DdmHandleNativeHeap.cpp b/core/jni/android_ddm_DdmHandleNativeHeap.cpp
index 3e7a04e..2f25d8f 100644
--- a/core/jni/android_ddm_DdmHandleNativeHeap.cpp
+++ b/core/jni/android_ddm_DdmHandleNativeHeap.cpp
@@ -18,7 +18,7 @@
 #undef LOG_TAG
 #define LOG_TAG "DdmHandleNativeHeap"
 
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <jni.h>
 #include "core_jni_helpers.h"
 
diff --git a/core/jni/android_hardware_Camera.cpp b/core/jni/android_hardware_Camera.cpp
index d606c2d..d6f8dc4 100644
--- a/core/jni/android_hardware_Camera.cpp
+++ b/core/jni/android_hardware_Camera.cpp
@@ -20,7 +20,7 @@
 #include <utils/Log.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 #include <android_runtime/android_graphics_SurfaceTexture.h>
 #include <android_runtime/android_view_Surface.h>
diff --git a/core/jni/android_hardware_SensorManager.cpp b/core/jni/android_hardware_SensorManager.cpp
index e90a41c..5b327d4 100644
--- a/core/jni/android_hardware_SensorManager.cpp
+++ b/core/jni/android_hardware_SensorManager.cpp
@@ -15,13 +15,13 @@
  */
 #define LOG_TAG "SensorManager"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_os_MessageQueue.h"
 #include "core_jni_helpers.h"
 #include "jni.h"
 
-#include <ScopedUtfChars.h>
-#include <ScopedLocalRef.h>
+#include <nativehelper/ScopedUtfChars.h>
+#include <nativehelper/ScopedLocalRef.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/android_hardware_HardwareBuffer.h>
 #include <vndk/hardware_buffer.h>
diff --git a/core/jni/android_hardware_SerialPort.cpp b/core/jni/android_hardware_SerialPort.cpp
index 393dc7b..190ddce 100644
--- a/core/jni/android_hardware_SerialPort.cpp
+++ b/core/jni/android_hardware_SerialPort.cpp
@@ -19,7 +19,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <stdio.h>
diff --git a/core/jni/android_hardware_SoundTrigger.cpp b/core/jni/android_hardware_SoundTrigger.cpp
index 0c7f5a1..9dbb8d7 100644
--- a/core/jni/android_hardware_SoundTrigger.cpp
+++ b/core/jni/android_hardware_SoundTrigger.cpp
@@ -20,7 +20,7 @@
 #include <utils/Log.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 #include <system/sound_trigger.h>
 #include <soundtrigger/SoundTriggerCallback.h>
diff --git a/core/jni/android_hardware_UsbDevice.cpp b/core/jni/android_hardware_UsbDevice.cpp
index 89d33e2..879d409 100644
--- a/core/jni/android_hardware_UsbDevice.cpp
+++ b/core/jni/android_hardware_UsbDevice.cpp
@@ -19,7 +19,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <usbhost/usbhost.h>
diff --git a/core/jni/android_hardware_UsbDeviceConnection.cpp b/core/jni/android_hardware_UsbDeviceConnection.cpp
index ba08bce..d953aee 100644
--- a/core/jni/android_hardware_UsbDeviceConnection.cpp
+++ b/core/jni/android_hardware_UsbDeviceConnection.cpp
@@ -19,7 +19,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <usbhost/usbhost.h>
diff --git a/core/jni/android_hardware_UsbRequest.cpp b/core/jni/android_hardware_UsbRequest.cpp
index 01fe078..9bdb605 100644
--- a/core/jni/android_hardware_UsbRequest.cpp
+++ b/core/jni/android_hardware_UsbRequest.cpp
@@ -19,7 +19,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <usbhost/usbhost.h>
diff --git a/core/jni/android_hardware_camera2_CameraMetadata.cpp b/core/jni/android_hardware_camera2_CameraMetadata.cpp
index d8eb7d2..fad5b0e 100644
--- a/core/jni/android_hardware_camera2_CameraMetadata.cpp
+++ b/core/jni/android_hardware_camera2_CameraMetadata.cpp
@@ -28,7 +28,7 @@
 #include <vector>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_os_Parcel.h"
 #include "core_jni_helpers.h"
 #include "android_runtime/android_hardware_camera2_CameraMetadata.h"
diff --git a/core/jni/android_hardware_camera2_DngCreator.cpp b/core/jni/android_hardware_camera2_DngCreator.cpp
index 3d021d6..c8eef7f 100644
--- a/core/jni/android_hardware_camera2_DngCreator.cpp
+++ b/core/jni/android_hardware_camera2_DngCreator.cpp
@@ -46,7 +46,7 @@
 #include "android_runtime/android_hardware_camera2_CameraMetadata.h"
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 using namespace android;
 using namespace img_utils;
diff --git a/core/jni/android_hardware_camera2_legacy_LegacyCameraDevice.cpp b/core/jni/android_hardware_camera2_legacy_LegacyCameraDevice.cpp
index 7121194..863ca8b 100644
--- a/core/jni/android_hardware_camera2_legacy_LegacyCameraDevice.cpp
+++ b/core/jni/android_hardware_camera2_legacy_LegacyCameraDevice.cpp
@@ -22,7 +22,7 @@
 #include <camera/CameraUtils.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 #include "android_runtime/android_view_Surface.h"
 #include "android_runtime/android_graphics_SurfaceTexture.h"
diff --git a/core/jni/android_hardware_camera2_legacy_PerfMeasurement.cpp b/core/jni/android_hardware_camera2_legacy_PerfMeasurement.cpp
index a081665..fac243a 100644
--- a/core/jni/android_hardware_camera2_legacy_PerfMeasurement.cpp
+++ b/core/jni/android_hardware_camera2_legacy_PerfMeasurement.cpp
@@ -21,7 +21,7 @@
 #include <utils/Vector.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <ui/GraphicBuffer.h>
diff --git a/core/jni/android_hardware_location_ActivityRecognitionHardware.cpp b/core/jni/android_hardware_location_ActivityRecognitionHardware.cpp
index 637234f..1c9ab94 100644
--- a/core/jni/android_hardware_location_ActivityRecognitionHardware.cpp
+++ b/core/jni/android_hardware_location_ActivityRecognitionHardware.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "ActivityRecognitionHardware"
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/Log.h>
diff --git a/core/jni/android_media_AudioRecord.cpp b/core/jni/android_media_AudioRecord.cpp
index 5e93fc9..e4da3c6 100644
--- a/core/jni/android_media_AudioRecord.cpp
+++ b/core/jni/android_media_AudioRecord.cpp
@@ -20,13 +20,13 @@
 
 #include <inttypes.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <utils/Log.h>
 #include <media/AudioRecord.h>
 
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 #include "android_media_AudioFormat.h"
 #include "android_media_AudioErrors.h"
diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp
index e8f6074..7ec68ed 100644
--- a/core/jni/android_media_AudioSystem.cpp
+++ b/core/jni/android_media_AudioSystem.cpp
@@ -22,7 +22,7 @@
 
 #include <sstream>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <media/AudioSystem.h>
diff --git a/core/jni/android_media_AudioTrack.cpp b/core/jni/android_media_AudioTrack.cpp
index 3e9ffce..c7ed599 100644
--- a/core/jni/android_media_AudioTrack.cpp
+++ b/core/jni/android_media_AudioTrack.cpp
@@ -19,11 +19,11 @@
 
 #include "android_media_AudioTrack.h"
 
-#include <JNIHelp.h>
-#include <JniConstants.h>
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JniConstants.h>
 #include "core_jni_helpers.h"
 
-#include "ScopedBytes.h"
+#include <nativehelper/ScopedBytes.h>
 
 #include <utils/Log.h>
 #include <media/AudioSystem.h>
diff --git a/core/jni/android_media_DeviceCallback.cpp b/core/jni/android_media_DeviceCallback.cpp
index e159373..108fa00 100644
--- a/core/jni/android_media_DeviceCallback.cpp
+++ b/core/jni/android_media_DeviceCallback.cpp
@@ -19,8 +19,8 @@
 #define LOG_TAG "AudioDeviceCallback-JNI"
 
 #include <utils/Log.h>
-#include <JNIHelp.h>
-#include <JniConstants.h>
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JniConstants.h>
 #include "core_jni_helpers.h"
 #include <media/AudioSystem.h>
 
diff --git a/core/jni/android_media_JetPlayer.cpp b/core/jni/android_media_JetPlayer.cpp
index 873c3f2..da116bf 100644
--- a/core/jni/android_media_JetPlayer.cpp
+++ b/core/jni/android_media_JetPlayer.cpp
@@ -23,7 +23,7 @@
 #include <fcntl.h>
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <utils/Log.h>
diff --git a/core/jni/android_media_RemoteDisplay.cpp b/core/jni/android_media_RemoteDisplay.cpp
index bd1a6ec..3b517f1 100644
--- a/core/jni/android_media_RemoteDisplay.cpp
+++ b/core/jni/android_media_RemoteDisplay.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "RemoteDisplay"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include "android_os_Parcel.h"
 #include "android_util_Binder.h"
@@ -36,7 +36,7 @@
 
 #include <utils/Log.h>
 
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 namespace android {
 
diff --git a/core/jni/android_media_ToneGenerator.cpp b/core/jni/android_media_ToneGenerator.cpp
index aec6263..ecb3cd6 100644
--- a/core/jni/android_media_ToneGenerator.cpp
+++ b/core/jni/android_media_ToneGenerator.cpp
@@ -22,7 +22,7 @@
 #include <fcntl.h>
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <utils/Log.h>
diff --git a/core/jni/android_net_LocalSocketImpl.cpp b/core/jni/android_net_LocalSocketImpl.cpp
index 37b6df1..6df23f7 100644
--- a/core/jni/android_net_LocalSocketImpl.cpp
+++ b/core/jni/android_net_LocalSocketImpl.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "LocalSocketImpl"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 #include "utils/Log.h"
 #include "utils/misc.h"
@@ -35,7 +35,7 @@
 
 #include <cutils/sockets.h>
 #include <netinet/tcp.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 namespace android {
 
diff --git a/core/jni/android_net_NetUtils.cpp b/core/jni/android_net_NetUtils.cpp
index 3e99521..823f1cc 100644
--- a/core/jni/android_net_NetUtils.cpp
+++ b/core/jni/android_net_NetUtils.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "NetUtils"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "NetdClient.h"
 #include <utils/misc.h>
 #include <android_runtime/AndroidRuntime.h>
diff --git a/core/jni/android_net_TrafficStats.cpp b/core/jni/android_net_TrafficStats.cpp
index 7b7d0cf..d0c237d 100644
--- a/core/jni/android_net_TrafficStats.cpp
+++ b/core/jni/android_net_TrafficStats.cpp
@@ -25,7 +25,7 @@
 
 #include "core_jni_helpers.h"
 #include <jni.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include <utils/misc.h>
 #include <utils/Log.h>
 
diff --git a/core/jni/android_opengl_EGL14.cpp b/core/jni/android_opengl_EGL14.cpp
index c8b1784..6163588 100644
--- a/core/jni/android_opengl_EGL14.cpp
+++ b/core/jni/android_opengl_EGL14.cpp
@@ -21,7 +21,7 @@
 #pragma GCC diagnostic ignored "-Wunused-function"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/android_view_Surface.h>
 #include <android_runtime/android_graphics_SurfaceTexture.h>
diff --git a/core/jni/android_opengl_EGLExt.cpp b/core/jni/android_opengl_EGLExt.cpp
index 62ccad4..df1aa20 100644
--- a/core/jni/android_opengl_EGLExt.cpp
+++ b/core/jni/android_opengl_EGLExt.cpp
@@ -21,7 +21,7 @@
 #pragma GCC diagnostic ignored "-Wunused-function"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/android_view_Surface.h>
 #include <android_runtime/android_graphics_SurfaceTexture.h>
diff --git a/core/jni/android_opengl_GLES10.cpp b/core/jni/android_opengl_GLES10.cpp
index 5bcb800..6d4f6ec 100644
--- a/core/jni/android_opengl_GLES10.cpp
+++ b/core/jni/android_opengl_GLES10.cpp
@@ -25,7 +25,7 @@
 #include <GLES/glext.h>
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES10Ext.cpp b/core/jni/android_opengl_GLES10Ext.cpp
index 38f7ba6..e630cfca 100644
--- a/core/jni/android_opengl_GLES10Ext.cpp
+++ b/core/jni/android_opengl_GLES10Ext.cpp
@@ -25,7 +25,7 @@
 #include <GLES/glext.h>
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES11.cpp b/core/jni/android_opengl_GLES11.cpp
index 014672d..ab9cbb1 100644
--- a/core/jni/android_opengl_GLES11.cpp
+++ b/core/jni/android_opengl_GLES11.cpp
@@ -25,7 +25,7 @@
 #include <GLES/glext.h>
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES11Ext.cpp b/core/jni/android_opengl_GLES11Ext.cpp
index b4a1ab6..8f71a6d 100644
--- a/core/jni/android_opengl_GLES11Ext.cpp
+++ b/core/jni/android_opengl_GLES11Ext.cpp
@@ -25,7 +25,7 @@
 #include <GLES/glext.h>
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES20.cpp b/core/jni/android_opengl_GLES20.cpp
index c1ffa81..f83d204 100644
--- a/core/jni/android_opengl_GLES20.cpp
+++ b/core/jni/android_opengl_GLES20.cpp
@@ -25,7 +25,7 @@
 #include <GLES2/gl2ext.h>
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES30.cpp b/core/jni/android_opengl_GLES30.cpp
index 1d12b0a..b649daf 100644
--- a/core/jni/android_opengl_GLES30.cpp
+++ b/core/jni/android_opengl_GLES30.cpp
@@ -25,7 +25,7 @@
 #include <GLES3/gl3ext.h>
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES31.cpp b/core/jni/android_opengl_GLES31.cpp
index e0750e4..07d920f 100644
--- a/core/jni/android_opengl_GLES31.cpp
+++ b/core/jni/android_opengl_GLES31.cpp
@@ -23,7 +23,7 @@
 #include <stdint.h>
 #include <GLES3/gl31.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES31Ext.cpp b/core/jni/android_opengl_GLES31Ext.cpp
index 8212eb1..723dd4c 100644
--- a/core/jni/android_opengl_GLES31Ext.cpp
+++ b/core/jni/android_opengl_GLES31Ext.cpp
@@ -24,7 +24,7 @@
 #include <GLES2/gl2ext.h>
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES32.cpp b/core/jni/android_opengl_GLES32.cpp
index 91b573b..62a6e6c 100644
--- a/core/jni/android_opengl_GLES32.cpp
+++ b/core/jni/android_opengl_GLES32.cpp
@@ -23,7 +23,7 @@
 #include <stdint.h>
 #include <GLES3/gl32.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_os_HwBinder.cpp b/core/jni/android_os_HwBinder.cpp
index 5663125..8106320 100644
--- a/core/jni/android_os_HwBinder.cpp
+++ b/core/jni/android_os_HwBinder.cpp
@@ -25,7 +25,7 @@
 
 #include <cstring>
 
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android/hidl/manager/1.0/IServiceManager.h>
 #include <android/hidl/base/1.0/IBase.h>
 #include <android/hidl/base/1.0/BpHwBase.h>
diff --git a/core/jni/android_os_HwBlob.cpp b/core/jni/android_os_HwBlob.cpp
index 8590ecf..0c23797 100644
--- a/core/jni/android_os_HwBlob.cpp
+++ b/core/jni/android_os_HwBlob.cpp
@@ -22,7 +22,7 @@
 
 #include "android_os_HwParcel.h"
 
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <hidl/Status.h>
 #include <nativehelper/ScopedLocalRef.h>
diff --git a/core/jni/android_os_HwParcel.cpp b/core/jni/android_os_HwParcel.cpp
index 6ea809a..b412b6a 100644
--- a/core/jni/android_os_HwParcel.cpp
+++ b/core/jni/android_os_HwParcel.cpp
@@ -24,7 +24,7 @@
 #include "android_os_HwBlob.h"
 #include "android_os_HwRemoteBinder.h"
 
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <hidl/HidlTransportSupport.h>
 #include <hidl/Status.h>
diff --git a/core/jni/android_os_HwRemoteBinder.cpp b/core/jni/android_os_HwRemoteBinder.cpp
index 9c2ee9c..cf59a56a 100644
--- a/core/jni/android_os_HwRemoteBinder.cpp
+++ b/core/jni/android_os_HwRemoteBinder.cpp
@@ -22,10 +22,10 @@
 
 #include "android_os_HwParcel.h"
 
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <hidl/Status.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include <nativehelper/ScopedLocalRef.h>
 
 #include "core_jni_helpers.h"
diff --git a/core/jni/android_os_MemoryFile.cpp b/core/jni/android_os_MemoryFile.cpp
index fdc9f9d..b21566b 100644
--- a/core/jni/android_os_MemoryFile.cpp
+++ b/core/jni/android_os_MemoryFile.cpp
@@ -19,7 +19,7 @@
 
 #include <cutils/ashmem.h>
 #include "core_jni_helpers.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <unistd.h>
 #include <sys/mman.h>
 
diff --git a/core/jni/android_os_MessageQueue.cpp b/core/jni/android_os_MessageQueue.cpp
index e57a719..f7a98d1 100644
--- a/core/jni/android_os_MessageQueue.cpp
+++ b/core/jni/android_os_MessageQueue.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "MessageQueue-JNI"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 
 #include <utils/Looper.h>
diff --git a/core/jni/android_os_Parcel.cpp b/core/jni/android_os_Parcel.cpp
index d35ddd0..f0ac79a 100644
--- a/core/jni/android_os_Parcel.cpp
+++ b/core/jni/android_os_Parcel.cpp
@@ -20,7 +20,7 @@
 #include "android_os_Parcel.h"
 #include "android_util_Binder.h"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <fcntl.h>
 #include <stdio.h>
@@ -41,8 +41,8 @@
 #include <utils/threads.h>
 #include <utils/String8.h>
 
-#include <ScopedUtfChars.h>
-#include <ScopedLocalRef.h>
+#include <nativehelper/ScopedUtfChars.h>
+#include <nativehelper/ScopedLocalRef.h>
 
 #include <android_runtime/AndroidRuntime.h>
 
diff --git a/core/jni/android_os_SELinux.cpp b/core/jni/android_os_SELinux.cpp
index 4b68c0d..6778b29 100644
--- a/core/jni/android_os_SELinux.cpp
+++ b/core/jni/android_os_SELinux.cpp
@@ -17,15 +17,15 @@
 #define LOG_TAG "SELinuxJNI"
 #include <utils/Log.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 #include "core_jni_helpers.h"
 #include "selinux/selinux.h"
 #include "selinux/android.h"
 #include <errno.h>
 #include <memory>
-#include <ScopedLocalRef.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedLocalRef.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 namespace android {
 
diff --git a/core/jni/android_os_SystemClock.cpp b/core/jni/android_os_SystemClock.cpp
index 2fade69..1f000d7 100644
--- a/core/jni/android_os_SystemClock.cpp
+++ b/core/jni/android_os_SystemClock.cpp
@@ -25,7 +25,7 @@
 #include <errno.h>
 #include <string.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 #include "core_jni_helpers.h"
 
diff --git a/core/jni/android_os_Trace.cpp b/core/jni/android_os_Trace.cpp
index de91f70..4f4e5da 100644
--- a/core/jni/android_os_Trace.cpp
+++ b/core/jni/android_os_Trace.cpp
@@ -23,9 +23,9 @@
 #include <utils/String8.h>
 #include <log/log.h>
 
-#include <JNIHelp.h>
-#include <ScopedUtfChars.h>
-#include <ScopedStringChars.h>
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedUtfChars.h>
+#include <nativehelper/ScopedStringChars.h>
 
 namespace android {
 
diff --git a/core/jni/android_os_UEventObserver.cpp b/core/jni/android_os_UEventObserver.cpp
index 30d40a2..2df74b0 100644
--- a/core/jni/android_os_UEventObserver.cpp
+++ b/core/jni/android_os_UEventObserver.cpp
@@ -21,13 +21,13 @@
 
 #include "hardware_legacy/uevent.h"
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 #include <utils/Mutex.h>
 #include <utils/Vector.h>
 #include <utils/String8.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 namespace android {
 
diff --git a/core/jni/android_os_VintfObject.cpp b/core/jni/android_os_VintfObject.cpp
index 8b4cc91..7ec4b8e 100644
--- a/core/jni/android_os_VintfObject.cpp
+++ b/core/jni/android_os_VintfObject.cpp
@@ -21,7 +21,7 @@
 #include <vector>
 #include <string>
 
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <vintf/VintfObject.h>
 #include <vintf/parse_string.h>
 #include <vintf/parse_xml.h>
diff --git a/core/jni/android_os_VintfRuntimeInfo.cpp b/core/jni/android_os_VintfRuntimeInfo.cpp
index ecb6854..19220cf0 100644
--- a/core/jni/android_os_VintfRuntimeInfo.cpp
+++ b/core/jni/android_os_VintfRuntimeInfo.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "VintfRuntimeInfo"
 //#define LOG_NDEBUG 0
 
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <vintf/VintfObject.h>
 #include <vintf/parse_string.h>
 #include <vintf/parse_xml.h>
diff --git a/core/jni/android_os_seccomp.cpp b/core/jni/android_os_seccomp.cpp
index 4502371..06e2a16 100644
--- a/core/jni/android_os_seccomp.cpp
+++ b/core/jni/android_os_seccomp.cpp
@@ -15,7 +15,7 @@
  */
 
 #include "core_jni_helpers.h"
-#include "JniConstants.h"
+#include <nativehelper/JniConstants.h>
 #include "utils/Log.h"
 #include <selinux/selinux.h>
 
diff --git a/core/jni/android_server_NetworkManagementSocketTagger.cpp b/core/jni/android_server_NetworkManagementSocketTagger.cpp
index 818bf53..58295af 100644
--- a/core/jni/android_server_NetworkManagementSocketTagger.cpp
+++ b/core/jni/android_server_NetworkManagementSocketTagger.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "NMST_QTagUidNative"
 #include <utils/Log.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include "jni.h"
 #include <utils/misc.h>
diff --git a/core/jni/android_server_Watchdog.cpp b/core/jni/android_server_Watchdog.cpp
index d1f9434..01d565b 100644
--- a/core/jni/android_server_Watchdog.cpp
+++ b/core/jni/android_server_Watchdog.cpp
@@ -25,7 +25,7 @@
 #include <errno.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 
 static void dumpOneStack(int tid, int outFd) {
diff --git a/core/jni/android_text_AndroidBidi.cpp b/core/jni/android_text_AndroidBidi.cpp
index 8b71572..f72f0f0 100644
--- a/core/jni/android_text_AndroidBidi.cpp
+++ b/core/jni/android_text_AndroidBidi.cpp
@@ -17,7 +17,7 @@
 
 #define LOG_TAG "AndroidUnicode"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 #include "utils/misc.h"
 #include "utils/Log.h"
diff --git a/core/jni/android_text_AndroidCharacter.cpp b/core/jni/android_text_AndroidCharacter.cpp
index 474a74e..8885aac 100644
--- a/core/jni/android_text_AndroidCharacter.cpp
+++ b/core/jni/android_text_AndroidCharacter.cpp
@@ -17,8 +17,8 @@
 
 #define LOG_TAG "AndroidUnicode"
 
-#include "JNIHelp.h"
-#include "ScopedPrimitiveArray.h"
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
 #include "core_jni_helpers.h"
 #include "utils/misc.h"
 #include "utils/Log.h"
diff --git a/core/jni/android_text_StaticLayout.cpp b/core/jni/android_text_StaticLayout.cpp
index d81bc2f..ba8dec1 100644
--- a/core/jni/android_text_StaticLayout.cpp
+++ b/core/jni/android_text_StaticLayout.cpp
@@ -21,9 +21,9 @@
 #include "unicode/brkiter.h"
 #include "utils/misc.h"
 #include "utils/Log.h"
-#include "ScopedStringChars.h"
-#include "ScopedPrimitiveArray.h"
-#include "JNIHelp.h"
+#include <nativehelper/ScopedStringChars.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 #include <cstdint>
 #include <vector>
diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp
index 90aee9e..b137da3 100644
--- a/core/jni/android_util_AssetManager.cpp
+++ b/core/jni/android_util_AssetManager.cpp
@@ -37,9 +37,9 @@
 #include "android_util_Binder.h"
 #include "core_jni_helpers.h"
 #include "jni.h"
-#include "JNIHelp.h"
-#include "ScopedStringChars.h"
-#include "ScopedUtfChars.h"
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedStringChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include "utils/Log.h"
 #include "utils/misc.h"
 #include "utils/String8.h"
diff --git a/core/jni/android_util_Binder.cpp b/core/jni/android_util_Binder.cpp
index e2aa17b..5b0f776 100644
--- a/core/jni/android_util_Binder.cpp
+++ b/core/jni/android_util_Binder.cpp
@@ -20,7 +20,7 @@
 #include "android_os_Parcel.h"
 #include "android_util_Binder.h"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <fcntl.h>
 #include <inttypes.h>
@@ -44,8 +44,8 @@
 #include <utils/SystemClock.h>
 #include <utils/threads.h>
 
-#include <ScopedUtfChars.h>
-#include <ScopedLocalRef.h>
+#include <nativehelper/ScopedUtfChars.h>
+#include <nativehelper/ScopedLocalRef.h>
 
 #include "core_jni_helpers.h"
 
diff --git a/core/jni/android_util_EventLog.cpp b/core/jni/android_util_EventLog.cpp
index 8a7600b..9fd7c40 100644
--- a/core/jni/android_util_EventLog.cpp
+++ b/core/jni/android_util_EventLog.cpp
@@ -20,7 +20,7 @@
 
 #include <log/log.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 #include "jni.h"
 
diff --git a/core/jni/android_util_FileObserver.cpp b/core/jni/android_util_FileObserver.cpp
index 2b93b6d..6f975b2 100644
--- a/core/jni/android_util_FileObserver.cpp
+++ b/core/jni/android_util_FileObserver.cpp
@@ -15,7 +15,7 @@
 ** limitations under the License.
 */
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 #include "utils/Log.h"
 #include "utils/misc.h"
diff --git a/core/jni/android_util_Log.cpp b/core/jni/android_util_Log.cpp
index 56505af..a6adc88 100644
--- a/core/jni/android_util_Log.cpp
+++ b/core/jni/android_util_Log.cpp
@@ -26,7 +26,7 @@
 #include <utils/String8.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "utils/misc.h"
 #include "core_jni_helpers.h"
 #include "android_util_Log.h"
diff --git a/core/jni/android_util_Log.h b/core/jni/android_util_Log.h
index 4804a854..8a32864 100644
--- a/core/jni/android_util_Log.h
+++ b/core/jni/android_util_Log.h
@@ -18,7 +18,7 @@
 #define _ANDROID_UTIL_LOG_H
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 
 namespace android {
diff --git a/core/jni/android_util_Process.cpp b/core/jni/android_util_Process.cpp
index f34b138..44f15cd 100644
--- a/core/jni/android_util_Process.cpp
+++ b/core/jni/android_util_Process.cpp
@@ -30,7 +30,7 @@
 #include "core_jni_helpers.h"
 
 #include "android_util_Binder.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <dirent.h>
 #include <fcntl.h>
diff --git a/core/jni/android_util_StringBlock.cpp b/core/jni/android_util_StringBlock.cpp
index b396afe..760f9e3 100644
--- a/core/jni/android_util_StringBlock.cpp
+++ b/core/jni/android_util_StringBlock.cpp
@@ -18,7 +18,7 @@
 #define LOG_TAG "StringBlock"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <utils/misc.h>
 #include <core_jni_helpers.h>
 #include <utils/Log.h>
diff --git a/core/jni/android_util_XmlBlock.cpp b/core/jni/android_util_XmlBlock.cpp
index 99882cc..ad6bad2 100644
--- a/core/jni/android_util_XmlBlock.cpp
+++ b/core/jni/android_util_XmlBlock.cpp
@@ -18,7 +18,7 @@
 #define LOG_TAG "XmlBlock"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <core_jni_helpers.h>
 #include <androidfw/AssetManager.h>
 #include <androidfw/ResourceTypes.h>
diff --git a/core/jni/android_util_jar_StrictJarFile.cpp b/core/jni/android_util_jar_StrictJarFile.cpp
index 4f1f926..4ab8db4 100644
--- a/core/jni/android_util_jar_StrictJarFile.cpp
+++ b/core/jni/android_util_jar_StrictJarFile.cpp
@@ -22,10 +22,10 @@
 
 #include <log/log.h>
 
-#include "JNIHelp.h"
-#include "JniConstants.h"
-#include "ScopedLocalRef.h"
-#include "ScopedUtfChars.h"
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JniConstants.h>
+#include <nativehelper/ScopedLocalRef.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include "jni.h"
 #include "ziparchive/zip_archive.h"
 
diff --git a/core/jni/android_view_DisplayEventReceiver.cpp b/core/jni/android_view_DisplayEventReceiver.cpp
index 831393b..c1b5aae 100644
--- a/core/jni/android_view_DisplayEventReceiver.cpp
+++ b/core/jni/android_view_DisplayEventReceiver.cpp
@@ -18,7 +18,7 @@
 
 //#define LOG_NDEBUG 0
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <inttypes.h>
 
@@ -30,7 +30,7 @@
 #include <gui/DisplayEventReceiver.h>
 #include "android_os_MessageQueue.h"
 
-#include <ScopedLocalRef.h>
+#include <nativehelper/ScopedLocalRef.h>
 
 #include "core_jni_helpers.h"
 
diff --git a/core/jni/android_view_InputChannel.cpp b/core/jni/android_view_InputChannel.cpp
index 1c6ead0..71742cb 100644
--- a/core/jni/android_view_InputChannel.cpp
+++ b/core/jni/android_view_InputChannel.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "InputChannel-JNI"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <android_runtime/AndroidRuntime.h>
 #include <binder/Parcel.h>
diff --git a/core/jni/android_view_InputDevice.cpp b/core/jni/android_view_InputDevice.cpp
index 4e6e512..494fad7 100644
--- a/core/jni/android_view_InputDevice.cpp
+++ b/core/jni/android_view_InputDevice.cpp
@@ -20,7 +20,7 @@
 #include <jni.h>
 #include <nativehelper/JNIHelp.h>
 
-#include <ScopedLocalRef.h>
+#include <nativehelper/ScopedLocalRef.h>
 
 #include "android_view_InputDevice.h"
 #include "android_view_KeyCharacterMap.h"
diff --git a/core/jni/android_view_InputEventReceiver.cpp b/core/jni/android_view_InputEventReceiver.cpp
index 8293cd8..31e954b 100644
--- a/core/jni/android_view_InputEventReceiver.cpp
+++ b/core/jni/android_view_InputEventReceiver.cpp
@@ -18,7 +18,7 @@
 
 //#define LOG_NDEBUG 0
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/Log.h>
@@ -31,7 +31,7 @@
 #include "android_view_KeyEvent.h"
 #include "android_view_MotionEvent.h"
 
-#include <ScopedLocalRef.h>
+#include <nativehelper/ScopedLocalRef.h>
 
 #include "core_jni_helpers.h"
 
diff --git a/core/jni/android_view_InputEventSender.cpp b/core/jni/android_view_InputEventSender.cpp
index 3bd6917..420ff2a 100644
--- a/core/jni/android_view_InputEventSender.cpp
+++ b/core/jni/android_view_InputEventSender.cpp
@@ -18,7 +18,7 @@
 
 //#define LOG_NDEBUG 0
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/Log.h>
@@ -31,7 +31,7 @@
 #include "android_view_KeyEvent.h"
 #include "android_view_MotionEvent.h"
 
-#include <ScopedLocalRef.h>
+#include <nativehelper/ScopedLocalRef.h>
 
 #include "core_jni_helpers.h"
 
diff --git a/core/jni/android_view_InputQueue.cpp b/core/jni/android_view_InputQueue.cpp
index 96ccdee..24c3ff8 100644
--- a/core/jni/android_view_InputQueue.cpp
+++ b/core/jni/android_view_InputQueue.cpp
@@ -26,9 +26,9 @@
 #include <input/Input.h>
 #include <utils/Looper.h>
 #include <utils/TypeHelpers.h>
-#include <ScopedLocalRef.h>
+#include <nativehelper/ScopedLocalRef.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_os_MessageQueue.h"
 #include "android_view_KeyEvent.h"
 #include "android_view_MotionEvent.h"
diff --git a/core/jni/android_view_KeyEvent.cpp b/core/jni/android_view_KeyEvent.cpp
index 216e6f6..8a6e745 100644
--- a/core/jni/android_view_KeyEvent.cpp
+++ b/core/jni/android_view_KeyEvent.cpp
@@ -16,13 +16,13 @@
 
 #define LOG_TAG "KeyEvent-JNI"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/Log.h>
 #include <utils/Log.h>
 #include <input/Input.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include "android_view_KeyEvent.h"
 
 #include "core_jni_helpers.h"
diff --git a/core/jni/android_view_MotionEvent.cpp b/core/jni/android_view_MotionEvent.cpp
index a9efb00..64bf0dc 100644
--- a/core/jni/android_view_MotionEvent.cpp
+++ b/core/jni/android_view_MotionEvent.cpp
@@ -16,14 +16,14 @@
 
 #define LOG_TAG "MotionEvent-JNI"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <SkMatrix.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/Log.h>
 #include <utils/Log.h>
 #include <input/Input.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include "android_os_Parcel.h"
 #include "android_view_MotionEvent.h"
 #include "android_util_Binder.h"
diff --git a/core/jni/android_view_PointerIcon.cpp b/core/jni/android_view_PointerIcon.cpp
index 4150636..4f79790 100644
--- a/core/jni/android_view_PointerIcon.cpp
+++ b/core/jni/android_view_PointerIcon.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "PointerIcon-JNI"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include "android_view_PointerIcon.h"
 
@@ -24,7 +24,7 @@
 #include <android_runtime/Log.h>
 #include <utils/Log.h>
 #include <android/graphics/GraphicsJNI.h>
-#include "ScopedLocalRef.h"
+#include <nativehelper/ScopedLocalRef.h>
 
 #include "core_jni_helpers.h"
 
diff --git a/core/jni/android_view_Surface.cpp b/core/jni/android_view_Surface.cpp
index 494e266..215a00e 100644
--- a/core/jni/android_view_Surface.cpp
+++ b/core/jni/android_view_Surface.cpp
@@ -19,7 +19,7 @@
 #include <stdio.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_os_Parcel.h"
 #include "android/graphics/GraphicBuffer.h"
 #include "android/graphics/GraphicsJNI.h"
@@ -47,7 +47,7 @@
 #include <utils/misc.h>
 #include <utils/Log.h>
 
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 #include <AnimationContext.h>
 #include <FrameInfo.h>
diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp
index 1df6b4a3..db9b52e 100644
--- a/core/jni/android_view_SurfaceControl.cpp
+++ b/core/jni/android_view_SurfaceControl.cpp
@@ -25,8 +25,8 @@
 #include "core_jni_helpers.h"
 
 #include <android-base/chrono_utils.h>
-#include <JNIHelp.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include <android_runtime/android_view_Surface.h>
 #include <android_runtime/android_view_SurfaceSession.h>
 #include <gui/Surface.h>
diff --git a/core/jni/android_view_SurfaceSession.cpp b/core/jni/android_view_SurfaceSession.cpp
index 508d897..30c0030 100644
--- a/core/jni/android_view_SurfaceSession.cpp
+++ b/core/jni/android_view_SurfaceSession.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "SurfaceSession"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/android_view_SurfaceSession.h>
diff --git a/core/jni/android_view_ThreadedRenderer.cpp b/core/jni/android_view_ThreadedRenderer.cpp
index 286c1a2..46b0a79 100644
--- a/core/jni/android_view_ThreadedRenderer.cpp
+++ b/core/jni/android_view_ThreadedRenderer.cpp
@@ -23,7 +23,7 @@
 #include <nativehelper/JNIHelp.h>
 #include "core_jni_helpers.h"
 #include <GraphicsJNI.h>
-#include <ScopedPrimitiveArray.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
 
 #include <gui/BufferItemConsumer.h>
 #include <gui/BufferQueue.h>
diff --git a/core/jni/android_view_VelocityTracker.cpp b/core/jni/android_view_VelocityTracker.cpp
index e1f2241..153789c 100644
--- a/core/jni/android_view_VelocityTracker.cpp
+++ b/core/jni/android_view_VelocityTracker.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "VelocityTracker-JNI"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/Log.h>
@@ -24,7 +24,7 @@
 #include <input/VelocityTracker.h>
 #include "android_view_MotionEvent.h"
 
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 #include "core_jni_helpers.h"
 
diff --git a/core/jni/com_android_internal_content_NativeLibraryHelper.cpp b/core/jni/com_android_internal_content_NativeLibraryHelper.cpp
index f8f9efe..fce5dd5 100644
--- a/core/jni/com_android_internal_content_NativeLibraryHelper.cpp
+++ b/core/jni/com_android_internal_content_NativeLibraryHelper.cpp
@@ -19,7 +19,7 @@
 
 #include "core_jni_helpers.h"
 
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include <androidfw/ZipFileRO.h>
 #include <androidfw/ZipUtils.h>
 #include <utils/Log.h>
diff --git a/core/jni/com_android_internal_net_NetworkStatsFactory.cpp b/core/jni/com_android_internal_net_NetworkStatsFactory.cpp
index 4a2b881..0cb6935 100644
--- a/core/jni/com_android_internal_net_NetworkStatsFactory.cpp
+++ b/core/jni/com_android_internal_net_NetworkStatsFactory.cpp
@@ -24,9 +24,9 @@
 #include <core_jni_helpers.h>
 #include <jni.h>
 
-#include <ScopedUtfChars.h>
-#include <ScopedLocalRef.h>
-#include <ScopedPrimitiveArray.h>
+#include <nativehelper/ScopedUtfChars.h>
+#include <nativehelper/ScopedLocalRef.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
 
 #include <utils/Log.h>
 #include <utils/misc.h>
diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index cb53106..3887c76 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -54,10 +54,10 @@
 #include <processgroup/processgroup.h>
 
 #include "core_jni_helpers.h"
-#include "JNIHelp.h"
-#include "ScopedLocalRef.h"
-#include "ScopedPrimitiveArray.h"
-#include "ScopedUtfChars.h"
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedLocalRef.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include "fd_utils.h"
 
 #include "nativebridge/native_bridge.h"
diff --git a/core/jni/com_google_android_gles_jni_EGLImpl.cpp b/core/jni/com_google_android_gles_jni_EGLImpl.cpp
index c00d698..940ac22 100644
--- a/core/jni/com_google_android_gles_jni_EGLImpl.cpp
+++ b/core/jni/com_google_android_gles_jni_EGLImpl.cpp
@@ -15,7 +15,7 @@
 ** limitations under the License.
 */
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/android_view_Surface.h>
 #include <android_runtime/android_graphics_SurfaceTexture.h>
diff --git a/core/jni/com_google_android_gles_jni_GLImpl.cpp b/core/jni/com_google_android_gles_jni_GLImpl.cpp
index eeb92fc..ac23eca 100644
--- a/core/jni/com_google_android_gles_jni_GLImpl.cpp
+++ b/core/jni/com_google_android_gles_jni_GLImpl.cpp
@@ -22,7 +22,7 @@
 #pragma GCC diagnostic ignored "-Wunused-function"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 
diff --git a/core/jni/core_jni_helpers.h b/core/jni/core_jni_helpers.h
index 3f169c3..1325b0c 100644
--- a/core/jni/core_jni_helpers.h
+++ b/core/jni/core_jni_helpers.h
@@ -17,7 +17,7 @@
 #ifndef CORE_JNI_HELPERS
 #define CORE_JNI_HELPERS
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 
 namespace android {
diff --git a/core/jni/include/android_runtime/android_view_InputQueue.h b/core/jni/include/android_runtime/android_view_InputQueue.h
index ed37b0a..ac8da58 100644
--- a/core/jni/include/android_runtime/android_view_InputQueue.h
+++ b/core/jni/include/android_runtime/android_view_InputQueue.h
@@ -22,7 +22,7 @@
 #include <utils/TypeHelpers.h>
 #include <utils/Vector.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 /*
  * Declare a concrete type for the NDK's AInputQueue forward declaration
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index c052e5145..8e88b67 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -562,6 +562,7 @@
         android:icon="@drawable/perm_group_contacts"
         android:label="@string/permgrouplab_contacts"
         android:description="@string/permgroupdesc_contacts"
+        android:request="@string/permgrouprequest_contacts"
         android:priority="100" />
 
     <!-- Allows an application to read the user's contacts data.
@@ -592,6 +593,7 @@
         android:icon="@drawable/perm_group_calendar"
         android:label="@string/permgrouplab_calendar"
         android:description="@string/permgroupdesc_calendar"
+        android:request="@string/permgrouprequest_calendar"
         android:priority="200" />
 
     <!-- Allows an application to read the user's calendar data.
@@ -622,6 +624,7 @@
         android:icon="@drawable/perm_group_sms"
         android:label="@string/permgrouplab_sms"
         android:description="@string/permgroupdesc_sms"
+        android:request="@string/permgrouprequest_sms"
         android:priority="300" />
 
     <!-- Allows an application to send SMS messages.
@@ -698,6 +701,7 @@
         android:icon="@drawable/perm_group_storage"
         android:label="@string/permgrouplab_storage"
         android:description="@string/permgroupdesc_storage"
+        android:request="@string/permgrouprequest_storage"
         android:priority="900" />
 
     <!-- Allows an application to read from external storage.
@@ -759,6 +763,7 @@
         android:icon="@drawable/perm_group_location"
         android:label="@string/permgrouplab_location"
         android:description="@string/permgroupdesc_location"
+        android:request="@string/permgrouprequest_location"
         android:priority="400" />
 
     <!-- Allows an app to access precise location.
@@ -791,6 +796,7 @@
         android:icon="@drawable/perm_group_phone_calls"
         android:label="@string/permgrouplab_phone"
         android:description="@string/permgroupdesc_phone"
+        android:request="@string/permgrouprequest_phone"
         android:priority="500" />
 
     <!-- Allows read only access to phone state, including the phone number of the device,
@@ -942,6 +948,7 @@
         android:icon="@drawable/perm_group_microphone"
         android:label="@string/permgrouplab_microphone"
         android:description="@string/permgroupdesc_microphone"
+        android:request="@string/permgrouprequest_microphone"
         android:priority="600" />
 
     <!-- Allows an application to record audio.
@@ -984,6 +991,7 @@
         android:icon="@drawable/perm_group_camera"
         android:label="@string/permgrouplab_camera"
         android:description="@string/permgroupdesc_camera"
+        android:request="@string/permgrouprequest_camera"
         android:priority="700" />
 
     <!-- Required to be able to access the camera device.
@@ -1013,6 +1021,7 @@
         android:icon="@drawable/perm_group_sensors"
         android:label="@string/permgrouplab_sensors"
         android:description="@string/permgroupdesc_sensors"
+        android:request="@string/permgrouprequest_sensors"
         android:priority="800" />
 
     <!-- Allows an application to access data from sensors that the user uses to
diff --git a/core/res/res/layout/notification_template_right_icon.xml b/core/res/res/layout/notification_template_right_icon.xml
index fbf7538..d379256 100644
--- a/core/res/res/layout/notification_template_right_icon.xml
+++ b/core/res/res/layout/notification_template_right_icon.xml
@@ -21,8 +21,8 @@
              android:layout_height="wrap_content"
              android:layout_gravity="top|end">
     <ImageView android:id="@+id/right_icon"
-               android:layout_width="40dp"
-               android:layout_height="40dp"
+               android:layout_width="@dimen/notification_right_icon_size"
+               android:layout_height="@dimen/notification_right_icon_size"
                android:layout_gravity="top|end"
                android:layout_marginTop="36dp"
                android:layout_marginEnd="@dimen/notification_content_margin_end"
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index dd840b0..2eecf6d 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -4677,9 +4677,11 @@
                  result to valid color values. Saturate(S + D) -->
             <enum name="add" value="16" />
         </attr>
-        <!-- Extra spacing between lines of text. -->
+        <!-- Extra spacing between lines of text. The value will not be applied for the last
+             line of text. -->
         <attr name="lineSpacingExtra" format="dimension" />
-        <!-- Extra spacing between lines of text, as a multiplier. -->
+        <!-- Extra spacing between lines of text, as a multiplier. The value will not be applied
+             for the last line of text.-->
         <attr name="lineSpacingMultiplier" format="float" />
         <!-- The number of times to repeat the marquee animation. Only applied if the
              TextView has marquee enabled. -->
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index 33f69b4..c2e9759 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -1527,6 +1527,7 @@
         <attr name="logo" />
         <attr name="permissionGroup" />
         <attr name="description" />
+        <attr name="request" />
         <attr name="protectionLevel" />
         <attr name="permissionFlags" />
     </declare-styleable>
@@ -1554,6 +1555,7 @@
         <attr name="banner" />
         <attr name="logo" />
         <attr name="description" />
+        <attr name="request" />
         <attr name="permissionGroupFlags" />
         <attr name="priority" />
     </declare-styleable>
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 7a19c3d..2fede7c 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -296,6 +296,11 @@
     <!-- Mask to use when checking skb mark defined in config_networkWakeupPacketMark above. -->
     <integer name="config_networkWakeupPacketMask">0</integer>
 
+    <!-- Whether the APF Filter in the device should filter out IEEE 802.3 Frames
+         Those frames are identified by the field Eth-type having values
+         less than 0x600 -->
+    <bool translatable="false" name="config_apfDrop802_3Frames">true</bool>
+
     <!-- Default value for ConnectivityManager.getMultipathPreference() on metered networks. Actual
          device behaviour is controlled by Settings.Global.NETWORK_METERED_MULTIPATH_PREFERENCE.
          This is the default value of that setting. -->
diff --git a/core/res/res/values/dimens.xml b/core/res/res/values/dimens.xml
index 9f9c883..743f4ad 100644
--- a/core/res/res/values/dimens.xml
+++ b/core/res/res/values/dimens.xml
@@ -580,6 +580,21 @@
     <dimen name="item_touch_helper_swipe_escape_velocity">120dp</dimen>
     <dimen name="item_touch_helper_swipe_escape_max_velocity">800dp</dimen>
 
+    <!-- The maximum height of any image in a remote view. This is applied to all images in custom remoteviews. This value is determined by the maximum notification height -->
+    <dimen name="notification_custom_view_max_image_height">284dp</dimen>
+    <!-- The maximum height of any image in a remote view. This is applied to all images in custom remoteviews. This value is determined a maximum notification width -->
+    <dimen name="notification_custom_view_max_image_width">450dp</dimen>
+    <!-- The maximum height of a big picture in a notification. The images will be reduced to that height in case they are bigger. This value is determined by the maximum notification height -->
+    <dimen name="notification_big_picture_max_height">284dp</dimen>
+    <!-- The maximum width of a big picture in a notification. The images will be reduced to that width in case they are bigger. This value is determined by the standard panel size -->
+    <dimen name="notification_big_picture_max_width">416dp</dimen>
+    <!-- The maximum height of a image in a media notification. The images will be reduced to that height in case they are bigger. This value is determined by the expanded media template-->
+    <dimen name="notification_media_image_max_height">140dp</dimen>
+    <!-- The maximum width of a image in a media notification. The images will be reduced to that width in case they are bigger.-->
+    <dimen name="notification_media_image_max_width">280dp</dimen>
+    <!-- The size of the right icon -->
+    <dimen name="notification_right_icon_size">40dp</dimen>
+
     <!-- Max width/height of the autofill data set picker as a fraction of the screen width/height -->
     <dimen name="autofill_dataset_picker_max_size">90%</dimen>
 
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 8c26db4..44f1264 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -633,46 +633,73 @@
     <string name="permgrouplab_contacts">Contacts</string>
     <!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgroupdesc_contacts">access your contacts</string>
+    <!-- Message shown to the user when the apps requests permission from this group -->
+    <string name="permgrouprequest_contacts">Allow
+        &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to access your contacts</string>
 
     <!-- Title of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgrouplab_location">Location</string>
     <!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgroupdesc_location">access this device\'s location</string>
+    <!-- Message shown to the user when the apps requests permission from this group -->
+    <string name="permgrouprequest_location">Allow
+        &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to access this device\'s location</string>
 
     <!-- Title of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgrouplab_calendar">Calendar</string>
     <!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgroupdesc_calendar">access your calendar</string>
+    <!-- Message shown to the user when the apps requests permission from this group -->
+    <string name="permgrouprequest_calendar">Allow
+        &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to access your calendar</string>
 
     <!-- Title of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgrouplab_sms">SMS</string>
     <!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgroupdesc_sms">send and view SMS messages</string>
+    <!-- Message shown to the user when the apps requests permission from this group -->
+    <string name="permgrouprequest_sms">Allow
+        &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to send and view SMS messages</string>
 
     <!-- Title of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgrouplab_storage">Storage</string>
     <!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgroupdesc_storage">access photos, media, and files on your device</string>
+    <!-- Message shown to the user when the apps requests permission from this group -->
+    <string name="permgrouprequest_storage">Allow
+        &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to access photos, media, and files on your device</string>
 
     <!-- Title of a category of application permissioncds, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgrouplab_microphone">Microphone</string>
     <!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgroupdesc_microphone">record audio</string>
+    <!-- Message shown to the user when the apps requests permission from this group -->
+    <string name="permgrouprequest_microphone">Allow
+        &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to record audio</string>
 
     <!-- Title of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgrouplab_camera">Camera</string>
     <!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgroupdesc_camera">take pictures and record video</string>
+    <!-- Message shown to the user when the apps requests permission from this group -->
+    <string name="permgrouprequest_camera">Allow
+        &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to take pictures and record video</string>
 
     <!-- Title of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgrouplab_phone">Phone</string>
     <!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgroupdesc_phone">make and manage phone calls</string>
+    <!-- Message shown to the user when the apps requests permission from this group -->
+    <string name="permgrouprequest_phone">Allow
+        &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to make and manage phone calls</string>
 
     <!-- Title of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgrouplab_sensors">Body Sensors</string>
     <!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgroupdesc_sensors">access sensor data about your vital signs</string>
+    <!-- Message shown to the user when the apps requests permission from this group -->
+    <string name="permgrouprequest_sensors">Allow
+        &lt;b><xliff:g id="app_name" example="Gmail">%1$s</xliff:g>&lt;/b> to access sensor data about your vital signs</string>
 
     <!-- Title for the capability of an accessibility service to retrieve window content. -->
     <string name="capability_title_canRetrieveWindowContent">Retrieve window content</string>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index beab29a..bab0c85 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -1152,6 +1152,7 @@
   <java-symbol type="string" name="lockscreen_transport_pause_description" />
   <java-symbol type="string" name="config_ethernet_tcp_buffers" />
   <java-symbol type="string" name="config_wifi_tcp_buffers" />
+  <java-symbol type="string" name="config_demoModePackage" />
   <java-symbol type="string" name="config_demoModeLauncherComponent" />
   <java-symbol type="string" name="config_carrierDemoModePassword" />
   <java-symbol type="string" name="config_carrierDemoModeSetting" />
@@ -1829,6 +1830,7 @@
   <java-symbol type="integer" name="config_networkAvoidBadWifi" />
   <java-symbol type="integer" name="config_networkWakeupPacketMark" />
   <java-symbol type="integer" name="config_networkWakeupPacketMask" />
+  <java-symbol type="bool" name="config_apfDrop802_3Frames" />
   <java-symbol type="integer" name="config_networkMeteredMultipathPreference" />
   <java-symbol type="integer" name="config_notificationsBatteryFullARGB" />
   <java-symbol type="integer" name="config_notificationsBatteryLedOff" />
@@ -2932,6 +2934,14 @@
   <java-symbol type="style" name="AutofillDatasetPicker" />
   <java-symbol type="dimen" name="autofill_dataset_picker_max_size"/>
 
+  <java-symbol type="dimen" name="notification_big_picture_max_height"/>
+  <java-symbol type="dimen" name="notification_big_picture_max_width"/>
+  <java-symbol type="dimen" name="notification_media_image_max_width"/>
+  <java-symbol type="dimen" name="notification_media_image_max_height"/>
+  <java-symbol type="dimen" name="notification_right_icon_size"/>
+  <java-symbol type="dimen" name="notification_custom_view_max_image_height"/>
+  <java-symbol type="dimen" name="notification_custom_view_max_image_width"/>
+
   <!-- Accessibility fingerprint gestures -->
   <java-symbol type="string" name="capability_title_canCaptureFingerprintGestures" />
   <java-symbol type="string" name="capability_desc_canCaptureFingerprintGestures" />
diff --git a/tests/radio/Android.mk b/core/tests/BroadcastRadioTests/Android.mk
similarity index 95%
rename from tests/radio/Android.mk
rename to core/tests/BroadcastRadioTests/Android.mk
index 35d3309..c409e3a 100644
--- a/tests/radio/Android.mk
+++ b/core/tests/BroadcastRadioTests/Android.mk
@@ -16,7 +16,7 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_PACKAGE_NAME := RadioTests
+LOCAL_PACKAGE_NAME := BroadcastRadioTests
 
 LOCAL_PRIVILEGED_MODULE := true
 LOCAL_CERTIFICATE := platform
diff --git a/tests/radio/AndroidManifest.xml b/core/tests/BroadcastRadioTests/AndroidManifest.xml
similarity index 94%
rename from tests/radio/AndroidManifest.xml
rename to core/tests/BroadcastRadioTests/AndroidManifest.xml
index d84674f..0f7d4c7 100644
--- a/tests/radio/AndroidManifest.xml
+++ b/core/tests/BroadcastRadioTests/AndroidManifest.xml
@@ -26,6 +26,6 @@
     <instrumentation
         android:name="android.support.test.runner.AndroidJUnitRunner"
         android:targetPackage="android.hardware.radio.tests"
-        android:label="Tests for broadcast radio API" >
+        android:label="Tests for Broadcast Radio APIs" >
     </instrumentation>
 </manifest>
diff --git a/tests/radio/src/android/hardware/radio/tests/RadioTest.java b/core/tests/BroadcastRadioTests/src/android/hardware/radio/tests/functional/RadioTunerTest.java
similarity index 98%
rename from tests/radio/src/android/hardware/radio/tests/RadioTest.java
rename to core/tests/BroadcastRadioTests/src/android/hardware/radio/tests/functional/RadioTunerTest.java
index aa5780a..82abbf5 100644
--- a/tests/radio/src/android/hardware/radio/tests/RadioTest.java
+++ b/core/tests/BroadcastRadioTests/src/android/hardware/radio/tests/functional/RadioTunerTest.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package android.hardware.radio.tests;
+package android.hardware.radio.tests.functional;
 
 import android.Manifest;
 import android.content.Context;
@@ -58,8 +58,8 @@
  */
 @RunWith(AndroidJUnit4.class)
 @MediumTest
-public class RadioTest {
-    private static final String TAG = "RadioTest";
+public class RadioTunerTest {
+    private static final String TAG = "BroadcastRadioTests.RadioTuner";
 
     public final Context mContext = InstrumentationRegistry.getContext();
 
diff --git a/core/tests/coretests/src/android/view/PinchZoomAction.java b/core/tests/coretests/src/android/view/PinchZoomAction.java
index 78a4b31..97fe980 100644
--- a/core/tests/coretests/src/android/view/PinchZoomAction.java
+++ b/core/tests/coretests/src/android/view/PinchZoomAction.java
@@ -16,23 +16,23 @@
 
 package android.view;
 
-import static android.support.test.espresso.core.deps.guava.base.Preconditions.checkNotNull;
 import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
 import static android.support.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
 import static org.hamcrest.Matchers.allOf;
 
 import android.os.SystemClock;
 import android.support.test.espresso.InjectEventSecurityException;
 import android.support.test.espresso.PerformException;
-import android.support.test.espresso.ViewAction;
-import android.support.test.espresso.action.MotionEvents;
-import android.support.test.espresso.action.Swiper;
 import android.support.test.espresso.UiController;
+import android.support.test.espresso.ViewAction;
+import android.support.test.espresso.action.Swiper;
 import android.support.test.espresso.util.HumanReadables;
 import android.view.MotionEvent;
 import android.view.View;
-import android.view.ViewConfiguration;
-import javax.annotation.Nullable;
+
 import org.hamcrest.Matcher;
 
 /**
diff --git a/core/tests/coretests/src/android/widget/espresso/MouseClickAction.java b/core/tests/coretests/src/android/widget/espresso/MouseClickAction.java
index bec4180..b50d6f4 100644
--- a/core/tests/coretests/src/android/widget/espresso/MouseClickAction.java
+++ b/core/tests/coretests/src/android/widget/espresso/MouseClickAction.java
@@ -16,8 +16,6 @@
 
 package android.widget.espresso;
 
-import org.hamcrest.Matcher;
-
 import android.support.test.espresso.UiController;
 import android.support.test.espresso.ViewAction;
 import android.support.test.espresso.action.CoordinatesProvider;
@@ -25,10 +23,13 @@
 import android.support.test.espresso.action.MotionEvents.DownResultHolder;
 import android.support.test.espresso.action.Press;
 import android.support.test.espresso.action.Tapper;
+import android.view.InputDevice;
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewConfiguration;
 
+import org.hamcrest.Matcher;
+
 /**
  * ViewAction for performing an click on View by a mouse.
  */
@@ -41,8 +42,9 @@
         TRIPLE {
             @Override
             public Tapper.Status sendTap(UiController uiController, float[] coordinates,
-                    float[] precision) {
-                Tapper.Status stat = sendSingleTap(uiController, coordinates, precision);
+                    float[] precision, int inputDevice, int buttonState) {
+                Tapper.Status stat = sendSingleTap(uiController, coordinates, precision,
+                        inputDevice, buttonState);
                 boolean warning = false;
                 if (stat == Tapper.Status.FAILURE) {
                     return Tapper.Status.FAILURE;
@@ -55,7 +57,8 @@
                     if (0 < doubleTapMinimumTimeout) {
                         uiController.loopMainThreadForAtLeast(doubleTapMinimumTimeout);
                     }
-                    stat = sendSingleTap(uiController, coordinates, precision);
+                    stat = sendSingleTap(uiController, coordinates, precision, inputDevice,
+                            buttonState);
                     if (stat == Tapper.Status.FAILURE) {
                         return Tapper.Status.FAILURE;
                     } else if (stat == Tapper.Status.WARNING) {
@@ -69,11 +72,19 @@
                     return Tapper.Status.SUCCESS;
                 }
             }
+
+            @Override
+            public Tapper.Status sendTap(UiController uiController, float[] coordinates,
+                    float[] precision) {
+                return sendTap(uiController, coordinates, precision, InputDevice.SOURCE_UNKNOWN,
+                        MotionEvent.BUTTON_PRIMARY);
+            }
         };
 
         private static Tapper.Status sendSingleTap(UiController uiController,
-                float[] coordinates, float[] precision) {
-            DownResultHolder res = MotionEvents.sendDown(uiController, coordinates, precision);
+                float[] coordinates, float[] precision, int inputDevice, int buttonState) {
+            DownResultHolder res = MotionEvents.sendDown(uiController, coordinates, precision,
+                    inputDevice, buttonState);
             try {
                 if (!MotionEvents.sendUp(uiController, res.down)) {
                     MotionEvents.sendCancel(uiController, res.down);
diff --git a/core/tests/coretests/src/com/android/internal/widget/MessagingLinearLayoutTest.java b/core/tests/coretests/src/com/android/internal/widget/MessagingLinearLayoutTest.java
index 20fd4d3..dfe8511 100644
--- a/core/tests/coretests/src/com/android/internal/widget/MessagingLinearLayoutTest.java
+++ b/core/tests/coretests/src/com/android/internal/widget/MessagingLinearLayoutTest.java
@@ -22,12 +22,12 @@
 
 import android.content.Context;
 import android.support.test.InstrumentationRegistry;
-import android.support.test.espresso.core.deps.guava.base.Function;
 import android.support.test.filters.SmallTest;
 import android.view.LayoutInflater;
 import android.view.View.MeasureSpec;
 
 import com.android.frameworks.coretests.R;
+import com.google.common.base.Function;
 
 import org.junit.Before;
 import org.junit.Test;
diff --git a/core/tests/utiltests/res/drawable/image.jpg b/core/tests/utiltests/res/drawable/image.jpg
new file mode 100644
index 0000000..bef1fb1
--- /dev/null
+++ b/core/tests/utiltests/res/drawable/image.jpg
Binary files differ
diff --git a/core/tests/utiltests/res/drawable/png.png b/core/tests/utiltests/res/drawable/png.png
new file mode 100644
index 0000000..b13c865
--- /dev/null
+++ b/core/tests/utiltests/res/drawable/png.png
Binary files differ
diff --git a/core/tests/utiltests/src/android/util/MetadataReaderTest.java b/core/tests/utiltests/src/android/util/MetadataReaderTest.java
new file mode 100644
index 0000000..193fb50
--- /dev/null
+++ b/core/tests/utiltests/src/android/util/MetadataReaderTest.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.util;
+
+import android.media.ExifInterface;
+import android.os.Bundle;
+import android.provider.DocumentsContract;
+import android.provider.MetadataReader;
+
+import libcore.io.IoUtils;
+
+import junit.framework.TestCase;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+
+public class MetadataReaderTest extends TestCase {
+
+    private InputStream mInputStream;
+    private Bundle mData;
+
+    @Before
+    protected void setUp() throws Exception {
+        mInputStream = getClass().getClassLoader().getResourceAsStream("res/drawable/image.jpg");
+        mData = new Bundle();
+    }
+
+    @After
+    protected void tearDown() throws Exception {
+        IoUtils.closeQuietly(mInputStream);
+    }
+
+    @Test
+    public void testGetMetadata() throws IOException {
+        MetadataReader.getMetadata(mData, mInputStream, "image/jpg", null);
+        Bundle exif = mData.getBundle(DocumentsContract.METADATA_EXIF);
+        assertEquals("3036", String.valueOf(exif.getInt(ExifInterface.TAG_IMAGE_WIDTH)));
+        assertEquals("4048", String.valueOf(exif.getInt(ExifInterface.TAG_IMAGE_LENGTH)));
+        assertEquals("2017:07:17 19:19:28", exif.getString(ExifInterface.TAG_DATETIME));
+        assertEquals(0.0, exif.getDouble(ExifInterface.TAG_GPS_LATITUDE));
+        assertEquals(0.0, exif.getDouble(ExifInterface.TAG_GPS_LONGITUDE));
+        assertEquals("Google", exif.getString(ExifInterface.TAG_MAKE));
+        assertEquals("Pixel", exif.getString(ExifInterface.TAG_MODEL));
+        assertEquals(mData.getStringArray(DocumentsContract.METADATA_TYPES)[0],
+                DocumentsContract.METADATA_EXIF);
+    }
+
+    @Test
+    public void testGetMetadata_JpegOneTag() throws IOException {
+        String[] tags = {ExifInterface.TAG_MAKE};
+        MetadataReader.getMetadata(mData, mInputStream, "image/jpg", tags);
+        assertEquals("Google",
+                mData.getBundle(DocumentsContract.METADATA_EXIF).getString(tags[0]));
+    }
+
+    @Test
+    public void testGetMetadata_JpegNoResults() throws IOException {
+        String[] tags = {ExifInterface.TAG_SPECTRAL_SENSITIVITY};
+        assertEquals(0, mData.size());
+        MetadataReader.getMetadata(mData, mInputStream, "image/jpg", tags);
+        assertEquals(1, mData.size());
+        assertEquals(mData.getStringArray(DocumentsContract.METADATA_TYPES).length, 0);
+    }
+
+    @Test
+    public void testGetMetadata_BadFile() {
+        try {
+            InputStream stream = new FileInputStream("badString");
+            MetadataReader.getMetadata(mData, stream, "image/jpg", null);
+        } catch (IOException e) {
+            assertEquals(FileNotFoundException.class, e.getClass());
+        }
+    }
+
+    @Test
+    public void testGetMetadata_UnsupportedMimeType() throws IOException {
+        MetadataReader.getMetadata(mData, mInputStream, "no/metadata", null);
+        assertEquals(1, mData.size());
+    }
+
+    @Test
+    public void testGetMetadata_NoTags() throws IOException {
+        MetadataReader.getMetadata(mData, mInputStream, "image/jpg", new String[0]);
+        assertEquals(1, mData.size());
+    }
+
+    @Test
+    public void testGetMetadata_Png() throws IOException {
+        InputStream pngStream = getClass().getClassLoader().getResourceAsStream("res/drawable/png.png");
+        MetadataReader.getMetadata(mData, pngStream, "image/png", null);
+        assertEquals(1, mData.size());
+
+    }
+
+}
diff --git a/drm/jni/android_drm_DrmManagerClient.cpp b/drm/jni/android_drm_DrmManagerClient.cpp
index 63fe8ac..52ea8e3 100644
--- a/drm/jni/android_drm_DrmManagerClient.cpp
+++ b/drm/jni/android_drm_DrmManagerClient.cpp
@@ -19,8 +19,8 @@
 #include <utils/Log.h>
 
 #include <jni.h>
-#include <JNIHelp.h>
-#include <ScopedLocalRef.h>
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedLocalRef.h>
 #include <android_runtime/AndroidRuntime.h>
 
 #include <drm/DrmInfo.h>
diff --git a/graphics/java/android/graphics/drawable/Icon.java b/graphics/java/android/graphics/drawable/Icon.java
index aa38f31..c329918 100644
--- a/graphics/java/android/graphics/drawable/Icon.java
+++ b/graphics/java/android/graphics/drawable/Icon.java
@@ -805,6 +805,43 @@
     };
 
     /**
+     * Scale down a bitmap to a given max width and max height. The scaling will be done in a uniform way
+     * @param bitmap the bitmap to scale down
+     * @param maxWidth the maximum width allowed
+     * @param maxHeight the maximum height allowed
+     *
+     * @return the scaled bitmap if necessary or the original bitmap if no scaling was needed
+     * @hide
+     */
+    public static Bitmap scaleDownIfNecessary(Bitmap bitmap, int maxWidth, int maxHeight) {
+        int bitmapWidth = bitmap.getWidth();
+        int bitmapHeight = bitmap.getHeight();
+        if (bitmapWidth > maxWidth || bitmapHeight > maxHeight) {
+            float scale = Math.min((float) maxWidth / bitmapWidth,
+                    (float) maxHeight / bitmapHeight);
+            bitmap = Bitmap.createScaledBitmap(bitmap, (int) (scale * bitmapWidth),
+                    (int) (scale * bitmapHeight), true /* filter */);
+        }
+        return bitmap;
+    }
+
+    /**
+     * Scale down this icon to a given max width and max height.
+     * The scaling will be done in a uniform way and currently only bitmaps are supported.
+     * @param maxWidth the maximum width allowed
+     * @param maxHeight the maximum height allowed
+     *
+     * @hide
+     */
+    public void scaleDownIfNecessary(int maxWidth, int maxHeight) {
+        if (mType != TYPE_BITMAP && mType != TYPE_ADAPTIVE_BITMAP) {
+            return;
+        }
+        Bitmap bitmap = getBitmap();
+        setBitmap(scaleDownIfNecessary(bitmap, maxWidth, maxHeight));
+    }
+
+    /**
      * Implement this interface to receive a callback when
      * {@link #loadDrawableAsync(Context, OnDrawableLoadedListener, Handler) loadDrawableAsync}
      * is finished and your Drawable is ready.
diff --git a/libs/hwui/Caches.cpp b/libs/hwui/Caches.cpp
index 2fdfcd4..0700d1f 100644
--- a/libs/hwui/Caches.cpp
+++ b/libs/hwui/Caches.cpp
@@ -50,9 +50,9 @@
 ///////////////////////////////////////////////////////////////////////////////
 
 Caches::Caches(RenderState& renderState)
-        : gradientCache(mExtensions)
+        : gradientCache(extensions())
         , patchCache(renderState)
-        , programCache(mExtensions)
+        , programCache(extensions())
         , mRenderState(&renderState)
         , mInitialized(false) {
     INIT_LOGD("Creating OpenGL renderer caches");
@@ -80,7 +80,7 @@
 }
 
 void Caches::initExtensions() {
-    if (mExtensions.hasDebugMarker()) {
+    if (extensions().hasDebugMarker()) {
         eventMark = glInsertEventMarkerEXT;
 
         startMark = glPushGroupMarkerEXT;
@@ -93,12 +93,12 @@
 }
 
 void Caches::initConstraints() {
-    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
+    maxTextureSize = DeviceInfo::get()->maxTextureSize();
 }
 
 void Caches::initStaticProperties() {
     // OpenGL ES 3.0+ specific features
-    gpuPixelBuffersEnabled = mExtensions.hasPixelBufferObjects()
+    gpuPixelBuffersEnabled = extensions().hasPixelBufferObjects()
             && property_get_bool(PROPERTY_ENABLE_GPU_PIXEL_BUFFERS, true);
 }
 
diff --git a/libs/hwui/Caches.h b/libs/hwui/Caches.h
index 19063e3..29eddde 100644
--- a/libs/hwui/Caches.h
+++ b/libs/hwui/Caches.h
@@ -16,6 +16,7 @@
 
 #pragma once
 
+#include "DeviceInfo.h"
 #include "Extensions.h"
 #include "FboCache.h"
 #include "GammaFontRenderer.h"
@@ -145,10 +146,6 @@
     // Misc
     GLint maxTextureSize;
 
-private:
-    // Declared before gradientCache and programCache which need this to initialize.
-    // TODO: cleanup / move elsewhere
-    Extensions mExtensions;
 public:
     TextureCache textureCache;
     RenderBufferCache renderBufferCache;
@@ -174,7 +171,7 @@
     void setProgram(const ProgramDescription& description);
     void setProgram(Program* program);
 
-    const Extensions& extensions() const { return mExtensions; }
+    const Extensions& extensions() const { return DeviceInfo::get()->extensions(); }
     Program& program() { return *mProgram; }
     PixelBufferState& pixelBufferState() { return *mPixelBufferState; }
     TextureState& textureState() { return *mTextureState; }
diff --git a/libs/hwui/DeviceInfo.cpp b/libs/hwui/DeviceInfo.cpp
index d180ba5..37965da 100644
--- a/libs/hwui/DeviceInfo.cpp
+++ b/libs/hwui/DeviceInfo.cpp
@@ -16,7 +16,8 @@
 
 #include <DeviceInfo.h>
 
-#include "Extensions.h"
+#include <gui/ISurfaceComposer.h>
+#include <gui/SurfaceComposerClient.h>
 
 #include <thread>
 #include <mutex>
@@ -46,13 +47,22 @@
 void DeviceInfo::initialize(int maxTextureSize) {
     std::call_once(sInitializedFlag, [maxTextureSize]() {
         sDeviceInfo = new DeviceInfo();
+        sDeviceInfo->loadDisplayInfo();
         sDeviceInfo->mMaxTextureSize = maxTextureSize;
     });
 }
 
 void DeviceInfo::load() {
+    loadDisplayInfo();
     glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
 }
 
+void DeviceInfo::loadDisplayInfo() {
+    sp<IBinder> dtoken(SurfaceComposerClient::getBuiltInDisplay(
+            ISurfaceComposer::eDisplayIdMain));
+    status_t status = SurfaceComposerClient::getDisplayInfo(dtoken, &mDisplayInfo);
+    LOG_ALWAYS_FATAL_IF(status, "Failed to get display info, error %d", status);
+}
+
 } /* namespace uirenderer */
 } /* namespace android */
diff --git a/libs/hwui/DeviceInfo.h b/libs/hwui/DeviceInfo.h
index aff84b0..5bd7b14 100644
--- a/libs/hwui/DeviceInfo.h
+++ b/libs/hwui/DeviceInfo.h
@@ -16,7 +16,10 @@
 #ifndef DEVICEINFO_H
 #define DEVICEINFO_H
 
+#include <ui/DisplayInfo.h>
+
 #include "utils/Macros.h"
+#include "Extensions.h"
 
 namespace android {
 namespace uirenderer {
@@ -35,14 +38,24 @@
     static void initialize(int maxTextureSize);
 
     int maxTextureSize() const { return mMaxTextureSize; }
+    const DisplayInfo& displayInfo() const { return mDisplayInfo; }
+    const Extensions& extensions() const { return mExtensions; }
+
+    static uint32_t multiplyByResolution(uint32_t in) {
+        auto di = DeviceInfo::get()->displayInfo();
+        return di.w * di.h * in;
+    }
 
 private:
     DeviceInfo() {}
     ~DeviceInfo() {}
 
     void load();
+    void loadDisplayInfo();
 
     int mMaxTextureSize;
+    DisplayInfo mDisplayInfo;
+    Extensions mExtensions;
 };
 
 } /* namespace uirenderer */
diff --git a/libs/hwui/FboCache.cpp b/libs/hwui/FboCache.cpp
index b2181b6..a39e49f 100644
--- a/libs/hwui/FboCache.cpp
+++ b/libs/hwui/FboCache.cpp
@@ -28,7 +28,7 @@
 ///////////////////////////////////////////////////////////////////////////////
 
 FboCache::FboCache()
-        : mMaxSize(Properties::fboCacheSize) {}
+        : mMaxSize(0) {}
 
 FboCache::~FboCache() {
     clear();
diff --git a/libs/hwui/FontRenderer.cpp b/libs/hwui/FontRenderer.cpp
index ee99018..bc41810 100644
--- a/libs/hwui/FontRenderer.cpp
+++ b/libs/hwui/FontRenderer.cpp
@@ -32,7 +32,6 @@
 #include "utils/Timing.h"
 
 #include <algorithm>
-#include <cutils/properties.h>
 #include <RenderScript.h>
 #include <SkGlyph.h>
 #include <SkUtils.h>
@@ -99,22 +98,14 @@
         INIT_LOGD("Creating FontRenderer");
     }
 
-    mSmallCacheWidth = property_get_int32(PROPERTY_TEXT_SMALL_CACHE_WIDTH,
-            DEFAULT_TEXT_SMALL_CACHE_WIDTH);
-    mSmallCacheHeight = property_get_int32(PROPERTY_TEXT_SMALL_CACHE_HEIGHT,
-            DEFAULT_TEXT_SMALL_CACHE_HEIGHT);
+    auto deviceInfo = DeviceInfo::get();
+    int maxTextureSize = deviceInfo->maxTextureSize();
 
-    mLargeCacheWidth = property_get_int32(PROPERTY_TEXT_LARGE_CACHE_WIDTH,
-            DEFAULT_TEXT_LARGE_CACHE_WIDTH);
-    mLargeCacheHeight = property_get_int32(PROPERTY_TEXT_LARGE_CACHE_HEIGHT,
-            DEFAULT_TEXT_LARGE_CACHE_HEIGHT);
-
-    uint32_t maxTextureSize = (uint32_t) Caches::getInstance().maxTextureSize;
-
-    mSmallCacheWidth = std::min(mSmallCacheWidth, maxTextureSize);
-    mSmallCacheHeight = std::min(mSmallCacheHeight, maxTextureSize);
-    mLargeCacheWidth = std::min(mLargeCacheWidth, maxTextureSize);
-    mLargeCacheHeight = std::min(mLargeCacheHeight, maxTextureSize);
+    // TODO: Most devices are hardcoded with this configuration, does it need to be dynamic?
+    mSmallCacheWidth = std::min(1024, maxTextureSize);
+    mSmallCacheHeight = std::min(1024, maxTextureSize);
+    mLargeCacheWidth = std::min(2048, maxTextureSize);
+    mLargeCacheHeight = std::min(1024, maxTextureSize);
 
     if (sLogFontRendererCreate) {
         INIT_LOGD("  Text cache sizes, in pixels: %i x %i, %i x %i, %i x %i, %i x %i",
diff --git a/libs/hwui/GradientCache.cpp b/libs/hwui/GradientCache.cpp
index d4d0c99..2026234 100644
--- a/libs/hwui/GradientCache.cpp
+++ b/libs/hwui/GradientCache.cpp
@@ -20,6 +20,7 @@
 #include "Debug.h"
 #include "GradientCache.h"
 #include "Properties.h"
+#include "DeviceInfo.h"
 
 #include <cutils/properties.h>
 
@@ -62,14 +63,14 @@
 // Constructors/destructor
 ///////////////////////////////////////////////////////////////////////////////
 
-GradientCache::GradientCache(Extensions& extensions)
+GradientCache::GradientCache(const Extensions& extensions)
         : mCache(LruCache<GradientCacheEntry, Texture*>::kUnlimitedCapacity)
         , mSize(0)
-        , mMaxSize(Properties::gradientCacheSize)
+        , mMaxSize(MB(1))
         , mUseFloatTexture(extensions.hasFloatTextures())
         , mHasNpot(extensions.hasNPot())
         , mHasLinearBlending(extensions.hasLinearBlending()) {
-    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
+    mMaxTextureSize = DeviceInfo::get()->maxTextureSize();
 
     mCache.setOnEntryRemovedListener(this);
 }
diff --git a/libs/hwui/GradientCache.h b/libs/hwui/GradientCache.h
index f299a40..d95589c 100644
--- a/libs/hwui/GradientCache.h
+++ b/libs/hwui/GradientCache.h
@@ -105,7 +105,7 @@
  */
 class GradientCache: public OnEntryRemoved<GradientCacheEntry, Texture*> {
 public:
-    explicit GradientCache(Extensions& extensions);
+    explicit GradientCache(const Extensions& extensions);
     ~GradientCache();
 
     /**
diff --git a/libs/hwui/PatchCache.cpp b/libs/hwui/PatchCache.cpp
index 983c17e..78c7eb9 100644
--- a/libs/hwui/PatchCache.cpp
+++ b/libs/hwui/PatchCache.cpp
@@ -32,7 +32,7 @@
 
 PatchCache::PatchCache(RenderState& renderState)
         : mRenderState(renderState)
-        , mMaxSize(Properties::patchCacheSize)
+        , mMaxSize(KB(128))
         , mSize(0)
         , mCache(LruCache<PatchDescription, Patch*>::kUnlimitedCapacity)
         , mMeshBuffer(0)
diff --git a/libs/hwui/PathCache.cpp b/libs/hwui/PathCache.cpp
index cc96de7..8d4ae1b 100644
--- a/libs/hwui/PathCache.cpp
+++ b/libs/hwui/PathCache.cpp
@@ -38,6 +38,8 @@
 namespace android {
 namespace uirenderer {
 
+static constexpr size_t PATH_CACHE_COUNT_LIMIT = 256;
+
 template <class T>
 static bool compareWidthHeight(const T& lhs, const T& rhs) {
     return (lhs.mWidth == rhs.mWidth) && (lhs.mHeight == rhs.mHeight);
@@ -179,13 +181,9 @@
 PathCache::PathCache()
         : mCache(LruCache<PathDescription, PathTexture*>::kUnlimitedCapacity)
         , mSize(0)
-        , mMaxSize(Properties::pathCacheSize) {
+        , mMaxSize(DeviceInfo::multiplyByResolution(4)) {
     mCache.setOnEntryRemovedListener(this);
-
-    GLint maxTextureSize;
-    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
-    mMaxTextureSize = maxTextureSize;
-
+    mMaxTextureSize = DeviceInfo::get()->maxTextureSize();
     mDebugEnabled = Properties::debugLevel & kDebugCaches;
 }
 
@@ -259,12 +257,7 @@
 }
 
 void PathCache::trim() {
-    // 25 is just an arbitrary lower bound to ensure we aren't in weird edge cases
-    // of things like a cap of 0 or 1 as that's going to break things.
-    // It does not represent a reasonable minimum value
-    static_assert(DEFAULT_PATH_TEXTURE_CAP > 25, "Path cache texture cap is too small");
-
-    while (mSize > mMaxSize || mCache.size() > DEFAULT_PATH_TEXTURE_CAP) {
+    while (mSize > mMaxSize || mCache.size() > PATH_CACHE_COUNT_LIMIT) {
         LOG_ALWAYS_FATAL_IF(!mCache.size(), "Inconsistent mSize! Ran out of items to remove!"
                 " mSize = %u, mMaxSize = %u", mSize, mMaxSize);
         mCache.removeOldest();
diff --git a/libs/hwui/ProgramCache.cpp b/libs/hwui/ProgramCache.cpp
index 8cc0aa7..b767046 100644
--- a/libs/hwui/ProgramCache.cpp
+++ b/libs/hwui/ProgramCache.cpp
@@ -505,7 +505,7 @@
 // Constructors/destructors
 ///////////////////////////////////////////////////////////////////////////////
 
-ProgramCache::ProgramCache(Extensions& extensions)
+ProgramCache::ProgramCache(const Extensions& extensions)
         : mHasES3(extensions.getMajorGlVersion() >= 3)
         , mHasLinearBlending(extensions.hasLinearBlending()) {
 }
diff --git a/libs/hwui/ProgramCache.h b/libs/hwui/ProgramCache.h
index cedd854b..ee76f22 100644
--- a/libs/hwui/ProgramCache.h
+++ b/libs/hwui/ProgramCache.h
@@ -40,7 +40,7 @@
  */
 class ProgramCache {
 public:
-    explicit ProgramCache(Extensions& extensions);
+    explicit ProgramCache(const Extensions& extensions);
     ~ProgramCache();
 
     Program* get(const ProgramDescription& description);
diff --git a/libs/hwui/Properties.cpp b/libs/hwui/Properties.cpp
index b587248..acc7539 100644
--- a/libs/hwui/Properties.cpp
+++ b/libs/hwui/Properties.cpp
@@ -16,6 +16,7 @@
 
 #include "Properties.h"
 #include "Debug.h"
+#include "DeviceInfo.h"
 
 #include <algorithm>
 #include <cstdlib>
@@ -36,20 +37,6 @@
 bool Properties::useBufferAge = true;
 bool Properties::enablePartialUpdates = true;
 
-float Properties::textGamma = DEFAULT_TEXT_GAMMA;
-
-int Properties::fboCacheSize = DEFAULT_FBO_CACHE_SIZE;
-int Properties::gradientCacheSize = MB(DEFAULT_GRADIENT_CACHE_SIZE);
-int Properties::layerPoolSize = MB(DEFAULT_LAYER_CACHE_SIZE);
-int Properties::patchCacheSize = KB(DEFAULT_PATCH_CACHE_SIZE);
-int Properties::pathCacheSize = MB(DEFAULT_PATH_CACHE_SIZE);
-int Properties::renderBufferCacheSize = MB(DEFAULT_RENDER_BUFFER_CACHE_SIZE);
-int Properties::tessellationCacheSize = MB(DEFAULT_VERTEX_CACHE_SIZE);
-int Properties::textDropShadowCacheSize = MB(DEFAULT_DROP_SHADOW_CACHE_SIZE);
-int Properties::textureCacheSize = MB(DEFAULT_TEXTURE_CACHE_SIZE);
-
-float Properties::textureCacheFlushRate = DEFAULT_TEXTURE_CACHE_FLUSH_RATE;
-
 DebugLevel Properties::debugLevel = kDebugDisabled;
 OverdrawColorSet Properties::overdrawColorSet = OverdrawColorSet::Default;
 StencilClipDebug Properties::debugStencilClip = StencilClipDebug::Hide;
@@ -80,15 +67,6 @@
     return defaultValue;
 }
 
-static float property_get_float(const char* key, float defaultValue) {
-    char buf[PROPERTY_VALUE_MAX] = {'\0',};
-
-    if (property_get(key, buf, "") > 0) {
-        return atof(buf);
-    }
-    return defaultValue;
-}
-
 bool Properties::load() {
     char property[PROPERTY_VALUE_MAX];
     bool prevDebugLayersUpdates = debugLayersUpdates;
@@ -147,20 +125,6 @@
     useBufferAge = property_get_bool(PROPERTY_USE_BUFFER_AGE, true);
     enablePartialUpdates = property_get_bool(PROPERTY_ENABLE_PARTIAL_UPDATES, true);
 
-    textGamma = property_get_float(PROPERTY_TEXT_GAMMA, DEFAULT_TEXT_GAMMA);
-
-    fboCacheSize = property_get_int(PROPERTY_FBO_CACHE_SIZE, DEFAULT_FBO_CACHE_SIZE);
-    gradientCacheSize = MB(property_get_float(PROPERTY_GRADIENT_CACHE_SIZE, DEFAULT_GRADIENT_CACHE_SIZE));
-    layerPoolSize = MB(property_get_float(PROPERTY_LAYER_CACHE_SIZE, DEFAULT_LAYER_CACHE_SIZE));
-    patchCacheSize = KB(property_get_float(PROPERTY_PATCH_CACHE_SIZE, DEFAULT_PATCH_CACHE_SIZE));
-    pathCacheSize = MB(property_get_float(PROPERTY_PATH_CACHE_SIZE, DEFAULT_PATH_CACHE_SIZE));
-    renderBufferCacheSize = MB(property_get_float(PROPERTY_RENDER_BUFFER_CACHE_SIZE, DEFAULT_RENDER_BUFFER_CACHE_SIZE));
-    tessellationCacheSize = MB(property_get_float(PROPERTY_VERTEX_CACHE_SIZE, DEFAULT_VERTEX_CACHE_SIZE));
-    textDropShadowCacheSize = MB(property_get_float(PROPERTY_DROP_SHADOW_CACHE_SIZE, DEFAULT_DROP_SHADOW_CACHE_SIZE));
-    textureCacheSize = MB(property_get_float(PROPERTY_TEXTURE_CACHE_SIZE, DEFAULT_TEXTURE_CACHE_SIZE));
-    textureCacheFlushRate = std::max(0.0f, std::min(1.0f,
-            property_get_float(PROPERTY_TEXTURE_CACHE_FLUSH_RATE, DEFAULT_TEXTURE_CACHE_FLUSH_RATE)));
-
     filterOutTestOverhead = property_get_bool(PROPERTY_FILTER_TEST_OVERHEAD, false);
 
     return (prevDebugLayersUpdates != debugLayersUpdates)
diff --git a/libs/hwui/Properties.h b/libs/hwui/Properties.h
index 91b4a2d..47ae9e9 100644
--- a/libs/hwui/Properties.h
+++ b/libs/hwui/Properties.h
@@ -153,81 +153,18 @@
 #define PROPERTY_FILTER_TEST_OVERHEAD "debug.hwui.filter_test_overhead"
 
 /**
+ * Indicates whether PBOs can be used to back pixel buffers.
+ * Accepted values are "true" and "false". Default is true.
+ */
+#define PROPERTY_ENABLE_GPU_PIXEL_BUFFERS "debug.hwui.use_gpu_pixel_buffers"
+
+/**
  * Allows to set rendering pipeline mode to OpenGL (default), Skia OpenGL
  * or Vulkan.
  */
 #define PROPERTY_RENDERER "debug.hwui.renderer"
 
 ///////////////////////////////////////////////////////////////////////////////
-// Runtime configuration properties
-///////////////////////////////////////////////////////////////////////////////
-
-/**
- * Used to enable/disable scissor optimization. The accepted values are
- * "true" and "false". The default value is "false".
- *
- * When scissor optimization is enabled, libhwui will attempt to
- * minimize the use of scissor by selectively enabling and disabling the
- * GL scissor test.
- * When the optimization is disabled, OpenGLRenderer will keep the GL
- * scissor test enabled and change the scissor rect as needed.
- * Some GPUs (for instance the SGX 540) perform better when changing
- * the scissor rect often than when enabling/disabling the scissor test
- * often.
- */
-#define PROPERTY_DISABLE_SCISSOR_OPTIMIZATION "ro.hwui.disable_scissor_opt"
-
-/**
- * Indicates whether PBOs can be used to back pixel buffers.
- * Accepted values are "true" and "false". Default is true.
- */
-#define PROPERTY_ENABLE_GPU_PIXEL_BUFFERS "ro.hwui.use_gpu_pixel_buffers"
-
-// These properties are defined in mega-bytes
-#define PROPERTY_TEXTURE_CACHE_SIZE "ro.hwui.texture_cache_size"
-#define PROPERTY_LAYER_CACHE_SIZE "ro.hwui.layer_cache_size"
-#define PROPERTY_RENDER_BUFFER_CACHE_SIZE "ro.hwui.r_buffer_cache_size"
-#define PROPERTY_GRADIENT_CACHE_SIZE "ro.hwui.gradient_cache_size"
-#define PROPERTY_PATH_CACHE_SIZE "ro.hwui.path_cache_size"
-#define PROPERTY_VERTEX_CACHE_SIZE "ro.hwui.vertex_cache_size"
-#define PROPERTY_PATCH_CACHE_SIZE "ro.hwui.patch_cache_size"
-#define PROPERTY_DROP_SHADOW_CACHE_SIZE "ro.hwui.drop_shadow_cache_size"
-#define PROPERTY_FBO_CACHE_SIZE "ro.hwui.fbo_cache_size"
-
-// These properties are defined in percentage (range 0..1)
-#define PROPERTY_TEXTURE_CACHE_FLUSH_RATE "ro.hwui.texture_cache_flushrate"
-
-// These properties are defined in pixels
-#define PROPERTY_TEXT_SMALL_CACHE_WIDTH "ro.hwui.text_small_cache_width"
-#define PROPERTY_TEXT_SMALL_CACHE_HEIGHT "ro.hwui.text_small_cache_height"
-#define PROPERTY_TEXT_LARGE_CACHE_WIDTH "ro.hwui.text_large_cache_width"
-#define PROPERTY_TEXT_LARGE_CACHE_HEIGHT "ro.hwui.text_large_cache_height"
-
-// Gamma (>= 1.0, <= 3.0)
-#define PROPERTY_TEXT_GAMMA "hwui.text_gamma"
-
-///////////////////////////////////////////////////////////////////////////////
-// Default property values
-///////////////////////////////////////////////////////////////////////////////
-
-#define DEFAULT_TEXTURE_CACHE_SIZE 24.0f
-#define DEFAULT_LAYER_CACHE_SIZE 16.0f
-#define DEFAULT_RENDER_BUFFER_CACHE_SIZE 2.0f
-#define DEFAULT_PATH_CACHE_SIZE 4.0f
-#define DEFAULT_VERTEX_CACHE_SIZE 1.0f
-#define DEFAULT_PATCH_CACHE_SIZE 128.0f // in kB
-#define DEFAULT_GRADIENT_CACHE_SIZE 0.5f
-#define DEFAULT_DROP_SHADOW_CACHE_SIZE 2.0f
-#define DEFAULT_FBO_CACHE_SIZE 0
-
-#define DEFAULT_TEXTURE_CACHE_FLUSH_RATE 0.6f
-
-#define DEFAULT_TEXT_GAMMA 1.45f // Match design tools
-
-// cap to 256 to limite paths in the path cache
-#define DEFAULT_PATH_TEXTURE_CAP 256
-
-///////////////////////////////////////////////////////////////////////////////
 // Misc
 ///////////////////////////////////////////////////////////////////////////////
 
@@ -279,18 +216,8 @@
     static bool useBufferAge;
     static bool enablePartialUpdates;
 
-    static float textGamma;
-
-    static int fboCacheSize;
-    static int gradientCacheSize;
-    static int layerPoolSize;
-    static int patchCacheSize;
-    static int pathCacheSize;
-    static int renderBufferCacheSize;
-    static int tessellationCacheSize;
-    static int textDropShadowCacheSize;
-    static int textureCacheSize;
-    static float textureCacheFlushRate;
+    // TODO: Move somewhere else?
+    static constexpr float textGamma = 1.45f;
 
     static DebugLevel debugLevel;
     static OverdrawColorSet overdrawColorSet;
diff --git a/libs/hwui/RenderBufferCache.cpp b/libs/hwui/RenderBufferCache.cpp
index 1ac57cd..2f8ddfe 100644
--- a/libs/hwui/RenderBufferCache.cpp
+++ b/libs/hwui/RenderBufferCache.cpp
@@ -17,6 +17,7 @@
 #include "Debug.h"
 #include "Properties.h"
 #include "RenderBufferCache.h"
+#include "DeviceInfo.h"
 
 #include <utils/Log.h>
 
@@ -36,13 +37,20 @@
     #define RENDER_BUFFER_LOGD(...)
 #endif
 
+static uint32_t calculateRboCacheSize() {
+    // TODO: Do we need to use extensions().has4BitStencil() here?
+    // The tuning guide recommends it, but all real devices are configured
+    // with a larger cache than necessary by 4x, so keep the 2x for now regardless
+    return DeviceInfo::multiplyByResolution(2);
+}
+
 ///////////////////////////////////////////////////////////////////////////////
 // Constructors/destructor
 ///////////////////////////////////////////////////////////////////////////////
 
 RenderBufferCache::RenderBufferCache()
         : mSize(0)
-        , mMaxSize(Properties::renderBufferCacheSize) {}
+        , mMaxSize(calculateRboCacheSize()) {}
 
 RenderBufferCache::~RenderBufferCache() {
     clear();
diff --git a/libs/hwui/TessellationCache.cpp b/libs/hwui/TessellationCache.cpp
index 91e7ac3..01582ce 100644
--- a/libs/hwui/TessellationCache.cpp
+++ b/libs/hwui/TessellationCache.cpp
@@ -290,7 +290,7 @@
 ///////////////////////////////////////////////////////////////////////////////
 
 TessellationCache::TessellationCache()
-        : mMaxSize(Properties::tessellationCacheSize)
+        : mMaxSize(MB(1))
         , mCache(LruCache<Description, Buffer*>::kUnlimitedCapacity)
         , mShadowCache(LruCache<ShadowDescription, Task<vertexBuffer_pair_t*>*>::kUnlimitedCapacity) {
     mCache.setOnEntryRemovedListener(&mBufferRemovedListener);
diff --git a/libs/hwui/TextDropShadowCache.cpp b/libs/hwui/TextDropShadowCache.cpp
index e1f0b2a..c521892 100644
--- a/libs/hwui/TextDropShadowCache.cpp
+++ b/libs/hwui/TextDropShadowCache.cpp
@@ -94,7 +94,7 @@
 ///////////////////////////////////////////////////////////////////////////////
 
 TextDropShadowCache::TextDropShadowCache()
-        : TextDropShadowCache(Properties::textDropShadowCacheSize) {}
+        : TextDropShadowCache(DeviceInfo::multiplyByResolution(2)) {}
 
 TextDropShadowCache::TextDropShadowCache(uint32_t maxByteSize)
         : mCache(LruCache<ShadowText, ShadowTexture*>::kUnlimitedCapacity)
diff --git a/libs/hwui/TextureCache.cpp b/libs/hwui/TextureCache.cpp
index 710cdd9..6fe3606 100644
--- a/libs/hwui/TextureCache.cpp
+++ b/libs/hwui/TextureCache.cpp
@@ -24,6 +24,7 @@
 #include "Properties.h"
 #include "utils/TraceUtils.h"
 #include "hwui/Bitmap.h"
+#include "DeviceInfo.h"
 
 namespace android {
 namespace uirenderer {
@@ -35,13 +36,10 @@
 TextureCache::TextureCache()
         : mCache(LruCache<uint32_t, Texture*>::kUnlimitedCapacity)
         , mSize(0)
-        , mMaxSize(Properties::textureCacheSize)
-        , mFlushRate(Properties::textureCacheFlushRate) {
+        , mMaxSize(DeviceInfo::multiplyByResolution(4 * 6)) // 6 screen-sized RGBA_8888 bitmaps
+        , mFlushRate(.4f) {
     mCache.setOnEntryRemovedListener(this);
-
-    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
-    INIT_LOGD("    Maximum texture dimension is %d pixels", mMaxTextureSize);
-
+    mMaxTextureSize = DeviceInfo::get()->maxTextureSize();
     mDebugEnabled = Properties::debugLevel & kDebugCaches;
 }
 
diff --git a/libs/hwui/font/FontUtil.h b/libs/hwui/font/FontUtil.h
index 07e8b34..d4b4ff9 100644
--- a/libs/hwui/font/FontUtil.h
+++ b/libs/hwui/font/FontUtil.h
@@ -25,11 +25,6 @@
 // Defines
 ///////////////////////////////////////////////////////////////////////////////
 
-#define DEFAULT_TEXT_SMALL_CACHE_WIDTH 1024
-#define DEFAULT_TEXT_SMALL_CACHE_HEIGHT 512
-#define DEFAULT_TEXT_LARGE_CACHE_WIDTH 2048
-#define DEFAULT_TEXT_LARGE_CACHE_HEIGHT 512
-
 #ifdef TEXTURE_BORDER_SIZE
   #if TEXTURE_BORDER_SIZE != 1
     #error TEXTURE_BORDER_SIZE other than 1 is not currently supported
diff --git a/libs/hwui/renderstate/OffscreenBufferPool.cpp b/libs/hwui/renderstate/OffscreenBufferPool.cpp
index 90b27c8..ea292d6 100644
--- a/libs/hwui/renderstate/OffscreenBufferPool.cpp
+++ b/libs/hwui/renderstate/OffscreenBufferPool.cpp
@@ -17,7 +17,6 @@
 #include "OffscreenBufferPool.h"
 
 #include "Caches.h"
-#include "Properties.h"
 #include "renderstate/RenderState.h"
 #include "utils/FatVector.h"
 #include "utils/TraceUtils.h"
@@ -118,7 +117,8 @@
 ///////////////////////////////////////////////////////////////////////////////
 
 OffscreenBufferPool::OffscreenBufferPool()
-    : mMaxSize(Properties::layerPoolSize) {
+     // 4 screen-sized RGBA_8888 textures
+    : mMaxSize(DeviceInfo::multiplyByResolution(4 * 4)) {
 }
 
 OffscreenBufferPool::~OffscreenBufferPool() {
@@ -179,8 +179,9 @@
         layer->region.clear();
         return layer;
     }
+    bool wideColorGamut = layer->wideColorGamut;
     putOrDelete(layer);
-    return get(renderState, width, height, layer->wideColorGamut);
+    return get(renderState, width, height, wideColorGamut);
 }
 
 void OffscreenBufferPool::dump() {
diff --git a/libs/hwui/renderstate/RenderState.cpp b/libs/hwui/renderstate/RenderState.cpp
index 2c92924..ededffb 100644
--- a/libs/hwui/renderstate/RenderState.cpp
+++ b/libs/hwui/renderstate/RenderState.cpp
@@ -53,6 +53,11 @@
     mScissor = new Scissor();
     mStencil = new Stencil();
 
+    // Deferred because creation needs GL context for texture limits
+    if (!mLayerPool) {
+        mLayerPool = new OffscreenBufferPool();
+    }
+
     // This is delayed because the first access of Caches makes GL calls
     if (!mCaches) {
         mCaches = &Caches::createInstance(*this);
@@ -67,7 +72,7 @@
 }
 
 void RenderState::onGLContextDestroyed() {
-    mLayerPool.clear();
+    mLayerPool->clear();
 
     // TODO: reset all cached state in state objects
     std::for_each(mActiveLayers.begin(), mActiveLayers.end(), layerLostGlContext);
@@ -100,7 +105,7 @@
 }
 
 void RenderState::onVkContextDestroyed() {
-    mLayerPool.clear();
+    mLayerPool->clear();
     std::for_each(mActiveLayers.begin(), mActiveLayers.end(), layerDestroyedVkContext);
     GpuMemoryTracker::onGpuContextDestroyed();
 }
@@ -116,10 +121,10 @@
         case Caches::FlushMode::Moderate:
             // fall through
         case Caches::FlushMode::Layers:
-            mLayerPool.clear();
+            if (mLayerPool) mLayerPool->clear();
             break;
     }
-    mCaches->flush(mode);
+    if (mCaches) mCaches->flush(mode);
 }
 
 void RenderState::onBitmapDestroyed(uint32_t pixelRefId) {
diff --git a/libs/hwui/renderstate/RenderState.h b/libs/hwui/renderstate/RenderState.h
index 4b7a865..df81e86 100644
--- a/libs/hwui/renderstate/RenderState.h
+++ b/libs/hwui/renderstate/RenderState.h
@@ -113,7 +113,7 @@
     Scissor& scissor() { return *mScissor; }
     Stencil& stencil() { return *mStencil; }
 
-    OffscreenBufferPool& layerPool() { return mLayerPool; }
+    OffscreenBufferPool& layerPool() { return *mLayerPool; }
 
     GrContext* getGrContext() const;
 
@@ -136,7 +136,7 @@
     Scissor* mScissor = nullptr;
     Stencil* mStencil = nullptr;
 
-    OffscreenBufferPool mLayerPool;
+    OffscreenBufferPool* mLayerPool = nullptr;
 
     std::set<Layer*> mActiveLayers;
     std::set<DeferredLayerUpdater*> mActiveLayerUpdaters;
diff --git a/libs/hwui/renderstate/Stencil.cpp b/libs/hwui/renderstate/Stencil.cpp
index d25ad51..f594421 100644
--- a/libs/hwui/renderstate/Stencil.cpp
+++ b/libs/hwui/renderstate/Stencil.cpp
@@ -47,7 +47,7 @@
  */
 GLenum Stencil::getLayerStencilFormat() {
 #if !DEBUG_STENCIL
-    const Extensions& extensions = Caches::getInstance().extensions();
+    const Extensions& extensions = DeviceInfo::get()->extensions();
     if (extensions.has4BitStencil()) {
         return GL_STENCIL_INDEX4_OES;
     }
diff --git a/libs/hwui/tests/unit/OffscreenBufferPoolTests.cpp b/libs/hwui/tests/unit/OffscreenBufferPoolTests.cpp
index 919852f..308fef3 100644
--- a/libs/hwui/tests/unit/OffscreenBufferPoolTests.cpp
+++ b/libs/hwui/tests/unit/OffscreenBufferPoolTests.cpp
@@ -74,8 +74,8 @@
     OffscreenBufferPool pool;
     EXPECT_EQ(0u, pool.getCount()) << "pool must be created empty";
     EXPECT_EQ(0u, pool.getSize()) << "pool must be created empty";
-    EXPECT_EQ((uint32_t) Properties::layerPoolSize, pool.getMaxSize())
-            << "pool must read size from Properties";
+    // TODO: Does this really make sense as a test?
+    EXPECT_EQ(DeviceInfo::multiplyByResolution(4 * 4), pool.getMaxSize());
 }
 
 RENDERTHREAD_OPENGL_PIPELINE_TEST(OffscreenBufferPool, getPutClear) {
diff --git a/media/java/android/media/MediaCodecInfo.java b/media/java/android/media/MediaCodecInfo.java
index a19726c..e2642c9 100644
--- a/media/java/android/media/MediaCodecInfo.java
+++ b/media/java/android/media/MediaCodecInfo.java
@@ -2861,6 +2861,8 @@
         public static final int AVCProfileHigh10   = 0x10;
         public static final int AVCProfileHigh422  = 0x20;
         public static final int AVCProfileHigh444  = 0x40;
+        public static final int AVCProfileConstrainedBaseline = 0x10000;
+        public static final int AVCProfileConstrainedHigh     = 0x80000;
 
         // from OMX_VIDEO_AVCLEVELTYPE
         public static final int AVCLevel1       = 0x01;
diff --git a/media/java/android/media/MediaHTTPConnection.java b/media/java/android/media/MediaHTTPConnection.java
index dd731df..aae1f51 100644
--- a/media/java/android/media/MediaHTTPConnection.java
+++ b/media/java/android/media/MediaHTTPConnection.java
@@ -61,9 +61,9 @@
     private final static int MAX_REDIRECTS = 20;
 
     public MediaHTTPConnection() {
-        CookieManager cookieManager = (CookieManager)CookieHandler.getDefault();
-        if (cookieManager == null) {
-            Log.w(TAG, "MediaHTTPConnection: Unexpected. No CookieManager found.");
+        CookieHandler cookieHandler = CookieHandler.getDefault();
+        if (cookieHandler == null) {
+            Log.w(TAG, "MediaHTTPConnection: Unexpected. No CookieHandler found.");
         }
 
         native_setup();
diff --git a/media/java/android/media/MediaHTTPService.java b/media/java/android/media/MediaHTTPService.java
index b678630..3a0e58a 100644
--- a/media/java/android/media/MediaHTTPService.java
+++ b/media/java/android/media/MediaHTTPService.java
@@ -41,34 +41,40 @@
         synchronized (mCookieStoreInitialized) {
             // Only need to do it once for all connections
             if ( !mCookieStoreInitialized )  {
-                CookieManager cookieManager = (CookieManager)CookieHandler.getDefault();
-                if (cookieManager == null) {
-                    cookieManager = new CookieManager();
-                    CookieHandler.setDefault(cookieManager);
-                    Log.v(TAG, "makeHTTPConnection: CookieManager created: " + cookieManager);
-                }
-                else {
-                    Log.v(TAG, "makeHTTPConnection: CookieManager(" + cookieManager + ") exists.");
+                CookieHandler cookieHandler = CookieHandler.getDefault();
+                if (cookieHandler == null) {
+                    cookieHandler = new CookieManager();
+                    CookieHandler.setDefault(cookieHandler);
+                    Log.v(TAG, "makeHTTPConnection: CookieManager created: " + cookieHandler);
+                } else {
+                    Log.v(TAG, "makeHTTPConnection: CookieHandler (" + cookieHandler + ") exists.");
                 }
 
                 // Applying the bootstrapping cookies
                 if ( mCookies != null ) {
-                    CookieStore store = cookieManager.getCookieStore();
-                    for ( HttpCookie cookie : mCookies ) {
-                        try {
-                            store.add(null, cookie);
-                        } catch ( Exception e ) {
-                            Log.v(TAG, "makeHTTPConnection: CookieStore.add" + e);
+                    if ( cookieHandler instanceof CookieManager ) {
+                        CookieManager cookieManager = (CookieManager)cookieHandler;
+                        CookieStore store = cookieManager.getCookieStore();
+                        for ( HttpCookie cookie : mCookies ) {
+                            try {
+                                store.add(null, cookie);
+                            } catch ( Exception e ) {
+                                Log.v(TAG, "makeHTTPConnection: CookieStore.add" + e);
+                            }
+                            //for extended debugging when needed
+                            //Log.v(TAG, "MediaHTTPConnection adding Cookie[" + cookie.getName() +
+                            //        "]: " + cookie);
                         }
-                        //for extended debugging when needed
-                        //Log.v(TAG, "MediaHTTPConnection adding Cookie[" + cookie.getName() +
-                        //        "]: " + cookie);
+                    } else {
+                        Log.w(TAG, "makeHTTPConnection: The installed CookieHandler is not a "
+                                + "CookieManager. Can’t add the provided cookies to the cookie "
+                                + "store.");
                     }
                 }   // mCookies
 
                 mCookieStoreInitialized = true;
 
-                Log.v(TAG, "makeHTTPConnection(" + this + "): cookieManager: " + cookieManager +
+                Log.v(TAG, "makeHTTPConnection(" + this + "): cookieHandler: " + cookieHandler +
                         " Cookies: " + mCookies);
             }   // mCookieStoreInitialized
         }   // synchronized
@@ -92,5 +98,4 @@
 
         return null;
     }
-
 }
diff --git a/media/java/android/media/MediaRouter.java b/media/java/android/media/MediaRouter.java
index cff7043..29b88a2 100644
--- a/media/java/android/media/MediaRouter.java
+++ b/media/java/android/media/MediaRouter.java
@@ -766,6 +766,15 @@
     }
 
     /**
+     * Returns a Bluetooth route if available, otherwise the default route.
+     * @hide
+     */
+    public RouteInfo getFallbackRoute() {
+        return (sStatic.mBluetoothA2dpRoute != null)
+                ? sStatic.mBluetoothA2dpRoute : sStatic.mDefaultAudioVideo;
+    }
+
+    /**
      * @hide for use by framework routing UI
      */
     public RouteCategory getSystemCategory() {
@@ -952,6 +961,19 @@
                 && (route == btRoute || route == sStatic.mDefaultAudioVideo)) {
             try {
                 sStatic.mAudioService.setBluetoothA2dpOn(route == btRoute);
+                // TODO: Remove the following logging when no longer needed.
+                if (route != btRoute) {
+                    StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
+                    StringBuffer sb = new StringBuffer();
+                    // callStack[3] is the caller of this method.
+                    for (int i = 3; i < callStack.length; i++) {
+                        StackTraceElement caller = callStack[i];
+                        sb.append(caller.getClassName() + "." + caller.getMethodName()
+                                + ":" + caller.getLineNumber()).append("  ");
+                    }
+                    Log.w(TAG, "Default route is selected while a BT route is available: pkgName="
+                            + sStatic.mPackageName + ", callers=" + sb.toString());
+                }
             } catch (RemoteException e) {
                 Log.e(TAG, "Error changing Bluetooth A2DP state", e);
             }
@@ -1244,7 +1266,9 @@
     }
 
     static void dispatchRouteChanged(RouteInfo info, int oldSupportedTypes) {
-        Log.v(TAG, "Dispatching route change: " + info);
+        if (DEBUG) {
+            Log.d(TAG, "Dispatching route change: " + info);
+        }
         final int newSupportedTypes = info.mSupportedTypes;
         for (CallbackInfo cbi : sStatic.mCallbacks) {
             // Reconstruct some of the history for callbacks that may not have observed
@@ -2038,6 +2062,11 @@
         }
 
         /** @hide */
+        public boolean isBluetooth() {
+            return this == sStatic.mBluetoothA2dpRoute;
+        }
+
+        /** @hide */
         public void select() {
             selectRouteStatic(mSupportedTypes, this, true);
         }
diff --git a/media/jni/android_media_ImageReader.cpp b/media/jni/android_media_ImageReader.cpp
index ff115f70..885bf03 100644
--- a/media/jni/android_media_ImageReader.cpp
+++ b/media/jni/android_media_ImageReader.cpp
@@ -34,7 +34,7 @@
 #include <grallocusage/GrallocUsageConversion.h>
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #include <stdint.h>
 #include <inttypes.h>
diff --git a/media/jni/android_media_ImageWriter.cpp b/media/jni/android_media_ImageWriter.cpp
index 7c424d9..2c74992 100644
--- a/media/jni/android_media_ImageWriter.cpp
+++ b/media/jni/android_media_ImageWriter.cpp
@@ -26,7 +26,7 @@
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/android_view_Surface.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #include <stdint.h>
 #include <inttypes.h>
diff --git a/media/jni/android_media_MediaCodec.cpp b/media/jni/android_media_MediaCodec.cpp
index a27d157..2d008c7 100644
--- a/media/jni/android_media_MediaCodec.cpp
+++ b/media/jni/android_media_MediaCodec.cpp
@@ -28,7 +28,7 @@
 #include "android_runtime/android_view_Surface.h"
 #include "android_util_Binder.h"
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <android/hardware/cas/native/1.0/IDescrambler.h>
 
diff --git a/media/jni/android_media_MediaCodecList.cpp b/media/jni/android_media_MediaCodecList.cpp
index de9bf1f..8de11ca 100644
--- a/media/jni/android_media_MediaCodecList.cpp
+++ b/media/jni/android_media_MediaCodecList.cpp
@@ -26,7 +26,7 @@
 
 #include "android_runtime/AndroidRuntime.h"
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_media_Utils.h"
 
 using namespace android;
diff --git a/media/jni/android_media_MediaCrypto.cpp b/media/jni/android_media_MediaCrypto.cpp
index cbdb8ce..1b3c24f 100644
--- a/media/jni/android_media_MediaCrypto.cpp
+++ b/media/jni/android_media_MediaCrypto.cpp
@@ -22,7 +22,7 @@
 
 #include "android_runtime/AndroidRuntime.h"
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <binder/IServiceManager.h>
 #include <cutils/properties.h>
diff --git a/media/jni/android_media_MediaDataSource.cpp b/media/jni/android_media_MediaDataSource.cpp
index 2ab7e39..8c38d88 100644
--- a/media/jni/android_media_MediaDataSource.cpp
+++ b/media/jni/android_media_MediaDataSource.cpp
@@ -23,7 +23,7 @@
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/Log.h"
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <binder/MemoryDealer.h>
 #include <drm/drm_framework_common.h>
diff --git a/media/jni/android_media_MediaDrm.cpp b/media/jni/android_media_MediaDrm.cpp
index ea35f78..d0c2aea 100644
--- a/media/jni/android_media_MediaDrm.cpp
+++ b/media/jni/android_media_MediaDrm.cpp
@@ -24,7 +24,7 @@
 #include "android_runtime/Log.h"
 #include "android_os_Parcel.h"
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <binder/IServiceManager.h>
 #include <binder/Parcel.h>
diff --git a/media/jni/android_media_MediaHTTPConnection.cpp b/media/jni/android_media_MediaHTTPConnection.cpp
index fa0b43f..365e045 100644
--- a/media/jni/android_media_MediaHTTPConnection.cpp
+++ b/media/jni/android_media_MediaHTTPConnection.cpp
@@ -27,7 +27,7 @@
 
 #include "android_runtime/AndroidRuntime.h"
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 namespace android {
 
diff --git a/media/jni/android_media_MediaMetadataRetriever.cpp b/media/jni/android_media_MediaMetadataRetriever.cpp
index 0a3ce21..71f3856 100644
--- a/media/jni/android_media_MediaMetadataRetriever.cpp
+++ b/media/jni/android_media_MediaMetadataRetriever.cpp
@@ -28,7 +28,7 @@
 #include <private/media/VideoFrame.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_media_MediaDataSource.h"
 #include "android_media_Utils.h"
diff --git a/media/jni/android_media_MediaMuxer.cpp b/media/jni/android_media_MediaMuxer.cpp
index c3461f0..f11452a 100644
--- a/media/jni/android_media_MediaMuxer.cpp
+++ b/media/jni/android_media_MediaMuxer.cpp
@@ -21,7 +21,7 @@
 #include "android_media_Utils.h"
 #include "android_runtime/AndroidRuntime.h"
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <unistd.h>
 #include <fcntl.h>
diff --git a/media/jni/android_media_MediaPlayer.cpp b/media/jni/android_media_MediaPlayer.cpp
index 3711462..c8ec7c4 100644
--- a/media/jni/android_media_MediaPlayer.cpp
+++ b/media/jni/android_media_MediaPlayer.cpp
@@ -32,7 +32,7 @@
 #include <fcntl.h>
 #include <utils/threads.h>
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/android_view_Surface.h"
 #include "android_runtime/Log.h"
diff --git a/media/jni/android_media_MediaProfiles.cpp b/media/jni/android_media_MediaProfiles.cpp
index 5800043..5bc8092 100644
--- a/media/jni/android_media_MediaProfiles.cpp
+++ b/media/jni/android_media_MediaProfiles.cpp
@@ -22,7 +22,7 @@
 #include <utils/threads.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include <media/MediaProfiles.h>
 
diff --git a/media/jni/android_media_MediaScanner.cpp b/media/jni/android_media_MediaScanner.cpp
index 0f3c61f..3b475b2 100644
--- a/media/jni/android_media_MediaScanner.cpp
+++ b/media/jni/android_media_MediaScanner.cpp
@@ -24,7 +24,7 @@
 #include <private/media/VideoFrame.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/Log.h"
 
diff --git a/media/jni/android_media_MediaSync.cpp b/media/jni/android_media_MediaSync.cpp
index 6de5ea9..f752008 100644
--- a/media/jni/android_media_MediaSync.cpp
+++ b/media/jni/android_media_MediaSync.cpp
@@ -26,7 +26,7 @@
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/android_view_Surface.h"
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include <gui/Surface.h>
 
diff --git a/media/jni/android_media_ResampleInputStream.cpp b/media/jni/android_media_ResampleInputStream.cpp
index fa75524..3d8f517c 100644
--- a/media/jni/android_media_ResampleInputStream.cpp
+++ b/media/jni/android_media_ResampleInputStream.cpp
@@ -27,7 +27,7 @@
 #include <utils/threads.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 
 
diff --git a/media/jni/android_media_SyncParams.cpp b/media/jni/android_media_SyncParams.cpp
index d9b2f1d..2d9738d 100644
--- a/media/jni/android_media_SyncParams.cpp
+++ b/media/jni/android_media_SyncParams.cpp
@@ -16,7 +16,7 @@
 
 #include "android_media_SyncParams.h"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 namespace android {
 
diff --git a/media/jni/android_media_Utils.h b/media/jni/android_media_Utils.h
index af2f2d7..821c6b2 100644
--- a/media/jni/android_media_Utils.h
+++ b/media/jni/android_media_Utils.h
@@ -23,7 +23,7 @@
 #include <android_runtime/AndroidRuntime.h>
 #include <gui/CpuConsumer.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <utils/KeyedVector.h>
 #include <utils/String8.h>
 #include <SkStream.h>
diff --git a/media/jni/android_mtp_MtpDatabase.cpp b/media/jni/android_mtp_MtpDatabase.cpp
index f7f79169..cf4458a 100644
--- a/media/jni/android_mtp_MtpDatabase.cpp
+++ b/media/jni/android_mtp_MtpDatabase.cpp
@@ -39,7 +39,7 @@
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/Log.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <nativehelper/ScopedLocalRef.h>
 
 #include <assert.h>
diff --git a/media/jni/android_mtp_MtpDevice.cpp b/media/jni/android_mtp_MtpDevice.cpp
index 768ac1d..d42c39e 100644
--- a/media/jni/android_mtp_MtpDevice.cpp
+++ b/media/jni/android_mtp_MtpDevice.cpp
@@ -29,8 +29,8 @@
 #include <string>
 
 #include "jni.h"
-#include "JNIHelp.h"
-#include "ScopedPrimitiveArray.h"
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
 
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/Log.h"
diff --git a/media/jni/android_mtp_MtpServer.cpp b/media/jni/android_mtp_MtpServer.cpp
index c325f4e..e9e9309 100644
--- a/media/jni/android_mtp_MtpServer.cpp
+++ b/media/jni/android_mtp_MtpServer.cpp
@@ -25,7 +25,7 @@
 #include <utils/threads.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "private/android_filesystem_config.h"
 
diff --git a/media/jni/audioeffect/android_media_AudioEffect.cpp b/media/jni/audioeffect/android_media_AudioEffect.cpp
index 1f93b34..48ddf9a 100644
--- a/media/jni/audioeffect/android_media_AudioEffect.cpp
+++ b/media/jni/audioeffect/android_media_AudioEffect.cpp
@@ -25,7 +25,7 @@
 #include <android_runtime/AndroidRuntime.h>
 #include "media/AudioEffect.h"
 
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 using namespace android;
 
diff --git a/media/jni/audioeffect/android_media_Visualizer.cpp b/media/jni/audioeffect/android_media_Visualizer.cpp
index f0cfeef..b7d7b03 100644
--- a/media/jni/audioeffect/android_media_Visualizer.cpp
+++ b/media/jni/audioeffect/android_media_Visualizer.cpp
@@ -26,7 +26,7 @@
 #include <utils/threads.h>
 #include "media/Visualizer.h"
 
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 using namespace android;
 
diff --git a/native/android/asset_manager.cpp b/native/android/asset_manager.cpp
index 0e5e5c6..98e9a42 100644
--- a/native/android/asset_manager.cpp
+++ b/native/android/asset_manager.cpp
@@ -24,7 +24,7 @@
 #include <utils/threads.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 using namespace android;
 
diff --git a/packages/DefaultContainerService/jni/com_android_defcontainer_MeasurementUtils.cpp b/packages/DefaultContainerService/jni/com_android_defcontainer_MeasurementUtils.cpp
index 6be4849..53cdc9d 100644
--- a/packages/DefaultContainerService/jni/com_android_defcontainer_MeasurementUtils.cpp
+++ b/packages/DefaultContainerService/jni/com_android_defcontainer_MeasurementUtils.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "DefContainer-JNI"
 
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #include <diskusage/dirsize.h>
 #include <utils/Log.h>
diff --git a/packages/PrintSpooler/jni/com_android_printspooler_util_BitmapSerializeUtils.cpp b/packages/PrintSpooler/jni/com_android_printspooler_util_BitmapSerializeUtils.cpp
index 1ce3949..7ff9ced 100644
--- a/packages/PrintSpooler/jni/com_android_printspooler_util_BitmapSerializeUtils.cpp
+++ b/packages/PrintSpooler/jni/com_android_printspooler_util_BitmapSerializeUtils.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "BitmapSerializeUtils"
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #include <android/bitmap.h>
 #include <android/log.h>
diff --git a/packages/PrintSpooler/res/values-pt-rPT/strings.xml b/packages/PrintSpooler/res/values-pt-rPT/strings.xml
index 174789f..fdb44c45 100644
--- a/packages/PrintSpooler/res/values-pt-rPT/strings.xml
+++ b/packages/PrintSpooler/res/values-pt-rPT/strings.xml
@@ -56,7 +56,7 @@
     <string name="print_select_printer" msgid="7388760939873368698">"Selecionar impressora"</string>
     <string name="print_forget_printer" msgid="5035287497291910766">"Esquecer impressora"</string>
     <plurals name="print_search_result_count_utterance" formatted="false" msgid="6997663738361080868">
-      <item quantity="one"><xliff:g id="COUNT_1">%1$s</xliff:g> printers found</item>
+      <item quantity="one"><xliff:g id="COUNT_1">%1$s</xliff:g> impressoras encontradas</item>
       <item quantity="other"><xliff:g id="COUNT_1">%1$s</xliff:g> impressoras encontradas</item>
     </plurals>
     <string name="printer_extended_description_template" msgid="1366699227703381874">"<xliff:g id="PRINT_SERVICE_LABEL">%1$s</xliff:g> – <xliff:g id="PRINTER_DESCRIPTION">%2$s</xliff:g>"</string>
@@ -76,7 +76,7 @@
     <string name="disabled_services_title" msgid="7313253167968363211">"Serviços desativados"</string>
     <string name="all_services_title" msgid="5578662754874906455">"Todos os serviços"</string>
     <plurals name="print_services_recommendation_subtitle" formatted="false" msgid="5678487708807185138">
-      <item quantity="one">Install to discover <xliff:g id="COUNT_1">%1$s</xliff:g> printers</item>
+      <item quantity="one">Instale para detetar <xliff:g id="COUNT_1">%1$s</xliff:g> impressoras</item>
       <item quantity="other">Instale para detetar <xliff:g id="COUNT_1">%1$s</xliff:g> impressoras</item>
     </plurals>
     <string name="printing_notification_title_template" msgid="295903957762447362">"A imprimir <xliff:g id="PRINT_JOB_NAME">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-af/strings.xml b/packages/SettingsLib/res/values-af/strings.xml
index 5d04cf6..b2f9c79 100644
--- a/packages/SettingsLib/res/values-af/strings.xml
+++ b/packages/SettingsLib/res/values-af/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Gepasmaak (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Hulp en terugvoer"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Kieslys"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"MGT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Voer wagwoord in om fabriekterugstelling in demonstrasiemodus uit te voer"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Volgende"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Wagwoord word benodig"</string>
diff --git a/packages/SettingsLib/res/values-am/strings.xml b/packages/SettingsLib/res/values-am/strings.xml
index b42d26a..a3eab26 100644
--- a/packages/SettingsLib/res/values-am/strings.xml
+++ b/packages/SettingsLib/res/values-am/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"ብጁ (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"እገዛ እና ግብረመልስ"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"ምናሌ"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"ጂኤምቲ"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"የፋብሪካ ዳግም ማስጀመር በማሳያ ሁነታ ውስጥ ለማከናወን የይለፍ ቃል ያስገቡ"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"ቀጣይ"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"የይለፍ ቃል ያስፈልጋል"</string>
diff --git a/packages/SettingsLib/res/values-ar/strings.xml b/packages/SettingsLib/res/values-ar/strings.xml
index 2ac6bb5..d58fdca 100644
--- a/packages/SettingsLib/res/values-ar/strings.xml
+++ b/packages/SettingsLib/res/values-ar/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"مخصص (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"المساعدة والتعليقات"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"القائمة"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"غرينيتش"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"إدخال كلمة المرور لإعادة الضبط بحسب بيانات المصنع في الوضع التجريبي"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"التالي"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"يلزم توفر كلمة مرور"</string>
diff --git a/packages/SettingsLib/res/values-az/strings.xml b/packages/SettingsLib/res/values-az/strings.xml
index 494ae00..d276497 100644
--- a/packages/SettingsLib/res/values-az/strings.xml
+++ b/packages/SettingsLib/res/values-az/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Fərdi (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Yardım və rəy"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menyu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Demo rejimində sıfırlamaq üçün parol daxil edin"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Növbəti"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Parol tələb olunur"</string>
diff --git a/packages/SettingsLib/res/values-b+sr+Latn/strings.xml b/packages/SettingsLib/res/values-b+sr+Latn/strings.xml
index fb06a82..ca2a390 100644
--- a/packages/SettingsLib/res/values-b+sr+Latn/strings.xml
+++ b/packages/SettingsLib/res/values-b+sr+Latn/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Prilagođeni (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Pomoć i povratne informacije"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Meni"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Unesite lozinku da biste obavili resetovanje na fabrička podešavanja u režimu demonstracije"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Dalje"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Potrebna je lozinka"</string>
diff --git a/packages/SettingsLib/res/values-be/strings.xml b/packages/SettingsLib/res/values-be/strings.xml
index f73fd39..eeb7968 100644
--- a/packages/SettingsLib/res/values-be/strings.xml
+++ b/packages/SettingsLib/res/values-be/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Карыстальніцкі (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Даведка і водгукі"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Меню"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Каб выканаць скід да заводскіх налад у дэманстрацыйным рэжыме, увядзіце пароль"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Далей"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Патрабуецца пароль"</string>
diff --git a/packages/SettingsLib/res/values-bg/strings.xml b/packages/SettingsLib/res/values-bg/strings.xml
index aa42cce..f66c43f 100644
--- a/packages/SettingsLib/res/values-bg/strings.xml
+++ b/packages/SettingsLib/res/values-bg/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Персонализирано (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Помощ и отзиви"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Меню"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"Средно време по Гринуич (GMT)"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Въведете парола за възст. на фабр. настройки в демонстр. режим"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Напред"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Изисква се парола"</string>
diff --git a/packages/SettingsLib/res/values-bn/strings.xml b/packages/SettingsLib/res/values-bn/strings.xml
index 62deb12..e425df1 100644
--- a/packages/SettingsLib/res/values-bn/strings.xml
+++ b/packages/SettingsLib/res/values-bn/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"কাস্টম (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"সহায়তা ও মতামত"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"মেনু"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"ডেমো মোডে ফ্যাক্টরি রিসেট করতে পাসওয়ার্ড দিন"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"পরবর্তী"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"পাসওয়ার্ড আবশ্যক"</string>
diff --git a/packages/SettingsLib/res/values-bs/strings.xml b/packages/SettingsLib/res/values-bs/strings.xml
index ca187ab..3dd172c 100644
--- a/packages/SettingsLib/res/values-bs/strings.xml
+++ b/packages/SettingsLib/res/values-bs/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Prilagodi (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Pomoć i povratne informacije"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Meni"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Unesite lozinku da izvršite vraćanje na fabričke postavke u načinu demonstracije"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Naprijed"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Potrebna je lozinka"</string>
diff --git a/packages/SettingsLib/res/values-ca/strings.xml b/packages/SettingsLib/res/values-ca/strings.xml
index 00bb4a9..9d3cf01 100644
--- a/packages/SettingsLib/res/values-ca/strings.xml
+++ b/packages/SettingsLib/res/values-ca/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Personalitzat (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Ajuda i suggeriments"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menú"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Introdueix la contrasenya per restablir les dades de fàbrica en mode de demostració"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Següent"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Contrasenya obligatòria"</string>
diff --git a/packages/SettingsLib/res/values-cs/strings.xml b/packages/SettingsLib/res/values-cs/strings.xml
index 8dd1c32..a83b3a1 100644
--- a/packages/SettingsLib/res/values-cs/strings.xml
+++ b/packages/SettingsLib/res/values-cs/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Vlastní (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Nápověda a zpětná vazba"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Nabídka"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Chcete-li v ukázkovém režimu obnovit zařízení do továrního nastavení, zadejte heslo"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Další"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Je třeba zadat heslo"</string>
diff --git a/packages/SettingsLib/res/values-da/strings.xml b/packages/SettingsLib/res/values-da/strings.xml
index 143ad92..d662dec 100644
--- a/packages/SettingsLib/res/values-da/strings.xml
+++ b/packages/SettingsLib/res/values-da/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Tilpasset (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Hjælp og feedback"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Angiv adgangskode for at gendanne fabriksdata i demotilstand"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Næste"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Angiv en adgangskode"</string>
diff --git a/packages/SettingsLib/res/values-de/strings.xml b/packages/SettingsLib/res/values-de/strings.xml
index fda1aa4..c46e5dd 100644
--- a/packages/SettingsLib/res/values-de/strings.xml
+++ b/packages/SettingsLib/res/values-de/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Benutzerdefiniert (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Hilfe &amp; Feedback"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menü"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Passwort eingeben, um Gerät im Demomodus auf Werkseinstellungen zurückzusetzen"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Weiter"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Passwort erforderlich"</string>
diff --git a/packages/SettingsLib/res/values-el/strings.xml b/packages/SettingsLib/res/values-el/strings.xml
index 244af42..351cd6a 100644
--- a/packages/SettingsLib/res/values-el/strings.xml
+++ b/packages/SettingsLib/res/values-el/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Προσαρμοσμένη (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Βοήθεια και σχόλια"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Μενού"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Εισαγάγετε κωδικό πρόσβασης για επαναφορά εργοστασιακών ρυθμίσεων στη λειτουργία επίδειξης"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Επόμενο"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Απαιτείται κωδικός πρόσβασης"</string>
diff --git a/packages/SettingsLib/res/values-en-rAU/strings.xml b/packages/SettingsLib/res/values-en-rAU/strings.xml
index 09ad05c..adfb8c2 100644
--- a/packages/SettingsLib/res/values-en-rAU/strings.xml
+++ b/packages/SettingsLib/res/values-en-rAU/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Custom (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Help &amp; feedback"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Enter password to perform factory reset in demo mode"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Next"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Password required"</string>
diff --git a/packages/SettingsLib/res/values-en-rGB/strings.xml b/packages/SettingsLib/res/values-en-rGB/strings.xml
index 09ad05c..adfb8c2 100644
--- a/packages/SettingsLib/res/values-en-rGB/strings.xml
+++ b/packages/SettingsLib/res/values-en-rGB/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Custom (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Help &amp; feedback"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Enter password to perform factory reset in demo mode"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Next"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Password required"</string>
diff --git a/packages/SettingsLib/res/values-en-rIN/strings.xml b/packages/SettingsLib/res/values-en-rIN/strings.xml
index 09ad05c..adfb8c2 100644
--- a/packages/SettingsLib/res/values-en-rIN/strings.xml
+++ b/packages/SettingsLib/res/values-en-rIN/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Custom (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Help &amp; feedback"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Enter password to perform factory reset in demo mode"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Next"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Password required"</string>
diff --git a/packages/SettingsLib/res/values-es-rUS/strings.xml b/packages/SettingsLib/res/values-es-rUS/strings.xml
index 7e21d6c..609b66f 100644
--- a/packages/SettingsLib/res/values-es-rUS/strings.xml
+++ b/packages/SettingsLib/res/values-es-rUS/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Personalizado (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Ayuda y comentarios"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menú"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Ingresa contraseña y restablece en demo"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Siguiente"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Contraseña obligatoria"</string>
diff --git a/packages/SettingsLib/res/values-es/strings.xml b/packages/SettingsLib/res/values-es/strings.xml
index 4a6f12d..efb845d 100644
--- a/packages/SettingsLib/res/values-es/strings.xml
+++ b/packages/SettingsLib/res/values-es/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Personalizado (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Ayuda y sugerencias"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menú"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Escribe una contraseña para restablecer datos de fábrica en modo demostración"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Siguiente"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Contraseña obligatoria"</string>
diff --git a/packages/SettingsLib/res/values-et/strings.xml b/packages/SettingsLib/res/values-et/strings.xml
index f3748f8..d988b8a 100644
--- a/packages/SettingsLib/res/values-et/strings.xml
+++ b/packages/SettingsLib/res/values-et/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Kohandatud (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Abi ja tagasiside"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menüü"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Sisestage parool, et demorežiimis tehaseseadetele lähtestada"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Järgmine"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Parool on kohustuslik"</string>
diff --git a/packages/SettingsLib/res/values-eu/strings.xml b/packages/SettingsLib/res/values-eu/strings.xml
index 9fd8ad8..6b7a4de 100644
--- a/packages/SettingsLib/res/values-eu/strings.xml
+++ b/packages/SettingsLib/res/values-eu/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Pertsonalizatua (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Laguntza eta iritziak"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menua"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Idatzi pasahitza jatorrizko ezarpenak demo moduan berrezartzeko"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Hurrengoa"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Pasahitza behar da"</string>
diff --git a/packages/SettingsLib/res/values-fa/strings.xml b/packages/SettingsLib/res/values-fa/strings.xml
index 0430592..427721a 100644
--- a/packages/SettingsLib/res/values-fa/strings.xml
+++ b/packages/SettingsLib/res/values-fa/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"سفارشی (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"راهنما و بازخورد"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"منو"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"برای انجام بازنشانی کارخانه‌ای در حالت نمایشی، گذرواژه را وارد کنید"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"بعدی"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"وارد کردن گذرواژه الزامی است"</string>
diff --git a/packages/SettingsLib/res/values-fi/strings.xml b/packages/SettingsLib/res/values-fi/strings.xml
index e3a92e6..69a2e3f 100644
--- a/packages/SettingsLib/res/values-fi/strings.xml
+++ b/packages/SettingsLib/res/values-fi/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Muokattu (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Ohje ja palaute"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Valikko"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Palauta tehdasasetukset antamalla salasana"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Seuraava"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Salasana vaaditaan"</string>
diff --git a/packages/SettingsLib/res/values-fr-rCA/strings.xml b/packages/SettingsLib/res/values-fr-rCA/strings.xml
index 99692a6..e52c4db 100644
--- a/packages/SettingsLib/res/values-fr-rCA/strings.xml
+++ b/packages/SettingsLib/res/values-fr-rCA/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Personnalisée (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Aide et commentaires"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Entrez m. passe pour réinit. en mode démo"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Suivant"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Mot de passe obligatoire"</string>
diff --git a/packages/SettingsLib/res/values-fr/strings.xml b/packages/SettingsLib/res/values-fr/strings.xml
index 2593c16..cde086c 100644
--- a/packages/SettingsLib/res/values-fr/strings.xml
+++ b/packages/SettingsLib/res/values-fr/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Personnalisé (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Aide et commentaires"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Saisir mot de passe pour rétablir conf. d\'usine en mode démo."</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Suivant"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Veuillez saisir le mot de passe"</string>
diff --git a/packages/SettingsLib/res/values-gl/strings.xml b/packages/SettingsLib/res/values-gl/strings.xml
index 1a6fd39..a9e0178 100644
--- a/packages/SettingsLib/res/values-gl/strings.xml
+++ b/packages/SettingsLib/res/values-gl/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Personalizado (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Axuda e comentarios"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menú"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Insire contrasinal para restablec. en demostración"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Seguinte"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"O contrasinal é obrigatorio"</string>
diff --git a/packages/SettingsLib/res/values-gu/strings.xml b/packages/SettingsLib/res/values-gu/strings.xml
index 674d4c9..8822d55f 100644
--- a/packages/SettingsLib/res/values-gu/strings.xml
+++ b/packages/SettingsLib/res/values-gu/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"કસ્ટમ (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"સહાય અને પ્રતિસાદ"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"મેનુ"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"ડેમો મોડમાં ફેક્ટરી રીસેટ પાસવર્ડ દાખલ કરો"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"આગલું"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"પાસવર્ડ આવશ્યક છે"</string>
diff --git a/packages/SettingsLib/res/values-hi/strings.xml b/packages/SettingsLib/res/values-hi/strings.xml
index dd9ad33..2a5b246 100644
--- a/packages/SettingsLib/res/values-hi/strings.xml
+++ b/packages/SettingsLib/res/values-hi/strings.xml
@@ -220,7 +220,7 @@
     <string name="mobile_data_always_on_summary" msgid="8149773901431697910">"वाई-फ़ाई के सक्रिय रहने पर भी, हमेशा मोबाइल डेटा सक्रिय रखें (तेज़ी से नेटवर्क स्विच करने के लिए)."</string>
     <string name="tethering_hardware_offload_summary" msgid="7726082075333346982">"हार्डवेयर त्‍वरण को टेदर करना उपलब्ध होने पर उसका उपयोग करें"</string>
     <string name="adb_warning_title" msgid="6234463310896563253">"USB डीबग करने की अनुमति दें?"</string>
-    <string name="adb_warning_message" msgid="7316799925425402244">"USB डीबग डीबग करने का उद्देश्‍य केवल विकास है. इसका उपयोग आपके कंप्‍यूटर और आपके डिवाइस के बीच डेटा की प्रतिलिपि बनाने, बिना नोटिफिकेशन के आपके डिवाइस पर ऐप्स इंस्‍टॉल करने और लॉग डेटा पढ़ने के लिए करें."</string>
+    <string name="adb_warning_message" msgid="7316799925425402244">"USB डीबग करने का उद्देश्‍य केवल विकास है. इसका इस्तेमाल आपके कंप्‍यूटर और आपके डिवाइस के बीच डेटा को कॉपी करने, बिना नोटिफिकेशन के आपके डिवाइस पर ऐप इंस्‍टॉल करने और लॉग डेटा पढ़ने के लिए करें."</string>
     <string name="adb_keys_warning_message" msgid="5659849457135841625">"आपके द्वारा पूर्व में प्राधिकृत सभी कंप्यूटर से USB डीबगिंग की पहुंच निरस्त करें?"</string>
     <string name="dev_settings_warning_title" msgid="7244607768088540165">"विकास सेटिंग की अनुमति दें?"</string>
     <string name="dev_settings_warning_message" msgid="2298337781139097964">"ये सेटिंग केवल विकास संबंधी उपयोग के प्रयोजन से हैं. वे आपके डिवाइस और उस पर स्‍थित ऐप्स  को खराब कर सकती हैं या उनके दुर्व्यवहार का कारण हो सकती हैं."</string>
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"कस्टम (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"सहायता और फ़ीडबैक"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"मेनू"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"डेमो मोड में फ़ैक्टरी रीसेट के लिए पासवर्ड डालें"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"आगे"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"पासवर्ड आवश्यक"</string>
diff --git a/packages/SettingsLib/res/values-hr/strings.xml b/packages/SettingsLib/res/values-hr/strings.xml
index 8ba4034..68c1c94 100644
--- a/packages/SettingsLib/res/values-hr/strings.xml
+++ b/packages/SettingsLib/res/values-hr/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Prilagođeno (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Pomoć i povratne informacije"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Izbornik"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Unesite zaporku za resetiranje u demo načinu"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Dalje"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Potrebna je zaporka"</string>
diff --git a/packages/SettingsLib/res/values-hu/strings.xml b/packages/SettingsLib/res/values-hu/strings.xml
index a544125..d40c905 100644
--- a/packages/SettingsLib/res/values-hu/strings.xml
+++ b/packages/SettingsLib/res/values-hu/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Egyéni (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Súgó és visszajelzés"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menü"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Írja be a jelszót a visszaállításhoz"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Következő"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Jelszó szükséges"</string>
diff --git a/packages/SettingsLib/res/values-hy/strings.xml b/packages/SettingsLib/res/values-hy/strings.xml
index cb04234..19414bf 100644
--- a/packages/SettingsLib/res/values-hy/strings.xml
+++ b/packages/SettingsLib/res/values-hy/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Հատուկ (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Օգնություն և հետադարձ կապ"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Ընտրացանկ"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Մուտքագրեք գաղտնաբառը՝ ցուցադրական ռեժիմում գործարանային վերակայում կատարելու համար"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Հաջորդը"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Պահանջվում է գաղտնաբառ"</string>
diff --git a/packages/SettingsLib/res/values-in/strings.xml b/packages/SettingsLib/res/values-in/strings.xml
index a8dd4c2..e468a6f 100644
--- a/packages/SettingsLib/res/values-in/strings.xml
+++ b/packages/SettingsLib/res/values-in/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"(<xliff:g id="DENSITYDPI">%d</xliff:g>) khusus"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Bantuan &amp; masukan"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Masukkan sandi untuk mengembalikan ke setelan pabrik dalam mode demo"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Berikutnya"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Perlu sandi"</string>
diff --git a/packages/SettingsLib/res/values-is/strings.xml b/packages/SettingsLib/res/values-is/strings.xml
index 7f541ce..3fa95c0 100644
--- a/packages/SettingsLib/res/values-is/strings.xml
+++ b/packages/SettingsLib/res/values-is/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Sérsniðið (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Hjálp og ábendingar"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Valmynd"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Sláðu inn aðgangsorð til að framkvæma núllstillingu í sýnisútgáfu"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Áfram"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Aðgangsorðs krafist"</string>
diff --git a/packages/SettingsLib/res/values-it/strings.xml b/packages/SettingsLib/res/values-it/strings.xml
index 5598d87..9551ed26 100644
--- a/packages/SettingsLib/res/values-it/strings.xml
+++ b/packages/SettingsLib/res/values-it/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Personalizzato (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Guida e feedback"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Inserisci la password per eseguire il ripristino dei dati di fabbrica in modalità demo"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Avanti"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Password obbligatoria"</string>
diff --git a/packages/SettingsLib/res/values-iw/strings.xml b/packages/SettingsLib/res/values-iw/strings.xml
index 26ce32e..979db30 100644
--- a/packages/SettingsLib/res/values-iw/strings.xml
+++ b/packages/SettingsLib/res/values-iw/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"מותאם אישית (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"עזרה ומשוב"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"תפריט"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"הזן סיסמה כדי לבצע איפוס להגדרות היצרן במצב הדגמה"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"הבא"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"דרושה סיסמה"</string>
diff --git a/packages/SettingsLib/res/values-ja/strings.xml b/packages/SettingsLib/res/values-ja/strings.xml
index 30c7267..13e64f3 100644
--- a/packages/SettingsLib/res/values-ja/strings.xml
+++ b/packages/SettingsLib/res/values-ja/strings.xml
@@ -377,7 +377,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"カスタム(<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"ヘルプとフィードバック"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"メニュー"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"デモモードで初期状態にリセットするには、パスワードを入力してください"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"次へ"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"パスワード必須"</string>
diff --git a/packages/SettingsLib/res/values-ka/strings.xml b/packages/SettingsLib/res/values-ka/strings.xml
index 553c4a0..09ee2e6 100644
--- a/packages/SettingsLib/res/values-ka/strings.xml
+++ b/packages/SettingsLib/res/values-ka/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"მორგებული (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"დახმარება და გამოხმაურება"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"მენიუ"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"შეიყვანეთ პაროლი დემო-რეჟიმში ქარხნულ მდგომარეობაზე დასაბრუნებლად"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"შემდეგი"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"საჭიროა პაროლი"</string>
diff --git a/packages/SettingsLib/res/values-kk/strings.xml b/packages/SettingsLib/res/values-kk/strings.xml
index 27622a1..75ed497 100644
--- a/packages/SettingsLib/res/values-kk/strings.xml
+++ b/packages/SettingsLib/res/values-kk/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Арнаулы (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Анықтама және пікір"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Mәзір"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Демо режимде зауыттық мәндерге қайтару үшін құпия сөзді енгізу"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Келесі"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Құпия сөз қажет"</string>
diff --git a/packages/SettingsLib/res/values-km/strings.xml b/packages/SettingsLib/res/values-km/strings.xml
index 5f614f6..8b41d96 100644
--- a/packages/SettingsLib/res/values-km/strings.xml
+++ b/packages/SettingsLib/res/values-km/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"ផ្ទាល់ខ្លួន (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"ជំនួយ និងមតិស្ថាបនា"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"ម៉ឺនុយ"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"បញ្ចូល​ពាក្យ​សម្ងាត់ ដើម្បី​កំណត់ឧបករណ៍​​ឡើង​វិញ​ដូចពេលចេញ​ពី​រោងចក្រ នៅក្នុង​មុខងារ​សាកល្បង"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"បន្ទាប់"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"តម្រូវ​ឲ្យ​មានពាក្យ​សម្ងាត់"</string>
diff --git a/packages/SettingsLib/res/values-kn/strings.xml b/packages/SettingsLib/res/values-kn/strings.xml
index c74b7be..b8b8daa 100644
--- a/packages/SettingsLib/res/values-kn/strings.xml
+++ b/packages/SettingsLib/res/values-kn/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"ಕಸ್ಟಮ್ (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"ಸಹಾಯ ಮತ್ತು ಪ್ರತಿಕ್ರಿಯೆ"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"ಮೆನು"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"ಫ್ಯಾಕ್ಟರಿ ರಿಸೆಟ್‌ಗೆ ಪಾಸ್‌ವರ್ಡ್ ನಮೂದಿಸಿ"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"ಮುಂದೆ"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"ಪಾಸ್‌ವರ್ಡ್ ಅಗತ್ಯವಿದೆ"</string>
diff --git a/packages/SettingsLib/res/values-ko/strings.xml b/packages/SettingsLib/res/values-ko/strings.xml
index b7cf515..7b9f354 100644
--- a/packages/SettingsLib/res/values-ko/strings.xml
+++ b/packages/SettingsLib/res/values-ko/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"맞춤(<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"고객센터"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"메뉴"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"데모 모드에서 초기화하려면 비밀번호 입력"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"다음"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"비밀번호 입력 필요"</string>
diff --git a/packages/SettingsLib/res/values-ky/strings.xml b/packages/SettingsLib/res/values-ky/strings.xml
index 1fb4b48..aeece87 100644
--- a/packages/SettingsLib/res/values-ky/strings.xml
+++ b/packages/SettingsLib/res/values-ky/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Ыңгайлаштырылган (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Жардам жана пикир билдирүү"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Меню"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Демо режиминде демейки жөндөөлөргө кайтаруу үчүн сырсөздү киргизиңиз"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Кийинки"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Сырсөз талап кылынат"</string>
diff --git a/packages/SettingsLib/res/values-lo/strings.xml b/packages/SettingsLib/res/values-lo/strings.xml
index 88bdc41..b4dd2be 100644
--- a/packages/SettingsLib/res/values-lo/strings.xml
+++ b/packages/SettingsLib/res/values-lo/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"ປັບແຕ່ງເອງ (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"ຊ່ວຍເຫຼືອ &amp; ຄຳຕິຊົມ"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"ເມນູ"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Enter password to perform factory reset in demo mode"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"ຕໍ່ໄປ"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"​ຕ້ອງ​ໃສ່​ລະ​ຫັດ​ຜ່ານ"</string>
diff --git a/packages/SettingsLib/res/values-lt/strings.xml b/packages/SettingsLib/res/values-lt/strings.xml
index 8ca0d36..8a3d28c 100644
--- a/packages/SettingsLib/res/values-lt/strings.xml
+++ b/packages/SettingsLib/res/values-lt/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Tinkintas (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Pagalba ir atsiliepimai"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Meniu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Įv. slapt. ir atk. gam. nust. dem. rež."</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Kitas"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Būtina nurodyti slaptažodį"</string>
diff --git a/packages/SettingsLib/res/values-lv/strings.xml b/packages/SettingsLib/res/values-lv/strings.xml
index 518eb33..9902b86 100644
--- a/packages/SettingsLib/res/values-lv/strings.xml
+++ b/packages/SettingsLib/res/values-lv/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Pielāgots (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Palīdzība un atsauksmes"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Izvēlne"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Iev. paroli, lai atiest. rūpnīcas iest. dem. režīmā"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Tālāk"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Nepieciešama parole"</string>
diff --git a/packages/SettingsLib/res/values-mk/strings.xml b/packages/SettingsLib/res/values-mk/strings.xml
index 3f7ab8c..0d21398 100644
--- a/packages/SettingsLib/res/values-mk/strings.xml
+++ b/packages/SettingsLib/res/values-mk/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Приспособен (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Помош и повратни информации"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Мени"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Внесете лозинка за фаб. ресет. во демо"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Следно"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Потребна е лозинка"</string>
diff --git a/packages/SettingsLib/res/values-ml/strings.xml b/packages/SettingsLib/res/values-ml/strings.xml
index 635d8a4..cd15513 100644
--- a/packages/SettingsLib/res/values-ml/strings.xml
+++ b/packages/SettingsLib/res/values-ml/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"ഇഷ്ടാനുസൃതം ( <xliff:g id="DENSITYDPI">%d</xliff:g> )"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"സഹായവും പ്രതികരണവും"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"മെനു"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"ഡെമോ ‌മോഡിൽ ഫാക്ടറി റീസെറ്റിന് പാസ്‌വേഡ് നൽകുക"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"അടുത്തത്"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"പാസ്‌വേഡ് ആവശ്യമാണ്"</string>
diff --git a/packages/SettingsLib/res/values-mn/strings.xml b/packages/SettingsLib/res/values-mn/strings.xml
index 1e864da..a6d16c9 100644
--- a/packages/SettingsLib/res/values-mn/strings.xml
+++ b/packages/SettingsLib/res/values-mn/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Тогтмол утга (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Тусламж, санал хүсэлт"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Цэс"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"Гринвичийн цаг"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Үйлдвэрийн тохиргоог демо горимд ажиллуулахын тулд нууц үг оруулна уу"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Дараагийн"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Нууц үг шаардлагатай"</string>
diff --git a/packages/SettingsLib/res/values-mr/strings.xml b/packages/SettingsLib/res/values-mr/strings.xml
index 0d5f90b..eb6b70d 100644
--- a/packages/SettingsLib/res/values-mr/strings.xml
+++ b/packages/SettingsLib/res/values-mr/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"सानुकूल करा (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"मदत आणि अभिप्राय"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"मेनू"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"डेमो मोडमध्ये फॅक्टरी रीसेट करण्यासाठी संकेतशब्द प्रविष्ट करा"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"पुढील"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"संकेतशब्द आवश्यक"</string>
diff --git a/packages/SettingsLib/res/values-ms/strings.xml b/packages/SettingsLib/res/values-ms/strings.xml
index caa07f9..b645116 100644
--- a/packages/SettingsLib/res/values-ms/strings.xml
+++ b/packages/SettingsLib/res/values-ms/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Tersuai (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Bantuan &amp; maklum balas"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Mskkn kta laluan utk ttpn sml kilang dlm mod demo"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Seterusnya"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Kata laluan diperlukan"</string>
diff --git a/packages/SettingsLib/res/values-my/strings.xml b/packages/SettingsLib/res/values-my/strings.xml
index e1f0085..ba50fad 100644
--- a/packages/SettingsLib/res/values-my/strings.xml
+++ b/packages/SettingsLib/res/values-my/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"စိတ်ကြိုက် (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"အကူအညီနှင့် အကြံပြုချက်"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"မီနူး"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"ဂရင်းနစ်စံတော်ချိန်"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"ဒီမိုမုဒ်၌မူလဆက်တင်ထားရန် စကားဝှက်ထည့်ပါ"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"ရှေ့သို့"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"စကားဝှက် လိုအပ်သည်"</string>
diff --git a/packages/SettingsLib/res/values-nb/strings.xml b/packages/SettingsLib/res/values-nb/strings.xml
index 004fcf1e..f0d01c1 100644
--- a/packages/SettingsLib/res/values-nb/strings.xml
+++ b/packages/SettingsLib/res/values-nb/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Egendefinert (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Hjelp og tilbakemelding"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Meny"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Skriv inn passordet for å tilbakestille til fabrikkstandard i demomodus"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Neste"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Passord er obligatorisk"</string>
diff --git a/packages/SettingsLib/res/values-ne/strings.xml b/packages/SettingsLib/res/values-ne/strings.xml
index eac1e24..89460df 100644
--- a/packages/SettingsLib/res/values-ne/strings.xml
+++ b/packages/SettingsLib/res/values-ne/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"आफू अनुकूल (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"मद्दत र प्रतिक्रिया"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"मेनु"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"डेमो मोडमा फ्याक्ट्री रिसेट गर्न पासवर्ड प्रविष्ट गर्नुहोस्"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"अर्को"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"पासवर्ड आवश्यक छ"</string>
diff --git a/packages/SettingsLib/res/values-nl/strings.xml b/packages/SettingsLib/res/values-nl/strings.xml
index 9ca3bfd..bd64e81 100644
--- a/packages/SettingsLib/res/values-nl/strings.xml
+++ b/packages/SettingsLib/res/values-nl/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Aangepast (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Help en feedback"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Geef wachtwoord op om terug te zetten op fabrieksinstellingen in demomodus"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Volgende"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Wachtwoord vereist"</string>
diff --git a/packages/SettingsLib/res/values-pa/strings.xml b/packages/SettingsLib/res/values-pa/strings.xml
index 084b9ed..7c45b8b 100644
--- a/packages/SettingsLib/res/values-pa/strings.xml
+++ b/packages/SettingsLib/res/values-pa/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"ਵਿਸ਼ੇਸ਼-ਵਿਉਂਤਬੱਧ (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"ਮਦਦ ਅਤੇ ਪ੍ਰਤੀਕਰਮ"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"ਮੀਨੂ"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"ਡੈਮੋ ਮੋਡ \'ਚ ਫੈਕਟਰੀ ਰੀਸੈੱਟ ਲਈ ਪਾਸਵਰਡ ਦਿਓ"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"ਅੱਗੇ"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"ਪਾਸਵਰਡ ਦੀ ਲੋੜ ਹੈ"</string>
diff --git a/packages/SettingsLib/res/values-pl/strings.xml b/packages/SettingsLib/res/values-pl/strings.xml
index 58454b4..64b4a34 100644
--- a/packages/SettingsLib/res/values-pl/strings.xml
+++ b/packages/SettingsLib/res/values-pl/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Niestandardowe (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Pomoc i opinie"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Wpisz hasło, by przywrócić ustawienia fabryczne w trybie demonstracyjnym"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Dalej"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Wymagane hasło"</string>
diff --git a/packages/SettingsLib/res/values-pt-rBR/arrays.xml b/packages/SettingsLib/res/values-pt-rBR/arrays.xml
index a444b59..e3f287b 100644
--- a/packages/SettingsLib/res/values-pt-rBR/arrays.xml
+++ b/packages/SettingsLib/res/values-pt-rBR/arrays.xml
@@ -190,9 +190,9 @@
   </string-array>
   <string-array name="animator_duration_scale_entries">
     <item msgid="6039901060648228241">"Animação desativada"</item>
-    <item msgid="1138649021950863198">"Escala de animação 5x"</item>
+    <item msgid="1138649021950863198">"Escala de animação 0,5x"</item>
     <item msgid="4394388961370833040">"Escala de animação 1x"</item>
-    <item msgid="8125427921655194973">"Escala de animação 1.5 x"</item>
+    <item msgid="8125427921655194973">"Escala de animação 1,5x"</item>
     <item msgid="3334024790739189573">"Escala de animação 2x"</item>
     <item msgid="3170120558236848008">"Escala de animação 5x"</item>
     <item msgid="1069584980746680398">"Escala de animação 10x"</item>
diff --git a/packages/SettingsLib/res/values-pt-rBR/strings.xml b/packages/SettingsLib/res/values-pt-rBR/strings.xml
index 3b97a7f..d99834f 100644
--- a/packages/SettingsLib/res/values-pt-rBR/strings.xml
+++ b/packages/SettingsLib/res/values-pt-rBR/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Personalizada (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Ajuda e feedback"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Digite a senha para redef. p/ configuração original em modo demo"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Próxima"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Senha necessária"</string>
diff --git a/packages/SettingsLib/res/values-pt-rPT/strings.xml b/packages/SettingsLib/res/values-pt-rPT/strings.xml
index e2c6b2f..10535e9 100644
--- a/packages/SettingsLib/res/values-pt-rPT/strings.xml
+++ b/packages/SettingsLib/res/values-pt-rPT/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Personalizado (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Ajuda e comentários"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Introduzir palavra-passe para efetuar a reposição de fábrica no modo demo"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Próximo"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Palavra-passe obrigatória"</string>
diff --git a/packages/SettingsLib/res/values-pt/arrays.xml b/packages/SettingsLib/res/values-pt/arrays.xml
index a444b59..e3f287b 100644
--- a/packages/SettingsLib/res/values-pt/arrays.xml
+++ b/packages/SettingsLib/res/values-pt/arrays.xml
@@ -190,9 +190,9 @@
   </string-array>
   <string-array name="animator_duration_scale_entries">
     <item msgid="6039901060648228241">"Animação desativada"</item>
-    <item msgid="1138649021950863198">"Escala de animação 5x"</item>
+    <item msgid="1138649021950863198">"Escala de animação 0,5x"</item>
     <item msgid="4394388961370833040">"Escala de animação 1x"</item>
-    <item msgid="8125427921655194973">"Escala de animação 1.5 x"</item>
+    <item msgid="8125427921655194973">"Escala de animação 1,5x"</item>
     <item msgid="3334024790739189573">"Escala de animação 2x"</item>
     <item msgid="3170120558236848008">"Escala de animação 5x"</item>
     <item msgid="1069584980746680398">"Escala de animação 10x"</item>
diff --git a/packages/SettingsLib/res/values-pt/strings.xml b/packages/SettingsLib/res/values-pt/strings.xml
index 3b97a7f..d99834f 100644
--- a/packages/SettingsLib/res/values-pt/strings.xml
+++ b/packages/SettingsLib/res/values-pt/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Personalizada (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Ajuda e feedback"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Digite a senha para redef. p/ configuração original em modo demo"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Próxima"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Senha necessária"</string>
diff --git a/packages/SettingsLib/res/values-ro/strings.xml b/packages/SettingsLib/res/values-ro/strings.xml
index a3a2b47..38a6e6a 100644
--- a/packages/SettingsLib/res/values-ro/strings.xml
+++ b/packages/SettingsLib/res/values-ro/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Personalizat (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Ajutor și feedback"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Meniu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Introduceți parola pentru a reveni la setările din fabrică în modul demo"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Înainte"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Trebuie să introduceți o parolă"</string>
diff --git a/packages/SettingsLib/res/values-ru/strings.xml b/packages/SettingsLib/res/values-ru/strings.xml
index 905195a..5955c5f 100644
--- a/packages/SettingsLib/res/values-ru/strings.xml
+++ b/packages/SettingsLib/res/values-ru/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Другой (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Справка/отзыв"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Меню"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Чтобы сбросить настройки в деморежиме, введите пароль."</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Далее"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Требуется пароль"</string>
diff --git a/packages/SettingsLib/res/values-si/strings.xml b/packages/SettingsLib/res/values-si/strings.xml
index 9c75355..da1c02e 100644
--- a/packages/SettingsLib/res/values-si/strings.xml
+++ b/packages/SettingsLib/res/values-si/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"අභිරුචි (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"උදව් සහ ප්‍රතිපෝෂණ"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"මෙනුව"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"ආදර්ශන ප්‍රකාර කර්මාන්තශාලා යළි සැකසීමට මුරපදය ඇ. ක."</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"ඊළඟ"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"මුරපදය අවශ්‍යයි"</string>
diff --git a/packages/SettingsLib/res/values-sk/strings.xml b/packages/SettingsLib/res/values-sk/strings.xml
index 595fd4c..19cceae 100644
--- a/packages/SettingsLib/res/values-sk/strings.xml
+++ b/packages/SettingsLib/res/values-sk/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Vlastné (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Pomocník a spätná väzba"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Ponuka"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Zadajte heslo na obnovenie továrenských nastavení v režime ukážky"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Ďalej"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Vyžaduje sa heslo"</string>
diff --git a/packages/SettingsLib/res/values-sl/strings.xml b/packages/SettingsLib/res/values-sl/strings.xml
index b8a0514..3cda4e1 100644
--- a/packages/SettingsLib/res/values-sl/strings.xml
+++ b/packages/SettingsLib/res/values-sl/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Po meri (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Pomoč in povratne informacije"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Meni"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Geslo za tovar. nast. v predstav. načinu"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Naprej"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Vnesite geslo"</string>
diff --git a/packages/SettingsLib/res/values-sq/strings.xml b/packages/SettingsLib/res/values-sq/strings.xml
index 34d0333..edce082 100644
--- a/packages/SettingsLib/res/values-sq/strings.xml
+++ b/packages/SettingsLib/res/values-sq/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"I personalizuar (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Ndihma dhe komentet"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menyja"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Fut fjalëkalimin për të kryer rivendosje në gjendje fabrike në modalitetin e demonstrimit"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Përpara"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Kërkohet fjalëkalimi"</string>
diff --git a/packages/SettingsLib/res/values-sr/strings.xml b/packages/SettingsLib/res/values-sr/strings.xml
index 2b21d30..c05b0ae 100644
--- a/packages/SettingsLib/res/values-sr/strings.xml
+++ b/packages/SettingsLib/res/values-sr/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Прилагођени (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Помоћ и повратне информације"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Мени"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Унесите лозинку да бисте обавили ресетовање на фабричка подешавања у режиму демонстрације"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Даље"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Потребна је лозинка"</string>
diff --git a/packages/SettingsLib/res/values-sv/strings.xml b/packages/SettingsLib/res/values-sv/strings.xml
index d73ec66..73e441c 100644
--- a/packages/SettingsLib/res/values-sv/strings.xml
+++ b/packages/SettingsLib/res/values-sv/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Anpassad (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Hjälp och feedback"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Meny"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Ange lösenord och utför fabriksåterställning i demoläge"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Nästa"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Lösenord krävs"</string>
diff --git a/packages/SettingsLib/res/values-sw/strings.xml b/packages/SettingsLib/res/values-sw/strings.xml
index e1fc468..699b213 100644
--- a/packages/SettingsLib/res/values-sw/strings.xml
+++ b/packages/SettingsLib/res/values-sw/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Kiwango maalum (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Usaidizi na maoni"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menyu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Weka nenosiri ili urejeshe mipangilio ya kiwandani ikiwa katika hali ya onyesho."</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Inayofuata"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Nenosiri linahitajika"</string>
diff --git a/packages/SettingsLib/res/values-ta/strings.xml b/packages/SettingsLib/res/values-ta/strings.xml
index b16a29c..0fb2225 100644
--- a/packages/SettingsLib/res/values-ta/strings.xml
+++ b/packages/SettingsLib/res/values-ta/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"தனிப்பயன் (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"உதவி &amp; கருத்து"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"மெனு"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"டெமோ பயன்முறையில் ஆரம்பநிலை மீட்டமைவைச் செயல்படுத்த, கடவுச்சொல்லை உள்ளிடவும்"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"அடுத்து"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"கடவுச்சொல் தேவை"</string>
diff --git a/packages/SettingsLib/res/values-te/strings.xml b/packages/SettingsLib/res/values-te/strings.xml
index 921af68..4cbf24c 100644
--- a/packages/SettingsLib/res/values-te/strings.xml
+++ b/packages/SettingsLib/res/values-te/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"అనుకూలం (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"సహాయం &amp; అభిప్రాయం"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"మెను"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"డెమో మోడ్‌లో ఫ్యాక్టరీ రీసెట్‌ను నిర్వహించడానికి పాస్‌వర్డ్‌ను నమోదు చేయండి"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"తదుపరి"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"పాస్‌వర్డ్ అవసరం"</string>
diff --git a/packages/SettingsLib/res/values-th/strings.xml b/packages/SettingsLib/res/values-th/strings.xml
index 4f31238..f7b8bf1 100644
--- a/packages/SettingsLib/res/values-th/strings.xml
+++ b/packages/SettingsLib/res/values-th/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"กำหนดเอง (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"ความช่วยเหลือและความคิดเห็น"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"เมนู"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"ป้อนรหัสผ่านเพื่อรีเซ็ตค่าในโหมดสาธิต"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"ถัดไป"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"ต้องป้อนรหัสผ่าน"</string>
diff --git a/packages/SettingsLib/res/values-tl/strings.xml b/packages/SettingsLib/res/values-tl/strings.xml
index 984030d..a1537d5 100644
--- a/packages/SettingsLib/res/values-tl/strings.xml
+++ b/packages/SettingsLib/res/values-tl/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Custom (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Tulong at feedback"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Ilagay ang password upang mag-factory reset sa demo mode"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Susunod"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Kinakailangan ang password"</string>
diff --git a/packages/SettingsLib/res/values-tr/strings.xml b/packages/SettingsLib/res/values-tr/strings.xml
index b0c60f5..380e1bd 100644
--- a/packages/SettingsLib/res/values-tr/strings.xml
+++ b/packages/SettingsLib/res/values-tr/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Özel (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Yardım ve geri bildirim"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menü"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Demo modunda sıfırlamak için şifreyi girin"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Sonraki"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Şifre gerekli"</string>
diff --git a/packages/SettingsLib/res/values-uk/strings.xml b/packages/SettingsLib/res/values-uk/strings.xml
index 0834d04..7c87e95 100644
--- a/packages/SettingsLib/res/values-uk/strings.xml
+++ b/packages/SettingsLib/res/values-uk/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Спеціальний масштаб (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Довідка й відгуки"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Меню"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Введіть пароль, щоб скинути налаштування в демо-режимі"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Далі"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Потрібен пароль"</string>
diff --git a/packages/SettingsLib/res/values-ur/strings.xml b/packages/SettingsLib/res/values-ur/strings.xml
index 3aec6aee..9ad7e78 100644
--- a/packages/SettingsLib/res/values-ur/strings.xml
+++ b/packages/SettingsLib/res/values-ur/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"حسب ضرورت (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"مدد اور تاثرات"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"مینو"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"ڈیمو موڈ میں فیکٹری ری سیٹ کیلئے پاس ورڈ درج کریں"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"اگلا"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"پاس ورڈ درکار ہے"</string>
diff --git a/packages/SettingsLib/res/values-uz/strings.xml b/packages/SettingsLib/res/values-uz/strings.xml
index 5c4d3bd..5b686df 100644
--- a/packages/SettingsLib/res/values-uz/strings.xml
+++ b/packages/SettingsLib/res/values-uz/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Moslashtirilgan (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Yordam va fikr-mulohaza"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menyu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Demo rejimda zavod holatiga qaytarish uchun parolni kiriting"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Keyingisi"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Parolni kiritish zarur"</string>
diff --git a/packages/SettingsLib/res/values-vi/strings.xml b/packages/SettingsLib/res/values-vi/strings.xml
index db2b29d..6a261db 100644
--- a/packages/SettingsLib/res/values-vi/strings.xml
+++ b/packages/SettingsLib/res/values-vi/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Tùy chỉnh (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Trợ giúp và phản hồi"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Menu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Nhập mật khẩu để tiến hành khôi phục cài đặt gốc ở chế độ trình diễn"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Tiếp theo"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Yêu cầu mật khẩu"</string>
diff --git a/packages/SettingsLib/res/values-zh-rCN/strings.xml b/packages/SettingsLib/res/values-zh-rCN/strings.xml
index 1fe8778..386478319 100644
--- a/packages/SettingsLib/res/values-zh-rCN/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rCN/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"自定义 (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"帮助和反馈"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"菜单"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"输入密码即可在演示模式下恢复出厂设置"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"下一步"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"需要输入密码"</string>
diff --git a/packages/SettingsLib/res/values-zh-rHK/strings.xml b/packages/SettingsLib/res/values-zh-rHK/strings.xml
index 080a417..00e0c9a 100644
--- a/packages/SettingsLib/res/values-zh-rHK/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rHK/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"自訂 (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"說明和意見反映"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"選單"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"輸入密碼即可在示範模式下重設原廠設定"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"下一步"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"請輸入密碼"</string>
diff --git a/packages/SettingsLib/res/values-zh-rTW/strings.xml b/packages/SettingsLib/res/values-zh-rTW/strings.xml
index b3c5212..76710b0 100644
--- a/packages/SettingsLib/res/values-zh-rTW/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rTW/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"自訂 (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"說明與意見回饋"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"選單"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"如要在示範模式中恢復原廠設定,請輸入密碼"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"下一步"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"請輸入密碼"</string>
diff --git a/packages/SettingsLib/res/values-zu/strings.xml b/packages/SettingsLib/res/values-zu/strings.xml
index f3c27a1..5da00bb 100644
--- a/packages/SettingsLib/res/values-zu/strings.xml
+++ b/packages/SettingsLib/res/values-zu/strings.xml
@@ -375,7 +375,6 @@
     <string name="screen_zoom_summary_custom" msgid="5611979864124160447">"Ngokwezifiso (<xliff:g id="DENSITYDPI">%d</xliff:g>)"</string>
     <string name="help_feedback_label" msgid="6815040660801785649">"Usizo nempendulo"</string>
     <string name="content_description_menu_button" msgid="8182594799812351266">"Imenyu"</string>
-    <string name="time_zone_gmt" msgid="2587097992671450782">"I-GMT"</string>
     <string name="retail_demo_reset_message" msgid="118771671364131297">"Faka iphasiwedi ukuze wenze ukusetha kwefekthri kumodi yedemo"</string>
     <string name="retail_demo_reset_next" msgid="8356731459226304963">"Okulandelayo"</string>
     <string name="retail_demo_reset_title" msgid="696589204029930100">"Iphasiwedi iyadingeka"</string>
diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml
index 5fc58dc..259446a 100644
--- a/packages/SettingsLib/res/values/strings.xml
+++ b/packages/SettingsLib/res/values/strings.xml
@@ -243,6 +243,12 @@
     <!-- Content description of the WIFI signal when it is full for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
     <string name="accessibility_wifi_signal_full">Wifi signal full.</string>
 
+    <!-- Content description of the Wi-Fi security type. This message indicates this is an open Wi-Fi (no password needed) [CHAR LIMIT=NONE] -->
+    <string name="accessibility_wifi_security_type_none">Open network</string>
+
+    <!-- Content description of the Wi-Fi security type. This message indicates this is a secured Wi-Fi (password needed) [CHAR LIMIT=NONE] -->
+    <string name="accessibility_wifi_security_type_secured">Secure network</string>
+
     <!-- Label for kernel threads in battery usage -->
     <string name="process_kernel_label">Android OS</string>
     <!-- Title of data usage item that represents all uninstalled applications. [CHAR LIMIT=48] -->
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java b/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java
index f5282b7..01d9014 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java
@@ -28,9 +28,11 @@
 import android.net.NetworkInfo;
 import android.net.NetworkInfo.DetailedState;
 import android.net.NetworkInfo.State;
+import android.net.NetworkKey;
 import android.net.NetworkScoreManager;
 import android.net.NetworkScorerAppData;
 import android.net.ScoredNetwork;
+import android.net.WifiKey;
 import android.net.wifi.IWifiManager;
 import android.net.wifi.ScanResult;
 import android.net.wifi.WifiConfiguration;
@@ -125,6 +127,7 @@
     static final String KEY_SCANRESULT = "key_scanresult";
     static final String KEY_SSID = "key_ssid";
     static final String KEY_SECURITY = "key_security";
+    static final String KEY_SPEED = "key_speed";
     static final String KEY_PSKTYPE = "key_psktype";
     static final String KEY_SCANRESULTCACHE = "key_scanresultcache";
     static final String KEY_CONFIG = "key_config";
@@ -200,10 +203,13 @@
         if (savedState.containsKey(KEY_SECURITY)) {
             security = savedState.getInt(KEY_SECURITY);
         }
+        if (savedState.containsKey(KEY_SPEED)) {
+            mSpeed = savedState.getInt(KEY_SPEED);
+        }
         if (savedState.containsKey(KEY_PSKTYPE)) {
             pskType = savedState.getInt(KEY_PSKTYPE);
         }
-        mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO);
+        mInfo = savedState.getParcelable(KEY_WIFIINFO);
         if (savedState.containsKey(KEY_NETWORKINFO)) {
             mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
         }
@@ -407,17 +413,34 @@
         mSpeed = Speed.NONE;
         mRankingScore = Integer.MIN_VALUE;
 
-        for (ScanResult result : mScanResultCache.values()) {
-            ScoredNetwork score = scoreCache.getScoredNetwork(result);
-            if (score == null) {
-                continue;
+        if (isActive() && mInfo != null) {
+            NetworkKey key = new NetworkKey(new WifiKey(
+                    AccessPoint.convertToQuotedString(ssid), mInfo.getBSSID()));
+            ScoredNetwork score = scoreCache.getScoredNetwork(key);
+            if (score != null) {
+                mSpeed = score.calculateBadge(mInfo.getRssi());
+                if (score.hasRankingScore()) {
+                    mRankingScore = score.calculateRankingScore(mInfo.getRssi());
+                }
             }
+        } else {
+            for (ScanResult result : mScanResultCache.values()) {
+                ScoredNetwork score = scoreCache.getScoredNetwork(result);
+                if (score == null) {
+                    continue;
+                }
 
-            if (score.hasRankingScore()) {
-                mRankingScore = Math.max(mRankingScore, score.calculateRankingScore(result.level));
+                if (score.hasRankingScore()) {
+                    mRankingScore =
+                            Math.max(mRankingScore, score.calculateRankingScore(result.level));
+                }
+                // TODO(sghuman): Rename calculateBadge API
+                mSpeed = Math.max(mSpeed, score.calculateBadge(result.level));
             }
-            // TODO(sghuman): Rename calculateBadge API
-            mSpeed = Math.max(mSpeed, score.calculateBadge(result.level));
+        }
+
+        if(WifiTracker.sVerboseLogging) {
+            Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed));
         }
 
         return (oldSpeed != mSpeed || oldRankingScore != mRankingScore);
@@ -430,12 +453,22 @@
     private boolean updateMetered(WifiNetworkScoreCache scoreCache) {
         boolean oldMetering = mIsScoredNetworkMetered;
         mIsScoredNetworkMetered = false;
-        for (ScanResult result : mScanResultCache.values()) {
-            ScoredNetwork score = scoreCache.getScoredNetwork(result);
-            if (score == null) {
-                continue;
+
+        if (isActive() && mInfo != null) {
+            NetworkKey key = new NetworkKey(new WifiKey(
+                    AccessPoint.convertToQuotedString(ssid), mInfo.getBSSID()));
+            ScoredNetwork score = scoreCache.getScoredNetwork(key);
+            if (score != null) {
+                mIsScoredNetworkMetered |= score.meteredHint;
             }
-            mIsScoredNetworkMetered |= score.meteredHint;
+        } else {
+            for (ScanResult result : mScanResultCache.values()) {
+                ScoredNetwork score = scoreCache.getScoredNetwork(result);
+                if (score == null) {
+                    continue;
+                }
+                mIsScoredNetworkMetered |= score.meteredHint;
+            }
         }
         return oldMetering == mIsScoredNetworkMetered;
     }
@@ -1004,6 +1037,7 @@
     public void saveWifiState(Bundle savedState) {
         if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
         savedState.putInt(KEY_SECURITY, security);
+        savedState.putInt(KEY_SPEED, mSpeed);
         savedState.putInt(KEY_PSKTYPE, pskType);
         if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
         savedState.putParcelable(KEY_WIFIINFO, mInfo);
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPointPreference.java b/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPointPreference.java
index 92995a8..2c4f9c4 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPointPreference.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPointPreference.java
@@ -25,6 +25,7 @@
 import android.net.wifi.WifiConfiguration;
 import android.os.Looper;
 import android.os.UserHandle;
+import android.support.annotation.VisibleForTesting;
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.PreferenceViewHolder;
 import android.text.TextUtils;
@@ -47,7 +48,17 @@
             R.attr.state_metered
     };
 
-    private static final int[] wifi_friction_attributes = { R.attr.wifi_friction };
+    private static final int[] FRICTION_ATTRS = {
+            R.attr.wifi_friction
+    };
+
+    private static final int[] WIFI_CONNECTION_STRENGTH = {
+            R.string.accessibility_no_wifi,
+            R.string.accessibility_wifi_one_bar,
+            R.string.accessibility_wifi_two_bars,
+            R.string.accessibility_wifi_three_bars,
+            R.string.accessibility_wifi_signal_full
+    };
 
     private final StateListDrawable mFrictionSld;
     private final int mBadgePadding;
@@ -62,14 +73,6 @@
     private int mDefaultIconResId;
     private int mWifiSpeed = NetworkBadging.BADGING_NONE;
 
-    static final int[] WIFI_CONNECTION_STRENGTH = {
-            R.string.accessibility_no_wifi,
-            R.string.accessibility_wifi_one_bar,
-            R.string.accessibility_wifi_two_bars,
-            R.string.accessibility_wifi_three_bars,
-            R.string.accessibility_wifi_signal_full
-    };
-
     public static String generatePreferenceKey(AccessPoint accessPoint) {
         StringBuilder builder = new StringBuilder();
 
@@ -103,7 +106,7 @@
 
         TypedArray frictionSld;
         try {
-            frictionSld = context.getTheme().obtainStyledAttributes(wifi_friction_attributes);
+            frictionSld = context.getTheme().obtainStyledAttributes(FRICTION_ATTRS);
         } catch (Resources.NotFoundException e) {
             // Fallback for platforms that do not need friction icon resources.
             frictionSld = null;
@@ -129,7 +132,7 @@
 
         TypedArray frictionSld;
         try {
-            frictionSld = context.getTheme().obtainStyledAttributes(wifi_friction_attributes);
+            frictionSld = context.getTheme().obtainStyledAttributes(FRICTION_ATTRS);
         } catch (Resources.NotFoundException e) {
             // Fallback for platforms that do not need friction icon resources.
             frictionSld = null;
@@ -249,14 +252,7 @@
         setSummary(mForSavedNetworks ? mAccessPoint.getSavedNetworkSummary()
                 : mAccessPoint.getSettingsSummary());
 
-        mContentDescription = getTitle();
-        if (getSummary() != null) {
-            mContentDescription = TextUtils.concat(mContentDescription, ",", getSummary());
-        }
-        if (level >= 0 && level < WIFI_CONNECTION_STRENGTH.length) {
-            mContentDescription = TextUtils.concat(mContentDescription, ",",
-                    getContext().getString(WIFI_CONNECTION_STRENGTH[level]));
-        }
+        mContentDescription = buildContentDescription(getContext(), this /* pref */, mAccessPoint);
     }
 
     @Override
@@ -269,6 +265,27 @@
         }
     }
 
+    /**
+     * Helper method to generate content description string.
+     */
+    @VisibleForTesting
+    static CharSequence buildContentDescription(Context context, Preference pref, AccessPoint ap) {
+        CharSequence contentDescription = pref.getTitle();
+        final CharSequence summary = pref.getSummary();
+        if (!TextUtils.isEmpty(summary)) {
+            contentDescription = TextUtils.concat(contentDescription, ",", summary);
+        }
+        int level = ap.getLevel();
+        if (level >= 0 && level < WIFI_CONNECTION_STRENGTH.length) {
+            contentDescription = TextUtils.concat(contentDescription, ",",
+                    context.getString(WIFI_CONNECTION_STRENGTH[level]));
+        }
+        return TextUtils.concat(contentDescription, ",",
+                ap.getSecurity() == AccessPoint.SECURITY_NONE
+                        ? context.getString(R.string.accessibility_wifi_security_type_none)
+                        : context.getString(R.string.accessibility_wifi_security_type_secured));
+    }
+
     public void onLevelChanged() {
         postNotifyChanged();
     }
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/TestAccessPointBuilder.java b/packages/SettingsLib/src/com/android/settingslib/wifi/TestAccessPointBuilder.java
index 4307cb0..46a53a3 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/TestAccessPointBuilder.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/TestAccessPointBuilder.java
@@ -19,10 +19,13 @@
 import android.content.Context;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
+import android.net.wifi.ScanResult;
 import android.net.wifi.WifiConfiguration;
 import android.net.wifi.WifiInfo;
 import android.os.Bundle;
 
+import java.util.ArrayList;
+
 /**
 * Build and return a valid AccessPoint.
 *
@@ -48,6 +51,7 @@
     private WifiInfo mWifiInfo;
 
     Context mContext;
+    private ArrayList<ScanResult> mScanResultCache;
 
     public TestAccessPointBuilder(Context context) {
         mContext = context;
@@ -70,6 +74,9 @@
         if (mProviderFriendlyName != null) {
             bundle.putString(AccessPoint.KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
         }
+        if (mScanResultCache != null) {
+            bundle.putParcelableArrayList(AccessPoint.KEY_SCANRESULTCACHE, mScanResultCache);
+        }
         bundle.putInt(AccessPoint.KEY_SECURITY, mSecurity);
 
         AccessPoint ap = new AccessPoint(mContext, bundle);
@@ -186,4 +193,9 @@
         mBssid = bssid;
         return this;
     }
+
+    public TestAccessPointBuilder setScanResultCache(ArrayList<ScanResult> scanResultCache) {
+        mScanResultCache = scanResultCache;
+        return this;
+    }
 }
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiTracker.java b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiTracker.java
index f0ac31f..b945700 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiTracker.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiTracker.java
@@ -250,6 +250,10 @@
             mLastNetworkInfo = mConnectivityManager.getNetworkInfo(mWifiManager.getCurrentNetwork());
 
             final List<ScanResult> newScanResults = mWifiManager.getScanResults();
+            if (sVerboseLogging) {
+                Log.i(TAG, "Fetched scan results: " + newScanResults);
+            }
+
             List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
             updateAccessPointsLocked(newScanResults, configs);
 
@@ -480,6 +484,9 @@
     private void updateAccessPoints() {
         List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
         final List<ScanResult> newScanResults = mWifiManager.getScanResults();
+        if (sVerboseLogging) {
+            Log.i(TAG, "Fetched scan results: " + newScanResults);
+        }
 
         synchronized (mLock) {
             if(!mStaleScanResults) {
diff --git a/packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/AccessPointTest.java b/packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/AccessPointTest.java
index aed0270..9a3f21f 100644
--- a/packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/AccessPointTest.java
+++ b/packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/AccessPointTest.java
@@ -21,6 +21,8 @@
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.anyInt;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
@@ -389,6 +391,39 @@
     }
 
     @Test
+    public void testSpeedLabel_isDerivedFromConnectedBssid() {
+        int rssi = -55;
+        String bssid = "00:00:00:00:00:00";
+        int networkId = 123;
+
+        WifiInfo info = new WifiInfo();
+        info.setRssi(rssi);
+        info.setSSID(WifiSsid.createFromAsciiEncoded(TEST_SSID));
+        info.setBSSID(bssid);
+        info.setNetworkId(networkId);
+
+        AccessPoint ap =
+                new TestAccessPointBuilder(mContext)
+                        .setActive(true)
+                        .setNetworkId(networkId)
+                        .setSsid(TEST_SSID)
+                        .setScanResultCache(buildScanResultCache())
+                        .setWifiInfo(info)
+                        .build();
+
+        NetworkKey key = new NetworkKey(new WifiKey('"' + TEST_SSID + '"', bssid));
+        when(mockWifiNetworkScoreCache.getScoredNetwork(key))
+                .thenReturn(buildScoredNetworkWithMockBadgeCurve());
+        when(mockBadgeCurve.lookupScore(anyInt())).thenReturn((byte) AccessPoint.Speed.FAST);
+
+        ap.update(mockWifiNetworkScoreCache, true /* scoringUiEnabled */);
+
+        verify(mockWifiNetworkScoreCache, times(2)).getScoredNetwork(key);
+        verify(mockWifiNetworkScoreCache, never()).getScoredNetwork(any(ScanResult.class));
+        assertThat(ap.getSpeed()).isEqualTo(AccessPoint.Speed.FAST);
+    }
+
+    @Test
     public void testSummaryString_showsSpeedLabel() {
         AccessPoint ap = createAccessPointWithScanResultCache();
 
@@ -443,6 +478,12 @@
 
     private AccessPoint createAccessPointWithScanResultCache() {
         Bundle bundle = new Bundle();
+        ArrayList<ScanResult> scanResults = buildScanResultCache();
+        bundle.putParcelableArrayList(AccessPoint.KEY_SCANRESULTCACHE, scanResults);
+        return new AccessPoint(mContext, bundle);
+    }
+
+    private ArrayList<ScanResult> buildScanResultCache() {
         ArrayList<ScanResult> scanResults = new ArrayList<>();
         for (int i = 0; i < 5; i++) {
             ScanResult scanResult = new ScanResult();
@@ -452,9 +493,7 @@
             scanResult.capabilities = "";
             scanResults.add(scanResult);
         }
-
-        bundle.putParcelableArrayList(AccessPoint.KEY_SCANRESULTCACHE, scanResults);
-        return new AccessPoint(mContext, bundle);
+        return scanResults;
     }
 
     private WifiConfiguration createWifiConfiguration() {
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/SettingLibRobolectricTestRunner.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/SettingLibRobolectricTestRunner.java
index fd3b1dc6..482b788 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/SettingLibRobolectricTestRunner.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/SettingLibRobolectricTestRunner.java
@@ -20,6 +20,9 @@
 import org.robolectric.annotation.Config;
 import org.robolectric.manifest.AndroidManifest;
 import org.robolectric.res.Fs;
+import org.robolectric.res.ResourcePath;
+
+import java.util.List;
 
 public class SettingLibRobolectricTestRunner extends RobolectricTestRunner {
 
@@ -36,10 +39,31 @@
         final String assetsDir = appRoot + config.assetDir();
 
         final AndroidManifest manifest = new AndroidManifest(Fs.fileFromPath(manifestPath),
-                Fs.fileFromPath(resDir), Fs.fileFromPath(assetsDir));
-
+                Fs.fileFromPath(resDir), Fs.fileFromPath(assetsDir)) {
+            @Override
+            public List<ResourcePath> getIncludedResourcePaths() {
+                List<ResourcePath> paths = super.getIncludedResourcePaths();
+                SettingLibRobolectricTestRunner.getIncludedResourcePaths(getPackageName(), paths);
+                return paths;
+            }
+        };
         manifest.setPackageName("com.android.settingslib");
         return manifest;
     }
 
+    static void getIncludedResourcePaths(String packageName, List<ResourcePath> paths) {
+        paths.add(new ResourcePath(
+                packageName,
+                Fs.fileFromPath("./frameworks/base/packages/SettingsLib/res"),
+                null));
+        paths.add(new ResourcePath(
+                packageName,
+                Fs.fileFromPath("./frameworks/base/core/res/res"),
+                null));
+        paths.add(new ResourcePath(
+                packageName,
+                Fs.fileFromPath("./frameworks/support/v7/appcompat/res"),
+                null));
+    }
+
 }
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/wifi/AccessPointPreferenceTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/wifi/AccessPointPreferenceTest.java
index 335653b..7fe69a7 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/wifi/AccessPointPreferenceTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/wifi/AccessPointPreferenceTest.java
@@ -16,6 +16,8 @@
 package com.android.settingslib.wifi;
 
 import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 import android.content.Context;
 
@@ -58,4 +60,22 @@
         assertThat(AccessPointPreference.generatePreferenceKey(builder.build()))
                 .isEqualTo(expectedKey);
     }
+
+    @Test
+    public void refresh_openNetwork_updateContentDescription() {
+        final String ssid = "ssid";
+        final String summary = "connected";
+        final int security = AccessPoint.SECURITY_WEP;
+        final AccessPoint ap = new TestAccessPointBuilder(mContext)
+                .setSsid(ssid)
+                .setSecurity(security)
+                .build();
+        final AccessPointPreference pref = mock(AccessPointPreference.class);
+        when(pref.getTitle()).thenReturn(ssid);
+        when(pref.getSummary()).thenReturn(summary);
+
+        assertThat(AccessPointPreference.buildContentDescription(
+                RuntimeEnvironment.application, pref, ap))
+                .isEqualTo("ssid,connected,Wifi signal full.,Secure network");
+    }
 }
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
index 8abdc64..6247b3b 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
@@ -16,6 +16,11 @@
 
 package com.android.providers.settings;
 
+import com.android.internal.R;
+import com.android.internal.app.LocalePicker;
+import com.android.internal.annotations.VisibleForTesting;
+
+import android.annotation.NonNull;
 import android.app.ActivityManager;
 import android.app.IActivityManager;
 import android.app.backup.IBackupManager;
@@ -24,11 +29,13 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.res.Configuration;
+import android.icu.util.ULocale;
 import android.location.LocationManager;
 import android.media.AudioManager;
 import android.media.RingtoneManager;
 import android.net.Uri;
 import android.os.IPowerManager;
+import android.os.LocaleList;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.UserHandle;
@@ -39,6 +46,9 @@
 import android.util.ArraySet;
 import android.util.Slog;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
 import java.util.Locale;
 
 public class SettingsHelper {
@@ -305,59 +315,106 @@
         }
     }
 
-    byte[] getLocaleData() {
+    /* package */ byte[] getLocaleData() {
         Configuration conf = mContext.getResources().getConfiguration();
-        final Locale loc = conf.locale;
-        String localeString = loc.getLanguage();
-        String country = loc.getCountry();
-        if (!TextUtils.isEmpty(country)) {
-            localeString += "-" + country;
+        return conf.getLocales().toLanguageTags().getBytes();
+    }
+
+    private static Locale toFullLocale(@NonNull Locale locale) {
+        if (locale.getScript().isEmpty() || locale.getCountry().isEmpty()) {
+            return ULocale.addLikelySubtags(ULocale.forLocale(locale)).toLocale();
         }
-        return localeString.getBytes();
+        return locale;
     }
 
     /**
-     * Sets the locale specified. Input data is the byte representation of a
-     * BCP-47 language tag. For backwards compatibility, strings of the form
+     * Merging the locale came from backup server and current device locale.
+     *
+     * Merge works with following rules.
+     * - The backup locales are appended to the current locale with keeping order.
+     *   e.g. current locale "en-US,zh-CN" and backup locale "ja-JP,ko-KR" are merged to
+     *   "en-US,zh-CH,ja-JP,ko-KR".
+     *
+     * - Duplicated locales are dropped.
+     *   e.g. current locale "en-US,zh-CN" and backup locale "ja-JP,zh-Hans-CN,en-US" are merged to
+     *   "en-US,zh-CN,ja-JP".
+     *
+     * - Unsupported locales are dropped.
+     *   e.g. current locale "en-US" and backup locale "ja-JP,zh-CN" but the supported locales
+     *   are "en-US,zh-CN", the merged locale list is "en-US,zh-CN".
+     *
+     * - The final result locale list only contains the supported locales.
+     *   e.g. current locale "en-US" and backup locale "zh-Hans-CN" and supported locales are
+     *   "en-US,zh-CN", the merged locale list is "en-US,zh-CN".
+     *
+     * @param restore The locale list that came from backup server.
+     * @param current The device's locale setting.
+     * @param supportedLocales The list of language tags supported by this device.
+     */
+    @VisibleForTesting
+    public static LocaleList resolveLocales(LocaleList restore, LocaleList current,
+            String[] supportedLocales) {
+        final HashMap<Locale, Locale> allLocales = new HashMap<>(supportedLocales.length);
+        for (String supportedLocaleStr : supportedLocales) {
+            final Locale locale = Locale.forLanguageTag(supportedLocaleStr);
+            allLocales.put(toFullLocale(locale), locale);
+        }
+
+        final ArrayList<Locale> filtered = new ArrayList<>(current.size());
+        for (int i = 0; i < current.size(); i++) {
+            final Locale locale = current.get(i);
+            allLocales.remove(toFullLocale(locale));
+            filtered.add(locale);
+        }
+
+        for (int i = 0; i < restore.size(); i++) {
+            final Locale locale = allLocales.remove(toFullLocale(restore.get(i)));
+            if (locale != null) {
+                filtered.add(locale);
+            }
+        }
+
+        if (filtered.size() == current.size()) {
+            return current;  // Nothing added to current locale list.
+        }
+
+        return new LocaleList(filtered.toArray(new Locale[filtered.size()]));
+    }
+
+    /**
+     * Sets the locale specified. Input data is the byte representation of comma separated
+     * multiple BCP-47 language tags. For backwards compatibility, strings of the form
      * {@code ll_CC} are also accepted, where {@code ll} is a two letter language
      * code and {@code CC} is a two letter country code.
      *
-     * @param data the locale string in bytes.
+     * @param data the comma separated BCP-47 language tags in bytes.
      */
-    void setLocaleData(byte[] data, int size) {
-        // Check if locale was set by the user:
-        final ContentResolver cr = mContext.getContentResolver();
-        final boolean userSetLocale = mContext.getResources().getConfiguration().userSetLocale;
-        final boolean provisioned = Settings.Global.getInt(cr,
-                Settings.Global.DEVICE_PROVISIONED, 0) != 0;
-        if (userSetLocale || provisioned) {
-            // Don't change if user set it in the SetupWizard, or if this is a post-setup
-            // deferred restore operation
-            Slog.i(TAG, "Not applying restored locale; "
-                    + (userSetLocale ? "user already specified" : "device already provisioned"));
+    /* package */ void setLocaleData(byte[] data, int size) {
+        final Configuration conf = mContext.getResources().getConfiguration();
+
+        // Replace "_" with "-" to deal with older backups.
+        final String localeCodes = new String(data, 0, size).replace('_', '-');
+        final LocaleList localeList = LocaleList.forLanguageTags(localeCodes);
+        if (localeList.isEmpty()) {
             return;
         }
 
-        final String[] availableLocales = mContext.getAssets().getLocales();
-        // Replace "_" with "-" to deal with older backups.
-        String localeCode = new String(data, 0, size).replace('_', '-');
-        Locale loc = null;
-        for (int i = 0; i < availableLocales.length; i++) {
-            if (availableLocales[i].equals(localeCode)) {
-                loc = Locale.forLanguageTag(localeCode);
-                break;
-            }
+        final String[] supportedLocales = LocalePicker.getSupportedLocales(mContext);
+        final LocaleList currentLocales = conf.getLocales();
+
+        final LocaleList merged = resolveLocales(localeList, currentLocales, supportedLocales);
+        if (merged.equals(currentLocales)) {
+            return;
         }
-        if (loc == null) return; // Couldn't find the saved locale in this version of the software
 
         try {
             IActivityManager am = ActivityManager.getService();
             Configuration config = am.getConfiguration();
-            config.locale = loc;
+            config.setLocales(merged);
             // indicate this isn't some passing default - the user wants this remembered
             config.userSetLocale = true;
 
-            am.updateConfiguration(config);
+            am.updatePersistentConfiguration(config);
         } catch (RemoteException e) {
             // Intentionally left blank
         }
diff --git a/packages/SettingsProvider/test/Android.mk b/packages/SettingsProvider/test/Android.mk
index 85e611f..a9707d4 100644
--- a/packages/SettingsProvider/test/Android.mk
+++ b/packages/SettingsProvider/test/Android.mk
@@ -4,10 +4,11 @@
 
 LOCAL_MODULE_TAGS := tests
 
-# Note we statically link SettingsState to do some unit tests.  It's not accessible otherwise
+# Note we statically link several classes to do some unit tests.  It's not accessible otherwise
 # because this test is not an instrumentation test. (because the target runs in the system process.)
 LOCAL_SRC_FILES := $(call all-subdir-java-files) \
-    ../src/com/android/providers/settings/SettingsState.java
+    ../src/com/android/providers/settings/SettingsState.java \
+    ../src/com/android/providers/settings/SettingsHelper.java
 
 LOCAL_STATIC_JAVA_LIBRARIES := android-support-test
 
diff --git a/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsHelperTest.java b/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsHelperTest.java
new file mode 100644
index 0000000..6fa014d
--- /dev/null
+++ b/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsHelperTest.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.providers.settings;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertSame;
+import static junit.framework.Assert.assertNull;
+import static junit.framework.Assert.fail;
+
+import com.android.internal.app.LocalePicker;
+import com.android.providers.settings.SettingsHelper;
+
+import android.os.LocaleList;
+import android.support.test.runner.AndroidJUnit4;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Tests for the SettingsHelperTest
+ */
+@RunWith(AndroidJUnit4.class)
+public class SettingsHelperTest {
+    @Test
+    public void testResolveLocales() throws Exception {
+        // Empty string from backup server
+        assertEquals(LocaleList.forLanguageTags("en-US"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags(""),  // restore
+                        LocaleList.forLanguageTags("en-US"),  // current
+                        new String[] { "en-US" }));  // supported
+
+        // Same as current settings
+        assertEquals(LocaleList.forLanguageTags("en-US"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("en-US"),  // restore
+                        LocaleList.forLanguageTags("en-US"),  // current
+                        new String[] { "en-US" }));  // supported
+
+        assertEquals(LocaleList.forLanguageTags("en-US,ja-JP"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("en-US,ja-JP"),  // restore
+                        LocaleList.forLanguageTags("en-US,ja-JP"),  // current
+                        new String[] { "en-US", "ja-JP" }));  // supported
+
+        // Current locale must be kept at the first place.
+        assertEquals(LocaleList.forLanguageTags("ja-JP,en-US"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("en-US"),  // restore
+                        LocaleList.forLanguageTags("ja-JP"),  // current
+                        new String[] { "en-US", "ja-JP" }));  // supported
+
+        assertEquals(LocaleList.forLanguageTags("ja-JP,ko-KR,en-US"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("en-US"),  // restore
+                        LocaleList.forLanguageTags("ja-JP,ko-KR"),  // current
+                        new String[] { "en-US", "ja-JP", "ko-KR" }));  // supported
+
+        assertEquals(LocaleList.forLanguageTags("ja-JP,en-US,ko-KR"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("en-US,ko-KR"),  // restore
+                        LocaleList.forLanguageTags("ja-JP"),  // current
+                        new String[] { "en-US", "ja-JP", "ko-KR" }));  // supported
+
+        // Duplicated entries must be removed.
+        assertEquals(LocaleList.forLanguageTags("ja-JP,ko-KR,en-US"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("en-US,ko-KR"),  // restore
+                        LocaleList.forLanguageTags("ja-JP,ko-KR"),  // current
+                        new String[] { "en-US", "ja-JP", "ko-KR" }));  // supported
+
+        // Drop unsupported locales.
+        assertEquals(LocaleList.forLanguageTags("en-US"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("en-US,zh-CN"),  // restore
+                        LocaleList.forLanguageTags("en-US"),  // current
+                        new String[] { "en-US" }));  // supported
+
+        // Comparison happens on fully-expanded locale.
+        assertEquals(LocaleList.forLanguageTags("en-US,sr-Latn-SR,sr-Cryl-SR"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("sr-Cryl-SR"),  // restore
+                        LocaleList.forLanguageTags("en-US,sr-Latn-SR"),  // current
+                        new String[] { "en-US", "sr-Latn-SR", "sr-Cryl-SR" }));  // supported
+
+        assertEquals(LocaleList.forLanguageTags("en-US"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("kk-Cryl-KZ"),  // restore
+                        LocaleList.forLanguageTags("en-US"),  // current
+                        new String[] { "en-US", "kk-Latn-KZ" }));  // supported
+
+        assertEquals(LocaleList.forLanguageTags("en-US,kk-Cryl-KZ"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("kk-Cryl-KZ"),  // restore
+                        LocaleList.forLanguageTags("en-US"),  // current
+                        new String[] { "en-US", "kk-Cryl-KZ" }));  // supported
+
+        assertEquals(LocaleList.forLanguageTags("en-US,zh-CN"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("zh-Hans-CN"),  // restore
+                        LocaleList.forLanguageTags("en-US"),  // current
+                        new String[] { "en-US", "zh-CN" }));  // supported
+
+        assertEquals(LocaleList.forLanguageTags("en-US,zh-Hans-CN"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("zh-CN"),  // restore
+                        LocaleList.forLanguageTags("en-US"),  // current
+                        new String[] { "en-US", "zh-Hans-CN" }));  // supported
+
+        // Old langauge code should be updated.
+        assertEquals(LocaleList.forLanguageTags("en-US,he-IL,id-ID,yi"),
+                SettingsHelper.resolveLocales(
+                        LocaleList.forLanguageTags("iw-IL,in-ID,ji"),  // restore
+                        LocaleList.forLanguageTags("en-US"),  // current
+                        new String[] { "he-IL", "id-ID", "yi" }));  // supported
+    }
+}
diff --git a/packages/SystemUI/res-keyguard/layout/keyguard_status_view.xml b/packages/SystemUI/res-keyguard/layout/keyguard_status_view.xml
index ef16eba..138733e 100644
--- a/packages/SystemUI/res-keyguard/layout/keyguard_status_view.xml
+++ b/packages/SystemUI/res-keyguard/layout/keyguard_status_view.xml
@@ -76,6 +76,7 @@
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_marginTop="@dimen/date_owner_info_margin"
+            android:layout_gravity="center_horizontal"
             android:layout_centerHorizontal="true"
             android:textColor="?attr/wallpaperTextColorSecondary"
             android:textSize="@dimen/widget_label_font_size"
diff --git a/packages/SystemUI/res-keyguard/values-ja/strings.xml b/packages/SystemUI/res-keyguard/values-ja/strings.xml
index c108d1e..ecd27de 100644
--- a/packages/SystemUI/res-keyguard/values-ja/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ja/strings.xml
@@ -110,9 +110,9 @@
     <string name="kg_prompt_reason_restart_pattern" msgid="7246972020562621506">"端末の再起動後はパターンの入力が必要となります"</string>
     <string name="kg_prompt_reason_restart_pin" msgid="6303592361322290145">"端末の再起動後は PIN の入力が必要となります"</string>
     <string name="kg_prompt_reason_restart_password" msgid="6984641181515902406">"端末の再起動後はパスワードの入力が必要となります"</string>
-    <string name="kg_prompt_reason_timeout_pattern" msgid="5304487696073914063">"セキュリティを強化するにはパターンが必要です"</string>
-    <string name="kg_prompt_reason_timeout_pin" msgid="8851462864335757813">"セキュリティを強化するには PIN が必要です"</string>
-    <string name="kg_prompt_reason_timeout_password" msgid="6563904839641583441">"セキュリティを強化するにはパスワードが必要です"</string>
+    <string name="kg_prompt_reason_timeout_pattern" msgid="5304487696073914063">"追加の確認のためパターンが必要です"</string>
+    <string name="kg_prompt_reason_timeout_pin" msgid="8851462864335757813">"追加の確認のため PIN が必要です"</string>
+    <string name="kg_prompt_reason_timeout_password" msgid="6563904839641583441">"追加の確認のためパスワードが必要です"</string>
     <string name="kg_prompt_reason_switch_profiles_pattern" msgid="3398054847288438444">"プロファイルを切り替えるにはパターンが必要です"</string>
     <string name="kg_prompt_reason_switch_profiles_pin" msgid="7426368139226961699">"プロファイルを切り替えるには PIN が必要です"</string>
     <string name="kg_prompt_reason_switch_profiles_password" msgid="8383831046318421845">"プロファイルを切り替えるにはパスワードが必要です"</string>
diff --git a/packages/SystemUI/res-keyguard/values-pt-rPT/strings.xml b/packages/SystemUI/res-keyguard/values-pt-rPT/strings.xml
index f3fa491..a13b3dc 100644
--- a/packages/SystemUI/res-keyguard/values-pt-rPT/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-pt-rPT/strings.xml
@@ -93,12 +93,12 @@
     <string name="kg_failed_attempts_almost_at_login" product="default" msgid="8364140853305528449">"Desenhou a sequência de desbloqueio incorretamente <xliff:g id="NUMBER_0">%1$d</xliff:g> vezes. Após mais <xliff:g id="NUMBER_1">%2$d</xliff:g> tentativas sem êxito, ser-lhe-á pedido para desbloquear o telemóvel através de uma conta de email.\n\n Tente novamente dentro de <xliff:g id="NUMBER_2">%3$d</xliff:g> segundos."</string>
     <string name="kg_password_wrong_pin_code_pukked" msgid="3389829202093674267">"Código PIN do cartão SIM incorreto. Tem de contactar o seu operador para desbloquear o dispositivo."</string>
     <plurals name="kg_password_wrong_pin_code" formatted="false" msgid="4314341367727055967">
-      <item quantity="one">Incorrect SIM PIN code, you have <xliff:g id="NUMBER_1">%d</xliff:g> remaining attempts.</item>
+      <item quantity="one">Código PIN do cartão SIM incorreto. Tem mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas.</item>
       <item quantity="other">Código PIN do cartão SIM incorreto. Tem mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas.</item>
     </plurals>
     <string name="kg_password_wrong_puk_code_dead" msgid="3329017604125179374">"Cartão SIM inutilizável. Contacte o seu operador."</string>
     <plurals name="kg_password_wrong_puk_code" formatted="false" msgid="2287504898931957513">
-      <item quantity="one">Incorrect SIM PUK code, you have <xliff:g id="NUMBER_1">%d</xliff:g> remaining attempts before SIM becomes permanently unusable.</item>
+      <item quantity="one">Código PUK do cartão SIM incorreto. Tem mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas antes de o cartão SIM ficar permanentemente inutilizável.</item>
       <item quantity="other">Código PUK do cartão SIM incorreto. Tem mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas antes de o cartão SIM ficar permanentemente inutilizável.</item>
     </plurals>
     <string name="kg_password_pin_failed" msgid="8769990811451236223">"Falha ao introduzir o PIN do cartão SIM!"</string>
@@ -119,15 +119,15 @@
     <string name="kg_prompt_reason_device_admin" msgid="3452168247888906179">"Dispositivo bloqueado pelo administrador"</string>
     <string name="kg_prompt_reason_user_request" msgid="8236951765212462286">"O dispositivo foi bloqueado manualmente"</string>
     <plurals name="kg_prompt_reason_time_pattern" formatted="false" msgid="71299470072448533">
-      <item quantity="one">Device hasn\'t been unlocked for <xliff:g id="NUMBER_1">%d</xliff:g> hours. Confirm pattern.</item>
+      <item quantity="one">O dispositivo não é desbloqueado há <xliff:g id="NUMBER_1">%d</xliff:g> horas. Confirme o padrão.</item>
       <item quantity="other">O dispositivo não é desbloqueado há <xliff:g id="NUMBER_1">%d</xliff:g> horas. Confirme o padrão.</item>
     </plurals>
     <plurals name="kg_prompt_reason_time_pin" formatted="false" msgid="34586942088144385">
-      <item quantity="one">Device hasn\'t been unlocked for <xliff:g id="NUMBER_1">%d</xliff:g> hours. Confirm PIN.</item>
+      <item quantity="one">O dispositivo não é desbloqueado há <xliff:g id="NUMBER_1">%d</xliff:g> horas. Confirme o PIN.</item>
       <item quantity="other">O dispositivo não é desbloqueado há <xliff:g id="NUMBER_1">%d</xliff:g> horas. Confirme o PIN.</item>
     </plurals>
     <plurals name="kg_prompt_reason_time_password" formatted="false" msgid="257297696215346527">
-      <item quantity="one">Device hasn\'t been unlocked for <xliff:g id="NUMBER_1">%d</xliff:g> hours. Confirm password.</item>
+      <item quantity="one">O dispositivo não é desbloqueado há <xliff:g id="NUMBER_1">%d</xliff:g> horas. Confirme a palavra-passe.</item>
       <item quantity="other">O dispositivo não é desbloqueado há <xliff:g id="NUMBER_1">%d</xliff:g> horas. Confirme a palavra-passe.</item>
     </plurals>
     <string name="fingerprint_not_recognized" msgid="348813995267914625">"Não reconhecido"</string>
diff --git a/packages/SystemUI/res/layout/car_fullscreen_user_switcher.xml b/packages/SystemUI/res/layout/car_fullscreen_user_switcher.xml
index c82eddc..257e281 100644
--- a/packages/SystemUI/res/layout/car_fullscreen_user_switcher.xml
+++ b/packages/SystemUI/res/layout/car_fullscreen_user_switcher.xml
@@ -35,6 +35,10 @@
         android:layout_width="match_parent"
         android:layout_height="match_parent">
 
+        <include layout="@layout/car_status_bar_header"
+            android:theme="@android:style/Theme"
+            android:layout_alignParentTop="true"/>
+
         <!-- This progress bar is the countdown timer. -->
         <ProgressBar
             android:id="@+id/countdown_progress"
diff --git a/packages/SystemUI/res/layout/car_qs_footer.xml b/packages/SystemUI/res/layout/car_qs_footer.xml
index 2ef3b05..96f34fc 100644
--- a/packages/SystemUI/res/layout/car_qs_footer.xml
+++ b/packages/SystemUI/res/layout/car_qs_footer.xml
@@ -27,8 +27,7 @@
     android:paddingTop="16dp"
     android:paddingEnd="32dp"
     android:paddingStart="32dp"
-    android:gravity="center_vertical"
-    android:orientation="horizontal">
+    android:gravity="center_vertical">
 
     <com.android.systemui.statusbar.phone.MultiUserSwitch
         android:id="@+id/multi_user_switch"
diff --git a/packages/SystemUI/res/values-pt-rBR/strings.xml b/packages/SystemUI/res/values-pt-rBR/strings.xml
index d28d7d3..0b7e8b01 100644
--- a/packages/SystemUI/res/values-pt-rBR/strings.xml
+++ b/packages/SystemUI/res/values-pt-rBR/strings.xml
@@ -214,10 +214,10 @@
     <string name="accessibility_quick_settings_bluetooth_connected" msgid="4306637793614573659">"Bluetooth conectado."</string>
     <string name="accessibility_quick_settings_bluetooth_changed_off" msgid="2730003763480934529">"O Bluetooth foi desativado."</string>
     <string name="accessibility_quick_settings_bluetooth_changed_on" msgid="8722351798763206577">"O Bluetooth foi ativado."</string>
-    <string name="accessibility_quick_settings_location_off" msgid="5119080556976115520">"Relatório de Localização desativado."</string>
-    <string name="accessibility_quick_settings_location_on" msgid="5809937096590102036">"Relatório de Localização ativado."</string>
-    <string name="accessibility_quick_settings_location_changed_off" msgid="8526845571503387376">"O Relatório de Localização foi desativado."</string>
-    <string name="accessibility_quick_settings_location_changed_on" msgid="339403053079338468">"O Relatório de Localização foi ativado."</string>
+    <string name="accessibility_quick_settings_location_off" msgid="5119080556976115520">"Relatório de localização desativado."</string>
+    <string name="accessibility_quick_settings_location_on" msgid="5809937096590102036">"Relatório de localização ativado."</string>
+    <string name="accessibility_quick_settings_location_changed_off" msgid="8526845571503387376">"O Relatório de localização foi desativado."</string>
+    <string name="accessibility_quick_settings_location_changed_on" msgid="339403053079338468">"O Relatório de localização foi ativado."</string>
     <string name="accessibility_quick_settings_alarm" msgid="3959908972897295660">"Alarme definido para <xliff:g id="TIME">%s</xliff:g>."</string>
     <string name="accessibility_quick_settings_close" msgid="3115847794692516306">"Fechar painel."</string>
     <string name="accessibility_quick_settings_more_time" msgid="3659274935356197708">"Mais tempo."</string>
diff --git a/packages/SystemUI/res/values-pt-rPT/strings.xml b/packages/SystemUI/res/values-pt-rPT/strings.xml
index 27f859b..c846d25 100644
--- a/packages/SystemUI/res/values-pt-rPT/strings.xml
+++ b/packages/SystemUI/res/values-pt-rPT/strings.xml
@@ -26,7 +26,7 @@
     <string name="status_bar_no_recent_apps" msgid="7374907845131203189">"Os ecrãs recentes aparecem aqui"</string>
     <string name="status_bar_accessibility_dismiss_recents" msgid="4576076075226540105">"Ignorar aplicações recentes"</string>
     <plurals name="status_bar_accessibility_recent_apps" formatted="false" msgid="9138535907802238759">
-      <item quantity="one">%d screens in Overview</item>
+      <item quantity="one">%d ecrãs na Vista geral</item>
       <item quantity="other">%d ecrãs na Vista geral</item>
     </plurals>
     <string name="status_bar_no_notifications_title" msgid="4755261167193833213">"Sem notificações"</string>
@@ -252,7 +252,7 @@
     <string name="accessibility_clear_all" msgid="5235938559247164925">"Limpar todas as notificações."</string>
     <string name="notification_group_overflow_indicator" msgid="1863231301642314183">"+ <xliff:g id="NUMBER">%s</xliff:g>"</string>
     <plurals name="notification_group_overflow_description" formatted="false" msgid="4579313201268495404">
-      <item quantity="one"><xliff:g id="NUMBER_1">%s</xliff:g> more notifications inside.</item>
+      <item quantity="one">Mais <xliff:g id="NUMBER_1">%s</xliff:g> notificações no grupo.</item>
       <item quantity="other">Mais <xliff:g id="NUMBER_1">%s</xliff:g> notificações no grupo.</item>
     </plurals>
     <string name="status_bar_notification_inspect_item_title" msgid="5668348142410115323">"Definições de notificação"</string>
@@ -556,12 +556,12 @@
     <string name="notification_default_channel_desc" msgid="2506053815870808359">"Esta aplicação não tem categorias de notificação"</string>
     <string name="notification_unblockable_desc" msgid="3561016061737896906">"Não é possível desativar as notificações desta aplicação"</string>
     <plurals name="notification_num_channels_desc" formatted="false" msgid="5492793452274077663">
-      <item quantity="one">1 out of <xliff:g id="NUMBER_1">%d</xliff:g> notification categories from this app</item>
+      <item quantity="one">1 de <xliff:g id="NUMBER_1">%d</xliff:g> categorias de notificação desta aplicação</item>
       <item quantity="other">1 de <xliff:g id="NUMBER_1">%d</xliff:g> categorias de notificação desta aplicação</item>
     </plurals>
     <string name="notification_channels_list_desc_2" msgid="6214732715833946441">"<xliff:g id="CHANNEL_NAME_1">%1$s</xliff:g>, <xliff:g id="CHANNEL_NAME_2">%2$s</xliff:g>"</string>
     <plurals name="notification_channels_list_desc_2_and_others" formatted="false" msgid="2747813553355336157">
-      <item quantity="one"><xliff:g id="CHANNEL_NAME_1_3">%1$s</xliff:g>, <xliff:g id="CHANNEL_NAME_2_4">%2$s</xliff:g>, and <xliff:g id="NUMBER_5">%3$d</xliff:g> others</item>
+      <item quantity="one"><xliff:g id="CHANNEL_NAME_1_3">%1$s</xliff:g>, <xliff:g id="CHANNEL_NAME_2_4">%2$s</xliff:g> e mais <xliff:g id="NUMBER_5">%3$d</xliff:g></item>
       <item quantity="other"><xliff:g id="CHANNEL_NAME_1_3">%1$s</xliff:g>, <xliff:g id="CHANNEL_NAME_2_4">%2$s</xliff:g> e mais <xliff:g id="NUMBER_5">%3$d</xliff:g></item>
     </plurals>
     <string name="notification_channel_controls_opened_accessibility" msgid="6553950422055908113">"Controlos de notificações da aplicação <xliff:g id="APP_NAME">%1$s</xliff:g> abertos"</string>
diff --git a/packages/SystemUI/res/values-pt/strings.xml b/packages/SystemUI/res/values-pt/strings.xml
index d28d7d3..0b7e8b01 100644
--- a/packages/SystemUI/res/values-pt/strings.xml
+++ b/packages/SystemUI/res/values-pt/strings.xml
@@ -214,10 +214,10 @@
     <string name="accessibility_quick_settings_bluetooth_connected" msgid="4306637793614573659">"Bluetooth conectado."</string>
     <string name="accessibility_quick_settings_bluetooth_changed_off" msgid="2730003763480934529">"O Bluetooth foi desativado."</string>
     <string name="accessibility_quick_settings_bluetooth_changed_on" msgid="8722351798763206577">"O Bluetooth foi ativado."</string>
-    <string name="accessibility_quick_settings_location_off" msgid="5119080556976115520">"Relatório de Localização desativado."</string>
-    <string name="accessibility_quick_settings_location_on" msgid="5809937096590102036">"Relatório de Localização ativado."</string>
-    <string name="accessibility_quick_settings_location_changed_off" msgid="8526845571503387376">"O Relatório de Localização foi desativado."</string>
-    <string name="accessibility_quick_settings_location_changed_on" msgid="339403053079338468">"O Relatório de Localização foi ativado."</string>
+    <string name="accessibility_quick_settings_location_off" msgid="5119080556976115520">"Relatório de localização desativado."</string>
+    <string name="accessibility_quick_settings_location_on" msgid="5809937096590102036">"Relatório de localização ativado."</string>
+    <string name="accessibility_quick_settings_location_changed_off" msgid="8526845571503387376">"O Relatório de localização foi desativado."</string>
+    <string name="accessibility_quick_settings_location_changed_on" msgid="339403053079338468">"O Relatório de localização foi ativado."</string>
     <string name="accessibility_quick_settings_alarm" msgid="3959908972897295660">"Alarme definido para <xliff:g id="TIME">%s</xliff:g>."</string>
     <string name="accessibility_quick_settings_close" msgid="3115847794692516306">"Fechar painel."</string>
     <string name="accessibility_quick_settings_more_time" msgid="3659274935356197708">"Mais tempo."</string>
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
index 820a773..a9d583f 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
@@ -333,6 +333,10 @@
             }
             child.setAlpha(dark ? 0 : 1);
         }
+        if (mOwnerInfo != null) {
+            mOwnerInfo.setAlpha(dark ? 0 : 1);
+        }
+
         updateDozeVisibleViews();
         mBatteryDoze.setDark(dark);
         mClockView.setTextColor(ColorUtils.blendARGB(mTextColor, Color.WHITE, darkAmount));
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java
index 14d6b59..5a02178 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java
@@ -154,13 +154,19 @@
 
     /**
      * Called when the device has started waking up.
+     *
+     * @deprecated use {@link com.android.systemui.keyguard.WakefulnessLifecycle}.
      */
+    @Deprecated
     public void onStartedWakingUp() { }
 
     /**
      * Called when the device has started going to sleep.
      * @param why see {@link #onFinishedGoingToSleep(int)}
+     *
+     * @deprecated use {@link com.android.systemui.keyguard.WakefulnessLifecycle}.
      */
+    @Deprecated
     public void onStartedGoingToSleep(int why) { }
 
     /**
@@ -168,17 +174,26 @@
      * @param why either {@link WindowManagerPolicy#OFF_BECAUSE_OF_ADMIN},
      * {@link WindowManagerPolicy#OFF_BECAUSE_OF_USER}, or
      * {@link WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT}.
+     *
+     * @deprecated use {@link com.android.systemui.keyguard.WakefulnessLifecycle}.
      */
+    @Deprecated
     public void onFinishedGoingToSleep(int why) { }
 
     /**
      * Called when the screen has been turned on.
+     *
+     * @deprecated use {@link com.android.systemui.keyguard.ScreenLifecycle}.
      */
+    @Deprecated
     public void onScreenTurnedOn() { }
 
     /**
      * Called when the screen has been turned off.
+     *
+     * @deprecated use {@link com.android.systemui.keyguard.ScreenLifecycle}.
      */
+    @Deprecated
     public void onScreenTurnedOff() { }
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/Dependency.java b/packages/SystemUI/src/com/android/systemui/Dependency.java
index 776d076..e5c729f 100644
--- a/packages/SystemUI/src/com/android/systemui/Dependency.java
+++ b/packages/SystemUI/src/com/android/systemui/Dependency.java
@@ -30,6 +30,8 @@
 import com.android.systemui.assist.AssistManager;
 import com.android.systemui.colorextraction.SysuiColorExtractor;
 import com.android.systemui.fragments.FragmentService;
+import com.android.systemui.keyguard.ScreenLifecycle;
+import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.plugins.PluginActivityManager;
 import com.android.systemui.plugins.PluginDependencyProvider;
@@ -248,6 +250,12 @@
         mProviders.put(StatusBarIconController.class, () ->
                 new StatusBarIconControllerImpl(mContext));
 
+        mProviders.put(ScreenLifecycle.class, () ->
+                new ScreenLifecycle());
+
+        mProviders.put(WakefulnessLifecycle.class, () ->
+                new WakefulnessLifecycle());
+
         mProviders.put(FragmentService.class, () ->
                 new FragmentService(mContext));
 
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardLifecyclesDispatcher.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardLifecyclesDispatcher.java
new file mode 100644
index 0000000..4c98c08
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardLifecyclesDispatcher.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard;
+
+import android.os.Handler;
+import android.os.Message;
+
+import com.android.internal.policy.IKeyguardDrawnCallback;
+
+/**
+ * Dispatches the lifecycles keyguard gets from WindowManager on the main thread.
+ */
+public class KeyguardLifecyclesDispatcher {
+
+    static final int SCREEN_TURNING_ON = 0;
+    static final int SCREEN_TURNED_ON = 1;
+    static final int SCREEN_TURNING_OFF = 2;
+    static final int SCREEN_TURNED_OFF = 3;
+
+    static final int STARTED_WAKING_UP = 4;
+    static final int FINISHED_WAKING_UP = 5;
+    static final int STARTED_GOING_TO_SLEEP = 6;
+    static final int FINISHED_GOING_TO_SLEEP = 7;
+
+    private final ScreenLifecycle mScreenLifecycle;
+    private final WakefulnessLifecycle mWakefulnessLifecycle;
+
+    public KeyguardLifecyclesDispatcher(ScreenLifecycle screenLifecycle,
+            WakefulnessLifecycle wakefulnessLifecycle) {
+        mScreenLifecycle = screenLifecycle;
+        mWakefulnessLifecycle = wakefulnessLifecycle;
+    }
+
+    void dispatch(int what) {
+        mHandler.obtainMessage(what).sendToTarget();
+    }
+
+    private Handler mHandler = new Handler() {
+        @Override
+        public void handleMessage(Message msg) {
+            switch (msg.what) {
+                case SCREEN_TURNING_ON:
+                    mScreenLifecycle.dispatchScreenTurningOn();
+                    break;
+                case SCREEN_TURNED_ON:
+                    mScreenLifecycle.dispatchScreenTurnedOn();
+                    break;
+                case SCREEN_TURNING_OFF:
+                    mScreenLifecycle.dispatchScreenTurningOff();
+                    break;
+                case SCREEN_TURNED_OFF:
+                    mScreenLifecycle.dispatchScreenTurnedOff();
+                    break;
+                case STARTED_WAKING_UP:
+                    mWakefulnessLifecycle.dispatchStartedWakingUp();
+                    break;
+                case FINISHED_WAKING_UP:
+                    mWakefulnessLifecycle.dispatchFinishedWakingUp();
+                    break;
+                case STARTED_GOING_TO_SLEEP:
+                    mWakefulnessLifecycle.dispatchStartedGoingToSleep();
+                    break;
+                case FINISHED_GOING_TO_SLEEP:
+                    mWakefulnessLifecycle.dispatchFinishedGoingToSleep();
+                    break;
+                default:
+                    throw new IllegalArgumentException("Unknown message: " + msg);
+            }
+        }
+    };
+
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java
index 2d5d198..2a5ae0d 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java
@@ -31,6 +31,7 @@
 import com.android.internal.policy.IKeyguardExitCallback;
 import com.android.internal.policy.IKeyguardService;
 import com.android.internal.policy.IKeyguardStateCallback;
+import com.android.systemui.Dependency;
 import com.android.systemui.SystemUIApplication;
 
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
@@ -40,12 +41,17 @@
     static final String PERMISSION = android.Manifest.permission.CONTROL_KEYGUARD;
 
     private KeyguardViewMediator mKeyguardViewMediator;
+    private KeyguardLifecyclesDispatcher mKeyguardLifecyclesDispatcher;
 
     @Override
     public void onCreate() {
         ((SystemUIApplication) getApplication()).startServicesIfNeeded();
         mKeyguardViewMediator =
                 ((SystemUIApplication) getApplication()).getComponent(KeyguardViewMediator.class);
+        mKeyguardLifecyclesDispatcher = new KeyguardLifecyclesDispatcher(
+                Dependency.get(ScreenLifecycle.class),
+                Dependency.get(WakefulnessLifecycle.class));
+
     }
 
     @Override
@@ -111,12 +117,16 @@
         public void onStartedGoingToSleep(int reason) {
             checkPermission();
             mKeyguardViewMediator.onStartedGoingToSleep(reason);
+            mKeyguardLifecyclesDispatcher.dispatch(
+                    KeyguardLifecyclesDispatcher.STARTED_GOING_TO_SLEEP);
         }
 
         @Override // Binder interface
         public void onFinishedGoingToSleep(int reason, boolean cameraGestureTriggered) {
             checkPermission();
             mKeyguardViewMediator.onFinishedGoingToSleep(reason, cameraGestureTriggered);
+            mKeyguardLifecyclesDispatcher.dispatch(
+                    KeyguardLifecyclesDispatcher.FINISHED_GOING_TO_SLEEP);
         }
 
         @Override // Binder interface
@@ -124,6 +134,15 @@
             Trace.beginSection("KeyguardService.mBinder#onStartedWakingUp");
             checkPermission();
             mKeyguardViewMediator.onStartedWakingUp();
+            mKeyguardLifecyclesDispatcher.dispatch(KeyguardLifecyclesDispatcher.STARTED_WAKING_UP);
+            Trace.endSection();
+        }
+
+        @Override // Binder interface
+        public void onFinishedWakingUp() {
+            Trace.beginSection("KeyguardService.mBinder#onFinishedWakingUp");
+            checkPermission();
+            mKeyguardLifecyclesDispatcher.dispatch(KeyguardLifecyclesDispatcher.FINISHED_WAKING_UP);
             Trace.endSection();
         }
 
@@ -132,6 +151,7 @@
             Trace.beginSection("KeyguardService.mBinder#onScreenTurningOn");
             checkPermission();
             mKeyguardViewMediator.onScreenTurningOn(callback);
+            mKeyguardLifecyclesDispatcher.dispatch(KeyguardLifecyclesDispatcher.SCREEN_TURNING_ON);
             Trace.endSection();
         }
 
@@ -140,13 +160,21 @@
             Trace.beginSection("KeyguardService.mBinder#onScreenTurnedOn");
             checkPermission();
             mKeyguardViewMediator.onScreenTurnedOn();
+            mKeyguardLifecyclesDispatcher.dispatch(KeyguardLifecyclesDispatcher.SCREEN_TURNED_ON);
             Trace.endSection();
         }
 
         @Override // Binder interface
+        public void onScreenTurningOff() {
+            checkPermission();
+            mKeyguardLifecyclesDispatcher.dispatch(KeyguardLifecyclesDispatcher.SCREEN_TURNING_OFF);
+        }
+
+        @Override // Binder interface
         public void onScreenTurnedOff() {
             checkPermission();
             mKeyguardViewMediator.onScreenTurnedOff();
+            mKeyguardLifecyclesDispatcher.dispatch(KeyguardLifecyclesDispatcher.SCREEN_TURNED_OFF);
         }
 
         @Override // Binder interface
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/Lifecycle.java b/packages/SystemUI/src/com/android/systemui/keyguard/Lifecycle.java
new file mode 100644
index 0000000..1b20cfb
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/Lifecycle.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard;
+
+import java.util.ArrayList;
+import java.util.function.Consumer;
+
+/**
+ * Base class for lifecycles with observers.
+ */
+public class Lifecycle<T> {
+
+    private ArrayList<T> mObservers = new ArrayList<>();
+
+    public void addObserver(T observer) {
+        mObservers.add(observer);
+    }
+
+    public void removeObserver(T observer) {
+        mObservers.remove(observer);
+    }
+
+    public void dispatch(Consumer<T> consumer) {
+        for (int i = 0; i < mObservers.size(); i++) {
+            consumer.accept(mObservers.get(i));
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ScreenLifecycle.java b/packages/SystemUI/src/com/android/systemui/keyguard/ScreenLifecycle.java
new file mode 100644
index 0000000..3f39dfe
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ScreenLifecycle.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard;
+
+import com.android.systemui.Dumpable;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+
+/**
+ * Tracks the screen lifecycle.
+ */
+public class ScreenLifecycle extends Lifecycle<ScreenLifecycle.Observer> implements Dumpable {
+
+    public static final int SCREEN_OFF = 0;
+    public static final int SCREEN_TURNING_ON = 1;
+    public static final int SCREEN_ON = 2;
+    public static final int SCREEN_TURNING_OFF = 3;
+
+    private int mScreenState = SCREEN_OFF;
+
+    public int getScreenState() {
+        return mScreenState;
+    }
+
+    public void dispatchScreenTurningOn() {
+        mScreenState = SCREEN_TURNING_ON;
+        dispatch(Observer::onScreenTurningOn);
+    }
+
+    public void dispatchScreenTurnedOn() {
+        mScreenState = SCREEN_ON;
+        dispatch(Observer::onScreenTurnedOn);
+    }
+
+    public void dispatchScreenTurningOff() {
+        mScreenState = SCREEN_TURNING_OFF;
+        dispatch(Observer::onScreenTurningOff);
+    }
+
+    public void dispatchScreenTurnedOff() {
+        mScreenState = SCREEN_OFF;
+        dispatch(Observer::onScreenTurnedOff);
+    }
+
+    @Override
+    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        pw.println("ScreenLifecycle:");
+        pw.println("  mScreenState=" + mScreenState);
+    }
+
+    public interface Observer {
+        default void onScreenTurningOn() {}
+        default void onScreenTurnedOn() {}
+        default void onScreenTurningOff() {}
+        default void onScreenTurnedOff() {}
+    }
+
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/WakefulnessLifecycle.java b/packages/SystemUI/src/com/android/systemui/keyguard/WakefulnessLifecycle.java
new file mode 100644
index 0000000..578e6fb
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/WakefulnessLifecycle.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard;
+
+import com.android.systemui.Dumpable;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+
+/**
+ * Tracks the wakefulness lifecycle.
+ */
+public class WakefulnessLifecycle extends Lifecycle<WakefulnessLifecycle.Observer> implements
+        Dumpable {
+
+    public static final int WAKEFULNESS_ASLEEP = 0;
+    public static final int WAKEFULNESS_WAKING = 1;
+    public static final int WAKEFULNESS_AWAKE = 2;
+    public static final int WAKEFULNESS_GOING_TO_SLEEP = 3;
+
+    private int mWakefulness = WAKEFULNESS_ASLEEP;
+
+    public int getWakefulness() {
+        return mWakefulness;
+    }
+
+    public void dispatchStartedWakingUp() {
+        mWakefulness = WAKEFULNESS_WAKING;
+        dispatch(Observer::onStartedWakingUp);
+    }
+
+    public void dispatchFinishedWakingUp() {
+        mWakefulness = WAKEFULNESS_AWAKE;
+        dispatch(Observer::onFinishedWakingUp);
+    }
+
+    public void dispatchStartedGoingToSleep() {
+        mWakefulness = WAKEFULNESS_GOING_TO_SLEEP;
+        dispatch(Observer::onStartedGoingToSleep);
+    }
+
+    public void dispatchFinishedGoingToSleep() {
+        mWakefulness = WAKEFULNESS_ASLEEP;
+        dispatch(Observer::onFinishedGoingToSleep);
+    }
+
+    @Override
+    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        pw.println("WakefulnessLifecycle:");
+        pw.println("  mWakefulness=" + mWakefulness);
+    }
+
+    public interface Observer {
+        default void onStartedWakingUp() {}
+        default void onFinishedWakingUp() {}
+        default void onStartedGoingToSleep() {}
+        default void onFinishedGoingToSleep() {}
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java b/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
index 0009fb9..2e10831 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
@@ -77,7 +77,7 @@
     private static final int MSG_TOGGLE_APP_SPLIT_SCREEN       = 30 << MSG_SHIFT;
     private static final int MSG_APP_TRANSITION_FINISHED       = 31 << MSG_SHIFT;
     private static final int MSG_DISMISS_KEYBOARD_SHORTCUTS    = 32 << MSG_SHIFT;
-    private static final int MSG_HANDLE_SYSNAV_KEY             = 33 << MSG_SHIFT;
+    private static final int MSG_HANDLE_SYSTEM_KEY             = 33 << MSG_SHIFT;
     private static final int MSG_SHOW_GLOBAL_ACTIONS           = 34 << MSG_SHIFT;
     private static final int MSG_TOGGLE_PANEL                  = 35 << MSG_SHIFT;
 
@@ -136,7 +136,7 @@
         default void remQsTile(ComponentName tile) { }
         default void clickTile(ComponentName tile) { }
 
-        default void handleSystemNavigationKey(int arg1) { }
+        default void handleSystemKey(int arg1) { }
         default void handleShowGlobalActionsMenu() { }
     }
 
@@ -424,9 +424,9 @@
     }
 
     @Override
-    public void handleSystemNavigationKey(int key) {
+    public void handleSystemKey(int key) {
         synchronized (mLock) {
-            mHandler.obtainMessage(MSG_HANDLE_SYSNAV_KEY, key, 0).sendToTarget();
+            mHandler.obtainMessage(MSG_HANDLE_SYSTEM_KEY, key, 0).sendToTarget();
         }
     }
 
@@ -614,9 +614,9 @@
                         mCallbacks.get(i).toggleSplitScreen();
                     }
                     break;
-                case MSG_HANDLE_SYSNAV_KEY:
+                case MSG_HANDLE_SYSTEM_KEY:
                     for (int i = 0; i < mCallbacks.size(); i++) {
-                        mCallbacks.get(i).handleSystemNavigationKey(msg.arg1);
+                        mCallbacks.get(i).handleSystemKey(msg.arg1);
                     }
                     break;
                 case MSG_SHOW_GLOBAL_ACTIONS:
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationGuts.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationGuts.java
index 23a67e2..54d622b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationGuts.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationGuts.java
@@ -329,4 +329,8 @@
     public boolean isExposed() {
         return mExposed;
     }
+
+    public boolean isLeavebehind() {
+        return mGutsContent != null && mGutsContent.isLeavebehind();
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/car/PageIndicator.java b/packages/SystemUI/src/com/android/systemui/statusbar/car/PageIndicator.java
index f7d0906..c830ff8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/car/PageIndicator.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/car/PageIndicator.java
@@ -98,6 +98,11 @@
     protected void onDraw(Canvas canvas) {
         super.onDraw(canvas);
 
+        // Don't draw anything unless there's multiple pages to scroll through.  No need to clear
+        // any previous dots, since onDraw provides a canvas that's already cleared.
+        if (mPageCount <= 1)
+            return;
+
         int x = canvas.getWidth() / 2 - (mPageCount / 2) * mStep;
         int y = canvas.getHeight() / 2;
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LightBarTransitionsController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LightBarTransitionsController.java
index 417bef8..b0ac6ec 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LightBarTransitionsController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LightBarTransitionsController.java
@@ -167,7 +167,7 @@
                 animation -> setIconTintInternal((Float) animation.getAnimatedValue()));
         mTintAnimator.setDuration(duration);
         mTintAnimator.setStartDelay(delay);
-        mTintAnimator.setInterpolator(Interpolators.FAST_OUT_SLOW_IN);
+        mTintAnimator.setInterpolator(Interpolators.LINEAR_OUT_SLOW_IN);
         mTintAnimator.start();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
index baa1444..4518ee9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
@@ -175,6 +175,8 @@
 import com.android.systemui.fragments.ExtensionFragmentListener;
 import com.android.systemui.fragments.FragmentHostManager;
 import com.android.systemui.keyguard.KeyguardViewMediator;
+import com.android.systemui.keyguard.ScreenLifecycle;
+import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.plugins.qs.QS;
 import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin.MenuItem;
@@ -423,8 +425,6 @@
     private DozeServiceHost mDozeServiceHost;
     private boolean mWakeUpComingFromTouch;
     private PointF mWakeUpTouchLocation;
-    private boolean mScreenTurningOn;
-    private boolean mScreenFullyOff;
 
     int mPixelFormat;
     Object mQueueLock = new Object();
@@ -635,11 +635,6 @@
     // Fingerprint (as computed by getLoggingFingerprint() of the last logged state.
     private int mLastLoggedStateFingerprint;
 
-    /**
-     * If set, the device has started going to sleep but isn't fully non-interactive yet.
-     */
-    protected boolean mStartedGoingToSleep;
-
     private final OnChildLocationsChangedListener mNotificationLocationsChangedListener =
             new OnChildLocationsChangedListener() {
                 @Override
@@ -738,6 +733,8 @@
     private String mKeyToRemoveOnGutsClosed;
     private SysuiColorExtractor mColorExtractor;
     private ForegroundServiceController mForegroundServiceController;
+    private ScreenLifecycle mScreenLifecycle;
+    private WakefulnessLifecycle mWakefulnessLifecycle;
 
     private void recycleAllVisibilityObjects(ArraySet<NotificationVisibility> array) {
         final int N = array.size();
@@ -776,6 +773,10 @@
         mNetworkController = Dependency.get(NetworkController.class);
         mUserSwitcherController = Dependency.get(UserSwitcherController.class);
         mKeyguardMonitor = (KeyguardMonitorImpl) Dependency.get(KeyguardMonitor.class);
+        mScreenLifecycle = Dependency.get(ScreenLifecycle.class);
+        mScreenLifecycle.addObserver(mScreenObserver);
+        mWakefulnessLifecycle = Dependency.get(WakefulnessLifecycle.class);
+        mWakefulnessLifecycle.addObserver(mWakefulnessObserver);
         mBatteryController = Dependency.get(BatteryController.class);
         mAssistManager = Dependency.get(AssistManager.class);
         mDeviceProvisionedController = Dependency.get(DeviceProvisionedController.class);
@@ -1792,7 +1793,8 @@
             return;
         }
         if (entry != null && mNotificationGutsExposed != null
-                && mNotificationGutsExposed == entry.row.getGuts()) {
+                && mNotificationGutsExposed == entry.row.getGuts() && entry.row.getGuts() != null
+                && !entry.row.getGuts().isLeavebehind()) {
             Log.w(TAG, "Keeping notification because it's showing guts. " + key);
             mLatestRankingMap = ranking;
             mKeyToRemoveOnGutsClosed = key;
@@ -2831,12 +2833,6 @@
         mRemoteInputEntriesToRemoveOnCollapse.clear();
     }
 
-    public void onScreenTurnedOff() {
-        mScreenFullyOff = true;
-        mFalsingManager.onScreenOff();
-        updateIsKeyguard();
-    }
-
     public NotificationStackScrollLayout getNotificationScrollLayout() {
         return mStackScroller;
     }
@@ -2946,8 +2942,8 @@
      * settings. Down action closes the entire panel.
      */
     @Override
-    public void handleSystemNavigationKey(int key) {
-        if (SPEW) Log.d(TAG, "handleSystemNavigationKey: " + key);
+    public void handleSystemKey(int key) {
+        if (SPEW) Log.d(TAG, "handleNavigationKey: " + key);
         if (!panelsEnabled() || !mKeyguardMonitor.isDeviceInteractive()
                 || mKeyguardMonitor.isShowing() && !mKeyguardMonitor.isOccluded()) {
             return;
@@ -4214,10 +4210,7 @@
 
     public void showKeyguard() {
         mKeyguardRequested = true;
-        // Unconditionally show keyguard again. There's some logic that relies on this
-        // being called even when the keyguard is already showing, e.g. for updating
-        // sensitiveness of notifications and making sure the panels are expanded.
-        showKeyguardImpl();
+        updateIsKeyguard();
     }
 
     public boolean hideKeyguard() {
@@ -4231,13 +4224,18 @@
         // late in the transition, so we also allow the device to start dozing once the screen has
         // turned off fully.
         boolean keyguardForDozing = mDozingRequested &&
-                (!mDeviceInteractive || mStartedGoingToSleep && (mScreenFullyOff || mIsKeyguard));
+                (!mDeviceInteractive || isGoingToSleep() && (isScreenFullyOff() || mIsKeyguard));
         boolean shouldBeKeyguard = mKeyguardRequested || keyguardForDozing;
         if (keyguardForDozing) {
             updatePanelExpansionForKeyguard();
         }
         if (shouldBeKeyguard) {
-            showKeyguardImpl();
+            if (isGoingToSleep()
+                    && mScreenLifecycle.getScreenState() == ScreenLifecycle.SCREEN_TURNING_OFF) {
+                // Delay showing the keyguard until screen turned off.
+            } else {
+                showKeyguardImpl();
+            }
         } else {
             return hideKeyguardImpl();
         }
@@ -5120,78 +5118,84 @@
         recomputeDisableFlags(true /* animate */);
     }
 
-    public void onStartedGoingToSleep() {
-        mStartedGoingToSleep = true;
-    }
-
-    public void onFinishedGoingToSleep() {
-        mNotificationPanel.onAffordanceLaunchEnded();
-        releaseGestureWakeLock();
-        mLaunchCameraOnScreenTurningOn = false;
-        mStartedGoingToSleep = false;
-        mDeviceInteractive = false;
-        mWakeUpComingFromTouch = false;
-        mWakeUpTouchLocation = null;
-        mStackScroller.setAnimationsEnabled(false);
-        mVisualStabilityManager.setScreenOn(false);
-        updateVisibleToUser();
-
-        // We need to disable touch events because these might
-        // collapse the panel after we expanded it, and thus we would end up with a blank
-        // Keyguard.
-        mNotificationPanel.setTouchDisabled(true);
-        mStatusBarWindow.cancelCurrentTouch();
-        if (mLaunchCameraOnFinishedGoingToSleep) {
-            mLaunchCameraOnFinishedGoingToSleep = false;
-
-            // This gets executed before we will show Keyguard, so post it in order that the state
-            // is correct.
-            mHandler.post(new Runnable() {
-                @Override
-                public void run() {
-                    onCameraLaunchGestureDetected(mLastCameraLaunchSource);
-                }
-            });
-        }
-        updateIsKeyguard();
-    }
-
-    public void onStartedWakingUp() {
-        mDeviceInteractive = true;
-        mStackScroller.setAnimationsEnabled(true);
-        mVisualStabilityManager.setScreenOn(true);
-        mNotificationPanel.setTouchDisabled(false);
-        updateVisibleToUser();
-        updateIsKeyguard();
-    }
-
-    public void onScreenTurningOn() {
-        mScreenFullyOff = false;
-        mScreenTurningOn = true;
-        mFalsingManager.onScreenTurningOn();
-        mNotificationPanel.onScreenTurningOn();
-        if (mLaunchCameraOnScreenTurningOn) {
-            mNotificationPanel.launchCamera(false, mLastCameraLaunchSource);
+    WakefulnessLifecycle.Observer mWakefulnessObserver = new WakefulnessLifecycle.Observer() {
+        @Override
+        public void onFinishedGoingToSleep() {
+            mNotificationPanel.onAffordanceLaunchEnded();
+            releaseGestureWakeLock();
             mLaunchCameraOnScreenTurningOn = false;
+            mDeviceInteractive = false;
+            mWakeUpComingFromTouch = false;
+            mWakeUpTouchLocation = null;
+            mStackScroller.setAnimationsEnabled(false);
+            mVisualStabilityManager.setScreenOn(false);
+            updateVisibleToUser();
+
+            // We need to disable touch events because these might
+            // collapse the panel after we expanded it, and thus we would end up with a blank
+            // Keyguard.
+            mNotificationPanel.setTouchDisabled(true);
+            mStatusBarWindow.cancelCurrentTouch();
+            if (mLaunchCameraOnFinishedGoingToSleep) {
+                mLaunchCameraOnFinishedGoingToSleep = false;
+
+                // This gets executed before we will show Keyguard, so post it in order that the state
+                // is correct.
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        onCameraLaunchGestureDetected(mLastCameraLaunchSource);
+                    }
+                });
+            }
+            updateIsKeyguard();
         }
-    }
+
+        @Override
+        public void onStartedWakingUp() {
+            mDeviceInteractive = true;
+            mStackScroller.setAnimationsEnabled(true);
+            mVisualStabilityManager.setScreenOn(true);
+            mNotificationPanel.setTouchDisabled(false);
+            updateVisibleToUser();
+            updateIsKeyguard();
+        }
+    };
+
+    ScreenLifecycle.Observer mScreenObserver = new ScreenLifecycle.Observer() {
+        @Override
+        public void onScreenTurningOn() {
+            mFalsingManager.onScreenTurningOn();
+            mNotificationPanel.onScreenTurningOn();
+            if (mLaunchCameraOnScreenTurningOn) {
+                mNotificationPanel.launchCamera(false, mLastCameraLaunchSource);
+                mLaunchCameraOnScreenTurningOn = false;
+            }
+        }
+
+        @Override
+        public void onScreenTurnedOn() {
+            mDozeScrimController.onScreenTurnedOn();
+        }
+
+        @Override
+        public void onScreenTurnedOff() {
+            mFalsingManager.onScreenOff();
+            updateIsKeyguard();
+        }
+    };
 
     private void vibrateForCameraGesture() {
         // Make sure to pass -1 for repeat so VibratorService doesn't stop us when going to sleep.
         mVibrator.vibrate(mCameraLaunchGestureVibePattern, -1 /* repeat */);
     }
 
-    public void onScreenTurnedOn() {
-        mScreenTurningOn = false;
-        mDozeScrimController.onScreenTurnedOn();
-    }
-
     /**
      * @return true if the screen is currently fully off, i.e. has finished turning off and has
      *         since not started turning on.
      */
     public boolean isScreenFullyOff() {
-        return mScreenFullyOff;
+        return mScreenLifecycle.getScreenState() == ScreenLifecycle.SCREEN_OFF;
     }
 
     @Override
@@ -5238,7 +5242,7 @@
     @Override
     public void onCameraLaunchGestureDetected(int source) {
         mLastCameraLaunchSource = source;
-        if (mStartedGoingToSleep) {
+        if (isGoingToSleep()) {
             if (DEBUG_CAMERA_LIFT) Slog.d(TAG, "Finish going to sleep before launching camera");
             mLaunchCameraOnFinishedGoingToSleep = true;
             return;
@@ -5265,7 +5269,7 @@
                 mScrimController.dontAnimateBouncerChangesUntilNextFrame();
                 mGestureWakeLock.acquire(LAUNCH_TRANSITION_TIMEOUT_MS + 1000L);
             }
-            if (mScreenTurningOn || mStatusBarKeyguardViewManager.isScreenTurnedOn()) {
+            if (isScreenTurningOnOrOn()) {
                 if (DEBUG_CAMERA_LIFT) Slog.d(TAG, "Launching camera");
                 mNotificationPanel.launchCamera(mDeviceInteractive /* animate */, source);
             } else {
@@ -5291,6 +5295,16 @@
         return true;
     }
 
+    private boolean isGoingToSleep() {
+        return mWakefulnessLifecycle.getWakefulness()
+                == WakefulnessLifecycle.WAKEFULNESS_GOING_TO_SLEEP;
+    }
+
+    private boolean isScreenTurningOnOrOn() {
+        return mScreenLifecycle.getScreenState() == ScreenLifecycle.SCREEN_TURNING_ON
+                || mScreenLifecycle.getScreenState() == ScreenLifecycle.SCREEN_ON;
+    }
+
     public void notifyFpAuthModeChanged() {
         updateDozing();
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
index 191b7a2..252df17 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
@@ -80,7 +80,6 @@
 
     private ViewGroup mContainer;
 
-    private boolean mDeviceInteractive = false;
     private boolean mScreenTurnedOn;
     protected KeyguardBouncer mBouncer;
     protected boolean mShowing;
@@ -100,7 +99,6 @@
 
     private OnDismissAction mAfterKeyguardGoneAction;
     private final ArrayList<Runnable> mAfterKeyguardGoneRunnables = new ArrayList<>();
-    private boolean mDeviceWillWakeUp;
     private boolean mDeferScrimFadeOut;
 
     private final KeyguardUpdateMonitorCallback mUpdateMonitorCallback =
@@ -213,31 +211,19 @@
     }
 
     public void onStartedGoingToSleep() {
-        mStatusBar.onStartedGoingToSleep();
+        // TODO: remove
     }
 
     public void onFinishedGoingToSleep() {
-        mDeviceInteractive = false;
-        mStatusBar.onFinishedGoingToSleep();
         mBouncer.onScreenTurnedOff();
     }
 
     public void onStartedWakingUp() {
-        Trace.beginSection("StatusBarKeyguardViewManager#onStartedWakingUp");
-        mDeviceInteractive = true;
-        mDeviceWillWakeUp = false;
-        mStatusBar.onStartedWakingUp();
-        Trace.endSection();
+        // TODO: remove
     }
 
     public void onScreenTurningOn() {
-        Trace.beginSection("StatusBarKeyguardViewManager#onScreenTurningOn");
-        mStatusBar.onScreenTurningOn();
-        Trace.endSection();
-    }
-
-    public boolean isScreenTurnedOn() {
-        return mScreenTurnedOn;
+        // TODO: remove
     }
 
     public void onScreenTurnedOn() {
@@ -249,7 +235,6 @@
                     true /* skipFirstFrame */);
             updateStates();
         }
-        mStatusBar.onScreenTurnedOn();
         Trace.endSection();
     }
 
@@ -269,11 +254,10 @@
 
     public void onScreenTurnedOff() {
         mScreenTurnedOn = false;
-        mStatusBar.onScreenTurnedOff();
     }
 
     public void notifyDeviceWakeUpRequested() {
-        mDeviceWillWakeUp = !mDeviceInteractive;
+        // TODO: remove
     }
 
     public void setNeedsInput(boolean needsInput) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/CastControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/CastControllerImpl.java
index b89a77b..2bf62bb 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/CastControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/CastControllerImpl.java
@@ -182,7 +182,7 @@
                 Log.w(TAG, "Projection is no longer active: " + projection);
             }
         } else {
-            mMediaRouter.getDefaultRoute().select();
+            mMediaRouter.getFallbackRoute().select();
         }
     }
 
diff --git a/packages/SystemUI/tests/src/com/android/AAAPlusPlusVerifySysuiRequiredTestPropertiesTest.java b/packages/SystemUI/tests/src/com/android/AAAPlusPlusVerifySysuiRequiredTestPropertiesTest.java
index b597868..fe23541 100644
--- a/packages/SystemUI/tests/src/com/android/AAAPlusPlusVerifySysuiRequiredTestPropertiesTest.java
+++ b/packages/SystemUI/tests/src/com/android/AAAPlusPlusVerifySysuiRequiredTestPropertiesTest.java
@@ -22,7 +22,6 @@
 import android.support.test.internal.runner.ClassPathScanner;
 import android.support.test.internal.runner.ClassPathScanner.ChainedClassNameFilter;
 import android.support.test.internal.runner.ClassPathScanner.ExternalClassNameFilter;
-import android.support.test.internal.runner.TestLoader;
 import android.testing.AndroidTestingRunner;
 import android.text.TextUtils;
 import android.util.Log;
@@ -32,8 +31,11 @@
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.internal.builders.AllDefaultPossibilitiesBuilder;
 
 import java.io.IOException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
@@ -69,12 +71,11 @@
     };
 
     @Test
-    public void testAllClassInheritance() {
+    public void testAllClassInheritance() throws Throwable {
         boolean anyClassWrong = false;
-        TestLoader loader = new TestLoader();
         for (String className : getClassNamesFromClassPath()) {
-            Class<?> cls = loader.loadIfTest(className);
-            if (cls == null) continue;
+            Class<?> cls = Class.forName(className, false, this.getClass().getClassLoader());		
+            if (!isTestClass(cls)) continue;
 
             boolean hasParent = false;
             for (Class<?> parent : BASE_CLS_WHITELIST) {
@@ -125,4 +126,85 @@
         return TextUtils.join(",", Arrays.asList(BASE_CLS_WHITELIST)
                 .stream().map(cls -> cls.getSimpleName()).toArray());
     }
+
+    /**
+     * Determines if given class is a valid test class.
+     *
+     * @param loadedClass
+     * @return <code>true</code> if loadedClass is a test
+     */
+    private boolean isTestClass(Class<?> loadedClass) {
+        try {
+            if (Modifier.isAbstract(loadedClass.getModifiers())) {
+                logDebug(String.format("Skipping abstract class %s: not a test",
+                        loadedClass.getName()));
+                return false;
+            }
+            // TODO: try to find upstream junit calls to replace these checks
+            if (junit.framework.Test.class.isAssignableFrom(loadedClass)) {
+                // ensure that if a TestCase, it has at least one test method otherwise
+                // TestSuite will throw error
+                if (junit.framework.TestCase.class.isAssignableFrom(loadedClass)) {
+                    return hasJUnit3TestMethod(loadedClass);
+                }
+                return true;
+            }
+            // TODO: look for a 'suite' method?
+            if (loadedClass.isAnnotationPresent(org.junit.runner.RunWith.class)) {
+                return true;
+            }
+            for (Method testMethod : loadedClass.getMethods()) {
+                if (testMethod.isAnnotationPresent(org.junit.Test.class)) {
+                    return true;
+                }
+            }
+            logDebug(String.format("Skipping class %s: not a test", loadedClass.getName()));
+            return false;
+        } catch (Exception e) {
+            // Defensively catch exceptions - Will throw runtime exception if it cannot load methods.
+            // For earlier versions of Android (Pre-ICS), Dalvik might try to initialize a class
+            // during getMethods(), fail to do so, hide the error and throw a NoSuchMethodException.
+            // Since the java.lang.Class.getMethods does not declare such an exception, resort to a
+            // generic catch all.
+            // For ICS+, Dalvik will throw a NoClassDefFoundException.
+            Log.w(TAG, String.format("%s in isTestClass for %s", e.toString(),
+                    loadedClass.getName()));
+            return false;
+        } catch (Error e) {
+            // defensively catch Errors too
+            Log.w(TAG, String.format("%s in isTestClass for %s", e.toString(),
+                    loadedClass.getName()));
+            return false;
+        }
+    }
+
+    private boolean hasJUnit3TestMethod(Class<?> loadedClass) {
+        for (Method testMethod : loadedClass.getMethods()) {
+            if (isPublicTestMethod(testMethod)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    // copied from junit.framework.TestSuite
+    private boolean isPublicTestMethod(Method m) {
+        return isTestMethod(m) && Modifier.isPublic(m.getModifiers());
+    }
+
+    // copied from junit.framework.TestSuite
+    private boolean isTestMethod(Method m) {
+        return m.getParameterTypes().length == 0 && m.getName().startsWith("test")
+                && m.getReturnType().equals(Void.TYPE);
+    }
+
+    /**
+     * Utility method for logging debug messages. Only actually logs a message if TAG is marked
+     * as loggable to limit log spam during normal use.
+     */
+    private void logDebug(String msg) {
+        if (Log.isLoggable(TAG, Log.DEBUG)) {
+            Log.d(TAG, msg);
+        }
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/LifecycleTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/LifecycleTest.java
new file mode 100644
index 0000000..e0807d6
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/LifecycleTest.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.support.test.filters.SmallTest;
+import android.testing.AndroidTestingRunner;
+
+import com.android.systemui.SysuiTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+
+@RunWith(AndroidTestingRunner.class)
+@SmallTest
+public class LifecycleTest extends SysuiTestCase {
+
+    private final Object mObj1 = new Object();
+    private final Object mObj2 = new Object();
+
+    private Lifecycle<Object> mLifecycle;
+    private ArrayList<Object> mDispatchedObjects;
+
+    @Before
+    public void setUp() throws Exception {
+        mLifecycle = new Lifecycle<>();
+        mDispatchedObjects = new ArrayList<>();
+    }
+
+    @Test
+    public void addObserver_addsObserver() throws Exception {
+        mLifecycle.addObserver(mObj1);
+
+        mLifecycle.dispatch(mDispatchedObjects::add);
+
+        assertTrue(mDispatchedObjects.contains(mObj1));
+    }
+
+    @Test
+    public void removeObserver() throws Exception {
+        mLifecycle.addObserver(mObj1);
+        mLifecycle.removeObserver(mObj1);
+
+        mLifecycle.dispatch(mDispatchedObjects::add);
+
+        assertFalse(mDispatchedObjects.contains(mObj1));
+    }
+
+    @Test
+    public void dispatch() throws Exception {
+        mLifecycle.addObserver(mObj1);
+        mLifecycle.addObserver(mObj2);
+
+        mLifecycle.dispatch(mDispatchedObjects::add);
+
+        assertTrue(mDispatchedObjects.contains(mObj1));
+        assertTrue(mDispatchedObjects.contains(mObj2));
+    }
+
+}
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ScreenLifecycleTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ScreenLifecycleTest.java
new file mode 100644
index 0000000..8c918f6
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ScreenLifecycleTest.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+
+import android.support.test.filters.SmallTest;
+import android.testing.AndroidTestingRunner;
+
+import com.android.systemui.SysuiTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+
+@RunWith(AndroidTestingRunner.class)
+@SmallTest
+public class ScreenLifecycleTest extends SysuiTestCase {
+
+    private ScreenLifecycle mScreen;
+    private ScreenLifecycle.Observer mScreenObserverMock;
+
+    @Before
+    public void setUp() throws Exception {
+        mScreen = new ScreenLifecycle();
+        mScreenObserverMock = mock(ScreenLifecycle.Observer.class);
+        mScreen.addObserver(mScreenObserverMock);
+    }
+
+    @Test
+    public void baseState() throws Exception {
+        assertEquals(ScreenLifecycle.SCREEN_OFF, mScreen.getScreenState());
+        verifyNoMoreInteractions(mScreenObserverMock);
+    }
+
+    @Test
+    public void screenTurningOn() throws Exception {
+        mScreen.dispatchScreenTurningOn();
+
+        assertEquals(ScreenLifecycle.SCREEN_TURNING_ON, mScreen.getScreenState());
+        verify(mScreenObserverMock).onScreenTurningOn();
+    }
+
+    @Test
+    public void screenTurnedOn() throws Exception {
+        mScreen.dispatchScreenTurningOn();
+        mScreen.dispatchScreenTurnedOn();
+
+        assertEquals(ScreenLifecycle.SCREEN_ON, mScreen.getScreenState());
+        verify(mScreenObserverMock).onScreenTurnedOn();
+    }
+
+    @Test
+    public void screenTurningOff() throws Exception {
+        mScreen.dispatchScreenTurningOn();
+        mScreen.dispatchScreenTurnedOn();
+        mScreen.dispatchScreenTurningOff();
+
+        assertEquals(ScreenLifecycle.SCREEN_TURNING_OFF, mScreen.getScreenState());
+        verify(mScreenObserverMock).onScreenTurningOff();
+    }
+
+    @Test
+    public void screenTurnedOff() throws Exception {
+        mScreen.dispatchScreenTurningOn();
+        mScreen.dispatchScreenTurnedOn();
+        mScreen.dispatchScreenTurningOff();
+        mScreen.dispatchScreenTurnedOff();
+
+        assertEquals(ScreenLifecycle.SCREEN_OFF, mScreen.getScreenState());
+        verify(mScreenObserverMock).onScreenTurnedOff();
+    }
+
+    @Test
+    public void dump() throws Exception {
+        mScreen.dump(null, new PrintWriter(new ByteArrayOutputStream()), new String[0]);
+    }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/WakefulnessLifecycleTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/WakefulnessLifecycleTest.java
new file mode 100644
index 0000000..e15e0b4
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/WakefulnessLifecycleTest.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+
+import android.support.test.filters.SmallTest;
+import android.testing.AndroidTestingRunner;
+
+import com.android.systemui.SysuiTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+
+@RunWith(AndroidTestingRunner.class)
+@SmallTest
+public class WakefulnessLifecycleTest extends SysuiTestCase {
+
+    private WakefulnessLifecycle mWakefulness;
+    private WakefulnessLifecycle.Observer mWakefulnessObserver;
+
+    @Before
+    public void setUp() throws Exception {
+        mWakefulness = new WakefulnessLifecycle();
+        mWakefulnessObserver = mock(WakefulnessLifecycle.Observer.class);
+        mWakefulness.addObserver(mWakefulnessObserver);
+    }
+
+    @Test
+    public void baseState() throws Exception {
+        assertEquals(WakefulnessLifecycle.WAKEFULNESS_ASLEEP, mWakefulness.getWakefulness());
+
+        verifyNoMoreInteractions(mWakefulnessObserver);
+    }
+
+    @Test
+    public void dispatchStartedWakingUp() throws Exception {
+        mWakefulness.dispatchStartedWakingUp();
+
+        assertEquals(WakefulnessLifecycle.WAKEFULNESS_WAKING, mWakefulness.getWakefulness());
+
+        verify(mWakefulnessObserver).onStartedWakingUp();
+    }
+
+    @Test
+    public void dispatchFinishedWakingUp() throws Exception {
+        mWakefulness.dispatchStartedWakingUp();
+        mWakefulness.dispatchFinishedWakingUp();
+
+        assertEquals(WakefulnessLifecycle.WAKEFULNESS_AWAKE, mWakefulness.getWakefulness());
+
+        verify(mWakefulnessObserver).onFinishedWakingUp();
+    }
+
+    @Test
+    public void dispatchStartedGoingToSleep() throws Exception {
+        mWakefulness.dispatchStartedWakingUp();
+        mWakefulness.dispatchFinishedWakingUp();
+        mWakefulness.dispatchStartedGoingToSleep();
+
+        assertEquals(WakefulnessLifecycle.WAKEFULNESS_GOING_TO_SLEEP,
+                mWakefulness.getWakefulness());
+
+        verify(mWakefulnessObserver).onStartedGoingToSleep();
+    }
+
+    @Test
+    public void dispatchFinishedGoingToSleep() throws Exception {
+        mWakefulness.dispatchStartedWakingUp();
+        mWakefulness.dispatchFinishedWakingUp();
+        mWakefulness.dispatchStartedGoingToSleep();
+        mWakefulness.dispatchFinishedGoingToSleep();
+
+        assertEquals(WakefulnessLifecycle.WAKEFULNESS_ASLEEP,
+                mWakefulness.getWakefulness());
+
+        verify(mWakefulnessObserver).onFinishedGoingToSleep();
+    }
+
+    @Test
+    public void dump() throws Exception {
+        mWakefulness.dump(null, new PrintWriter(new ByteArrayOutputStream()), new String[0]);
+    }
+
+}
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java
index 8cacb4b..9603207 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java
@@ -269,9 +269,9 @@
     }
 
     @Test
-    public void testHandleSysnavKey() {
-        mCommandQueue.handleSystemNavigationKey(1);
+    public void testHandleSysKey() {
+        mCommandQueue.handleSystemKey(1);
         waitForIdleSync();
-        verify(mCallbacks).handleSystemNavigationKey(eq(1));
+        verify(mCallbacks).handleSystemKey(eq(1));
     }
 }
diff --git a/packages/services/PacProcessor/jni/com_android_pacprocessor_PacNative.cpp b/packages/services/PacProcessor/jni/com_android_pacprocessor_PacNative.cpp
index 990d770..846ff25 100644
--- a/packages/services/PacProcessor/jni/com_android_pacprocessor_PacNative.cpp
+++ b/packages/services/PacProcessor/jni/com_android_pacprocessor_PacNative.cpp
@@ -21,7 +21,7 @@
 #include "android_runtime/AndroidRuntime.h"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 #include "proxy_resolver_v8.h"
 
diff --git a/proto/src/system_messages.proto b/proto/src/system_messages.proto
index 93fae58..52f721b 100644
--- a/proto/src/system_messages.proto
+++ b/proto/src/system_messages.proto
@@ -183,6 +183,10 @@
     // Inform the user that the connected audio accessory is not supported
     NOTE_USB_AUDIO_ACCESSORY_NOT_SUPPORTED = 41;
 
+    // Inform the user that a wrong password was detected while attempting to connect
+    // to a Wi-Fi network
+    NOTE_WIFI_WRONG_PASSWORD = 42;
+
     // ADD_NEW_IDS_ABOVE_THIS_LINE
     // Legacy IDs with arbitrary values appear below
     // Legacy IDs existed as stable non-conflicting constants prior to the O release
diff --git a/rs/jni/android_renderscript_RenderScript.cpp b/rs/jni/android_renderscript_RenderScript.cpp
index ee48289..f9f6bf7 100644
--- a/rs/jni/android_renderscript_RenderScript.cpp
+++ b/rs/jni/android_renderscript_RenderScript.cpp
@@ -30,7 +30,7 @@
 #include <android-base/macros.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/android_view_Surface.h"
 #include "android_runtime/android_util_AssetManager.h"
diff --git a/services/autofill/java/com/android/server/autofill/Session.java b/services/autofill/java/com/android/server/autofill/Session.java
index 6d4fb75..a38b9d3f4 100644
--- a/services/autofill/java/com/android/server/autofill/Session.java
+++ b/services/autofill/java/com/android/server/autofill/Session.java
@@ -264,9 +264,20 @@
                 value = getValueFromContexts(id);
             }
         }
-        // TODO(b/62534917): support list values, using the String provided by getAutofillOptions()
-        if (value != null && value.isText()) {
-            return value.getTextValue().toString();
+        if (value != null) {
+            if (value.isText()) {
+                return value.getTextValue().toString();
+            }
+            if (value.isList()) {
+                final CharSequence[] options = getAutofillOptionsFromContexts(id);
+                if (options != null) {
+                    final int index = value.getListValue();
+                    final CharSequence option = options[index];
+                    return option != null ? option.toString() : null;
+                } else {
+                    Slog.w(TAG, "getValueAsString(): no autofill options for id " + id);
+                }
+            }
         }
         return null;
     }
@@ -919,22 +930,38 @@
      */
     @Nullable
     private AutofillValue getValueFromContexts(AutofillId id) {
-        AutofillValue value = null;
         final int numContexts = mContexts.size();
-        for (int i = 0; i < numContexts; i++) {
+        for (int i = numContexts - 1; i >= 0; i--) {
             final FillContext context = mContexts.get(i);
             final ViewNode node = context.findViewNodeByAutofillId(id);
             if (node != null) {
-                final AutofillValue candidate = node.getAutofillValue();
+                final AutofillValue value = node.getAutofillValue();
                 if (sDebug) {
-                    Slog.d(TAG, "getValueFromContexts(" + id + ") at " + i + ": " + candidate);
+                    Slog.d(TAG, "getValueFromContexts(" + id + ") at " + i + ": " + value);
                 }
-                if (candidate != null && !candidate.isEmpty()) {
-                    value = candidate;
+                if (value != null && !value.isEmpty()) {
+                    return value;
                 }
             }
         }
-        return value;
+        return null;
+    }
+
+    /**
+     * Gets the latest autofill options for the given id in the autofill contexts.
+     */
+    @Nullable
+    private CharSequence[] getAutofillOptionsFromContexts(AutofillId id) {
+        final int numContexts = mContexts.size();
+
+        for (int i = numContexts - 1; i >= 0; i--) {
+            final FillContext context = mContexts.get(i);
+            final ViewNode node = context.findViewNodeByAutofillId(id);
+            if (node != null && node.getAutofillOptions() != null) {
+                return node.getAutofillOptions();
+            }
+        }
+        return null;
     }
 
     /**
diff --git a/services/core/java/com/android/server/IpSecService.java b/services/core/java/com/android/server/IpSecService.java
index ac5da93..f72cbc9 100644
--- a/services/core/java/com/android/server/IpSecService.java
+++ b/services/core/java/com/android/server/IpSecService.java
@@ -46,6 +46,7 @@
 import android.util.Slog;
 import android.util.SparseArray;
 import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
 import java.io.FileDescriptor;
 import java.io.IOException;
 import java.io.PrintWriter;
@@ -64,7 +65,7 @@
     private static final int[] DIRECTIONS =
             new int[] {IpSecTransform.DIRECTION_OUT, IpSecTransform.DIRECTION_IN};
 
-    private static final int NETD_FETCH_TIMEOUT = 5000; //ms
+    private static final int NETD_FETCH_TIMEOUT_MS = 5000; // ms
     private static final int MAX_PORT_BIND_ATTEMPTS = 10;
     private static final InetAddress INADDR_ANY;
 
@@ -96,6 +97,24 @@
     private final ManagedResourceArray<UdpSocketRecord> mUdpSocketRecords =
             new ManagedResourceArray<>();
 
+    interface IpSecServiceConfiguration {
+        INetd getNetdInstance() throws RemoteException;
+
+        static IpSecServiceConfiguration GETSRVINSTANCE =
+                new IpSecServiceConfiguration() {
+                    @Override
+                    public INetd getNetdInstance() throws RemoteException {
+                        final INetd netd = NetdService.getInstance();
+                        if (netd == null) {
+                            throw new RemoteException("Failed to Get Netd Instance");
+                        }
+                        return netd;
+                    }
+                };
+    }
+
+    private final IpSecServiceConfiguration mSrvConfig;
+
     /**
      * The ManagedResource class provides a facility to cleanly and reliably release system
      * resources. It relies on two things: an IBinder that allows ManagedResource to automatically
@@ -198,8 +217,7 @@
     };
 
     /**
-     * Minimal wrapper around SparseArray that performs ownership
-     * validation on element accesses.
+     * Minimal wrapper around SparseArray that performs ownership validation on element accesses.
      */
     private class ManagedResourceArray<T extends ManagedResource> {
         SparseArray<T> mArray = new SparseArray<>();
@@ -264,7 +282,8 @@
             for (int direction : DIRECTIONS) {
                 int spi = mSpis[direction].getSpi();
                 try {
-                    getNetdInstance()
+                    mSrvConfig
+                            .getNetdInstance()
                             .ipSecDeleteSecurityAssociation(
                                     mResourceId,
                                     direction,
@@ -328,7 +347,8 @@
             }
 
             try {
-                getNetdInstance()
+                mSrvConfig
+                        .getNetdInstance()
                         .ipSecDeleteSecurityAssociation(
                                 mResourceId, mDirection, mLocalAddress, mRemoteAddress, mSpi);
             } catch (ServiceSpecificException e) {
@@ -387,7 +407,7 @@
      * @param context Binder context for this service
      */
     private IpSecService(Context context) {
-        mContext = context;
+        this(context, IpSecServiceConfiguration.GETSRVINSTANCE);
     }
 
     static IpSecService create(Context context) throws InterruptedException {
@@ -396,6 +416,13 @@
         return service;
     }
 
+    /** @hide */
+    @VisibleForTesting
+    public IpSecService(Context context, IpSecServiceConfiguration config) {
+        mContext = context;
+        mSrvConfig = config;
+    }
+
     public void systemReady() {
         if (isNetdAlive()) {
             Slog.d(TAG, "IpSecService is ready");
@@ -410,23 +437,15 @@
             @Override
             public void run() {
                 synchronized (IpSecService.this) {
-                    NetdService.get(NETD_FETCH_TIMEOUT);
+                    NetdService.get(NETD_FETCH_TIMEOUT_MS);
                 }
             }
         }.start();
     }
 
-    INetd getNetdInstance() throws RemoteException {
-        final INetd netd = NetdService.getInstance();
-        if (netd == null) {
-            throw new RemoteException("Failed to Get Netd Instance");
-        }
-        return netd;
-    }
-
     synchronized boolean isNetdAlive() {
         try {
-            final INetd netd = getNetdInstance();
+            final INetd netd = mSrvConfig.getNetdInstance();
             if (netd == null) {
                 return false;
             }
@@ -447,7 +466,8 @@
         String localAddress = "";
         try {
             spi =
-                    getNetdInstance()
+                    mSrvConfig
+                            .getNetdInstance()
                             .ipSecAllocateSpi(
                                     resourceId,
                                     direction,
@@ -606,7 +626,7 @@
             spis[direction] = mSpiRecords.get(c.getSpiResourceId(direction));
             int spi = spis[direction].getSpi();
             try {
-                getNetdInstance()
+                mSrvConfig.getNetdInstance()
                         .ipSecAddSecurityAssociation(
                                 resourceId,
                                 c.getMode(),
@@ -676,7 +696,8 @@
         IpSecConfig c = info.getConfig();
         try {
             for (int direction : DIRECTIONS) {
-                getNetdInstance()
+                mSrvConfig
+                        .getNetdInstance()
                         .ipSecApplyTransportModeTransform(
                                 socket.getFileDescriptor(),
                                 resourceId,
@@ -704,7 +725,9 @@
     public void removeTransportModeTransform(ParcelFileDescriptor socket, int resourceId)
             throws RemoteException {
         try {
-            getNetdInstance().ipSecRemoveTransportModeTransform(socket.getFileDescriptor());
+            mSrvConfig
+                    .getNetdInstance()
+                    .ipSecRemoveTransportModeTransform(socket.getFileDescriptor());
         } catch (ServiceSpecificException e) {
             // FIXME: get the error code and throw is at an IOException from Errno Exception
         }
diff --git a/services/core/java/com/android/server/PinnerService.java b/services/core/java/com/android/server/PinnerService.java
index 45f9025..3d7408e 100644
--- a/services/core/java/com/android/server/PinnerService.java
+++ b/services/core/java/com/android/server/PinnerService.java
@@ -267,9 +267,10 @@
 
         // determine the ABI from either ApplicationInfo or Build
         String arch = "arm";
-        if (cameraInfo.primaryCpuAbi != null
-            && VMRuntime.is64BitAbi(cameraInfo.primaryCpuAbi)) {
-            arch = arch + "64";
+        if (cameraInfo.primaryCpuAbi != null) {
+            if (VMRuntime.is64BitAbi(cameraInfo.primaryCpuAbi)) {
+                arch = arch + "64";
+            }
         } else {
             if (VMRuntime.is64BitAbi(Build.SUPPORTED_ABIS[0])) {
                 arch = arch + "64";
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index ec0e595..b46e5e5 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -164,7 +164,6 @@
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBLE_BEHIND;
 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
-import static com.android.server.am.ActivityStackSupervisor.ActivityContainer.FORCE_NEW_TASK_FLAGS;
 import static com.android.server.am.ActivityStackSupervisor.CREATE_IF_NEEDED;
 import static com.android.server.am.ActivityStackSupervisor.DEFER_RESUME;
 import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_ONLY;
@@ -211,8 +210,6 @@
 import android.app.BroadcastOptions;
 import android.app.ContentProviderHolder;
 import android.app.Dialog;
-import android.app.IActivityContainer;
-import android.app.IActivityContainerCallback;
 import android.app.IActivityController;
 import android.app.IActivityManager;
 import android.app.IAppTask;
@@ -1732,6 +1729,8 @@
 
     final boolean mPermissionReviewRequired;
 
+    private static String sTheRealBuildSerial = Build.UNKNOWN;
+
     /**
      * Current global configuration information. Contains general settings for the entire system,
      * also corresponds to the merged configuration of the default display.
@@ -4120,8 +4119,7 @@
                             ri.activityInfo.packageName, ri.activityInfo.name));
                     mActivityStarter.startActivityLocked(null, intent, null /*ephemeralIntent*/,
                             null, ri.activityInfo, null /*rInfo*/, null, null, null, null, 0, 0, 0,
-                            null, 0, 0, 0, null, false, false, null, null, null,
-                            "startSetupActivity");
+                            null, 0, 0, 0, null, false, false, null, null, "startSetupActivity");
                 }
             }
         }
@@ -4459,26 +4457,6 @@
                 UserHandle.getCallingUserId());
     }
 
-    final int startActivity(Intent intent, ActivityStackSupervisor.ActivityContainer container) {
-        enforceNotIsolatedCaller("ActivityContainer.startActivity");
-        final int userId = mUserController.handleIncomingUser(Binder.getCallingPid(),
-                Binder.getCallingUid(), mStackSupervisor.mCurrentUser, false,
-                ActivityManagerService.ALLOW_FULL_ONLY, "ActivityContainer", null);
-
-        // TODO: Switch to user app stacks here.
-        String mimeType = intent.getType();
-        final Uri data = intent.getData();
-        if (mimeType == null && data != null && "content".equals(data.getScheme())) {
-            mimeType = getProviderMimeType(data, userId);
-        }
-        container.checkEmbeddedAllowedInner(userId, intent, mimeType);
-
-        intent.addFlags(FORCE_NEW_TASK_FLAGS);
-        return mActivityStarter.startActivityMayWait(null, -1, null, intent, mimeType, null, null,
-                null, null, 0, 0, null, null, null, null, false, userId, container, null,
-                "startActivity");
-    }
-
     @Override
     public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
@@ -4489,8 +4467,7 @@
         // TODO: Switch to user app stacks here.
         return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
-                profilerInfo, null, null, bOptions, false, userId, null, null,
-                "startActivityAsUser");
+                profilerInfo, null, null, bOptions, false, userId, null, "startActivityAsUser");
     }
 
     @Override
@@ -4553,7 +4530,7 @@
         try {
             int ret = mActivityStarter.startActivityMayWait(null, targetUid, targetPackage, intent,
                     resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, null,
-                    null, null, bOptions, ignoreTargetSecurity, userId, null, null,
+                    null, null, bOptions, ignoreTargetSecurity, userId, null,
                     "startActivityAsCaller");
             return ret;
         } catch (SecurityException e) {
@@ -4583,7 +4560,7 @@
         // TODO: Switch to user app stacks here.
         mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
                 null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, res, null,
-                bOptions, false, userId, null, null, "startActivityAndWait");
+                bOptions, false, userId, null, "startActivityAndWait");
         return res;
     }
 
@@ -4597,7 +4574,7 @@
         // TODO: Switch to user app stacks here.
         int ret = mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
-                null, null, config, bOptions, false, userId, null, null, "startActivityWithConfig");
+                null, null, config, bOptions, false, userId, null, "startActivityWithConfig");
         return ret;
     }
 
@@ -4628,7 +4605,7 @@
             }
         }
         int ret = pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
-                resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions, null);
+                resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
         return ret;
     }
 
@@ -4654,7 +4631,7 @@
         // TODO: Switch to user app stacks here.
         return mActivityStarter.startActivityMayWait(null, callingUid, callingPackage, intent,
                 resolvedType, session, interactor, null, null, 0, startFlags, profilerInfo, null,
-                null, bOptions, false, userId, null, null, "startVoiceActivity");
+                null, bOptions, false, userId, null, "startVoiceActivity");
     }
 
     @Override
@@ -4673,7 +4650,7 @@
                 ALLOW_FULL_ONLY, "startAssistantActivity", null);
         return mActivityStarter.startActivityMayWait(null, callingUid, callingPackage, intent,
                 resolvedType, null, null, null, null, 0, 0, null, null, null, bOptions, false,
-                userId, null, null, "startAssistantActivity");
+                userId, null, "startAssistantActivity");
     }
 
     @Override
@@ -4846,7 +4823,7 @@
                     null /*ephemeralIntent*/, r.resolvedType, aInfo, null /*rInfo*/, null,
                     null, resultTo != null ? resultTo.appToken : null, resultWho, requestCode, -1,
                     r.launchedFromUid, r.launchedFromPackage, -1, r.launchedFromUid, 0, options,
-                    false, false, null, null, null, "startNextMatchingActivity");
+                    false, false, null, null, "startNextMatchingActivity");
             Binder.restoreCallingIdentity(origId);
 
             r.finishing = wasFinishing;
@@ -4878,16 +4855,15 @@
     final int startActivityInPackage(int uid, String callingPackage,
             Intent intent, String resolvedType, IBinder resultTo,
             String resultWho, int requestCode, int startFlags, Bundle bOptions, int userId,
-            IActivityContainer container, TaskRecord inTask, String reason) {
+            TaskRecord inTask, String reason) {
 
         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
                 userId, false, ALLOW_FULL_ONLY, "startActivityInPackage", null);
 
         // TODO: Switch to user app stacks here.
-        int ret = mActivityStarter.startActivityMayWait(null, uid, callingPackage, intent,
+        return mActivityStarter.startActivityMayWait(null, uid, callingPackage, intent,
                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
-                null, null, null, bOptions, false, userId, container, inTask, reason);
-        return ret;
+                null, null, null, bOptions, false, userId, inTask, reason);
     }
 
     @Override
@@ -6990,12 +6966,8 @@
             // We deprecated Build.SERIAL and it is not accessible to
             // apps that target the v2 security sandbox. Since access to
             // the serial is now behind a permission we push down the value.
-            String buildSerial = Build.UNKNOWN;
-            if (appInfo.targetSandboxVersion != 2) {
-                buildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
-                        ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
-                        .getSerial();
-            }
+            String buildSerial = appInfo.targetSandboxVersion < 2
+                    ? sTheRealBuildSerial : Build.UNKNOWN;
 
             // Check if this is a secondary process that should be incorporated into some
             // currently active instrumentation.  (Note we do this AFTER all of the profiling
@@ -10481,44 +10453,25 @@
     }
 
     @Override
-    public IActivityContainer createVirtualActivityContainer(IBinder parentActivityToken,
-            IActivityContainerCallback callback) throws RemoteException {
-        enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "createActivityContainer()");
-        synchronized (this) {
-            if (parentActivityToken == null) {
-                throw new IllegalArgumentException("parent token must not be null");
-            }
-            ActivityRecord r = ActivityRecord.forTokenLocked(parentActivityToken);
-            if (r == null) {
-                return null;
-            }
-            if (callback == null) {
-                throw new IllegalArgumentException("callback must not be null");
-            }
-            return mStackSupervisor.createVirtualActivityContainer(r, callback);
-        }
-    }
-
-    @Override
-    public IActivityContainer createStackOnDisplay(int displayId) throws RemoteException {
+    public int createStackOnDisplay(int displayId) throws RemoteException {
         enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "createStackOnDisplay()");
         synchronized (this) {
             final int stackId = mStackSupervisor.getNextStackId();
             final ActivityStack stack =
                     mStackSupervisor.createStackOnDisplay(stackId, displayId, true /*onTop*/);
             if (stack == null) {
-                return null;
+                return INVALID_STACK_ID;
             }
-            return stack.mActivityContainer;
+            return stack.mStackId;
         }
     }
 
     @Override
     public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
         synchronized (this) {
-            ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
-            if (stack != null && stack.mActivityContainer.isAttachedLocked()) {
-                return stack.mActivityContainer.getDisplayId();
+            final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
+            if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
+                return stack.mDisplayId;
             }
             return DEFAULT_DISPLAY;
         }
@@ -14118,6 +14071,12 @@
             mSystemReady = true;
         }
 
+        try {
+            sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
+                    ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
+                    .getSerial();
+        } catch (RemoteException e) {}
+
         ArrayList<ProcessRecord> procsToKill = null;
         synchronized(mPidsSelfLocked) {
             for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
@@ -24360,7 +24319,7 @@
             }
             return mActivityStarter.startActivityMayWait(appThread, -1, callingPackage, intent,
                     resolvedType, null, null, null, null, 0, 0, null, null,
-                    null, bOptions, false, callingUser, null, tr, "AppTaskImpl");
+                    null, bOptions, false, callingUser, tr, "AppTaskImpl");
         }
 
         @Override
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index 9273b3c..45357cb 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -19,7 +19,6 @@
 import android.app.ActivityManager;
 import android.app.ActivityOptions;
 import android.app.AppGlobals;
-import android.app.IActivityContainer;
 import android.app.IActivityController;
 import android.app.IActivityManager;
 import android.app.IStopUserCallback;
@@ -1959,9 +1958,17 @@
             throw new RuntimeException(e.getMessage(), e);
         }
 
-        IActivityContainer container = mInterface.createStackOnDisplay(displayId);
-        if (container != null) {
-            container.startActivity(intent);
+        final int stackId = mInterface.createStackOnDisplay(displayId);
+        if (stackId != INVALID_STACK_ID) {
+            // TODO: Need proper support if this is used by test...
+//            container.startActivity(intent);
+//            ActivityOptions options = ActivityOptions.makeBasic();
+//            options.setLaunchDisplayId(displayId);
+//            options.setLaunchStackId(stackId);
+//            mInterface.startAct
+//            mInterface.startActivityAsUser(null, null, intent, mimeType,
+//                    null, null, 0, mStartFlags, profilerInfo,
+//                    options != null ? options.toBundle() : null, mUserId);
         }
         return 0;
     }
diff --git a/services/core/java/com/android/server/am/ActivityRecord.java b/services/core/java/com/android/server/am/ActivityRecord.java
index 6f68c7a..9a1d928 100644
--- a/services/core/java/com/android/server/am/ActivityRecord.java
+++ b/services/core/java/com/android/server/am/ActivityRecord.java
@@ -164,7 +164,6 @@
 import com.android.server.AttributeCache;
 import com.android.server.AttributeCache.Entry;
 import com.android.server.am.ActivityStack.ActivityState;
-import com.android.server.am.ActivityStackSupervisor.ActivityContainer;
 import com.android.server.wm.AppWindowContainerController;
 import com.android.server.wm.AppWindowContainerListener;
 import com.android.server.wm.TaskWindowContainerController;
@@ -306,7 +305,6 @@
     int launchCount;        // count of launches since last state
     long lastLaunchTime;    // time of last launch of this activity
     ComponentName requestedVrComponent; // the requested component for handling VR mode.
-    ArrayList<ActivityContainer> mChildContainers = new ArrayList<>();
 
     String stringName;      // for caching of toString().
 
@@ -320,7 +318,6 @@
     boolean mTaskOverlay = false; // Task is always on-top of other activities in the task.
 
     boolean mUpdateTaskThumbnailWhenHidden;
-    ActivityContainer mInitialActivityContainer;
 
     TaskDescription taskDescription; // the recents information for this activity
     boolean mLaunchTaskBehind; // this activity is actively being launched with
@@ -798,8 +795,8 @@
             ActivityInfo aInfo, Configuration _configuration,
             ActivityRecord _resultTo, String _resultWho, int _reqCode,
             boolean _componentSpecified, boolean _rootVoiceInteraction,
-            ActivityStackSupervisor supervisor,
-            ActivityContainer container, ActivityOptions options, ActivityRecord sourceRecord) {
+            ActivityStackSupervisor supervisor, ActivityOptions options,
+            ActivityRecord sourceRecord) {
         service = _service;
         appToken = new Token(this);
         info = aInfo;
@@ -830,7 +827,6 @@
         idle = false;
         hasBeenLaunched = false;
         mStackSupervisor = supervisor;
-        mInitialActivityContainer = container;
 
         mRotationAnimationHint = aInfo.rotationAnimation;
 
@@ -1595,11 +1591,6 @@
             mUpdateTaskThumbnailWhenHidden = false;
         }
         setVisibility(visible);
-        final ArrayList<ActivityContainer> containers = mChildContainers;
-        for (int containerNdx = containers.size() - 1; containerNdx >= 0; --containerNdx) {
-            final ActivityContainer container = containers.get(containerNdx);
-            container.setVisible(visible);
-        }
         mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = true;
     }
 
@@ -2615,8 +2606,6 @@
 
         startFreezingScreenLocked(app, 0);
 
-        mStackSupervisor.removeChildActivityContainers(this);
-
         try {
             if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_SWITCH,
                     "Moving to " + (andResume ? "RESUMED" : "PAUSED") + " Relaunching " + this
@@ -2795,7 +2784,7 @@
                 0 /* launchedFromPid */, launchedFromUid, launchedFromPackage, intent, resolvedType,
                 aInfo, service.getConfiguration(), null /* resultTo */, null /* resultWho */,
                 0 /* reqCode */, componentSpecified, false /* rootVoiceInteraction */,
-                stackSupervisor, null /* container */, null /* options */, null /* sourceRecord */);
+                stackSupervisor, null /* options */, null /* sourceRecord */);
 
         r.persistentState = persistentState;
         r.taskDescription = taskDescription;
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index ab76529..ce8aa5e 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/am/ActivityStack.java
@@ -30,6 +30,7 @@
 import static android.view.Display.DEFAULT_DISPLAY;
 import static android.view.Display.FLAG_CAN_SHOW_WITH_INSECURE_KEYGUARD;
 
+import static android.view.Display.INVALID_DISPLAY;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ADD_REMOVE;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_APP;
@@ -124,7 +125,6 @@
 import com.android.internal.os.BatteryStatsImpl;
 import com.android.server.Watchdog;
 import com.android.server.am.ActivityManagerService.ItemMatcher;
-import com.android.server.am.ActivityStackSupervisor.ActivityContainer;
 import com.android.server.wm.StackWindowController;
 import com.android.server.wm.StackWindowListener;
 import com.android.server.wm.WindowManagerService;
@@ -205,7 +205,7 @@
 
     @Override
     protected ConfigurationContainer getParent() {
-        return mActivityContainer.mActivityDisplay;
+        return getDisplay();
     }
 
     @Override
@@ -336,8 +336,8 @@
     int mCurrentUser;
 
     final int mStackId;
-    final ActivityContainer mActivityContainer;
     /** The other stacks, in order, on the attached display. Updated at attach/detach time. */
+    // TODO: This list doesn't belong here...
     ArrayList<ActivityStack> mStacks;
     /** The attached Display's unique identifier, or -1 if detached */
     int mDisplayId;
@@ -447,24 +447,21 @@
         return count;
     }
 
-    ActivityStack(ActivityStackSupervisor.ActivityContainer activityContainer,
-            RecentTasks recentTasks, boolean onTop) {
-        mActivityContainer = activityContainer;
-        mStackSupervisor = activityContainer.getOuter();
-        mService = mStackSupervisor.mService;
+    ActivityStack(ActivityStackSupervisor.ActivityDisplay display, int stackId,
+            ActivityStackSupervisor supervisor, RecentTasks recentTasks, boolean onTop) {
+        mStackSupervisor = supervisor;
+        mService = supervisor.mService;
         mHandler = new ActivityStackHandler(mService.mHandler.getLooper());
         mWindowManager = mService.mWindowManager;
-        mStackId = activityContainer.mStackId;
+        mStackId = stackId;
         mCurrentUser = mService.mUserController.getCurrentUserIdLocked();
         mRecentTasks = recentTasks;
         mTaskPositioner = mStackId == FREEFORM_WORKSPACE_STACK_ID
                 ? new LaunchingTaskPositioner() : null;
-        final ActivityStackSupervisor.ActivityDisplay display = mActivityContainer.mActivityDisplay;
         mTmpRect2.setEmpty();
         mWindowContainerController = createStackWindowController(display.mDisplayId, onTop,
                 mTmpRect2);
-        activityContainer.mStack = this;
-        mStackSupervisor.mActivityContainers.put(mStackId, activityContainer);
+        mStackSupervisor.mStacks.put(mStackId, this);
         postAddToDisplay(display, mTmpRect2.isEmpty() ? null : mTmpRect2, onTop);
     }
 
@@ -521,7 +518,11 @@
      * either destroyed completely or re-parented.
      */
     private void removeFromDisplay() {
-        mDisplayId = Display.INVALID_DISPLAY;
+        final ActivityStackSupervisor.ActivityDisplay display = getDisplay();
+        if (display != null) {
+            display.detachStack(this);
+        }
+        mDisplayId = INVALID_DISPLAY;
         mStacks = null;
         if (mTaskPositioner != null) {
             mTaskPositioner.reset();
@@ -537,14 +538,18 @@
     /** Removes the stack completely. Also calls WindowManager to do the same on its side. */
     void remove() {
         removeFromDisplay();
-        mStackSupervisor.deleteActivityContainerRecord(mStackId);
+        mStackSupervisor.mStacks.remove(mStackId);
         mWindowContainerController.removeContainer();
         mWindowContainerController = null;
         onParentChanged();
     }
 
+    ActivityStackSupervisor.ActivityDisplay getDisplay() {
+        return mStackSupervisor.getActivityDisplay(mDisplayId);
+    }
+
     void getDisplaySize(Point out) {
-        mActivityContainer.mActivityDisplay.mDisplay.getSize(out);
+        getDisplay().mDisplay.getSize(out);
     }
 
     /**
@@ -829,8 +834,7 @@
     }
 
     final boolean isOnHomeDisplay() {
-        return isAttached() &&
-                mActivityContainer.mActivityDisplay.mDisplayId == DEFAULT_DISPLAY;
+        return isAttached() && mDisplayId == DEFAULT_DISPLAY;
     }
 
     void moveToFront(String reason) {
@@ -1257,12 +1261,6 @@
             return false;
         }
 
-        if (mActivityContainer.mParentActivity == null) {
-            // Top level stack, not a child. Look for child stacks.
-            mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming,
-                    pauseImmediately);
-        }
-
         if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSING: " + prev);
         else if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Start pausing: " + prev);
         mResumedActivity = null;
@@ -1965,8 +1963,7 @@
      * {@link Display#FLAG_CAN_SHOW_WITH_INSECURE_KEYGUARD} applied.
      */
     private boolean canShowWithInsecureKeyguard() {
-        final ActivityStackSupervisor.ActivityDisplay activityDisplay
-                = mActivityContainer.mActivityDisplay;
+        final ActivityStackSupervisor.ActivityDisplay activityDisplay = getDisplay();
         if (activityDisplay == null) {
             throw new IllegalStateException("Stack is not attached to any display, stackId="
                     + mStackId);
@@ -2108,7 +2105,6 @@
      * occurred and the activity will be notified immediately.
      */
     void notifyActivityDrawnLocked(ActivityRecord r) {
-        mActivityContainer.setDrawn();
         if ((r == null)
                 || (mUndrawnActivitiesBelowTopTranslucent.remove(r) &&
                         mUndrawnActivitiesBelowTopTranslucent.isEmpty())) {
@@ -2236,12 +2232,8 @@
 
         final boolean hasRunningActivity = next != null;
 
-        final ActivityRecord parent = mActivityContainer.mParentActivity;
-        final boolean isParentNotResumed = parent != null && parent.state != ActivityState.RESUMED;
-        if (hasRunningActivity
-                && (isParentNotResumed || !mActivityContainer.isAttachedLocked())) {
-            // Do not resume this stack if its parent is not resumed.
-            // TODO: If in a loop, make sure that parent stack resumeTopActivity is called 1st.
+        // TODO: Maybe this entire condition can get removed?
+        if (hasRunningActivity && getDisplay() == null) {
             return false;
         }
 
@@ -3809,7 +3801,7 @@
             }
         }
         if (noActivitiesInStack) {
-            mActivityContainer.onTaskListEmptyLocked();
+            remove();
         }
     }
 
@@ -3920,7 +3912,7 @@
                             destIntent, null /*ephemeralIntent*/, null, aInfo, null /*rInfo*/, null,
                             null, parent.appToken, null, 0, -1, parent.launchedFromUid,
                             parent.launchedFromPackage, -1, parent.launchedFromUid, 0, null,
-                            false, true, null, null, null, "navigateUpTo");
+                            false, true, null, null, "navigateUpTo");
                     foundParentInTask = res == ActivityManager.START_SUCCESS;
                 } catch (RemoteException e) {
                     foundParentInTask = false;
@@ -4005,7 +3997,6 @@
     }
 
     private void removeActivityFromHistoryLocked(ActivityRecord r, String reason) {
-        mStackSupervisor.removeChildActivityContainers(r);
         finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
         r.makeFinishingLocked();
         if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE,
@@ -4620,7 +4611,7 @@
      * focus may be on another display.
      */
     private ActivityStack getTopStackOnDisplay() {
-        final ArrayList<ActivityStack> stacks = mActivityContainer.mActivityDisplay.mStacks;
+        final ArrayList<ActivityStack> stacks = getDisplay().mStacks;
         return stacks.isEmpty() ? null : stacks.get(stacks.size() - 1);
     }
 
@@ -5097,7 +5088,7 @@
                 mStacks.add(0, this);
             }
             if (!isHomeOrRecentsStack()) {
-                mActivityContainer.onTaskListEmptyLocked();
+                remove();
             }
         }
 
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index 90d9149..d9b7d76 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -36,8 +36,6 @@
 import static android.app.ActivityManager.StackId.RECENTS_STACK_ID;
 import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY;
 import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
-import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
-import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
 import static android.os.Process.SYSTEM_UID;
 import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
@@ -50,7 +48,6 @@
 
 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
-import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONTAINERS;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IDLE;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
@@ -72,7 +69,6 @@
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
-import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBLE_BEHIND;
 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.am.ActivityManagerService.ANIMATE;
@@ -112,7 +108,6 @@
 import android.app.ActivityManager.StackInfo;
 import android.app.ActivityOptions;
 import android.app.AppOpsManager;
-import android.app.IActivityContainerCallback;
 import android.app.ProfilerInfo;
 import android.app.ResultInfo;
 import android.app.StatusBarManager;
@@ -120,7 +115,6 @@
 import android.app.admin.IDevicePolicyManager;
 import android.content.ComponentName;
 import android.content.Context;
-import android.content.IIntentSender;
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
@@ -132,10 +126,7 @@
 import android.graphics.Rect;
 import android.hardware.display.DisplayManager;
 import android.hardware.display.DisplayManager.DisplayListener;
-import android.hardware.display.DisplayManagerGlobal;
 import android.hardware.display.DisplayManagerInternal;
-import android.hardware.display.VirtualDisplay;
-import android.hardware.input.InputManager;
 import android.hardware.input.InputManagerInternal;
 import android.os.Binder;
 import android.os.Bundle;
@@ -151,7 +142,6 @@
 import android.os.ServiceManager;
 import android.os.SystemClock;
 import android.os.Trace;
-import android.os.TransactionTooLargeException;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.os.WorkSource;
@@ -168,9 +158,8 @@
 import android.util.SparseArray;
 import android.util.SparseIntArray;
 import android.view.Display;
-import android.view.InputEvent;
-import android.view.Surface;
 
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.content.ReferrerIntent;
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.os.TransferPipe;
@@ -194,7 +183,6 @@
 
 public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener {
     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStackSupervisor" : TAG_AM;
-    private static final String TAG_CONTAINERS = TAG + POSTFIX_CONTAINERS;
     private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
     private static final String TAG_IDLE = TAG + POSTFIX_IDLE;
     private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
@@ -205,7 +193,6 @@
     private static final String TAG_STATES = TAG + POSTFIX_STATES;
     private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
     static final String TAG_TASKS = TAG + POSTFIX_TASKS;
-    private static final String TAG_VISIBLE_BEHIND = TAG + POSTFIX_VISIBLE_BEHIND;
 
     /** How long we wait until giving up on the last activity telling us it is idle. */
     static final int IDLE_TIMEOUT = 10 * 1000;
@@ -224,10 +211,8 @@
     static final int HANDLE_DISPLAY_ADDED = FIRST_SUPERVISOR_STACK_MSG + 5;
     static final int HANDLE_DISPLAY_CHANGED = FIRST_SUPERVISOR_STACK_MSG + 6;
     static final int HANDLE_DISPLAY_REMOVED = FIRST_SUPERVISOR_STACK_MSG + 7;
-    static final int CONTAINER_CALLBACK_VISIBILITY = FIRST_SUPERVISOR_STACK_MSG + 8;
     static final int LOCK_TASK_START_MSG = FIRST_SUPERVISOR_STACK_MSG + 9;
     static final int LOCK_TASK_END_MSG = FIRST_SUPERVISOR_STACK_MSG + 10;
-    static final int CONTAINER_CALLBACK_TASK_LIST_EMPTY = FIRST_SUPERVISOR_STACK_MSG + 11;
     static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_STACK_MSG + 12;
     static final int SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG = FIRST_SUPERVISOR_STACK_MSG + 13;
     static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 14;
@@ -414,7 +399,7 @@
 
     // TODO: Add listener for removal of references.
     /** Mapping from (ActivityStack/TaskStack).mStackId to their current state */
-    SparseArray<ActivityContainer> mActivityContainers = new SparseArray<>();
+    SparseArray<ActivityStack> mStacks = new SparseArray<>();
 
     // TODO: There should be an ActivityDisplayController coordinating am/wm interaction.
     /** Mapping from displayId to display current state */
@@ -680,31 +665,15 @@
     }
 
     boolean isFocusedStack(ActivityStack stack) {
-        if (stack == null) {
-            return false;
-        }
-
-        final ActivityRecord parent = stack.mActivityContainer.mParentActivity;
-        if (parent != null) {
-            stack = parent.getStack();
-        }
-        return stack == mFocusedStack;
+        return stack != null && stack == mFocusedStack;
     }
 
     /** The top most stack on its display. */
     boolean isFrontStackOnDisplay(ActivityStack stack) {
-        return isFrontOfStackList(stack, stack.mActivityContainer.mActivityDisplay.mStacks);
+        return isFrontOfStackList(stack, stack.getDisplay().mStacks);
     }
 
     private boolean isFrontOfStackList(ActivityStack stack, List<ActivityStack> stackList) {
-        if (stack == null) {
-            return false;
-        }
-
-        final ActivityRecord parent = stack.mActivityContainer.mParentActivity;
-        if (parent != null) {
-            stack = parent.getStack();
-        }
         return stack == stackList.get((stackList.size() - 1));
     }
 
@@ -1097,21 +1066,6 @@
         return pausing;
     }
 
-    void pauseChildStacks(ActivityRecord parent, boolean userLeaving, boolean uiSleeping,
-            ActivityRecord resuming, boolean dontWait) {
-        // TODO: Put all stacks in supervisor and iterate through them instead.
-        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
-            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
-            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
-                final ActivityStack stack = stacks.get(stackNdx);
-                if (stack.mResumedActivity != null &&
-                        stack.mActivityContainer.mParentActivity == parent) {
-                    stack.startPausingLocked(userLeaving, uiSleeping, resuming, dontWait);
-                }
-            }
-        }
-    }
-
     void cancelInitializingActivities() {
         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
@@ -2210,9 +2164,9 @@
 
     protected <T extends ActivityStack> T getStack(int stackId, boolean createStaticStackIfNeeded,
             boolean createOnTop) {
-        final ActivityContainer activityContainer = mActivityContainers.get(stackId);
-        if (activityContainer != null) {
-            return (T) activityContainer.mStack;
+        final ActivityStack stack = mStacks.get(stackId);
+        if (stack != null) {
+            return (T) stack;
         }
         if (!createStaticStackIfNeeded || !StackId.isStaticStack(stackId)) {
             return null;
@@ -2355,33 +2309,6 @@
                 (StackId.isResizeableByDockedStack(stackId) && getStack(DOCKED_STACK_ID) != null);
     }
 
-    ActivityContainer createVirtualActivityContainer(ActivityRecord parentActivity,
-            IActivityContainerCallback callback) {
-        ActivityContainer activityContainer =
-                new VirtualActivityContainer(parentActivity, callback);
-        mActivityContainers.put(activityContainer.mStackId, activityContainer);
-        if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS,
-                "createActivityContainer: " + activityContainer);
-        parentActivity.mChildContainers.add(activityContainer);
-        return activityContainer;
-    }
-
-    void removeChildActivityContainers(ActivityRecord parentActivity) {
-        final ArrayList<ActivityContainer> childStacks = parentActivity.mChildContainers;
-        for (int containerNdx = childStacks.size() - 1; containerNdx >= 0; --containerNdx) {
-            ActivityContainer container = childStacks.remove(containerNdx);
-            if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS, "removeChildActivityContainers: removing "
-                    + container);
-            container.release();
-        }
-    }
-
-    void deleteActivityContainerRecord(int stackId) {
-        if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS,
-                "deleteActivityContainerRecord: callers=" + Debug.getCallers(4));
-        mActivityContainers.remove(stackId);
-    }
-
     void resizeStackLocked(int stackId, Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds,
             boolean preserveWindows, boolean allowResizeInDockedMode, boolean deferResume) {
         if (stackId == DOCKED_STACK_ID) {
@@ -2646,12 +2573,18 @@
         if (activityDisplay == null) {
             return null;
         }
+        return createStack(stackId, activityDisplay, onTop);
 
-        final ActivityContainer activityContainer =
-                new ActivityContainer(stackId, activityDisplay, onTop);
-        return activityContainer.mStack;
     }
 
+    ActivityStack createStack(int stackId, ActivityDisplay display, boolean onTop) {
+        switch (stackId) {
+            case PINNED_STACK_ID:
+                return new PinnedActivityStack(display, stackId, this, mRecentTasks, onTop);
+            default:
+                return new ActivityStack(display, stackId, this, mRecentTasks, onTop);
+        }
+    }
 
     void removeStackInSurfaceTransaction(int stackId) {
         final ActivityStack stack = getStack(stackId);
@@ -2879,23 +2812,24 @@
             throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown displayId="
                     + displayId);
         }
-        final ActivityContainer activityContainer = mActivityContainers.get(stackId);
-        if (activityContainer != null) {
-            if (activityContainer.isAttachedLocked()) {
-                if (activityContainer.getDisplayId() == displayId) {
-                    throw new IllegalArgumentException("Trying to move stackId=" + stackId
-                            + " to its current displayId=" + displayId);
-                }
-
-                activityContainer.moveToDisplayLocked(activityDisplay, onTop);
-            } else {
-                throw new IllegalStateException("moveStackToDisplayLocked: Stack with stackId="
-                        + stackId + " is not attached to any display.");
-            }
-        } else {
+        final ActivityStack stack = mStacks.get(stackId);
+        if (stack == null) {
             throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown stackId="
                     + stackId);
         }
+
+        final ActivityDisplay currentDisplay = stack.getDisplay();
+        if (currentDisplay == null) {
+            throw new IllegalStateException("moveStackToDisplayLocked: Stack with stack=" + stack
+                    + " is not attached to any display.");
+        }
+
+        if (currentDisplay.mDisplayId == displayId) {
+            throw new IllegalArgumentException("Trying to move stack=" + stack
+                    + " to its current displayId=" + displayId);
+        }
+
+        stack.reparent(activityDisplay, onTop);
         // TODO(multi-display): resize stacks properly if moved from split-screen.
     }
 
@@ -2923,7 +2857,6 @@
         // Ensure that we're not moving a task to a dynamic stack if device doesn't support
         // multi-display.
         // TODO(multi-display): Support non-dynamic stacks on secondary displays.
-        // TODO: Check ActivityView after fixing b/35349678.
         if (StackId.isDynamicStack(stackId) && !mService.mSupportsMultiDisplay) {
             throw new IllegalArgumentException("Device doesn't support multi-display, can not"
                     + " reparent task=" + task + " to stackId=" + stackId);
@@ -3107,11 +3040,6 @@
                             + stack);
                     continue;
                 }
-                if (!stack.mActivityContainer.isEligibleForNewTasks()) {
-                    if (DEBUG_TASKS) Slog.d(TAG_TASKS,
-                            "Skipping stack: (new task not allowed) " + stack);
-                    continue;
-                }
                 stack.findTaskLocked(r, mTmpFindTaskResult);
                 // It is possible to have tasks in multiple stacks with the same root affinity, so
                 // we should keep looking after finding an affinity match to see if there is a
@@ -3626,7 +3554,7 @@
         pw.print(prefix);
         pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
         pw.print(prefix); pw.println("mUserStackInFront=" + mUserStackInFront);
-        pw.print(prefix); pw.println("mActivityContainers=" + mActivityContainers);
+        pw.print(prefix); pw.println("mStacks=" + mStacks);
         pw.print(prefix); pw.print("mLockTaskModeState=" + lockTaskModeToString());
         final SparseArray<String[]> packages = mService.mLockTaskPackages;
         if (packages.size() > 0) {
@@ -3920,6 +3848,10 @@
         return getActivityDisplayOrCreateLocked(displayId) != null;
     }
 
+    ActivityDisplay getActivityDisplay(int displayId) {
+        return mActivityDisplays.get(displayId);
+    }
+
     /**
      * Get an existing instance of {@link ActivityDisplay} or create new if there is a
      * corresponding record in display manager.
@@ -4481,16 +4413,6 @@
                 case HANDLE_DISPLAY_REMOVED: {
                     handleDisplayRemoved(msg.arg1);
                 } break;
-                case CONTAINER_CALLBACK_VISIBILITY: {
-                    final ActivityContainer container = (ActivityContainer) msg.obj;
-                    final IActivityContainerCallback callback = container.mCallback;
-                    if (callback != null) {
-                        try {
-                            callback.setVisible(container.asBinder(), msg.arg1 == 1);
-                        } catch (RemoteException e) {
-                        }
-                    }
-                } break;
                 case LOCK_TASK_START_MSG: {
                     // When lock task starts, we disable the status bars.
                     try {
@@ -4563,16 +4485,6 @@
                     }
                     mLockTaskNotify.showToast(LOCK_TASK_MODE_PINNED);
                 } break;
-                case CONTAINER_CALLBACK_TASK_LIST_EMPTY: {
-                    final ActivityContainer container = (ActivityContainer) msg.obj;
-                    final IActivityContainerCallback callback = container.mCallback;
-                    if (callback != null) {
-                        try {
-                            callback.onAllActivitiesComplete(container.asBinder());
-                        } catch (RemoteException e) {
-                        }
-                    }
-                } break;
                 case LAUNCH_TASK_BEHIND_COMPLETE: {
                     synchronized (mService) {
                         ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
@@ -4586,340 +4498,7 @@
         }
     }
 
-    class ActivityContainer extends android.app.IActivityContainer.Stub {
-        final static int FORCE_NEW_TASK_FLAGS = FLAG_ACTIVITY_NEW_TASK |
-                FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION;
-        final int mStackId;
-        IActivityContainerCallback mCallback = null;
-        ActivityStack mStack;
-        ActivityRecord mParentActivity = null;
-        String mIdString;
-
-        boolean mVisible = true;
-
-        /** Display this ActivityStack is currently on. Null if not attached to a Display. */
-        ActivityDisplay mActivityDisplay;
-
-        final static int CONTAINER_STATE_HAS_SURFACE = 0;
-        final static int CONTAINER_STATE_NO_SURFACE = 1;
-        final static int CONTAINER_STATE_FINISHING = 2;
-        int mContainerState = CONTAINER_STATE_HAS_SURFACE;
-
-        ActivityContainer(int stackId, ActivityDisplay activityDisplay, boolean onTop) {
-            synchronized (mService) {
-                mStackId = stackId;
-                mActivityDisplay = activityDisplay;
-                mIdString = "ActivtyContainer{" + mStackId + "}";
-
-                createStack(stackId, onTop);
-                if (DEBUG_STACK) Slog.d(TAG_STACK, "Creating " + this);
-            }
-        }
-
-        protected void createStack(int stackId, boolean onTop) {
-            switch (stackId) {
-                case PINNED_STACK_ID:
-                    new PinnedActivityStack(this, mRecentTasks, onTop);
-                    break;
-                default:
-                    new ActivityStack(this, mRecentTasks, onTop);
-                    break;
-            }
-        }
-
-        /**
-         * Adds the stack to specified display. Also calls WindowManager to do the same from
-         * {@link ActivityStack#reparent(ActivityDisplay, boolean)}.
-         * @param activityDisplay The display to add the stack to.
-         */
-        void addToDisplayLocked(ActivityDisplay activityDisplay) {
-            if (DEBUG_STACK) Slog.d(TAG_STACK, "addToDisplayLocked: " + this
-                    + " to display=" + activityDisplay);
-            if (mActivityDisplay != null) {
-                throw new IllegalStateException("ActivityContainer is already attached, " +
-                        "displayId=" + mActivityDisplay.mDisplayId);
-            }
-            mActivityDisplay = activityDisplay;
-            mStack.reparent(activityDisplay, true /* onTop */);
-        }
-
-        @Override
-        public void addToDisplay(int displayId) {
-            synchronized (mService) {
-                final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
-                if (activityDisplay == null) {
-                    return;
-                }
-                addToDisplayLocked(activityDisplay);
-            }
-        }
-
-        @Override
-        public int getDisplayId() {
-            synchronized (mService) {
-                if (mActivityDisplay != null) {
-                    return mActivityDisplay.mDisplayId;
-                }
-            }
-            return -1;
-        }
-
-        @Override
-        public int getStackId() {
-            synchronized (mService) {
-                return mStackId;
-            }
-        }
-
-        @Override
-        public boolean injectEvent(InputEvent event) {
-            final long origId = Binder.clearCallingIdentity();
-            try {
-                synchronized (mService) {
-                    if (mActivityDisplay != null) {
-                        return mInputManagerInternal.injectInputEvent(event,
-                                mActivityDisplay.mDisplayId,
-                                InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
-                    }
-                }
-                return false;
-            } finally {
-                Binder.restoreCallingIdentity(origId);
-            }
-        }
-
-        @Override
-        public void release() {
-            synchronized (mService) {
-                if (mContainerState == CONTAINER_STATE_FINISHING) {
-                    return;
-                }
-                mContainerState = CONTAINER_STATE_FINISHING;
-
-                long origId = Binder.clearCallingIdentity();
-                try {
-                    mStack.finishAllActivitiesLocked(false);
-                    mService.mActivityStarter.removePendingActivityLaunchesLocked(mStack);
-                } finally {
-                    Binder.restoreCallingIdentity(origId);
-                }
-            }
-        }
-
-        /**
-         * Remove the stack completely. Must be called only when there are no tasks left in it,
-         * as this method does not finish running activities.
-         */
-        void removeLocked() {
-            if (DEBUG_STACK) Slog.d(TAG_STACK, "removeLocked: " + this + " from display="
-                    + mActivityDisplay + " Callers=" + Debug.getCallers(2));
-            if (mActivityDisplay != null) {
-                removeFromDisplayLocked();
-            }
-            mStack.remove();
-        }
-
-        /**
-         * Remove the stack from its current {@link ActivityDisplay}, so it can be either destroyed
-         * completely or re-parented.
-         */
-        private void removeFromDisplayLocked() {
-            if (DEBUG_STACK) Slog.d(TAG_STACK, "removeFromDisplayLocked: " + this
-                    + " current displayId=" + mActivityDisplay.mDisplayId);
-
-            mActivityDisplay.detachStack(mStack);
-            mActivityDisplay = null;
-        }
-
-        /**
-         * Move the stack to specified display.
-         * @param activityDisplay Target display to move the stack to.
-         * @param onTop Indicates whether container should be place on top or on bottom.
-         */
-        void moveToDisplayLocked(ActivityDisplay activityDisplay, boolean onTop) {
-            if (DEBUG_STACK) Slog.d(TAG_STACK, "moveToDisplayLocked: " + this + " from display="
-                    + mActivityDisplay + " to display=" + activityDisplay
-                    + " Callers=" + Debug.getCallers(2));
-
-            removeFromDisplayLocked();
-
-            mActivityDisplay = activityDisplay;
-            mStack.reparent(activityDisplay, onTop);
-        }
-
-        @Override
-        public final int startActivity(Intent intent) {
-            return mService.startActivity(intent, this);
-        }
-
-        @Override
-        public final int startActivityIntentSender(IIntentSender intentSender)
-                throws TransactionTooLargeException {
-            mService.enforceNotIsolatedCaller("ActivityContainer.startActivityIntentSender");
-
-            if (!(intentSender instanceof PendingIntentRecord)) {
-                throw new IllegalArgumentException("Bad PendingIntent object");
-            }
-
-            final int userId = mService.mUserController.handleIncomingUser(Binder.getCallingPid(),
-                    Binder.getCallingUid(), mCurrentUser, false,
-                    ActivityManagerService.ALLOW_FULL_ONLY, "ActivityContainer", null);
-
-            final PendingIntentRecord pendingIntent = (PendingIntentRecord) intentSender;
-            checkEmbeddedAllowedInner(userId, pendingIntent.key.requestIntent,
-                    pendingIntent.key.requestResolvedType);
-
-            return pendingIntent.sendInner(0, null, null, null, null, null, null, null, 0,
-                    FORCE_NEW_TASK_FLAGS, FORCE_NEW_TASK_FLAGS, null, this);
-        }
-
-        void checkEmbeddedAllowedInner(int userId, Intent intent, String resolvedType) {
-            ActivityInfo aInfo = resolveActivity(intent, resolvedType, 0, null, userId);
-            if (aInfo != null && (aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
-                throw new SecurityException(
-                        "Attempt to embed activity that has not set allowEmbedded=\"true\"");
-            }
-        }
-
-        @Override
-        public IBinder asBinder() {
-            return this;
-        }
-
-        @Override
-        public void setSurface(Surface surface, int width, int height, int density) {
-            mService.enforceNotIsolatedCaller("ActivityContainer.attachToSurface");
-        }
-
-        ActivityStackSupervisor getOuter() {
-            return ActivityStackSupervisor.this;
-        }
-
-        boolean isAttachedLocked() {
-            return mActivityDisplay != null;
-        }
-
-        // TODO: Make sure every change to ActivityRecord.visible results in a call to this.
-        void setVisible(boolean visible) {
-            if (mVisible != visible) {
-                mVisible = visible;
-                if (mCallback != null) {
-                    mHandler.obtainMessage(CONTAINER_CALLBACK_VISIBILITY, visible ? 1 : 0,
-                            0 /* unused */, this).sendToTarget();
-                }
-            }
-        }
-
-        void setDrawn() {
-        }
-
-        // You can always start a new task on a regular ActivityStack.
-        boolean isEligibleForNewTasks() {
-            return true;
-        }
-
-        void onTaskListEmptyLocked() {
-            removeLocked();
-            mHandler.obtainMessage(CONTAINER_CALLBACK_TASK_LIST_EMPTY, this).sendToTarget();
-        }
-
-        @Override
-        public String toString() {
-            return mIdString + (mActivityDisplay == null ? "N" : "A");
-        }
-    }
-
-    private class VirtualActivityContainer extends ActivityContainer {
-        Surface mSurface;
-        boolean mDrawn = false;
-
-        VirtualActivityContainer(ActivityRecord parent, IActivityContainerCallback callback) {
-            super(getNextStackId(), parent.getStack().mActivityContainer.mActivityDisplay,
-                    true /* onTop */);
-            mParentActivity = parent;
-            mCallback = callback;
-            mContainerState = CONTAINER_STATE_NO_SURFACE;
-            mIdString = "VirtualActivityContainer{" + mStackId + ", parent=" + mParentActivity + "}";
-        }
-
-        @Override
-        public void setSurface(Surface surface, int width, int height, int density) {
-            super.setSurface(surface, width, height, density);
-
-            synchronized (mService) {
-                final long origId = Binder.clearCallingIdentity();
-                try {
-                    setSurfaceLocked(surface, width, height, density);
-                } finally {
-                    Binder.restoreCallingIdentity(origId);
-                }
-            }
-        }
-
-        private void setSurfaceLocked(Surface surface, int width, int height, int density) {
-            if (mContainerState == CONTAINER_STATE_FINISHING) {
-                return;
-            }
-            VirtualActivityDisplay virtualActivityDisplay =
-                    (VirtualActivityDisplay) mActivityDisplay;
-            if (virtualActivityDisplay == null) {
-                virtualActivityDisplay =
-                        new VirtualActivityDisplay(width, height, density);
-                mActivityDisplay = virtualActivityDisplay;
-                mActivityDisplays.put(virtualActivityDisplay.mDisplayId, virtualActivityDisplay);
-                addToDisplayLocked(virtualActivityDisplay);
-            }
-
-            if (mSurface != null) {
-                mSurface.release();
-            }
-
-            mSurface = surface;
-            if (surface != null) {
-                resumeFocusedStackTopActivityLocked();
-            } else {
-                mContainerState = CONTAINER_STATE_NO_SURFACE;
-                ((VirtualActivityDisplay) mActivityDisplay).setSurface(null);
-                if (mStack.mPausingActivity == null && mStack.mResumedActivity != null) {
-                    mStack.startPausingLocked(false, true, null, false);
-                }
-            }
-
-            setSurfaceIfReadyLocked();
-
-            if (DEBUG_STACK) Slog.d(TAG_STACK,
-                    "setSurface: " + this + " to display=" + virtualActivityDisplay);
-        }
-
-        @Override
-        boolean isAttachedLocked() {
-            return mSurface != null && super.isAttachedLocked();
-        }
-
-        @Override
-        void setDrawn() {
-            synchronized (mService) {
-                mDrawn = true;
-                setSurfaceIfReadyLocked();
-            }
-        }
-
-        // Never start a new task on an ActivityView if it isn't explicitly specified.
-        @Override
-        boolean isEligibleForNewTasks() {
-            return false;
-        }
-
-        private void setSurfaceIfReadyLocked() {
-            if (DEBUG_STACK) Slog.v(TAG_STACK, "setSurfaceIfReadyLocked: mDrawn=" + mDrawn +
-                    " mContainerState=" + mContainerState + " mSurface=" + mSurface);
-            if (mDrawn && mSurface != null && mContainerState == CONTAINER_STATE_NO_SURFACE) {
-                ((VirtualActivityDisplay) mActivityDisplay).setSurface(mSurface);
-                mContainerState = CONTAINER_STATE_HAS_SURFACE;
-            }
-        }
-    }
-
+    // TODO: Move to its own file.
     /** Exactly one of these classes per Display in the system. Capable of holding zero or more
      * attached {@link ActivityStack}s */
     class ActivityDisplay extends ConfigurationContainer {
@@ -4934,7 +4513,9 @@
         /** Array of all UIDs that are present on the display. */
         private IntArray mDisplayAccessUIDs = new IntArray();
 
+        @VisibleForTesting
         ActivityDisplay() {
+            mActivityDisplays.put(mDisplayId, this);
         }
 
         // After instantiation, check that mDisplay is not null before using this. The alternative
@@ -5011,43 +4592,6 @@
         }
     }
 
-    class VirtualActivityDisplay extends ActivityDisplay {
-        VirtualDisplay mVirtualDisplay;
-
-        VirtualActivityDisplay(int width, int height, int density) {
-            DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
-            mVirtualDisplay = dm.createVirtualDisplay(mService.mContext, null /* projection */,
-                    VIRTUAL_DISPLAY_BASE_NAME, width, height, density, null /* surface */,
-                    DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC |
-                    DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY, null /* callback */,
-                    null /* handler */, null /* uniqueId */);
-
-            init(mVirtualDisplay.getDisplay());
-
-            mWindowManager.onDisplayAdded(mDisplayId);
-        }
-
-        void setSurface(Surface surface) {
-            if (mVirtualDisplay != null) {
-                mVirtualDisplay.setSurface(surface);
-            }
-        }
-
-        @Override
-        void detachStack(ActivityStack stack) {
-            super.detachStack(stack);
-            if (mVirtualDisplay != null) {
-                mVirtualDisplay.release();
-                mVirtualDisplay = null;
-            }
-        }
-
-        @Override
-        public String toString() {
-            return "VirtualActivityDisplay={" + mDisplayId + "}";
-        }
-    }
-
     ActivityStack findStackBehind(ActivityStack stack) {
         // TODO(multi-display): We are only looking for stacks on the default display.
         final ActivityDisplay display = mActivityDisplays.get(DEFAULT_DISPLAY);
@@ -5154,7 +4698,7 @@
             intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
             userId = task.userId;
             int result = mService.startActivityInPackage(callingUid, callingPackage, intent, null,
-                    null, null, 0, 0, bOptions, userId, null, task, "startActivityFromRecents");
+                    null, null, 0, 0, bOptions, userId, task, "startActivityFromRecents");
             if (launchStackId == DOCKED_STACK_ID) {
                 setResizingDuringAnimation(task);
             }
diff --git a/services/core/java/com/android/server/am/ActivityStarter.java b/services/core/java/com/android/server/am/ActivityStarter.java
index 4f04066..7495832 100644
--- a/services/core/java/com/android/server/am/ActivityStarter.java
+++ b/services/core/java/com/android/server/am/ActivityStarter.java
@@ -90,12 +90,10 @@
 import android.app.ActivityManager;
 import android.app.ActivityOptions;
 import android.app.AppGlobals;
-import android.app.IActivityContainer;
 import android.app.IApplicationThread;
 import android.app.PendingIntent;
 import android.app.ProfilerInfo;
 import android.app.WaitResult;
-import android.content.ComponentName;
 import android.content.IIntentSender;
 import android.content.Intent;
 import android.content.IntentSender;
@@ -260,8 +258,7 @@
             IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
             String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
             ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
-            ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
-            TaskRecord inTask, String reason) {
+            ActivityRecord[] outActivity, TaskRecord inTask, String reason) {
 
         if (TextUtils.isEmpty(reason)) {
             throw new IllegalArgumentException("Need to specify a reason.");
@@ -274,7 +271,7 @@
                 aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                 callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                 options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
-                container, inTask);
+                inTask);
 
         if (outActivity != null) {
             // mLastStartActivityRecord[0] is set in the call to startActivity above.
@@ -292,8 +289,7 @@
             IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
             String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
             ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
-            ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
-            TaskRecord inTask) {
+            ActivityRecord[] outActivity, TaskRecord inTask) {
         int err = ActivityManager.START_SUCCESS;
         // Pull the optional Ephemeral Installer-only bundle out of the options early.
         final Bundle verificationBundle
@@ -505,10 +501,8 @@
                 if (DEBUG_PERMISSIONS_REVIEW) {
                     Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true,
                             true, false) + "} from uid " + callingUid + " on display "
-                            + (container == null ? (mSupervisor.mFocusedStack == null ?
-                            DEFAULT_DISPLAY : mSupervisor.mFocusedStack.mDisplayId) :
-                            (container.mActivityDisplay == null ? DEFAULT_DISPLAY :
-                                    container.mActivityDisplay.mDisplayId)));
+                            + (mSupervisor.mFocusedStack == null
+                            ? DEFAULT_DISPLAY : mSupervisor.mFocusedStack.mDisplayId));
                 }
             }
         }
@@ -530,7 +524,7 @@
         ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
                 callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
                 resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
-                mSupervisor, container, options, sourceRecord);
+                mSupervisor, options, sourceRecord);
         if (outActivity != null) {
             outActivity[0] = r;
         }
@@ -649,7 +643,7 @@
                 null /*callingPackage*/, 0 /*realCallingPid*/, 0 /*realCallingUid*/,
                 0 /*startFlags*/, null /*options*/, false /*ignoreTargetSecurity*/,
                 false /*componentSpecified*/, mLastHomeActivityStartRecord /*outActivity*/,
-                null /*container*/, null /*inTask*/, "startHomeActivity: " + reason);
+                null /*inTask*/, "startHomeActivity: " + reason);
         if (mSupervisor.inResumeTopActivity) {
             // If we are in resume section already, home activity will be initialized, but not
             // resumed (to avoid recursive resume) and will stay that way until something pokes it
@@ -674,7 +668,7 @@
             IBinder resultTo, String resultWho, int requestCode, int startFlags,
             ProfilerInfo profilerInfo, WaitResult outResult,
             Configuration globalConfig, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
-            IActivityContainer iContainer, TaskRecord inTask, String reason) {
+            TaskRecord inTask, String reason) {
         // Refuse possible leaked file descriptors
         if (intent != null && intent.hasFileDescriptors()) {
             throw new IllegalArgumentException("File descriptors passed in Intent");
@@ -727,14 +721,7 @@
         ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
 
         ActivityOptions options = ActivityOptions.fromBundle(bOptions);
-        ActivityStackSupervisor.ActivityContainer container =
-                (ActivityStackSupervisor.ActivityContainer)iContainer;
         synchronized (mService) {
-            if (container != null && container.mParentActivity != null &&
-                    container.mParentActivity.state != RESUMED) {
-                // Cannot start a child activity if the parent is not resumed.
-                return ActivityManager.START_CANCELED;
-            }
             final int realCallingPid = Binder.getCallingPid();
             final int realCallingUid = Binder.getCallingUid();
             int callingPid;
@@ -747,12 +734,7 @@
                 callingPid = callingUid = -1;
             }
 
-            final ActivityStack stack;
-            if (container == null || container.mStack.isOnHomeDisplay()) {
-                stack = mSupervisor.mFocusedStack;
-            } else {
-                stack = container.mStack;
-            }
+            final ActivityStack stack = mSupervisor.mFocusedStack;
             stack.mConfigWillChange = globalConfig != null
                     && mService.getGlobalConfiguration().diff(globalConfig) != 0;
             if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
@@ -828,8 +810,8 @@
                     aInfo, rInfo, voiceSession, voiceInteractor,
                     resultTo, resultWho, requestCode, callingPid,
                     callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
-                    options, ignoreTargetSecurity, componentSpecified, outRecord, container,
-                    inTask, reason);
+                    options, ignoreTargetSecurity, componentSpecified, outRecord, inTask,
+                    reason);
 
             Binder.restoreCallingIdentity(origId);
 
@@ -954,7 +936,7 @@
                             resolvedTypes[i], aInfo, null /*rInfo*/, null, null, resultTo, null, -1,
                             callingPid, callingUid, callingPackage,
                             realCallingPid, realCallingUid, 0,
-                            options, false, componentSpecified, outActivity, null, null, reason);
+                            options, false, componentSpecified, outActivity, null, reason);
                     if (res < 0) {
                         return res;
                     }
@@ -2069,13 +2051,6 @@
             return currentStack;
         }
 
-        final ActivityStackSupervisor.ActivityContainer container = r.mInitialActivityContainer;
-        if (container != null) {
-            // The first time put it on the desired stack, after this put on task stack.
-            r.mInitialActivityContainer = null;
-            return container.mStack;
-        }
-
         if (canLaunchIntoFocusedStack(r, newTask)) {
             if (DEBUG_FOCUS || DEBUG_STACK) Slog.d(TAG_FOCUS,
                     "computeStackFocus: Have a focused stack=" + mSupervisor.mFocusedStack);
@@ -2140,13 +2115,11 @@
             default:
                 // Dynamic stacks behave similarly to the fullscreen stack and can contain any
                 // resizeable task.
-                // TODO: Check ActivityView after fixing b/35349678.
                 canUseFocusedStack = isDynamicStack(focusedStackId)
                         && r.canBeLaunchedOnDisplay(focusedStack.mDisplayId);
         }
 
-        return canUseFocusedStack
-                && (!newTask || focusedStack.mActivityContainer.isEligibleForNewTasks())
+        return canUseFocusedStack && !newTask
                 // We strongly prefer to launch activities on the same display as their source.
                 && (mSourceDisplayId == focusedStack.mDisplayId);
     }
@@ -2212,9 +2185,7 @@
 
         // The parent activity doesn't want to launch the activity on top of itself, but
         // instead tries to put it onto other side in side-by-side mode.
-        final ActivityStack parentStack = task != null ? task.getStack()
-                : r.mInitialActivityContainer != null ? r.mInitialActivityContainer.mStack
-                : mSupervisor.mFocusedStack;
+        final ActivityStack parentStack = task != null ? task.getStack(): mSupervisor.mFocusedStack;
 
         if (parentStack != mSupervisor.mFocusedStack) {
             // If task's parent stack is not focused - use it during adjacent launch.
@@ -2265,7 +2236,6 @@
             case ASSISTANT_STACK_ID:
                 return r.isAssistantActivity();
             default:
-                // TODO: Check ActivityView after fixing b/35349678.
                 if (StackId.isDynamicStack(stackId)) {
                     return r.canBeLaunchedOnDisplay(displayId);
                 }
diff --git a/services/core/java/com/android/server/am/AppErrors.java b/services/core/java/com/android/server/am/AppErrors.java
index 0d1c579..fc03db1 100644
--- a/services/core/java/com/android/server/am/AppErrors.java
+++ b/services/core/java/com/android/server/am/AppErrors.java
@@ -409,10 +409,9 @@
                         final Set<String> cats = task.intent.getCategories();
                         if (cats != null && cats.contains(Intent.CATEGORY_LAUNCHER)) {
                             mService.startActivityInPackage(task.mCallingUid,
-                                    task.mCallingPackage, task.intent,
-                                    null, null, null, 0, 0,
-                                    ActivityOptions.makeBasic().toBundle(),
-                                    task.userId, null, null, "AppErrors");
+                                    task.mCallingPackage, task.intent, null, null, null, 0, 0,
+                                    ActivityOptions.makeBasic().toBundle(), task.userId, null,
+                                    "AppErrors");
                         }
                     }
                 }
diff --git a/services/core/java/com/android/server/am/PendingIntentRecord.java b/services/core/java/com/android/server/am/PendingIntentRecord.java
index cad5dcf..ee59386 100644
--- a/services/core/java/com/android/server/am/PendingIntentRecord.java
+++ b/services/core/java/com/android/server/am/PendingIntentRecord.java
@@ -20,7 +20,6 @@
 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
 
 import android.app.ActivityManager;
-import android.app.IActivityContainer;
 import android.content.IIntentSender;
 import android.content.IIntentReceiver;
 import android.app.PendingIntent;
@@ -37,7 +36,6 @@
 import android.util.TimeUtils;
 
 import com.android.internal.os.IResultReceiver;
-import com.android.server.am.ActivityStackSupervisor.ActivityContainer;
 
 import java.io.PrintWriter;
 import java.lang.ref.WeakReference;
@@ -234,30 +232,23 @@
     public void send(int code, Intent intent, String resolvedType, IBinder whitelistToken,
             IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
         sendInner(code, intent, resolvedType, whitelistToken, finishedReceiver,
-                requiredPermission, null, null, 0, 0, 0, options, null);
+                requiredPermission, null, null, 0, 0, 0, options);
     }
 
     public int sendWithResult(int code, Intent intent, String resolvedType, IBinder whitelistToken,
             IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
         return sendInner(code, intent, resolvedType, whitelistToken, finishedReceiver,
-                requiredPermission, null, null, 0, 0, 0, options, null);
+                requiredPermission, null, null, 0, 0, 0, options);
     }
 
     int sendInner(int code, Intent intent, String resolvedType, IBinder whitelistToken,
             IIntentReceiver finishedReceiver,
             String requiredPermission, IBinder resultTo, String resultWho, int requestCode,
-            int flagsMask, int flagsValues, Bundle options, IActivityContainer container) {
+            int flagsMask, int flagsValues, Bundle options) {
         if (intent != null) intent.setDefusable(true);
         if (options != null) options.setDefusable(true);
 
         synchronized (owner) {
-            final ActivityContainer activityContainer = (ActivityContainer)container;
-            if (activityContainer != null && activityContainer.mParentActivity != null &&
-                    activityContainer.mParentActivity.state
-                            != ActivityStack.ActivityState.RESUMED) {
-                // Cannot start a child activity if the parent is not resumed.
-                return ActivityManager.START_CANCELED;
-            }
             if (!canceled) {
                 sent = true;
                 if ((key.flags&PendingIntent.FLAG_ONE_SHOT) != 0) {
@@ -346,7 +337,7 @@
                             } else {
                                 owner.startActivityInPackage(uid, key.packageName, finalIntent,
                                         resolvedType, resultTo, resultWho, requestCode, 0,
-                                        options, userId, container, null, "PendingIntentRecord");
+                                        options, userId, null, "PendingIntentRecord");
                             }
                         } catch (RuntimeException e) {
                             Slog.w(TAG, "Unable to send startActivity intent", e);
diff --git a/services/core/java/com/android/server/am/PinnedActivityStack.java b/services/core/java/com/android/server/am/PinnedActivityStack.java
index 2010c24..392fbb2 100644
--- a/services/core/java/com/android/server/am/PinnedActivityStack.java
+++ b/services/core/java/com/android/server/am/PinnedActivityStack.java
@@ -20,7 +20,6 @@
 import android.content.res.Configuration;
 import android.graphics.Rect;
 
-import com.android.server.am.ActivityStackSupervisor.ActivityContainer;
 import com.android.server.wm.PinnedStackWindowController;
 import com.android.server.wm.PinnedStackWindowListener;
 
@@ -33,9 +32,9 @@
 class PinnedActivityStack extends ActivityStack<PinnedStackWindowController>
         implements PinnedStackWindowListener {
 
-    PinnedActivityStack(ActivityContainer activityContainer,
-            RecentTasks recentTasks, boolean onTop) {
-        super(activityContainer, recentTasks, onTop);
+    PinnedActivityStack(ActivityStackSupervisor.ActivityDisplay display, int stackId,
+            ActivityStackSupervisor supervisor, RecentTasks recentTasks, boolean onTop) {
+        super(display, stackId, supervisor, recentTasks, onTop);
     }
 
     @Override
diff --git a/services/core/java/com/android/server/am/TaskRecord.java b/services/core/java/com/android/server/am/TaskRecord.java
index 96d8573..751ecef 100644
--- a/services/core/java/com/android/server/am/TaskRecord.java
+++ b/services/core/java/com/android/server/am/TaskRecord.java
@@ -1045,8 +1045,7 @@
         }
         // We need to provide the current orientation of the display on which this task resides,
         // not the orientation of the task.
-        final int orientation =
-                getStack().mActivityContainer.mActivityDisplay.getConfiguration().orientation;
+        final int orientation = getStack().getDisplay().getConfiguration().orientation;
         return setLastThumbnailLocked(thumbnail, taskWidth, taskHeight, orientation);
     }
 
diff --git a/services/core/java/com/android/server/radio/RadioService.java b/services/core/java/com/android/server/broadcastradio/BroadcastRadioService.java
similarity index 91%
rename from services/core/java/com/android/server/radio/RadioService.java
rename to services/core/java/com/android/server/broadcastradio/BroadcastRadioService.java
index 8b0d3aa..914f034 100644
--- a/services/core/java/com/android/server/radio/RadioService.java
+++ b/services/core/java/com/android/server/broadcastradio/BroadcastRadioService.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.radio;
+package com.android.server.broadcastradio;
 
 import android.Manifest;
 import android.content.Context;
@@ -29,8 +29,8 @@
 
 import java.util.List;
 
-public class RadioService extends SystemService {
-    private final RadioServiceImpl mServiceImpl = new RadioServiceImpl();
+public class BroadcastRadioService extends SystemService {
+    private final ServiceImpl mServiceImpl = new ServiceImpl();
 
     /**
      * This field is used by native code, do not access or modify.
@@ -40,7 +40,7 @@
     private final Object mLock = new Object();
     private List<RadioManager.ModuleProperties> mModules = null;
 
-    public RadioService(Context context) {
+    public BroadcastRadioService(Context context) {
         super(context);
     }
 
@@ -61,7 +61,7 @@
         publishBinderService(Context.RADIO_SERVICE, mServiceImpl);
     }
 
-    private class RadioServiceImpl extends IRadioService.Stub {
+    private class ServiceImpl extends IRadioService.Stub {
         private void enforcePolicyAccess() {
             if (PackageManager.PERMISSION_GRANTED != getContext().checkCallingPermission(
                     Manifest.permission.ACCESS_FM_RADIO)) {
diff --git a/services/core/java/com/android/server/radio/Tuner.java b/services/core/java/com/android/server/broadcastradio/Tuner.java
similarity index 91%
rename from services/core/java/com/android/server/radio/Tuner.java
rename to services/core/java/com/android/server/broadcastradio/Tuner.java
index 3d16cac..b9a1e81 100644
--- a/services/core/java/com/android/server/radio/Tuner.java
+++ b/services/core/java/com/android/server/broadcastradio/Tuner.java
@@ -14,9 +14,11 @@
  * limitations under the License.
  */
 
-package com.android.server.radio;
+package com.android.server.broadcastradio;
 
 import android.annotation.NonNull;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
 import android.hardware.radio.ITuner;
 import android.hardware.radio.ITunerCallback;
 import android.hardware.radio.ProgramSelector;
@@ -28,7 +30,7 @@
 import java.util.List;
 
 class Tuner extends ITuner.Stub {
-    private static final String TAG = "RadioService.Tuner";
+    private static final String TAG = "BroadcastRadioService.Tuner";
 
     /**
      * This field is used by native code, do not access or modify.
@@ -86,6 +88,8 @@
     private native List<RadioManager.ProgramInfo> nativeGetProgramList(long nativeContext,
             String filter);
 
+    private native byte[] nativeGetImage(long nativeContext, int id);
+
     private native boolean nativeIsAnalogForced(long nativeContext);
     private native void nativeSetAnalogForced(long nativeContext, boolean isForced);
 
@@ -213,6 +217,23 @@
     }
 
     @Override
+    public Bitmap getImage(int id) {
+        if (id == 0) {
+            throw new IllegalArgumentException("Image ID is missing");
+        }
+
+        byte[] rawImage;
+        synchronized (mLock) {
+            rawImage = nativeGetImage(mNativeContext, id);
+        }
+        if (rawImage == null || rawImage.length == 0) {
+            return null;
+        }
+
+        return BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
+    }
+
+    @Override
     public boolean startBackgroundScan() {
         synchronized (mLock) {
             checkNotClosedLocked();
diff --git a/services/core/java/com/android/server/radio/TunerCallback.java b/services/core/java/com/android/server/broadcastradio/TunerCallback.java
similarity index 96%
rename from services/core/java/com/android/server/radio/TunerCallback.java
rename to services/core/java/com/android/server/broadcastradio/TunerCallback.java
index 62110cf..25f3775 100644
--- a/services/core/java/com/android/server/radio/TunerCallback.java
+++ b/services/core/java/com/android/server/broadcastradio/TunerCallback.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.radio;
+package com.android.server.broadcastradio;
 
 import android.annotation.NonNull;
 import android.hardware.radio.ITuner;
@@ -27,7 +27,7 @@
 import android.util.Slog;
 
 class TunerCallback implements ITunerCallback {
-    private static final String TAG = "RadioService.TunerCallback";
+    private static final String TAG = "BroadcastRadioService.TunerCallback";
 
     /**
      * This field is used by native code, do not access or modify.
diff --git a/services/core/java/com/android/server/input/InputForwarder.java b/services/core/java/com/android/server/input/InputForwarder.java
new file mode 100644
index 0000000..bebbc93
--- /dev/null
+++ b/services/core/java/com/android/server/input/InputForwarder.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.server.input;
+
+import android.app.IInputForwarder;
+import android.hardware.input.InputManagerInternal;
+import android.view.InputEvent;
+import android.os.Binder;
+
+import com.android.server.LocalServices;
+
+import static android.hardware.input.InputManager.INJECT_INPUT_EVENT_MODE_ASYNC;
+
+/**
+ * Basic implementation of {@link IInputForwarder}.
+ */
+class InputForwarder extends IInputForwarder.Stub {
+
+    private final InputManagerInternal mInputManagerInternal;
+    private final int mDisplayId;
+
+    InputForwarder(int displayId) {
+        mDisplayId = displayId;
+        mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
+    }
+
+    @Override
+    public boolean forwardEvent(InputEvent event) {
+        return mInputManagerInternal.injectInputEvent(event, mDisplayId,
+                INJECT_INPUT_EVENT_MODE_ASYNC);
+    }
+}
\ No newline at end of file
diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java
index 717efbf..fa9b107 100644
--- a/services/core/java/com/android/server/input/InputManagerService.java
+++ b/services/core/java/com/android/server/input/InputManagerService.java
@@ -37,6 +37,7 @@
 import org.xmlpull.v1.XmlPullParser;
 
 import android.Manifest;
+import android.app.IInputForwarder;
 import android.app.Notification;
 import android.app.NotificationManager;
 import android.app.PendingIntent;
@@ -57,6 +58,7 @@
 import android.content.res.TypedArray;
 import android.content.res.XmlResourceParser;
 import android.database.ContentObserver;
+import android.hardware.display.DisplayManager;
 import android.hardware.display.DisplayViewport;
 import android.hardware.input.IInputDevicesChangedListener;
 import android.hardware.input.IInputManager;
@@ -85,6 +87,7 @@
 import android.util.Slog;
 import android.util.SparseArray;
 import android.util.Xml;
+import android.view.Display;
 import android.view.IInputFilter;
 import android.view.IInputFilterHost;
 import android.view.IWindow;
@@ -1862,6 +1865,29 @@
         nativeMonitor(mPtr);
     }
 
+    // Binder call
+    @Override
+    public IInputForwarder createInputForwarder(int displayId) throws RemoteException {
+        if (!checkCallingPermission(android.Manifest.permission.INJECT_EVENTS,
+                "createInputForwarder()")) {
+            throw new SecurityException("Requires INJECT_EVENTS permission");
+        }
+        final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
+        final Display display = displayManager.getDisplay(displayId);
+        if (display == null) {
+            throw new IllegalArgumentException(
+                    "Can't create input forwarder for non-existent displayId: " + displayId);
+        }
+        final int callingUid = Binder.getCallingUid();
+        final int displayOwnerUid = display.getOwnerUid();
+        if (callingUid != displayOwnerUid) {
+            throw new SecurityException(
+                    "Only owner of the display can forward input events to it.");
+        }
+
+        return new InputForwarder(displayId);
+    }
+
     // Native callback.
     private void notifyConfigurationChanged(long whenNanos) {
         mWindowManagerCallbacks.notifyConfigurationChanged();
diff --git a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
index 9d92cbc..a6ea6b2 100644
--- a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
+++ b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
@@ -111,7 +111,7 @@
             mProjectionGrant.stop();
         }
         if (mMediaRouteInfo != null) {
-            mMediaRouter.getDefaultRoute().select();
+            mMediaRouter.getFallbackRoute().select();
         }
         mProjectionToken = projection.asBinder();
         mProjectionGrant = projection;
diff --git a/services/core/java/com/android/server/notification/ConditionProviders.java b/services/core/java/com/android/server/notification/ConditionProviders.java
index 5cc14b5..3444ef3 100644
--- a/services/core/java/com/android/server/notification/ConditionProviders.java
+++ b/services/core/java/com/android/server/notification/ConditionProviders.java
@@ -35,6 +35,7 @@
 import android.util.Slog;
 
 import com.android.internal.R;
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.server.notification.NotificationManagerService.DumpFilter;
 
 import java.io.PrintWriter;
@@ -43,7 +44,8 @@
 
 public class ConditionProviders extends ManagedServices {
 
-    private static final String TAG_ENABLED_DND_APPS = "dnd_apps";
+    @VisibleForTesting
+    static final String TAG_ENABLED_DND_APPS = "dnd_apps";
 
     private final ArrayList<ConditionRecord> mRecords = new ArrayList<>();
     private final ArraySet<String> mSystemConditionProviderNames;
@@ -84,7 +86,7 @@
         c.caption = "condition provider";
         c.serviceInterface = ConditionProviderService.SERVICE_INTERFACE;
         c.secureSettingName = Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES;
-        c.managedServiceTypeTag = TAG_ENABLED_DND_APPS;
+        c.xmlTag = TAG_ENABLED_DND_APPS;
         c.secondarySettingName = Settings.Secure.ENABLED_NOTIFICATION_LISTENERS;
         c.bindPermission = android.Manifest.permission.BIND_CONDITION_PROVIDER_SERVICE;
         c.settingsAction = Settings.ACTION_CONDITION_PROVIDER_SETTINGS;
diff --git a/services/core/java/com/android/server/notification/ManagedServices.java b/services/core/java/com/android/server/notification/ManagedServices.java
index 2f88740..8087813 100644
--- a/services/core/java/com/android/server/notification/ManagedServices.java
+++ b/services/core/java/com/android/server/notification/ManagedServices.java
@@ -52,6 +52,7 @@
 import android.util.Slog;
 import android.util.SparseArray;
 
+import com.android.internal.util.XmlUtils;
 import com.android.server.notification.NotificationManagerService.DumpFilter;
 
 import org.xmlpull.v1.XmlPullParser;
@@ -226,7 +227,7 @@
     }
 
     public void writeXml(XmlSerializer out, boolean forBackup) throws IOException {
-        out.startTag(null, getConfig().managedServiceTypeTag);
+        out.startTag(null, getConfig().xmlTag);
 
         if (forBackup) {
             trimApprovedListsAccordingToInstalledServices();
@@ -241,7 +242,7 @@
                 for (int j = 0; j < M; j++) {
                     final boolean isPrimary = approvedByType.keyAt(j);
                     final Set<String> approved = approvedByType.valueAt(j);
-                    if (approved != null && approved.size() > 0) {
+                    if (approved != null) {
                         String allowedItems = String.join(ENABLED_SERVICES_SEPARATOR, approved);
                         out.startTag(null, TAG_MANAGED_SERVICES);
                         out.attribute(null, ATT_APPROVED_LIST, allowedItems);
@@ -260,43 +261,34 @@
             }
         }
 
-        out.endTag(null, getConfig().managedServiceTypeTag);
+        out.endTag(null, getConfig().xmlTag);
     }
 
-    /**
-     * @return false if modifications were made to the data on load that requires the xml file
-     * to be re-written
-     */
-    public boolean readXml(XmlPullParser parser)
+    protected void migrateToXml() {
+        loadAllowedComponentsFromSettings();
+    }
+
+    public void readXml(XmlPullParser parser)
             throws XmlPullParserException, IOException {
-        boolean rewriteXml = false;
-        int type = parser.getEventType();
-        String tag = parser.getName();
-        if (type != XmlPullParser.START_TAG || !getConfig().managedServiceTypeTag.equals(tag)) {
-            // xml empty/invalid - read from setting instead
-            loadAllowedComponentsFromSettings();
-            rewriteXml = true;
-        } else {
-            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
-                tag = parser.getName();
-                if (type == XmlPullParser.END_TAG
-                        && getConfig().managedServiceTypeTag.equals(tag)) {
-                    break;
-                }
-                if (type == XmlPullParser.START_TAG) {
-                    if (TAG_MANAGED_SERVICES.equals(tag)) {
-                        final String approved = XmlUtils.safeString(parser, ATT_APPROVED_LIST, "");
-                        final int userId = XmlUtils.safeInt(parser, ATT_USER_ID, 0);
-                        final boolean isPrimary = XmlUtils.safeBool(parser, ATT_IS_PRIMARY, true);
-                        addApprovedList(approved, userId, isPrimary);
-                    }
+        int type;
+        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
+            String tag = parser.getName();
+            if (type == XmlPullParser.END_TAG
+                    && getConfig().xmlTag.equals(tag)) {
+                break;
+            }
+            if (type == XmlPullParser.START_TAG) {
+                if (TAG_MANAGED_SERVICES.equals(tag)) {
+                    final String approved = XmlUtils.readStringAttribute(parser, ATT_APPROVED_LIST);
+                    final int userId = XmlUtils.readIntAttribute(parser, ATT_USER_ID, 0);
+                    final boolean isPrimary =
+                            XmlUtils.readBooleanAttribute(parser, ATT_IS_PRIMARY, true);
+                    addApprovedList(approved, userId, isPrimary);
+                    mUseXml = true;
                 }
             }
-            mUseXml = true;
         }
         rebindServices(false);
-
-        return rewriteXml;
     }
 
     private void loadAllowedComponentsFromSettings() {
@@ -1119,7 +1111,7 @@
         public String serviceInterface;
         public String secureSettingName;
         public String secondarySettingName;
-        public String managedServiceTypeTag;
+        public String xmlTag;
         public String bindPermission;
         public String settingsAction;
         public int clientLabel;
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index 6a10113..9866928 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -55,7 +55,6 @@
 
 import static android.view.Display.DEFAULT_DISPLAY;
 import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
-import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
 
 import android.Manifest;
 import android.annotation.NonNull;
@@ -162,6 +161,7 @@
 import com.android.internal.util.DumpUtils;
 import com.android.internal.util.FastXmlSerializer;
 import com.android.internal.util.Preconditions;
+import com.android.internal.util.XmlUtils;
 import com.android.server.DeviceIdleController;
 import com.android.server.EventLogTags;
 import com.android.server.LocalServices;
@@ -342,7 +342,7 @@
 
     private final UserProfiles mUserProfiles = new UserProfiles();
     private NotificationListeners mListeners;
-    private NotificationAssistants mNotificationAssistants;
+    private NotificationAssistants mAssistants;
     private ConditionProviders mConditionProviders;
     private NotificationUsageStats mUsageStats;
 
@@ -441,24 +441,38 @@
         }
     }
 
-    private void readPolicyXml(InputStream stream, boolean forRestore)
+    void readPolicyXml(InputStream stream, boolean forRestore)
             throws XmlPullParserException, NumberFormatException, IOException {
         final XmlPullParser parser = Xml.newPullParser();
         parser.setInput(stream, StandardCharsets.UTF_8.name());
-
-        boolean saveXml = false;
-        while (parser.next() != END_DOCUMENT) {
-            mZenModeHelper.readXml(parser, forRestore);
-            mRankingHelper.readXml(parser, forRestore);
+        XmlUtils.beginDocument(parser, TAG_NOTIFICATION_POLICY);
+        boolean migratedManagedServices = false;
+        int outerDepth = parser.getDepth();
+        while (XmlUtils.nextElementWithin(parser, outerDepth)) {
+            if (ZenModeConfig.ZEN_TAG.equals(parser.getName())) {
+                mZenModeHelper.readXml(parser, forRestore);
+            } else if (RankingHelper.TAG_RANKING.equals(parser.getName())){
+                mRankingHelper.readXml(parser, forRestore);
+            }
             // No non-system managed services are allowed on low ram devices
             if (!ActivityManager.isLowRamDeviceStatic()) {
-                saveXml |= mListeners.readXml(parser);
-                saveXml |= mNotificationAssistants.readXml(parser);
-                saveXml |= mConditionProviders.readXml(parser);
+                if (mListeners.getConfig().xmlTag.equals(parser.getName())) {
+                    mListeners.readXml(parser);
+                    migratedManagedServices = true;
+                } else if (mAssistants.getConfig().xmlTag.equals(parser.getName())) {
+                    mAssistants.readXml(parser);
+                    migratedManagedServices = true;
+                } else if (mConditionProviders.getConfig().xmlTag.equals(parser.getName())) {
+                    mConditionProviders.readXml(parser);
+                    migratedManagedServices = true;
+                }
             }
         }
 
-        if (saveXml) {
+        if (!migratedManagedServices) {
+            mListeners.migrateToXml();
+            mAssistants.migrateToXml();
+            mConditionProviders.migrateToXml();
             savePolicyFile();
         }
     }
@@ -467,7 +481,7 @@
         if (DBG) Slog.d(TAG, "loadPolicyFile");
         synchronized (mPolicyFile) {
 
-            FileInputStream infile = null;
+            InputStream infile = null;
             try {
                 infile = mPolicyFile.openRead();
                 readPolicyXml(infile, false /*forRestore*/);
@@ -523,7 +537,7 @@
         mZenModeHelper.writeXml(out, forBackup);
         mRankingHelper.writeXml(out, forBackup);
         mListeners.writeXml(out, forBackup);
-        mNotificationAssistants.writeXml(out, forBackup);
+        mAssistants.writeXml(out, forBackup);
         mConditionProviders.writeXml(out, forBackup);
         out.endTag(null, TAG_NOTIFICATION_POLICY);
         out.endDocument();
@@ -898,7 +912,7 @@
                     }
                 }
                 mListeners.onPackagesChanged(removingPackage, pkgList, uidList);
-                mNotificationAssistants.onPackagesChanged(removingPackage, pkgList, uidList);
+                mAssistants.onPackagesChanged(removingPackage, pkgList, uidList);
                 mConditionProviders.onPackagesChanged(removingPackage, pkgList, uidList);
                 mRankingHelper.onPackagesChanged(removingPackage, changeUserId, pkgList, uidList);
                 savePolicyFile();
@@ -970,7 +984,7 @@
                 // Refresh managed services
                 mConditionProviders.onUserSwitched(user);
                 mListeners.onUserSwitched(user);
-                mNotificationAssistants.onUserSwitched(user);
+                mAssistants.onUserSwitched(user);
                 mZenModeHelper.onUserSwitched(user);
             } else if (action.equals(Intent.ACTION_USER_ADDED)) {
                 mUserProfiles.updateCache(context);
@@ -983,7 +997,7 @@
                 final int user = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
                 mConditionProviders.onUserUnlocked(user);
                 mListeners.onUserUnlocked(user);
-                mNotificationAssistants.onUserUnlocked(user);
+                mAssistants.onUserUnlocked(user);
                 mZenModeHelper.onUserUnlocked(user);
             }
         }
@@ -1231,7 +1245,7 @@
         mListeners = notificationListeners;
 
         // This is a MangedServices object that keeps track of the assistant.
-        mNotificationAssistants = notificationAssistants;
+        mAssistants = notificationAssistants;
 
         mPolicyFile = policyFile;
         loadPolicyFile();
@@ -1400,7 +1414,7 @@
             // bind to listener services.
             mSettingsObserver.observe();
             mListeners.onBootPhaseAppsCanStart();
-            mNotificationAssistants.onBootPhaseAppsCanStart();
+            mAssistants.onBootPhaseAppsCanStart();
             mConditionProviders.onBootPhaseAppsCanStart();
         }
     }
@@ -1569,7 +1583,6 @@
                 Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
                 return ;
             }
-
             final boolean isSystemToast = isCallerSystemOrPhone() || ("android".equals(pkg));
             final boolean isPackageSuspended =
                     isPackageSuspendedForUser(pkg, Binder.getCallingUid());
@@ -1928,7 +1941,7 @@
 
             // Listener & assistant
             mListeners.onPackagesChanged(true, packages, uids);
-            mNotificationAssistants.onPackagesChanged(true, packages, uids);
+            mAssistants.onPackagesChanged(true, packages, uids);
 
             // Zen
             mConditionProviders.onPackagesChanged(true, packages, uids);
@@ -2134,8 +2147,8 @@
             long identity = Binder.clearCallingIdentity();
             try {
                 ManagedServices manager =
-                        mNotificationAssistants.isComponentEnabledForCurrentProfiles(component)
-                        ? mNotificationAssistants
+                        mAssistants.isComponentEnabledForCurrentProfiles(component)
+                        ? mAssistants
                         : mListeners;
                 manager.setComponentState(component, true);
             } finally {
@@ -2255,7 +2268,7 @@
             try {
                 synchronized (mNotificationLock) {
                     final ManagedServiceInfo info =
-                            mNotificationAssistants.checkServiceTokenLocked(token);
+                            mAssistants.checkServiceTokenLocked(token);
                     unsnoozeNotificationInt(key, info);
                 }
             } finally {
@@ -2788,7 +2801,7 @@
         public boolean isNotificationAssistantAccessGranted(ComponentName assistant) {
             Preconditions.checkNotNull(assistant);
             checkCallerIsSystemOrSameApp(assistant.getPackageName());
-            return mNotificationAssistants.isPackageOrComponentAllowed(assistant.flattenToString(),
+            return mAssistants.isPackageOrComponentAllowed(assistant.flattenToString(),
                     getCallingUserHandle().getIdentifier());
         }
 
@@ -2835,7 +2848,7 @@
             if (!mActivityManager.isLowRamDevice()) {
                 mConditionProviders.setPackageOrComponentEnabled(assistant.flattenToString(),
                         userId, false, granted);
-                mNotificationAssistants.setPackageOrComponentEnabled(assistant.flattenToString(),
+                mAssistants.setPackageOrComponentEnabled(assistant.flattenToString(),
                         userId, true, granted);
 
                 getContext().sendBroadcastAsUser(new Intent(
@@ -2854,7 +2867,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mNotificationLock) {
-                    mNotificationAssistants.checkServiceTokenLocked(token);
+                    mAssistants.checkServiceTokenLocked(token);
                     int N = mEnqueuedNotifications.size();
                     for (int i = 0; i < N; i++) {
                         final NotificationRecord n = mEnqueuedNotifications.get(i);
@@ -2876,7 +2889,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mNotificationLock) {
-                    mNotificationAssistants.checkServiceTokenLocked(token);
+                    mAssistants.checkServiceTokenLocked(token);
                     NotificationRecord n = mNotificationsByKey.get(adjustment.getKey());
                     applyAdjustment(n, adjustment);
                 }
@@ -2893,7 +2906,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mNotificationLock) {
-                    mNotificationAssistants.checkServiceTokenLocked(token);
+                    mAssistants.checkServiceTokenLocked(token);
                     for (Adjustment adjustment : adjustments) {
                         NotificationRecord n = mNotificationsByKey.get(adjustment.getKey());
                         applyAdjustment(n, adjustment);
@@ -3273,7 +3286,7 @@
                 }
                 pw.println(')');
                 pw.println("\n  Notification assistant services:");
-                mNotificationAssistants.dump(pw, filter);
+                mAssistants.dump(pw, filter);
             }
 
             if (!filter.filtered || zenOnly) {
@@ -3664,7 +3677,7 @@
             cancelNotificationLocked(r, false, REASON_SNOOZED, wasPosted);
             updateLightsLocked();
             if (mSnoozeCriterionId != null) {
-                mNotificationAssistants.notifyAssistantSnoozedLocked(r.sbn, mSnoozeCriterionId);
+                mAssistants.notifyAssistantSnoozedLocked(r.sbn, mSnoozeCriterionId);
                 mSnoozeHelper.snooze(r);
             } else {
                 mSnoozeHelper.snooze(r, mDuration);
@@ -3728,8 +3741,8 @@
                 mRankingHelper.extractSignals(r);
 
                 // tell the assistant service about the notification
-                if (mNotificationAssistants.isEnabled()) {
-                    mNotificationAssistants.onNotificationEnqueued(r);
+                if (mAssistants.isEnabled()) {
+                    mAssistants.onNotificationEnqueued(r);
                     mHandler.postDelayed(new PostNotificationRunnable(r.getKey()),
                             DELAY_FOR_ASSISTANT_TIME);
                 } else {
@@ -5238,7 +5251,7 @@
             Config c = new Config();
             c.caption = "notification assistant service";
             c.serviceInterface = NotificationAssistantService.SERVICE_INTERFACE;
-            c.managedServiceTypeTag = TAG_ENABLED_NOTIFICATION_ASSISTANTS;
+            c.xmlTag = TAG_ENABLED_NOTIFICATION_ASSISTANTS;
             c.secureSettingName = Settings.Secure.ENABLED_NOTIFICATION_ASSISTANT;
             c.bindPermission = Manifest.permission.BIND_NOTIFICATION_ASSISTANT_SERVICE;
             c.settingsAction = Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS;
@@ -5350,7 +5363,7 @@
             Config c = new Config();
             c.caption = "notification listener";
             c.serviceInterface = NotificationListenerService.SERVICE_INTERFACE;
-            c.managedServiceTypeTag = TAG_ENABLED_NOTIFICATION_LISTENERS;
+            c.xmlTag = TAG_ENABLED_NOTIFICATION_LISTENERS;
             c.secureSettingName = Settings.Secure.ENABLED_NOTIFICATION_LISTENERS;
             c.bindPermission = android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE;
             c.settingsAction = Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS;
diff --git a/services/core/java/com/android/server/notification/RankingHelper.java b/services/core/java/com/android/server/notification/RankingHelper.java
index 5c2c2b3..8265b65 100644
--- a/services/core/java/com/android/server/notification/RankingHelper.java
+++ b/services/core/java/com/android/server/notification/RankingHelper.java
@@ -20,6 +20,7 @@
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto;
 import com.android.internal.util.Preconditions;
+import com.android.internal.util.XmlUtils;
 
 import android.app.Notification;
 import android.app.NotificationChannel;
@@ -64,7 +65,7 @@
 
     private static final int XML_VERSION = 1;
 
-    private static final String TAG_RANKING = "ranking";
+    static final String TAG_RANKING = "ranking";
     private static final String TAG_PACKAGE = "package";
     private static final String TAG_CHANNEL = "channel";
     private static final String TAG_GROUP = "channelGroup";
@@ -169,7 +170,7 @@
             }
             if (type == XmlPullParser.START_TAG) {
                 if (TAG_PACKAGE.equals(tag)) {
-                    int uid = XmlUtils.safeInt(parser, ATT_UID, Record.UNKNOWN_UID);
+                    int uid = XmlUtils.readIntAttribute(parser, ATT_UID, Record.UNKNOWN_UID);
                     String name = parser.getAttributeValue(null, ATT_NAME);
                     if (!TextUtils.isEmpty(name)) {
                         if (forRestore) {
@@ -182,14 +183,21 @@
                         }
 
                         Record r = getOrCreateRecord(name, uid,
-                                XmlUtils.safeInt(parser, ATT_IMPORTANCE, DEFAULT_IMPORTANCE),
-                                XmlUtils.safeInt(parser, ATT_PRIORITY, DEFAULT_PRIORITY),
-                                XmlUtils.safeInt(parser, ATT_VISIBILITY, DEFAULT_VISIBILITY),
-                                XmlUtils.safeBool(parser, ATT_SHOW_BADGE, DEFAULT_SHOW_BADGE));
-                        r.importance = XmlUtils.safeInt(parser, ATT_IMPORTANCE, DEFAULT_IMPORTANCE);
-                        r.priority = XmlUtils.safeInt(parser, ATT_PRIORITY, DEFAULT_PRIORITY);
-                        r.visibility = XmlUtils.safeInt(parser, ATT_VISIBILITY, DEFAULT_VISIBILITY);
-                        r.showBadge = XmlUtils.safeBool(parser, ATT_SHOW_BADGE, DEFAULT_SHOW_BADGE);
+                                XmlUtils.readIntAttribute(
+                                        parser, ATT_IMPORTANCE, DEFAULT_IMPORTANCE),
+                                XmlUtils.readIntAttribute(parser, ATT_PRIORITY, DEFAULT_PRIORITY),
+                                XmlUtils.readIntAttribute(
+                                        parser, ATT_VISIBILITY, DEFAULT_VISIBILITY),
+                                XmlUtils.readBooleanAttribute(
+                                        parser, ATT_SHOW_BADGE, DEFAULT_SHOW_BADGE));
+                        r.importance = XmlUtils.readIntAttribute(
+                                parser, ATT_IMPORTANCE, DEFAULT_IMPORTANCE);
+                        r.priority = XmlUtils.readIntAttribute(
+                                parser, ATT_PRIORITY, DEFAULT_PRIORITY);
+                        r.visibility = XmlUtils.readIntAttribute(
+                                parser, ATT_VISIBILITY, DEFAULT_VISIBILITY);
+                        r.showBadge = XmlUtils.readBooleanAttribute(
+                                parser, ATT_SHOW_BADGE, DEFAULT_SHOW_BADGE);
 
                         final int innerDepth = parser.getDepth();
                         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
@@ -214,7 +222,7 @@
                             if (TAG_CHANNEL.equals(tagName)) {
                                 String id = parser.getAttributeValue(null, ATT_ID);
                                 String channelName = parser.getAttributeValue(null, ATT_NAME);
-                                int channelImportance = XmlUtils.safeInt(
+                                int channelImportance = XmlUtils.readIntAttribute(
                                         parser, ATT_IMPORTANCE, DEFAULT_IMPORTANCE);
                                 if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(channelName)) {
                                     NotificationChannel channel = new NotificationChannel(id,
diff --git a/services/core/java/com/android/server/notification/XmlUtils.java b/services/core/java/com/android/server/notification/XmlUtils.java
deleted file mode 100644
index 831d039..0000000
--- a/services/core/java/com/android/server/notification/XmlUtils.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Copyright (c) 2017, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.notification;
-
-import android.annotation.NonNull;
-import android.text.TextUtils;
-
-import org.xmlpull.v1.XmlPullParser;
-
-class XmlUtils {
-
-    static @NonNull String safeString(XmlPullParser parser, String att, String defValue) {
-        final String value = parser.getAttributeValue(null, att);
-        if (value == null) return defValue;
-        return value;
-    }
-
-    static @NonNull boolean safeBool(XmlPullParser parser, String att, boolean defValue) {
-        final String value = parser.getAttributeValue(null, att);
-        if (TextUtils.isEmpty(value)) return defValue;
-        return Boolean.parseBoolean(value);
-    }
-
-    static @NonNull int safeInt(XmlPullParser parser, String att, int defValue) {
-        final String val = parser.getAttributeValue(null, att);
-        return tryParseInt(val, defValue);
-    }
-
-    private static int tryParseInt(String value, int defValue) {
-        if (TextUtils.isEmpty(value)) return defValue;
-        try {
-            return Integer.parseInt(value);
-        } catch (NumberFormatException e) {
-            return defValue;
-        }
-    }
-
-}
diff --git a/services/core/java/com/android/server/pm/BackgroundDexOptService.java b/services/core/java/com/android/server/pm/BackgroundDexOptService.java
index 0f28647..415c9a9 100644
--- a/services/core/java/com/android/server/pm/BackgroundDexOptService.java
+++ b/services/core/java/com/android/server/pm/BackgroundDexOptService.java
@@ -37,6 +37,7 @@
 import com.android.server.pm.dex.DexManager;
 import com.android.server.LocalServices;
 import com.android.server.PinnerService;
+import com.android.server.pm.dex.DexoptOptions;
 
 import java.io.File;
 import java.util.Set;
@@ -221,12 +222,10 @@
             // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
             // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
             // trade-off worth doing to save boot time work.
-            int result = pm.performDexOptWithStatus(pkg,
-                    /* checkProfiles */ false,
+            int result = pm.performDexOptWithStatus(new DexoptOptions(
+                    pkg,
                     PackageManagerService.REASON_BOOT,
-                    /* force */ false,
-                    /* bootComplete */ true,
-                    /* downgrade */ false);
+                    DexoptOptions.DEXOPT_BOOT_COMPLETE));
             if (result == PackageDexOptimizer.DEX_OPT_PERFORMED)  {
                 updatedPackages.add(pkg);
             }
@@ -338,22 +337,22 @@
             // Optimize package if needed. Note that there can be no race between
             // concurrent jobs because PackageDexOptimizer.performDexOpt is synchronized.
             boolean success;
+            int dexoptFlags =
+                    DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
+                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
+                    (downgrade ? DexoptOptions.DEXOPT_DOWNGRADE : 0);
             if (is_for_primary_dex) {
-                int result = pm.performDexOptWithStatus(pkg,
-                        /* checkProfiles */ true,
-                        reason,
-                        false /* forceCompile*/,
-                        true /* bootComplete */,
-                        downgrade);
+                int result = pm.performDexOptWithStatus(new DexoptOptions(pkg,
+                        PackageManagerService.REASON_BACKGROUND_DEXOPT,
+                        dexoptFlags));
                 success = result != PackageDexOptimizer.DEX_OPT_FAILED;
                 if (result == PackageDexOptimizer.DEX_OPT_PERFORMED) {
                     updatedPackages.add(pkg);
                 }
             } else {
-                success = pm.performDexOptSecondary(pkg,
-                        reason,
-                        false /* force */,
-                        downgrade);
+                success = pm.performDexOpt(new DexoptOptions(pkg,
+                        PackageManagerService.REASON_BACKGROUND_DEXOPT,
+                        dexoptFlags | DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX));
             }
             if (success) {
                 // Dexopt succeeded, remove package from the list of failing ones.
diff --git a/services/core/java/com/android/server/pm/OtaDexoptService.java b/services/core/java/com/android/server/pm/OtaDexoptService.java
index 4ff6cbf..241d76f 100644
--- a/services/core/java/com/android/server/pm/OtaDexoptService.java
+++ b/services/core/java/com/android/server/pm/OtaDexoptService.java
@@ -18,7 +18,6 @@
 
 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
-import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
 
 import android.annotation.Nullable;
 import android.content.Context;
@@ -35,6 +34,7 @@
 
 import com.android.internal.logging.MetricsLogger;
 import com.android.server.pm.Installer.InstallerException;
+import com.android.server.pm.dex.DexoptOptions;
 
 import java.io.File;
 import java.io.FileDescriptor;
@@ -314,19 +314,19 @@
             libraryDependencies = NO_LIBRARIES;
         }
 
+
         optimizer.performDexOpt(pkg, libraryDependencies,
-                null /* ISAs */, false /* checkProfiles */,
-                getCompilerFilterForReason(compilationReason),
+                null /* ISAs */,
                 null /* CompilerStats.PackageStats */,
                 mPackageManagerService.getDexManager().isUsedByOtherApps(pkg.packageName),
-                true /* bootComplete */,
-                false /* downgrade */);
+                new DexoptOptions(pkg.packageName, compilationReason,
+                        DexoptOptions.DEXOPT_BOOT_COMPLETE));
 
-        mPackageManagerService.getDexManager().dexoptSecondaryDex(pkg.packageName,
-                getCompilerFilterForReason(compilationReason),
-                false /* force */,
-                false /* compileOnlySharedDex */,
-                false /* downgrade */);
+        mPackageManagerService.getDexManager().dexoptSecondaryDex(
+                new DexoptOptions(pkg.packageName, compilationReason,
+                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
+                        DexoptOptions.DEXOPT_BOOT_COMPLETE));
+
         return commands;
     }
 
diff --git a/services/core/java/com/android/server/pm/PackageDexOptimizer.java b/services/core/java/com/android/server/pm/PackageDexOptimizer.java
index 3eaeb6d..41bc7f2 100644
--- a/services/core/java/com/android/server/pm/PackageDexOptimizer.java
+++ b/services/core/java/com/android/server/pm/PackageDexOptimizer.java
@@ -19,9 +19,7 @@
 import android.annotation.Nullable;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
 import android.content.pm.PackageParser;
-import android.os.Environment;
 import android.os.FileUtils;
 import android.os.PowerManager;
 import android.os.SystemClock;
@@ -29,11 +27,12 @@
 import android.os.WorkSource;
 import android.util.Log;
 import android.util.Slog;
-import android.util.SparseArray;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.util.IndentingPrintWriter;
 import com.android.server.pm.Installer.InstallerException;
+import com.android.server.pm.dex.DexoptOptions;
+import com.android.server.pm.dex.DexoptUtils;
 
 import java.io.File;
 import java.io.IOException;
@@ -112,18 +111,16 @@
      * synchronized on {@link #mInstallLock}.
      */
     int performDexOpt(PackageParser.Package pkg, String[] sharedLibraries,
-            String[] instructionSets, boolean checkProfiles, String targetCompilationFilter,
-            CompilerStats.PackageStats packageStats, boolean isUsedByOtherApps,
-            boolean bootComplete, boolean downgrade) {
+            String[] instructionSets, CompilerStats.PackageStats packageStats,
+            boolean isUsedByOtherApps, DexoptOptions options) {
         if (!canOptimizePackage(pkg)) {
             return DEX_OPT_SKIPPED;
         }
         synchronized (mInstallLock) {
             final long acquireTime = acquireWakeLockLI(pkg.applicationInfo.uid);
             try {
-                return performDexOptLI(pkg, sharedLibraries, instructionSets, checkProfiles,
-                        targetCompilationFilter, packageStats, isUsedByOtherApps, bootComplete,
-                        downgrade);
+                return performDexOptLI(pkg, sharedLibraries, instructionSets,
+                        packageStats, isUsedByOtherApps, options);
             } finally {
                 releaseWakeLockLI(acquireTime);
             }
@@ -136,9 +133,8 @@
      */
     @GuardedBy("mInstallLock")
     private int performDexOptLI(PackageParser.Package pkg, String[] sharedLibraries,
-            String[] targetInstructionSets, boolean checkForProfileUpdates,
-            String targetCompilerFilter, CompilerStats.PackageStats packageStats,
-            boolean isUsedByOtherApps, boolean bootComplete, boolean downgrade) {
+            String[] targetInstructionSets, CompilerStats.PackageStats packageStats,
+            boolean isUsedByOtherApps, DexoptOptions options) {
         final String[] instructionSets = targetInstructionSets != null ?
                 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
         final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
@@ -146,16 +142,18 @@
         final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
 
         final String compilerFilter = getRealCompilerFilter(pkg.applicationInfo,
-                targetCompilerFilter, isUsedByOtherApps);
-        final boolean profileUpdated = checkForProfileUpdates &&
+                options.getCompilerFilter(), isUsedByOtherApps);
+        final boolean profileUpdated = options.isCheckForProfileUpdates() &&
                 isProfileUpdated(pkg, sharedGid, compilerFilter);
 
-        final String sharedLibrariesPath = getSharedLibrariesPath(sharedLibraries);
         // Get the dexopt flags after getRealCompilerFilter to make sure we get the correct flags.
-        final int dexoptFlags = getDexFlags(pkg, compilerFilter, bootComplete);
-        // Get the dependencies of each split in the package. For each code path in the package,
-        // this array contains the relative paths of each split it depends on, separated by colons.
-        String[] splitDependencies = getSplitDependencies(pkg);
+        final int dexoptFlags = getDexFlags(pkg, compilerFilter, options.isBootComplete());
+
+        // Get the class loader context dependencies.
+        // For each code path in the package, this array contains the class loader context that
+        // needs to be passed to dexopt in order to ensure correct optimizations.
+        String[] classLoaderContexts = DexoptUtils.getClassLoaderContexts(
+                pkg.applicationInfo, sharedLibraries);
 
         int result = DEX_OPT_SKIPPED;
         for (int i = 0; i < paths.size(); i++) {
@@ -166,17 +164,18 @@
             }
             // Append shared libraries with split dependencies for this split.
             String path = paths.get(i);
-            String sharedLibrariesPathWithSplits;
-            if (sharedLibrariesPath != null && splitDependencies[i] != null) {
-                sharedLibrariesPathWithSplits = sharedLibrariesPath + ":" + splitDependencies[i];
-            } else {
-                sharedLibrariesPathWithSplits =
-                        splitDependencies[i] != null ? splitDependencies[i] : sharedLibrariesPath;
+            if (options.getSplitName() != null) {
+                // We are asked to compile only a specific split. Check that the current path is
+                // what we are looking for.
+                if (!options.getSplitName().equals(new File(path).getName())) {
+                    continue;
+                }
             }
+
             for (String dexCodeIsa : dexCodeInstructionSets) {
-                int newResult = dexOptPath(pkg, path, dexCodeIsa, compilerFilter, profileUpdated,
-                        sharedLibrariesPathWithSplits, dexoptFlags, sharedGid, packageStats,
-                        downgrade);
+                int newResult = dexOptPath(pkg, path, dexCodeIsa, compilerFilter,
+                        profileUpdated, classLoaderContexts[i], dexoptFlags, sharedGid,
+                        packageStats, options.isDowngrade());
                 // The end result is:
                 //  - FAILED if any path failed,
                 //  - PERFORMED if at least one path needed compilation,
@@ -445,86 +444,6 @@
     }
 
     /**
-     * Computes the shared libraries path that should be passed to dexopt.
-     */
-    private String getSharedLibrariesPath(String[] sharedLibraries) {
-        if (sharedLibraries == null || sharedLibraries.length == 0) {
-            return null;
-        }
-        StringBuilder sb = new StringBuilder();
-        for (String lib : sharedLibraries) {
-            if (sb.length() != 0) {
-                sb.append(":");
-            }
-            sb.append(lib);
-        }
-        return sb.toString();
-    }
-
-    /**
-     * Walks dependency tree and gathers the dependencies for each split in a split apk.
-     * The split paths are stored as relative paths, separated by colons.
-     */
-    private String[] getSplitDependencies(PackageParser.Package pkg) {
-        // Convert all the code paths to relative paths.
-        String baseCodePath = new File(pkg.baseCodePath).getParent();
-        List<String> paths = pkg.getAllCodePaths();
-        String[] splitDependencies = new String[paths.size()];
-        for (int i = 0; i < paths.size(); i++) {
-            File pathFile = new File(paths.get(i));
-            String fileName = pathFile.getName();
-            paths.set(i, fileName);
-
-            // Sanity check that the base paths of the splits are all the same.
-            String basePath = pathFile.getParent();
-            if (!basePath.equals(baseCodePath)) {
-                Slog.wtf(TAG, "Split paths have different base paths: " + basePath + " and " +
-                        baseCodePath);
-            }
-        }
-
-        // If there are no other dependencies, fill in the implicit dependency on the base apk.
-        SparseArray<int[]> dependencies = pkg.applicationInfo.splitDependencies;
-        if (dependencies == null) {
-            for (int i = 1; i < paths.size(); i++) {
-                splitDependencies[i] = paths.get(0);
-            }
-            return splitDependencies;
-        }
-
-        // Fill in the dependencies, skipping the base apk which has no dependencies.
-        for (int i = 1; i < dependencies.size(); i++) {
-            getParentDependencies(dependencies.keyAt(i), paths, dependencies, splitDependencies);
-        }
-
-        return splitDependencies;
-    }
-
-    /**
-     * Recursive method to generate dependencies for a particular split.
-     * The index is a key from the package's splitDependencies.
-     */
-    private String getParentDependencies(int index, List<String> paths,
-            SparseArray<int[]> dependencies, String[] splitDependencies) {
-        // The base apk is always first, and has no dependencies.
-        if (index == 0) {
-            return null;
-        }
-        // Return the result if we've computed the dependencies for this index already.
-        if (splitDependencies[index] != null) {
-            return splitDependencies[index];
-        }
-        // Get the dependencies for the parent of this index and append its path to it.
-        int parent = dependencies.get(index)[0];
-        String parentDependencies =
-                getParentDependencies(parent, paths, dependencies, splitDependencies);
-        String path = parentDependencies == null ? paths.get(parent) :
-                parentDependencies + ":" + paths.get(parent);
-        splitDependencies[index] = path;
-        return path;
-    }
-
-    /**
      * Checks if there is an update on the profile information of the {@code pkg}.
      * If the compiler filter is not profile guided the method returns false.
      *
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 32983ec..98b6949 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -283,6 +283,7 @@
 import com.android.server.pm.Settings.DatabaseVersion;
 import com.android.server.pm.Settings.VersionInfo;
 import com.android.server.pm.dex.DexManager;
+import com.android.server.pm.dex.DexoptOptions;
 import com.android.server.pm.dex.PackageDexUsage;
 import com.android.server.storage.DeviceStorageMonitorInternal;
 
@@ -9371,21 +9372,22 @@
             // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
             // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
             // trade-off worth doing to save boot time work.
-            int primaryDexOptStaus = performDexOptTraced(pkg.packageName,
-                    false /* checkProfiles */,
+            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
+            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
+                    pkg.packageName,
                     compilerFilter,
-                    false /* force */,
-                    bootComplete,
-                    false /* downgrade */);
+                    dexoptFlags));
 
             if (pkg.isSystemApp()) {
                 // Only dexopt shared secondary dex files belonging to system apps to not slow down
                 // too much boot after an OTA.
-                mDexManager.dexoptSecondaryDex(pkg.packageName,
+                int secondaryDexoptFlags = dexoptFlags |
+                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
+                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
+                mDexManager.dexoptSecondaryDex(new DexoptOptions(
+                        pkg.packageName,
                         compilerFilter,
-                        false /* force */,
-                        true /* compileOnlySharedDex */,
-                        false /* downgrade */);
+                        secondaryDexoptFlags));
             }
 
             // TODO(shubhamajmera): Record secondary dexopt stats.
@@ -9468,19 +9470,53 @@
         }
     }
 
+    /**
+     * Ask the package manager to perform a dex-opt with the given compiler filter.
+     *
+     * Note: exposed only for the shell command to allow moving packages explicitly to a
+     *       definite state.
+     */
     @Override
-    public boolean performDexOpt(String packageName,
-            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete,
-            boolean downgrade) {
+    public boolean performDexOptMode(String packageName,
+            boolean checkProfiles, String targetCompilerFilter, boolean force,
+            boolean bootComplete, String splitName) {
+        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
+                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
+                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
+        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
+                splitName, flags));
+    }
+
+    /**
+     * Ask the package manager to perform a dex-opt with the given compiler filter on the
+     * secondary dex files belonging to the given package.
+     *
+     * Note: exposed only for the shell command to allow moving packages explicitly to a
+     *       definite state.
+     */
+    @Override
+    public boolean performDexOptSecondary(String packageName, String compilerFilter,
+            boolean force) {
+        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
+                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
+                DexoptOptions.DEXOPT_BOOT_COMPLETE |
+                (force ? DexoptOptions.DEXOPT_FORCE : 0);
+        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
+    }
+
+    /*package*/ boolean performDexOpt(DexoptOptions options) {
         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
             return false;
-        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
+        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
             return false;
         }
-        int dexoptStatus = performDexOptWithStatus(
-              packageName, checkProfiles, compileReason, force, bootComplete,
-              downgrade);
-        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
+
+        if (options.isDexoptOnlySecondaryDex()) {
+            return mDexManager.dexoptSecondaryDex(options);
+        } else {
+            int dexoptStatus = performDexOptWithStatus(options);
+            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
+        }
     }
 
     /**
@@ -9489,34 +9525,14 @@
      *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
      *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
      */
-    /* package */ int performDexOptWithStatus(String packageName,
-            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete,
-            boolean downgrade) {
-        return performDexOptTraced(packageName, checkProfiles,
-                getCompilerFilterForReason(compileReason), force, bootComplete, downgrade);
+    /* package */ int performDexOptWithStatus(DexoptOptions options) {
+        return performDexOptTraced(options);
     }
 
-    @Override
-    public boolean performDexOptMode(String packageName,
-            boolean checkProfiles, String targetCompilerFilter, boolean force,
-            boolean bootComplete) {
-        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
-            return false;
-        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
-            return false;
-        }
-        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
-                targetCompilerFilter, force, bootComplete, false /* downgrade */);
-        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
-    }
-
-    private int performDexOptTraced(String packageName,
-                boolean checkProfiles, String targetCompilerFilter, boolean force,
-                boolean bootComplete, boolean downgrade) {
+    private int performDexOptTraced(DexoptOptions options) {
         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
         try {
-            return performDexOptInternal(packageName, checkProfiles,
-                    targetCompilerFilter, force, bootComplete, downgrade);
+            return performDexOptInternal(options);
         } finally {
             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
         }
@@ -9524,12 +9540,10 @@
 
     // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
     // if the package can now be considered up to date for the given filter.
-    private int performDexOptInternal(String packageName,
-                boolean checkProfiles, String targetCompilerFilter, boolean force,
-                boolean bootComplete, boolean downgrade) {
+    private int performDexOptInternal(DexoptOptions options) {
         PackageParser.Package p;
         synchronized (mPackages) {
-            p = mPackages.get(packageName);
+            p = mPackages.get(options.getPackageName());
             if (p == null) {
                 // Package could not be found. Report failure.
                 return PackageDexOptimizer.DEX_OPT_FAILED;
@@ -9540,8 +9554,7 @@
         long callingId = Binder.clearCallingIdentity();
         try {
             synchronized (mInstallLock) {
-                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
-                        targetCompilerFilter, force, bootComplete, downgrade);
+                return performDexOptInternalWithDependenciesLI(p, options);
             }
         } finally {
             Binder.restoreCallingIdentity(callingId);
@@ -9561,12 +9574,11 @@
     }
 
     private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
-            boolean checkProfiles, String targetCompilerFilter,
-            boolean force, boolean bootComplete, boolean downgrade) {
+            DexoptOptions options) {
         // Select the dex optimizer based on the force parameter.
         // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
         //       allocate an object here.
-        PackageDexOptimizer pdo = force
+        PackageDexOptimizer pdo = options.isForce()
                 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
                 : mPackageDexOptimizer;
 
@@ -9583,37 +9595,14 @@
             for (PackageParser.Package depPackage : deps) {
                 // TODO: Analyze and investigate if we (should) profile libraries.
                 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
-                        false /* checkProfiles */,
-                        targetCompilerFilter,
                         getOrCreateCompilerPackageStats(depPackage),
                         true /* isUsedByOtherApps */,
-                        bootComplete,
-                        downgrade);
+                        options);
             }
         }
-        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
-                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
-                mDexManager.isUsedByOtherApps(p.packageName), bootComplete, downgrade);
-    }
-
-    // Performs dexopt on the used secondary dex files belonging to the given package.
-    // Returns true if all dex files were process successfully (which could mean either dexopt or
-    // skip). Returns false if any of the files caused errors.
-    @Override
-    public boolean performDexOptSecondary(String packageName, String compilerFilter,
-            boolean force) {
-        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
-            return false;
-        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
-            return false;
-        }
-        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force,
-                false /* compileOnlySharedDex */, false /* downgrade */);
-    }
-
-    public boolean performDexOptSecondary(String packageName, int compileReason,
-            boolean force, boolean downgrade) {
-        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force, downgrade);
+        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
+                getOrCreateCompilerPackageStats(p),
+                mDexManager.isUsedByOtherApps(p.packageName), options);
     }
 
     /**
@@ -9789,11 +9778,11 @@
 
             // Whoever is calling forceDexOpt wants a compiled package.
             // Don't use profiles since that may cause compilation to be skipped.
-            final int res = performDexOptInternalWithDependenciesLI(pkg,
-                    false /* checkProfiles */, getDefaultCompilerFilter(),
-                    true /* force */,
-                    true /* bootComplete */,
-                    false /* downgrade */);
+            final int res = performDexOptInternalWithDependenciesLI(
+                    pkg,
+                    new DexoptOptions(packageName,
+                            getDefaultCompilerFilter(),
+                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
 
             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
             if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
@@ -18255,13 +18244,14 @@
                 // method because `pkg` may not be in `mPackages` yet.
                 //
                 // Also, don't fail application installs if the dexopt step fails.
+                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
+                        REASON_INSTALL,
+                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
                 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
-                        null /* instructionSets */, false /* checkProfiles */,
-                        getCompilerFilterForReason(REASON_INSTALL),
+                        null /* instructionSets */,
                         getOrCreateCompilerPackageStats(pkg),
                         mDexManager.isUsedByOtherApps(pkg.packageName),
-                        true /* bootComplete */,
-                        false /* downgrade */);
+                        dexoptOptions);
                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
             }
 
diff --git a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
index 9765113..6d6611f 100644
--- a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
+++ b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
@@ -365,6 +365,7 @@
         String compilationReason = null;
         String checkProfilesRaw = null;
         boolean secondaryDex = false;
+        String split = null;
 
         String opt;
         while ((opt = getNextOption()) != null) {
@@ -395,6 +396,9 @@
                 case "--secondary-dex":
                     secondaryDex = true;
                     break;
+                case "--split":
+                    split = getNextArgRequired();
+                    break;
                 default:
                     pw.println("Error: Unknown option: " + opt);
                     return 1;
@@ -423,6 +427,16 @@
             return 1;
         }
 
+        if (allPackages && split != null) {
+            pw.println("-a cannot be specified together with --split");
+            return 1;
+        }
+
+        if (secondaryDex && split != null) {
+            pw.println("--secondary-dex cannot be specified together with --split");
+            return 1;
+        }
+
         String targetCompilerFilter;
         if (compilerFilter != null) {
             if (!DexFile.isValidCompilerFilter(compilerFilter)) {
@@ -472,7 +486,7 @@
                             targetCompilerFilter, forceCompilation)
                     : mInterface.performDexOptMode(packageName,
                             checkProfiles, targetCompilerFilter, forceCompilation,
-                            true /* bootComplete */);
+                            true /* bootComplete */, split);
             if (!result) {
                 failedPackages.add(packageName);
             }
@@ -1609,7 +1623,7 @@
         pw.println("  help");
         pw.println("    Print this help text.");
         pw.println("");
-        pw.println("  compile [-m MODE | -r REASON] [-f] [-c]");
+        pw.println("  compile [-m MODE | -r REASON] [-f] [-c] [--split SPLIT_NAME]");
         pw.println("          [--reset] [--check-prof (true | false)] (-a | TARGET-PACKAGE)");
         pw.println("    Trigger compilation of TARGET-PACKAGE or all packages if \"-a\".");
         pw.println("    Options:");
@@ -1635,6 +1649,7 @@
         pw.println("      --reset: restore package to its post-install state");
         pw.println("      --check-prof (true | false): look at profiles when doing dexopt?");
         pw.println("      --secondary-dex: compile app secondary dex files");
+        pw.println("      --split SPLIT: compile only the given split name");
         pw.println("  bg-dexopt-job");
         pw.println("    Execute the background optimizations immediately.");
         pw.println("    Note that the command only runs the background optimizer logic. It may");
diff --git a/services/core/java/com/android/server/pm/dex/DexManager.java b/services/core/java/com/android/server/pm/dex/DexManager.java
index 22de010..3d2d483 100644
--- a/services/core/java/com/android/server/pm/dex/DexManager.java
+++ b/services/core/java/com/android/server/pm/dex/DexManager.java
@@ -301,33 +301,21 @@
     }
 
     /**
-     * Perform dexopt on the package {@code packageName} secondary dex files.
+     * Perform dexopt on with the given {@code options} on the secondary dex files.
      * @return true if all secondary dex files were processed successfully (compiled or skipped
      *         because they don't need to be compiled)..
      */
-    public boolean dexoptSecondaryDex(String packageName, int compilerReason, boolean force,
-            boolean downgrade) {
-        return dexoptSecondaryDex(packageName,
-                PackageManagerServiceCompilerMapping.getCompilerFilterForReason(compilerReason),
-                force, /* compileOnlySharedDex */ false, downgrade);
-    }
-
-    /**
-     * Perform dexopt on the package {@code packageName} secondary dex files.
-     * @return true if all secondary dex files were processed successfully (compiled or skipped
-     *         because they don't need to be compiled)..
-     */
-    public boolean dexoptSecondaryDex(String packageName, String compilerFilter, boolean force,
-            boolean compileOnlySharedDex, boolean downgrade) {
+    public boolean dexoptSecondaryDex(DexoptOptions options) {
         // Select the dex optimizer based on the force parameter.
         // Forced compilation is done through ForcedUpdatePackageDexOptimizer which will adjust
         // the necessary dexopt flags to make sure that compilation is not skipped. This avoid
         // passing the force flag through the multitude of layers.
         // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
         //       allocate an object here.
-        PackageDexOptimizer pdo = force
+        PackageDexOptimizer pdo = options.isForce()
                 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
                 : mPackageDexOptimizer;
+        String packageName = options.getPackageName();
         PackageUseInfo useInfo = getPackageUseInfo(packageName);
         if (useInfo == null || useInfo.getDexUseInfoMap().isEmpty()) {
             if (DEBUG) {
@@ -340,7 +328,7 @@
         for (Map.Entry<String, DexUseInfo> entry : useInfo.getDexUseInfoMap().entrySet()) {
             String dexPath = entry.getKey();
             DexUseInfo dexUseInfo = entry.getValue();
-            if (compileOnlySharedDex && !dexUseInfo.isUsedByOtherApps()) {
+            if (options.isDexoptOnlySharedDex() && !dexUseInfo.isUsedByOtherApps()) {
                 continue;
             }
             PackageInfo pkg = null;
@@ -362,8 +350,8 @@
             }
 
             int result = pdo.dexOptSecondaryDexPath(pkg.applicationInfo, dexPath,
-                    dexUseInfo.getLoaderIsas(), compilerFilter, dexUseInfo.isUsedByOtherApps(),
-                    downgrade);
+                    dexUseInfo.getLoaderIsas(), options.getCompilerFilter(),
+                    dexUseInfo.isUsedByOtherApps(), options.isDowngrade());
             success = success && (result != PackageDexOptimizer.DEX_OPT_FAILED);
         }
         return success;
diff --git a/services/core/java/com/android/server/pm/dex/DexoptOptions.java b/services/core/java/com/android/server/pm/dex/DexoptOptions.java
new file mode 100644
index 0000000..f57cf5e
--- /dev/null
+++ b/services/core/java/com/android/server/pm/dex/DexoptOptions.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.server.pm.dex;
+
+import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
+
+import android.annotation.Nullable;
+
+/**
+ * Options used for dexopt invocations.
+ */
+public final class DexoptOptions {
+    // When set, the profiles will be checked for updates before calling dexopt. If
+    // the apps profiles didn't update in a meaningful way (decided by the compiler), dexopt
+    // will be skipped.
+    // Currently this only affects the optimization of primary apks. Secondary dex files
+    // will always check the profiles for updates.
+    public static final int DEXOPT_CHECK_FOR_PROFILES_UPDATES = 1 << 0;
+
+    // When set, dexopt will execute unconditionally (even if not needed).
+    public static final int DEXOPT_FORCE = 1 << 1;
+
+    // Whether or not the invocation of dexopt is done after the boot is completed. This is used
+    // in order to adjust the priority of the compilation thread.
+    public static final int DEXOPT_BOOT_COMPLETE = 1 << 2;
+
+    // When set, the dexopt invocation will optimize only the secondary dex files. If false, dexopt
+    // will only consider the primary apk.
+    public static final int DEXOPT_ONLY_SECONDARY_DEX = 1 << 3;
+
+    // When set, dexopt will optimize only dex files that are used by other apps.
+    // Currently, this flag is ignored for primary apks.
+    public static final int DEXOPT_ONLY_SHARED_DEX = 1 << 4;
+
+    // When set, dexopt will attempt to scale down the optimizations previously applied in order
+    // save disk space.
+    public static final int DEXOPT_DOWNGRADE = 1 << 5;
+
+    // The name of package to optimize.
+    private final String mPackageName;
+
+    // The intended target compiler filter. Note that dexopt might adjust the filter before the
+    // execution based on factors like: vmSafeMode and packageUsedByOtherApps.
+    private final String mCompilerFilter;
+
+    // The set of flags for the dexopt options. It's a mix of the DEXOPT_* flags.
+    private final int mFlags;
+
+    // When not null, dexopt will optimize only the split identified by this name.
+    // It only applies for primary apk and it's always null if mOnlySecondaryDex is true.
+    private final String mSplitName;
+
+    public DexoptOptions(String packageName, String compilerFilter, int flags) {
+        this(packageName, compilerFilter, /*splitName*/ null, flags);
+    }
+
+    public DexoptOptions(String packageName, int compilerReason, int flags) {
+        this(packageName, getCompilerFilterForReason(compilerReason), flags);
+    }
+
+    public DexoptOptions(String packageName, String compilerFilter, String splitName, int flags) {
+        int validityMask =
+                DEXOPT_CHECK_FOR_PROFILES_UPDATES |
+                DEXOPT_FORCE |
+                DEXOPT_BOOT_COMPLETE |
+                DEXOPT_ONLY_SECONDARY_DEX |
+                DEXOPT_ONLY_SHARED_DEX |
+                DEXOPT_DOWNGRADE;
+        if ((flags & (~validityMask)) != 0) {
+            throw new IllegalArgumentException("Invalid flags : " + Integer.toHexString(flags));
+        }
+
+        mPackageName = packageName;
+        mCompilerFilter = compilerFilter;
+        mFlags = flags;
+        mSplitName = splitName;
+    }
+
+    public String getPackageName() {
+        return mPackageName;
+    }
+
+    public boolean isCheckForProfileUpdates() {
+        return (mFlags & DEXOPT_CHECK_FOR_PROFILES_UPDATES) != 0;
+    }
+
+    public String getCompilerFilter() {
+        return mCompilerFilter;
+    }
+
+    public boolean isForce() {
+        return (mFlags & DEXOPT_FORCE) != 0;
+    }
+
+    public boolean isBootComplete() {
+        return (mFlags & DEXOPT_BOOT_COMPLETE) != 0;
+    }
+
+    public boolean isDexoptOnlySecondaryDex() {
+        return (mFlags & DEXOPT_ONLY_SECONDARY_DEX) != 0;
+    }
+
+    public boolean isDexoptOnlySharedDex() {
+        return (mFlags & DEXOPT_ONLY_SHARED_DEX) != 0;
+    }
+
+    public boolean isDowngrade() {
+        return (mFlags & DEXOPT_DOWNGRADE) != 0;
+    }
+
+    public String getSplitName() {
+        return mSplitName;
+    }
+}
diff --git a/services/core/java/com/android/server/pm/dex/DexoptUtils.java b/services/core/java/com/android/server/pm/dex/DexoptUtils.java
new file mode 100644
index 0000000..18e91df
--- /dev/null
+++ b/services/core/java/com/android/server/pm/dex/DexoptUtils.java
@@ -0,0 +1,255 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.server.pm.dex;
+
+import android.content.pm.ApplicationInfo;
+import android.util.Slog;
+import android.util.SparseArray;
+
+import com.android.internal.os.ClassLoaderFactory;
+
+import java.io.File;
+import java.util.List;
+
+public final class DexoptUtils {
+    private static final String TAG = "DexoptUtils";
+
+    private DexoptUtils() {}
+
+    /**
+     * Creates the class loader context dependencies for each of the application code paths.
+     * The returned array contains the class loader contexts that needs to be passed to dexopt in
+     * order to ensure correct optimizations.
+     *
+     * A class loader context describes how the class loader chain should be built by dex2oat
+     * in order to ensure that classes are resolved during compilation as they would be resolved
+     * at runtime. The context will be encoded in the compiled code. If at runtime the dex file is
+     * loaded in a different context (with a different set of class loaders or a different
+     * classpath), the compiled code will be rejected.
+     *
+     * Note that the class loader context only includes dependencies and not the code path itself.
+     * The contexts are created based on the application split dependency list and
+     * the provided shared libraries.
+     *
+     * All the code paths encoded in the context will be relative to the base directory. This
+     * enables stage compilation where compiler artifacts may be moved around.
+     *
+     * The result is indexed as follows:
+     *   - index 0 contains the context for the base apk
+     *   - index 1 to n contain the context for the splits in the order determined by
+     *     {@code info.getSplitCodePaths()}
+     *
+     * IMPORTANT: keep this logic in sync with the loading code in {@link android.app.LoadedApk}
+     * and pay attention to the way the classpath is created for the non isolated mode in:
+     * {@link android.app.LoadedApk#makePaths(
+     * android.app.ActivityThread, boolean, ApplicationInfo, List, List)}.
+     */
+    public static String[] getClassLoaderContexts(ApplicationInfo info, String[] sharedLibraries) {
+        // The base class loader context contains only the shared library.
+        String sharedLibrariesClassPath = encodeClasspath(sharedLibraries);
+        String baseApkContextClassLoader = encodeClassLoader(
+                sharedLibrariesClassPath, info.classLoaderName);
+
+        if (info.getSplitCodePaths() == null) {
+            // The application has no splits.
+            return new String[] {baseApkContextClassLoader};
+        }
+
+        // The application has splits. Compute their class loader contexts.
+
+        // First, cache the relative paths of the splits and do some sanity checks
+        String[] splitRelativeCodePaths = getSplitRelativeCodePaths(info);
+
+        // The splits have an implicit dependency on the base apk.
+        // This means that we have to add the base apk file in addition to the shared libraries.
+        String baseApkName = new File(info.getBaseCodePath()).getName();
+        String sharedLibrariesAndBaseClassPath =
+                encodeClasspath(sharedLibrariesClassPath, baseApkName);
+
+        // The result is stored in classLoaderContexts.
+        // Index 0 is the class loaded context for the base apk.
+        // Index `i` is the class loader context encoding for split `i`.
+        String[] classLoaderContexts = new String[/*base apk*/ 1 + splitRelativeCodePaths.length];
+        classLoaderContexts[0] = baseApkContextClassLoader;
+
+        if (!info.requestsIsolatedSplitLoading() || info.splitDependencies == null) {
+            // If the app didn't request for the splits to be loaded in isolation or if it does not
+            // declare inter-split dependencies, then all the splits will be loaded in the base
+            // apk class loader (in the order of their definition).
+            String classpath = sharedLibrariesAndBaseClassPath;
+            for (int i = 1; i < classLoaderContexts.length; i++) {
+                classLoaderContexts[i] = encodeClassLoader(classpath, info.classLoaderName);
+                classpath = encodeClasspath(classpath, splitRelativeCodePaths[i - 1]);
+            }
+        } else {
+            // In case of inter-split dependencies, we need to walk the dependency chain of each
+            // split. We do this recursively and store intermediate results in classLoaderContexts.
+
+            // First, look at the split class loaders and cache their individual contexts (i.e.
+            // the class loader + the name of the split). This is an optimization to avoid
+            // re-computing them during the recursive call.
+            // The cache is stored in splitClassLoaderEncodingCache. The difference between this and
+            // classLoaderContexts is that the later contains the full chain of class loaders for
+            // a given split while splitClassLoaderEncodingCache only contains a single class loader
+            // encoding.
+            String[] splitClassLoaderEncodingCache = new String[splitRelativeCodePaths.length];
+            for (int i = 0; i < splitRelativeCodePaths.length; i++) {
+                splitClassLoaderEncodingCache[i] = encodeClassLoader(splitRelativeCodePaths[i],
+                        info.splitClassLoaderNames[i]);
+            }
+            String splitDependencyOnBase = encodeClassLoader(
+                    sharedLibrariesAndBaseClassPath, info.classLoaderName);
+            SparseArray<int[]> splitDependencies = info.splitDependencies;
+            for (int i = 1; i < splitDependencies.size(); i++) {
+                getParentDependencies(splitDependencies.keyAt(i), splitClassLoaderEncodingCache,
+                        splitDependencies, classLoaderContexts, splitDependencyOnBase);
+            }
+
+            // At this point classLoaderContexts contains only the parent dependencies.
+            // We also need to add the class loader of the current split which should
+            // come first in the context.
+            for (int i = 1; i < classLoaderContexts.length; i++) {
+                String splitClassLoader = encodeClassLoader("", info.splitClassLoaderNames[i - 1]);
+                classLoaderContexts[i] = encodeClassLoaderChain(
+                        splitClassLoader, classLoaderContexts[i]);
+            }
+        }
+
+        return classLoaderContexts;
+    }
+
+    /**
+     * Recursive method to generate the class loader context dependencies for the split with the
+     * given index. {@param classLoaderContexts} acts as an accumulator. Upton return
+     * {@code classLoaderContexts[index]} will contain the split dependency.
+     * During computation, the method may resolve the dependencies of other splits as it traverses
+     * the entire parent chain. The result will also be stored in {@param classLoaderContexts}.
+     *
+     * Note that {@code index 0} denotes the base apk and it is special handled. When the
+     * recursive call hits {@code index 0} the method returns {@code splitDependencyOnBase}.
+     * {@code classLoaderContexts[0]} is not modified in this method.
+     *
+     * @param index the index of the split (Note that index 0 denotes the base apk)
+     * @param splitClassLoaderEncodingCache the class loader encoding for the individual splits.
+     *    It contains only the split class loader and not the the base. The split
+     *    with {@code index} has its context at {@code splitClassLoaderEncodingCache[index - 1]}.
+     * @param splitDependencies the dependencies for all splits. Note that in this array index 0
+     *    is the base and splits start from index 1.
+     * @param classLoaderContexts the result accumulator. index 0 is the base and never set. Splits
+     *    start at index 1.
+     * @param splitDependencyOnBase the encoding of the implicit split dependency on base.
+     */
+    private static String getParentDependencies(int index, String[] splitClassLoaderEncodingCache,
+            SparseArray<int[]> splitDependencies, String[] classLoaderContexts,
+            String splitDependencyOnBase) {
+        // If we hit the base apk return its custom dependency list which is
+        // sharedLibraries + base.apk
+        if (index == 0) {
+            return splitDependencyOnBase;
+        }
+        // Return the result if we've computed the splitDependencies for this index already.
+        if (classLoaderContexts[index] != null) {
+            return classLoaderContexts[index];
+        }
+        // Get the splitDependencies for the parent of this index and append its path to it.
+        int parent = splitDependencies.get(index)[0];
+        String parentDependencies = getParentDependencies(parent, splitClassLoaderEncodingCache,
+                splitDependencies, classLoaderContexts, splitDependencyOnBase);
+
+        // The split context is: `parent context + parent dependencies context`.
+        String splitContext = (parent == 0) ?
+                parentDependencies :
+                encodeClassLoaderChain(splitClassLoaderEncodingCache[parent - 1], parentDependencies);
+        classLoaderContexts[index] = splitContext;
+        return splitContext;
+    }
+
+    /**
+     * Encodes the shared libraries classpathElements in a format accepted by dexopt.
+     * NOTE: Keep this in sync with the dexopt expectations! Right now that is
+     * a list separated by ':'.
+     */
+    private static String encodeClasspath(String[] classpathElements) {
+        if (classpathElements == null || classpathElements.length == 0) {
+            return "";
+        }
+        StringBuilder sb = new StringBuilder();
+        for (String element : classpathElements) {
+            if (sb.length() != 0) {
+                sb.append(":");
+            }
+            sb.append(element);
+        }
+        return sb.toString();
+    }
+
+    /**
+     * Adds an element to the encoding of an existing classpath.
+     * {@see PackageDexOptimizer.encodeClasspath(String[])}
+     */
+    private static String encodeClasspath(String classpath, String newElement) {
+        return classpath.isEmpty() ? newElement : (classpath + ":" + newElement);
+    }
+
+    /**
+     * Encodes a single class loader dependency starting from {@param path} and
+     * {@param classLoaderName}.
+     * NOTE: Keep this in sync with the dexopt expectations! Right now that is either "PCL[path]"
+     * for a PathClassLoader or "DLC[path]" for a DelegateLastClassLoader.
+     */
+    private static String encodeClassLoader(String classpath, String classLoaderName) {
+        String classLoaderDexoptEncoding = classLoaderName;
+        if (ClassLoaderFactory.isPathClassLoaderName(classLoaderName)) {
+            classLoaderDexoptEncoding = "PCL";
+        } else if (ClassLoaderFactory.isDelegateLastClassLoaderName(classLoaderName)) {
+            classLoaderDexoptEncoding = "DLC";
+        } else {
+            Slog.wtf(TAG, "Unsupported classLoaderName: " + classLoaderName);
+        }
+        return classLoaderDexoptEncoding + "[" + classpath + "]";
+    }
+
+    /**
+     * Links to dependencies together in a format accepted by dexopt.
+     * NOTE: Keep this in sync with the dexopt expectations! Right now that is a list of split
+     * dependencies {@see encodeClassLoader} separated by ';'.
+     */
+    private static String encodeClassLoaderChain(String cl1, String cl2) {
+        return cl1.isEmpty() ? cl2 : (cl1 + ";" + cl2);
+    }
+
+    /**
+     * Returns the relative paths of the splits declared by the application {@code info}.
+     * Assumes that the application declares a non-null array of splits.
+     */
+    private static String[] getSplitRelativeCodePaths(ApplicationInfo info) {
+        String baseCodePath = new File(info.getBaseCodePath()).getParent();
+        String[] splitCodePaths = info.getSplitCodePaths();
+        String[] splitRelativeCodePaths = new String[splitCodePaths.length];
+        for (int i = 0; i < splitCodePaths.length; i++) {
+            File pathFile = new File(splitCodePaths[i]);
+            splitRelativeCodePaths[i] = pathFile.getName();
+            // Sanity check that the base paths of the splits are all the same.
+            String basePath = pathFile.getParent();
+            if (!basePath.equals(baseCodePath)) {
+                Slog.wtf(TAG, "Split paths have different base paths: " + basePath + " and " +
+                        baseCodePath);
+            }
+        }
+        return splitRelativeCodePaths;
+    }
+}
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 7e0b950..8e2097a 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -1278,6 +1278,16 @@
             }
         }
 
+        // Inform the StatusBar; but do not allow it to consume the event.
+        IStatusBarService statusBar = getStatusBarService();
+        if (statusBar != null) {
+            try {
+                statusBar.handleSystemKey(event.getKeyCode());
+            } catch (RemoteException e) {
+                // Oh well.
+            }
+        }
+
         // If the power key has still not yet been handled, then detect short
         // press, long press, or multi press and decide what to do.
         mPowerKeyHandled = hungUp || mScreenshotChordVolumeDownKeyTriggered
@@ -3158,10 +3168,18 @@
 
     @Override
     public void selectRotationAnimationLw(int anim[]) {
+        // If the screen is off or non-interactive, force a jumpcut.
+        final boolean forceJumpcut = !mScreenOnFully || !mAwake;
         if (PRINT_ANIM) Slog.i(TAG, "selectRotationAnimation mTopFullscreen="
                 + mTopFullscreenOpaqueWindowState + " rotationAnimation="
                 + (mTopFullscreenOpaqueWindowState == null ?
-                        "0" : mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation));
+                        "0" : mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation)
+                + " forceJumpcut=" + forceJumpcut);
+        if (forceJumpcut) {
+            anim[0] = R.anim.rotation_animation_jump_exit;
+            anim[1] = R.anim.rotation_animation_enter;
+            return;
+        }
         if (mTopFullscreenOpaqueWindowState != null) {
             int animationHint = mTopFullscreenOpaqueWindowState.getRotationAnimationHint();
             if (animationHint < 0 && mTopIsFullscreen) {
@@ -6221,7 +6239,7 @@
                     IStatusBarService sbar = getStatusBarService();
                     if (sbar != null) {
                         try {
-                            sbar.handleSystemNavigationKey(event.getKeyCode());
+                            sbar.handleSystemKey(event.getKeyCode());
                         } catch (RemoteException e1) {
                             // oops, no statusbar. Ignore event.
                         }
@@ -6606,6 +6624,10 @@
     @Override
     public void finishedWakingUp() {
         if (DEBUG_WAKEUP) Slog.i(TAG, "Finished waking up...");
+
+        if (mKeyguardDelegate != null) {
+            mKeyguardDelegate.onFinishedWakingUp();
+        }
     }
 
     private void wakeUpFromPowerKey(long eventTime) {
@@ -6714,6 +6736,11 @@
     @Override
     public void screenTurningOff(ScreenOffListener screenOffListener) {
         mWindowManagerFuncs.screenTurningOff(screenOffListener);
+        synchronized (mLock) {
+            if (mKeyguardDelegate != null) {
+                mKeyguardDelegate.onScreenTurningOff();
+            }
+        }
     }
 
     private void reportScreenStateToVrManager(boolean isScreenOn) {
@@ -6810,8 +6837,8 @@
     }
 
     @Override
-    public boolean isInteractive() {
-        return mAwake;
+    public boolean okToAnimate() {
+        return mAwake && !mGoingToSleep;
     }
 
     /** {@inheritDoc} */
diff --git a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java
index 0121ee1..50e5e7b 100644
--- a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java
+++ b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java
@@ -35,10 +35,12 @@
     private static final int SCREEN_STATE_OFF = 0;
     private static final int SCREEN_STATE_TURNING_ON = 1;
     private static final int SCREEN_STATE_ON = 2;
+    private static final int SCREEN_STATE_TURNING_OFF = 3;
 
     private static final int INTERACTIVE_STATE_SLEEP = 0;
-    private static final int INTERACTIVE_STATE_AWAKE = 1;
-    private static final int INTERACTIVE_STATE_GOING_TO_SLEEP = 2;
+    private static final int INTERACTIVE_STATE_WAKING = 1;
+    private static final int INTERACTIVE_STATE_AWAKE = 2;
+    private static final int INTERACTIVE_STATE_GOING_TO_SLEEP = 3;
 
     protected KeyguardServiceWrapper mKeyguardService;
     private final Context mContext;
@@ -164,9 +166,13 @@
                     mKeyguardService.setCurrentUser(mKeyguardState.currentUser);
                 }
                 // This is used to hide the scrim once keyguard displays.
-                if (mKeyguardState.interactiveState == INTERACTIVE_STATE_AWAKE) {
+                if (mKeyguardState.interactiveState == INTERACTIVE_STATE_AWAKE
+                        || mKeyguardState.interactiveState == INTERACTIVE_STATE_WAKING) {
                     mKeyguardService.onStartedWakingUp();
                 }
+                if (mKeyguardState.interactiveState == INTERACTIVE_STATE_AWAKE) {
+                    mKeyguardService.onFinishedWakingUp();
+                }
                 if (mKeyguardState.screenState == SCREEN_STATE_ON
                         || mKeyguardState.screenState == SCREEN_STATE_TURNING_ON) {
                     mKeyguardService.onScreenTurningOn(
@@ -277,9 +283,25 @@
             if (DEBUG) Log.v(TAG, "onStartedWakingUp()");
             mKeyguardService.onStartedWakingUp();
         }
+        mKeyguardState.interactiveState = INTERACTIVE_STATE_WAKING;
+    }
+
+    public void onFinishedWakingUp() {
+        if (mKeyguardService != null) {
+            if (DEBUG) Log.v(TAG, "onFinishedWakingUp()");
+            mKeyguardService.onFinishedWakingUp();
+        }
         mKeyguardState.interactiveState = INTERACTIVE_STATE_AWAKE;
     }
 
+    public void onScreenTurningOff() {
+        if (mKeyguardService != null) {
+            if (DEBUG) Log.v(TAG, "onScreenTurningOff()");
+            mKeyguardService.onScreenTurningOff();
+        }
+        mKeyguardState.screenState = SCREEN_STATE_TURNING_OFF;
+    }
+
     public void onScreenTurnedOff() {
         if (mKeyguardService != null) {
             if (DEBUG) Log.v(TAG, "onScreenTurnedOff()");
diff --git a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java
index 425be54..952e0b0 100644
--- a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java
+++ b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java
@@ -128,6 +128,15 @@
     }
 
     @Override
+    public void onFinishedWakingUp() {
+        try {
+            mService.onFinishedWakingUp();
+        } catch (RemoteException e) {
+            Slog.w(TAG , "Remote Exception", e);
+        }
+    }
+
+    @Override
     public void onScreenTurningOn(IKeyguardDrawnCallback callback) {
         try {
             mService.onScreenTurningOn(callback);
@@ -146,6 +155,15 @@
     }
 
     @Override
+    public void onScreenTurningOff() {
+        try {
+            mService.onScreenTurningOff();
+        } catch (RemoteException e) {
+            Slog.w(TAG , "Remote Exception", e);
+        }
+    }
+
+    @Override
     public void onScreenTurnedOff() {
         try {
             mService.onScreenTurnedOff();
diff --git a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
index 5b6bf1f..ae04b83 100644
--- a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
+++ b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
@@ -416,12 +416,12 @@
     }
 
     @Override
-    public void handleSystemNavigationKey(int key) throws RemoteException {
+    public void handleSystemKey(int key) throws RemoteException {
         enforceExpandStatusBar();
 
         if (mBar != null) {
             try {
-                mBar.handleSystemNavigationKey(key);
+                mBar.handleSystemKey(key);
             } catch (RemoteException ex) {
             }
         }
diff --git a/services/core/java/com/android/server/wm/AppWindowContainerController.java b/services/core/java/com/android/server/wm/AppWindowContainerController.java
index a6ffe83..84fafe2 100644
--- a/services/core/java/com/android/server/wm/AppWindowContainerController.java
+++ b/services/core/java/com/android/server/wm/AppWindowContainerController.java
@@ -115,41 +115,6 @@
         mListener.onWindowsGone();
     };
 
-    private final Runnable mRemoveStartingWindow = () -> {
-        StartingSurface surface = null;
-        synchronized (mWindowMap) {
-            if (mContainer == null) {
-                if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "mContainer was null while trying to"
-                        + " remove starting window");
-                return;
-            }
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Remove starting " + mContainer
-                    + ": startingWindow=" + mContainer.startingWindow
-                    + " startingView=" + mContainer.startingSurface);
-            if (mContainer.startingData != null) {
-                surface = mContainer.startingSurface;
-                mContainer.startingData = null;
-                mContainer.startingSurface = null;
-                mContainer.startingWindow = null;
-                mContainer.startingDisplayed = false;
-                if (surface == null && DEBUG_STARTING_WINDOW) {
-                    Slog.v(TAG_WM, "startingWindow was set but startingSurface==null, couldn't "
-                            + "remove");
-                }
-            } else if (DEBUG_STARTING_WINDOW) {
-                Slog.v(TAG_WM, "Tried to remove starting window but startingWindow was null:"
-                        + mContainer);
-            }
-        }
-        if (surface != null) {
-            try {
-                surface.remove();
-            } catch (Exception e) {
-                Slog.w(TAG_WM, "Exception when removing starting window", e);
-            }
-        }
-    };
-
     private final Runnable mAddStartingWindow = () -> {
         final StartingData startingData;
         final AppWindowToken container;
@@ -665,13 +630,6 @@
 
     void removeStartingWindow() {
         synchronized (mWindowMap) {
-            if (mHandler.hasCallbacks(mRemoveStartingWindow)) {
-                // Already scheduled.
-                if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Trying to remove starting window but "
-                        + "already scheduled");
-                return;
-            }
-
             if (mContainer.startingWindow == null) {
                 if (mContainer.startingData != null) {
                     // Starting window has not been added yet, but it is scheduled to be added.
@@ -683,12 +641,39 @@
                 return;
             }
 
+            final StartingSurface surface;
+            if (mContainer.startingData != null) {
+                surface = mContainer.startingSurface;
+                mContainer.startingData = null;
+                mContainer.startingSurface = null;
+                mContainer.startingWindow = null;
+                mContainer.startingDisplayed = false;
+                if (surface == null && DEBUG_STARTING_WINDOW) {
+                    Slog.v(TAG_WM, "startingWindow was set but startingSurface==null, couldn't "
+                            + "remove");
+                }
+            } else {
+                if (DEBUG_STARTING_WINDOW) {
+                    Slog.v(TAG_WM, "Tried to remove starting window but startingWindow was null:"
+                            + mContainer);
+                }
+                return;
+            }
+
             if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Schedule remove starting " + mContainer
-                    + " startingWindow=" + mContainer.startingWindow);
+                    + " startingWindow=" + mContainer.startingWindow
+                    + " startingView=" + mContainer.startingSurface);
 
             // Use the same thread to remove the window as we used to add it, as otherwise we end up
             // with things in the view hierarchy being called from different threads.
-            mService.mAnimationHandler.post(mRemoveStartingWindow);
+            mHandler.post(() -> {
+                if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Removing startingView=" + surface);
+                try {
+                    surface.remove();
+                } catch (Exception e) {
+                    Slog.w(TAG_WM, "Exception when removing starting window", e);
+                }
+            });
         }
     }
 
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 902c2ff..847e7d2 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -2410,7 +2410,7 @@
     }
 
     boolean okToAnimate() {
-        return okToDisplay() && mPolicy.isInteractive();
+        return okToDisplay() && mPolicy.okToAnimate();
     }
 
     @Override
@@ -3584,7 +3584,6 @@
     }
 
     private void updateCircularDisplayMaskIfNeeded() {
-        // we're fullscreen and not hosted in an ActivityView
         if (mContext.getResources().getConfiguration().isScreenRound()
                 && mContext.getResources().getBoolean(
                 com.android.internal.R.bool.config_windowShowCircularMask)) {
diff --git a/services/core/jni/Android.mk b/services/core/jni/Android.mk
index a6065025..651cc7d 100644
--- a/services/core/jni/Android.mk
+++ b/services/core/jni/Android.mk
@@ -5,8 +5,12 @@
 LOCAL_CFLAGS += -Wall -Werror -Wno-unused-parameter
 
 LOCAL_SRC_FILES += \
-    $(LOCAL_REL_DIR)/JavaRef.cpp \
-    $(LOCAL_REL_DIR)/NativeCallbackThread.cpp \
+    $(LOCAL_REL_DIR)/BroadcastRadio/JavaRef.cpp \
+    $(LOCAL_REL_DIR)/BroadcastRadio/NativeCallbackThread.cpp \
+    $(LOCAL_REL_DIR)/BroadcastRadio/BroadcastRadioService.cpp \
+    $(LOCAL_REL_DIR)/BroadcastRadio/Tuner.cpp \
+    $(LOCAL_REL_DIR)/BroadcastRadio/TunerCallback.cpp \
+    $(LOCAL_REL_DIR)/BroadcastRadio/convert.cpp \
     $(LOCAL_REL_DIR)/com_android_server_AlarmManagerService.cpp \
     $(LOCAL_REL_DIR)/com_android_server_am_BatteryStatsService.cpp \
     $(LOCAL_REL_DIR)/com_android_server_connectivity_Vpn.cpp \
@@ -22,10 +26,6 @@
     $(LOCAL_REL_DIR)/com_android_server_location_GnssLocationProvider.cpp \
     $(LOCAL_REL_DIR)/com_android_server_locksettings_SyntheticPasswordManager.cpp \
     $(LOCAL_REL_DIR)/com_android_server_power_PowerManagerService.cpp \
-    $(LOCAL_REL_DIR)/com_android_server_radio_RadioService.cpp \
-    $(LOCAL_REL_DIR)/com_android_server_radio_Tuner.cpp \
-    $(LOCAL_REL_DIR)/com_android_server_radio_TunerCallback.cpp \
-    $(LOCAL_REL_DIR)/com_android_server_radio_convert.cpp \
     $(LOCAL_REL_DIR)/com_android_server_SerialService.cpp \
     $(LOCAL_REL_DIR)/com_android_server_storage_AppFuseBridge.cpp \
     $(LOCAL_REL_DIR)/com_android_server_SystemServer.cpp \
diff --git a/services/core/jni/com_android_server_radio_RadioService.cpp b/services/core/jni/BroadcastRadio/BroadcastRadioService.cpp
similarity index 91%
rename from services/core/jni/com_android_server_radio_RadioService.cpp
rename to services/core/jni/BroadcastRadio/BroadcastRadioService.cpp
index 459c0d0..492be17 100644
--- a/services/core/jni/com_android_server_radio_RadioService.cpp
+++ b/services/core/jni/BroadcastRadio/BroadcastRadioService.cpp
@@ -14,13 +14,13 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "radio.RadioService.jni"
+#define LOG_TAG "BroadcastRadioService.jni"
 #define LOG_NDEBUG 0
 
-#include "com_android_server_radio_RadioService.h"
+#include "BroadcastRadioService.h"
 
-#include "com_android_server_radio_Tuner.h"
-#include "com_android_server_radio_convert.h"
+#include "Tuner.h"
+#include "convert.h"
 
 #include <android/hardware/broadcastradio/1.1/IBroadcastRadio.h>
 #include <android/hardware/broadcastradio/1.1/IBroadcastRadioFactory.h>
@@ -32,8 +32,8 @@
 
 namespace android {
 namespace server {
-namespace radio {
-namespace RadioService {
+namespace BroadcastRadio {
+namespace BroadcastRadioService {
 
 using hardware::Return;
 using hardware::hidl_string;
@@ -232,7 +232,7 @@
         return nullptr;
     }
 
-    Tuner::setHalTuner(env, tuner, halTuner);
+    Tuner::assignHalInterfaces(env, tuner, module, halTuner);
     ALOGD("Opened tuner %p", halTuner.get());
     return tuner.release();
 }
@@ -242,20 +242,20 @@
     { "nativeFinalize", "(J)V", (void*)nativeFinalize },
     { "nativeLoadModules", "(J)Ljava/util/List;", (void*)nativeLoadModules },
     { "nativeOpenTuner", "(JILandroid/hardware/radio/RadioManager$BandConfig;Z"
-            "Landroid/hardware/radio/ITunerCallback;)Lcom/android/server/radio/Tuner;",
+            "Landroid/hardware/radio/ITunerCallback;)Lcom/android/server/broadcastradio/Tuner;",
             (void*)nativeOpenTuner },
 };
 
-} // namespace RadioService
-} // namespace radio
+} // namespace BroadcastRadioService
+} // namespace BroadcastRadio
 } // namespace server
 
-void register_android_server_radio_RadioService(JNIEnv *env) {
-    using namespace server::radio::RadioService;
+void register_android_server_broadcastradio_BroadcastRadioService(JNIEnv *env) {
+    using namespace server::BroadcastRadio::BroadcastRadioService;
 
-    register_android_server_radio_convert(env);
+    register_android_server_broadcastradio_convert(env);
 
-    auto tunerClass = FindClassOrDie(env, "com/android/server/radio/Tuner");
+    auto tunerClass = FindClassOrDie(env, "com/android/server/broadcastradio/Tuner");
     gjni.Tuner.clazz = MakeGlobalRefOrDie(env, tunerClass);
     gjni.Tuner.cstor = GetMethodIDOrDie(env, tunerClass, "<init>",
             "(Landroid/hardware/radio/ITunerCallback;IIZI)V");
@@ -265,7 +265,8 @@
     gjni.ArrayList.cstor = GetMethodIDOrDie(env, arrayListClass, "<init>", "()V");
     gjni.ArrayList.add = GetMethodIDOrDie(env, arrayListClass, "add", "(Ljava/lang/Object;)Z");
 
-    auto res = jniRegisterNativeMethods(env, "com/android/server/radio/RadioService",
+    auto res = jniRegisterNativeMethods(env,
+            "com/android/server/broadcastradio/BroadcastRadioService",
             gRadioServiceMethods, NELEM(gRadioServiceMethods));
     LOG_ALWAYS_FATAL_IF(res < 0, "Unable to register native methods.");
 }
diff --git a/services/core/jni/com_android_server_radio_RadioService.h b/services/core/jni/BroadcastRadio/BroadcastRadioService.h
similarity index 71%
rename from services/core/jni/com_android_server_radio_RadioService.h
rename to services/core/jni/BroadcastRadio/BroadcastRadioService.h
index 91e119c..df7af89 100644
--- a/services/core/jni/com_android_server_radio_RadioService.h
+++ b/services/core/jni/BroadcastRadio/BroadcastRadioService.h
@@ -14,15 +14,15 @@
  * limitations under the License.
  */
 
-#ifndef _ANDROID_SERVER_RADIO_RADIOSERVICE_H
-#define _ANDROID_SERVER_RADIO_RADIOSERVICE_H
+#ifndef _ANDROID_SERVER_BROADCASTRADIO_BROADCASTRADIOSERVICE_H
+#define _ANDROID_SERVER_BROADCASTRADIO_BROADCASTRADIOSERVICE_H
 
 #include <jni.h>
 
 namespace android {
 
-void register_android_server_radio_RadioService(JNIEnv *env);
+void register_android_server_broadcastradio_BroadcastRadioService(JNIEnv *env);
 
 } // namespace android
 
-#endif // _ANDROID_SERVER_RADIO_RADIOSERVICE_H
+#endif // _ANDROID_SERVER_BROADCASTRADIO_BROADCASTRADIOSERVICE_H
diff --git a/services/core/jni/JavaRef.cpp b/services/core/jni/BroadcastRadio/JavaRef.cpp
similarity index 100%
rename from services/core/jni/JavaRef.cpp
rename to services/core/jni/BroadcastRadio/JavaRef.cpp
diff --git a/services/core/jni/JavaRef.h b/services/core/jni/BroadcastRadio/JavaRef.h
similarity index 100%
rename from services/core/jni/JavaRef.h
rename to services/core/jni/BroadcastRadio/JavaRef.h
diff --git a/services/core/jni/NativeCallbackThread.cpp b/services/core/jni/BroadcastRadio/NativeCallbackThread.cpp
similarity index 100%
rename from services/core/jni/NativeCallbackThread.cpp
rename to services/core/jni/BroadcastRadio/NativeCallbackThread.cpp
diff --git a/services/core/jni/NativeCallbackThread.h b/services/core/jni/BroadcastRadio/NativeCallbackThread.h
similarity index 100%
rename from services/core/jni/NativeCallbackThread.h
rename to services/core/jni/BroadcastRadio/NativeCallbackThread.h
diff --git a/services/core/jni/com_android_server_radio_Tuner.cpp b/services/core/jni/BroadcastRadio/Tuner.cpp
similarity index 87%
rename from services/core/jni/com_android_server_radio_Tuner.cpp
rename to services/core/jni/BroadcastRadio/Tuner.cpp
index d984a0c..2e8798b 100644
--- a/services/core/jni/com_android_server_radio_Tuner.cpp
+++ b/services/core/jni/BroadcastRadio/Tuner.cpp
@@ -14,13 +14,13 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "radio.Tuner.jni"
+#define LOG_TAG "BroadcastRadioService.Tuner.jni"
 #define LOG_NDEBUG 0
 
-#include "com_android_server_radio_Tuner.h"
+#include "Tuner.h"
 
-#include "com_android_server_radio_convert.h"
-#include "com_android_server_radio_TunerCallback.h"
+#include "convert.h"
+#include "TunerCallback.h"
 
 #include <JNIHelp.h>
 #include <Utils.h>
@@ -32,7 +32,7 @@
 
 namespace android {
 namespace server {
-namespace radio {
+namespace BroadcastRadio {
 namespace Tuner {
 
 using hardware::Return;
@@ -82,6 +82,8 @@
     HalRevision mHalRev;
     bool mWithAudio;
     Band mBand;
+    wp<V1_0::IBroadcastRadio> mHalModule;
+    wp<V1_1::IBroadcastRadio> mHalModule11;
     sp<V1_0::ITuner> mHalTuner;
     sp<V1_1::ITuner> mHalTuner11;
     sp<HalDeathRecipient> mHalDeathRecipient;
@@ -146,7 +148,8 @@
     IPCThreadState::self()->restoreCallingIdentity(token);
 }
 
-void setHalTuner(JNIEnv *env, JavaRef<jobject> const &jTuner, sp<V1_0::ITuner> halTuner) {
+void assignHalInterfaces(JNIEnv *env, JavaRef<jobject> const &jTuner,
+        sp<V1_0::IBroadcastRadio> halModule, sp<V1_0::ITuner> halTuner) {
     ALOGV("setHalTuner(%p)", halTuner.get());
     ALOGE_IF(halTuner == nullptr, "HAL tuner is a nullptr");
 
@@ -163,6 +166,9 @@
         return;
     }
 
+    ctx.mHalModule = halModule;
+    ctx.mHalModule11 = V1_1::IBroadcastRadio::castFrom(halModule).withDefault(nullptr);
+
     ctx.mHalTuner = halTuner;
     ctx.mHalTuner11 = V1_1::ITuner::castFrom(halTuner).withDefault(nullptr);
     ALOGW_IF(ctx.mHalRev >= HalRevision::V1_1 && ctx.mHalTuner11 == nullptr,
@@ -390,6 +396,44 @@
     return jList.release();
 }
 
+static jbyteArray nativeGetImage(JNIEnv *env, jobject obj, jlong nativeContext, jint id) {
+    ALOGV("%s(%x)", __func__, id);
+    AutoMutex _l(gContextMutex);
+    auto& ctx = getNativeContext(nativeContext);
+
+    if (ctx.mHalModule11 == nullptr) {
+        jniThrowException(env, "java/lang/IllegalStateException",
+                "Out-of-band images are not supported with HAL < 1.1");
+        return nullptr;
+    }
+
+    auto halModule = ctx.mHalModule11.promote();
+    if (halModule == nullptr) {
+        ALOGE("HAL module is gone");
+        return nullptr;
+    }
+
+    JavaRef<jbyteArray> jRawImage = nullptr;
+
+    auto hidlResult = halModule->getImage(id, [&](hidl_vec<uint8_t> rawImage) {
+        auto len = rawImage.size();
+        if (len == 0) return;
+
+        jRawImage = make_javaref(env, env->NewByteArray(len));
+        if (jRawImage == nullptr) {
+            ALOGE("Failed to allocate byte array of len %zu", len);
+            return;
+        }
+
+        env->SetByteArrayRegion(jRawImage.get(), 0, len,
+                reinterpret_cast<const jbyte*>(rawImage.data()));
+    });
+
+    if (convert::ThrowIfFailed(env, hidlResult)) return nullptr;
+
+    return jRawImage.get();
+}
+
 static bool nativeIsAnalogForced(JNIEnv *env, jobject obj, jlong nativeContext) {
     ALOGV("nativeIsAnalogForced()");
     auto halTuner = getHalTuner11(nativeContext);
@@ -457,32 +501,33 @@
     { "nativeStartBackgroundScan", "(J)Z", (void*)nativeStartBackgroundScan },
     { "nativeGetProgramList", "(JLjava/lang/String;)Ljava/util/List;",
             (void*)nativeGetProgramList },
+    { "nativeGetImage", "(JI)[B", (void*)nativeGetImage},
     { "nativeIsAnalogForced", "(J)Z", (void*)nativeIsAnalogForced },
     { "nativeSetAnalogForced", "(JZ)V", (void*)nativeSetAnalogForced },
     { "nativeIsAntennaConnected", "(J)Z", (void*)nativeIsAntennaConnected },
 };
 
 } // namespace Tuner
-} // namespace radio
+} // namespace BroadcastRadio
 } // namespace server
 
-void register_android_server_radio_Tuner(JavaVM *vm, JNIEnv *env) {
-    using namespace server::radio::Tuner;
+void register_android_server_broadcastradio_Tuner(JavaVM *vm, JNIEnv *env) {
+    using namespace server::BroadcastRadio::Tuner;
 
-    register_android_server_radio_TunerCallback(vm, env);
+    register_android_server_broadcastradio_TunerCallback(vm, env);
 
-    auto tunerClass = FindClassOrDie(env, "com/android/server/radio/Tuner");
+    auto tunerClass = FindClassOrDie(env, "com/android/server/broadcastradio/Tuner");
     gjni.Tuner.nativeContext = GetFieldIDOrDie(env, tunerClass, "mNativeContext", "J");
     gjni.Tuner.region = GetFieldIDOrDie(env, tunerClass, "mRegion", "I");
     gjni.Tuner.tunerCallback = GetFieldIDOrDie(env, tunerClass, "mTunerCallback",
-            "Lcom/android/server/radio/TunerCallback;");
+            "Lcom/android/server/broadcastradio/TunerCallback;");
 
     auto arrayListClass = FindClassOrDie(env, "java/util/ArrayList");
     gjni.ArrayList.clazz = MakeGlobalRefOrDie(env, arrayListClass);
     gjni.ArrayList.cstor = GetMethodIDOrDie(env, arrayListClass, "<init>", "()V");
     gjni.ArrayList.add = GetMethodIDOrDie(env, arrayListClass, "add", "(Ljava/lang/Object;)Z");
 
-    auto res = jniRegisterNativeMethods(env, "com/android/server/radio/Tuner",
+    auto res = jniRegisterNativeMethods(env, "com/android/server/broadcastradio/Tuner",
             gTunerMethods, NELEM(gTunerMethods));
     LOG_ALWAYS_FATAL_IF(res < 0, "Unable to register native methods.");
 }
diff --git a/services/core/jni/com_android_server_radio_Tuner.h b/services/core/jni/BroadcastRadio/Tuner.h
similarity index 68%
rename from services/core/jni/com_android_server_radio_Tuner.h
rename to services/core/jni/BroadcastRadio/Tuner.h
index f653832..818597b 100644
--- a/services/core/jni/com_android_server_radio_Tuner.h
+++ b/services/core/jni/BroadcastRadio/Tuner.h
@@ -14,13 +14,14 @@
  * limitations under the License.
  */
 
-#ifndef _ANDROID_SERVER_RADIO_TUNER_H
-#define _ANDROID_SERVER_RADIO_TUNER_H
+#ifndef _ANDROID_SERVER_BROADCASTRADIORADIO_TUNER_H
+#define _ANDROID_SERVER_BROADCASTRADIORADIO_TUNER_H
 
-#include "com_android_server_radio_types.h"
+#include "types.h"
 
 #include "JavaRef.h"
 
+#include <android/hardware/broadcastradio/1.1/IBroadcastRadio.h>
 #include <android/hardware/broadcastradio/1.1/ITuner.h>
 #include <android/hardware/broadcastradio/1.1/ITunerCallback.h>
 #include <jni.h>
@@ -28,13 +29,14 @@
 
 namespace android {
 
-void register_android_server_radio_Tuner(JavaVM *vm, JNIEnv *env);
+void register_android_server_broadcastradio_Tuner(JavaVM *vm, JNIEnv *env);
 
 namespace server {
-namespace radio {
+namespace BroadcastRadio {
 namespace Tuner {
 
-void setHalTuner(JNIEnv *env, JavaRef<jobject> const &jTuner,
+void assignHalInterfaces(JNIEnv *env, JavaRef<jobject> const &jTuner,
+        sp<hardware::broadcastradio::V1_0::IBroadcastRadio> halModule,
         sp<hardware::broadcastradio::V1_0::ITuner> halTuner);
 
 sp<hardware::broadcastradio::V1_1::ITunerCallback>
@@ -43,8 +45,8 @@
 Region getRegion(JNIEnv *env, jobject obj);
 
 } // namespace Tuner
-} // namespace radio
+} // namespace BroadcastRadio
 } // namespace server
 } // namespace android
 
-#endif // _ANDROID_SERVER_RADIO_TUNER_H
+#endif // _ANDROID_SERVER_BROADCASTRADIORADIO_TUNER_H
diff --git a/services/core/jni/com_android_server_radio_TunerCallback.cpp b/services/core/jni/BroadcastRadio/TunerCallback.cpp
similarity index 95%
rename from services/core/jni/com_android_server_radio_TunerCallback.cpp
rename to services/core/jni/BroadcastRadio/TunerCallback.cpp
index 815a212..d22ee82 100644
--- a/services/core/jni/com_android_server_radio_TunerCallback.cpp
+++ b/services/core/jni/BroadcastRadio/TunerCallback.cpp
@@ -14,13 +14,13 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "radio.TunerCallback.jni"
+#define LOG_TAG "BroadcastRadioService.TunerCallback.jni"
 #define LOG_NDEBUG 0
 
-#include "com_android_server_radio_TunerCallback.h"
+#include "TunerCallback.h"
 
-#include "com_android_server_radio_convert.h"
-#include "com_android_server_radio_Tuner.h"
+#include "Tuner.h"
+#include "convert.h"
 
 #include <JNIHelp.h>
 #include <Utils.h>
@@ -29,7 +29,7 @@
 
 namespace android {
 namespace server {
-namespace radio {
+namespace BroadcastRadio {
 namespace TunerCallback {
 
 using hardware::Return;
@@ -355,21 +355,21 @@
 }
 
 static const JNINativeMethod gTunerCallbackMethods[] = {
-    { "nativeInit", "(Lcom/android/server/radio/Tuner;I)J", (void*)nativeInit },
+    { "nativeInit", "(Lcom/android/server/broadcastradio/Tuner;I)J", (void*)nativeInit },
     { "nativeFinalize", "(J)V", (void*)nativeFinalize },
     { "nativeDetach", "(J)V", (void*)nativeDetach },
 };
 
 } // namespace TunerCallback
-} // namespace radio
+} // namespace BroadcastRadio
 } // namespace server
 
-void register_android_server_radio_TunerCallback(JavaVM *vm, JNIEnv *env) {
-    using namespace server::radio::TunerCallback;
+void register_android_server_broadcastradio_TunerCallback(JavaVM *vm, JNIEnv *env) {
+    using namespace server::BroadcastRadio::TunerCallback;
 
     gvm = vm;
 
-    auto tunerCbClass = FindClassOrDie(env, "com/android/server/radio/TunerCallback");
+    auto tunerCbClass = FindClassOrDie(env, "com/android/server/broadcastradio/TunerCallback");
     gjni.TunerCallback.clazz = MakeGlobalRefOrDie(env, tunerCbClass);
     gjni.TunerCallback.nativeContext = GetFieldIDOrDie(env, tunerCbClass, "mNativeContext", "J");
     gjni.TunerCallback.handleHwFailure = GetMethodIDOrDie(env, tunerCbClass, "handleHwFailure", "()V");
@@ -391,7 +391,7 @@
     gjni.TunerCallback.onProgramListChanged = GetMethodIDOrDie(env, tunerCbClass,
             "onProgramListChanged", "()V");
 
-    auto res = jniRegisterNativeMethods(env, "com/android/server/radio/TunerCallback",
+    auto res = jniRegisterNativeMethods(env, "com/android/server/broadcastradio/TunerCallback",
             gTunerCallbackMethods, NELEM(gTunerCallbackMethods));
     LOG_ALWAYS_FATAL_IF(res < 0, "Unable to register native methods.");
 }
diff --git a/services/core/jni/com_android_server_radio_TunerCallback.h b/services/core/jni/BroadcastRadio/TunerCallback.h
similarity index 75%
rename from services/core/jni/com_android_server_radio_TunerCallback.h
rename to services/core/jni/BroadcastRadio/TunerCallback.h
index 7d37b87..af12d21 100644
--- a/services/core/jni/com_android_server_radio_TunerCallback.h
+++ b/services/core/jni/BroadcastRadio/TunerCallback.h
@@ -14,30 +14,30 @@
  * limitations under the License.
  */
 
-#ifndef _ANDROID_SERVER_RADIO_TUNERCALLBACK_H
-#define _ANDROID_SERVER_RADIO_TUNERCALLBACK_H
+#ifndef _ANDROID_SERVER_BROADCASTRADIO_TUNERCALLBACK_H
+#define _ANDROID_SERVER_BROADCASTRADIO_TUNERCALLBACK_H
 
 #include "JavaRef.h"
 #include "NativeCallbackThread.h"
-#include "com_android_server_radio_types.h"
+#include "types.h"
 
 #include <android/hardware/broadcastradio/1.1/ITunerCallback.h>
 #include <jni.h>
 
 namespace android {
 
-void register_android_server_radio_TunerCallback(JavaVM *vm, JNIEnv *env);
+void register_android_server_broadcastradio_TunerCallback(JavaVM *vm, JNIEnv *env);
 
 namespace server {
-namespace radio {
+namespace BroadcastRadio {
 namespace TunerCallback {
 
 sp<hardware::broadcastradio::V1_1::ITunerCallback>
 getNativeCallback(JNIEnv *env, jobject jTunerCallback);
 
 } // namespace TunerCallback
-} // namespace radio
+} // namespace BroadcastRadio
 } // namespace server
 } // namespace android
 
-#endif // _ANDROID_SERVER_RADIO_TUNERCALLBACK_H
+#endif // _ANDROID_SERVER_BROADCASTRADIO_TUNERCALLBACK_H
diff --git a/services/core/jni/com_android_server_radio_convert.cpp b/services/core/jni/BroadcastRadio/convert.cpp
similarity index 97%
rename from services/core/jni/com_android_server_radio_convert.cpp
rename to services/core/jni/BroadcastRadio/convert.cpp
index 6cad7f8..a2e5643 100644
--- a/services/core/jni/com_android_server_radio_convert.cpp
+++ b/services/core/jni/BroadcastRadio/convert.cpp
@@ -14,10 +14,10 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "radio.convert.jni"
+#define LOG_TAG "BroadcastRadioService.convert.jni"
 #define LOG_NDEBUG 0
 
-#include "com_android_server_radio_convert.h"
+#include "convert.h"
 
 #include <JNIHelp.h>
 #include <Utils.h>
@@ -26,7 +26,7 @@
 
 namespace android {
 namespace server {
-namespace radio {
+namespace BroadcastRadio {
 namespace convert {
 
 using hardware::Return;
@@ -126,6 +126,11 @@
     } ParcelableException;
 } gjni;
 
+template <>
+bool ThrowIfFailed(JNIEnv *env, const hardware::Return<void> &hidlResult) {
+    return __ThrowIfFailedHidl(env, hidlResult);
+}
+
 bool __ThrowIfFailedHidl(JNIEnv *env, const hardware::details::return_status &hidlResult) {
     if (hidlResult.isOk()) return false;
 
@@ -266,7 +271,7 @@
     auto jVersion = make_javastr(env, prop10.version);
     auto jSerial = make_javastr(env, prop10.serial);
     bool isBgScanSupported = prop11 ? prop11->supportsBackgroundScanning : false;
-    auto jVendorExtension = prop11 ? make_javastr(env, prop11->vendorExension) : nullptr;
+    auto jVendorInfo = prop11 ? make_javastr(env, prop11->vendorInfo) : nullptr;
     // ITU_1 is the default region just because its index is 0.
     auto jBands = ArrayFromHal<V1_0::BandConfig>(env, prop10.bands, gjni.BandDescriptor.clazz,
         std::bind(BandDescriptorFromHal, _1, _2, Region::ITU_1));
@@ -279,7 +284,7 @@
             gjni.ModuleProperties.cstor, moduleId, jServiceName.get(), prop10.classId,
             jImplementor.get(), jProduct.get(), jVersion.get(), jSerial.get(), prop10.numTuners,
             prop10.numAudioSources, prop10.supportsCapture, jBands.get(), isBgScanSupported,
-            jSupportedProgramTypes.get(), jSupportedIdentifierTypes.get(), jVendorExtension.get()));
+            jSupportedProgramTypes.get(), jSupportedIdentifierTypes.get(), jVendorInfo.get()));
 }
 
 JavaRef<jobject> ModulePropertiesFromHal(JNIEnv *env, const V1_0::Properties &properties,
@@ -507,12 +512,12 @@
     ALOGV("ProgramInfoFromHal()");
 
     auto jMetadata = MetadataFromHal(env, info10.metadata);
-    auto jVendorExtension = info11 ? make_javastr(env, info11->vendorExension) : nullptr;
+    auto jVendorInfo = info11 ? make_javastr(env, info11->vendorInfo) : nullptr;
     auto jSelector = ProgramSelectorFromHal(env, selector);
 
     return make_javaref(env, env->NewObject(gjni.ProgramInfo.clazz, gjni.ProgramInfo.cstor,
             jSelector.get(), info10.tuned, info10.stereo, info10.digital, info10.signalStrength,
-            jMetadata.get(), info11 ? info11->flags : 0, jVendorExtension.get()));
+            jMetadata.get(), info11 ? info11->flags : 0, jVendorInfo.get()));
 }
 
 JavaRef<jobject> ProgramInfoFromHal(JNIEnv *env, const V1_0::ProgramInfo &info, V1_0::Band band) {
@@ -525,11 +530,11 @@
 }
 
 } // namespace convert
-} // namespace radio
+} // namespace BroadcastRadio
 } // namespace server
 
-void register_android_server_radio_convert(JNIEnv *env) {
-    using namespace server::radio::convert;
+void register_android_server_broadcastradio_convert(JNIEnv *env) {
+    using namespace server::BroadcastRadio::convert;
 
     auto bandConfigClass = FindClassOrDie(env, "android/hardware/radio/RadioManager$BandConfig");
     gjni.BandConfig.descriptor = GetFieldIDOrDie(env, bandConfigClass,
diff --git a/services/core/jni/com_android_server_radio_convert.h b/services/core/jni/BroadcastRadio/convert.h
similarity index 86%
rename from services/core/jni/com_android_server_radio_convert.h
rename to services/core/jni/BroadcastRadio/convert.h
index 8b91ced..198e594 100644
--- a/services/core/jni/com_android_server_radio_convert.h
+++ b/services/core/jni/BroadcastRadio/convert.h
@@ -14,21 +14,22 @@
  * limitations under the License.
  */
 
-#ifndef _ANDROID_SERVER_RADIO_CONVERT_H
-#define _ANDROID_SERVER_RADIO_CONVERT_H
+#ifndef _ANDROID_SERVER_BROADCASTRADIO_CONVERT_H
+#define _ANDROID_SERVER_BROADCASTRADIO_CONVERT_H
+
+#include "types.h"
 
 #include "JavaRef.h"
-#include "com_android_server_radio_types.h"
 
 #include <android/hardware/broadcastradio/1.1/types.h>
 #include <jni.h>
 
 namespace android {
 
-void register_android_server_radio_convert(JNIEnv *env);
+void register_android_server_broadcastradio_convert(JNIEnv *env);
 
 namespace server {
-namespace radio {
+namespace BroadcastRadio {
 namespace convert {
 
 namespace V1_0 = hardware::broadcastradio::V1_0;
@@ -68,9 +69,12 @@
     return __ThrowIfFailedHidl(env, hidlResult) || __ThrowIfFailed(env, static_cast<T>(hidlResult));
 }
 
+template <>
+bool ThrowIfFailed(JNIEnv *env, const hardware::Return<void> &hidlResult);
+
 } // namespace convert
-} // namespace radio
+} // namespace BroadcastRadio
 } // namespace server
 } // namespace android
 
-#endif // _ANDROID_SERVER_RADIO_CONVERT_H
+#endif // _ANDROID_SERVER_BROADCASTRADIO_CONVERT_H
diff --git a/services/core/jni/com_android_server_radio_types.h b/services/core/jni/BroadcastRadio/types.h
similarity index 90%
rename from services/core/jni/com_android_server_radio_types.h
rename to services/core/jni/BroadcastRadio/types.h
index 36f7643..f726af3 100644
--- a/services/core/jni/com_android_server_radio_types.h
+++ b/services/core/jni/BroadcastRadio/types.h
@@ -14,14 +14,14 @@
  * limitations under the License.
  */
 
-#ifndef _ANDROID_SERVER_RADIO_TYPES_H
-#define _ANDROID_SERVER_RADIO_TYPES_H
+#ifndef _ANDROID_SERVER_BROADCASTRADIO_TYPES_H
+#define _ANDROID_SERVER_BROADCASTRADIO_TYPES_H
 
 #include <jni.h>
 
 namespace android {
 namespace server {
-namespace radio {
+namespace BroadcastRadio {
 
 /* Most of these enums are dereived from Java code, based at
  * frameworks/base/core/java/android/hardware/radio/RadioManager.java.
@@ -53,7 +53,7 @@
     KOREA = 4,
 };
 
-} // namespace radio
+} // namespace BroadcastRadio
 } // namespace server
 } // namespace android
 
diff --git a/services/core/jni/com_android_server_AlarmManagerService.cpp b/services/core/jni/com_android_server_AlarmManagerService.cpp
index 3a0273d..bcb0b4f 100644
--- a/services/core/jni/com_android_server_AlarmManagerService.cpp
+++ b/services/core/jni/com_android_server_AlarmManagerService.cpp
@@ -17,7 +17,7 @@
 
 #define LOG_TAG "AlarmManagerService"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 #include <utils/Log.h>
 #include <utils/misc.h>
diff --git a/services/core/jni/com_android_server_HardwarePropertiesManagerService.cpp b/services/core/jni/com_android_server_HardwarePropertiesManagerService.cpp
index ba3be67..5f67ac1 100644
--- a/services/core/jni/com_android_server_HardwarePropertiesManagerService.cpp
+++ b/services/core/jni/com_android_server_HardwarePropertiesManagerService.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "HardwarePropertiesManagerService-JNI"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 
 #include <math.h>
diff --git a/services/core/jni/com_android_server_PersistentDataBlockService.cpp b/services/core/jni/com_android_server_PersistentDataBlockService.cpp
index f94e5d9..97e69fb 100644
--- a/services/core/jni/com_android_server_PersistentDataBlockService.cpp
+++ b/services/core/jni/com_android_server_PersistentDataBlockService.cpp
@@ -15,9 +15,9 @@
  */
 
 #include <android_runtime/AndroidRuntime.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <jni.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 #include <utils/misc.h>
 #include <sys/ioctl.h>
diff --git a/services/core/jni/com_android_server_SerialService.cpp b/services/core/jni/com_android_server_SerialService.cpp
index 1bd7a59..aef0b25 100644
--- a/services/core/jni/com_android_server_SerialService.cpp
+++ b/services/core/jni/com_android_server_SerialService.cpp
@@ -18,7 +18,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 
 #include <sys/types.h>
diff --git a/services/core/jni/com_android_server_SystemServer.cpp b/services/core/jni/com_android_server_SystemServer.cpp
index 470cc57..3901ceb 100644
--- a/services/core/jni/com_android_server_SystemServer.cpp
+++ b/services/core/jni/com_android_server_SystemServer.cpp
@@ -15,7 +15,7 @@
  */
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #include <hidl/HidlTransportSupport.h>
 
diff --git a/services/core/jni/com_android_server_UsbDeviceManager.cpp b/services/core/jni/com_android_server_UsbDeviceManager.cpp
index 3733a55..f37f870 100644
--- a/services/core/jni/com_android_server_UsbDeviceManager.cpp
+++ b/services/core/jni/com_android_server_UsbDeviceManager.cpp
@@ -18,7 +18,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/Log.h"
 
diff --git a/services/core/jni/com_android_server_UsbHostManager.cpp b/services/core/jni/com_android_server_UsbHostManager.cpp
index a2b79ff..88ae824 100644
--- a/services/core/jni/com_android_server_UsbHostManager.cpp
+++ b/services/core/jni/com_android_server_UsbHostManager.cpp
@@ -18,7 +18,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/Log.h"
 
diff --git a/services/core/jni/com_android_server_UsbMidiDevice.cpp b/services/core/jni/com_android_server_UsbMidiDevice.cpp
index e12a016..79d935f 100644
--- a/services/core/jni/com_android_server_UsbMidiDevice.cpp
+++ b/services/core/jni/com_android_server_UsbMidiDevice.cpp
@@ -19,7 +19,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/Log.h"
 
diff --git a/services/core/jni/com_android_server_VibratorService.cpp b/services/core/jni/com_android_server_VibratorService.cpp
index 45e9cc7..0370490 100644
--- a/services/core/jni/com_android_server_VibratorService.cpp
+++ b/services/core/jni/com_android_server_VibratorService.cpp
@@ -21,7 +21,7 @@
 #include <android/hardware/vibrator/1.1/IVibrator.h>
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 
 #include <utils/misc.h>
diff --git a/services/core/jni/com_android_server_am_BatteryStatsService.cpp b/services/core/jni/com_android_server_am_BatteryStatsService.cpp
index 2dfd8b9..2dc388a 100644
--- a/services/core/jni/com_android_server_am_BatteryStatsService.cpp
+++ b/services/core/jni/com_android_server_am_BatteryStatsService.cpp
@@ -33,8 +33,8 @@
 #include <android_runtime/AndroidRuntime.h>
 #include <jni.h>
 
-#include <ScopedLocalRef.h>
-#include <ScopedPrimitiveArray.h>
+#include <nativehelper/ScopedLocalRef.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
 
 #include <log/log.h>
 #include <utils/misc.h>
@@ -301,30 +301,17 @@
             if (status != Status::SUCCESS)
                 return;
 
-            for (size_t i = 0; i < subsystems.size(); i++) {
-                int added;
-                const PowerStateSubsystem &subsystem = subsystems[i];
-
-                added = snprintf(offset, remaining,
-                                 "subsystem_%zu name=%s ", i + 1, subsystem.name.c_str());
-                if (added < 0) {
-                    break;
-                }
-
-                if (added > remaining) {
-                    added = remaining;
-                }
-
+            if (subsystems.size() > 0) {
+                int added = snprintf(offset, remaining, "SubsystemPowerState ");
                 offset += added;
                 remaining -= added;
                 total_added += added;
 
-                for (size_t j = 0; j < subsystem.states.size(); j++) {
-                    const PowerStateSubsystemSleepState& state = subsystem.states[j];
+                for (size_t i = 0; i < subsystems.size(); i++) {
+                    const PowerStateSubsystem &subsystem = subsystems[i];
+
                     added = snprintf(offset, remaining,
-                                     "state_%zu name=%s time=%" PRIu64 " count=%" PRIu64 " last entry TS(ms)=%" PRIu64 " ",
-                                     j + 1, state.name.c_str(), state.residencyInMsecSinceBoot,
-                                     state.totalTransitions, state.lastEntryTimestampMs);
+                                     "subsystem_%zu name=%s ", i + 1, subsystem.name.c_str());
                     if (added < 0) {
                         break;
                     }
@@ -336,14 +323,33 @@
                     offset += added;
                     remaining -= added;
                     total_added += added;
-                }
 
-                if (remaining <= 0) {
-                    /* rewrite NULL character*/
-                    offset--;
-                    total_added--;
-                    ALOGE("PowerHal: buffer not enough");
-                    break;
+                    for (size_t j = 0; j < subsystem.states.size(); j++) {
+                        const PowerStateSubsystemSleepState& state = subsystem.states[j];
+                        added = snprintf(offset, remaining,
+                                         "state_%zu name=%s time=%" PRIu64 " count=%" PRIu64 " last entry=%" PRIu64 " ",
+                                         j + 1, state.name.c_str(), state.residencyInMsecSinceBoot,
+                                         state.totalTransitions, state.lastEntryTimestampMs);
+                        if (added < 0) {
+                            break;
+                        }
+
+                        if (added > remaining) {
+                            added = remaining;
+                        }
+
+                        offset += added;
+                        remaining -= added;
+                        total_added += added;
+                    }
+
+                    if (remaining <= 0) {
+                        /* rewrite NULL character*/
+                        offset--;
+                        total_added--;
+                        ALOGE("PowerHal: buffer not enough");
+                        break;
+                    }
                 }
             }
         }
diff --git a/services/core/jni/com_android_server_connectivity_Vpn.cpp b/services/core/jni/com_android_server_connectivity_Vpn.cpp
index 4d85d9a..b6bea11 100644
--- a/services/core/jni/com_android_server_connectivity_Vpn.cpp
+++ b/services/core/jni/com_android_server_connectivity_Vpn.cpp
@@ -38,7 +38,7 @@
 #include "netutils/ifc.h"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 
 namespace android
 {
diff --git a/services/core/jni/com_android_server_connectivity_tethering_OffloadHardwareInterface.cpp b/services/core/jni/com_android_server_connectivity_tethering_OffloadHardwareInterface.cpp
index 4e5c27f..87312f8 100644
--- a/services/core/jni/com_android_server_connectivity_tethering_OffloadHardwareInterface.cpp
+++ b/services/core/jni/com_android_server_connectivity_tethering_OffloadHardwareInterface.cpp
@@ -18,7 +18,7 @@
 #include <error.h>
 #include <hidl/HidlSupport.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <linux/netfilter/nfnetlink.h>
 #include <linux/netlink.h>
 #include <sys/socket.h>
diff --git a/services/core/jni/com_android_server_fingerprint_FingerprintService.cpp b/services/core/jni/com_android_server_fingerprint_FingerprintService.cpp
index 39474ec..503f0cf 100644
--- a/services/core/jni/com_android_server_fingerprint_FingerprintService.cpp
+++ b/services/core/jni/com_android_server_fingerprint_FingerprintService.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "Fingerprint-JNI"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include <inttypes.h>
 
 #include <android_runtime/AndroidRuntime.h>
diff --git a/services/core/jni/com_android_server_hdmi_HdmiCecController.cpp b/services/core/jni/com_android_server_hdmi_HdmiCecController.cpp
index 4df7256..c22109c 100644
--- a/services/core/jni/com_android_server_hdmi_HdmiCecController.cpp
+++ b/services/core/jni/com_android_server_hdmi_HdmiCecController.cpp
@@ -18,8 +18,8 @@
 
 #define LOG_NDEBUG 1
 
-#include <JNIHelp.h>
-#include <ScopedPrimitiveArray.h>
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
 
 #include <android/hardware/tv/cec/1.0/IHdmiCec.h>
 #include <android/hardware/tv/cec/1.0/IHdmiCecCallback.h>
diff --git a/services/core/jni/com_android_server_input_InputApplicationHandle.cpp b/services/core/jni/com_android_server_input_InputApplicationHandle.cpp
index e927b60..232b2c2 100644
--- a/services/core/jni/com_android_server_input_InputApplicationHandle.cpp
+++ b/services/core/jni/com_android_server_input_InputApplicationHandle.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "InputApplicationHandle"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/threads.h>
diff --git a/services/core/jni/com_android_server_input_InputApplicationHandle.h b/services/core/jni/com_android_server_input_InputApplicationHandle.h
index e6f25cc..c9af711 100644
--- a/services/core/jni/com_android_server_input_InputApplicationHandle.h
+++ b/services/core/jni/com_android_server_input_InputApplicationHandle.h
@@ -19,7 +19,7 @@
 
 #include <inputflinger/InputApplication.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 
 namespace android {
diff --git a/services/core/jni/com_android_server_input_InputManagerService.cpp b/services/core/jni/com_android_server_input_InputManagerService.cpp
index 59a174e..21300ed 100644
--- a/services/core/jni/com_android_server_input_InputManagerService.cpp
+++ b/services/core/jni/com_android_server_input_InputManagerService.cpp
@@ -27,7 +27,7 @@
 #define DEBUG_INPUT_DISPATCHER_POLICY 0
 
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 #include <atomic>
 #include <cinttypes>
@@ -54,9 +54,9 @@
 #include <android_view_PointerIcon.h>
 #include <android/graphics/GraphicsJNI.h>
 
-#include <ScopedLocalRef.h>
-#include <ScopedPrimitiveArray.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedLocalRef.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 #include "com_android_server_power_PowerManagerService.h"
 #include "com_android_server_input_InputApplicationHandle.h"
diff --git a/services/core/jni/com_android_server_input_InputWindowHandle.cpp b/services/core/jni/com_android_server_input_InputWindowHandle.cpp
index 197d056..2b2a6fa 100644
--- a/services/core/jni/com_android_server_input_InputWindowHandle.cpp
+++ b/services/core/jni/com_android_server_input_InputWindowHandle.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "InputWindowHandle"
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/threads.h>
diff --git a/services/core/jni/com_android_server_input_InputWindowHandle.h b/services/core/jni/com_android_server_input_InputWindowHandle.h
index 8d9e7d7..44d4620 100644
--- a/services/core/jni/com_android_server_input_InputWindowHandle.h
+++ b/services/core/jni/com_android_server_input_InputWindowHandle.h
@@ -19,7 +19,7 @@
 
 #include <inputflinger/InputWindow.h>
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 
 namespace android {
diff --git a/services/core/jni/com_android_server_lights_LightsService.cpp b/services/core/jni/com_android_server_lights_LightsService.cpp
index c873bdc..c90113f 100644
--- a/services/core/jni/com_android_server_lights_LightsService.cpp
+++ b/services/core/jni/com_android_server_lights_LightsService.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "LightsService"
 
 #include "jni.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 
 #include <android/hardware/light/2.0/ILight.h>
diff --git a/services/core/jni/com_android_server_power_PowerManagerService.h b/services/core/jni/com_android_server_power_PowerManagerService.h
index f5fd3d6..a17fd65 100644
--- a/services/core/jni/com_android_server_power_PowerManagerService.h
+++ b/services/core/jni/com_android_server_power_PowerManagerService.h
@@ -17,7 +17,7 @@
 #ifndef _ANDROID_SERVER_POWER_MANAGER_SERVICE_H
 #define _ANDROID_SERVER_POWER_MANAGER_SERVICE_H
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 
 #include <powermanager/PowerManager.h>
diff --git a/services/core/jni/com_android_server_tv_TvInputHal.cpp b/services/core/jni/com_android_server_tv_TvInputHal.cpp
index 78c0fa7..93c4829 100644
--- a/services/core/jni/com_android_server_tv_TvInputHal.cpp
+++ b/services/core/jni/com_android_server_tv_TvInputHal.cpp
@@ -21,7 +21,7 @@
 #include "android_os_MessageQueue.h"
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/android_view_Surface.h"
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 
 #include <android/hardware/tv/input/1.0/ITvInputCallback.h>
diff --git a/services/core/jni/com_android_server_tv_TvUinputBridge.cpp b/services/core/jni/com_android_server_tv_TvUinputBridge.cpp
index de115c8..980922a 100644
--- a/services/core/jni/com_android_server_tv_TvUinputBridge.cpp
+++ b/services/core/jni/com_android_server_tv_TvUinputBridge.cpp
@@ -20,7 +20,7 @@
 
 #include "jni.h"
 #include <android_runtime/AndroidRuntime.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include <android/keycodes.h>
 
 #include <utils/BitSet.h>
diff --git a/services/core/jni/com_android_server_vr_VrManagerService.cpp b/services/core/jni/com_android_server_vr_VrManagerService.cpp
index 9052697..c675080 100644
--- a/services/core/jni/com_android_server_vr_VrManagerService.cpp
+++ b/services/core/jni/com_android_server_vr_VrManagerService.cpp
@@ -18,7 +18,7 @@
 
 #include <android_runtime/AndroidRuntime.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #include <android/hardware/vr/1.0/IVr.h>
 #include <utils/Errors.h>
diff --git a/services/core/jni/onload.cpp b/services/core/jni/onload.cpp
index c3617e0..e8ef168 100644
--- a/services/core/jni/onload.cpp
+++ b/services/core/jni/onload.cpp
@@ -14,13 +14,13 @@
  * limitations under the License.
  */
 
-#include "JNIHelp.h"
+#include <nativehelper/JNIHelp.h>
 #include "jni.h"
 #include "utils/Log.h"
 #include "utils/misc.h"
 
-#include "com_android_server_radio_RadioService.h"
-#include "com_android_server_radio_Tuner.h"
+#include "BroadcastRadio/BroadcastRadioService.h"
+#include "BroadcastRadio/Tuner.h"
 
 namespace android {
 int register_android_server_AlarmManagerService(JNIEnv* env);
@@ -67,8 +67,8 @@
     }
     ALOG_ASSERT(env, "Could not retrieve the env!");
 
-    register_android_server_radio_RadioService(env);
-    register_android_server_radio_Tuner(vm, env);
+    register_android_server_broadcastradio_BroadcastRadioService(env);
+    register_android_server_broadcastradio_Tuner(vm, env);
     register_android_server_PowerManagerService(env);
     register_android_server_SerialService(env);
     register_android_server_InputApplicationHandle(env);
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index d10cc02..8574728 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -97,7 +97,7 @@
 import com.android.server.policy.PhoneWindowManager;
 import com.android.server.power.PowerManagerService;
 import com.android.server.power.ShutdownThread;
-import com.android.server.radio.RadioService;
+import com.android.server.broadcastradio.BroadcastRadioService;
 import com.android.server.restrictions.RestrictionsManagerService;
 import com.android.server.retaildemo.RetailDemoModeService;
 import com.android.server.security.KeyAttestationApplicationIdProviderService;
@@ -1208,7 +1208,7 @@
 
             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BROADCAST_RADIO)) {
                 traceBeginAndSlog("StartBroadcastRadioService");
-                mSystemServiceManager.startService(RadioService.class);
+                mSystemServiceManager.startService(BroadcastRadioService.class);
                 traceEnd();
             }
 
diff --git a/services/net/java/android/net/apf/ApfFilter.java b/services/net/java/android/net/apf/ApfFilter.java
index e4c6690..8cb2df7 100644
--- a/services/net/java/android/net/apf/ApfFilter.java
+++ b/services/net/java/android/net/apf/ApfFilter.java
@@ -179,6 +179,7 @@
     private static final int ETH_HEADER_LEN = 14;
     private static final int ETH_DEST_ADDR_OFFSET = 0;
     private static final int ETH_ETHERTYPE_OFFSET = 12;
+    private static final int ETH_TYPE_MIN = 0x0600;
     private static final byte[] ETH_BROADCAST_MAC_ADDRESS =
             {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff };
     // TODO: Make these offsets relative to end of link-layer header; don't include ETH_HEADER_LEN.
@@ -236,6 +237,7 @@
     private final IpManager.Callback mIpManagerCallback;
     private final NetworkInterface mNetworkInterface;
     private final IpConnectivityLog mMetricsLog;
+
     @VisibleForTesting
     byte[] mHardwareAddress;
     @VisibleForTesting
@@ -244,6 +246,7 @@
     private long mUniqueCounter;
     @GuardedBy("this")
     private boolean mMulticastFilter;
+    private final boolean mDrop802_3Frames;
     // Our IPv4 address, if we have just one, otherwise null.
     @GuardedBy("this")
     private byte[] mIPv4Address;
@@ -253,11 +256,13 @@
 
     @VisibleForTesting
     ApfFilter(ApfCapabilities apfCapabilities, NetworkInterface networkInterface,
-            IpManager.Callback ipManagerCallback, boolean multicastFilter, IpConnectivityLog log) {
+            IpManager.Callback ipManagerCallback, boolean multicastFilter,
+            boolean ieee802_3Filter, IpConnectivityLog log) {
         mApfCapabilities = apfCapabilities;
         mIpManagerCallback = ipManagerCallback;
         mNetworkInterface = networkInterface;
         mMulticastFilter = multicastFilter;
+        mDrop802_3Frames = ieee802_3Filter;
         mMetricsLog = log;
 
         // TODO: ApfFilter should not generate programs until IpManager sends provisioning success.
@@ -885,6 +890,7 @@
     /**
      * Begin generating an APF program to:
      * <ul>
+     * <li>Drop/Pass 802.3 frames (based on policy)
      * <li>Drop ARP requests not for us, if mIPv4Address is set,
      * <li>Drop IPv4 broadcast packets, except DHCP destined to our MAC,
      * <li>Drop IPv4 multicast packets, if mMulticastFilter,
@@ -906,6 +912,8 @@
 
         // Here's a basic summary of what the initial program does:
         //
+        // if it's a 802.3 Frame (ethtype < 0x0600):
+        //    drop or pass based on configurations
         // if it's ARP:
         //   insert ARP filter to drop or pass these appropriately
         // if it's IPv4:
@@ -916,9 +924,15 @@
         //   pass
         // insert IPv6 filter to drop, pass, or fall off the end for ICMPv6 packets
 
+        gen.addLoad16(Register.R0, ETH_ETHERTYPE_OFFSET);
+
+        if (mDrop802_3Frames) {
+            // drop 802.3 frames (ethtype < 0x0600)
+            gen.addJumpIfR0LessThan(ETH_TYPE_MIN, gen.DROP_LABEL);
+        }
+
         // Add ARP filters:
         String skipArpFiltersLabel = "skipArpFilters";
-        gen.addLoad16(Register.R0, ETH_ETHERTYPE_OFFSET);
         gen.addJumpIfR0NotEquals(ETH_P_ARP, skipArpFiltersLabel);
         generateArpFilterLocked(gen);
         gen.defineLabel(skipArpFiltersLabel);
@@ -1101,7 +1115,7 @@
      */
     public static ApfFilter maybeCreate(ApfCapabilities apfCapabilities,
             NetworkInterface networkInterface, IpManager.Callback ipManagerCallback,
-            boolean multicastFilter) {
+            boolean multicastFilter, boolean ieee802_3Filter) {
         if (apfCapabilities == null || networkInterface == null) return null;
         if (apfCapabilities.apfVersionSupported == 0) return null;
         if (apfCapabilities.maximumApfProgramSize < 512) {
@@ -1118,7 +1132,7 @@
             return null;
         }
         return new ApfFilter(apfCapabilities, networkInterface, ipManagerCallback,
-                multicastFilter, new IpConnectivityLog());
+                multicastFilter, ieee802_3Filter, new IpConnectivityLog());
     }
 
     public synchronized void shutdown() {
diff --git a/services/net/java/android/net/ip/IpManager.java b/services/net/java/android/net/ip/IpManager.java
index 5aaec9e..46c1292 100644
--- a/services/net/java/android/net/ip/IpManager.java
+++ b/services/net/java/android/net/ip/IpManager.java
@@ -51,6 +51,7 @@
 import android.util.SparseArray;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.R;
 import com.android.internal.util.IndentingPrintWriter;
 import com.android.internal.util.IState;
 import com.android.internal.util.Preconditions;
@@ -1418,8 +1419,12 @@
 
         @Override
         public void enter() {
+            // Get the Configuration for ApfFilter from Context
+            boolean filter802_3Frames =
+                    mContext.getResources().getBoolean(R.bool.config_apfDrop802_3Frames);
+
             mApfFilter = ApfFilter.maybeCreate(mConfiguration.mApfCapabilities, mNetworkInterface,
-                    mCallback, mMulticastFiltering);
+                    mCallback, mMulticastFiltering, filter802_3Frames);
             // TODO: investigate the effects of any multicast filtering racing/interfering with the
             // rest of this IP configuration startup.
             if (mApfFilter == null) {
diff --git a/services/tests/notification/src/com/android/server/notification/ManagedServicesTest.java b/services/tests/notification/src/com/android/server/notification/ManagedServicesTest.java
index ffbd8d4..bd65f57 100644
--- a/services/tests/notification/src/com/android/server/notification/ManagedServicesTest.java
+++ b/services/tests/notification/src/com/android/server/notification/ManagedServicesTest.java
@@ -170,7 +170,7 @@
                     null);
             writeExpectedValuesToSettings(approvalLevel);
 
-            assertTrue(service.readXml(parser));
+            service.migrateToXml();
 
             verifyExpectedApprovedEntries(service);
         }
@@ -182,7 +182,7 @@
             ManagedServices service = new TestManagedServices(getContext(), mLock, mUserProfiles,
                     mIpm, approvalLevel);
 
-            assertFalse(loadXml(service));
+            loadXml(service);
 
             verifyExpectedApprovedEntries(service);
         }
@@ -239,7 +239,7 @@
             parser.setInput(new BufferedInputStream(
                     new ByteArrayInputStream(baos.toByteArray())), null);
             parser.nextTag();
-            assertFalse(service.readXml(parser));
+            service.readXml(parser);
 
             verifyExpectedApprovedEntries(service);
             assertFalse(service.isPackageOrComponentAllowed("this.is.a.package.name", 0));
@@ -341,11 +341,8 @@
         for (int approvalLevel : new int[] {APPROVAL_BY_COMPONENT, APPROVAL_BY_PACKAGE}) {
             ManagedServices service = new TestManagedServices(getContext(), mLock, mUserProfiles,
                     mIpm, approvalLevel);
-            XmlPullParser parser = Xml.newPullParser();
-            parser.setInput(new BufferedInputStream(new ByteArrayInputStream(new byte[]{})),
-                    null);
             writeExpectedValuesToSettings(approvalLevel);
-            service.readXml(parser);
+            service.migrateToXml();
 
             mExpectedPrimaryPackages.put(0, "another.package");
             mExpectedPrimaryComponentNames.put(0, "another.package/B1");
@@ -360,11 +357,8 @@
         for (int approvalLevel : new int[] {APPROVAL_BY_COMPONENT, APPROVAL_BY_PACKAGE}) {
             ManagedServices service = new TestManagedServices(getContext(), mLock, mUserProfiles,
                     mIpm, approvalLevel);
-            XmlPullParser parser = Xml.newPullParser();
-            parser.setInput(new BufferedInputStream(new ByteArrayInputStream(new byte[]{})),
-                    null);
             writeExpectedValuesToSettings(approvalLevel);
-            service.readXml(parser);
+            service.migrateToXml();
 
             mExpectedSecondaryComponentNames.put(10, "component/2");
             mExpectedSecondaryPackages.put(10, "component");
@@ -516,9 +510,9 @@
         assertEquals(0, service.getAllowedComponents(10).size());
     }
 
-    private boolean loadXml(ManagedServices service) throws Exception {
+    private void loadXml(ManagedServices service) throws Exception {
         final StringBuffer xml = new StringBuffer();
-        xml.append("<" + service.getConfig().managedServiceTypeTag + ">\n");
+        xml.append("<" + service.getConfig().xmlTag + ">\n");
         for (int userId : mExpectedPrimary.get(service.mApprovalLevel).keySet()) {
             xml.append(getXmlEntry(
                     mExpectedPrimary.get(service.mApprovalLevel).get(userId), userId, true));
@@ -527,13 +521,13 @@
             xml.append(getXmlEntry(
                     mExpectedSecondary.get(service.mApprovalLevel).get(userId), userId, false));
         }
-        xml.append("</" + service.getConfig().managedServiceTypeTag + ">");
+        xml.append("</" + service.getConfig().xmlTag + ">");
 
         XmlPullParser parser = Xml.newPullParser();
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(xml.toString().getBytes())), null);
         parser.nextTag();
-        return service.readXml(parser);
+        service.readXml(parser);
     }
 
     private void addExpectedServices(final ManagedServices service, final List<String> packages,
@@ -674,7 +668,7 @@
         @Override
         protected Config getConfig() {
             final Config c = new Config();
-            c.managedServiceTypeTag= "test";
+            c.xmlTag = "test";
             c.secureSettingName = SETTING;
             c.secondarySettingName = SECONDARY_SETTING;
             c.bindPermission = "permission";
diff --git a/services/tests/notification/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/notification/src/com/android/server/notification/NotificationManagerServiceTest.java
index ae2253e..ed94917 100644
--- a/services/tests/notification/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/notification/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -20,9 +20,6 @@
 import static android.app.NotificationManager.IMPORTANCE_NONE;
 import static android.content.pm.PackageManager.PERMISSION_DENIED;
 
-import static com.android.server.notification.NotificationManagerService
-        .MESSAGE_SEND_RANKING_UPDATE;
-
 import static junit.framework.Assert.assertEquals;
 import static junit.framework.Assert.assertFalse;
 import static junit.framework.Assert.assertTrue;
@@ -34,12 +31,10 @@
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -60,35 +55,34 @@
 import android.graphics.Color;
 import android.media.AudioManager;
 import android.os.Binder;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
 import android.os.Process;
 import android.os.UserHandle;
 import android.provider.Settings.Secure;
 import android.service.notification.NotificationListenerService;
 import android.service.notification.StatusBarNotification;
+import android.service.notification.ZenModeConfig;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.util.ArrayMap;
 import android.util.AtomicFile;
-import android.util.Log;
-import android.util.Slog;
 
 import com.android.server.lights.Light;
 import com.android.server.lights.LightsManager;
+import com.android.server.notification.NotificationManagerService.NotificationAssistants;
+import com.android.server.notification.NotificationManagerService.NotificationListeners;
 
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 import org.mockito.stubbing.Answer;
 
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
@@ -115,7 +109,6 @@
     private TestableLooper mTestableLooper;
     @Mock
     private RankingHelper mRankingHelper;
-    @Mock
     AtomicFile mPolicyFile;
     File mFile;
     @Mock
@@ -129,8 +122,8 @@
     private NotificationChannel mTestNotificationChannel = new NotificationChannel(
             TEST_CHANNEL_ID, TEST_CHANNEL_ID, NotificationManager.IMPORTANCE_DEFAULT);
     @Mock
-    private NotificationManagerService.NotificationListeners mNotificationListeners;
-    @Mock private NotificationManagerService.NotificationAssistants mNotificationAssistants;
+    private NotificationListeners mListeners;
+    @Mock private NotificationAssistants mAssistants;
     @Mock private ConditionProviders mConditionProviders;
     private ManagedServices.ManagedServiceInfo mListener;
     @Mock private ICompanionDeviceManager mCompanionMgr;
@@ -182,18 +175,34 @@
         when(mockLightsManager.getLight(anyInt())).thenReturn(mock(Light.class));
         when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_NORMAL);
 
+        // write to a test file; the system file isn't readable from tests
         mFile = new File(mContext.getCacheDir(), "test.xml");
         mFile.createNewFile();
-        when(mPolicyFile.openRead()).thenReturn(new FileInputStream(mFile));
-        when(mPolicyFile.startWrite()).thenReturn(new FileOutputStream(mFile));
+        final String preupgradeXml = "<notification-policy></notification-policy>";
+        mPolicyFile = new AtomicFile(mFile);
+        FileOutputStream fos = mPolicyFile.startWrite();
+        fos.write(preupgradeXml.getBytes());
+        mPolicyFile.finishWrite(fos);
+        FileInputStream fStream = new FileInputStream(mFile);
 
-        mListener = mNotificationListeners.new ManagedServiceInfo(
+        // Setup managed services
+        mListener = mListeners.new ManagedServiceInfo(
                 null, new ComponentName(PKG, "test_class"), uid, true, null, 0);
-        when(mNotificationListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
+        when(mListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
+        ManagedServices.Config listenerConfig = new ManagedServices.Config();
+        listenerConfig.xmlTag = NotificationListeners.TAG_ENABLED_NOTIFICATION_LISTENERS;
+        when(mListeners.getConfig()).thenReturn(listenerConfig);
+        ManagedServices.Config assistantConfig = new ManagedServices.Config();
+        assistantConfig.xmlTag = NotificationAssistants.TAG_ENABLED_NOTIFICATION_ASSISTANTS;
+        when(mAssistants.getConfig()).thenReturn(assistantConfig);
+        ManagedServices.Config dndConfig = new ManagedServices.Config();
+        dndConfig.xmlTag = ConditionProviders.TAG_ENABLED_DND_APPS;
+        when(mConditionProviders.getConfig()).thenReturn(dndConfig);
+
         try {
             mNotificationManagerService.init(mTestableLooper.getLooper(),
                     mPackageManager, mPackageManagerClient, mockLightsManager,
-                    mNotificationListeners, mNotificationAssistants, mConditionProviders,
+                    mListeners, mAssistants, mConditionProviders,
                     mCompanionMgr, mSnoozeHelper, mUsageStats, mPolicyFile, mActivityManager,
                     mGroupHelper);
         } catch (SecurityException e) {
@@ -786,13 +795,13 @@
                 eq(channel2.getId()), anyBoolean()))
                 .thenReturn(channel2);
 
-        reset(mNotificationListeners);
+        reset(mListeners);
         mBinderService.createNotificationChannels(PKG,
                 new ParceledListSlice(Arrays.asList(mTestNotificationChannel, channel2)));
-        verify(mNotificationListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
+        verify(mListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
                 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
                 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_ADDED));
-        verify(mNotificationListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
+        verify(mListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
                 eq(Process.myUserHandle()), eq(channel2),
                 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_ADDED));
     }
@@ -806,13 +815,13 @@
         NotificationChannelGroup group1 = new NotificationChannelGroup("a", "b");
         NotificationChannelGroup group2 = new NotificationChannelGroup("n", "m");
 
-        reset(mNotificationListeners);
+        reset(mListeners);
         mBinderService.createNotificationChannelGroups(PKG,
                 new ParceledListSlice(Arrays.asList(group1, group2)));
-        verify(mNotificationListeners, times(1)).notifyNotificationChannelGroupChanged(eq(PKG),
+        verify(mListeners, times(1)).notifyNotificationChannelGroupChanged(eq(PKG),
                 eq(Process.myUserHandle()), eq(group1),
                 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_ADDED));
-        verify(mNotificationListeners, times(1)).notifyNotificationChannelGroupChanged(eq(PKG),
+        verify(mListeners, times(1)).notifyNotificationChannelGroupChanged(eq(PKG),
                 eq(Process.myUserHandle()), eq(group2),
                 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_ADDED));
     }
@@ -828,9 +837,9 @@
                 eq(mTestNotificationChannel.getId()), anyBoolean()))
                 .thenReturn(mTestNotificationChannel);
 
-        reset(mNotificationListeners);
+        reset(mListeners);
         mBinderService.updateNotificationChannelForPackage(PKG, 0, mTestNotificationChannel);
-        verify(mNotificationListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
+        verify(mListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
                 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
                 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED));
     }
@@ -844,9 +853,9 @@
         when(mRankingHelper.getNotificationChannel(eq(PKG), anyInt(),
                 eq(mTestNotificationChannel.getId()), anyBoolean()))
                 .thenReturn(mTestNotificationChannel);
-        reset(mNotificationListeners);
+        reset(mListeners);
         mBinderService.deleteNotificationChannel(PKG, mTestNotificationChannel.getId());
-        verify(mNotificationListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
+        verify(mListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
                 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
                 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_DELETED));
     }
@@ -860,9 +869,9 @@
         mNotificationManagerService.setRankingHelper(mRankingHelper);
         when(mRankingHelper.getNotificationChannelGroup(eq(ncg.getId()), eq(PKG), anyInt()))
                 .thenReturn(ncg);
-        reset(mNotificationListeners);
+        reset(mListeners);
         mBinderService.deleteNotificationChannelGroup(PKG, ncg.getId());
-        verify(mNotificationListeners, times(1)).notifyNotificationChannelGroupChanged(eq(PKG),
+        verify(mListeners, times(1)).notifyNotificationChannelGroupChanged(eq(PKG),
                 eq(Process.myUserHandle()), eq(ncg),
                 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_DELETED));
     }
@@ -879,7 +888,7 @@
 
         verify(mRankingHelper, times(1)).updateNotificationChannel(anyString(), anyInt(), any());
 
-        verify(mNotificationListeners, never()).notifyNotificationChannelChanged(eq(PKG),
+        verify(mListeners, never()).notifyNotificationChannelChanged(eq(PKG),
                 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
                 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED));
     }
@@ -900,7 +909,7 @@
 
         verify(mRankingHelper, never()).updateNotificationChannel(anyString(), anyInt(), any());
 
-        verify(mNotificationListeners, never()).notifyNotificationChannelChanged(eq(PKG),
+        verify(mListeners, never()).notifyNotificationChannelChanged(eq(PKG),
                 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
                 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED));
     }
@@ -914,7 +923,7 @@
         mListener = mock(ManagedServices.ManagedServiceInfo.class);
         mListener.component = new ComponentName(PKG, PKG);
         when(mListener.enabledAndUserMatches(anyInt())).thenReturn(false);
-        when(mNotificationListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
+        when(mListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
 
         try {
             mBinderService.updateNotificationChannelFromPrivilegedListener(
@@ -926,7 +935,7 @@
 
         verify(mRankingHelper, never()).updateNotificationChannel(anyString(), anyInt(), any());
 
-        verify(mNotificationListeners, never()).notifyNotificationChannelChanged(eq(PKG),
+        verify(mListeners, never()).notifyNotificationChannelChanged(eq(PKG),
                 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
                 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED));
     }
@@ -971,7 +980,7 @@
         when(mCompanionMgr.getAssociations(PKG, uid)).thenReturn(associations);
         mListener = mock(ManagedServices.ManagedServiceInfo.class);
         when(mListener.enabledAndUserMatches(anyInt())).thenReturn(false);
-        when(mNotificationListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
+        when(mListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
 
         try {
             mBinderService.getNotificationChannelsFromPrivilegedListener(
@@ -1022,7 +1031,7 @@
         when(mCompanionMgr.getAssociations(PKG, uid)).thenReturn(associations);
         mListener = mock(ManagedServices.ManagedServiceInfo.class);
         when(mListener.enabledAndUserMatches(anyInt())).thenReturn(false);
-        when(mNotificationListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
+        when(mListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
 
         try {
             mBinderService.getNotificationChannelGroupsFromPrivilegedListener(
@@ -1191,11 +1200,11 @@
             }
         }
 
-        verify(mNotificationListeners, times(1)).setPackageOrComponentEnabled(
+        verify(mListeners, times(1)).setPackageOrComponentEnabled(
                 c.flattenToString(), 0, true, true);
         verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
                 c.flattenToString(), 0, false, true);
-        verify(mNotificationAssistants, never()).setPackageOrComponentEnabled(
+        verify(mAssistants, never()).setPackageOrComponentEnabled(
                 any(), anyInt(), anyBoolean(), anyBoolean());
     }
 
@@ -1210,11 +1219,11 @@
             }
         }
 
-        verify(mNotificationAssistants, times(1)).setPackageOrComponentEnabled(
+        verify(mAssistants, times(1)).setPackageOrComponentEnabled(
                 c.flattenToString(), 0, true, true);
         verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
                 c.flattenToString(), 0, false, true);
-        verify(mNotificationListeners, never()).setPackageOrComponentEnabled(
+        verify(mListeners, never()).setPackageOrComponentEnabled(
                 any(), anyInt(), anyBoolean(), anyBoolean());
     }
 
@@ -1231,9 +1240,9 @@
 
         verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
                 c.getPackageName(), 0, true, true);
-        verify(mNotificationAssistants, never()).setPackageOrComponentEnabled(
+        verify(mAssistants, never()).setPackageOrComponentEnabled(
                 any(), anyInt(), anyBoolean(), anyBoolean());
-        verify(mNotificationListeners, never()).setPackageOrComponentEnabled(
+        verify(mListeners, never()).setPackageOrComponentEnabled(
                 any(), anyInt(), anyBoolean(), anyBoolean());
     }
 
@@ -1243,11 +1252,11 @@
         ComponentName c = ComponentName.unflattenFromString("package/Component");
         mBinderService.setNotificationListenerAccessGranted(c, true);
 
-        verify(mNotificationListeners, never()).setPackageOrComponentEnabled(
+        verify(mListeners, never()).setPackageOrComponentEnabled(
                 c.flattenToString(), 0, true, true);
         verify(mConditionProviders, never()).setPackageOrComponentEnabled(
                 c.flattenToString(), 0, false, true);
-        verify(mNotificationAssistants, never()).setPackageOrComponentEnabled(
+        verify(mAssistants, never()).setPackageOrComponentEnabled(
                 any(), anyInt(), anyBoolean(), anyBoolean());
     }
 
@@ -1258,11 +1267,11 @@
         mBinderService.setNotificationAssistantAccessGranted(c, true);
 
 
-        verify(mNotificationListeners, never()).setPackageOrComponentEnabled(
+        verify(mListeners, never()).setPackageOrComponentEnabled(
                 c.flattenToString(), 0, true, true);
         verify(mConditionProviders, never()).setPackageOrComponentEnabled(
                 c.flattenToString(), 0, false, true);
-        verify(mNotificationAssistants, never()).setPackageOrComponentEnabled(
+        verify(mAssistants, never()).setPackageOrComponentEnabled(
                 any(), anyInt(), anyBoolean(), anyBoolean());
     }
 
@@ -1272,11 +1281,11 @@
         ComponentName c = ComponentName.unflattenFromString("package/Component");
         mBinderService.setNotificationPolicyAccessGranted(c.getPackageName(), true);
 
-        verify(mNotificationListeners, never()).setPackageOrComponentEnabled(
+        verify(mListeners, never()).setPackageOrComponentEnabled(
                 c.flattenToString(), 0, true, true);
         verify(mConditionProviders, never()).setPackageOrComponentEnabled(
                 c.flattenToString(), 0, false, true);
-        verify(mNotificationAssistants, never()).setPackageOrComponentEnabled(
+        verify(mAssistants, never()).setPackageOrComponentEnabled(
                 any(), anyInt(), anyBoolean(), anyBoolean());
     }
 
@@ -1427,4 +1436,50 @@
         mNotificationManagerService.handleRankingSort();
         verify(handler, never()).scheduleSendRankingUpdate();
     }
+
+    @Test
+    public void testReadPolicyXml_readApprovedServicesFromXml() throws Exception {
+        final String preupgradeXml = "<notification-policy version=\"1\">"
+                + "<zen></zen>"
+                + "<ranking></ranking>"
+                + "<enabled_listeners>"
+                + "<service_listing approved=\"test\" user=\"0\" primary=\"true\" />"
+                + "</enabled_listeners>"
+                + "<enabled_assistants>"
+                + "<service_listing approved=\"test\" user=\"0\" primary=\"true\" />"
+                + "</enabled_assistants>"
+                + "<dnd_apps>"
+                + "<service_listing approved=\"test\" user=\"0\" primary=\"true\" />"
+                + "</dnd_apps>"
+                + "</notification-policy>";
+        mNotificationManagerService.readPolicyXml(
+                new BufferedInputStream(new ByteArrayInputStream(preupgradeXml.getBytes())), false);
+        verify(mListeners, times(1)).readXml(any());
+        verify(mConditionProviders, times(1)).readXml(any());
+        verify(mAssistants, times(1)).readXml(any());
+
+        // numbers are inflated for setup
+        verify(mListeners, times(1)).migrateToXml();
+        verify(mConditionProviders, times(1)).migrateToXml();
+        verify(mAssistants, times(1)).migrateToXml();
+    }
+
+    @Test
+    public void testReadPolicyXml_readApprovedServicesFromSettings() throws Exception {
+        final String preupgradeXml = "<notification-policy version=\"1\">"
+                + "<zen></zen>"
+                + "<ranking></ranking>"
+                + "</notification-policy>";
+        mNotificationManagerService.readPolicyXml(
+                new BufferedInputStream(new ByteArrayInputStream(preupgradeXml.getBytes())), false);
+        verify(mListeners, never()).readXml(any());
+        verify(mConditionProviders, never()).readXml(any());
+        verify(mAssistants, never()).readXml(any());
+
+        // numbers are inflated for setup
+        verify(mListeners, times(2)).migrateToXml();
+        verify(mConditionProviders, times(2)).migrateToXml();
+        verify(mAssistants, times(2)).migrateToXml();
+    }
+
 }
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityTestsBase.java b/services/tests/servicestests/src/com/android/server/am/ActivityTestsBase.java
index 16bc011..04b5bde 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityTestsBase.java
+++ b/services/tests/servicestests/src/com/android/server/am/ActivityTestsBase.java
@@ -16,6 +16,7 @@
 
 package com.android.server.am;
 
+import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.any;
@@ -78,7 +79,7 @@
             int stackId, int displayId, boolean onTop) {
         if (service.mStackSupervisor instanceof TestActivityStackSupervisor) {
             return ((TestActivityStackSupervisor) service.mStackSupervisor)
-                    .createTestStack(service, stackId, onTop);
+                    .createTestStack(stackId, onTop);
         }
 
         return null;
@@ -96,8 +97,7 @@
                 0 /* launchedFromPid */, 0, null, intent, null,
                 aInfo /*aInfo*/, new Configuration(), null /* resultTo */, null /* resultWho */,
                 0 /* reqCode */, false /*componentSpecified*/, false /* rootVoiceInteraction */,
-                service.mStackSupervisor, null /* container */, null /* options */,
-                null /* sourceRecord */);
+                service.mStackSupervisor, null /* options */, null /* sourceRecord */);
         activity.mWindowContainerController = mock(AppWindowContainerController.class);
 
         if (task != null) {
@@ -187,12 +187,24 @@
                 boolean preserveWindows) {
         }
 
-        public <T extends ActivityStack> T createTestStack(ActivityManagerService service,
-                int stackId, boolean onTop) {
-            final TestActivityContainer container =
-                    new TestActivityContainer(service, stackId, mDisplay, onTop);
-            mActivityContainers.put(stackId, container);
-            return (T) container.getStack();
+        <T extends ActivityStack> T createTestStack(int stackId, boolean onTop) {
+            return (T) createStack(stackId, mDisplay, onTop);
+        }
+
+        @Override
+        ActivityStack createStack(int stackId, ActivityDisplay display, boolean onTop) {
+            final RecentTasks recents =
+                    new RecentTasks(mService, mService.mStackSupervisor);
+            if (stackId == PINNED_STACK_ID) {
+                return new PinnedActivityStack(display, stackId, this, recents, onTop) {
+                    @Override
+                    Rect getDefaultPictureInPictureBounds(float aspectRatio) {
+                        return new Rect(50, 50, 100, 100);
+                    }
+                };
+            } else {
+                return new TestActivityStack(display, stackId, this, recents, onTop);
+            }
         }
 
         @Override
@@ -204,49 +216,7 @@
                 return stack;
             }
 
-            return createTestStack(mService, stackId, createOnTop);
-        }
-
-        private class TestActivityContainer extends ActivityContainer {
-            private final ActivityManagerService mService;
-
-            private boolean mOnTop;
-            private int mStackId;
-            private ActivityStack mStack;
-
-            TestActivityContainer(ActivityManagerService service, int stackId,
-                    ActivityDisplay activityDisplay, boolean onTop) {
-                super(stackId, activityDisplay, onTop);
-                mService = service;
-            }
-
-            @Override
-            protected void createStack(int stackId, boolean onTop) {
-                // normally stack creation is done here. However we need to do it on demand since
-                // we cannot set {@link mService} by the time the super constructor calling this
-                // method is invoked.
-                mOnTop = onTop;
-                mStackId = stackId;
-            }
-
-            public ActivityStack getStack() {
-                if (mStack == null) {
-                    final RecentTasks recents =
-                            new RecentTasks(mService, mService.mStackSupervisor);
-                    if (mStackId == ActivityManager.StackId.PINNED_STACK_ID) {
-                        mStack = new PinnedActivityStack(this, recents, mOnTop) {
-                            @Override
-                            Rect getDefaultPictureInPictureBounds(float aspectRatio) {
-                                return new Rect(50, 50, 100, 100);
-                            }
-                        };
-                    } else {
-                        mStack = new TestActivityStack(this, recents, mOnTop);
-                    }
-                }
-
-                return mStack;
-            }
+            return createTestStack(stackId, createOnTop);
         }
     }
 
@@ -277,9 +247,9 @@
             extends ActivityStack<T> implements ActivityStackReporter {
         private int mOnActivityRemovedFromStackCount = 0;
         private T mContainerController;
-        TestActivityStack(ActivityStackSupervisor.ActivityContainer activityContainer,
-                RecentTasks recentTasks, boolean onTop) {
-            super(activityContainer, recentTasks, onTop);
+        TestActivityStack(ActivityStackSupervisor.ActivityDisplay display, int stackId,
+                ActivityStackSupervisor supervisor, RecentTasks recentTasks, boolean onTop) {
+            super(display, stackId, supervisor, recentTasks, onTop);
         }
 
         @Override
diff --git a/services/tests/servicestests/src/com/android/server/pm/dex/DexoptOptionsTests.java b/services/tests/servicestests/src/com/android/server/pm/dex/DexoptOptionsTests.java
new file mode 100644
index 0000000..1eb5552
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/pm/dex/DexoptOptionsTests.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.server.pm.dex;
+
+
+import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
+
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import com.android.server.pm.PackageManagerService;
+import com.android.server.pm.PackageManagerServiceCompilerMapping;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class DexoptOptionsTests {
+    private final static String mPackageName = "test.android.com";
+    private final static String mCompilerFilter =
+            PackageManagerServiceCompilerMapping.getDefaultCompilerFilter();
+    private final static String mSplitName = "split-A.apk";
+
+    @Test
+    public void testCreateDexoptOptionsEmpty() {
+        DexoptOptions opt = new DexoptOptions(mPackageName, mCompilerFilter, /*flags*/ 0);
+        assertEquals(mPackageName, opt.getPackageName());
+        assertEquals(mCompilerFilter, opt.getCompilerFilter());
+        assertEquals(null, opt.getSplitName());
+        assertFalse(opt.isBootComplete());
+        assertFalse(opt.isCheckForProfileUpdates());
+        assertFalse(opt.isDexoptOnlySecondaryDex());
+        assertFalse(opt.isDexoptOnlySharedDex());
+        assertFalse(opt.isDowngrade());
+        assertFalse(opt.isForce());
+    }
+
+    @Test
+    public void testCreateDexoptOptionsFull() {
+        int flags =
+                DexoptOptions.DEXOPT_FORCE |
+                DexoptOptions.DEXOPT_BOOT_COMPLETE |
+                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
+                DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
+                DexoptOptions.DEXOPT_ONLY_SHARED_DEX |
+                DexoptOptions.DEXOPT_DOWNGRADE;
+
+        DexoptOptions opt = new DexoptOptions(mPackageName, mCompilerFilter, flags);
+        assertEquals(mPackageName, opt.getPackageName());
+        assertEquals(mCompilerFilter, opt.getCompilerFilter());
+        assertEquals(null, opt.getSplitName());
+        assertTrue(opt.isBootComplete());
+        assertTrue(opt.isCheckForProfileUpdates());
+        assertTrue(opt.isDexoptOnlySecondaryDex());
+        assertTrue(opt.isDexoptOnlySharedDex());
+        assertTrue(opt.isDowngrade());
+        assertTrue(opt.isForce());
+    }
+
+    @Test
+    public void testCreateDexoptOptionsReason() {
+        int flags =
+                DexoptOptions.DEXOPT_FORCE |
+                DexoptOptions.DEXOPT_BOOT_COMPLETE |
+                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES;
+
+        int[] reasons = new int[] {
+                PackageManagerService.REASON_FIRST_BOOT,
+                PackageManagerService.REASON_BOOT,
+                PackageManagerService.REASON_INSTALL,
+                PackageManagerService.REASON_BACKGROUND_DEXOPT,
+                PackageManagerService.REASON_AB_OTA,
+                PackageManagerService.REASON_INACTIVE_PACKAGE_DOWNGRADE};
+
+        for (int reason : reasons) {
+            DexoptOptions opt = new DexoptOptions(mPackageName, reason, flags);
+            assertEquals(mPackageName, opt.getPackageName());
+            assertEquals(getCompilerFilterForReason(reason), opt.getCompilerFilter());
+            assertEquals(null, opt.getSplitName());
+            assertTrue(opt.isBootComplete());
+            assertTrue(opt.isCheckForProfileUpdates());
+            assertFalse(opt.isDexoptOnlySecondaryDex());
+            assertFalse(opt.isDexoptOnlySharedDex());
+            assertFalse(opt.isDowngrade());
+            assertTrue(opt.isForce());
+        }
+    }
+
+    @Test
+    public void testCreateDexoptOptionsSplit() {
+        int flags = DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE;
+
+        DexoptOptions opt = new DexoptOptions(mPackageName, mCompilerFilter, mSplitName, flags);
+        assertEquals(mPackageName, opt.getPackageName());
+        assertEquals(mCompilerFilter, opt.getCompilerFilter());
+        assertEquals(mSplitName, opt.getSplitName());
+        assertTrue(opt.isBootComplete());
+        assertFalse(opt.isCheckForProfileUpdates());
+        assertFalse(opt.isDexoptOnlySecondaryDex());
+        assertFalse(opt.isDexoptOnlySharedDex());
+        assertFalse(opt.isDowngrade());
+        assertTrue(opt.isForce());
+    }
+
+    @Test
+    public void testCreateDexoptInvalid() {
+        boolean gotException = false;
+        try {
+            int invalidFlags = 999;
+            new DexoptOptions(mPackageName, mCompilerFilter, invalidFlags);
+        } catch (IllegalArgumentException ignore) {
+            gotException = true;
+        }
+
+        assertTrue(gotException);
+    }
+}
\ No newline at end of file
diff --git a/services/tests/servicestests/src/com/android/server/pm/dex/DexoptUtilsTest.java b/services/tests/servicestests/src/com/android/server/pm/dex/DexoptUtilsTest.java
new file mode 100644
index 0000000..47918ea
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/pm/dex/DexoptUtilsTest.java
@@ -0,0 +1,213 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.server.pm.dex;
+
+import static org.junit.Assert.assertEquals;
+
+import android.content.pm.ApplicationInfo;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.util.SparseArray;
+
+import dalvik.system.DelegateLastClassLoader;
+import dalvik.system.PathClassLoader;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class DexoptUtilsTest {
+    private static final String PATH_CLASS_LOADER_NAME = PathClassLoader.class.getName();
+    private static final String DELEGATE_LAST_CLASS_LOADER_NAME =
+            DelegateLastClassLoader.class.getName();
+
+    private ApplicationInfo createMockApplicationInfo(String baseClassLoader, boolean addSplits,
+            boolean addSplitDependencies) {
+        ApplicationInfo ai = new ApplicationInfo();
+        String codeDir = "/data/app/mock.android.com";
+        ai.setBaseCodePath(codeDir + "/base.dex");
+        ai.classLoaderName = baseClassLoader;
+        ai.privateFlags = ai.privateFlags | ApplicationInfo.PRIVATE_FLAG_ISOLATED_SPLIT_LOADING;
+
+        if (addSplits) {
+            ai.setSplitCodePaths(new String[]{
+                    codeDir + "/base-1.dex",
+                    codeDir + "/base-2.dex",
+                    codeDir + "/base-3.dex",
+                    codeDir + "/base-4.dex",
+                    codeDir + "/base-5.dex",
+                    codeDir + "/base-6.dex"});
+
+            ai.splitClassLoaderNames = new String[]{
+                    DELEGATE_LAST_CLASS_LOADER_NAME,
+                    DELEGATE_LAST_CLASS_LOADER_NAME,
+                    PATH_CLASS_LOADER_NAME,
+                    PATH_CLASS_LOADER_NAME,
+                    PATH_CLASS_LOADER_NAME,
+                    null};  // A null class loader name should default to PathClassLoader.
+            if (addSplitDependencies) {
+                ai.splitDependencies = new SparseArray<>(ai.splitClassLoaderNames.length + 1);
+                ai.splitDependencies.put(0, new int[] {-1}); // base has no dependency
+                ai.splitDependencies.put(1, new int[] {2}); // split 1 depends on 2
+                ai.splitDependencies.put(2, new int[] {4}); // split 2 depends on 4
+                ai.splitDependencies.put(3, new int[] {4}); // split 3 depends on 4
+                ai.splitDependencies.put(4, new int[] {0}); // split 4 depends on base
+                ai.splitDependencies.put(5, new int[] {0}); // split 5 depends on base
+                ai.splitDependencies.put(6, new int[] {5}); // split 6 depends on 5
+            }
+        }
+        return ai;
+    }
+
+    @Test
+    public void testSplitChain() {
+        ApplicationInfo ai = createMockApplicationInfo(PATH_CLASS_LOADER_NAME, true, true);
+        String[] sharedLibrary = new String[] {"a.dex", "b.dex"};
+        String[] contexts = DexoptUtils.getClassLoaderContexts(ai, sharedLibrary);
+
+        assertEquals(7, contexts.length);
+        assertEquals("PCL[a.dex:b.dex]", contexts[0]);
+        assertEquals("DLC[];DLC[base-2.dex];PCL[base-4.dex];PCL[a.dex:b.dex:base.dex]",
+                contexts[1]);
+        assertEquals("DLC[];PCL[base-4.dex];PCL[a.dex:b.dex:base.dex]", contexts[2]);
+        assertEquals("PCL[];PCL[base-4.dex];PCL[a.dex:b.dex:base.dex]", contexts[3]);
+        assertEquals("PCL[];PCL[a.dex:b.dex:base.dex]", contexts[4]);
+        assertEquals("PCL[];PCL[a.dex:b.dex:base.dex]", contexts[5]);
+        assertEquals("PCL[];PCL[base-5.dex];PCL[a.dex:b.dex:base.dex]", contexts[6]);
+    }
+
+    @Test
+    public void testSplitChainNoSplitDependencies() {
+        ApplicationInfo ai = createMockApplicationInfo(PATH_CLASS_LOADER_NAME, true, false);
+        String[] sharedLibrary = new String[] {"a.dex", "b.dex"};
+        String[] contexts = DexoptUtils.getClassLoaderContexts(ai, sharedLibrary);
+
+        assertEquals(7, contexts.length);
+        assertEquals("PCL[a.dex:b.dex]", contexts[0]);
+        assertEquals("PCL[a.dex:b.dex:base.dex]", contexts[1]);
+        assertEquals("PCL[a.dex:b.dex:base.dex:base-1.dex]", contexts[2]);
+        assertEquals("PCL[a.dex:b.dex:base.dex:base-1.dex:base-2.dex]", contexts[3]);
+        assertEquals("PCL[a.dex:b.dex:base.dex:base-1.dex:base-2.dex:base-3.dex]", contexts[4]);
+        assertEquals(
+                "PCL[a.dex:b.dex:base.dex:base-1.dex:base-2.dex:base-3.dex:base-4.dex]",
+                contexts[5]);
+        assertEquals(
+                "PCL[a.dex:b.dex:base.dex:base-1.dex:base-2.dex:base-3.dex:base-4.dex:base-5.dex]",
+                contexts[6]);
+    }
+
+    @Test
+    public void testSplitChainNoIsolationNoSharedLibrary() {
+        ApplicationInfo ai = createMockApplicationInfo(PATH_CLASS_LOADER_NAME, true, true);
+        ai.privateFlags = ai.privateFlags & (~ApplicationInfo.PRIVATE_FLAG_ISOLATED_SPLIT_LOADING);
+        String[] contexts = DexoptUtils.getClassLoaderContexts(ai, null);
+
+        assertEquals(7, contexts.length);
+        assertEquals("PCL[]", contexts[0]);
+        assertEquals("PCL[base.dex]", contexts[1]);
+        assertEquals("PCL[base.dex:base-1.dex]", contexts[2]);
+        assertEquals("PCL[base.dex:base-1.dex:base-2.dex]", contexts[3]);
+        assertEquals("PCL[base.dex:base-1.dex:base-2.dex:base-3.dex]", contexts[4]);
+        assertEquals("PCL[base.dex:base-1.dex:base-2.dex:base-3.dex:base-4.dex]", contexts[5]);
+        assertEquals(
+                "PCL[base.dex:base-1.dex:base-2.dex:base-3.dex:base-4.dex:base-5.dex]",
+                contexts[6]);
+    }
+    @Test
+    public void testSplitChainNoSharedLibraries() {
+        ApplicationInfo ai = createMockApplicationInfo(
+                DELEGATE_LAST_CLASS_LOADER_NAME, true, true);
+        String[] contexts = DexoptUtils.getClassLoaderContexts(ai, null);
+
+        assertEquals(7, contexts.length);
+        assertEquals("DLC[]", contexts[0]);
+        assertEquals("DLC[];DLC[base-2.dex];PCL[base-4.dex];DLC[base.dex]", contexts[1]);
+        assertEquals("DLC[];PCL[base-4.dex];DLC[base.dex]", contexts[2]);
+        assertEquals("PCL[];PCL[base-4.dex];DLC[base.dex]", contexts[3]);
+        assertEquals("PCL[];DLC[base.dex]", contexts[4]);
+        assertEquals("PCL[];DLC[base.dex]", contexts[5]);
+        assertEquals("PCL[];PCL[base-5.dex];DLC[base.dex]", contexts[6]);
+    }
+
+    @Test
+    public void testSplitChainWithNullPrimaryClassLoader() {
+        // A null classLoaderName should mean PathClassLoader.
+        ApplicationInfo ai = createMockApplicationInfo(null, true, true);
+        String[] sharedLibrary = new String[] {"a.dex", "b.dex"};
+        String[] contexts = DexoptUtils.getClassLoaderContexts(ai, sharedLibrary);
+
+        assertEquals(7, contexts.length);
+        assertEquals("PCL[a.dex:b.dex]", contexts[0]);
+        assertEquals("DLC[];DLC[base-2.dex];PCL[base-4.dex];PCL[a.dex:b.dex:base.dex]", contexts[1]);
+        assertEquals("DLC[];PCL[base-4.dex];PCL[a.dex:b.dex:base.dex]", contexts[2]);
+        assertEquals("PCL[];PCL[base-4.dex];PCL[a.dex:b.dex:base.dex]", contexts[3]);
+        assertEquals("PCL[];PCL[a.dex:b.dex:base.dex]", contexts[4]);
+        assertEquals("PCL[];PCL[a.dex:b.dex:base.dex]", contexts[5]);
+        assertEquals("PCL[];PCL[base-5.dex];PCL[a.dex:b.dex:base.dex]", contexts[6]);
+    }
+
+    @Test
+    public void tesNoSplits() {
+        ApplicationInfo ai = createMockApplicationInfo(PATH_CLASS_LOADER_NAME, false, false);
+        String[] sharedLibrary = new String[] {"a.dex", "b.dex"};
+        String[] contexts = DexoptUtils.getClassLoaderContexts(ai, sharedLibrary);
+
+        assertEquals(1, contexts.length);
+        assertEquals("PCL[a.dex:b.dex]", contexts[0]);
+    }
+
+    @Test
+    public void tesNoSplitsNullClassLoaderName() {
+        ApplicationInfo ai = createMockApplicationInfo(null, false, false);
+        String[] sharedLibrary = new String[] {"a.dex", "b.dex"};
+        String[] contexts = DexoptUtils.getClassLoaderContexts(ai, sharedLibrary);
+
+        assertEquals(1, contexts.length);
+        assertEquals("PCL[a.dex:b.dex]", contexts[0]);
+    }
+
+    @Test
+    public void tesNoSplitDelegateLast() {
+        ApplicationInfo ai = createMockApplicationInfo(
+                DELEGATE_LAST_CLASS_LOADER_NAME, false, false);
+        String[] sharedLibrary = new String[] {"a.dex", "b.dex"};
+        String[] contexts = DexoptUtils.getClassLoaderContexts(ai, sharedLibrary);
+
+        assertEquals(1, contexts.length);
+        assertEquals("DLC[a.dex:b.dex]", contexts[0]);
+    }
+
+    @Test
+    public void tesNoSplitsNoSharedLibraries() {
+        ApplicationInfo ai = createMockApplicationInfo(PATH_CLASS_LOADER_NAME, false, false);
+        String[] contexts = DexoptUtils.getClassLoaderContexts(ai, null);
+
+        assertEquals(1, contexts.length);
+        assertEquals("PCL[]", contexts[0]);
+    }
+
+    @Test
+    public void tesNoSplitDelegateLastNoSharedLibraries() {
+        ApplicationInfo ai = createMockApplicationInfo(
+                DELEGATE_LAST_CLASS_LOADER_NAME, false, false);
+        String[] contexts = DexoptUtils.getClassLoaderContexts(ai, null);
+
+        assertEquals(1, contexts.length);
+        assertEquals("DLC[]", contexts[0]);
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/wm/TestWindowManagerPolicy.java b/services/tests/servicestests/src/com/android/server/wm/TestWindowManagerPolicy.java
index 0a7a5f2..828d405 100644
--- a/services/tests/servicestests/src/com/android/server/wm/TestWindowManagerPolicy.java
+++ b/services/tests/servicestests/src/com/android/server/wm/TestWindowManagerPolicy.java
@@ -382,7 +382,7 @@
     }
 
     @Override
-    public boolean isInteractive() {
+    public boolean okToAnimate() {
         return true;
     }
 
diff --git a/telecomm/java/android/telecom/Logging/EventManager.java b/telecomm/java/android/telecom/Logging/EventManager.java
index fddbfce..4fc3385 100644
--- a/telecomm/java/android/telecom/Logging/EventManager.java
+++ b/telecomm/java/android/telecom/Logging/EventManager.java
@@ -36,6 +36,7 @@
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.TimeZone;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.stream.Collectors;
 
@@ -268,6 +269,7 @@
 
     public EventManager(@NonNull SessionManager.ISessionIdQueryHandler l) {
         mSessionIdHandler = l;
+        sDateFormat.setTimeZone(TimeZone.getDefault());
     }
 
     public void event(Loggable recordEntry, String event, Object data) {
diff --git a/telephony/java/android/telephony/MbmsDownloadManager.java b/telephony/java/android/telephony/MbmsDownloadManager.java
index 4eeabb0..c747b84 100644
--- a/telephony/java/android/telephony/MbmsDownloadManager.java
+++ b/telephony/java/android/telephony/MbmsDownloadManager.java
@@ -28,8 +28,8 @@
 import android.os.IBinder;
 import android.os.RemoteException;
 import android.telephony.mbms.FileInfo;
-import android.telephony.mbms.IDownloadCallback;
 import android.telephony.mbms.DownloadRequest;
+import android.telephony.mbms.IDownloadProgressListener;
 import android.telephony.mbms.IMbmsDownloadManagerCallback;
 import android.telephony.mbms.MbmsDownloadManagerCallback;
 import android.telephony.mbms.MbmsDownloadReceiver;
@@ -390,9 +390,10 @@
      * Asynchronous errors through the listener include any of the errors
      *
      * @param request The request that specifies what should be downloaded
-     * @param callback Optional callback that will provide progress updates if the app is running.
+     * @param progressListener Optional listener that will be provided progress updates
+     *                         if the app is running.
      */
-    public void download(DownloadRequest request, IDownloadCallback callback)
+    public void download(DownloadRequest request, IDownloadProgressListener progressListener)
             throws MbmsException {
         IMbmsDownloadService downloadService = mService.get();
         if (downloadService == null) {
@@ -412,7 +413,7 @@
         checkValidDownloadDestination(request);
         writeDownloadRequestToken(request);
         try {
-            downloadService.download(request, callback);
+            downloadService.download(request, progressListener);
         } catch (RemoteException e) {
             mService.set(null);
             throw new MbmsException(MbmsException.ERROR_MIDDLEWARE_LOST);
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index b5b32e4..2e7b19a 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -767,12 +767,15 @@
      * The {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} extra is a
      * {@link android.app.PendingIntent} that will launch the voicemail settings. This extra is only
      * available when the voicemail number is not set.
+     * The {@link #EXTRA_IS_REFRESH} extra indicates whether the notification is a refresh or a new
+     * notification.
      *
      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
      * @see #EXTRA_NOTIFICATION_COUNT
      * @see #EXTRA_VOICEMAIL_NUMBER
      * @see #EXTRA_CALL_VOICEMAIL_INTENT
      * @see #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT
+     * @see #EXTRA_IS_REFRESH
      */
     public static final String ACTION_SHOW_VOICEMAIL_NOTIFICATION =
             "android.telephony.action.SHOW_VOICEMAIL_NOTIFICATION";
@@ -811,6 +814,15 @@
             "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
 
     /**
+     * Boolean value representing whether the {@link
+     * TelephonyManager#ACTION_SHOW_VOICEMAIL_NOTIFICATION} is new or a refresh of an existing
+     * notification. Notification refresh happens after reboot or connectivity changes. The user has
+     * already been notified for the voicemail so it should not alert the user, and should not be
+     * shown again if the user has dismissed it.
+     */
+    public static final String EXTRA_IS_REFRESH = "android.telephony.extra.IS_REFRESH";
+
+    /**
      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
      * successfully handed over from WIFI to LTE.
      * <p>
diff --git a/telephony/java/android/telephony/mbms/DownloadCallback.java b/telephony/java/android/telephony/mbms/DownloadCallback.java
deleted file mode 100644
index 0c6fec4..0000000
--- a/telephony/java/android/telephony/mbms/DownloadCallback.java
+++ /dev/null
@@ -1,41 +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 android.telephony.mbms;
-
-/**
- * A optional listener class used by download clients to track progress.
- * @hide
- */
-public class DownloadCallback extends IDownloadCallback.Stub {
-    /**
-     * Gives process callbacks for a given DownloadRequest.
-     * request indicates which download is being referenced.
-     * fileInfo gives information about the file being downloaded.  Note that
-     *   the request may result in many files being downloaded and the client
-     *   may not have been able to get a list of them in advance.
-     * downloadSize is the final amount to be downloaded.  This may be different
-     *   from the decoded final size, but is useful in gauging download progress.
-     * currentSize is the amount currently downloaded.
-     * decodedPercent is the percent from 0 to 100 of the file decoded.  After the
-     *   download completes the contents needs to be processed.  It is perhaps
-     *   uncompressed, transcoded and/or decrypted.  Generally the download completes
-     *   before the decode is started, but that's not required.
-     */
-    public void progress(DownloadRequest request, FileInfo fileInfo,
-            int downloadSize, int currentSize, int decodedPercent) {
-    }
-}
diff --git a/telephony/java/android/telephony/mbms/DownloadProgressListener.java b/telephony/java/android/telephony/mbms/DownloadProgressListener.java
new file mode 100644
index 0000000..d6bd5dc
--- /dev/null
+++ b/telephony/java/android/telephony/mbms/DownloadProgressListener.java
@@ -0,0 +1,45 @@
+/*
+ * 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.telephony.mbms;
+
+/**
+ * A optional listener class used by download clients to track progress.
+ * @hide
+ */
+public class DownloadProgressListener extends IDownloadProgressListener.Stub {
+    /**
+     * Gives process callbacks for a given DownloadRequest.
+     * This is optionally specified when requesting a download and
+     * only lives while the app is running - it's unlikely to be useful for
+     * downloads far in the future.
+     *
+     * @param request a {@link DownloadRequest}, indicating which download is being referenced.
+     * @param fileInfo a {@link FileInfo} specifying the file to report progress on.  Note that
+     *   the request may result in many files being downloaded and the client
+     *   may not have been able to get a list of them in advance.
+     * @param currentDownloadSize is the current amount downloaded.
+     * @param fullDownloadSize is the total number of bytes that make up the downloaded content.
+     *   This may be different from the decoded final size, but is useful in gauging download
+     *   progress.
+     * @param currentDecodedSize is the number of bytes that have been decoded.
+     * @param fullDecodedSize is the total number of bytes that make up the final decoded content.
+     */
+    public void progress(DownloadRequest request, FileInfo fileInfo,
+            int currentDownloadSize, int fullDownloadSize,
+            int currentDecodedSize, int fullDecodedSize) {
+    }
+}
diff --git a/telephony/java/android/telephony/mbms/IDownloadCallback.aidl b/telephony/java/android/telephony/mbms/IDownloadProgressListener.aidl
similarity index 87%
rename from telephony/java/android/telephony/mbms/IDownloadCallback.aidl
rename to telephony/java/android/telephony/mbms/IDownloadProgressListener.aidl
index a6bd7e5..bb9dc6c 100755
--- a/telephony/java/android/telephony/mbms/IDownloadCallback.aidl
+++ b/telephony/java/android/telephony/mbms/IDownloadProgressListener.aidl
@@ -23,12 +23,12 @@
  * The optional interface used by download clients to track progress.
  * @hide
  */
-interface IDownloadCallback
+interface IDownloadProgressListener
 {
     /**
      * Gives progress callbacks for a given DownloadRequest.  Includes a FileInfo
      * as the list of files may not have been known at request-time.
      */
-    void progress(in DownloadRequest request, in FileInfo fileInfo, int downloadSize,
-            int currentSize, int decodedPercent);
+    void progress(in DownloadRequest request, in FileInfo fileInfo, int currentDownloadSize,
+            int fullDownloadSize, int currentDecodedSize, int fullDecodedSize);
 }
diff --git a/telephony/java/android/telephony/mbms/vendor/IMbmsDownloadService.aidl b/telephony/java/android/telephony/mbms/vendor/IMbmsDownloadService.aidl
index 725d11c..0a76f32 100755
--- a/telephony/java/android/telephony/mbms/vendor/IMbmsDownloadService.aidl
+++ b/telephony/java/android/telephony/mbms/vendor/IMbmsDownloadService.aidl
@@ -21,7 +21,7 @@
 import android.telephony.mbms.DownloadRequest;
 import android.telephony.mbms.FileInfo;
 import android.telephony.mbms.IMbmsDownloadManagerCallback;
-import android.telephony.mbms.IDownloadCallback;
+import android.telephony.mbms.IDownloadProgressListener;
 
 /**
  * @hide
@@ -34,7 +34,7 @@
 
     int setTempFileRootDirectory(int subId, String rootDirectoryPath);
 
-    int download(in DownloadRequest downloadRequest, IDownloadCallback listener);
+    int download(in DownloadRequest downloadRequest, IDownloadProgressListener listener);
 
     List<DownloadRequest> listPendingDownloads(int subscriptionId);
 
diff --git a/telephony/java/android/telephony/mbms/vendor/MbmsDownloadServiceBase.java b/telephony/java/android/telephony/mbms/vendor/MbmsDownloadServiceBase.java
index 8fbd448..d725d9f 100644
--- a/telephony/java/android/telephony/mbms/vendor/MbmsDownloadServiceBase.java
+++ b/telephony/java/android/telephony/mbms/vendor/MbmsDownloadServiceBase.java
@@ -20,7 +20,7 @@
 import android.os.RemoteException;
 import android.telephony.mbms.DownloadRequest;
 import android.telephony.mbms.FileInfo;
-import android.telephony.mbms.IDownloadCallback;
+import android.telephony.mbms.IDownloadProgressListener;
 import android.telephony.mbms.IMbmsDownloadManagerCallback;
 import android.telephony.mbms.MbmsException;
 
@@ -105,7 +105,7 @@
      * @return TODO: enumerate possible return values
      */
     @Override
-    public int download(DownloadRequest downloadRequest, IDownloadCallback listener)
+    public int download(DownloadRequest downloadRequest, IDownloadProgressListener listener)
             throws RemoteException {
         return 0;
     }
diff --git a/tests/net/java/android/net/IpSecManagerTest.java b/tests/net/java/android/net/IpSecManagerTest.java
new file mode 100644
index 0000000..9f31d27
--- /dev/null
+++ b/tests/net/java/android/net/IpSecManagerTest.java
@@ -0,0 +1,225 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net;
+
+import static android.system.OsConstants.AF_INET;
+import static android.system.OsConstants.IPPROTO_UDP;
+import static android.system.OsConstants.SOCK_DGRAM;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.support.test.filters.SmallTest;
+import android.system.Os;
+import android.test.AndroidTestCase;
+import com.android.server.IpSecService;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Unit tests for {@link IpSecManager}. */
+@SmallTest
+@RunWith(JUnit4.class)
+public class IpSecManagerTest {
+
+    private static final int TEST_UDP_ENCAP_PORT = 34567;
+    private static final int DROID_SPI = 0xD1201D;
+
+    private static final InetAddress GOOGLE_DNS_4;
+
+    static {
+        try {
+            // Google Public DNS Addresses;
+            GOOGLE_DNS_4 = InetAddress.getByName("8.8.8.8");
+        } catch (UnknownHostException e) {
+            throw new RuntimeException("Could not resolve DNS Addresses", e);
+        }
+    }
+
+    private IpSecService mMockIpSecService;
+    private IpSecManager mIpSecManager;
+
+    @Before
+    public void setUp() throws Exception {
+        mMockIpSecService = mock(IpSecService.class);
+        mIpSecManager = new IpSecManager(mMockIpSecService);
+    }
+
+    /*
+     * Allocate a specific SPI
+     * Close SPIs
+     */
+    @Test
+    public void testAllocSpi() throws Exception {
+        int resourceId = 1;
+        IpSecSpiResponse spiResp =
+                new IpSecSpiResponse(IpSecManager.Status.OK, resourceId, DROID_SPI);
+        when(mMockIpSecService.reserveSecurityParameterIndex(
+                        eq(IpSecTransform.DIRECTION_IN),
+                        eq(GOOGLE_DNS_4.getHostAddress()),
+                        eq(DROID_SPI),
+                        anyObject()))
+                .thenReturn(spiResp);
+
+        IpSecManager.SecurityParameterIndex droidSpi =
+                mIpSecManager.reserveSecurityParameterIndex(
+                        IpSecTransform.DIRECTION_IN, GOOGLE_DNS_4, DROID_SPI);
+        assertEquals(DROID_SPI, droidSpi.getSpi());
+
+        droidSpi.close();
+
+        verify(mMockIpSecService).releaseSecurityParameterIndex(resourceId);
+    }
+
+    @Test
+    public void testAllocRandomSpi() throws Exception {
+        int resourceId = 1;
+        IpSecSpiResponse spiResp =
+                new IpSecSpiResponse(IpSecManager.Status.OK, resourceId, DROID_SPI);
+        when(mMockIpSecService.reserveSecurityParameterIndex(
+                        eq(IpSecTransform.DIRECTION_OUT),
+                        eq(GOOGLE_DNS_4.getHostAddress()),
+                        eq(IpSecManager.INVALID_SECURITY_PARAMETER_INDEX),
+                        anyObject()))
+                .thenReturn(spiResp);
+
+        IpSecManager.SecurityParameterIndex randomSpi =
+                mIpSecManager.reserveSecurityParameterIndex(
+                        IpSecTransform.DIRECTION_OUT, GOOGLE_DNS_4);
+
+        assertEquals(DROID_SPI, randomSpi.getSpi());
+
+        randomSpi.close();
+
+        verify(mMockIpSecService).releaseSecurityParameterIndex(resourceId);
+    }
+
+    /*
+     * Throws resource unavailable exception
+     */
+    @Test
+    public void testAllocSpiResUnavaiableExeption() throws Exception {
+        IpSecSpiResponse spiResp =
+                new IpSecSpiResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE, 0, 0);
+        when(mMockIpSecService.reserveSecurityParameterIndex(
+                        anyInt(), anyString(), anyInt(), anyObject()))
+                .thenReturn(spiResp);
+
+        try {
+            mIpSecManager.reserveSecurityParameterIndex(IpSecTransform.DIRECTION_OUT, GOOGLE_DNS_4);
+            fail("ResourceUnavailableException was not thrown");
+        } catch (IpSecManager.ResourceUnavailableException e) {
+        }
+    }
+
+    /*
+     * Throws spi unavailable exception
+     */
+    @Test
+    public void testAllocSpiSpiUnavaiableExeption() throws Exception {
+        IpSecSpiResponse spiResp = new IpSecSpiResponse(IpSecManager.Status.SPI_UNAVAILABLE, 0, 0);
+        when(mMockIpSecService.reserveSecurityParameterIndex(
+                        anyInt(), anyString(), anyInt(), anyObject()))
+                .thenReturn(spiResp);
+
+        try {
+            mIpSecManager.reserveSecurityParameterIndex(IpSecTransform.DIRECTION_OUT, GOOGLE_DNS_4);
+            fail("ResourceUnavailableException was not thrown");
+        } catch (IpSecManager.ResourceUnavailableException e) {
+        }
+    }
+
+    /*
+     * Should throw exception when request spi 0 in IpSecManager
+     */
+    @Test
+    public void testRequestAllocInvalidSpi() throws Exception {
+        try {
+            mIpSecManager.reserveSecurityParameterIndex(
+                    IpSecTransform.DIRECTION_OUT, GOOGLE_DNS_4, 0);
+            fail("Able to allocate invalid spi");
+        } catch (IllegalArgumentException e) {
+        }
+    }
+
+    @Test
+    public void testOpenEncapsulationSocket() throws Exception {
+        int resourceId = 1;
+        IpSecUdpEncapResponse udpEncapResp =
+                new IpSecUdpEncapResponse(
+                        IpSecManager.Status.OK,
+                        resourceId,
+                        TEST_UDP_ENCAP_PORT,
+                        Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP));
+        when(mMockIpSecService.openUdpEncapsulationSocket(eq(TEST_UDP_ENCAP_PORT), anyObject()))
+                .thenReturn(udpEncapResp);
+
+        IpSecManager.UdpEncapsulationSocket encapSocket =
+                mIpSecManager.openUdpEncapsulationSocket(TEST_UDP_ENCAP_PORT);
+        assertNotNull(encapSocket.getSocket());
+        assertEquals(TEST_UDP_ENCAP_PORT, encapSocket.getPort());
+
+        encapSocket.close();
+
+        verify(mMockIpSecService).closeUdpEncapsulationSocket(resourceId);
+    }
+
+    @Test
+    public void testOpenEncapsulationSocketOnRandomPort() throws Exception {
+        int resourceId = 1;
+        IpSecUdpEncapResponse udpEncapResp =
+                new IpSecUdpEncapResponse(
+                        IpSecManager.Status.OK,
+                        resourceId,
+                        TEST_UDP_ENCAP_PORT,
+                        Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP));
+
+        when(mMockIpSecService.openUdpEncapsulationSocket(eq(0), anyObject()))
+                .thenReturn(udpEncapResp);
+
+        IpSecManager.UdpEncapsulationSocket encapSocket =
+                mIpSecManager.openUdpEncapsulationSocket();
+
+        assertNotNull(encapSocket.getSocket());
+        assertEquals(TEST_UDP_ENCAP_PORT, encapSocket.getPort());
+
+        encapSocket.close();
+
+        verify(mMockIpSecService).closeUdpEncapsulationSocket(resourceId);
+    }
+
+    @Test
+    public void testOpenEncapsulationSocketWithInvalidPort() throws Exception {
+        try {
+            mIpSecManager.openUdpEncapsulationSocket(IpSecManager.INVALID_SECURITY_PARAMETER_INDEX);
+            fail("IllegalArgumentException was not thrown");
+        } catch (IllegalArgumentException e) {
+        }
+    }
+
+    // TODO: add test when applicable transform builder interface is available
+}
diff --git a/tests/net/java/android/net/apf/ApfTest.java b/tests/net/java/android/net/apf/ApfTest.java
index 6bf3b6b..bfbb8cc 100644
--- a/tests/net/java/android/net/apf/ApfTest.java
+++ b/tests/net/java/android/net/apf/ApfTest.java
@@ -92,6 +92,9 @@
     private final static boolean DROP_MULTICAST = true;
     private final static boolean ALLOW_MULTICAST = false;
 
+    private final static boolean DROP_802_3_FRAMES = true;
+    private final static boolean ALLOW_802_3_FRAMES = false;
+
     private static String label(int code) {
         switch (code) {
             case PASS: return "PASS";
@@ -611,9 +614,9 @@
         private final long mFixedTimeMs = SystemClock.elapsedRealtime();
 
         public TestApfFilter(IpManager.Callback ipManagerCallback, boolean multicastFilter,
-                IpConnectivityLog log) throws Exception {
+                boolean ieee802_3Filter, IpConnectivityLog log) throws Exception {
             super(new ApfCapabilities(2, 1700, ARPHRD_ETHER), NetworkInterface.getByName("lo"),
-                    ipManagerCallback, multicastFilter, log);
+                    ipManagerCallback, multicastFilter, ieee802_3Filter, log);
         }
 
         // Pretend an RA packet has been received and show it to ApfFilter.
@@ -742,7 +745,8 @@
         LinkProperties lp = new LinkProperties();
         lp.addLinkAddress(link);
 
-        ApfFilter apfFilter = new TestApfFilter(ipManagerCallback, DROP_MULTICAST, mLog);
+        ApfFilter apfFilter = new TestApfFilter(ipManagerCallback, DROP_MULTICAST,
+                ALLOW_802_3_FRAMES, mLog);
         apfFilter.setLinkProperties(lp);
 
         byte[] program = ipManagerCallback.getApfProgram();
@@ -793,7 +797,8 @@
     @SmallTest
     public void testApfFilterIPv6() throws Exception {
         MockIpManagerCallback ipManagerCallback = new MockIpManagerCallback();
-        ApfFilter apfFilter = new TestApfFilter(ipManagerCallback, ALLOW_MULTICAST, mLog);
+        ApfFilter apfFilter = new TestApfFilter(ipManagerCallback, ALLOW_MULTICAST,
+                ALLOW_802_3_FRAMES, mLog);
         byte[] program = ipManagerCallback.getApfProgram();
 
         // Verify empty IPv6 packet is passed
@@ -834,7 +839,8 @@
         LinkProperties lp = new LinkProperties();
         lp.addLinkAddress(link);
 
-        ApfFilter apfFilter = new TestApfFilter(ipManagerCallback, ALLOW_MULTICAST, mLog);
+        ApfFilter apfFilter = new TestApfFilter(ipManagerCallback, ALLOW_MULTICAST,
+                DROP_802_3_FRAMES, mLog);
         apfFilter.setLinkProperties(lp);
 
         byte[] program = ipManagerCallback.getApfProgram();
@@ -896,7 +902,8 @@
         // Verify it can be initialized to on
         ipManagerCallback.resetApfProgramWait();
         apfFilter.shutdown();
-        apfFilter = new TestApfFilter(ipManagerCallback, DROP_MULTICAST, mLog);
+        apfFilter = new TestApfFilter(ipManagerCallback, DROP_MULTICAST,
+                DROP_802_3_FRAMES, mLog);
         apfFilter.setLinkProperties(lp);
         program = ipManagerCallback.getApfProgram();
         assertDrop(program, mcastv4packet.array());
@@ -911,6 +918,56 @@
         apfFilter.shutdown();
     }
 
+    @SmallTest
+    public void testApfFilter802_3() throws Exception {
+        MockIpManagerCallback ipManagerCallback = new MockIpManagerCallback();
+        LinkAddress link = new LinkAddress(InetAddress.getByAddress(MOCK_IPV4_ADDR), 19);
+        LinkProperties lp = new LinkProperties();
+        lp.addLinkAddress(link);
+
+        ApfFilter apfFilter = new TestApfFilter(ipManagerCallback, ALLOW_MULTICAST,
+                ALLOW_802_3_FRAMES, mLog);
+        apfFilter.setLinkProperties(lp);
+
+        byte[] program = ipManagerCallback.getApfProgram();
+
+        // Verify empty packet of 100 zero bytes is passed
+        // Note that eth-type = 0 makes it an IEEE802.3 frame
+        ByteBuffer packet = ByteBuffer.wrap(new byte[100]);
+        assertPass(program, packet.array());
+
+        // Verify empty packet with IPv4 is passed
+        packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IP);
+        assertPass(program, packet.array());
+
+        // Verify empty IPv6 packet is passed
+        packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IPV6);
+        assertPass(program, packet.array());
+
+        // Now turn on the filter
+        ipManagerCallback.resetApfProgramWait();
+        apfFilter.shutdown();
+        apfFilter = new TestApfFilter(ipManagerCallback, ALLOW_MULTICAST,
+                DROP_802_3_FRAMES, mLog);
+        apfFilter.setLinkProperties(lp);
+        program = ipManagerCallback.getApfProgram();
+
+        // Verify that IEEE802.3 frame is dropped
+        // In this case ethtype is used for payload length
+        packet.putShort(ETH_ETHERTYPE_OFFSET, (short)(100 - 14));
+        assertDrop(program, packet.array());
+
+        // Verify that IPv4 (as example of Ethernet II) frame will pass
+        packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IP);
+        assertPass(program, packet.array());
+
+        // Verify that IPv6 (as example of Ethernet II) frame will pass
+        packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IPV6);
+        assertPass(program, packet.array());
+
+        apfFilter.shutdown();
+    }
+
     private byte[] getProgram(MockIpManagerCallback cb, ApfFilter filter, LinkProperties lp) {
         cb.resetApfProgramWait();
         filter.setLinkProperties(lp);
@@ -935,7 +992,8 @@
     @SmallTest
     public void testApfFilterArp() throws Exception {
         MockIpManagerCallback ipManagerCallback = new MockIpManagerCallback();
-        ApfFilter apfFilter = new TestApfFilter(ipManagerCallback, ALLOW_MULTICAST, mLog);
+        ApfFilter apfFilter = new TestApfFilter(ipManagerCallback, ALLOW_MULTICAST,
+                DROP_802_3_FRAMES, mLog);
 
         // Verify initially ARP request filter is off, and GARP filter is on.
         verifyArpFilter(ipManagerCallback.getApfProgram(), PASS);
@@ -1056,7 +1114,8 @@
     @SmallTest
     public void testApfFilterRa() throws Exception {
         MockIpManagerCallback ipManagerCallback = new MockIpManagerCallback();
-        TestApfFilter apfFilter = new TestApfFilter(ipManagerCallback, DROP_MULTICAST, mLog);
+        TestApfFilter apfFilter = new TestApfFilter(ipManagerCallback, DROP_MULTICAST,
+                DROP_802_3_FRAMES, mLog);
         byte[] program = ipManagerCallback.getApfProgram();
 
         final int ROUTER_LIFETIME = 1000;
@@ -1198,7 +1257,8 @@
         final int maxRandomPacketSize = 512;
         final Random r = new Random();
         MockIpManagerCallback cb = new MockIpManagerCallback();
-        TestApfFilter apfFilter = new TestApfFilter(cb, DROP_MULTICAST, mLog);
+        TestApfFilter apfFilter = new TestApfFilter(cb, DROP_MULTICAST,
+                DROP_802_3_FRAMES, mLog);
         for (int i = 0; i < 1000; i++) {
             byte[] packet = new byte[r.nextInt(maxRandomPacketSize + 1)];
             r.nextBytes(packet);
@@ -1216,7 +1276,8 @@
         final int maxRandomPacketSize = 512;
         final Random r = new Random();
         MockIpManagerCallback cb = new MockIpManagerCallback();
-        TestApfFilter apfFilter = new TestApfFilter(cb, DROP_MULTICAST, mLog);
+        TestApfFilter apfFilter = new TestApfFilter(cb, DROP_MULTICAST,
+                DROP_802_3_FRAMES, mLog);
         for (int i = 0; i < 1000; i++) {
             byte[] packet = new byte[r.nextInt(maxRandomPacketSize + 1)];
             r.nextBytes(packet);
diff --git a/tests/net/java/com/android/server/IpSecServiceTest.java b/tests/net/java/com/android/server/IpSecServiceTest.java
new file mode 100644
index 0000000..23fee28
--- /dev/null
+++ b/tests/net/java/com/android/server/IpSecServiceTest.java
@@ -0,0 +1,435 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server;
+
+import static android.system.OsConstants.AF_INET;
+import static android.system.OsConstants.EADDRINUSE;
+import static android.system.OsConstants.IPPROTO_UDP;
+import static android.system.OsConstants.SOCK_DGRAM;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyLong;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.net.INetd;
+import android.net.IpSecAlgorithm;
+import android.net.IpSecConfig;
+import android.net.IpSecManager;
+import android.net.IpSecSpiResponse;
+import android.net.IpSecTransform;
+import android.net.IpSecTransformResponse;
+import android.net.IpSecUdpEncapResponse;
+import android.os.Binder;
+import android.os.ParcelFileDescriptor;
+import android.support.test.filters.SmallTest;
+import android.system.ErrnoException;
+import android.system.Os;
+import java.io.FileDescriptor;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.UnknownHostException;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Unit tests for {@link IpSecService}. */
+@SmallTest
+@RunWith(JUnit4.class)
+public class IpSecServiceTest {
+
+    private static final int DROID_SPI = 0xD1201D;
+    private static final int DROID_SPI2 = DROID_SPI + 1;
+    private static final int TEST_UDP_ENCAP_INVALID_PORT = 100;
+    private static final int TEST_UDP_ENCAP_PORT_OUT_RANGE = 100000;
+    private static final int TEST_UDP_ENCAP_PORT = 34567;
+
+    private static final String IPV4_LOOPBACK = "127.0.0.1";
+    private static final String IPV4_ADDR = "192.168.0.2";
+
+    private static final InetAddress INADDR_ANY;
+
+    static {
+        try {
+            INADDR_ANY = InetAddress.getByAddress(new byte[] {0, 0, 0, 0});
+        } catch (UnknownHostException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private static final int[] DIRECTIONS =
+            new int[] {IpSecTransform.DIRECTION_OUT, IpSecTransform.DIRECTION_IN};
+    private static final byte[] CRYPT_KEY = {
+        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+        0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
+        0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+        0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
+    };
+    private static final byte[] AUTH_KEY = {
+        0x7A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F,
+        0x7A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F
+    };
+
+    Context mMockContext;
+    INetd mMockNetd;
+    IpSecService.IpSecServiceConfiguration mMockIpSecSrvConfig;
+    IpSecService mIpSecService;
+
+    @Before
+    public void setUp() throws Exception {
+        mMockContext = mock(Context.class);
+        mMockNetd = mock(INetd.class);
+        mMockIpSecSrvConfig = mock(IpSecService.IpSecServiceConfiguration.class);
+        mIpSecService = new IpSecService(mMockContext, mMockIpSecSrvConfig);
+
+        // Injecting mock netd
+        when(mMockIpSecSrvConfig.getNetdInstance()).thenReturn(mMockNetd);
+    }
+
+    @Test
+    public void testIpSecServiceCreate() throws InterruptedException {
+        IpSecService ipSecSrv = IpSecService.create(mMockContext);
+        assertNotNull(ipSecSrv);
+    }
+
+    @Test
+    public void testIpSecServiceReserveSpi() throws Exception {
+        when(mMockNetd.ipSecAllocateSpi(
+                        anyInt(),
+                        eq(IpSecTransform.DIRECTION_OUT),
+                        anyString(),
+                        eq(IPV4_LOOPBACK),
+                        eq(DROID_SPI)))
+                .thenReturn(DROID_SPI);
+
+        IpSecSpiResponse spiResp =
+                mIpSecService.reserveSecurityParameterIndex(
+                        IpSecTransform.DIRECTION_OUT, IPV4_LOOPBACK, DROID_SPI, new Binder());
+        assertEquals(IpSecManager.Status.OK, spiResp.status);
+        assertEquals(DROID_SPI, spiResp.spi);
+    }
+
+    @Test
+    public void testReleaseSecurityParameterIndex() throws Exception {
+        when(mMockNetd.ipSecAllocateSpi(
+                        anyInt(),
+                        eq(IpSecTransform.DIRECTION_OUT),
+                        anyString(),
+                        eq(IPV4_LOOPBACK),
+                        eq(DROID_SPI)))
+                .thenReturn(DROID_SPI);
+
+        IpSecSpiResponse spiResp =
+                mIpSecService.reserveSecurityParameterIndex(
+                        IpSecTransform.DIRECTION_OUT, IPV4_LOOPBACK, DROID_SPI, new Binder());
+
+        mIpSecService.releaseSecurityParameterIndex(spiResp.resourceId);
+
+        verify(mMockNetd)
+                .ipSecDeleteSecurityAssociation(
+                        eq(spiResp.resourceId), anyInt(), anyString(), anyString(), eq(DROID_SPI));
+    }
+
+    @Test
+    public void testReleaseInvalidSecurityParameterIndex() throws Exception {
+        try {
+            mIpSecService.releaseSecurityParameterIndex(1);
+            fail("IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException e) {
+        }
+    }
+
+    /** This function finds an available port */
+    int findUnusedPort() throws Exception {
+        // Get an available port.
+        ServerSocket s = new ServerSocket(0);
+        int port = s.getLocalPort();
+        s.close();
+        return port;
+    }
+
+    @Test
+    public void testOpenAndCloseUdpEncapsulationSocket() throws Exception {
+        int localport = findUnusedPort();
+
+        IpSecUdpEncapResponse udpEncapResp =
+                mIpSecService.openUdpEncapsulationSocket(localport, new Binder());
+        assertNotNull(udpEncapResp);
+        assertEquals(IpSecManager.Status.OK, udpEncapResp.status);
+        assertEquals(localport, udpEncapResp.port);
+
+        mIpSecService.closeUdpEncapsulationSocket(udpEncapResp.resourceId);
+        udpEncapResp.fileDescriptor.close();
+
+        // TODO: Added check for the resource tracker
+    }
+
+    @Test
+    public void testOpenUdpEncapsulationSocketAfterClose() throws Exception {
+        int localport = findUnusedPort();
+        IpSecUdpEncapResponse udpEncapResp =
+                mIpSecService.openUdpEncapsulationSocket(localport, new Binder());
+        assertNotNull(udpEncapResp);
+        assertEquals(IpSecManager.Status.OK, udpEncapResp.status);
+        assertEquals(localport, udpEncapResp.port);
+
+        mIpSecService.closeUdpEncapsulationSocket(udpEncapResp.resourceId);
+        udpEncapResp.fileDescriptor.close();
+
+        /** Check if localport is available. */
+        FileDescriptor newSocket = Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+        Os.bind(newSocket, INADDR_ANY, localport);
+        Os.close(newSocket);
+    }
+
+    /**
+     * This function checks if the IpSecService holds the reserved port. If
+     * closeUdpEncapsulationSocket is not called, the socket cleanup should not be complete.
+     */
+    @Test
+    public void testUdpEncapPortNotReleased() throws Exception {
+        int localport = findUnusedPort();
+        IpSecUdpEncapResponse udpEncapResp =
+                mIpSecService.openUdpEncapsulationSocket(localport, new Binder());
+        assertNotNull(udpEncapResp);
+        assertEquals(IpSecManager.Status.OK, udpEncapResp.status);
+        assertEquals(localport, udpEncapResp.port);
+
+        udpEncapResp.fileDescriptor.close();
+
+        FileDescriptor newSocket = Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+        try {
+            Os.bind(newSocket, INADDR_ANY, localport);
+            fail("ErrnoException not thrown");
+        } catch (ErrnoException e) {
+            assertEquals(EADDRINUSE, e.errno);
+        }
+        mIpSecService.closeUdpEncapsulationSocket(udpEncapResp.resourceId);
+    }
+
+    @Test
+    public void testOpenUdpEncapsulationSocketOnRandomPort() throws Exception {
+        IpSecUdpEncapResponse udpEncapResp =
+                mIpSecService.openUdpEncapsulationSocket(0, new Binder());
+        assertNotNull(udpEncapResp);
+        assertEquals(IpSecManager.Status.OK, udpEncapResp.status);
+        mIpSecService.closeUdpEncapsulationSocket(udpEncapResp.resourceId);
+        udpEncapResp.fileDescriptor.close();
+    }
+
+    @Test
+    public void testOpenUdpEncapsulationSocketPortRange() throws Exception {
+        try {
+            mIpSecService.openUdpEncapsulationSocket(TEST_UDP_ENCAP_INVALID_PORT, new Binder());
+            fail("IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException e) {
+        }
+
+        try {
+            mIpSecService.openUdpEncapsulationSocket(TEST_UDP_ENCAP_PORT_OUT_RANGE, new Binder());
+            fail("IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException e) {
+        }
+    }
+
+    @Test
+    public void testOpenUdpEncapsulationSocketTwice() throws Exception {
+        int localport = findUnusedPort();
+
+        IpSecUdpEncapResponse udpEncapResp =
+                mIpSecService.openUdpEncapsulationSocket(localport, new Binder());
+        assertNotNull(udpEncapResp);
+        assertEquals(IpSecManager.Status.OK, udpEncapResp.status);
+        assertEquals(localport, udpEncapResp.port);
+        mIpSecService.openUdpEncapsulationSocket(localport, new Binder());
+
+        IpSecUdpEncapResponse testUdpEncapResp =
+                mIpSecService.openUdpEncapsulationSocket(localport, new Binder());
+        assertEquals(IpSecManager.Status.RESOURCE_UNAVAILABLE, testUdpEncapResp.status);
+
+        mIpSecService.closeUdpEncapsulationSocket(udpEncapResp.resourceId);
+        udpEncapResp.fileDescriptor.close();
+    }
+
+    @Test
+    public void testCloseInvalidUdpEncapsulationSocket() throws Exception {
+        try {
+            mIpSecService.closeUdpEncapsulationSocket(1);
+            fail("IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException e) {
+        }
+    }
+
+    IpSecConfig buildIpSecConfig() throws Exception {
+        IpSecManager ipSecManager = new IpSecManager(mIpSecService);
+
+        // Mocking the netd to allocate SPI
+        when(mMockNetd.ipSecAllocateSpi(anyInt(), anyInt(), anyString(), anyString(), anyInt()))
+                .thenReturn(DROID_SPI)
+                .thenReturn(DROID_SPI2);
+
+        IpSecAlgorithm encryptAlgo = new IpSecAlgorithm(IpSecAlgorithm.CRYPT_AES_CBC, CRYPT_KEY);
+        IpSecAlgorithm authAlgo =
+                new IpSecAlgorithm(IpSecAlgorithm.AUTH_HMAC_SHA256, AUTH_KEY, AUTH_KEY.length * 8);
+
+        InetAddress localAddr = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
+
+        /** Allocate and add SPI records in the IpSecService through IpSecManager interface. */
+        IpSecManager.SecurityParameterIndex outSpi =
+                ipSecManager.reserveSecurityParameterIndex(IpSecTransform.DIRECTION_OUT, localAddr);
+        IpSecManager.SecurityParameterIndex inSpi =
+                ipSecManager.reserveSecurityParameterIndex(IpSecTransform.DIRECTION_IN, localAddr);
+
+        IpSecConfig ipSecConfig =
+                new IpSecTransform.Builder(mMockContext)
+                        .setSpi(IpSecTransform.DIRECTION_OUT, outSpi)
+                        .setSpi(IpSecTransform.DIRECTION_IN, inSpi)
+                        .setEncryption(IpSecTransform.DIRECTION_OUT, encryptAlgo)
+                        .setAuthentication(IpSecTransform.DIRECTION_OUT, authAlgo)
+                        .setEncryption(IpSecTransform.DIRECTION_IN, encryptAlgo)
+                        .setAuthentication(IpSecTransform.DIRECTION_IN, authAlgo)
+                        .getIpSecConfig();
+        return ipSecConfig;
+    }
+
+    @Test
+    public void testCreateTransportModeTransform() throws Exception {
+        IpSecConfig ipSecConfig = buildIpSecConfig();
+
+        IpSecTransformResponse createTransformResp =
+                mIpSecService.createTransportModeTransform(ipSecConfig, new Binder());
+        assertEquals(IpSecManager.Status.OK, createTransformResp.status);
+
+        verify(mMockNetd)
+                .ipSecAddSecurityAssociation(
+                        eq(createTransformResp.resourceId),
+                        anyInt(),
+                        eq(IpSecTransform.DIRECTION_OUT),
+                        anyString(),
+                        anyString(),
+                        anyLong(),
+                        eq(DROID_SPI),
+                        eq(IpSecAlgorithm.AUTH_HMAC_SHA256),
+                        eq(AUTH_KEY),
+                        anyInt(),
+                        eq(IpSecAlgorithm.CRYPT_AES_CBC),
+                        eq(CRYPT_KEY),
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyInt());
+        verify(mMockNetd)
+                .ipSecAddSecurityAssociation(
+                        eq(createTransformResp.resourceId),
+                        anyInt(),
+                        eq(IpSecTransform.DIRECTION_IN),
+                        anyString(),
+                        anyString(),
+                        anyLong(),
+                        eq(DROID_SPI2),
+                        eq(IpSecAlgorithm.AUTH_HMAC_SHA256),
+                        eq(AUTH_KEY),
+                        anyInt(),
+                        eq(IpSecAlgorithm.CRYPT_AES_CBC),
+                        eq(CRYPT_KEY),
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyInt());
+    }
+
+    @Test
+    public void testDeleteTransportModeTransform() throws Exception {
+        IpSecConfig ipSecConfig = buildIpSecConfig();
+
+        IpSecTransformResponse createTransformResp =
+                mIpSecService.createTransportModeTransform(ipSecConfig, new Binder());
+        mIpSecService.deleteTransportModeTransform(createTransformResp.resourceId);
+
+        verify(mMockNetd)
+                .ipSecDeleteSecurityAssociation(
+                        eq(createTransformResp.resourceId),
+                        eq(IpSecTransform.DIRECTION_OUT),
+                        anyString(),
+                        anyString(),
+                        eq(DROID_SPI));
+        verify(mMockNetd)
+                .ipSecDeleteSecurityAssociation(
+                        eq(createTransformResp.resourceId),
+                        eq(IpSecTransform.DIRECTION_IN),
+                        anyString(),
+                        anyString(),
+                        eq(DROID_SPI2));
+    }
+
+    @Test
+    public void testDeleteInvalidTransportModeTransform() throws Exception {
+        try {
+            mIpSecService.deleteTransportModeTransform(1);
+            fail("IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException e) {
+        }
+    }
+
+    @Test
+    public void testApplyTransportModeTransform() throws Exception {
+        IpSecConfig ipSecConfig = buildIpSecConfig();
+
+        IpSecTransformResponse createTransformResp =
+                mIpSecService.createTransportModeTransform(ipSecConfig, new Binder());
+        ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(new Socket());
+
+        int resourceId = createTransformResp.resourceId;
+        mIpSecService.applyTransportModeTransform(pfd, resourceId);
+
+        verify(mMockNetd)
+                .ipSecApplyTransportModeTransform(
+                        eq(pfd.getFileDescriptor()),
+                        eq(resourceId),
+                        eq(IpSecTransform.DIRECTION_OUT),
+                        anyString(),
+                        anyString(),
+                        eq(DROID_SPI));
+        verify(mMockNetd)
+                .ipSecApplyTransportModeTransform(
+                        eq(pfd.getFileDescriptor()),
+                        eq(resourceId),
+                        eq(IpSecTransform.DIRECTION_IN),
+                        anyString(),
+                        anyString(),
+                        eq(DROID_SPI2));
+    }
+
+    @Test
+    public void testRemoveTransportModeTransform() throws Exception {
+        ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(new Socket());
+        mIpSecService.removeTransportModeTransform(pfd, 1);
+
+        verify(mMockNetd).ipSecRemoveTransportModeTransform(pfd.getFileDescriptor());
+    }
+}
diff --git a/tests/net/jni/apf_jni.cpp b/tests/net/jni/apf_jni.cpp
index dc108c1..d415d22 100644
--- a/tests/net/jni/apf_jni.cpp
+++ b/tests/net/jni/apf_jni.cpp
@@ -14,8 +14,8 @@
  * limitations under the License.
  */
 
-#include <JNIHelp.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include <jni.h>
 #include <pcap.h>
 #include <stdlib.h>
diff --git a/tools/aapt/SdkConstants.h b/tools/aapt/SdkConstants.h
index d92de06..0dbf4ee 100644
--- a/tools/aapt/SdkConstants.h
+++ b/tools/aapt/SdkConstants.h
@@ -41,7 +41,8 @@
     SDK_MNC = 23,
     SDK_NOUGAT = 24,
     SDK_NOUGAT_MR1 = 25,
-    SDK_O = 26, // STOPSHIP replace with real version
+    SDK_O = 26,
+    SDK_O_MR1 = 10000, // STOPSHIP Replace with the real version.
 };
 
 #endif // H_AAPT_SDK_CONSTANTS
diff --git a/tools/aapt2/SdkConstants.h b/tools/aapt2/SdkConstants.h
index e3745e8..864e57d 100644
--- a/tools/aapt2/SdkConstants.h
+++ b/tools/aapt2/SdkConstants.h
@@ -52,6 +52,7 @@
   SDK_NOUGAT = 24,
   SDK_NOUGAT_MR1 = 25,
   SDK_O = 26,
+  SDK_O_MR1 = 10000, // STOPSHIP Replace with the real version.
 };
 
 ApiVersion FindAttributeSdkLevel(const ResourceId& id);
diff --git a/wifi/java/android/net/wifi/WifiInfo.java b/wifi/java/android/net/wifi/WifiInfo.java
index bd25356..f8485ef 100644
--- a/wifi/java/android/net/wifi/WifiInfo.java
+++ b/wifi/java/android/net/wifi/WifiInfo.java
@@ -105,34 +105,43 @@
     private boolean mEphemeral;
 
     /**
+     * Running total count of lost (not ACKed) transmitted unicast data packets.
      * @hide
      */
     public long txBad;
     /**
+     * Running total count of transmitted unicast data retry packets.
      * @hide
      */
     public long txRetries;
     /**
+     * Running total count of successfully transmitted (ACKed) unicast data packets.
      * @hide
      */
     public long txSuccess;
     /**
+     * Running total count of received unicast data packets.
      * @hide
      */
     public long rxSuccess;
+
     /**
+     * Average rate of lost transmitted packets, in units of packets per 5 seconds.
      * @hide
      */
     public double txBadRate;
     /**
+     * Average rate of transmitted retry packets, in units of packets per 5 seconds.
      * @hide
      */
     public double txRetriesRate;
     /**
+     * Average rate of successfully transmitted unicast packets, in units of packets per 5 seconds.
      * @hide
      */
     public double txSuccessRate;
     /**
+     * Average rate of received unicast data packets, in units of packets per 5 seconds.
      * @hide
      */
     public double rxSuccessRate;