Merge changes from topics 'AutofillContext2', 'AutofillContext' into oc-dev

* changes:
  Return all previous FillContexts onFill
  Report multiple FillContext-s onSave
diff --git a/Android.mk b/Android.mk
index 28d1d64..e58f306 100644
--- a/Android.mk
+++ b/Android.mk
@@ -143,7 +143,6 @@
 	core/java/android/bluetooth/IBluetoothGatt.aidl \
 	core/java/android/bluetooth/IBluetoothGattCallback.aidl \
 	core/java/android/bluetooth/IBluetoothGattServerCallback.aidl \
-	core/java/android/bluetooth/le/IAdvertiserCallback.aidl \
 	core/java/android/bluetooth/le/IAdvertisingSetCallback.aidl \
 	core/java/android/bluetooth/le/IPeriodicAdvertisingCallback.aidl \
 	core/java/android/bluetooth/le/IScannerCallback.aidl \
diff --git a/api/current.txt b/api/current.txt
index 26f251b..58d617a 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -7600,6 +7600,7 @@
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback);
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback, int);
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback, int, int);
+    method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback, int, int, android.os.Handler);
     method public boolean createBond();
     method public android.bluetooth.BluetoothSocket createInsecureRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException;
     method public android.bluetooth.BluetoothSocket createRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException;
@@ -24778,7 +24779,6 @@
   }
 
   public static final class TvContract.WatchNextPrograms implements android.media.tv.TvContract.BaseTvColumns {
-    ctor public TvContract.WatchNextPrograms();
     field public static final int ASPECT_RATIO_16_9 = 0; // 0x0
     field public static final int ASPECT_RATIO_1_1 = 3; // 0x3
     field public static final int ASPECT_RATIO_2_3 = 4; // 0x4
diff --git a/api/system-current.txt b/api/system-current.txt
index 0c8e71c..3723e7e 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -8073,6 +8073,7 @@
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback);
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback, int);
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback, int, int);
+    method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback, int, int, android.os.Handler);
     method public boolean createBond();
     method public android.bluetooth.BluetoothSocket createInsecureRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException;
     method public android.bluetooth.BluetoothSocket createRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException;
@@ -26776,7 +26777,6 @@
   }
 
   public static final class TvContract.WatchNextPrograms implements android.media.tv.TvContract.BaseTvColumns {
-    ctor public TvContract.WatchNextPrograms();
     field public static final int ASPECT_RATIO_16_9 = 0; // 0x0
     field public static final int ASPECT_RATIO_1_1 = 3; // 0x3
     field public static final int ASPECT_RATIO_2_3 = 4; // 0x4
diff --git a/api/test-current.txt b/api/test-current.txt
index c616022..9f7441c 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -7631,6 +7631,7 @@
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback);
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback, int);
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback, int, int);
+    method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback, int, int, android.os.Handler);
     method public boolean createBond();
     method public android.bluetooth.BluetoothSocket createInsecureRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException;
     method public android.bluetooth.BluetoothSocket createRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException;
@@ -24886,7 +24887,6 @@
   }
 
   public static final class TvContract.WatchNextPrograms implements android.media.tv.TvContract.BaseTvColumns {
-    ctor public TvContract.WatchNextPrograms();
     field public static final int ASPECT_RATIO_16_9 = 0; // 0x0
     field public static final int ASPECT_RATIO_1_1 = 3; // 0x3
     field public static final int ASPECT_RATIO_2_3 = 4; // 0x4
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index a939eb0..7855b92 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -1518,7 +1518,8 @@
      * Service action: Action for a service that device owner and profile owner can optionally
      * own.  If a device owner or a profile owner has such a service, the system tries to keep
      * a bound connection to it, in order to keep their process always running.
-     * The service must not be exported.
+     * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
+     * permission.
      */
     @SdkConstant(SdkConstantType.SERVICE_ACTION)
     public static final String ACTION_DEVICE_ADMIN_SERVICE
diff --git a/core/java/android/bluetooth/BluetoothDevice.java b/core/java/android/bluetooth/BluetoothDevice.java
index 639e056..c427268 100644
--- a/core/java/android/bluetooth/BluetoothDevice.java
+++ b/core/java/android/bluetooth/BluetoothDevice.java
@@ -22,6 +22,8 @@
 import android.annotation.SdkConstant.SdkConstantType;
 import android.annotation.SystemApi;
 import android.content.Context;
+import android.os.Handler;
+import android.os.Looper;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.os.ParcelUuid;
@@ -593,32 +595,38 @@
     public static final int TRANSPORT_LE = 2;
 
     /**
-     * Bluetooth LE 1M PHY.
+     * Bluetooth LE 1M PHY. Used to refer to LE 1M Physical Channel for advertising, scanning or
+     * connection.
      */
     public static final int PHY_LE_1M = 1;
 
     /**
-     * Bluetooth LE 2M PHY.
+     * Bluetooth LE 2M PHY. Used to refer to LE 2M Physical Channel for advertising, scanning or
+     * connection.
      */
     public static final int PHY_LE_2M = 2;
 
     /**
-     * Bluetooth LE Coded PHY.
+     * Bluetooth LE Coded PHY. Used to refer to LE Coded Physical Channel for advertising, scanning
+     * or connection.
      */
     public static final int PHY_LE_CODED = 3;
 
     /**
-     * Bluetooth LE 1M PHY mask.
+     * Bluetooth LE 1M PHY mask. Used to specify LE 1M Physical Channel as one of many available
+     * options in a bitmask.
      */
     public static final int PHY_LE_1M_MASK = 1;
 
     /**
-     * Bluetooth LE 2M PHY mask.
+     * Bluetooth LE 2M PHY mask. Used to specify LE 2M Physical Channel as one of many available
+     * options in a bitmask.
      */
     public static final int PHY_LE_2M_MASK = 2;
 
     /**
-     * Bluetooth LE Coded PHY mask.
+     * Bluetooth LE Coded PHY mask. Used to specify LE Coded Physical Channel as one of many
+     * available options in a bitmask.
      */
     public static final int PHY_LE_CODED_MASK = 4;
 
@@ -1668,12 +1676,45 @@
      *             {@link BluetoothDevice#TRANSPORT_BREDR} or {@link BluetoothDevice#TRANSPORT_LE}
      * @param phy preferred PHY for connections to remote LE device. Bitwise OR of any of
      *             {@link BluetoothDevice#PHY_LE_1M_MASK}, {@link BluetoothDevice#PHY_LE_2M_MASK},
-     *             and {@link BluetoothDevice#PHY_LE_CODED_MASK}. This option does not take effect if
-     *             {@code autoConnect} is set to true.
-     * @throws IllegalArgumentException if callback is null
+     *             and {@link BluetoothDevice#PHY_LE_CODED_MASK}. This option does not take effect
+     *             if {@code autoConnect} is set to true.
+     * @throws NullPointerException if callback is null
      */
     public BluetoothGatt connectGatt(Context context, boolean autoConnect,
                                      BluetoothGattCallback callback, int transport, int phy) {
+        return connectGatt(context, autoConnect,callback, TRANSPORT_AUTO, PHY_LE_1M_MASK, null);
+    }
+
+    /**
+     * Connect to GATT Server hosted by this device. Caller acts as GATT client.
+     * The callback is used to deliver results to Caller, such as connection status as well
+     * as any further GATT client operations.
+     * The method returns a BluetoothGatt instance. You can use BluetoothGatt to conduct
+     * GATT client operations.
+     * @param callback GATT callback handler that will receive asynchronous callbacks.
+     * @param autoConnect Whether to directly connect to the remote device (false)
+     *                    or to automatically connect as soon as the remote
+     *                    device becomes available (true).
+     * @param transport preferred transport for GATT connections to remote dual-mode devices
+     *             {@link BluetoothDevice#TRANSPORT_AUTO} or
+     *             {@link BluetoothDevice#TRANSPORT_BREDR} or {@link BluetoothDevice#TRANSPORT_LE}
+     * @param phy preferred PHY for connections to remote LE device. Bitwise OR of any of
+     *             {@link BluetoothDevice#PHY_LE_1M_MASK}, {@link BluetoothDevice#PHY_LE_2M_MASK},
+     *             an d{@link BluetoothDevice#PHY_LE_CODED_MASK}. This option does not take effect
+     *             if {@code autoConnect} is set to true.
+     * @param handler The handler to use for the callback. If {@code null}, callbacks will happen
+     *             on the service's main thread.
+     * @throws NullPointerException if callback is null
+     */
+    public BluetoothGatt connectGatt(Context context, boolean autoConnect,
+                                     BluetoothGattCallback callback, int transport, int phy,
+                                     Handler handler) {
+        if (callback == null)
+            throw new NullPointerException("callback is null");
+
+        if (handler == null)
+            handler = new Handler(Looper.getMainLooper());
+
         // TODO(Bluetooth) check whether platform support BLE
         //     Do the check here or in GattServer?
         BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
@@ -1685,7 +1726,7 @@
                 return null;
             }
             BluetoothGatt gatt = new BluetoothGatt(iGatt, this, transport, phy);
-            gatt.connect(autoConnect, callback);
+            gatt.connect(autoConnect, callback, handler);
             return gatt;
         } catch (RemoteException e) {Log.e(TAG, "", e);}
         return null;
diff --git a/core/java/android/bluetooth/BluetoothGatt.java b/core/java/android/bluetooth/BluetoothGatt.java
index 4aaf6bd..713dbf4 100644
--- a/core/java/android/bluetooth/BluetoothGatt.java
+++ b/core/java/android/bluetooth/BluetoothGatt.java
@@ -17,6 +17,7 @@
 package android.bluetooth;
 
 import android.content.Context;
+import android.os.Handler;
 import android.os.ParcelUuid;
 import android.os.RemoteException;
 import android.util.Log;
@@ -43,6 +44,7 @@
 
     private IBluetoothGatt mService;
     private BluetoothGattCallback mCallback;
+    private Handler mHandler;
     private int mClientIf;
     private BluetoothDevice mDevice;
     private boolean mAutoConnect;
@@ -154,8 +156,14 @@
                 }
                 mClientIf = clientIf;
                 if (status != GATT_SUCCESS) {
-                    mCallback.onConnectionStateChange(BluetoothGatt.this, GATT_FAILURE,
-                                                      BluetoothProfile.STATE_DISCONNECTED);
+                    mHandler.post(new Runnable() {
+                        @Override
+                        public void run() {
+                            mCallback.onConnectionStateChange(BluetoothGatt.this, GATT_FAILURE,
+                                              BluetoothProfile.STATE_DISCONNECTED);
+                        }
+                    });
+
                     synchronized(mStateLock) {
                         mConnState = CONN_STATE_IDLE;
                     }
@@ -181,11 +189,12 @@
                     return;
                 }
 
-                try {
-                    mCallback.onPhyUpdate(BluetoothGatt.this, txPhy, rxPhy, status);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onPhyUpdate(BluetoothGatt.this, txPhy, rxPhy, status);
+                    }
+                });
             }
 
             /**
@@ -200,11 +209,12 @@
                     return;
                 }
 
-                try {
-                    mCallback.onPhyRead(BluetoothGatt.this, txPhy, rxPhy, status);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onPhyRead(BluetoothGatt.this, txPhy, rxPhy, status);
+                    }
+                });
             }
 
             /**
@@ -221,11 +231,13 @@
                 }
                 int profileState = connected ? BluetoothProfile.STATE_CONNECTED :
                                                BluetoothProfile.STATE_DISCONNECTED;
-                try {
-                    mCallback.onConnectionStateChange(BluetoothGatt.this, status, profileState);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onConnectionStateChange(BluetoothGatt.this, status, profileState);
+                    }
+                });
 
                 synchronized(mStateLock) {
                     if (connected) {
@@ -279,11 +291,12 @@
                     }
                 }
 
-                try {
-                    mCallback.onServicesDiscovered(BluetoothGatt.this, status);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onServicesDiscovered(BluetoothGatt.this, status);
+                    }
+                });
             }
 
             /**
@@ -328,11 +341,12 @@
 
                 if (status == 0) characteristic.setValue(value);
 
-                try {
-                    mCallback.onCharacteristicRead(BluetoothGatt.this, characteristic, status);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onCharacteristicRead(BluetoothGatt.this, characteristic, status);
+                    }
+                });
             }
 
             /**
@@ -373,11 +387,12 @@
 
                 mAuthRetryState = AUTH_RETRY_STATE_IDLE;
 
-                try {
-                    mCallback.onCharacteristicWrite(BluetoothGatt.this, characteristic, status);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onCharacteristicWrite(BluetoothGatt.this, characteristic, status);
+                    }
+                });
             }
 
             /**
@@ -398,11 +413,12 @@
 
                 characteristic.setValue(value);
 
-                try {
-                    mCallback.onCharacteristicChanged(BluetoothGatt.this, characteristic);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onCharacteristicChanged(BluetoothGatt.this, characteristic);
+                    }
+                });
             }
 
             /**
@@ -442,11 +458,12 @@
 
                 mAuthRetryState = AUTH_RETRY_STATE_IDLE;
 
-                try {
-                    mCallback.onDescriptorRead(BluetoothGatt.this, descriptor, status);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onDescriptorRead(BluetoothGatt.this, descriptor, status);
+                    }
+                });
             }
 
             /**
@@ -485,11 +502,12 @@
 
                 mAuthRetryState = AUTH_RETRY_STATE_IDLE;
 
-                try {
-                    mCallback.onDescriptorWrite(BluetoothGatt.this, descriptor, status);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onDescriptorWrite(BluetoothGatt.this, descriptor, status);
+                    }
+                });
             }
 
             /**
@@ -508,11 +526,12 @@
                     mDeviceBusy = false;
                 }
 
-                try {
-                    mCallback.onReliableWriteCompleted(BluetoothGatt.this, status);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onReliableWriteCompleted(BluetoothGatt.this, status);
+                    }
+                });
             }
 
             /**
@@ -526,11 +545,12 @@
                 if (!address.equals(mDevice.getAddress())) {
                     return;
                 }
-                try {
-                    mCallback.onReadRemoteRssi(BluetoothGatt.this, rssi, status);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onReadRemoteRssi(BluetoothGatt.this, rssi, status);
+                    }
+                });
             }
 
             /**
@@ -544,11 +564,13 @@
                 if (!address.equals(mDevice.getAddress())) {
                     return;
                 }
-                try {
-                    mCallback.onMtuChanged(BluetoothGatt.this, mtu, status);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onMtuChanged(BluetoothGatt.this, mtu, status);
+                    }
+                });
             }
 
             /**
@@ -564,12 +586,14 @@
                 if (!address.equals(mDevice.getAddress())) {
                     return;
                 }
-                try {
-                    mCallback.onConnectionUpdated(BluetoothGatt.this, interval, latency,
-                                                  timeout, status);
-                } catch (Exception ex) {
-                    Log.w(TAG, "Unhandled exception in callback", ex);
-                }
+
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback.onConnectionUpdated(BluetoothGatt.this, interval, latency,
+                                                      timeout, status);
+                    }
+                });
             }
         };
 
@@ -659,11 +683,12 @@
      * @return If true, the callback will be called to notify success or failure,
      *         false on immediate error
      */
-    private boolean registerApp(BluetoothGattCallback callback) {
+    private boolean registerApp(BluetoothGattCallback callback, Handler handler) {
         if (DBG) Log.d(TAG, "registerApp()");
         if (mService == null) return false;
 
         mCallback = callback;
+        mHandler = handler;
         UUID uuid = UUID.randomUUID();
         if (DBG) Log.d(TAG, "registerApp() - UUID=" + uuid);
 
@@ -716,7 +741,8 @@
      *                    device becomes available (true).
      * @return true, if the connection attempt was initiated successfully
      */
-    /*package*/ boolean connect(Boolean autoConnect, BluetoothGattCallback callback) {
+    /*package*/ boolean connect(Boolean autoConnect, BluetoothGattCallback callback,
+                                Handler handler) {
         if (DBG) Log.d(TAG, "connect() - device: " + mDevice.getAddress() + ", auto: " + autoConnect);
         synchronized(mStateLock) {
             if (mConnState != CONN_STATE_IDLE) {
@@ -727,7 +753,7 @@
 
         mAutoConnect = autoConnect;
 
-        if (!registerApp(callback)) {
+        if (!registerApp(callback, handler)) {
             synchronized(mStateLock) {
                 mConnState = CONN_STATE_IDLE;
             }
diff --git a/core/java/android/bluetooth/BluetoothGattCallback.java b/core/java/android/bluetooth/BluetoothGattCallback.java
index 11a15c6..c6f82ff 100644
--- a/core/java/android/bluetooth/BluetoothGattCallback.java
+++ b/core/java/android/bluetooth/BluetoothGattCallback.java
@@ -30,7 +30,8 @@
      *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}.
      * @param rxPhy the receiver PHY in use. One of {@link BluetoothDevice#PHY_LE_1M},
      *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}.
-     * @param status status of the operation
+     * @param status Status of the PHY update operation.
+     *                  {@link BluetoothGatt#GATT_SUCCESS} if the operation succeeds.
      */
     public void onPhyUpdate(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
     }
@@ -43,7 +44,8 @@
      *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}.
      * @param rxPhy the receiver PHY in use. One of {@link BluetoothDevice#PHY_LE_1M},
      *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}.
-     * @param status status of the operation
+     * @param status Status of the PHY read operation.
+     *                  {@link BluetoothGatt#GATT_SUCCESS} if the operation succeeds.
      */
     public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
     }
diff --git a/core/java/android/bluetooth/BluetoothGattServerCallback.java b/core/java/android/bluetooth/BluetoothGattServerCallback.java
index 3b8f962..02307bd 100644
--- a/core/java/android/bluetooth/BluetoothGattServerCallback.java
+++ b/core/java/android/bluetooth/BluetoothGattServerCallback.java
@@ -167,7 +167,8 @@
      *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}
      * @param rxPhy the receiver PHY in use. One of {@link BluetoothDevice#PHY_LE_1M},
      *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}
-     * @param status status of the operation
+     * @param status Status of the PHY update operation.
+     *                  {@link BluetoothGatt#GATT_SUCCESS} if the operation succeeds.
      */
     public void onPhyUpdate(BluetoothDevice device, int txPhy, int rxPhy, int status) {
     }
@@ -180,7 +181,8 @@
      *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}
      * @param rxPhy the receiver PHY in use. One of {@link BluetoothDevice#PHY_LE_1M},
      *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}
-     * @param status status of the operation
+     * @param status Status of the PHY read operation.
+     *                  {@link BluetoothGatt#GATT_SUCCESS} if the operation succeeds.
      */
     public void onPhyRead(BluetoothDevice device, int txPhy, int rxPhy, int status) {
     }
diff --git a/core/java/android/bluetooth/IBluetoothGatt.aidl b/core/java/android/bluetooth/IBluetoothGatt.aidl
index 582709c..12e9baa 100644
--- a/core/java/android/bluetooth/IBluetoothGatt.aidl
+++ b/core/java/android/bluetooth/IBluetoothGatt.aidl
@@ -32,7 +32,6 @@
 
 import android.bluetooth.IBluetoothGattCallback;
 import android.bluetooth.IBluetoothGattServerCallback;
-import android.bluetooth.le.IAdvertiserCallback;
 import android.bluetooth.le.IAdvertisingSetCallback;
 import android.bluetooth.le.IPeriodicAdvertisingCallback;
 import android.bluetooth.le.IScannerCallback;
diff --git a/core/java/android/bluetooth/le/BluetoothLeAdvertiser.java b/core/java/android/bluetooth/le/BluetoothLeAdvertiser.java
index ea3031b..0c7958d 100644
--- a/core/java/android/bluetooth/le/BluetoothLeAdvertiser.java
+++ b/core/java/android/bluetooth/le/BluetoothLeAdvertiser.java
@@ -22,7 +22,6 @@
 import android.bluetooth.BluetoothUuid;
 import android.bluetooth.IBluetoothGatt;
 import android.bluetooth.IBluetoothManager;
-import android.bluetooth.le.IAdvertiserCallback;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.ParcelUuid;
diff --git a/core/java/android/bluetooth/le/IAdvertiserCallback.aidl b/core/java/android/bluetooth/le/IAdvertiserCallback.aidl
deleted file mode 100644
index c58b1df..0000000
--- a/core/java/android/bluetooth/le/IAdvertiserCallback.aidl
+++ /dev/null
@@ -1,29 +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.bluetooth.le;
-
-import android.bluetooth.le.AdvertiseSettings;
-
-/**
- * Callback definitions for interacting with Advertiser
- * @hide
- */
-oneway interface IAdvertiserCallback {
-    void onAdvertiserRegistered(in int status, in int advertiserId);
-
-    void onMultiAdvertiseCallback(in int status, boolean isStart,
-                                  in AdvertiseSettings advertiseSettings);
-}
diff --git a/core/java/android/content/IntentFilter.java b/core/java/android/content/IntentFilter.java
index d64f018..c9bce53 100644
--- a/core/java/android/content/IntentFilter.java
+++ b/core/java/android/content/IntentFilter.java
@@ -16,6 +16,7 @@
 
 package android.content;
 
+import android.annotation.IntDef;
 import android.annotation.SystemApi;
 import android.net.Uri;
 import android.os.Parcel;
@@ -33,6 +34,8 @@
 import org.xmlpull.v1.XmlSerializer;
 
 import java.io.IOException;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.Set;
@@ -283,9 +286,22 @@
     private static final int STATE_VERIFIED            = 0x00001000;
 
     private int mVerifyState;
-
+    /** @hide */
+    public static final int VISIBILITY_NONE = 0;
+    /** @hide */
+    public static final int VISIBILITY_EXPLICIT = 1;
+    /** @hide */
+    public static final int VISIBILITY_IMPLICIT = 2;
+    /** @hide */
+    @IntDef(prefix = { "VISIBILITY_" }, value = {
+            VISIBILITY_NONE,
+            VISIBILITY_EXPLICIT,
+            VISIBILITY_IMPLICIT,
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface InstantAppVisibility {}
     /** Whether or not the intent filter is visible to instant apps. */
-    private boolean mVisibleToInstantApp;
+    private @InstantAppVisibility int mInstantAppVisibility;
     // These functions are the start of more optimized code for managing
     // the string sets...  not yet implemented.
 
@@ -452,7 +468,7 @@
         }
         mHasPartialTypes = o.mHasPartialTypes;
         mVerifyState = o.mVerifyState;
-        mVisibleToInstantApp = o.mVisibleToInstantApp;
+        mInstantAppVisibility = o.mInstantAppVisibility;
     }
 
     /**
@@ -655,12 +671,24 @@
     }
 
     /** @hide */
-    public void setVisibleToInstantApp(boolean visibleToInstantApp) {
-        mVisibleToInstantApp = visibleToInstantApp;
+    public void setVisibilityToInstantApp(@InstantAppVisibility int visibility) {
+        mInstantAppVisibility = visibility;
+    }
+    /** @hide */
+    public @InstantAppVisibility int getVisibilityToInstantApp() {
+        return mInstantAppVisibility;
     }
     /** @hide */
     public boolean isVisibleToInstantApp() {
-        return mVisibleToInstantApp;
+        return mInstantAppVisibility != VISIBILITY_NONE;
+    }
+    /** @hide */
+    public boolean isExplicitlyVisibleToInstantApp() {
+        return mInstantAppVisibility == VISIBILITY_EXPLICIT;
+    }
+    /** @hide */
+    public boolean isImplicitlyVisibleToInstantApp() {
+        return mInstantAppVisibility == VISIBILITY_IMPLICIT;
     }
 
     /**
@@ -1859,7 +1887,7 @@
         dest.writeInt(mPriority);
         dest.writeInt(mHasPartialTypes ? 1 : 0);
         dest.writeInt(getAutoVerify() ? 1 : 0);
-        dest.writeInt(isVisibleToInstantApp() ? 1 : 0);
+        dest.writeInt(mInstantAppVisibility);
     }
 
     /**
@@ -1928,7 +1956,7 @@
         mPriority = source.readInt();
         mHasPartialTypes = source.readInt() > 0;
         setAutoVerify(source.readInt() > 0);
-        setVisibleToInstantApp(source.readInt() > 0);
+        setVisibilityToInstantApp(source.readInt());
     }
 
     private final boolean findMimeType(String type) {
diff --git a/core/java/android/content/pm/ActivityInfo.java b/core/java/android/content/pm/ActivityInfo.java
index b01e6a1..0be0885 100644
--- a/core/java/android/content/pm/ActivityInfo.java
+++ b/core/java/android/content/pm/ActivityInfo.java
@@ -17,6 +17,7 @@
 package android.content.pm;
 
 import android.annotation.IntDef;
+import android.content.Intent;
 import android.content.res.Configuration;
 import android.content.res.Configuration.NativeConfig;
 import android.os.Parcel;
@@ -412,17 +413,33 @@
     public static final int FLAG_ALWAYS_FOCUSABLE = 0x40000;
 
     /**
-     * Bit in {@link #flags} indicating if the activity is visible to ephemeral applications.
+     * Bit in {@link #flags} indicating if the activity is visible to instant
+     * applications. The activity is visible if it's either implicitly or
+     * explicitly exposed.
      * @hide
      */
-    public static final int FLAG_VISIBLE_TO_EPHEMERAL = 0x100000;
+    public static final int FLAG_VISIBLE_TO_INSTANT_APP = 0x100000;
+
+    /**
+     * Bit in {@link #flags} indicating if the activity is implicitly visible
+     * to instant applications. Implicitly visible activities are those that
+     * implement certain intent-filters:
+     * <ul>
+     * <li>action {@link Intent#CATEGORY_BROWSABLE}</li>
+     * <li>action {@link Intent#ACTION_SEND}</li>
+     * <li>action {@link Intent#ACTION_SENDTO}</li>
+     * <li>action {@link Intent#ACTION_SEND_MULTIPLE}</li>
+     * </ul>
+     * @hide
+     */
+    public static final int FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP = 0x200000;
 
     /**
      * Bit in {@link #flags} indicating if the activity supports picture-in-picture mode.
      * See {@link android.R.attr#supportsPictureInPicture}.
      * @hide
      */
-    public static final int FLAG_SUPPORTS_PICTURE_IN_PICTURE = 0x200000;
+    public static final int FLAG_SUPPORTS_PICTURE_IN_PICTURE = 0x400000;
 
     /**
      * @hide Bit in {@link #flags}: If set, this component will only be seen
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index ecaf7eb..d2468d9 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -461,12 +461,20 @@
 
     /**
      * Internal {@link PackageInfo} flag: include only components that are exposed to
-     * ephemeral apps.
+     * instant apps. Matched components may have been either explicitly or implicitly
+     * exposed.
      * @hide
      */
     public static final int MATCH_VISIBLE_TO_INSTANT_APP_ONLY = 0x01000000;
 
     /**
+     * Internal {@link PackageInfo} flag: include only components that have been
+     * explicitly exposed to instant apps.
+     * @hide
+     */
+    public static final int MATCH_EXPLICITLY_VISIBLE_ONLY = 0x02000000;
+
+    /**
      * Internal flag used to indicate that a system component has done their
      * homework and verified that they correctly handle packages and components
      * that come and go over time. In particular:
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 8609351..e4db0f0 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -4271,7 +4271,7 @@
         boolean visibleToEphemeral =
                 sa.getBoolean(R.styleable.AndroidManifestActivity_visibleToInstantApps, false);
         if (visibleToEphemeral) {
-            a.info.flags |= ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL;
+            a.info.flags |= ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP;
             owner.visibleToInstantApps = true;
         }
 
@@ -4313,9 +4313,17 @@
                     a.intents.add(intent);
                 }
                 // adjust activity flags when we implicitly expose it via a browsable filter
-                intent.setVisibleToInstantApp(visibleToEphemeral || isImplicitlyExposedIntent(intent));
+                final int visibility = visibleToEphemeral
+                        ? IntentFilter.VISIBILITY_EXPLICIT
+                        : !receiver && isImplicitlyExposedIntent(intent)
+                                ? IntentFilter.VISIBILITY_IMPLICIT
+                                : IntentFilter.VISIBILITY_NONE;
+                intent.setVisibilityToInstantApp(visibility);
                 if (intent.isVisibleToInstantApp()) {
-                    a.info.flags |= ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL;
+                    a.info.flags |= ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP;
+                }
+                if (intent.isImplicitlyVisibleToInstantApp()) {
+                    a.info.flags |= ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP;
                 }
                 if (LOG_UNSAFE_BROADCASTS && receiver
                         && (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.O)) {
@@ -4346,9 +4354,17 @@
                     owner.preferredActivityFilters.add(intent);
                 }
                 // adjust activity flags when we implicitly expose it via a browsable filter
-                intent.setVisibleToInstantApp(visibleToEphemeral || isImplicitlyExposedIntent(intent));
+                final int visibility = visibleToEphemeral
+                        ? IntentFilter.VISIBILITY_EXPLICIT
+                        : !receiver && isImplicitlyExposedIntent(intent)
+                                ? IntentFilter.VISIBILITY_IMPLICIT
+                                : IntentFilter.VISIBILITY_NONE;
+                intent.setVisibilityToInstantApp(visibility);
                 if (intent.isVisibleToInstantApp()) {
-                    a.info.flags |= ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL;
+                    a.info.flags |= ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP;
+                }
+                if (intent.isImplicitlyVisibleToInstantApp()) {
+                    a.info.flags |= ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP;
                 }
             } else if (parser.getName().equals("meta-data")) {
                 if ((a.metaData = parseMetaData(res, parser, a.metaData,
@@ -4358,16 +4374,18 @@
                 // we don't have an attribute [or it's false], but, we have meta-data
                 if (!visibleToEphemeral && a.metaData.getBoolean(META_DATA_INSTANT_APPS)) {
                     visibleToEphemeral = true; // set in case there are more intent filters
-                    a.info.flags |= ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL;
+                    a.info.flags |= ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP;
+                    a.info.flags &= ~ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP;
                     owner.visibleToInstantApps = true;
                     // cycle through any filters already seen
                     for (int i = a.intents.size() - 1; i >= 0; --i) {
-                        a.intents.get(i).setVisibleToInstantApp(true /*visibleToInstantApp*/);
+                        a.intents.get(i)
+                                .setVisibilityToInstantApp(IntentFilter.VISIBILITY_EXPLICIT);
                     }
                     if (owner.preferredActivityFilters != null) {
                         for (int i = owner.preferredActivityFilters.size() - 1; i >= 0; --i) {
                             owner.preferredActivityFilters.get(i)
-                                    .setVisibleToInstantApp(true /*visibleToInstantApp*/);
+                                    .setVisibilityToInstantApp(IntentFilter.VISIBILITY_EXPLICIT);
                         }
                     }
                 }
@@ -4645,7 +4663,7 @@
 
         // TODO add visibleToInstantApps attribute to activity alias
         final boolean visibleToEphemeral =
-                ((a.info.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0);
+                ((a.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0);
 
         sa.recycle();
 
@@ -4673,13 +4691,20 @@
                             + mArchiveSourcePath + " "
                             + parser.getPositionDescription());
                 } else {
-                    intent.setVisibleToInstantApp(
-                            visibleToEphemeral || isImplicitlyExposedIntent(intent));
                     a.intents.add(intent);
                 }
                 // adjust activity flags when we implicitly expose it via a browsable filter
+                final int visibility = visibleToEphemeral
+                        ? IntentFilter.VISIBILITY_EXPLICIT
+                        : isImplicitlyExposedIntent(intent)
+                                ? IntentFilter.VISIBILITY_IMPLICIT
+                                : IntentFilter.VISIBILITY_NONE;
+                intent.setVisibilityToInstantApp(visibility);
                 if (intent.isVisibleToInstantApp()) {
-                    a.info.flags |= ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL;
+                    a.info.flags |= ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP;
+                }
+                if (intent.isImplicitlyVisibleToInstantApp()) {
+                    a.info.flags |= ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP;
                 }
             } else if (parser.getName().equals("meta-data")) {
                 if ((a.metaData=parseMetaData(res, parser, a.metaData,
@@ -4822,7 +4847,7 @@
         final boolean visibleToEphemeral =
                 sa.getBoolean(R.styleable.AndroidManifestProvider_visibleToInstantApps, false);
         if (visibleToEphemeral) {
-            p.info.flags |= ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL;
+            p.info.flags |= ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP;
             owner.visibleToInstantApps = true;
         }
 
@@ -4874,12 +4899,11 @@
                         intent, outError)) {
                     return false;
                 }
-                outInfo.intents.add(intent);
-                // adjust provider flags when we implicitly expose it via a browsable filter
-                intent.setVisibleToInstantApp(visibleToEphemeral || isImplicitlyExposedIntent(intent));
-                if (intent.isVisibleToInstantApp()) {
-                    outInfo.info.flags |= ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL;
+                if (visibleToEphemeral) {
+                    intent.setVisibilityToInstantApp(IntentFilter.VISIBILITY_EXPLICIT);
+                    outInfo.info.flags |= ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP;
                 }
+                outInfo.intents.add(intent);
 
             } else if (parser.getName().equals("meta-data")) {
                 if ((outInfo.metaData=parseMetaData(res, parser,
@@ -4889,11 +4913,12 @@
                 // we don't have an attribute [or it's false], but, we have meta-data
                 if (!visibleToEphemeral && outInfo.metaData.getBoolean(META_DATA_INSTANT_APPS)) {
                     visibleToEphemeral = true; // set in case there are more intent filters
-                    outInfo.info.flags |= ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL;
+                    outInfo.info.flags |= ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP;
                     owner.visibleToInstantApps = true;
                     // cycle through any filters already seen
                     for (int i = outInfo.intents.size() - 1; i >= 0; --i) {
-                        outInfo.intents.get(i).setVisibleToInstantApp(true /*visibleToInstantApp*/);
+                        outInfo.intents.get(i)
+                                .setVisibilityToInstantApp(IntentFilter.VISIBILITY_EXPLICIT);
                     }
                 }
 
@@ -5149,7 +5174,7 @@
         boolean visibleToEphemeral =
                 sa.getBoolean(R.styleable.AndroidManifestService_visibleToInstantApps, false);
         if (visibleToEphemeral) {
-            s.info.flags |= ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL;
+            s.info.flags |= ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP;
             owner.visibleToInstantApps = true;
         }
 
@@ -5180,10 +5205,9 @@
                         intent, outError)) {
                     return null;
                 }
-                // adjust activity flags when we implicitly expose it via a browsable filter
-                intent.setVisibleToInstantApp(visibleToEphemeral || isImplicitlyExposedIntent(intent));
-                if (intent.isVisibleToInstantApp()) {
-                    s.info.flags |= ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL;
+                if (visibleToEphemeral) {
+                    intent.setVisibilityToInstantApp(IntentFilter.VISIBILITY_EXPLICIT);
+                    s.info.flags |= ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP;
                 }
                 s.intents.add(intent);
             } else if (parser.getName().equals("meta-data")) {
@@ -5194,11 +5218,12 @@
                 // we don't have an attribute [or it's false], but, we have meta-data
                 if (!visibleToEphemeral && s.metaData.getBoolean(META_DATA_INSTANT_APPS)) {
                     visibleToEphemeral = true; // set in case there are more intent filters
-                    s.info.flags |= ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL;
+                    s.info.flags |= ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP;
                     owner.visibleToInstantApps = true;
                     // cycle through any filters already seen
                     for (int i = s.intents.size() - 1; i >= 0; --i) {
-                        s.intents.get(i).setVisibleToInstantApp(true /*visibleToInstantApp*/);
+                        s.intents.get(i)
+                                .setVisibilityToInstantApp(IntentFilter.VISIBILITY_EXPLICIT);
                     }
                 }
             } else {
diff --git a/core/java/android/content/pm/ProviderInfo.java b/core/java/android/content/pm/ProviderInfo.java
index 8c21563..91dc06e 100644
--- a/core/java/android/content/pm/ProviderInfo.java
+++ b/core/java/android/content/pm/ProviderInfo.java
@@ -79,7 +79,7 @@
      * Bit in {@link #flags} indicating if the provider is visible to ephemeral applications.
      * @hide
      */
-    public static final int FLAG_VISIBLE_TO_EPHEMERAL = 0x100000;
+    public static final int FLAG_VISIBLE_TO_INSTANT_APP = 0x100000;
 
     /**
      * Bit in {@link #flags}: If set, a single instance of the provider will
diff --git a/core/java/android/content/pm/ServiceInfo.java b/core/java/android/content/pm/ServiceInfo.java
index f0766be..c683ea5 100644
--- a/core/java/android/content/pm/ServiceInfo.java
+++ b/core/java/android/content/pm/ServiceInfo.java
@@ -59,7 +59,7 @@
      * Bit in {@link #flags} indicating if the service is visible to ephemeral applications.
      * @hide
      */
-    public static final int FLAG_VISIBLE_TO_EPHEMERAL = 0x100000;
+    public static final int FLAG_VISIBLE_TO_INSTANT_APP = 0x100000;
 
     /**
      * Bit in {@link #flags}: If set, a single instance of the service will
diff --git a/core/java/android/hardware/SystemSensorManager.java b/core/java/android/hardware/SystemSensorManager.java
index f5ad5cc..51506b0 100644
--- a/core/java/android/hardware/SystemSensorManager.java
+++ b/core/java/android/hardware/SystemSensorManager.java
@@ -285,17 +285,22 @@
                 }
                 // Initialize a client for data_injection.
                 if (sInjectEventQueue == null) {
-                    sInjectEventQueue = new InjectEventQueue(mMainLooper, this,
-                            mContext.getPackageName());
+                    try {
+                        sInjectEventQueue = new InjectEventQueue(
+                                mMainLooper, this, mContext.getPackageName());
+                    } catch (RuntimeException e) {
+                        Log.e(TAG, "Cannot create InjectEventQueue: " + e);
+                    }
                 }
+                return sInjectEventQueue != null;
             } else {
                 // If data injection is being disabled clean up the native resources.
                 if (sInjectEventQueue != null) {
                     sInjectEventQueue.dispose();
                     sInjectEventQueue = null;
                 }
+                return true;
             }
-            return true;
         }
     }
 
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 69371be..cbd41c3 100755
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -6943,6 +6943,7 @@
             ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED,
             ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED,
             ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED,
+            AUTOFILL_SERVICE,
             ACCESSIBILITY_DISPLAY_MAGNIFICATION_SCALE,
             ENABLED_ACCESSIBILITY_SERVICES,
             ENABLED_NOTIFICATION_LISTENERS,
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index 1977ef5..b7834823 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -5823,34 +5823,6 @@
     }
 
     /**
-     * Quick invalidation method that simply transforms the dirty rect into the parent's
-     * coordinate system, pruning the invalidation if the parent has already been invalidated.
-     *
-     * @hide
-     */
-    protected ViewParent damageChildInParent(int left, int top, final Rect dirty) {
-        if ((mPrivateFlags & PFLAG_DRAWN) != 0
-                || (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) != 0) {
-            dirty.offset(left - mScrollX, top - mScrollY);
-            if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0) {
-                dirty.union(0, 0, mRight - mLeft, mBottom - mTop);
-            }
-
-            if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0 ||
-                    dirty.intersect(0, 0, mRight - mLeft, mBottom - mTop)) {
-
-                if (!getMatrix().isIdentity()) {
-                    transformRect(dirty);
-                }
-
-                return mParent;
-            }
-        }
-
-        return null;
-    }
-
-    /**
      * Offset a rectangle that is in a descendant's coordinate
      * space into our coordinate space.
      * @param descendant A descendant of this view
diff --git a/core/java/android/view/ViewOverlay.java b/core/java/android/view/ViewOverlay.java
index f061370..21123c1 100644
--- a/core/java/android/view/ViewOverlay.java
+++ b/core/java/android/view/ViewOverlay.java
@@ -330,20 +330,20 @@
 
         @Override
         public void onDescendantInvalidated(@NonNull View child, @NonNull View target) {
-            if (mHostView != null && mHostView.getParent() != null) {
-                mHostView.getParent().onDescendantInvalidated(mHostView, target);
-            }
-        }
+            if (mHostView != null) {
+                if (mHostView instanceof ViewGroup) {
+                    // Propagate invalidate through the host...
+                    ((ViewGroup) mHostView).onDescendantInvalidated(mHostView, target);
 
-        /**
-         * @hide
-         */
-        @Override
-        protected ViewParent damageChildInParent(int left, int top, Rect dirty) {
-            if (mHostView instanceof ViewGroup) {
-                return ((ViewGroup) mHostView).damageChildInParent(left, top, dirty);
+                    // ...and also this view, since it will hold the descendant, and must later
+                    // propagate the calls to update display lists if dirty
+                    super.onDescendantInvalidated(child, target);
+                } else {
+                    // Can't use onDescendantInvalidated because host isn't a ViewGroup - fall back
+                    // to invalidating.
+                    invalidate();
+                }
             }
-            return null;
         }
 
         @Override
diff --git a/core/java/android/widget/ArrayAdapter.java b/core/java/android/widget/ArrayAdapter.java
index 869ef71..74f22b3 100644
--- a/core/java/android/widget/ArrayAdapter.java
+++ b/core/java/android/widget/ArrayAdapter.java
@@ -37,19 +37,38 @@
 import java.util.List;
 
 /**
- * A concrete BaseAdapter that is backed by an array of arbitrary
- * objects.  By default this class expects that the provided resource id references
- * a single TextView.  If you want to use a more complex layout, use the constructors that
- * also takes a field id.  That field id should reference a TextView in the larger layout
- * resource.
- *
- * <p>However the TextView is referenced, it will be filled with the toString() of each object in
- * the array. You can add lists or arrays of custom objects. Override the toString() method
- * of your objects to determine what text will be displayed for the item in the list.
- *
- * <p>To use something other than TextViews for the array display, for instance, ImageViews,
- * or to have some of data besides toString() results fill the views,
- * override {@link #getView(int, View, ViewGroup)} to return the type of view you want.
+ * You can use this adapter to provide views for an {@link AdapterView},
+ * Returns a view for each object in a collection of data objects you
+ * provide, and can be used with list-based user interface widgets such as
+ * {@link ListView} or {@link Spinner}.
+ * <p>
+ * By default, the array adapter creates a view by calling {@link Object#toString()} on each
+ * data object in the collection you provide, and places the result in a TextView.
+ * You may also customize what type of view is used for the data object in the collection.
+ * To customize what type of view is used for the data object,
+ * override {@link #getView(int, View, ViewGroup)}
+ * and inflate a view resource.
+ * For a code example, see
+ * the <a href="https://developer.android.com/samples/CustomChoiceList/index.html">
+ * CustomChoiceList</a> sample.
+ * </p>
+ * <p>
+ * For an example of using an array adapter with a ListView, see the
+ * <a href="{@docRoot}guide/topics/ui/declaring-layout.html#AdapterViews">
+ * Adapter Views</a> guide.
+ * </p>
+ * <p>
+ * For an example of using an array adapter with a Spinner, see the
+ * <a href="{@docRoot}guide/topics/ui/controls/spinner.html">Spinners</a> guide.
+ * </p>
+ * <p class="note"><strong>Note:</strong>
+ * If you are considering using array adapter with a ListView, consider using
+ * {@link android.support.v7.widget.RecyclerView} instead.
+ * RecyclerView offers similar features with better performance and more flexibility than
+ * ListView provides.
+ * See the
+ * <a href="https://developer.android.com/guide/topics/ui/layout/recyclerview.html">
+ * Recycler View</a> guide.</p>
  */
 public class ArrayAdapter<T> extends BaseAdapter implements Filterable, ThemedSpinnerAdapter {
     /**
diff --git a/core/java/android/widget/ListView.java b/core/java/android/widget/ListView.java
index 12e35a1..569fe01 100644
--- a/core/java/android/widget/ListView.java
+++ b/core/java/android/widget/ListView.java
@@ -67,11 +67,77 @@
 
 
 /**
- * A view that shows items in a vertically scrolling list. The items
- * come from the {@link ListAdapter} associated with this view.
+ * <p>Displays a vertically-scrollable collection of views, where each view is positioned
+ * immediatelybelow the previous view in the list.  For a more modern, flexible, and performant
+ * approach to displaying lists, use {@link android.support.v7.widget.RecyclerView}.</p>
  *
- * <p>See the <a href="{@docRoot}guide/topics/ui/layout/listview.html">List View</a>
- * guide.</p>
+ * <p>To display a list, you can include a list view in your layout XML file:</p>
+ *
+ * <pre>&lt;ListView
+ *      android:id="@+id/list_view"
+ *      android:layout_width="match_parent"
+ *      android:layout_height="match_parent" /&gt;</pre>
+ *
+ * <p>A list view is an <a href="{@docRoot}guide/topics/ui/declaring-layout.html#AdapterViews">
+ * adapter view</a> that does not know the details, such as type and contents, of the views it
+ * contains. Instead list view requests views on demand from a {@link ListAdapter} as needed,
+ * such as to display new views as the user scrolls up or down.</p>
+ *
+ * <p>In order to display items in the list, call {@link #setAdapter(ListAdapter adapter)}
+ * to associate an adapter with the list.  For a simple example, see the discussion of filling an
+ * adapter view with text in the
+ * <a href="{@docRoot}guide/topics/ui/declaring-layout.html#FillingTheLayout">
+ * Layouts</a> guide.</p>
+ *
+ * <p>To display a more custom view for each item in your dataset, implement a ListAdapter.
+ * For example, extend {@link BaseAdapter} and create and configure the view for each data item in
+ * {@code getView(...)}:</p>
+ *
+ *  <pre>private class MyAdapter extends BaseAdapter {
+ *
+ *      // override other abstract methods here
+ *
+ *      &#64;Override
+ *      public View getView(int position, View convertView, ViewGroup container) {
+ *          if (convertView == null) {
+ *              convertView = getLayoutInflater().inflate(R.layout.list_item, container, false);
+ *          }
+ *
+ *          ((TextView) convertView.findViewById(android.R.id.text1))
+ *                  .setText(getItem(position));
+ *          return convertView;
+ *      }
+ *  }</pre>
+ *
+ * <p class="note">ListView attempts to reuse view objects in order to improve performance and
+ * avoid a lag in response to user scrolls.  To take advantage of this feature, check if the
+ * {@code convertView} provided to {@code getView(...)} is null before creating or inflating a new
+ * view object.  See
+ * <a href="{@docRoot}training/improving-layouts/smooth-scrolling.html">
+ * Making ListView Scrolling Smooth</a> for more ways to ensure a smooth user experience.</p>
+ *
+ * <p>For a more complete example of creating a custom adapter, see the
+ * <a href="{@docRoot}samples/CustomChoiceList/index.html">
+ *     Custom Choice List</a> sample app.</p>
+ *
+ * <p>To specify an action when a user clicks or taps on a single list item, see
+ * <a href="{@docRoot}guide/topics/ui/declaring-layout.html#HandlingUserSelections">
+ *     Handling click events</a>.</p>
+ *
+ * <p>To learn how to populate a list view with a CursorAdapter, see the discussion of filling an
+ * adapter view with text in the
+ * <a href="{@docRoot}guide/topics/ui/declaring-layout.html#FillingTheLayout">
+ * Layouts</a> guide.
+ * See <a href="{@docRoot}guide/topics/ui/layout/listview.html">
+ *     Using a Loader</a>
+ * to learn how to avoid blocking the main thread when using a cursor.</p>
+ *
+ * <p class="note">Note, many examples use {@link android.app.ListActivity ListActivity}
+ * or {@link android.app.ListFragment ListFragment}
+ * to display a list view. Instead, favor the more flexible approach when writing your own app:
+ * use a more generic Activity subclass or Fragment subclass and add a list view to the layout
+ * or view hierarchy directly.  This approach gives you more direct control of the
+ * list view and adapter.</p>
  *
  * @attr ref android.R.styleable#ListView_entries
  * @attr ref android.R.styleable#ListView_divider
diff --git a/core/jni/android_hardware_SensorManager.cpp b/core/jni/android_hardware_SensorManager.cpp
index d046996..f1b19e17 100644
--- a/core/jni/android_hardware_SensorManager.cpp
+++ b/core/jni/android_hardware_SensorManager.cpp
@@ -427,6 +427,11 @@
     String8 clientName(packageUtf.c_str());
     sp<SensorEventQueue> queue(mgr->createEventQueue(clientName, mode));
 
+    if (queue == NULL) {
+        jniThrowRuntimeException(env, "Cannot construct native SensorEventQueue.");
+        return 0;
+    }
+
     sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, msgQ);
     if (messageQueue == NULL) {
         jniThrowRuntimeException(env, "MessageQueue is not initialized.");
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 3e11368..3898cae 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -2332,10 +2332,18 @@
         <attr name="importantForAutofill">
             <!-- Let the Android System use its heuristics to determine if the view is important for autofill. -->
             <flag name="auto" value="0" />
-            <!-- Hint the Android System that this view is important for autofill. -->
+            <!-- Hint the Android System that this view is important for autofill,
+                  and its children (if any) will be traversed.. -->
             <flag name="yes" value="0x1" />
-            <!-- Hint the Android System that this view is *not* important for autofill. -->
+            <!-- Hint the Android System that this view is *not* important for autofill,
+                  but its children (if any) will be traversed.. -->
             <flag name="no" value="0x2" />
+            <!-- Hint the Android System that this view is important for autofill,
+                 but its children (if any) will not be traversed. -->
+            <flag name="yesExcludeDescendants" value="0x4" />
+            <!-- Hint the Android System that this view is *not* important for autofill,
+                 and its children (if any) will not be traversed. -->
+            <flag name="noExcludeDescendants" value="0x8" />
         </attr>
 
         <!-- Boolean that controls whether a view can take focus while in touch mode.
diff --git a/core/tests/coretests/src/android/provider/SettingsBackupTest.java b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
index 38ab865..4586940 100644
--- a/core/tests/coretests/src/android/provider/SettingsBackupTest.java
+++ b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
@@ -37,7 +37,8 @@
 
 /** Tests that ensure appropriate settings are backed up. */
 @RunWith(AndroidJUnit4.class)
-@Presubmit
+// TODO(b/37684646): Can re-enable pre-submit once test is fixed.
+//@Presubmit
 @SmallTest
 public class SettingsBackupTest {
 
diff --git a/libs/hwui/Texture.h b/libs/hwui/Texture.h
index 052c018..55b74ed 100644
--- a/libs/hwui/Texture.h
+++ b/libs/hwui/Texture.h
@@ -28,6 +28,7 @@
 #include <ui/ColorSpace.h>
 
 #include <GLES2/gl2.h>
+#include <GLES3/gl3.h>
 #include <EGL/egl.h>
 #include <EGL/eglext.h>
 #include <SkBitmap.h>
diff --git a/media/java/android/media/tv/TvContract.java b/media/java/android/media/tv/TvContract.java
index 2e8b0ae..947adfc 100644
--- a/media/java/android/media/tv/TvContract.java
+++ b/media/java/android/media/tv/TvContract.java
@@ -2997,6 +2997,8 @@
          */
         public static final String COLUMN_LAST_ENGAGEMENT_TIME_UTC_MILLIS =
                 "last_engagement_time_utc_millis";
+
+        private WatchNextPrograms() {}
     }
 
     /**
diff --git a/services/backup/java/com/android/server/backup/BackupManagerService.java b/services/backup/java/com/android/server/backup/BackupManagerService.java
index 9301006..1b970e5 100644
--- a/services/backup/java/com/android/server/backup/BackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/BackupManagerService.java
@@ -5641,14 +5641,24 @@
     // The job scheduler says our constraints don't hold any more,
     // so tear down any ongoing backup task right away.
     void endFullBackup() {
-        synchronized (mQueueLock) {
-            if (mRunningFullBackupTask != null) {
-                if (DEBUG_SCHEDULING) {
-                    Slog.i(TAG, "Telling running backup to stop");
+        // offload the mRunningFullBackupTask.handleCancel() call to another thread,
+        // as we might have to wait for mCancelLock
+        Runnable endFullBackupRunnable = new Runnable() {
+            @Override
+            public void run() {
+                PerformFullTransportBackupTask pftbt = null;
+                synchronized (mQueueLock) {
+                    if (mRunningFullBackupTask != null) {
+                        if (DEBUG_SCHEDULING) {
+                            Slog.i(TAG, "Telling running backup to stop");
+                        }
+                        pftbt = mRunningFullBackupTask;
+                    }
                 }
-                mRunningFullBackupTask.handleCancel(true);
+                pftbt.handleCancel(true);
             }
-        }
+        };
+        new Thread(endFullBackupRunnable, "end-full-backup").start();
     }
 
     // ----- Restore infrastructure -----
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 45c2054..01ef01b 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -411,6 +411,7 @@
 import com.android.server.pm.Installer.InstallerException;
 import com.android.server.statusbar.StatusBarManagerInternal;
 import com.android.server.vr.VrManagerInternal;
+import com.android.server.wm.PinnedStackWindowController;
 import com.android.server.wm.WindowManagerService;
 
 import org.xmlpull.v1.XmlPullParser;
@@ -7818,10 +7819,15 @@
         try {
             synchronized(this) {
                 final ActivityStack stack = ActivityRecord.getStackLocked(token);
-                if (stack == null) {
+                if (stack == null || stack.mStackId != PINNED_STACK_ID) {
                     return false;
                 }
-                return stack.mStackId == PINNED_STACK_ID;
+
+                // If we are animating to fullscreen then we have already dispatched the PIP mode
+                // changed, so we should reflect that check here as well.
+                final PinnedStackWindowController windowController =
+                        ((PinnedActivityStack) stack).getWindowContainerController();
+                return !windowController.isAnimatingBoundsToFullscreen();
             }
         } finally {
             Binder.restoreCallingIdentity(origId);
@@ -11255,9 +11261,13 @@
                     holder.provider = null;
                     return holder;
                 }
-                // Don't expose instant app providers
-                if (cpr.appInfo.isInstantApp()) {
-                    return null;
+                // Don't expose providers between normal apps and instant apps
+                try {
+                    if (AppGlobals.getPackageManager()
+                            .resolveContentProvider(name, 0 /*flags*/, userId) == null) {
+                        return null;
+                    }
+                } catch (RemoteException e) {
                 }
 
                 final long origId = Binder.clearCallingIdentity();
diff --git a/services/core/java/com/android/server/am/BroadcastQueue.java b/services/core/java/com/android/server/am/BroadcastQueue.java
index 349180f..d08298b 100644
--- a/services/core/java/com/android/server/am/BroadcastQueue.java
+++ b/services/core/java/com/android/server/am/BroadcastQueue.java
@@ -1180,7 +1180,7 @@
                 skip = true;
             }
             if (!skip && r.callerInstantApp
-                    && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0
+                    && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0
                     && r.callingUid != info.activityInfo.applicationInfo.uid) {
                 Slog.w(TAG, "Instant App Denial: receiving "
                         + r.intent
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 4aa19ee..7bbb1fe 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -4074,14 +4074,26 @@
      * action and a {@code android.intent.category.BROWSABLE} category</li>
      * </ul>
      */
+    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
+        return updateFlagsForResolve(flags, userId, intent, callingUid,
+                false /*includeInstantApps*/, false /*onlyExposedExplicitly*/);
+    }
     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
             boolean includeInstantApps) {
+        return updateFlagsForResolve(flags, userId, intent, callingUid,
+                includeInstantApps, false /*onlyExposedExplicitly*/);
+    }
+    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
+            boolean includeInstantApps, boolean onlyExposedExplicitly) {
         // Safe mode means we shouldn't match any third-party components
         if (mSafeMode) {
             flags |= PackageManager.MATCH_SYSTEM_ONLY;
         }
         if (getInstantAppPackageName(callingUid) != null) {
             // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
+            if (onlyExposedExplicitly) {
+                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
+            }
             flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
             flags |= PackageManager.MATCH_INSTANT;
         } else {
@@ -4098,7 +4110,8 @@
                     || isSpecialProcess
                     || mContext.checkCallingOrSelfPermission(
                             android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
-            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
+            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
+                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
             if (!allowMatchInstant) {
                 flags &= ~PackageManager.MATCH_INSTANT;
             }
@@ -5659,19 +5672,19 @@
     }
 
     private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
-            int flags, int userId, boolean includeInstantApps) {
+            int flags, int userId, boolean resolveForStart) {
         try {
             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
 
             if (!sUserManager.exists(userId)) return null;
             final int callingUid = Binder.getCallingUid();
-            flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
+            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
             enforceCrossUserPermission(callingUid, userId,
                     false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
 
             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
             final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
-                    flags, userId, includeInstantApps);
+                    flags, userId, resolveForStart);
             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
 
             final ResolveInfo bestChoice =
@@ -6208,14 +6221,14 @@
     }
 
     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
-            String resolvedType, int flags, int userId, boolean includeInstantApps) {
+            String resolvedType, int flags, int userId, boolean resolveForStart) {
         if (!sUserManager.exists(userId)) return Collections.emptyList();
         final int callingUid = Binder.getCallingUid();
         final String instantAppPkgName = getInstantAppPackageName(callingUid);
-        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
         enforceCrossUserPermission(callingUid, userId,
                 false /* requireFullPermission */, false /* checkShell */,
                 "query intent activities");
+        final String pkgName = intent.getPackage();
         ComponentName comp = intent.getComponent();
         if (comp == null) {
             if (intent.getSelector() != null) {
@@ -6224,6 +6237,8 @@
             }
         }
 
+        flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart,
+                comp != null || pkgName != null /*onlyExposedExplicitly*/);
         if (comp != null) {
             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
             final ActivityInfo ai = getActivityInfo(comp, flags, userId);
@@ -6236,6 +6251,8 @@
                         (flags & PackageManager.MATCH_INSTANT) != 0;
                 final boolean matchVisibleToInstantAppOnly =
                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
+                final boolean matchExplicitlyVisibleOnly =
+                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
                 final boolean isCallerInstantApp =
                         instantAppPkgName != null;
                 final boolean isTargetSameInstantApp =
@@ -6243,8 +6260,14 @@
                 final boolean isTargetInstantApp =
                         (ai.applicationInfo.privateFlags
                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
+                final boolean isTargetVisibleToInstantApp =
+                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
+                final boolean isTargetExplicitlyVisibleToInstantApp =
+                        isTargetVisibleToInstantApp
+                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
                 final boolean isTargetHiddenFromInstantApp =
-                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
+                        !isTargetVisibleToInstantApp
+                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
                 final boolean blockResolution =
                         !isTargetSameInstantApp
                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
@@ -6263,7 +6286,6 @@
         boolean sortResult = false;
         boolean addEphemeral = false;
         List<ResolveInfo> result;
-        final String pkgName = intent.getPackage();
         final boolean ephemeralDisabled = isEphemeralDisabled();
         synchronized (mPackages) {
             if (pkgName == null) {
@@ -6529,7 +6551,7 @@
             }
             // allow activities that have been explicitly exposed to ephemeral apps
             if (!isEphemeralApp
-                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
+                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
                 continue;
             }
             resolveInfos.remove(i);
@@ -7069,16 +7091,16 @@
     @Override
     public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
         final int callingUid = Binder.getCallingUid();
-        return resolveServiceInternal(
-                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
+        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
     }
 
     private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
-            int userId, int callingUid, boolean includeInstantApps) {
+            int userId, int callingUid) {
         if (!sUserManager.exists(userId)) return null;
-        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
+        flags = updateFlagsForResolve(
+                flags, userId, intent, callingUid, false /*includeInstantApps*/);
         List<ResolveInfo> query = queryIntentServicesInternal(
-                intent, resolvedType, flags, userId, callingUid, includeInstantApps);
+                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
         if (query != null) {
             if (query.size() >= 1) {
                 // If there is more than one service with the same priority,
@@ -7130,7 +7152,7 @@
                         (si.applicationInfo.privateFlags
                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
                 final boolean isTargetHiddenFromInstantApp =
-                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
+                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
                 final boolean blockResolution =
                         !isTargetSameInstantApp
                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
@@ -7202,7 +7224,7 @@
             }
             // allow services that have been explicitly exposed to ephemeral apps
             if (!isEphemeralApp
-                    && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
+                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
                 continue;
             }
             resolveInfos.remove(i);
@@ -7251,7 +7273,7 @@
                         (pi.applicationInfo.privateFlags
                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
                 final boolean isTargetHiddenFromInstantApp =
-                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
+                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
                 final boolean blockResolution =
                         !isTargetSameInstantApp
                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
@@ -7323,7 +7345,7 @@
             }
             // allow providers that have been explicitly exposed to instant applications
             if (!isEphemeralApp
-                    && ((info.providerInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
+                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
                 continue;
             }
             resolveInfos.remove(i);
@@ -7684,7 +7706,7 @@
                 // instant application; filter out non-exposed provider
                 if (instantAppPkgName != null
                         && !isInstantApp
-                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0) {
+                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
                     return null;
                 }
                 // provider not enabled
@@ -12430,16 +12452,21 @@
             if (ai == null) {
                 return null;
             }
+            final boolean matchExplicitlyVisibleOnly =
+                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
             final boolean matchVisibleToInstantApp =
                     (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
-            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
+            final boolean componentVisible =
+                    matchVisibleToInstantApp
+                    && info.isVisibleToInstantApp()
+                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
+            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
             // throw out filters that aren't visible to ephemeral apps
-            if (matchVisibleToInstantApp
-                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
+            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
                 return null;
             }
-            // throw out ephemeral filters if we're not explicitly requesting them
-            if (!isInstantApp && userState.instantApp) {
+            // throw out instant app filters if we're not explicitly requesting them
+            if (!matchInstantApp && userState.instantApp) {
                 return null;
             }
             // throw out instant app filters if updates are available; will trigger
@@ -23521,14 +23548,13 @@
         public ResolveInfo resolveIntent(Intent intent, String resolvedType,
                 int flags, int userId) {
             return resolveIntentInternal(
-                    intent, resolvedType, flags, userId, true /*includeInstantApps*/);
+                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
         }
 
         @Override
         public ResolveInfo resolveService(Intent intent, String resolvedType,
                 int flags, int userId, int callingUid) {
-            return resolveServiceInternal(
-                    intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/);
+            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
         }
 
         @Override
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 6cde53a..05ec479 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -4318,7 +4318,10 @@
                     if (mWaitingForConfig) {
                         mWaitingForConfig = false;
                         mLastFinishedFreezeSource = "config-unchanged";
-                        mRoot.getDisplayContent(displayId).setLayoutNeeded();
+                        final DisplayContent dc = mRoot.getDisplayContent(displayId);
+                        if (dc != null) {
+                            dc.setLayoutNeeded();
+                        }
                         mWindowPlacerLocked.performSurfacePlacement();
                     }
                 }
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DeviceAdminServiceController.java b/services/devicepolicy/java/com/android/server/devicepolicy/DeviceAdminServiceController.java
index 97fa9d55..c7b8f02 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DeviceAdminServiceController.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DeviceAdminServiceController.java
@@ -15,6 +15,7 @@
  */
 package com.android.server.devicepolicy;
 
+import android.Manifest.permission;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.app.admin.DevicePolicyManager;
@@ -115,10 +116,12 @@
                 return null;
             }
             final ServiceInfo si = list.get(0).serviceInfo;
-            if (si.exported) {
-                Log.e(TAG, "DeviceAdminService must not be exported: '"
+
+            if (!permission.BIND_DEVICE_ADMIN.equals(si.permission)) {
+                Log.e(TAG, "DeviceAdminService "
                         + si.getComponentName().flattenToShortString()
-                        + "' will be ignored.");
+                        + " must be protected with " + permission.BIND_DEVICE_ADMIN
+                        + ".");
                 return null;
             }
             return si;
diff --git a/services/tests/servicestests/src/com/android/server/wm/AppBoundsTests.java b/services/tests/servicestests/src/com/android/server/wm/AppBoundsTests.java
index f68e06a..a599427 100644
--- a/services/tests/servicestests/src/com/android/server/wm/AppBoundsTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/AppBoundsTests.java
@@ -19,7 +19,6 @@
 import android.app.ActivityManager;
 import android.content.res.Configuration;
 import android.graphics.Rect;
-import android.os.Debug;
 import android.view.DisplayInfo;
 import org.junit.Test;
 
@@ -53,11 +52,11 @@
      */
     @Test
     public void testRootConfigurationBounds() throws Exception {
-        final DisplayInfo info = sDisplayContent.getDisplayInfo();
+        final DisplayInfo info = mDisplayContent.getDisplayInfo();
         info.appWidth = 1024;
         info.appHeight = 768;
 
-        final Configuration config = sWm.computeNewConfiguration(sDisplayContent.getDisplayId());
+        final Configuration config = sWm.computeNewConfiguration(mDisplayContent.getDisplayId());
         // The bounds should always be positioned in the top left.
         assertEquals(config.appBounds.left, 0);
         assertEquals(config.appBounds.top, 0);
@@ -116,8 +115,8 @@
      */
     @Test
     public void testFullScreenFreeFormBounds() throws Exception {
-        final Rect fullScreenBounds = new Rect(0, 0, sDisplayInfo.logicalWidth,
-                sDisplayInfo.logicalHeight);
+        final Rect fullScreenBounds = new Rect(0, 0, mDisplayInfo.logicalWidth,
+                mDisplayInfo.logicalHeight);
         testStackBoundsConfiguration(null /*stackId*/, mParentBounds, fullScreenBounds,
                 mParentBounds);
     }
@@ -126,16 +125,16 @@
     private void testStackBoundsConfiguration(Integer stackId, Rect parentBounds, Rect bounds,
             Rect expectedConfigBounds) {
         final StackWindowController stackController = stackId != null ?
-                createStackControllerOnStackOnDisplay(stackId, sDisplayContent)
-                : createStackControllerOnDisplay(sDisplayContent);
+                createStackControllerOnStackOnDisplay(stackId, mDisplayContent)
+                : createStackControllerOnDisplay(mDisplayContent);
 
-        final Configuration parentConfig = sDisplayContent.getConfiguration();
+        final Configuration parentConfig = mDisplayContent.getConfiguration();
         parentConfig.setAppBounds(parentBounds);
 
         final Configuration config = new Configuration();
         stackController.adjustConfigurationForBounds(bounds, null /*insetBounds*/,
                 new Rect() /*nonDecorBounds*/, new Rect() /*stableBounds*/, false /*overrideWidth*/,
-                false /*overrideHeight*/, sDisplayInfo.logicalDensityDpi, config, parentConfig);
+                false /*overrideHeight*/, mDisplayInfo.logicalDensityDpi, config, parentConfig);
         // Assert that both expected and actual are null or are equal to each other
 
         assertTrue((expectedConfigBounds == null && config.appBounds == null)
diff --git a/services/tests/servicestests/src/com/android/server/wm/AppWindowContainerControllerTests.java b/services/tests/servicestests/src/com/android/server/wm/AppWindowContainerControllerTests.java
index d206407..dcbedb6 100644
--- a/services/tests/servicestests/src/com/android/server/wm/AppWindowContainerControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/AppWindowContainerControllerTests.java
@@ -48,14 +48,14 @@
                 createAppWindowController();
 
         // Assert token was added to display.
-        assertNotNull(sDisplayContent.getWindowToken(controller.mToken.asBinder()));
+        assertNotNull(mDisplayContent.getWindowToken(controller.mToken.asBinder()));
         // Assert that the container was created and linked.
         assertNotNull(controller.mContainer);
 
-        controller.removeContainer(sDisplayContent.getDisplayId());
+        controller.removeContainer(mDisplayContent.getDisplayId());
 
         // Assert token was remove from display.
-        assertNull(sDisplayContent.getWindowToken(controller.mToken.asBinder()));
+        assertNull(mDisplayContent.getWindowToken(controller.mToken.asBinder()));
         // Assert that the container was removed.
         assertNull(controller.mContainer);
     }
@@ -68,11 +68,11 @@
         // Assert orientation is unspecified to start.
         assertEquals(SCREEN_ORIENTATION_UNSPECIFIED, controller.getOrientation());
 
-        controller.setOrientation(SCREEN_ORIENTATION_LANDSCAPE, sDisplayContent.getDisplayId(),
+        controller.setOrientation(SCREEN_ORIENTATION_LANDSCAPE, mDisplayContent.getDisplayId(),
                 EMPTY /* displayConfig */, false /* freezeScreenIfNeeded */);
         assertEquals(SCREEN_ORIENTATION_LANDSCAPE, controller.getOrientation());
 
-        controller.removeContainer(sDisplayContent.getDisplayId());
+        controller.removeContainer(mDisplayContent.getDisplayId());
         // Assert orientation is unspecified to after container is removed.
         assertEquals(SCREEN_ORIENTATION_UNSPECIFIED, controller.getOrientation());
 
@@ -99,7 +99,7 @@
         controller.addStartingWindow(InstrumentationRegistry.getContext().getPackageName(),
                 android.R.style.Theme, null, "Test", 0, 0, 0, 0, null, true, true, false, true);
         waitUntilHandlersIdle();
-        final AppWindowToken atoken = controller.getAppWindowToken();
+        final AppWindowToken atoken = controller.getAppWindowToken(mDisplayContent);
         assertHasStartingWindow(atoken);
         controller.removeStartingWindow();
         waitUntilHandlersIdle();
@@ -119,8 +119,8 @@
                 android.R.style.Theme, null, "Test", 0, 0, 0, 0, controller1.mToken.asBinder(),
                 true, true, false, true);
         waitUntilHandlersIdle();
-        assertNoStartingWindow(controller1.getAppWindowToken());
-        assertHasStartingWindow(controller2.getAppWindowToken());
+        assertNoStartingWindow(controller1.getAppWindowToken(mDisplayContent));
+        assertHasStartingWindow(controller2.getAppWindowToken(mDisplayContent));
     }
 
     @Test
@@ -129,7 +129,7 @@
                 createAppWindowController();
         final WindowTestUtils.TestAppWindowContainerController controller2 =
                 createAppWindowController();
-        sPolicy.setRunnableWhenAddingSplashScreen(() -> {
+        ((TestWindowManagerPolicy) sWm.mPolicy).setRunnableWhenAddingSplashScreen(() -> {
 
             // Surprise, ...! Transfer window in the middle of the creation flow.
             controller2.addStartingWindow(InstrumentationRegistry.getContext().getPackageName(),
@@ -139,14 +139,14 @@
         controller1.addStartingWindow(InstrumentationRegistry.getContext().getPackageName(),
                 android.R.style.Theme, null, "Test", 0, 0, 0, 0, null, true, true, false, true);
         waitUntilHandlersIdle();
-        assertNoStartingWindow(controller1.getAppWindowToken());
-        assertHasStartingWindow(controller2.getAppWindowToken());
+        assertNoStartingWindow(controller1.getAppWindowToken(mDisplayContent));
+        assertHasStartingWindow(controller2.getAppWindowToken(mDisplayContent));
     }
 
     @Test
     public void testReparent() throws Exception {
         final StackWindowController stackController =
-            createStackControllerOnDisplay(sDisplayContent);
+            createStackControllerOnDisplay(mDisplayContent);
         final WindowTestUtils.TestTaskWindowContainerController taskController1 =
                 new WindowTestUtils.TestTaskWindowContainerController(stackController);
         final WindowTestUtils.TestAppWindowContainerController appWindowController1 =
@@ -183,7 +183,8 @@
     }
 
     private WindowTestUtils.TestAppWindowContainerController createAppWindowController() {
-        return createAppWindowController(new WindowTestUtils.TestTaskWindowContainerController());
+        return createAppWindowController(
+                new WindowTestUtils.TestTaskWindowContainerController(this));
     }
 
     private WindowTestUtils.TestAppWindowContainerController createAppWindowController(
diff --git a/services/tests/servicestests/src/com/android/server/wm/AppWindowTokenTests.java b/services/tests/servicestests/src/com/android/server/wm/AppWindowTokenTests.java
index 7a7ca3f..876008b 100644
--- a/services/tests/servicestests/src/com/android/server/wm/AppWindowTokenTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/AppWindowTokenTests.java
@@ -17,7 +17,6 @@
 package com.android.server.wm;
 
 import org.junit.Test;
-import org.junit.Ignore;
 import org.junit.runner.RunWith;
 
 import android.platform.test.annotations.Presubmit;
@@ -52,7 +51,7 @@
     @Test
     public void testAddWindow_Order() throws Exception {
         final WindowTestUtils.TestAppWindowToken token =
-                new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
 
         assertEquals(0, token.getWindowsCount());
 
@@ -80,7 +79,7 @@
     @Test
     public void testFindMainWindow() throws Exception {
         final WindowTestUtils.TestAppWindowToken token =
-                new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
 
         assertNull(token.findMainWindow());
 
@@ -102,10 +101,10 @@
         sWm.mDisplayEnabled = true;
 
         // Create an app window with token on a display.
-        final TaskStack stack = createTaskStackOnDisplay(sDisplayContent);
+        final TaskStack stack = createTaskStackOnDisplay(mDisplayContent);
         final Task task = createTaskInStack(stack, 0 /* userId */);
         final WindowTestUtils.TestAppWindowToken appWindowToken =
-                new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
         task.addChild(appWindowToken, 0);
         final WindowManager.LayoutParams attrs = new WindowManager.LayoutParams(
                 TYPE_BASE_APPLICATION);
@@ -115,17 +114,17 @@
 
         // Set initial orientation and update.
         appWindowToken.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
-        sWm.updateOrientationFromAppTokens(sDisplayContent.getOverrideConfiguration(), null,
-                sDisplayContent.getDisplayId());
-        assertEquals(SCREEN_ORIENTATION_LANDSCAPE, sDisplayContent.getLastOrientation());
+        sWm.updateOrientationFromAppTokens(mDisplayContent.getOverrideConfiguration(), null,
+                mDisplayContent.getDisplayId());
+        assertEquals(SCREEN_ORIENTATION_LANDSCAPE, mDisplayContent.getLastOrientation());
         appWindow.resizeReported = false;
 
         // Update the orientation to perform 180 degree rotation and check that resize was reported.
         appWindowToken.setOrientation(SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
-        sWm.updateOrientationFromAppTokens(sDisplayContent.getOverrideConfiguration(), null,
-                sDisplayContent.getDisplayId());
+        sWm.updateOrientationFromAppTokens(mDisplayContent.getOverrideConfiguration(), null,
+                mDisplayContent.getDisplayId());
         sWm.mRoot.performSurfacePlacement(false /* recoveringMemory */);
-        assertEquals(SCREEN_ORIENTATION_REVERSE_LANDSCAPE, sDisplayContent.getLastOrientation());
+        assertEquals(SCREEN_ORIENTATION_REVERSE_LANDSCAPE, mDisplayContent.getLastOrientation());
         assertTrue(appWindow.resizeReported);
         appWindow.removeImmediately();
     }
@@ -170,7 +169,7 @@
     @Test
     public void testGetOrientation() throws Exception {
         final WindowTestUtils.TestAppWindowToken token =
-                new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
         token.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
 
         token.setFillsParent(false);
diff --git a/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java b/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java
index 837ce56..e8dc69f 100644
--- a/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java
@@ -52,74 +52,74 @@
     @Test
     public void testForAllWindows() throws Exception {
         final WindowState exitingAppWindow = createWindow(null, TYPE_BASE_APPLICATION,
-                sDisplayContent, "exiting app");
+                mDisplayContent, "exiting app");
         final AppWindowToken exitingAppToken = exitingAppWindow.mAppToken;
         exitingAppToken.mIsExiting = true;
         exitingAppToken.getTask().mStack.mExitingAppTokens.add(exitingAppToken);
 
         assertForAllWindowsOrder(Arrays.asList(
-                sWallpaperWindow,
+                mWallpaperWindow,
                 exitingAppWindow,
-                sChildAppWindowBelow,
-                sAppWindow,
-                sChildAppWindowAbove,
-                sDockedDividerWindow,
-                sStatusBarWindow,
-                sNavBarWindow,
-                sImeWindow,
-                sImeDialogWindow));
+                mChildAppWindowBelow,
+                mAppWindow,
+                mChildAppWindowAbove,
+                mDockedDividerWindow,
+                mStatusBarWindow,
+                mNavBarWindow,
+                mImeWindow,
+                mImeDialogWindow));
     }
 
     @Test
     public void testForAllWindows_WithAppImeTarget() throws Exception {
         final WindowState imeAppTarget =
-                createWindow(null, TYPE_BASE_APPLICATION, sDisplayContent, "imeAppTarget");
+                createWindow(null, TYPE_BASE_APPLICATION, mDisplayContent, "imeAppTarget");
 
         sWm.mInputMethodTarget = imeAppTarget;
 
         assertForAllWindowsOrder(Arrays.asList(
-                sWallpaperWindow,
-                sChildAppWindowBelow,
-                sAppWindow,
-                sChildAppWindowAbove,
+                mWallpaperWindow,
+                mChildAppWindowBelow,
+                mAppWindow,
+                mChildAppWindowAbove,
                 imeAppTarget,
-                sImeWindow,
-                sImeDialogWindow,
-                sDockedDividerWindow,
-                sStatusBarWindow,
-                sNavBarWindow));
+                mImeWindow,
+                mImeDialogWindow,
+                mDockedDividerWindow,
+                mStatusBarWindow,
+                mNavBarWindow));
     }
 
     @Test
     public void testForAllWindows_WithChildWindowImeTarget() throws Exception {
-        sWm.mInputMethodTarget = sChildAppWindowAbove;
+        sWm.mInputMethodTarget = mChildAppWindowAbove;
 
         assertForAllWindowsOrder(Arrays.asList(
-                sWallpaperWindow,
-                sChildAppWindowBelow,
-                sAppWindow,
-                sChildAppWindowAbove,
-                sImeWindow,
-                sImeDialogWindow,
-                sDockedDividerWindow,
-                sStatusBarWindow,
-                sNavBarWindow));
+                mWallpaperWindow,
+                mChildAppWindowBelow,
+                mAppWindow,
+                mChildAppWindowAbove,
+                mImeWindow,
+                mImeDialogWindow,
+                mDockedDividerWindow,
+                mStatusBarWindow,
+                mNavBarWindow));
     }
 
     @Test
     public void testForAllWindows_WithStatusBarImeTarget() throws Exception {
-        sWm.mInputMethodTarget = sStatusBarWindow;
+        sWm.mInputMethodTarget = mStatusBarWindow;
 
         assertForAllWindowsOrder(Arrays.asList(
-                sWallpaperWindow,
-                sChildAppWindowBelow,
-                sAppWindow,
-                sChildAppWindowAbove,
-                sDockedDividerWindow,
-                sStatusBarWindow,
-                sImeWindow,
-                sImeDialogWindow,
-                sNavBarWindow));
+                mWallpaperWindow,
+                mChildAppWindowBelow,
+                mAppWindow,
+                mChildAppWindowAbove,
+                mDockedDividerWindow,
+                mStatusBarWindow,
+                mImeWindow,
+                mImeDialogWindow,
+                mNavBarWindow));
     }
 
     @Test
@@ -127,28 +127,28 @@
         // This window is set-up to be z-ordered between some windows that go in the same token like
         // the nav bar and status bar.
         final WindowState voiceInteractionWindow = createWindow(null, TYPE_VOICE_INTERACTION,
-                sDisplayContent, "voiceInteractionWindow");
+                mDisplayContent, "voiceInteractionWindow");
 
         assertForAllWindowsOrder(Arrays.asList(
-                sWallpaperWindow,
-                sChildAppWindowBelow,
-                sAppWindow,
-                sChildAppWindowAbove,
-                sDockedDividerWindow,
+                mWallpaperWindow,
+                mChildAppWindowBelow,
+                mAppWindow,
+                mChildAppWindowAbove,
+                mDockedDividerWindow,
                 voiceInteractionWindow,
-                sStatusBarWindow,
-                sNavBarWindow,
-                sImeWindow,
-                sImeDialogWindow));
+                mStatusBarWindow,
+                mNavBarWindow,
+                mImeWindow,
+                mImeDialogWindow));
     }
 
     @Test
     public void testComputeImeTarget() throws Exception {
         // Verify that an app window can be an ime target.
-        final WindowState appWin = createWindow(null, TYPE_APPLICATION, sDisplayContent, "appWin");
+        final WindowState appWin = createWindow(null, TYPE_APPLICATION, mDisplayContent, "appWin");
         appWin.setHasSurface(true);
         assertTrue(appWin.canBeImeTarget());
-        WindowState imeTarget = sDisplayContent.computeImeTarget(false /* updateImeTarget */);
+        WindowState imeTarget = mDisplayContent.computeImeTarget(false /* updateImeTarget */);
         assertEquals(appWin, imeTarget);
 
         // Verify that an child window can be an ime target.
@@ -156,7 +156,7 @@
                 TYPE_APPLICATION_ATTACHED_DIALOG, "childWin");
         childWin.setHasSurface(true);
         assertTrue(childWin.canBeImeTarget());
-        imeTarget = sDisplayContent.computeImeTarget(false /* updateImeTarget */);
+        imeTarget = mDisplayContent.computeImeTarget(false /* updateImeTarget */);
         assertEquals(childWin, imeTarget);
     }
 
@@ -182,12 +182,12 @@
         assertEquals(dc, token.getDisplayContent());
 
         // Move stack to first display.
-        sDisplayContent.moveStackToDisplay(stack, true /* onTop */);
-        assertEquals(sDisplayContent.getDisplayId(), stack.getDisplayContent().getDisplayId());
-        assertEquals(sDisplayContent, stack.getParent().getParent());
-        assertEquals(sDisplayContent, stack.getDisplayContent());
-        assertEquals(sDisplayContent, task.getDisplayContent());
-        assertEquals(sDisplayContent, token.getDisplayContent());
+        mDisplayContent.moveStackToDisplay(stack, true /* onTop */);
+        assertEquals(mDisplayContent.getDisplayId(), stack.getDisplayContent().getDisplayId());
+        assertEquals(mDisplayContent, stack.getParent().getParent());
+        assertEquals(mDisplayContent, stack.getDisplayContent());
+        assertEquals(mDisplayContent, task.getDisplayContent());
+        assertEquals(mDisplayContent, token.getDisplayContent());
     }
 
     /**
@@ -195,8 +195,8 @@
      */
     @Test
     public void testDisplayOverrideConfigUpdate() throws Exception {
-        final int displayId = sDisplayContent.getDisplayId();
-        final Configuration currentOverrideConfig = sDisplayContent.getOverrideConfiguration();
+        final int displayId = mDisplayContent.getDisplayId();
+        final Configuration currentOverrideConfig = mDisplayContent.getOverrideConfiguration();
 
         // Create new, slightly changed override configuration and apply it to the display.
         final Configuration newOverrideConfig = new Configuration(currentOverrideConfig);
@@ -206,7 +206,7 @@
         sWm.setNewDisplayOverrideConfiguration(newOverrideConfig, displayId);
 
         // Check that override config is applied.
-        assertEquals(newOverrideConfig, sDisplayContent.getOverrideConfiguration());
+        assertEquals(newOverrideConfig, mDisplayContent.getOverrideConfiguration());
     }
 
     /**
@@ -214,7 +214,7 @@
      */
     @Test
     public void testDefaultDisplayOverrideConfigUpdate() throws Exception {
-        final Configuration currentConfig = sDisplayContent.getConfiguration();
+        final Configuration currentConfig = mDisplayContent.getConfiguration();
 
         // Create new, slightly changed override configuration and apply it to the display.
         final Configuration newOverrideConfig = new Configuration(currentConfig);
@@ -239,7 +239,7 @@
     public void testFocusedWindowMultipleDisplays() throws Exception {
         // Create a focusable window and check that focus is calcualted correctly
         final WindowState window1 =
-                createWindow(null, TYPE_BASE_APPLICATION, sDisplayContent, "window1");
+                createWindow(null, TYPE_BASE_APPLICATION, mDisplayContent, "window1");
         assertEquals(window1, sWm.mRoot.computeFocusedWindow());
 
         // Check that a new display doesn't affect focus
@@ -264,30 +264,30 @@
         final int baseHeight = 2560;
         final int baseDensity = 300;
 
-        sDisplayContent.updateBaseDisplayMetrics(baseWidth, baseHeight, baseDensity);
+        mDisplayContent.updateBaseDisplayMetrics(baseWidth, baseHeight, baseDensity);
 
         final int maxWidth = 300;
         final int resultingHeight = (maxWidth * baseHeight) / baseWidth;
         final int resultingDensity = (maxWidth * baseDensity) / baseWidth;
 
-        sDisplayContent.setMaxUiWidth(maxWidth);
-        verifySizes(sDisplayContent, maxWidth, resultingHeight, resultingDensity);
+        mDisplayContent.setMaxUiWidth(maxWidth);
+        verifySizes(mDisplayContent, maxWidth, resultingHeight, resultingDensity);
 
         // Assert setting values again does not change;
-        sDisplayContent.updateBaseDisplayMetrics(baseWidth, baseHeight, baseDensity);
-        verifySizes(sDisplayContent, maxWidth, resultingHeight, resultingDensity);
+        mDisplayContent.updateBaseDisplayMetrics(baseWidth, baseHeight, baseDensity);
+        verifySizes(mDisplayContent, maxWidth, resultingHeight, resultingDensity);
 
         final int smallerWidth = 200;
         final int smallerHeight = 400;
         final int smallerDensity = 100;
 
         // Specify smaller dimension, verify that it is honored
-        sDisplayContent.updateBaseDisplayMetrics(smallerWidth, smallerHeight, smallerDensity);
-        verifySizes(sDisplayContent, smallerWidth, smallerHeight, smallerDensity);
+        mDisplayContent.updateBaseDisplayMetrics(smallerWidth, smallerHeight, smallerDensity);
+        verifySizes(mDisplayContent, smallerWidth, smallerHeight, smallerDensity);
 
         // Verify that setting the max width to a greater value than the base width has no effect
-        sDisplayContent.setMaxUiWidth(maxWidth);
-        verifySizes(sDisplayContent, smallerWidth, smallerHeight, smallerDensity);
+        mDisplayContent.setMaxUiWidth(maxWidth);
+        verifySizes(mDisplayContent, smallerWidth, smallerHeight, smallerDensity);
     }
 
     /**
@@ -295,17 +295,17 @@
      */
     @Test
     public void testPinnedStackLocation() {
-        createStackControllerOnStackOnDisplay(PINNED_STACK_ID, sDisplayContent);
-        final int initialStackCount = sDisplayContent.getStackCount();
+        createStackControllerOnStackOnDisplay(PINNED_STACK_ID, mDisplayContent);
+        final int initialStackCount = mDisplayContent.getStackCount();
         // Ensure that the pinned stack was placed at the end
-        assertEquals(initialStackCount - 1, sDisplayContent.getStaskPosById(PINNED_STACK_ID));
+        assertEquals(initialStackCount - 1, mDisplayContent.getStaskPosById(PINNED_STACK_ID));
         // By default, this should try to create a new stack on top
-        createTaskStackOnDisplay(sDisplayContent);
-        final int afterStackCount = sDisplayContent.getStackCount();
+        createTaskStackOnDisplay(mDisplayContent);
+        final int afterStackCount = mDisplayContent.getStackCount();
         // Make sure the stack count has increased
         assertEquals(initialStackCount + 1, afterStackCount);
         // Ensure that the pinned stack is still on top
-        assertEquals(afterStackCount - 1, sDisplayContent.getStaskPosById(PINNED_STACK_ID));
+        assertEquals(afterStackCount - 1, mDisplayContent.getStaskPosById(PINNED_STACK_ID));
     }
 
     private static void verifySizes(DisplayContent displayContent, int expectedBaseWidth,
@@ -319,7 +319,7 @@
         final LinkedList<WindowState> actualWindows = new LinkedList();
 
         // Test forward traversal.
-        sDisplayContent.forAllWindows(actualWindows::addLast, false /* traverseTopToBottom */);
+        mDisplayContent.forAllWindows(actualWindows::addLast, false /* traverseTopToBottom */);
         assertEquals(expectedWindows.size(), actualWindows.size());
         for (WindowState w : expectedWindows) {
             assertEquals(w, actualWindows.pollFirst());
@@ -327,7 +327,7 @@
         assertTrue(actualWindows.isEmpty());
 
         // Test backward traversal.
-        sDisplayContent.forAllWindows(actualWindows::addLast, true /* traverseTopToBottom */);
+        mDisplayContent.forAllWindows(actualWindows::addLast, true /* traverseTopToBottom */);
         assertEquals(expectedWindows.size(), actualWindows.size());
         for (WindowState w : expectedWindows) {
             assertEquals(w, actualWindows.pollLast());
diff --git a/services/tests/servicestests/src/com/android/server/wm/StackWindowControllerTests.java b/services/tests/servicestests/src/com/android/server/wm/StackWindowControllerTests.java
index 61f7f57..d9b99ee 100644
--- a/services/tests/servicestests/src/com/android/server/wm/StackWindowControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/StackWindowControllerTests.java
@@ -42,7 +42,7 @@
     @Test
     public void testRemoveContainer() throws Exception {
         final StackWindowController stackController =
-                createStackControllerOnDisplay(sDisplayContent);
+                createStackControllerOnDisplay(mDisplayContent);
         final WindowTestUtils.TestTaskWindowContainerController taskController =
                 new WindowTestUtils.TestTaskWindowContainerController(stackController);
 
@@ -62,7 +62,7 @@
     @Test
     public void testRemoveContainer_deferRemoval() throws Exception {
         final StackWindowController stackController =
-                createStackControllerOnDisplay(sDisplayContent);
+                createStackControllerOnDisplay(mDisplayContent);
         final WindowTestUtils.TestTaskWindowContainerController taskController =
                 new WindowTestUtils.TestTaskWindowContainerController(stackController);
 
@@ -89,7 +89,7 @@
     public void testReparent() throws Exception {
         // Create first stack on primary display.
         final StackWindowController stack1Controller =
-                createStackControllerOnDisplay(sDisplayContent);
+                createStackControllerOnDisplay(mDisplayContent);
         final TaskStack stack1 = stack1Controller.mContainer;
         final WindowTestUtils.TestTaskWindowContainerController taskController =
                 new WindowTestUtils.TestTaskWindowContainerController(stack1Controller);
diff --git a/services/tests/servicestests/src/com/android/server/wm/TaskPositionerTests.java b/services/tests/servicestests/src/com/android/server/wm/TaskPositionerTests.java
index e6975e7..887def7 100644
--- a/services/tests/servicestests/src/com/android/server/wm/TaskPositionerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/TaskPositionerTests.java
@@ -22,16 +22,12 @@
 import org.junit.runner.RunWith;
 
 import android.graphics.Rect;
-import android.os.Binder;
-import android.platform.test.annotations.Presubmit;
-import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
 import android.util.DisplayMetrics;
 import android.util.Log;
 import android.view.Display;
 
-import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
 import static com.android.server.wm.TaskPositioner.MIN_ASPECT;
 import static com.android.server.wm.WindowManagerService.dipToPixel;
 import static com.android.server.wm.WindowState.MINIMUM_VISIBLE_HEIGHT_IN_DP;
@@ -61,7 +57,7 @@
     @Before
     public void setUp() throws Exception {
         super.setUp();
-        final Display display = sDisplayContent.getDisplay();
+        final Display display = mDisplayContent.getDisplay();
         final DisplayMetrics dm = new DisplayMetrics();
         display.getMetrics(dm);
 
diff --git a/services/tests/servicestests/src/com/android/server/wm/TaskSnapshotCacheTest.java b/services/tests/servicestests/src/com/android/server/wm/TaskSnapshotCacheTest.java
index c61076d..a23a6b22 100644
--- a/services/tests/servicestests/src/com/android/server/wm/TaskSnapshotCacheTest.java
+++ b/services/tests/servicestests/src/com/android/server/wm/TaskSnapshotCacheTest.java
@@ -16,28 +16,13 @@
 
 package com.android.server.wm;
 
-import static android.graphics.GraphicBuffer.USAGE_HW_TEXTURE;
-import static android.graphics.GraphicBuffer.USAGE_SW_READ_NEVER;
-import static android.graphics.GraphicBuffer.USAGE_SW_READ_RARELY;
-import static android.graphics.GraphicBuffer.USAGE_SW_WRITE_NEVER;
-import static android.graphics.GraphicBuffer.create;
 import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
 import static junit.framework.Assert.assertNotNull;
 import static junit.framework.Assert.assertNull;
 
-import android.app.ActivityManager.TaskSnapshot;
-import android.content.res.Configuration;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.GraphicBuffer;
-import android.graphics.PixelFormat;
-import android.graphics.Rect;
-import android.os.Debug;
-import android.platform.test.annotations.Presubmit;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
 
-import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
diff --git a/services/tests/servicestests/src/com/android/server/wm/TaskSnapshotControllerTest.java b/services/tests/servicestests/src/com/android/server/wm/TaskSnapshotControllerTest.java
index 2752340..2b4d9fb 100644
--- a/services/tests/servicestests/src/com/android/server/wm/TaskSnapshotControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/wm/TaskSnapshotControllerTest.java
@@ -75,12 +75,12 @@
     @Test
     public void testGetSnapshotMode() throws Exception {
         final WindowState disabledWindow = createWindow(null,
-                FIRST_APPLICATION_WINDOW, sDisplayContent, "disabledWindow");
+                FIRST_APPLICATION_WINDOW, mDisplayContent, "disabledWindow");
         disabledWindow.mAppToken.setDisablePreviewSnapshots(true);
         assertEquals(SNAPSHOT_MODE_APP_THEME,
                 sWm.mTaskSnapshotController.getSnapshotMode(disabledWindow.getTask()));
         final WindowState normalWindow = createWindow(null,
-                FIRST_APPLICATION_WINDOW, sDisplayContent, "normalWindow");
+                FIRST_APPLICATION_WINDOW, mDisplayContent, "normalWindow");
         assertEquals(SNAPSHOT_MODE_REAL,
                 sWm.mTaskSnapshotController.getSnapshotMode(normalWindow.getTask()));
     }
diff --git a/services/tests/servicestests/src/com/android/server/wm/TaskStackContainersTests.java b/services/tests/servicestests/src/com/android/server/wm/TaskStackContainersTests.java
index 82ea2313..5feda41 100644
--- a/services/tests/servicestests/src/com/android/server/wm/TaskStackContainersTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/TaskStackContainersTests.java
@@ -51,12 +51,13 @@
     public void setUp() throws Exception {
         super.setUp();
         mPinnedStack = new StackWindowController(PINNED_STACK_ID, null,
-                sDisplayContent.getDisplayId(), true /* onTop */, new Rect(), sWm).mContainer;
+                mDisplayContent.getDisplayId(), true /* onTop */, new Rect(), sWm).mContainer;
 
         // Stack should contain visible app window to be considered visible.
         final Task pinnedTask = createTaskInStack(mPinnedStack, 0 /* userId */);
         assertFalse(mPinnedStack.isVisible());
-        final WindowTestUtils.TestAppWindowToken pinnedApp = new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+        final WindowTestUtils.TestAppWindowToken pinnedApp = new WindowTestUtils.TestAppWindowToken(
+                mDisplayContent);
         pinnedTask.addChild(pinnedApp, 0 /* addPos */);
         assertTrue(mPinnedStack.isVisible());
     }
@@ -69,8 +70,8 @@
     @Test
     public void testStackPositionChildAt() throws Exception {
         // Test that always-on-top stack can't be moved to position other than top.
-        final TaskStack stack1 = createTaskStackOnDisplay(sDisplayContent);
-        final TaskStack stack2 = createTaskStackOnDisplay(sDisplayContent);
+        final TaskStack stack1 = createTaskStackOnDisplay(mDisplayContent);
+        final TaskStack stack2 = createTaskStackOnDisplay(mDisplayContent);
 
         final WindowContainer taskStackContainer = stack1.getParent();
 
@@ -94,7 +95,7 @@
     @Test
     public void testStackPositionBelowPinnedStack() throws Exception {
         // Test that no stack can be above pinned stack.
-        final TaskStack stack1 = createTaskStackOnDisplay(sDisplayContent);
+        final TaskStack stack1 = createTaskStackOnDisplay(mDisplayContent);
 
         final WindowContainer taskStackContainer = stack1.getParent();
 
diff --git a/services/tests/servicestests/src/com/android/server/wm/TaskStackTests.java b/services/tests/servicestests/src/com/android/server/wm/TaskStackTests.java
index 267e5f7..b846fd0 100644
--- a/services/tests/servicestests/src/com/android/server/wm/TaskStackTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/TaskStackTests.java
@@ -45,7 +45,7 @@
 
     @Test
     public void testStackPositionChildAt() throws Exception {
-        final TaskStack stack = createTaskStackOnDisplay(sDisplayContent);
+        final TaskStack stack = createTaskStackOnDisplay(mDisplayContent);
         final Task task1 = createTaskInStack(stack, 0 /* userId */);
         final Task task2 = createTaskInStack(stack, 1 /* userId */);
 
@@ -62,16 +62,16 @@
 
     @Test
     public void testClosingAppDifferentStackOrientation() throws Exception {
-        final TaskStack stack = createTaskStackOnDisplay(sDisplayContent);
+        final TaskStack stack = createTaskStackOnDisplay(mDisplayContent);
         final Task task1 = createTaskInStack(stack, 0 /* userId */);
         WindowTestUtils.TestAppWindowToken appWindowToken1 =
-                new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
         task1.addChild(appWindowToken1, 0);
         appWindowToken1.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
 
         final Task task2 = createTaskInStack(stack, 1 /* userId */);
         WindowTestUtils.TestAppWindowToken appWindowToken2 =
-                new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
         task2.addChild(appWindowToken2, 0);
         appWindowToken2.setOrientation(SCREEN_ORIENTATION_PORTRAIT);
 
@@ -82,16 +82,16 @@
 
     @Test
     public void testMoveTaskToBackDifferentStackOrientation() throws Exception {
-        final TaskStack stack = createTaskStackOnDisplay(sDisplayContent);
+        final TaskStack stack = createTaskStackOnDisplay(mDisplayContent);
         final Task task1 = createTaskInStack(stack, 0 /* userId */);
         WindowTestUtils.TestAppWindowToken appWindowToken1 =
-                new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
         task1.addChild(appWindowToken1, 0);
         appWindowToken1.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
 
         final Task task2 = createTaskInStack(stack, 1 /* userId */);
         WindowTestUtils.TestAppWindowToken appWindowToken2 =
-                new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
         task2.addChild(appWindowToken2, 0);
         appWindowToken2.setOrientation(SCREEN_ORIENTATION_PORTRAIT);
 
@@ -102,17 +102,17 @@
 
     @Test
     public void testStackRemoveImmediately() throws Exception {
-        final TaskStack stack = createTaskStackOnDisplay(sDisplayContent);
+        final TaskStack stack = createTaskStackOnDisplay(mDisplayContent);
         final Task task = createTaskInStack(stack, 0 /* userId */);
         assertEquals(stack, task.mStack);
-        assertTrue(sDisplayContent.mDimLayerController.hasDimLayerUser(stack));
-        assertTrue(sDisplayContent.mDimLayerController.hasDimLayerUser(task));
+        assertTrue(mDisplayContent.mDimLayerController.hasDimLayerUser(stack));
+        assertTrue(mDisplayContent.mDimLayerController.hasDimLayerUser(task));
 
         // Remove stack and check if its child is also removed.
         stack.removeImmediately();
         assertNull(stack.getDisplayContent());
         assertNull(task.mStack);
-        assertFalse(sDisplayContent.mDimLayerController.hasDimLayerUser(stack));
-        assertFalse(sDisplayContent.mDimLayerController.hasDimLayerUser(task));
+        assertFalse(mDisplayContent.mDimLayerController.hasDimLayerUser(stack));
+        assertFalse(mDisplayContent.mDimLayerController.hasDimLayerUser(task));
     }
 }
diff --git a/services/tests/servicestests/src/com/android/server/wm/TaskWindowContainerControllerTests.java b/services/tests/servicestests/src/com/android/server/wm/TaskWindowContainerControllerTests.java
index 98d20a2..1dd9365 100644
--- a/services/tests/servicestests/src/com/android/server/wm/TaskWindowContainerControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/TaskWindowContainerControllerTests.java
@@ -41,7 +41,7 @@
     @Test
     public void testRemoveContainer() throws Exception {
         final WindowTestUtils.TestTaskWindowContainerController taskController =
-                new WindowTestUtils.TestTaskWindowContainerController();
+                new WindowTestUtils.TestTaskWindowContainerController(this);
         final WindowTestUtils.TestAppWindowContainerController appController =
                 new WindowTestUtils.TestAppWindowContainerController(taskController);
 
@@ -54,7 +54,7 @@
     @Test
     public void testRemoveContainer_deferRemoval() throws Exception {
         final WindowTestUtils.TestTaskWindowContainerController taskController =
-                new WindowTestUtils.TestTaskWindowContainerController();
+                new WindowTestUtils.TestTaskWindowContainerController(this);
         final WindowTestUtils.TestAppWindowContainerController appController =
                 new WindowTestUtils.TestAppWindowContainerController(taskController);
 
@@ -79,11 +79,11 @@
     @Test
     public void testReparent() throws Exception {
         final StackWindowController stackController1 =
-                createStackControllerOnDisplay(sDisplayContent);
+                createStackControllerOnDisplay(mDisplayContent);
         final WindowTestUtils.TestTaskWindowContainerController taskController =
                 new WindowTestUtils.TestTaskWindowContainerController(stackController1);
         final StackWindowController stackController2 =
-                createStackControllerOnDisplay(sDisplayContent);
+                createStackControllerOnDisplay(mDisplayContent);
         final WindowTestUtils.TestTaskWindowContainerController taskController2 =
                 new WindowTestUtils.TestTaskWindowContainerController(stackController2);
 
@@ -96,7 +96,7 @@
         assertTrue("Should not be able to reparent to the same parent", gotException);
 
         final StackWindowController stackController3 =
-                createStackControllerOnDisplay(sDisplayContent);
+                createStackControllerOnDisplay(mDisplayContent);
         stackController3.setContainer(null);
         gotException = false;
         try {
@@ -117,13 +117,13 @@
     public void testReparent_BetweenDisplays() throws Exception {
         // Create first stack on primary display.
         final StackWindowController stack1Controller =
-                createStackControllerOnDisplay(sDisplayContent);
+                createStackControllerOnDisplay(mDisplayContent);
         final TaskStack stack1 = stack1Controller.mContainer;
         final WindowTestUtils.TestTaskWindowContainerController taskController =
                 new WindowTestUtils.TestTaskWindowContainerController(stack1Controller);
         final WindowTestUtils.TestTask task1 = (WindowTestUtils.TestTask) taskController.mContainer;
         task1.mOnDisplayChangedCalled = false;
-        assertEquals(sDisplayContent, stack1.getDisplayContent());
+        assertEquals(mDisplayContent, stack1.getDisplayContent());
 
         // Create second display and put second stack on it.
         final DisplayContent dc = createNewDisplay();
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 9392e8e..be53667 100644
--- a/services/tests/servicestests/src/com/android/server/wm/TestWindowManagerPolicy.java
+++ b/services/tests/servicestests/src/com/android/server/wm/TestWindowManagerPolicy.java
@@ -23,7 +23,6 @@
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.doAnswer;
 
-import android.content.pm.ActivityInfo;
 import android.os.PowerSaveState;
 import org.mockito.invocation.InvocationOnMock;
 
@@ -199,7 +198,7 @@
         final com.android.server.wm.WindowState window;
         final AppWindowToken atoken;
         synchronized (sWm.mWindowMap) {
-            atoken = WindowTestsBase.sDisplayContent.getAppWindowToken(appToken);
+            atoken = sWm.mRoot.getAppWindowToken(appToken);
             window = WindowTestsBase.createWindow(null, TYPE_APPLICATION_STARTING, atoken,
                     "Starting window");
             atoken.startingWindow = window;
diff --git a/services/tests/servicestests/src/com/android/server/wm/UnknownAppVisibilityControllerTest.java b/services/tests/servicestests/src/com/android/server/wm/UnknownAppVisibilityControllerTest.java
index 0eaf5bc..5a4bb27 100644
--- a/services/tests/servicestests/src/com/android/server/wm/UnknownAppVisibilityControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/wm/UnknownAppVisibilityControllerTest.java
@@ -36,8 +36,6 @@
 @RunWith(AndroidJUnit4.class)
 public class UnknownAppVisibilityControllerTest extends WindowTestsBase {
 
-    private WindowManagerService mWm;
-
     @Before
     public void setUp() throws Exception {
         super.setUp();
@@ -46,7 +44,7 @@
 
     @Test
     public void testFlow() throws Exception {
-        final AppWindowToken token = new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+        final AppWindowToken token = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
         sWm.mUnknownAppVisibilityController.notifyLaunched(token);
         sWm.mUnknownAppVisibilityController.notifyAppResumedFinished(token);
         sWm.mUnknownAppVisibilityController.notifyRelayouted(token);
@@ -58,8 +56,8 @@
 
     @Test
     public void testMultiple() throws Exception {
-        final AppWindowToken token1 = new WindowTestUtils.TestAppWindowToken(sDisplayContent);
-        final AppWindowToken token2 = new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+        final AppWindowToken token1 = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
+        final AppWindowToken token2 = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
         sWm.mUnknownAppVisibilityController.notifyLaunched(token1);
         sWm.mUnknownAppVisibilityController.notifyAppResumedFinished(token1);
         sWm.mUnknownAppVisibilityController.notifyLaunched(token2);
@@ -74,7 +72,7 @@
 
     @Test
     public void testClear() throws Exception {
-        final AppWindowToken token = new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+        final AppWindowToken token = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
         sWm.mUnknownAppVisibilityController.notifyLaunched(token);
         sWm.mUnknownAppVisibilityController.clear();;
         assertTrue(sWm.mUnknownAppVisibilityController.allResolved());
@@ -82,7 +80,7 @@
 
     @Test
     public void testAppRemoved() throws Exception {
-        final AppWindowToken token = new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+        final AppWindowToken token = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
         sWm.mUnknownAppVisibilityController.notifyLaunched(token);
         sWm.mUnknownAppVisibilityController.appRemoved(token);
         assertTrue(sWm.mUnknownAppVisibilityController.allResolved());
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowContainerControllerTests.java b/services/tests/servicestests/src/com/android/server/wm/WindowContainerControllerTests.java
index 956735c..f1e15d9 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowContainerControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowContainerControllerTests.java
@@ -17,7 +17,6 @@
 package com.android.server.wm;
 
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import android.platform.test.annotations.Presubmit;
 import android.support.test.filters.SmallTest;
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowFrameTests.java b/services/tests/servicestests/src/com/android/server/wm/WindowFrameTests.java
index a2aa058..8fe4116 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowFrameTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowFrameTests.java
@@ -96,8 +96,7 @@
 
     @Before
     public void setUp() throws Exception {
-        final Context context = InstrumentationRegistry.getTargetContext();
-        sWm = TestWindowManagerPolicy.getWindowManagerService(context);
+        super.setUp();
 
         // Just any non zero value.
         sWm.mSystemDecorLayer = 10000;
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowLayersControllerTests.java b/services/tests/servicestests/src/com/android/server/wm/WindowLayersControllerTests.java
index d5e6b6d..e1f318d 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowLayersControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowLayersControllerTests.java
@@ -45,45 +45,45 @@
     @Test
     public void testAssignWindowLayers_ForImeWithNoTarget() throws Exception {
         sWm.mInputMethodTarget = null;
-        sLayersController.assignWindowLayers(sDisplayContent);
+        mLayersController.assignWindowLayers(mDisplayContent);
 
         // The Ime has an higher base layer than app windows and lower base layer than system
         // windows, so it should be above app windows and below system windows if there isn't an IME
         // target.
-        assertWindowLayerGreaterThan(sImeWindow, sChildAppWindowAbove);
-        assertWindowLayerGreaterThan(sImeWindow, sAppWindow);
-        assertWindowLayerGreaterThan(sImeWindow, sDockedDividerWindow);
-        assertWindowLayerGreaterThan(sNavBarWindow, sImeWindow);
-        assertWindowLayerGreaterThan(sStatusBarWindow, sImeWindow);
+        assertWindowLayerGreaterThan(mImeWindow, mChildAppWindowAbove);
+        assertWindowLayerGreaterThan(mImeWindow, mAppWindow);
+        assertWindowLayerGreaterThan(mImeWindow, mDockedDividerWindow);
+        assertWindowLayerGreaterThan(mNavBarWindow, mImeWindow);
+        assertWindowLayerGreaterThan(mStatusBarWindow, mImeWindow);
 
         // And, IME dialogs should always have an higher layer than the IME.
-        assertWindowLayerGreaterThan(sImeDialogWindow, sImeWindow);
+        assertWindowLayerGreaterThan(mImeDialogWindow, mImeWindow);
     }
 
     @Test
     public void testAssignWindowLayers_ForImeWithAppTarget() throws Exception {
         final WindowState imeAppTarget =
-                createWindow(null, TYPE_BASE_APPLICATION, sDisplayContent, "imeAppTarget");
+                createWindow(null, TYPE_BASE_APPLICATION, mDisplayContent, "imeAppTarget");
         sWm.mInputMethodTarget = imeAppTarget;
-        sLayersController.assignWindowLayers(sDisplayContent);
+        mLayersController.assignWindowLayers(mDisplayContent);
 
         // Ime should be above all app windows and below system windows if it is targeting an app
         // window.
-        assertWindowLayerGreaterThan(sImeWindow, imeAppTarget);
-        assertWindowLayerGreaterThan(sImeWindow, sChildAppWindowAbove);
-        assertWindowLayerGreaterThan(sImeWindow, sAppWindow);
-        assertWindowLayerGreaterThan(sImeWindow, sDockedDividerWindow);
-        assertWindowLayerGreaterThan(sNavBarWindow, sImeWindow);
-        assertWindowLayerGreaterThan(sStatusBarWindow, sImeWindow);
+        assertWindowLayerGreaterThan(mImeWindow, imeAppTarget);
+        assertWindowLayerGreaterThan(mImeWindow, mChildAppWindowAbove);
+        assertWindowLayerGreaterThan(mImeWindow, mAppWindow);
+        assertWindowLayerGreaterThan(mImeWindow, mDockedDividerWindow);
+        assertWindowLayerGreaterThan(mNavBarWindow, mImeWindow);
+        assertWindowLayerGreaterThan(mStatusBarWindow, mImeWindow);
 
         // And, IME dialogs should always have an higher layer than the IME.
-        assertWindowLayerGreaterThan(sImeDialogWindow, sImeWindow);
+        assertWindowLayerGreaterThan(mImeDialogWindow, mImeWindow);
     }
 
     @Test
     public void testAssignWindowLayers_ForImeWithAppTargetWithChildWindows() throws Exception {
         final WindowState imeAppTarget =
-                createWindow(null, TYPE_BASE_APPLICATION, sDisplayContent, "imeAppTarget");
+                createWindow(null, TYPE_BASE_APPLICATION, mDisplayContent, "imeAppTarget");
         final WindowState imeAppTargetChildAboveWindow = createWindow(imeAppTarget,
                 TYPE_APPLICATION_ATTACHED_DIALOG, imeAppTarget.mToken,
                 "imeAppTargetChildAboveWindow");
@@ -92,84 +92,84 @@
                 "imeAppTargetChildBelowWindow");
 
         sWm.mInputMethodTarget = imeAppTarget;
-        sLayersController.assignWindowLayers(sDisplayContent);
+        mLayersController.assignWindowLayers(mDisplayContent);
 
         // Ime should be above all app windows except for child windows that are z-ordered above it
         // and below system windows if it is targeting an app window.
-        assertWindowLayerGreaterThan(sImeWindow, imeAppTarget);
-        assertWindowLayerGreaterThan(imeAppTargetChildAboveWindow, sImeWindow);
-        assertWindowLayerGreaterThan(sImeWindow, imeAppTargetChildBelowWindow);
-        assertWindowLayerGreaterThan(sImeWindow, sChildAppWindowAbove);
-        assertWindowLayerGreaterThan(sImeWindow, sAppWindow);
-        assertWindowLayerGreaterThan(sImeWindow, sDockedDividerWindow);
-        assertWindowLayerGreaterThan(sNavBarWindow, sImeWindow);
-        assertWindowLayerGreaterThan(sStatusBarWindow, sImeWindow);
+        assertWindowLayerGreaterThan(mImeWindow, imeAppTarget);
+        assertWindowLayerGreaterThan(imeAppTargetChildAboveWindow, mImeWindow);
+        assertWindowLayerGreaterThan(mImeWindow, imeAppTargetChildBelowWindow);
+        assertWindowLayerGreaterThan(mImeWindow, mChildAppWindowAbove);
+        assertWindowLayerGreaterThan(mImeWindow, mAppWindow);
+        assertWindowLayerGreaterThan(mImeWindow, mDockedDividerWindow);
+        assertWindowLayerGreaterThan(mNavBarWindow, mImeWindow);
+        assertWindowLayerGreaterThan(mStatusBarWindow, mImeWindow);
 
         // And, IME dialogs should always have an higher layer than the IME.
-        assertWindowLayerGreaterThan(sImeDialogWindow, sImeWindow);
+        assertWindowLayerGreaterThan(mImeDialogWindow, mImeWindow);
     }
 
     @Test
     public void testAssignWindowLayers_ForImeWithAppTargetAndAppAbove() throws Exception {
         final WindowState appBelowImeTarget =
-                createWindow(null, TYPE_BASE_APPLICATION, sDisplayContent, "appBelowImeTarget");
+                createWindow(null, TYPE_BASE_APPLICATION, mDisplayContent, "appBelowImeTarget");
         final WindowState imeAppTarget =
-                createWindow(null, TYPE_BASE_APPLICATION, sDisplayContent, "imeAppTarget");
+                createWindow(null, TYPE_BASE_APPLICATION, mDisplayContent, "imeAppTarget");
         final WindowState appAboveImeTarget =
-                createWindow(null, TYPE_BASE_APPLICATION, sDisplayContent, "appAboveImeTarget");
+                createWindow(null, TYPE_BASE_APPLICATION, mDisplayContent, "appAboveImeTarget");
 
         sWm.mInputMethodTarget = imeAppTarget;
-        sLayersController.assignWindowLayers(sDisplayContent);
+        mLayersController.assignWindowLayers(mDisplayContent);
 
         // Ime should be above all app windows except for non-fullscreen app window above it and
         // below system windows if it is targeting an app window.
-        assertWindowLayerGreaterThan(sImeWindow, imeAppTarget);
-        assertWindowLayerGreaterThan(sImeWindow, appBelowImeTarget);
-        assertWindowLayerGreaterThan(appAboveImeTarget, sImeWindow);
-        assertWindowLayerGreaterThan(sImeWindow, sChildAppWindowAbove);
-        assertWindowLayerGreaterThan(sImeWindow, sAppWindow);
-        assertWindowLayerGreaterThan(sImeWindow, sDockedDividerWindow);
-        assertWindowLayerGreaterThan(sNavBarWindow, sImeWindow);
-        assertWindowLayerGreaterThan(sStatusBarWindow, sImeWindow);
+        assertWindowLayerGreaterThan(mImeWindow, imeAppTarget);
+        assertWindowLayerGreaterThan(mImeWindow, appBelowImeTarget);
+        assertWindowLayerGreaterThan(appAboveImeTarget, mImeWindow);
+        assertWindowLayerGreaterThan(mImeWindow, mChildAppWindowAbove);
+        assertWindowLayerGreaterThan(mImeWindow, mAppWindow);
+        assertWindowLayerGreaterThan(mImeWindow, mDockedDividerWindow);
+        assertWindowLayerGreaterThan(mNavBarWindow, mImeWindow);
+        assertWindowLayerGreaterThan(mStatusBarWindow, mImeWindow);
 
         // And, IME dialogs should always have an higher layer than the IME.
-        assertWindowLayerGreaterThan(sImeDialogWindow, sImeWindow);
+        assertWindowLayerGreaterThan(mImeDialogWindow, mImeWindow);
     }
 
     @Test
     public void testAssignWindowLayers_ForImeNonAppImeTarget() throws Exception {
         final WindowState imeSystemOverlayTarget = createWindow(null, TYPE_SYSTEM_OVERLAY,
-                sDisplayContent, "imeSystemOverlayTarget",
+                mDisplayContent, "imeSystemOverlayTarget",
                 true /* ownerCanAddInternalSystemWindow */);
 
         sWm.mInputMethodTarget = imeSystemOverlayTarget;
-        sLayersController.assignWindowLayers(sDisplayContent);
+        mLayersController.assignWindowLayers(mDisplayContent);
 
         // The IME target base layer is higher than all window except for the nav bar window, so the
         // IME should be above all windows except for the nav bar.
-        assertWindowLayerGreaterThan(sImeWindow, imeSystemOverlayTarget);
-        assertWindowLayerGreaterThan(sImeWindow, sChildAppWindowAbove);
-        assertWindowLayerGreaterThan(sImeWindow, sAppWindow);
-        assertWindowLayerGreaterThan(sImeWindow, sDockedDividerWindow);
-        assertWindowLayerGreaterThan(sImeWindow, sStatusBarWindow);
-        assertWindowLayerGreaterThan(sNavBarWindow, sImeWindow);
+        assertWindowLayerGreaterThan(mImeWindow, imeSystemOverlayTarget);
+        assertWindowLayerGreaterThan(mImeWindow, mChildAppWindowAbove);
+        assertWindowLayerGreaterThan(mImeWindow, mAppWindow);
+        assertWindowLayerGreaterThan(mImeWindow, mDockedDividerWindow);
+        assertWindowLayerGreaterThan(mImeWindow, mStatusBarWindow);
+        assertWindowLayerGreaterThan(mNavBarWindow, mImeWindow);
 
         // And, IME dialogs should always have an higher layer than the IME.
-        assertWindowLayerGreaterThan(sImeDialogWindow, sImeWindow);
+        assertWindowLayerGreaterThan(mImeDialogWindow, mImeWindow);
     }
 
     @Test
     public void testStackLayers() throws Exception {
         WindowState pinnedStackWindow = createWindowOnStack(null, PINNED_STACK_ID,
-                TYPE_BASE_APPLICATION, sDisplayContent, "pinnedStackWindow");
+                TYPE_BASE_APPLICATION, mDisplayContent, "pinnedStackWindow");
         WindowState dockedStackWindow = createWindowOnStack(null, DOCKED_STACK_ID,
-                TYPE_BASE_APPLICATION, sDisplayContent, "dockedStackWindow");
+                TYPE_BASE_APPLICATION, mDisplayContent, "dockedStackWindow");
         WindowState assistantStackWindow = createWindowOnStack(null, ASSISTANT_STACK_ID,
-                TYPE_BASE_APPLICATION, sDisplayContent, "assistantStackWindow");
+                TYPE_BASE_APPLICATION, mDisplayContent, "assistantStackWindow");
 
-        sLayersController.assignWindowLayers(sDisplayContent);
+        mLayersController.assignWindowLayers(mDisplayContent);
 
-        assertWindowLayerGreaterThan(dockedStackWindow, sAppWindow);
+        assertWindowLayerGreaterThan(dockedStackWindow, mAppWindow);
         assertWindowLayerGreaterThan(assistantStackWindow, dockedStackWindow);
         assertWindowLayerGreaterThan(pinnedStackWindow, assistantStackWindow);
     }
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowTestUtils.java b/services/tests/servicestests/src/com/android/server/wm/WindowTestUtils.java
index ae3eb52..47ced99 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowTestUtils.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowTestUtils.java
@@ -92,7 +92,7 @@
     public static class TestAppWindowToken extends AppWindowToken {
 
         TestAppWindowToken(DisplayContent dc) {
-            super(WindowTestsBase.sWm, null, false, dc, true /* fillsParent */,
+            super(dc.mService, null, false, dc, true /* fillsParent */,
                     null /* overrideConfig */, null /* bounds */);
         }
 
@@ -137,7 +137,7 @@
         }
 
         TestWindowToken(int type, DisplayContent dc, boolean persistOnEmpty) {
-            super(WindowTestsBase.sWm, mock(IBinder.class), type, persistOnEmpty, dc,
+            super(dc.mService, mock(IBinder.class), type, persistOnEmpty, dc,
                     false /* ownerCanManageAppTokens */);
         }
 
@@ -201,8 +201,8 @@
      */
     public static class TestTaskWindowContainerController extends TaskWindowContainerController {
 
-        TestTaskWindowContainerController() {
-            this(WindowTestsBase.createStackControllerOnDisplay(WindowTestsBase.sDisplayContent));
+        TestTaskWindowContainerController(WindowTestsBase testsBase) {
+            this(testsBase.createStackControllerOnDisplay(testsBase.mDisplayContent));
         }
 
         TestTaskWindowContainerController(StackWindowController stackController) {
@@ -219,7 +219,8 @@
                     }, stackController, 0 /* userId */, null /* bounds */,
                     EMPTY /* overrideConfig*/, RESIZE_MODE_UNRESIZEABLE,
                     false /* supportsPictureInPicture */, false /* homeTask*/, true /* toTop*/,
-                    true /* showForAllUsers */, new ActivityManager.TaskDescription(), WindowTestsBase.sWm);
+                    true /* showForAllUsers */, new ActivityManager.TaskDescription(),
+                    stackController.mService);
         }
 
         @Override
@@ -246,8 +247,8 @@
                     true /* showForAllUsers */, 0 /* configChanges */, false /* voiceInteraction */,
                     false /* launchTaskBehind */, false /* alwaysFocusable */,
                     0 /* targetSdkVersion */, 0 /* rotationAnimationHint */,
-                    0 /* inputDispatchingTimeoutNanos */, WindowTestsBase.sWm, null /* overrideConfig */,
-                    null /* bounds */);
+                    0 /* inputDispatchingTimeoutNanos */, taskController.mService,
+                    null /* overrideConfig */, null /* bounds */);
             mToken = token;
         }
 
@@ -265,8 +266,8 @@
                     controller, overrideConfig, bounds);
         }
 
-        AppWindowToken getAppWindowToken() {
-            return (AppWindowToken) WindowTestsBase.sDisplayContent.getWindowToken(mToken.asBinder());
+        AppWindowToken getAppWindowToken(DisplayContent dc) {
+            return (AppWindowToken) dc.getWindowToken(mToken.asBinder());
         }
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowTestsBase.java b/services/tests/servicestests/src/com/android/server/wm/WindowTestsBase.java
index 218af73..0167654 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowTestsBase.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowTestsBase.java
@@ -16,9 +16,9 @@
 
 package com.android.server.wm;
 
+import static android.view.Display.DEFAULT_DISPLAY;
 import static android.view.View.VISIBLE;
 
-import android.app.ActivityManager.TaskDescription;
 import android.graphics.Rect;
 import android.hardware.display.DisplayManagerGlobal;
 import android.view.Display;
@@ -61,85 +61,67 @@
  */
 class WindowTestsBase {
     static WindowManagerService sWm = null;
-    static TestWindowManagerPolicy sPolicy = null;
-    private final static IWindow sIWindow = new TestIWindow();
-    private final static Session sMockSession = mock(Session.class);
+    private static final IWindow sIWindow = new TestIWindow();
+    private static final Session sMockSession = mock(Session.class);
     // The default display is removed in {@link #setUp} and then we iterate over all displays to
     // make sure we don't collide with any existing display. If we run into no other display, the
     // added display should be treated as default. This cannot be the default display
-    private static int sNextDisplayId = Display.DEFAULT_DISPLAY + 1;
+    private static int sNextDisplayId = DEFAULT_DISPLAY + 1;
     private static int sNextStackId = FIRST_DYNAMIC_STACK_ID;
 
     private static boolean sOneTimeSetupDone = false;
-    static DisplayContent sDisplayContent;
-    static DisplayInfo sDisplayInfo = new DisplayInfo();
-    static WindowLayersController sLayersController;
-    static WindowState sWallpaperWindow;
-    static WindowState sImeWindow;
-    static WindowState sImeDialogWindow;
-    static WindowState sStatusBarWindow;
-    static WindowState sDockedDividerWindow;
-    static WindowState sNavBarWindow;
-    static WindowState sAppWindow;
-    static WindowState sChildAppWindowAbove;
-    static WindowState sChildAppWindowBelow;
-    static HashSet<WindowState> sCommonWindows;
+    DisplayContent mDisplayContent;
+    DisplayInfo mDisplayInfo = new DisplayInfo();
+    WindowLayersController mLayersController;
+    WindowState mWallpaperWindow;
+    WindowState mImeWindow;
+    WindowState mImeDialogWindow;
+    WindowState mStatusBarWindow;
+    WindowState mDockedDividerWindow;
+    WindowState mNavBarWindow;
+    WindowState mAppWindow;
+    WindowState mChildAppWindowAbove;
+    WindowState mChildAppWindowBelow;
+    HashSet<WindowState> mCommonWindows;
 
     @Before
     public void setUp() throws Exception {
-        if (sOneTimeSetupDone) {
-            return;
+        if (!sOneTimeSetupDone) {
+            sOneTimeSetupDone = true;
+            MockitoAnnotations.initMocks(this);
         }
-        sOneTimeSetupDone = true;
-        MockitoAnnotations.initMocks(this);
+
         final Context context = InstrumentationRegistry.getTargetContext();
         AttributeCache.init(context);
         sWm = TestWindowManagerPolicy.getWindowManagerService(context);
-        sPolicy = (TestWindowManagerPolicy) sWm.mPolicy;
-        sLayersController = new WindowLayersController(sWm);
+        mLayersController = new WindowLayersController(sWm);
 
-        // Make sure that display ids don't overlap, so there won't be several displays with same
-        // ids among RootWindowContainer children.
-        for (DisplayContent dc : sWm.mRoot.mChildren) {
-            if (dc.getDisplayId() >= sNextDisplayId) {
-                sNextDisplayId = dc.getDisplayId() + 1;
-            }
-
-            // The default display must be preserved as some tests require it to function
-            // (such as policy rotation).
-            if (dc.getDisplayId() != Display.DEFAULT_DISPLAY) {
-                // It is safe to remove these displays as new displays will always be created with
-                // new ids.
-                dc.removeImmediately();
-            }
-        }
-
-        context.getDisplay().getDisplayInfo(sDisplayInfo);
-        sDisplayContent = createNewDisplay();
+        context.getDisplay().getDisplayInfo(mDisplayInfo);
+        mDisplayContent = createNewDisplay();
         sWm.mDisplayEnabled = true;
         sWm.mDisplayReady = true;
 
         // Set-up some common windows.
-        sCommonWindows = new HashSet();
-        sWallpaperWindow = createCommonWindow(null, TYPE_WALLPAPER, "wallpaperWindow");
-        sImeWindow = createCommonWindow(null, TYPE_INPUT_METHOD, "sImeWindow");
-        sWm.mInputMethodWindow = sImeWindow;
-        sImeDialogWindow = createCommonWindow(null, TYPE_INPUT_METHOD_DIALOG, "sImeDialogWindow");
-        sStatusBarWindow = createCommonWindow(null, TYPE_STATUS_BAR, "sStatusBarWindow");
-        sNavBarWindow = createCommonWindow(null, TYPE_NAVIGATION_BAR, "sNavBarWindow");
-        sDockedDividerWindow = createCommonWindow(null, TYPE_DOCK_DIVIDER, "sDockedDividerWindow");
-        sAppWindow = createCommonWindow(null, TYPE_BASE_APPLICATION, "sAppWindow");
-        sChildAppWindowAbove = createCommonWindow(sAppWindow, TYPE_APPLICATION_ATTACHED_DIALOG,
-                "sChildAppWindowAbove");
-        sChildAppWindowBelow = createCommonWindow(sAppWindow, TYPE_APPLICATION_MEDIA_OVERLAY,
-                "sChildAppWindowBelow");
+        mCommonWindows = new HashSet();
+        mWallpaperWindow = createCommonWindow(null, TYPE_WALLPAPER, "wallpaperWindow");
+        mImeWindow = createCommonWindow(null, TYPE_INPUT_METHOD, "mImeWindow");
+        sWm.mInputMethodWindow = mImeWindow;
+        mImeDialogWindow = createCommonWindow(null, TYPE_INPUT_METHOD_DIALOG, "mImeDialogWindow");
+        mStatusBarWindow = createCommonWindow(null, TYPE_STATUS_BAR, "mStatusBarWindow");
+        mNavBarWindow = createCommonWindow(null, TYPE_NAVIGATION_BAR, "mNavBarWindow");
+        mDockedDividerWindow = createCommonWindow(null, TYPE_DOCK_DIVIDER, "mDockedDividerWindow");
+        mAppWindow = createCommonWindow(null, TYPE_BASE_APPLICATION, "mAppWindow");
+        mChildAppWindowAbove = createCommonWindow(mAppWindow, TYPE_APPLICATION_ATTACHED_DIALOG,
+                "mChildAppWindowAbove");
+        mChildAppWindowBelow = createCommonWindow(mAppWindow, TYPE_APPLICATION_MEDIA_OVERLAY,
+                "mChildAppWindowBelow");
     }
 
     @After
     public void tearDown() throws Exception {
         final LinkedList<WindowState> nonCommonWindows = new LinkedList();
         sWm.mRoot.forAllWindows(w -> {
-            if (!sCommonWindows.contains(w)) {
+            if (!mCommonWindows.contains(w)) {
                 nonCommonWindows.addLast(w);
             }
         }, true /* traverseTopToBottom */);
@@ -148,12 +130,13 @@
             nonCommonWindows.pollLast().removeImmediately();
         }
 
+        mDisplayContent.removeImmediately();
         sWm.mInputMethodTarget = null;
     }
 
-    private static WindowState createCommonWindow(WindowState parent, int type, String name) {
+    private WindowState createCommonWindow(WindowState parent, int type, String name) {
         final WindowState win = createWindow(parent, type, name);
-        sCommonWindows.add(win);
+        mCommonWindows.add(win);
         // Prevent common windows from been IMe targets
         win.mAttrs.flags |= FLAG_NOT_FOCUSABLE;
         return win;
@@ -172,7 +155,7 @@
         sWm.mAnimationHandler.runWithScissors(() -> { }, 0);
     }
 
-    private static WindowToken createWindowToken(DisplayContent dc, int stackId, int type) {
+    private WindowToken createWindowToken(DisplayContent dc, int stackId, int type) {
         if (type < FIRST_APPLICATION_WINDOW || type > LAST_APPLICATION_WINDOW) {
             return new WindowTestUtils.TestWindowToken(type, dc);
         }
@@ -186,30 +169,30 @@
         return token;
     }
 
-    static WindowState createWindow(WindowState parent, int type, String name) {
+    WindowState createWindow(WindowState parent, int type, String name) {
         return (parent == null)
-                ? createWindow(parent, type, sDisplayContent, name)
+                ? createWindow(parent, type, mDisplayContent, name)
                 : createWindow(parent, type, parent.mToken, name);
     }
 
-    static WindowState createWindowOnStack(WindowState parent, int stackId, int type,
+    WindowState createWindowOnStack(WindowState parent, int stackId, int type,
             DisplayContent dc, String name) {
         final WindowToken token = createWindowToken(dc, stackId, type);
         return createWindow(parent, type, token, name);
     }
 
     WindowState createAppWindow(Task task, int type, String name) {
-        final AppWindowToken token = new WindowTestUtils.TestAppWindowToken(sDisplayContent);
+        final AppWindowToken token = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
         task.addChild(token, 0);
         return createWindow(null, type, token, name);
     }
 
-    static WindowState createWindow(WindowState parent, int type, DisplayContent dc, String name) {
+    WindowState createWindow(WindowState parent, int type, DisplayContent dc, String name) {
         final WindowToken token = createWindowToken(dc, INVALID_STACK_ID, type);
         return createWindow(parent, type, token, name);
     }
 
-    static WindowState createWindow(WindowState parent, int type, DisplayContent dc, String name,
+    WindowState createWindow(WindowState parent, int type, DisplayContent dc, String name,
             boolean ownerCanAddInternalSystemWindow) {
         final WindowToken token = createWindowToken(dc, INVALID_STACK_ID, type);
         return createWindow(parent, type, token, name, ownerCanAddInternalSystemWindow);
@@ -233,23 +216,23 @@
     }
 
     /** Creates a {@link TaskStack} and adds it to the specified {@link DisplayContent}. */
-    static TaskStack createTaskStackOnDisplay(DisplayContent dc) {
+    TaskStack createTaskStackOnDisplay(DisplayContent dc) {
         return createStackControllerOnDisplay(dc).mContainer;
     }
 
-    static StackWindowController createStackControllerOnDisplay(DisplayContent dc) {
+    StackWindowController createStackControllerOnDisplay(DisplayContent dc) {
         final int stackId = ++sNextStackId;
         return createStackControllerOnStackOnDisplay(stackId, dc);
     }
 
-    static StackWindowController createStackControllerOnStackOnDisplay(int stackId,
+    StackWindowController createStackControllerOnStackOnDisplay(int stackId,
             DisplayContent dc) {
         return new StackWindowController(stackId, null, dc.getDisplayId(),
                 true /* onTop */, new Rect(), sWm);
     }
 
     /** Creates a {@link Task} and adds it to the specified {@link TaskStack}. */
-    static Task createTaskInStack(TaskStack stack, int userId) {
+    Task createTaskInStack(TaskStack stack, int userId) {
         return WindowTestUtils.createTaskInStack(sWm, stack, userId);
     }
 
@@ -257,8 +240,8 @@
     DisplayContent createNewDisplay() {
         final int displayId = sNextDisplayId++;
         final Display display = new Display(DisplayManagerGlobal.getInstance(), displayId,
-                sDisplayInfo, DEFAULT_DISPLAY_ADJUSTMENTS);
-        return new DisplayContent(display, sWm, sLayersController, new WallpaperController(sWm));
+                mDisplayInfo, DEFAULT_DISPLAY_ADJUSTMENTS);
+        return new DisplayContent(display, sWm, mLayersController, new WallpaperController(sWm));
     }
 
     /** Creates a {@link com.android.server.wm.WindowTestUtils.TestWindowState} */
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowTokenTests.java b/services/tests/servicestests/src/com/android/server/wm/WindowTokenTests.java
index 4f7ad41..692e08b 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowTokenTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowTokenTests.java
@@ -47,7 +47,7 @@
     @Test
     public void testAddWindow() throws Exception {
         final WindowTestUtils.TestWindowToken token =
-                new WindowTestUtils.TestWindowToken(0, sDisplayContent);
+                new WindowTestUtils.TestWindowToken(0, mDisplayContent);
 
         assertEquals(0, token.getWindowsCount());
 
@@ -76,7 +76,7 @@
 
     @Test
     public void testChildRemoval() throws Exception {
-        final DisplayContent dc = sDisplayContent;
+        final DisplayContent dc = mDisplayContent;
         final WindowTestUtils.TestWindowToken token = new WindowTestUtils.TestWindowToken(0, dc);
 
         assertEquals(token, dc.getWindowToken(token.token));
@@ -97,7 +97,7 @@
     @Test
     public void testAdjustAnimLayer() throws Exception {
         final WindowTestUtils.TestWindowToken token =
-                new WindowTestUtils.TestWindowToken(0, sDisplayContent);
+                new WindowTestUtils.TestWindowToken(0, mDisplayContent);
         final WindowState window1 = createWindow(null, TYPE_APPLICATION, token, "window1");
         final WindowState window11 = createWindow(window1, FIRST_SUB_WINDOW, token, "window11");
         final WindowState window12 = createWindow(window1, FIRST_SUB_WINDOW, token, "window12");
@@ -109,7 +109,7 @@
 
         // We assign layers once, to get the base values computed by
         // the controller.
-        sLayersController.assignWindowLayers(sDisplayContent);
+        mLayersController.assignWindowLayers(mDisplayContent);
 
         final int window1StartLayer = window1.mWinAnimator.mAnimLayer;
         final int window11StartLayer = window11.mWinAnimator.mAnimLayer;
@@ -120,7 +120,7 @@
         // Then we set an adjustment, and assign them again, they should
         // be offset.
         int adj = token.adj = 50;
-        sLayersController.assignWindowLayers(sDisplayContent);
+        mLayersController.assignWindowLayers(mDisplayContent);
         final int highestLayer = token.getHighestAnimLayer();
 
         assertEquals(window1StartLayer + adj, window1.mWinAnimator.mAnimLayer);
@@ -138,18 +138,18 @@
     @Test
     public void testTokenRemovalProcess() throws Exception {
         final WindowTestUtils.TestWindowToken token =
-                new WindowTestUtils.TestWindowToken(TYPE_TOAST, sDisplayContent,
+                new WindowTestUtils.TestWindowToken(TYPE_TOAST, mDisplayContent,
                         true /* persistOnEmpty */);
 
         // Verify that the token is on the display
-        assertNotNull(sDisplayContent.getWindowToken(token.token));
+        assertNotNull(mDisplayContent.getWindowToken(token.token));
 
         final WindowState window1 = createWindow(null, TYPE_TOAST, token, "window1");
         final WindowState window2 = createWindow(null, TYPE_TOAST, token, "window2");
 
-        sDisplayContent.removeWindowToken(token.token);
+        mDisplayContent.removeWindowToken(token.token);
         // Verify that the token is no longer mapped on the display
-        assertNull(sDisplayContent.getWindowToken(token.token));
+        assertNull(mDisplayContent.getWindowToken(token.token));
         // Verify that the token is still attached to its parent
         assertNotNull(token.getParent());
         // Verify that the token windows are still around.