Merge "Revert "Hide APIs not intended to ship in DR.""
diff --git a/Android.mk b/Android.mk
index 66c5987..49b8f48 100644
--- a/Android.mk
+++ b/Android.mk
@@ -714,6 +714,7 @@
 	frameworks/base/core/java/android/print/PrintJobId.aidl \
 	frameworks/base/core/java/android/printservice/recommendation/RecommendationInfo.aidl \
 	frameworks/base/core/java/android/hardware/radio/RadioManager.aidl \
+	frameworks/base/core/java/android/hardware/radio/RadioMetadata.aidl \
 	frameworks/base/core/java/android/hardware/usb/UsbDevice.aidl \
 	frameworks/base/core/java/android/hardware/usb/UsbInterface.aidl \
 	frameworks/base/core/java/android/hardware/usb/UsbEndpoint.aidl \
diff --git a/api/current.txt b/api/current.txt
index 0c86ec9..88390b9 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -69848,7 +69848,6 @@
   public abstract class SSLSocketFactory extends javax.net.SocketFactory {
     ctor public SSLSocketFactory();
     method public abstract java.net.Socket createSocket(java.net.Socket, java.lang.String, int, boolean) throws java.io.IOException;
-    method public java.net.Socket createSocket(java.net.Socket, java.io.InputStream, boolean) throws java.io.IOException;
     method public static synchronized javax.net.SocketFactory getDefault();
     method public abstract java.lang.String[] getDefaultCipherSuites();
     method public abstract java.lang.String[] getSupportedCipherSuites();
diff --git a/api/system-current.txt b/api/system-current.txt
index 0e934c1..4fb52d7 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -73766,7 +73766,6 @@
   public abstract class SSLSocketFactory extends javax.net.SocketFactory {
     ctor public SSLSocketFactory();
     method public abstract java.net.Socket createSocket(java.net.Socket, java.lang.String, int, boolean) throws java.io.IOException;
-    method public java.net.Socket createSocket(java.net.Socket, java.io.InputStream, boolean) throws java.io.IOException;
     method public static synchronized javax.net.SocketFactory getDefault();
     method public abstract java.lang.String[] getDefaultCipherSuites();
     method public abstract java.lang.String[] getSupportedCipherSuites();
diff --git a/api/test-current.txt b/api/test-current.txt
index 7d78dca..29eeec8 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -70278,7 +70278,6 @@
   public abstract class SSLSocketFactory extends javax.net.SocketFactory {
     ctor public SSLSocketFactory();
     method public abstract java.net.Socket createSocket(java.net.Socket, java.lang.String, int, boolean) throws java.io.IOException;
-    method public java.net.Socket createSocket(java.net.Socket, java.io.InputStream, boolean) throws java.io.IOException;
     method public static synchronized javax.net.SocketFactory getDefault();
     method public abstract java.lang.String[] getDefaultCipherSuites();
     method public abstract java.lang.String[] getSupportedCipherSuites();
diff --git a/cmds/pm/src/com/android/commands/pm/Pm.java b/cmds/pm/src/com/android/commands/pm/Pm.java
index 9813cb1..ad989de 100644
--- a/cmds/pm/src/com/android/commands/pm/Pm.java
+++ b/cmds/pm/src/com/android/commands/pm/Pm.java
@@ -1473,7 +1473,7 @@
         ClearDataObserver obs = new ClearDataObserver();
         try {
             mPm.freeStorageAndNotify(volumeUuid, sizeVal,
-                    StorageManager.FLAG_ALLOCATE_DEFY_RESERVED, obs);
+                    StorageManager.FLAG_ALLOCATE_DEFY_ALL_RESERVED, obs);
             synchronized (obs) {
                 while (!obs.finished) {
                     try {
diff --git a/core/java/android/animation/ValueAnimator.java b/core/java/android/animation/ValueAnimator.java
index e686a89..ee89ca8 100644
--- a/core/java/android/animation/ValueAnimator.java
+++ b/core/java/android/animation/ValueAnimator.java
@@ -1469,24 +1469,21 @@
         if (!mSelfPulse) {
             return;
         }
-        AnimationHandler handler = AnimationHandler.getInstance();
-        handler.addOneShotCommitCallback(this);
+        getAnimationHandler().addOneShotCommitCallback(this);
     }
 
     private void removeAnimationCallback() {
         if (!mSelfPulse) {
             return;
         }
-        AnimationHandler handler = AnimationHandler.getInstance();
-        handler.removeCallback(this);
+        getAnimationHandler().removeCallback(this);
     }
 
     private void addAnimationCallback(long delay) {
         if (!mSelfPulse) {
             return;
         }
-        AnimationHandler handler = AnimationHandler.getInstance();
-        handler.addAnimationFrameCallback(this, delay);
+        getAnimationHandler().addAnimationFrameCallback(this, delay);
     }
 
     /**
@@ -1643,4 +1640,12 @@
     public void setAllowRunningAsynchronously(boolean mayRunAsync) {
         // It is up to subclasses to support this, if they can.
     }
+
+    /**
+     * @return The {@link AnimationHandler} that will be used to schedule updates for this animator.
+     * @hide
+     */
+    public AnimationHandler getAnimationHandler() {
+        return AnimationHandler.getInstance();
+    }
 }
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index e672ada..b331d84 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -1947,4 +1947,13 @@
     public void finishOp(int op) {
         finishOp(op, Process.myUid(), mContext.getOpPackageName());
     }
+
+    /** @hide */
+    public boolean isOperationActive(int code, int uid, String packageName) {
+        try {
+            return mService.isOperationActive(code, uid, packageName);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
 }
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index 4f9ed83..1d1a590 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -33,6 +33,8 @@
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.pm.ShortcutInfo;
 import android.content.res.ColorStateList;
+import android.content.res.Configuration;
+import android.content.res.Resources;
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.Color;
@@ -2752,6 +2754,9 @@
         private ArrayList<Action> mOriginalActions;
         private boolean mRebuildStyledRemoteViews;
 
+        private boolean mTintActionButtons;
+        private boolean mInNightMode;
+
         /**
          * Constructs a new Builder with the defaults:
          *
@@ -2783,6 +2788,14 @@
          */
         public Builder(Context context, Notification toAdopt) {
             mContext = context;
+            Resources res = mContext.getResources();
+            mTintActionButtons = res.getBoolean(R.bool.config_tintNotificationActionButtons);
+
+            if (res.getBoolean(R.bool.config_enableNightMode)) {
+                Configuration currentConfig = res.getConfiguration();
+                mInNightMode = (currentConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK)
+                        == Configuration.UI_MODE_NIGHT_YES;
+            }
 
             if (toAdopt == null) {
                 mN = new Notification();
@@ -4631,14 +4644,14 @@
                     // We need to set the text color as well since changing a text to uppercase
                     // clears its spans.
                     button.setTextColor(R.id.action0, outResultColor[0]);
-                } else if (mN.color != COLOR_DEFAULT && !isColorized()) {
+                } else if (mN.color != COLOR_DEFAULT && !isColorized() && mTintActionButtons) {
                     button.setTextColor(R.id.action0,resolveContrastColor());
                 }
             } else {
                 button.setTextViewText(R.id.action0, processLegacyText(action.title));
                 if (isColorized() && !ambient) {
                     setTextViewColorPrimary(button, R.id.action0);
-                } else if (mN.color != COLOR_DEFAULT) {
+                } else if (mN.color != COLOR_DEFAULT && mTintActionButtons) {
                     button.setTextColor(R.id.action0,
                             ambient ? resolveAmbientColor() : resolveContrastColor());
                 }
@@ -4717,7 +4730,7 @@
                             int[] newColors = new int[colors.length];
                             for (int i = 0; i < newColors.length; i++) {
                                 newColors[i] = NotificationColorUtil.ensureLargeTextContrast(
-                                        colors[i], background);
+                                        colors[i], background, mInNightMode);
                             }
                             textColor = new ColorStateList(textColor.getStates().clone(),
                                     newColors);
@@ -4736,7 +4749,7 @@
                         ForegroundColorSpan originalSpan = (ForegroundColorSpan) resultSpan;
                         int foregroundColor = originalSpan.getForegroundColor();
                         foregroundColor = NotificationColorUtil.ensureLargeTextContrast(
-                                foregroundColor, background);
+                                foregroundColor, background, mInNightMode);
                         resultSpan = new ForegroundColorSpan(foregroundColor);
                         if (fullLength) {
                             outResultColor[0] = ColorStateList.valueOf(foregroundColor);
@@ -4831,7 +4844,7 @@
                 color = mSecondaryTextColor;
             } else {
                 color = NotificationColorUtil.resolveContrastColor(mContext, mN.color,
-                        background);
+                        background, mInNightMode);
             }
             if (Color.alpha(color) < 255) {
                 // alpha doesn't go well for color filters, so let's blend it manually
@@ -5064,6 +5077,10 @@
             return mN.isColorized();
         }
 
+        private boolean shouldTintActionButtons() {
+            return mTintActionButtons;
+        }
+
         private boolean textColorsNeedInversion() {
             if (mStyle == null || !MediaStyle.class.equals(mStyle.getClass())) {
                 return false;
@@ -6067,6 +6084,8 @@
             BidiFormatter bidi = BidiFormatter.getInstance();
             SpannableStringBuilder sb = new SpannableStringBuilder();
             boolean colorize = builder.isColorized();
+            TextAppearanceSpan colorSpan;
+            CharSequence messageName;
             if (TextUtils.isEmpty(m.mSender)) {
                 CharSequence replyName = mUserDisplayName == null ? "" : mUserDisplayName;
                 sb.append(bidi.unicodeWrap(replyName),
@@ -6595,8 +6614,16 @@
             RemoteViews button = new BuilderRemoteViews(mBuilder.mContext.getApplicationInfo(),
                     R.layout.notification_material_media_action);
             button.setImageViewIcon(R.id.action0, action.getIcon());
-            button.setDrawableParameters(R.id.action0, false, -1, color, PorterDuff.Mode.SRC_ATOP,
-                    -1);
+
+            // If the action buttons should not be tinted, then just use the default
+            // notification color. Otherwise, just use the passed-in color.
+            int tintColor = mBuilder.shouldTintActionButtons() || mBuilder.isColorized()
+                    ? color
+                    : NotificationColorUtil.resolveColor(mBuilder.mContext,
+                            Notification.COLOR_DEFAULT);
+
+            button.setDrawableParameters(R.id.action0, false, -1, tintColor,
+                    PorterDuff.Mode.SRC_ATOP, -1);
             if (!tombstone) {
                 button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
             }
diff --git a/core/java/android/content/ContentProvider.java b/core/java/android/content/ContentProvider.java
index 9d46da1..64e464c 100644
--- a/core/java/android/content/ContentProvider.java
+++ b/core/java/android/content/ContentProvider.java
@@ -44,6 +44,7 @@
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.UserHandle;
+import android.os.storage.StorageManager;
 import android.text.TextUtils;
 import android.util.Log;
 import android.util.MathUtils;
@@ -1376,6 +1377,12 @@
      * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
      * {@link ParcelFileDescriptor#createReliablePipe()}, or
      * {@link ParcelFileDescriptor#createReliableSocketPair()}.
+     * <p>
+     * If you need to return a large file that isn't backed by a real file on
+     * disk, such as a file on a network share or cloud storage service,
+     * consider using
+     * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
+     * which will let you to stream the content on-demand.
      *
      * <p class="note">For use in Intents, you will want to implement {@link #getType}
      * to return the appropriate MIME type for the data returned here with
diff --git a/core/java/android/hardware/camera2/dispatch/MethodNameInvoker.java b/core/java/android/hardware/camera2/dispatch/MethodNameInvoker.java
index c66a3a4..8296b7a 100644
--- a/core/java/android/hardware/camera2/dispatch/MethodNameInvoker.java
+++ b/core/java/android/hardware/camera2/dispatch/MethodNameInvoker.java
@@ -15,13 +15,13 @@
  */
 package android.hardware.camera2.dispatch;
 
+import static com.android.internal.util.Preconditions.checkNotNull;
+
 import android.hardware.camera2.utils.UncheckedThrow;
 
 import java.lang.reflect.Method;
 import java.util.concurrent.ConcurrentHashMap;
 
-import static com.android.internal.util.Preconditions.*;
-
 /**
  * Invoke a method on a dispatchable by its name (without knowing the {@code Method} ahead of time).
  *
@@ -31,6 +31,7 @@
 
     private final Dispatchable<T> mTarget;
     private final Class<T> mTargetClass;
+    private final Method[] mTargetClassMethods;
     private final ConcurrentHashMap<String, Method> mMethods =
             new ConcurrentHashMap<>();
 
@@ -42,6 +43,7 @@
      */
     public MethodNameInvoker(Dispatchable<T> target, Class<T> targetClass) {
         mTargetClass = targetClass;
+        mTargetClassMethods = targetClass.getMethods();
         mTarget = target;
     }
 
@@ -68,7 +70,7 @@
 
         Method targetMethod = mMethods.get(methodName);
         if (targetMethod == null) {
-            for (Method method : mTargetClass.getMethods()) {
+            for (Method method : mTargetClassMethods) {
                 // TODO future: match types of params if possible
                 if (method.getName().equals(methodName) &&
                         (params.length == method.getParameterTypes().length) ) {
diff --git a/core/java/android/hardware/radio/ITunerCallback.aidl b/core/java/android/hardware/radio/ITunerCallback.aidl
index b32c683..aed114e 100644
--- a/core/java/android/hardware/radio/ITunerCallback.aidl
+++ b/core/java/android/hardware/radio/ITunerCallback.aidl
@@ -17,10 +17,18 @@
 package android.hardware.radio;
 
 import android.hardware.radio.RadioManager;
+import android.hardware.radio.RadioMetadata;
 
 /** {@hide} */
 oneway interface ITunerCallback {
     void onError(int status);
     void onConfigurationChanged(in RadioManager.BandConfig config);
     void onProgramInfoChanged(in RadioManager.ProgramInfo info);
+    void onMetadataChanged(in RadioMetadata metadata);
+    void onTrafficAnnouncement(boolean active);
+    void onEmergencyAnnouncement(boolean active);
+    void onAntennaState(boolean connected);
+    void onBackgroundScanAvailabilityChange(boolean isAvailable);
+    void onBackgroundScanComplete();
+    void onProgramListChanged();
 }
diff --git a/core/java/android/hardware/radio/RadioMetadata.aidl b/core/java/android/hardware/radio/RadioMetadata.aidl
new file mode 100644
index 0000000..cbf4713
--- /dev/null
+++ b/core/java/android/hardware/radio/RadioMetadata.aidl
@@ -0,0 +1,20 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.radio;
+
+/** @hide */
+parcelable RadioMetadata;
diff --git a/core/java/android/hardware/radio/RadioTuner.java b/core/java/android/hardware/radio/RadioTuner.java
index 6e1232d..78d7b61 100644
--- a/core/java/android/hardware/radio/RadioTuner.java
+++ b/core/java/android/hardware/radio/RadioTuner.java
@@ -19,14 +19,9 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.SystemApi;
-import android.content.Context;
-import android.content.Intent;
 import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import java.lang.ref.WeakReference;
+
 import java.util.List;
-import java.util.UUID;
 
 /**
  * RadioTuner interface provides methods to control a radio tuner on the device: selecting and
@@ -303,6 +298,16 @@
     public static final  int ERROR_SCAN_TIMEOUT = 3;
     /** The requested configuration could not be applied */
     public static final  int ERROR_CONFIG = 4;
+    /**
+     * Background scan was interrupted due to hardware becoming temporarily unavailable.
+     * @hide FutureFeature
+     */
+    public static final int ERROR_BACKGROUND_SCAN_UNAVAILABLE = 5;
+    /**
+     * Background scan failed due to other error, ie. HW failure.
+     * @hide FutureFeature
+     */
+    public static final int ERROR_BACKGROUND_SCAN_FAILED = 6;
 
     /**
      * Callback provided by the client application when opening a {@link RadioTuner}
diff --git a/core/java/android/hardware/radio/TunerCallbackAdapter.java b/core/java/android/hardware/radio/TunerCallbackAdapter.java
index ba85017..155ffa7 100644
--- a/core/java/android/hardware/radio/TunerCallbackAdapter.java
+++ b/core/java/android/hardware/radio/TunerCallbackAdapter.java
@@ -51,4 +51,39 @@
     public void onProgramInfoChanged(RadioManager.ProgramInfo info) {
         mHandler.post(() -> mCallback.onProgramInfoChanged(info));
     }
+
+    @Override
+    public void onMetadataChanged(RadioMetadata metadata) {
+        mHandler.post(() -> mCallback.onMetadataChanged(metadata));
+    }
+
+    @Override
+    public void onTrafficAnnouncement(boolean active) {
+        mHandler.post(() -> mCallback.onTrafficAnnouncement(active));
+    }
+
+    @Override
+    public void onEmergencyAnnouncement(boolean active) {
+        mHandler.post(() -> mCallback.onEmergencyAnnouncement(active));
+    }
+
+    @Override
+    public void onAntennaState(boolean connected) {
+        mHandler.post(() -> mCallback.onAntennaState(connected));
+    }
+
+    @Override
+    public void onBackgroundScanAvailabilityChange(boolean isAvailable) {
+        mHandler.post(() -> mCallback.onBackgroundScanAvailabilityChange(isAvailable));
+    }
+
+    @Override
+    public void onBackgroundScanComplete() {
+        mHandler.post(() -> mCallback.onBackgroundScanComplete());
+    }
+
+    @Override
+    public void onProgramListChanged() {
+        mHandler.post(() -> mCallback.onProgramListChanged());
+    }
 }
diff --git a/core/java/android/os/SynchronousResultReceiver.java b/core/java/android/os/SynchronousResultReceiver.java
index d1b6288..6e1d4b31 100644
--- a/core/java/android/os/SynchronousResultReceiver.java
+++ b/core/java/android/os/SynchronousResultReceiver.java
@@ -43,9 +43,19 @@
     }
 
     private final CompletableFuture<Result> mFuture = new CompletableFuture<>();
+    private final String mName;
 
     public SynchronousResultReceiver() {
         super((Handler) null);
+        mName = null;
+    }
+
+    /**
+     * @param name Name for logging purposes
+     */
+    public SynchronousResultReceiver(String name) {
+        super((Handler) null);
+        mName = name;
     }
 
     @Override
@@ -54,6 +64,10 @@
         mFuture.complete(new Result(resultCode, resultData));
     }
 
+    public String getName() {
+        return mName;
+    }
+
     /**
      * Blocks waiting for the result from the remote client.
      *
diff --git a/core/java/android/os/storage/IStorageManager.aidl b/core/java/android/os/storage/IStorageManager.aidl
index 92f7f31..50855bb 100644
--- a/core/java/android/os/storage/IStorageManager.aidl
+++ b/core/java/android/os/storage/IStorageManager.aidl
@@ -293,7 +293,7 @@
     ParcelFileDescriptor openProxyFileDescriptor(int mountPointId, int fileId, int mode) = 74;
     long getCacheQuotaBytes(String volumeUuid, int uid) = 75;
     long getCacheSizeBytes(String volumeUuid, int uid) = 76;
-    long getAllocatableBytes(String volumeUuid, int flags) = 77;
-    void allocateBytes(String volumeUuid, long bytes, int flags) = 78;
+    long getAllocatableBytes(String volumeUuid, int flags, String callingPackage) = 77;
+    void allocateBytes(String volumeUuid, long bytes, int flags, String callingPackage) = 78;
     void secdiscard(in String path) = 79;
 }
diff --git a/core/java/android/os/storage/StorageManager.java b/core/java/android/os/storage/StorageManager.java
index 5046735..f2aa113 100644
--- a/core/java/android/os/storage/StorageManager.java
+++ b/core/java/android/os/storage/StorageManager.java
@@ -29,6 +29,7 @@
 import android.annotation.SystemApi;
 import android.annotation.SystemService;
 import android.annotation.WorkerThread;
+import android.app.Activity;
 import android.app.ActivityThread;
 import android.content.ContentResolver;
 import android.content.Context;
@@ -159,6 +160,12 @@
      * If the sending application has a specific storage device or allocation
      * size in mind, they can optionally define {@link #EXTRA_UUID} or
      * {@link #EXTRA_REQUESTED_BYTES}, respectively.
+     * <p>
+     * This intent should be launched using
+     * {@link Activity#startActivityForResult(Intent, int)} so that the user
+     * knows which app is requesting the storage space. The returned result will
+     * be {@link Activity#RESULT_OK} if the requested space was made available,
+     * or {@link Activity#RESULT_CANCELED} otherwise.
      */
     @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION)
     public static final String ACTION_MANAGE_STORAGE = "android.os.storage.action.MANAGE_STORAGE";
@@ -1174,7 +1181,7 @@
      *
      * @hide
      */
-    public long getStorageCacheBytes(File path) {
+    public long getStorageCacheBytes(File path, @AllocateFlags int flags) {
         final long cachePercent = Settings.Global.getInt(mResolver,
                 Settings.Global.SYS_STORAGE_CACHE_PERCENTAGE, DEFAULT_CACHE_PERCENTAGE);
         final long cacheBytes = (path.getTotalSpace() * cachePercent) / 100;
@@ -1182,7 +1189,16 @@
         final long maxCacheBytes = Settings.Global.getLong(mResolver,
                 Settings.Global.SYS_STORAGE_CACHE_MAX_BYTES, DEFAULT_CACHE_MAX_BYTES);
 
-        return Math.min(cacheBytes, maxCacheBytes);
+        final long result = Math.min(cacheBytes, maxCacheBytes);
+        if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
+            return 0;
+        } else if ((flags & StorageManager.FLAG_ALLOCATE_DEFY_ALL_RESERVED) != 0) {
+            return 0;
+        } else if ((flags & StorageManager.FLAG_ALLOCATE_DEFY_HALF_RESERVED) != 0) {
+            return result / 2;
+        } else {
+            return result;
+        }
     }
 
     /**
@@ -1467,15 +1483,26 @@
     }
 
     /**
-     * Opens seekable ParcelFileDescriptor that routes file operation requests to
-     * ProxyFileDescriptorCallback.
+     * Opens a seekable {@link ParcelFileDescriptor} that proxies all low-level
+     * I/O requests back to the given {@link ProxyFileDescriptorCallback}.
+     * <p>
+     * This can be useful when you want to provide quick access to a large file
+     * that isn't backed by a real file on disk, such as a file on a network
+     * share, cloud storage service, etc. As an example, you could respond to a
+     * {@link ContentResolver#openFileDescriptor(android.net.Uri, String)}
+     * request by returning a {@link ParcelFileDescriptor} created with this
+     * method, and then stream the content on-demand as requested.
+     * <p>
+     * Another useful example might be where you have an encrypted file that
+     * you're willing to decrypt on-demand, but where you want to avoid
+     * persisting the cleartext version.
      *
      * @param mode The desired access mode, must be one of
-     *     {@link ParcelFileDescriptor#MODE_READ_ONLY},
-     *     {@link ParcelFileDescriptor#MODE_WRITE_ONLY}, or
-     *     {@link ParcelFileDescriptor#MODE_READ_WRITE}
-     * @param callback Callback to process file operation requests issued on returned file
-     *     descriptor.
+     *            {@link ParcelFileDescriptor#MODE_READ_ONLY},
+     *            {@link ParcelFileDescriptor#MODE_WRITE_ONLY}, or
+     *            {@link ParcelFileDescriptor#MODE_READ_WRITE}
+     * @param callback Callback to process file operation requests issued on
+     *            returned file descriptor.
      * @param handler Handler that invokes callback methods.
      * @return Seekable ParcelFileDescriptor.
      * @throws IOException
@@ -1487,7 +1514,6 @@
         return openProxyFileDescriptor(mode, callback, handler, null);
     }
 
-
     /** {@hide} */
     @VisibleForTesting
     public int getProxyFileDescriptorMountPointId() {
@@ -1628,17 +1654,26 @@
     public static final int FLAG_ALLOCATE_AGGRESSIVE = 1 << 0;
 
     /**
-     * Flag indicating that a disk space allocation request should defy any
-     * reserved disk space.
+     * Flag indicating that a disk space allocation request should be allowed to
+     * clear up to all reserved disk space.
      *
      * @hide
      */
-    public static final int FLAG_ALLOCATE_DEFY_RESERVED = 1 << 1;
+    public static final int FLAG_ALLOCATE_DEFY_ALL_RESERVED = 1 << 1;
+
+    /**
+     * Flag indicating that a disk space allocation request should be allowed to
+     * clear up to half of all reserved disk space.
+     *
+     * @hide
+     */
+    public static final int FLAG_ALLOCATE_DEFY_HALF_RESERVED = 1 << 2;
 
     /** @hide */
     @IntDef(flag = true, value = {
             FLAG_ALLOCATE_AGGRESSIVE,
-            FLAG_ALLOCATE_DEFY_RESERVED,
+            FLAG_ALLOCATE_DEFY_ALL_RESERVED,
+            FLAG_ALLOCATE_DEFY_HALF_RESERVED,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface AllocateFlags {}
@@ -1660,6 +1695,10 @@
      * persist, you can launch {@link #ACTION_MANAGE_STORAGE} with the
      * {@link #EXTRA_UUID} and {@link #EXTRA_REQUESTED_BYTES} options to help
      * involve the user in freeing up disk space.
+     * <p>
+     * If you're progressively allocating an unbounded amount of storage space
+     * (such as when recording a video) you should avoid calling this method
+     * more than once every 30 seconds.
      * <p class="note">
      * Note: if your app uses the {@code android:sharedUserId} manifest feature,
      * then allocatable space for all packages in your shared UID is tracked
@@ -1677,6 +1716,7 @@
      * @throws IOException when the storage device isn't present, or when it
      *             doesn't support allocating space.
      */
+    @WorkerThread
     public @BytesLong long getAllocatableBytes(@NonNull UUID storageUuid)
             throws IOException {
         return getAllocatableBytes(storageUuid, 0);
@@ -1684,11 +1724,13 @@
 
     /** @hide */
     @SystemApi
+    @WorkerThread
     @SuppressLint("Doclava125")
     public long getAllocatableBytes(@NonNull UUID storageUuid,
             @RequiresPermission @AllocateFlags int flags) throws IOException {
         try {
-            return mStorageManager.getAllocatableBytes(convert(storageUuid), flags);
+            return mStorageManager.getAllocatableBytes(convert(storageUuid), flags,
+                    mContext.getOpPackageName());
         } catch (ParcelableException e) {
             e.maybeRethrow(IOException.class);
             throw new RuntimeException(e);
@@ -1699,6 +1741,7 @@
 
     /** @removed */
     @Deprecated
+    @WorkerThread
     @SuppressLint("Doclava125")
     public long getAllocatableBytes(@NonNull File path,
             @RequiresPermission @AllocateFlags int flags) throws IOException {
@@ -1717,6 +1760,10 @@
      * subject to race conditions. If possible, consider using
      * {@link #allocateBytes(FileDescriptor, long, int)} which will guarantee
      * that bytes are allocated to an opened file.
+     * <p>
+     * If you're progressively allocating an unbounded amount of storage space
+     * (such as when recording a video) you should avoid calling this method
+     * more than once every 60 seconds.
      *
      * @param storageUuid the UUID of the storage volume where you'd like to
      *            allocate disk space. The UUID for a specific path can be
@@ -1727,6 +1774,7 @@
      *             trouble allocating the requested space.
      * @see #getAllocatableBytes(UUID, int)
      */
+    @WorkerThread
     public void allocateBytes(@NonNull UUID storageUuid, @BytesLong long bytes)
             throws IOException {
         allocateBytes(storageUuid, bytes, 0);
@@ -1734,11 +1782,13 @@
 
     /** @hide */
     @SystemApi
+    @WorkerThread
     @SuppressLint("Doclava125")
     public void allocateBytes(@NonNull UUID storageUuid, @BytesLong long bytes,
             @RequiresPermission @AllocateFlags int flags) throws IOException {
         try {
-            mStorageManager.allocateBytes(convert(storageUuid), bytes, flags);
+            mStorageManager.allocateBytes(convert(storageUuid), bytes, flags,
+                    mContext.getOpPackageName());
         } catch (ParcelableException e) {
             e.maybeRethrow(IOException.class);
         } catch (RemoteException e) {
@@ -1748,6 +1798,7 @@
 
     /** @removed */
     @Deprecated
+    @WorkerThread
     @SuppressLint("Doclava125")
     public void allocateBytes(@NonNull File path, @BytesLong long bytes,
             @RequiresPermission @AllocateFlags int flags) throws IOException {
@@ -1766,6 +1817,10 @@
      * otherwise it will throw if fast allocation is not possible. Fast
      * allocation is typically only supported in private app data directories,
      * and on shared/external storage devices which are emulated.
+     * <p>
+     * If you're progressively allocating an unbounded amount of storage space
+     * (such as when recording a video) you should avoid calling this method
+     * more than once every 60 seconds.
      *
      * @param fd the open file that you'd like to allocate disk space for.
      * @param bytes the number of bytes to allocate. This is the desired final
@@ -1779,12 +1834,14 @@
      * @see #getAllocatableBytes(UUID, int)
      * @see Environment#isExternalStorageEmulated(File)
      */
+    @WorkerThread
     public void allocateBytes(FileDescriptor fd, @BytesLong long bytes) throws IOException {
         allocateBytes(fd, bytes, 0);
     }
 
     /** @hide */
     @SystemApi
+    @WorkerThread
     @SuppressLint("Doclava125")
     public void allocateBytes(FileDescriptor fd, @BytesLong long bytes,
             @RequiresPermission @AllocateFlags int flags) throws IOException {
diff --git a/core/java/android/util/LocalLog.java b/core/java/android/util/LocalLog.java
index 665c583..eb84479f 100644
--- a/core/java/android/util/LocalLog.java
+++ b/core/java/android/util/LocalLog.java
@@ -18,10 +18,10 @@
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
-import java.util.Calendar;
-import java.util.Iterator;
-import java.util.Deque;
+import java.time.LocalDateTime;
 import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.Iterator;
 
 /**
  * @hide
@@ -40,9 +40,7 @@
         if (mMaxLines <= 0) {
             return;
         }
-        Calendar c = Calendar.getInstance();
-        c.setTimeInMillis(System.currentTimeMillis());
-        append(String.format("%tm-%td %tH:%tM:%tS.%tL - %s", c, c, c, c, c, c, msg));
+        append(String.format("%s - %s", LocalDateTime.now(), msg));
     }
 
     private synchronized void append(String logLine) {
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index ef78559..679a9cd 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -1196,6 +1196,12 @@
             mBackgroundControl.deferTransactionUntil(handle, frame);
         }
 
+        @Override
+        public void deferTransactionUntil(Surface barrier, long frame) {
+            super.deferTransactionUntil(barrier, frame);
+            mBackgroundControl.deferTransactionUntil(barrier, frame);
+        }
+
         void updateBackgroundVisibility() {
             if (mOpaque && mVisible) {
                 mBackgroundControl.show();
diff --git a/core/java/com/android/internal/app/IAppOpsService.aidl b/core/java/com/android/internal/app/IAppOpsService.aidl
index 35d4ba8..7a119b4 100644
--- a/core/java/com/android/internal/app/IAppOpsService.aidl
+++ b/core/java/com/android/internal/app/IAppOpsService.aidl
@@ -48,4 +48,6 @@
     void setUserRestrictions(in Bundle restrictions, IBinder token, int userHandle);
     void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle, in String[] exceptionPackages);
     void removeUser(int userHandle);
+
+    boolean isOperationActive(int code, int uid, String packageName);
 }
diff --git a/core/java/com/android/internal/app/LocalePickerWithRegion.java b/core/java/com/android/internal/app/LocalePickerWithRegion.java
index d0719ee..3d5cd0f 100644
--- a/core/java/com/android/internal/app/LocalePickerWithRegion.java
+++ b/core/java/com/android/internal/app/LocalePickerWithRegion.java
@@ -238,7 +238,7 @@
             mSearchView.setOnQueryTextListener(this);
 
             // Restore previous search status
-            if (!TextUtils.isEmpty(mPreviousSearch)) {
+            if (mPreviousSearch != null) {
                 searchMenuItem.expandActionView();
                 mSearchView.setIconified(false);
                 mSearchView.setActivated(true);
diff --git a/core/java/com/android/internal/graphics/SfVsyncFrameCallbackProvider.java b/core/java/com/android/internal/graphics/SfVsyncFrameCallbackProvider.java
new file mode 100644
index 0000000..931eb99
--- /dev/null
+++ b/core/java/com/android/internal/graphics/SfVsyncFrameCallbackProvider.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.graphics;
+
+import android.animation.AnimationHandler.AnimationFrameCallbackProvider;
+import android.view.Choreographer;
+
+/**
+ * Provider of timing pulse that uses SurfaceFlinger Vsync Choreographer for frame callbacks.
+ *
+ * @hide
+ */
+public final class SfVsyncFrameCallbackProvider implements AnimationFrameCallbackProvider {
+
+    private final Choreographer mChoreographer = Choreographer.getSfInstance();
+
+    @Override
+    public void postFrameCallback(Choreographer.FrameCallback callback) {
+        mChoreographer.postFrameCallback(callback);
+    }
+
+    @Override
+    public void postCommitCallback(Runnable runnable) {
+        mChoreographer.postCallback(Choreographer.CALLBACK_COMMIT, runnable, null);
+    }
+
+    @Override
+    public long getFrameTime() {
+        return mChoreographer.getFrameTime();
+    }
+
+    @Override
+    public long getFrameDelay() {
+        return Choreographer.getFrameDelay();
+    }
+
+    @Override
+    public void setFrameDelay(long delay) {
+        Choreographer.setFrameDelay(delay);
+    }
+}
\ No newline at end of file
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 2363f68..696dbda 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -95,6 +95,7 @@
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
+import java.util.concurrent.Future;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.locks.ReentrantLock;
 
@@ -121,15 +122,34 @@
     private static final int VERSION = 159 + (USE_OLD_HISTORY ? 1000 : 0);
 
     // Maximum number of items we will record in the history.
-    private static final int MAX_HISTORY_ITEMS = 2000;
+    private static final int MAX_HISTORY_ITEMS;
 
     // No, really, THIS is the maximum number of items we will record in the history.
-    private static final int MAX_MAX_HISTORY_ITEMS = 3000;
+    private static final int MAX_MAX_HISTORY_ITEMS;
 
     // The maximum number of names wakelocks we will keep track of
     // per uid; once the limit is reached, we batch the remaining wakelocks
     // in to one common name.
-    private static final int MAX_WAKELOCKS_PER_UID = 100;
+    private static final int MAX_WAKELOCKS_PER_UID;
+
+    static final int MAX_HISTORY_BUFFER; // 256KB
+    static final int MAX_MAX_HISTORY_BUFFER; // 320KB
+
+    static {
+        if (ActivityManager.isLowRamDeviceStatic()) {
+            MAX_HISTORY_ITEMS = 800;
+            MAX_MAX_HISTORY_ITEMS = 1200;
+            MAX_WAKELOCKS_PER_UID = 40;
+            MAX_HISTORY_BUFFER = 96*1024;  // 96KB
+            MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
+        } else {
+            MAX_HISTORY_ITEMS = 2000;
+            MAX_MAX_HISTORY_ITEMS = 3000;
+            MAX_WAKELOCKS_PER_UID = 100;
+            MAX_HISTORY_BUFFER = 256*1024;  // 256KB
+            MAX_MAX_HISTORY_BUFFER = 320*1024;  // 256KB
+        }
+    }
 
     // Number of transmit power states the Wifi controller can be in.
     private static final int NUM_WIFI_TX_LEVELS = 1;
@@ -236,12 +256,12 @@
         int UPDATE_BT = 0x08;
         int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT;
 
-        void scheduleSync(String reason, int flags);
-        void scheduleCpuSyncDueToRemovedUid(int uid);
+        Future<?> scheduleSync(String reason, int flags);
+        Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
     }
 
     public final MyHandler mHandler;
-    private final ExternalStatsSync mExternalSync;
+    private ExternalStatsSync mExternalSync = null;
 
     private BatteryCallback mCallback;
 
@@ -299,8 +319,6 @@
     boolean mRecordingHistory = false;
     int mNumHistoryItems;
 
-    static final int MAX_HISTORY_BUFFER = 256*1024; // 256KB
-    static final int MAX_MAX_HISTORY_BUFFER = 320*1024; // 320KB
     final Parcel mHistoryBuffer = Parcel.obtain();
     final HistoryItem mHistoryLastWritten = new HistoryItem();
     final HistoryItem mHistoryLastLastWritten = new HistoryItem();
@@ -630,7 +648,6 @@
         mCheckinFile = null;
         mDailyFile = null;
         mHandler = null;
-        mExternalSync = null;
         mPlatformIdleStateCallback = null;
         clearHistoryLocked();
     }
@@ -8597,17 +8614,16 @@
         return mCpuFreqs;
     }
 
-    public BatteryStatsImpl(File systemDir, Handler handler, ExternalStatsSync externalSync) {
-        this(new SystemClocks(), systemDir, handler, externalSync, null);
+    public BatteryStatsImpl(File systemDir, Handler handler) {
+        this(new SystemClocks(), systemDir, handler, null);
     }
 
-    public BatteryStatsImpl(File systemDir, Handler handler, ExternalStatsSync externalSync,
-                            PlatformIdleStateCallback cb) {
-        this(new SystemClocks(), systemDir, handler, externalSync, cb);
+    public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb) {
+        this(new SystemClocks(), systemDir, handler, cb);
     }
 
     public BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
-            ExternalStatsSync externalSync, PlatformIdleStateCallback cb) {
+            PlatformIdleStateCallback cb) {
         init(clocks);
 
         if (systemDir != null) {
@@ -8618,7 +8634,6 @@
         }
         mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
         mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
-        mExternalSync = externalSync;
         mHandler = new MyHandler(handler.getLooper());
         mStartCount++;
         mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
@@ -8745,6 +8760,10 @@
         }
     }
 
+    public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
+        mExternalSync = sync;
+    }
+
     public void updateDailyDeadlineLocked() {
         // Get the current time.
         long currentTime = mDailyStartTime = System.currentTimeMillis();
@@ -9750,7 +9769,7 @@
                 return;
             }
 
-            final long elapsedRealtimeMs = SystemClock.elapsedRealtime();
+            final long elapsedRealtimeMs = mClocks.elapsedRealtime();
             long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
                     elapsedRealtimeMs * 1000);
             mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
diff --git a/core/java/com/android/internal/util/NotificationColorUtil.java b/core/java/com/android/internal/util/NotificationColorUtil.java
index 1ba92bf..5c9f1c6 100644
--- a/core/java/com/android/internal/util/NotificationColorUtil.java
+++ b/core/java/com/android/internal/util/NotificationColorUtil.java
@@ -360,20 +360,28 @@
         return findContrastColorAgainstDark(color, Color.BLACK, true /* fg */, 12);
     }
 
-    /**
-     * Finds a text color with sufficient contrast over bg that has the same hue as the original
-     * color, assuming it is for large text.
+     /**
+     * Finds a large text color with sufficient contrast over bg that has the same or darker hue as
+     * the original color, depending on the value of {@code isBgDarker}.
+     *
+     * @param isBgDarker {@code true} if {@code bg} is darker than {@code color}.
      */
-    public static int ensureLargeTextContrast(int color, int bg) {
-        return findContrastColor(color, bg, true, 3);
+    public static int ensureLargeTextContrast(int color, int bg, boolean isBgDarker) {
+        return isBgDarker
+                ? findContrastColorAgainstDark(color, bg, true, 3)
+                : findContrastColor(color, bg, true, 3);
     }
 
     /**
-     * Finds a text color with sufficient contrast over bg that has the same hue as the original
-     * color.
+     * Finds a text color with sufficient contrast over bg that has the same or darker hue as the
+     * original color, depending on the value of {@code isBgDarker}.
+     *
+     * @param isBgDarker {@code true} if {@code bg} is darker than {@code color}.
      */
-    private static int ensureTextContrast(int color, int bg) {
-        return findContrastColor(color, bg, true, 4.5);
+    private static int ensureTextContrast(int color, int bg, boolean isBgDarker) {
+        return isBgDarker
+                ? findContrastColorAgainstDark(color, bg, true, 4.5)
+                : findContrastColor(color, bg, true, 4.5);
     }
 
     /** Finds a background color for a text view with given text color and hint text color, that
@@ -402,22 +410,37 @@
 
     /**
      * Resolves a Notification's color such that it has enough contrast to be used as the
+     * color for the Notification's action and header text on a background that is lighter than
+     * {@code notificationColor}.
+     *
+     * @see {@link #resolveContrastColor(Context, int, boolean)}
+     */
+    public static int resolveContrastColor(Context context, int notificationColor,
+            int backgroundColor) {
+        return NotificationColorUtil.resolveContrastColor(context, notificationColor,
+                backgroundColor, false /* isDark */);
+    }
+
+    /**
+     * Resolves a Notification's color such that it has enough contrast to be used as the
      * color for the Notification's action and header text.
      *
      * @param notificationColor the color of the notification or {@link Notification#COLOR_DEFAULT}
      * @param backgroundColor the background color to ensure the contrast against.
+     * @param isDark whether or not the {@code notificationColor} will be placed on a background
+     *               that is darker than the color itself
      * @return a color of the same hue with enough contrast against the backgrounds.
      */
     public static int resolveContrastColor(Context context, int notificationColor,
-            int backgroundColor) {
+            int backgroundColor, boolean isDark) {
         final int resolvedColor = resolveColor(context, notificationColor);
 
         final int actionBg = context.getColor(
                 com.android.internal.R.color.notification_action_list);
 
         int color = resolvedColor;
-        color = NotificationColorUtil.ensureLargeTextContrast(color, actionBg);
-        color = NotificationColorUtil.ensureTextContrast(color, backgroundColor);
+        color = NotificationColorUtil.ensureLargeTextContrast(color, actionBg, isDark);
+        color = NotificationColorUtil.ensureTextContrast(color, backgroundColor, isDark);
 
         if (color != resolvedColor) {
             if (DEBUG){
diff --git a/core/java/com/android/internal/view/TooltipPopup.java b/core/java/com/android/internal/view/TooltipPopup.java
index d834e63..52357ac 100644
--- a/core/java/com/android/internal/view/TooltipPopup.java
+++ b/core/java/com/android/internal/view/TooltipPopup.java
@@ -25,7 +25,6 @@
 import android.view.View;
 import android.view.WindowManager;
 import android.view.WindowManagerGlobal;
-import android.widget.PopupWindow;
 import android.widget.TextView;
 
 public class TooltipPopup {
@@ -33,7 +32,6 @@
 
     private final Context mContext;
 
-    private final PopupWindow mPopupWindow;
     private final View mContentView;
     private final TextView mMessageView;
 
@@ -45,8 +43,6 @@
     public TooltipPopup(Context context) {
         mContext = context;
 
-        mPopupWindow = new PopupWindow(context);
-        mPopupWindow.setBackgroundDrawable(null);
         mContentView = LayoutInflater.from(mContext).inflate(
                 com.android.internal.R.layout.tooltip, null);
         mMessageView = (TextView) mContentView.findViewById(
@@ -74,16 +70,17 @@
 
         computePosition(anchorView, anchorX, anchorY, fromTouch, mLayoutParams);
 
-        mPopupWindow.setContentView(mContentView);
-        mPopupWindow.showAtLocation(
-            anchorView, mLayoutParams.gravity, mLayoutParams.x, mLayoutParams.y);
+        WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
+        wm.addView(mContentView, mLayoutParams);
     }
 
     public void hide() {
         if (!isShowing()) {
             return;
         }
-        mPopupWindow.dismiss();
+
+        WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
+        wm.removeView(mContentView);
     }
 
     public View getContentView() {
@@ -91,7 +88,7 @@
     }
 
     public boolean isShowing() {
-        return mPopupWindow.isShowing();
+        return mContentView.getParent() != null;
     }
 
     public void updateContent(CharSequence tooltipText) {
@@ -100,6 +97,8 @@
 
     private void computePosition(View anchorView, int anchorX, int anchorY, boolean fromTouch,
             WindowManager.LayoutParams outParams) {
+        outParams.token = anchorView.getWindowToken();
+
         final int tooltipPreciseAnchorThreshold = mContext.getResources().getDimensionPixelOffset(
                 com.android.internal.R.dimen.tooltip_precise_anchor_threshold);
 
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 9455d92..395250c 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -455,6 +455,7 @@
     <protected-broadcast android:name="com.android.server.NetworkTimeUpdateService.action.POLL" />
     <protected-broadcast android:name="com.android.server.telecom.intent.action.CALLS_ADD_ENTRY" />
     <protected-broadcast android:name="com.android.settings.location.MODE_CHANGING" />
+    <protected-broadcast android:name="com.android.settings.bluetooth.ACTION_DISMISS_PAIRING" />
 
     <protected-broadcast android:name="NotificationManagerService.TIMEOUT" />
     <protected-broadcast android:name="ScheduleConditionProvider.EVALUATE" />
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 76cee70..4a000b9 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -2978,4 +2978,11 @@
 
     <!-- An array of packages that need to be treated as type service in battery settings -->
     <string-array translatable="false" name="config_batteryPackageTypeService"/>
+
+    <!-- Flag indicating whether or not to enable night mode detection. -->
+    <bool name="config_enableNightMode">false</bool>
+
+    <!-- Flag indicating that the actions buttons for a notification should be tinted with by the
+         color supplied by the Notification.Builder if present. -->
+    <bool name="config_tintNotificationActionButtons">true</bool>
 </resources>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 241886c..023b032 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -1749,6 +1749,8 @@
   <java-symbol type="bool" name="config_automatic_brightness_available" />
   <java-symbol type="bool" name="config_autoBrightnessResetAmbientLuxAfterWarmUp" />
   <java-symbol type="bool" name="config_notificationHeaderClickableForExpand" />
+  <java-symbol type="bool" name="config_enableNightMode" />
+  <java-symbol type="bool" name="config_tintNotificationActionButtons" />
   <java-symbol type="bool" name="config_dozeAfterScreenOff" />
   <java-symbol type="bool" name="config_enableActivityRecognitionHardwareOverlay" />
   <java-symbol type="bool" name="config_enableFusedLocationOverlay" />
diff --git a/media/java/android/media/ExifInterface.java b/media/java/android/media/ExifInterface.java
index 0a61148..6677178 100644
--- a/media/java/android/media/ExifInterface.java
+++ b/media/java/android/media/ExifInterface.java
@@ -2661,9 +2661,9 @@
     }
 
     private void addDefaultValuesForCompatibility() {
-        // The value of DATETIME tag has the same value of DATETIME_ORIGINAL tag.
+        // If DATETIME tag has no value, then set the value to DATETIME_ORIGINAL tag's.
         String valueOfDateTimeOriginal = getAttribute(TAG_DATETIME_ORIGINAL);
-        if (valueOfDateTimeOriginal != null) {
+        if (valueOfDateTimeOriginal != null && getAttribute(TAG_DATETIME) == null) {
             mAttributes[IFD_TYPE_PRIMARY].put(TAG_DATETIME,
                     ExifAttribute.createString(valueOfDateTimeOriginal));
         }
diff --git a/media/java/android/media/audiofx/AcousticEchoCanceler.java b/media/java/android/media/audiofx/AcousticEchoCanceler.java
index f5f98ef..3a44df4 100644
--- a/media/java/android/media/audiofx/AcousticEchoCanceler.java
+++ b/media/java/android/media/audiofx/AcousticEchoCanceler.java
@@ -20,7 +20,7 @@
 
 /**
  * Acoustic Echo Canceler (AEC).
- * <p>Acoustic Echo Canceler (AEC) is an audio pre-processing which removes the contribution of the
+ * <p>Acoustic Echo Canceler (AEC) is an audio pre-processor which removes the contribution of the
  * signal received from the remote party from the captured audio signal.
  * <p>AEC is used by voice communication applications (voice chat, video conferencing, SIP calls)
  * where the presence of echo with significant delay in the signal received from the remote party
diff --git a/media/java/android/media/audiofx/AutomaticGainControl.java b/media/java/android/media/audiofx/AutomaticGainControl.java
index 4a6b1f3..a76b4de 100644
--- a/media/java/android/media/audiofx/AutomaticGainControl.java
+++ b/media/java/android/media/audiofx/AutomaticGainControl.java
@@ -20,7 +20,7 @@
 
 /**
  * Automatic Gain Control (AGC).
- * <p>Automatic Gain Control (AGC) is an audio pre-processing which automatically normalizes the
+ * <p>Automatic Gain Control (AGC) is an audio pre-processor which automatically normalizes the
  * output of the captured signal by boosting or lowering input from the microphone to match a preset
  * level so that the output signal level is virtually constant.
  * AGC can be used by applications where the input signal dynamic range is not important but where
diff --git a/media/java/android/media/audiofx/NoiseSuppressor.java b/media/java/android/media/audiofx/NoiseSuppressor.java
index bca990f..70cc87c 100644
--- a/media/java/android/media/audiofx/NoiseSuppressor.java
+++ b/media/java/android/media/audiofx/NoiseSuppressor.java
@@ -20,7 +20,7 @@
 
 /**
  * Noise Suppressor (NS).
- * <p>Noise suppression (NS) is an audio pre-processing which removes background noise from the
+ * <p>Noise suppression (NS) is an audio pre-processor which removes background noise from the
  * captured signal. The component of the signal considered as noise can be either stationary
  * (car/airplane engine, AC system) or non-stationary (other peoples conversations, car horn) for
  * more advanced implementations.
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index b8de9f3..6d10d94 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -1868,12 +1868,7 @@
                         + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
             }
 
-            if (!(mContext instanceof Activity)) {
-                final int finalFlags = flags;
-                mUiOffloadThread.submit(() -> {
-                    mStatusBarManager.disable(finalFlags);
-                });
-            }
+            mStatusBarManager.disable(flags);
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/InputConsumerController.java b/packages/SystemUI/src/com/android/systemui/pip/phone/InputConsumerController.java
index 867c15c..6733421 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/InputConsumerController.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/InputConsumerController.java
@@ -21,12 +21,15 @@
 import android.os.Looper;
 import android.os.RemoteException;
 import android.util.Log;
+import android.view.BatchedInputEventReceiver;
+import android.view.Choreographer;
 import android.view.InputChannel;
 import android.view.InputEvent;
-import android.view.InputEventReceiver;
 import android.view.IWindowManager;
 import android.view.MotionEvent;
 
+import com.android.systemui.recents.misc.Utilities;
+
 import java.io.PrintWriter;
 
 /**
@@ -52,12 +55,13 @@
     }
 
     /**
-     * Input handler used for the PiP input consumer.
+     * Input handler used for the PiP input consumer. Input events are batched and consumed with the
+     * SurfaceFlinger vsync.
      */
-    private final class PipInputEventReceiver extends InputEventReceiver {
+    private final class PipInputEventReceiver extends BatchedInputEventReceiver {
 
         public PipInputEventReceiver(InputChannel inputChannel, Looper looper) {
-            super(inputChannel, looper);
+            super(inputChannel, looper, Choreographer.getSfInstance());
         }
 
         @Override
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java
index 013b9ac..0f69f47 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java
@@ -573,13 +573,11 @@
     }
 
     private void cancelDelayedFinish() {
-        View v = getWindow().getDecorView();
-        v.removeCallbacks(mFinishRunnable);
+        mHandler.removeCallbacks(mFinishRunnable);
     }
 
     private void repostDelayedFinish(long delay) {
-        View v = getWindow().getDecorView();
-        v.removeCallbacks(mFinishRunnable);
-        v.postDelayed(mFinishRunnable, delay);
+        mHandler.removeCallbacks(mFinishRunnable);
+        mHandler.postDelayed(mFinishRunnable, delay);
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMotionHelper.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMotionHelper.java
index 9fa7ff6..b8771d7 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMotionHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMotionHelper.java
@@ -22,6 +22,7 @@
 import static com.android.systemui.Interpolators.FAST_OUT_SLOW_IN;
 import static com.android.systemui.Interpolators.LINEAR_OUT_SLOW_IN;
 
+import android.animation.AnimationHandler;
 import android.animation.Animator;
 import android.animation.Animator.AnimatorListener;
 import android.animation.AnimatorListenerAdapter;
@@ -36,14 +37,15 @@
 import android.graphics.Rect;
 import android.os.Debug;
 import android.os.Handler;
+import android.os.Message;
 import android.os.RemoteException;
 import android.util.Log;
-import android.view.Choreographer;
 import android.view.animation.Interpolator;
 
-import com.android.internal.os.BackgroundThread;
+import com.android.internal.graphics.SfVsyncFrameCallbackProvider;
+import com.android.internal.os.SomeArgs;
 import com.android.internal.policy.PipSnapAlgorithm;
-import com.android.internal.view.SurfaceFlingerVsyncChoreographer;
+import com.android.systemui.recents.misc.ForegroundThread;
 import com.android.systemui.recents.misc.SystemServicesProxy;
 import com.android.systemui.statusbar.FlingAnimationUtils;
 
@@ -52,7 +54,7 @@
 /**
  * A helper to animate and manipulate the PiP.
  */
-public class PipMotionHelper {
+public class PipMotionHelper implements Handler.Callback {
 
     private static final String TAG = "PipMotionHelper";
     private static final boolean DEBUG = false;
@@ -74,38 +76,34 @@
     // The fraction of the stack height that the user has to drag offscreen to dismiss the PiP
     private static final float DISMISS_OFFSCREEN_FRACTION = 0.3f;
 
+    private static final int MSG_RESIZE_IMMEDIATE = 1;
+    private static final int MSG_RESIZE_ANIMATE = 2;
+
     private Context mContext;
     private IActivityManager mActivityManager;
-    private SurfaceFlingerVsyncChoreographer mVsyncChoreographer;
     private Handler mHandler;
 
     private PipMenuActivityController mMenuController;
     private PipSnapAlgorithm mSnapAlgorithm;
     private FlingAnimationUtils mFlingAnimationUtils;
+    private AnimationHandler mAnimationHandler;
 
     private final Rect mBounds = new Rect();
     private final Rect mStableInsets = new Rect();
 
     private ValueAnimator mBoundsAnimator = null;
-    private ValueAnimator.AnimatorUpdateListener mUpdateBoundsListener =
-            new AnimatorUpdateListener() {
-                @Override
-                public void onAnimationUpdate(ValueAnimator animation) {
-                    mBounds.set((Rect) animation.getAnimatedValue());
-                }
-            };
 
     public PipMotionHelper(Context context, IActivityManager activityManager,
             PipMenuActivityController menuController, PipSnapAlgorithm snapAlgorithm,
             FlingAnimationUtils flingAnimationUtils) {
         mContext = context;
-        mHandler = BackgroundThread.getHandler();
+        mHandler = new Handler(ForegroundThread.get().getLooper(), this);
         mActivityManager = activityManager;
         mMenuController = menuController;
         mSnapAlgorithm = snapAlgorithm;
         mFlingAnimationUtils = flingAnimationUtils;
-        mVsyncChoreographer = new SurfaceFlingerVsyncChoreographer(mHandler, mContext.getDisplay(),
-                Choreographer.getInstance());
+        mAnimationHandler = new AnimationHandler();
+        mAnimationHandler.setProvider(new SfVsyncFrameCallbackProvider());
         onConfigurationChanged();
     }
 
@@ -252,8 +250,7 @@
         Rect toBounds = mSnapAlgorithm.findClosestSnapBounds(movementBounds, mBounds,
                 0 /* velocityX */, velocityY);
         if (!mBounds.equals(toBounds)) {
-            mBoundsAnimator = createAnimationToBounds(mBounds, toBounds, 0, FAST_OUT_SLOW_IN,
-                    mUpdateBoundsListener);
+            mBoundsAnimator = createAnimationToBounds(mBounds, toBounds, 0, FAST_OUT_SLOW_IN);
             mFlingAnimationUtils.apply(mBoundsAnimator, 0,
                     distanceBetweenRectOffsets(mBounds, toBounds),
                     velocityY);
@@ -271,7 +268,7 @@
         Rect toBounds = getClosestMinimizedBounds(mBounds, movementBounds);
         if (!mBounds.equals(toBounds)) {
             mBoundsAnimator = createAnimationToBounds(mBounds, toBounds,
-                    MINIMIZE_STACK_MAX_DURATION, LINEAR_OUT_SLOW_IN, mUpdateBoundsListener);
+                    MINIMIZE_STACK_MAX_DURATION, LINEAR_OUT_SLOW_IN);
             if (updateListener != null) {
                 mBoundsAnimator.addUpdateListener(updateListener);
             }
@@ -289,8 +286,7 @@
         Rect toBounds = mSnapAlgorithm.findClosestSnapBounds(movementBounds, mBounds,
                 velocityX, velocityY);
         if (!mBounds.equals(toBounds)) {
-            mBoundsAnimator = createAnimationToBounds(mBounds, toBounds, 0, FAST_OUT_SLOW_IN,
-                    mUpdateBoundsListener);
+            mBoundsAnimator = createAnimationToBounds(mBounds, toBounds, 0, FAST_OUT_SLOW_IN);
             mFlingAnimationUtils.apply(mBoundsAnimator, 0,
                     distanceBetweenRectOffsets(mBounds, toBounds),
                     velocity);
@@ -314,7 +310,7 @@
         Rect toBounds = mSnapAlgorithm.findClosestSnapBounds(movementBounds, mBounds);
         if (!mBounds.equals(toBounds)) {
             mBoundsAnimator = createAnimationToBounds(mBounds, toBounds, SNAP_STACK_DURATION,
-                    FAST_OUT_SLOW_IN, mUpdateBoundsListener);
+                    FAST_OUT_SLOW_IN);
             if (updateListener != null) {
                 mBoundsAnimator.addUpdateListener(updateListener);
             }
@@ -379,7 +375,7 @@
         Rect toBounds = new Rect(pipBounds);
         toBounds.offsetTo(p.x, p.y);
         mBoundsAnimator = createAnimationToBounds(mBounds, toBounds, DRAG_TO_DISMISS_STACK_DURATION,
-                FAST_OUT_LINEAR_IN, mUpdateBoundsListener);
+                FAST_OUT_LINEAR_IN);
         mBoundsAnimator.addListener(new AnimatorListenerAdapter() {
             @Override
             public void onAnimationEnd(Animator animation) {
@@ -411,16 +407,20 @@
      * Creates an animation to move the PiP to give given {@param toBounds}.
      */
     private ValueAnimator createAnimationToBounds(Rect fromBounds, Rect toBounds, int duration,
-            Interpolator interpolator, ValueAnimator.AnimatorUpdateListener updateListener) {
-        ValueAnimator anim = ValueAnimator.ofObject(RECT_EVALUATOR, fromBounds, toBounds);
+            Interpolator interpolator) {
+        ValueAnimator anim = new ValueAnimator() {
+            @Override
+            public AnimationHandler getAnimationHandler() {
+                return mAnimationHandler;
+            }
+        };
+        anim.setObjectValues(fromBounds, toBounds);
+        anim.setEvaluator(RECT_EVALUATOR);
         anim.setDuration(duration);
         anim.setInterpolator(interpolator);
         anim.addUpdateListener((ValueAnimator animation) -> {
             resizePipUnchecked((Rect) animation.getAnimatedValue());
         });
-        if (updateListener != null) {
-            anim.addUpdateListener(updateListener);
-        }
         return anim;
     }
 
@@ -433,14 +433,9 @@
                     + " callers=\n" + Debug.getCallers(5, "    "));
         }
         if (!toBounds.equals(mBounds)) {
-            mVsyncChoreographer.scheduleAtSfVsync(() -> {
-                try {
-                    mActivityManager.resizePinnedStack(toBounds, null /* tempPinnedTaskBounds */);
-                    mBounds.set(toBounds);
-                } catch (RemoteException e) {
-                    Log.e(TAG, "Could not resize pinned stack to bounds: " + toBounds, e);
-                }
-            });
+            SomeArgs args = SomeArgs.obtain();
+            args.arg1 = toBounds;
+            mHandler.sendMessage(mHandler.obtainMessage(MSG_RESIZE_IMMEDIATE, args));
         }
     }
 
@@ -453,23 +448,10 @@
                     + " duration=" + duration + " callers=\n" + Debug.getCallers(5, "    "));
         }
         if (!toBounds.equals(mBounds)) {
-            mHandler.post(() -> {
-                try {
-                    StackInfo stackInfo = mActivityManager.getStackInfo(PINNED_STACK_ID);
-                    if (stackInfo == null) {
-                        // In the case where we've already re-expanded or dismissed the PiP, then
-                        // just skip the resize
-                        return;
-                    }
-
-                    mActivityManager.resizeStack(PINNED_STACK_ID, toBounds,
-                            false /* allowResizeInDockedMode */, true /* preserveWindows */,
-                            true /* animate */, duration);
-                    mBounds.set(toBounds);
-                } catch (RemoteException e) {
-                    Log.e(TAG, "Could not animate resize pinned stack to bounds: " + toBounds, e);
-                }
-            });
+            SomeArgs args = SomeArgs.obtain();
+            args.arg1 = toBounds;
+            args.argi1 = duration;
+            mHandler.sendMessage(mHandler.obtainMessage(MSG_RESIZE_ANIMATE, args));
         }
     }
 
@@ -524,6 +506,50 @@
         return PointF.length(r1.left - r2.left, r1.top - r2.top);
     }
 
+    /**
+     * Handles messages to be processed on the background thread.
+     */
+    public boolean handleMessage(Message msg) {
+        switch (msg.what) {
+            case MSG_RESIZE_IMMEDIATE: {
+                SomeArgs args = (SomeArgs) msg.obj;
+                Rect toBounds = (Rect) args.arg1;
+                try {
+                    mActivityManager.resizePinnedStack(toBounds, null /* tempPinnedTaskBounds */);
+                    mBounds.set(toBounds);
+                } catch (RemoteException e) {
+                    Log.e(TAG, "Could not resize pinned stack to bounds: " + toBounds, e);
+                }
+                return true;
+            }
+
+            case MSG_RESIZE_ANIMATE: {
+                SomeArgs args = (SomeArgs) msg.obj;
+                Rect toBounds = (Rect) args.arg1;
+                int duration = args.argi1;
+                try {
+                    StackInfo stackInfo = mActivityManager.getStackInfo(PINNED_STACK_ID);
+                    if (stackInfo == null) {
+                        // In the case where we've already re-expanded or dismissed the PiP, then
+                        // just skip the resize
+                        return true;
+                    }
+
+                    mActivityManager.resizeStack(PINNED_STACK_ID, toBounds,
+                            false /* allowResizeInDockedMode */, true /* preserveWindows */,
+                            true /* animate */, duration);
+                    mBounds.set(toBounds);
+                } catch (RemoteException e) {
+                    Log.e(TAG, "Could not animate resize pinned stack to bounds: " + toBounds, e);
+                }
+                return true;
+            }
+
+            default:
+                return false;
+        }
+    }
+
     public void dump(PrintWriter pw, String prefix) {
         final String innerPrefix = prefix + "  ";
         pw.println(prefix + TAG);
diff --git a/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java b/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java
index 1f13830..c66b2dd 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java
@@ -154,6 +154,13 @@
     Canvas mBgProtectionCanvas;
 
     private final Handler mHandler = new H();
+    private final Runnable mGcRunnable = new Runnable() {
+        @Override
+        public void run() {
+            System.gc();
+            System.runFinalization();
+        }
+    };
 
     private final UiOffloadThread mUiOffloadThread = Dependency.get(UiOffloadThread.class);
 
@@ -365,13 +372,7 @@
      * Requests a gc() from the background thread.
      */
     public void gc() {
-        BackgroundThread.getHandler().post(new Runnable() {
-            @Override
-            public void run() {
-                System.gc();
-                System.runFinalization();
-            }
-        });
+        BackgroundThread.getHandler().post(mGcRunnable);
     }
 
     /**
@@ -799,11 +800,8 @@
         if (RecentsDebugFlags.Static.EnableMockTasks) return;
 
         // Remove the task.
-        BackgroundThread.getHandler().post(new Runnable() {
-            @Override
-            public void run() {
-                mAm.removeTask(taskId);
-            }
+        mUiOffloadThread.submit(() -> {
+            mAm.removeTask(taskId);
         });
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/recents/model/RecentsPackageMonitor.java b/packages/SystemUI/src/com/android/systemui/recents/model/RecentsPackageMonitor.java
index 1f82c16..308cece 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/model/RecentsPackageMonitor.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/model/RecentsPackageMonitor.java
@@ -20,9 +20,9 @@
 import android.os.UserHandle;
 
 import com.android.internal.content.PackageMonitor;
-import com.android.internal.os.BackgroundThread;
 import com.android.systemui.recents.events.EventBus;
 import com.android.systemui.recents.events.activity.PackagesChangedEvent;
+import com.android.systemui.recents.misc.ForegroundThread;
 
 /**
  * The package monitor listens for changes from PackageManager to update the contents of the
@@ -36,7 +36,7 @@
             // We register for events from all users, but will cross-reference them with
             // packages for the current user and any profiles they have.  Ensure that events are
             // handled in a background thread.
-            register(context, BackgroundThread.get().getLooper(), UserHandle.ALL, true);
+            register(context, ForegroundThread.get().getLooper(), UserHandle.ALL, true);
         } catch (IllegalStateException e) {
             e.printStackTrace();
         }
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/Divider.java b/packages/SystemUI/src/com/android/systemui/stackdivider/Divider.java
index 4022718..da0a435 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/Divider.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/Divider.java
@@ -25,6 +25,8 @@
 import com.android.systemui.R;
 import com.android.systemui.SystemUI;
 import com.android.systemui.recents.Recents;
+import com.android.systemui.recents.events.EventBus;
+import com.android.systemui.recents.events.ui.RecentsDrawnEvent;
 import com.android.systemui.recents.misc.SystemServicesProxy;
 
 import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
@@ -56,6 +58,7 @@
         SystemServicesProxy ssp = Recents.getSystemServices();
         ssp.registerDockedStackListener(mDockDividerVisibilityListener);
         mForcedResizableController = new ForcedResizableInfoActivityController(mContext);
+        EventBus.getDefault().register(this);
     }
 
     @Override
@@ -153,6 +156,18 @@
         mWindowManager.setTouchable((mHomeStackResizable || !mMinimized) && !mAdjustedForIme);
     }
 
+    /**
+     * Workaround for b/62528361, at the time RecentsDrawnEvent is sent, it may happen before a
+     * configuration change to the Divider, and internally, the event will be posted to the
+     * subscriber, or DividerView, which has been removed and prevented from resizing. Instead,
+     * register the event handler here and proxy the event to the current DividerView.
+     */
+    public final void onBusEvent(RecentsDrawnEvent drawnEvent) {
+        if (mView != null) {
+            mView.onRecentsDrawn();
+        }
+    }
+
     @Override
     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         pw.print("  mVisible="); pw.println(mVisible);
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
index 09f459b..45835d5 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
@@ -1224,7 +1224,7 @@
                 mSnapAlgorithm.getMiddleTarget());
     }
 
-    public final void onBusEvent(RecentsDrawnEvent drawnEvent) {
+    public void onRecentsDrawn() {
         if (mState.animateAfterRecentsDrawn) {
             mState.animateAfterRecentsDrawn = false;
             updateDockSide();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/ActivatableNotificationView.java b/packages/SystemUI/src/com/android/systemui/statusbar/ActivatableNotificationView.java
index bae6a27..5528bb9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/ActivatableNotificationView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/ActivatableNotificationView.java
@@ -214,15 +214,24 @@
         mFakeShadow = findViewById(R.id.fake_shadow);
         mShadowHidden = mFakeShadow.getVisibility() != VISIBLE;
         mBackgroundDimmed = findViewById(R.id.backgroundDimmed);
-        mBackgroundNormal.setCustomBackground(R.drawable.notification_material_bg);
-        mBackgroundDimmed.setCustomBackground(R.drawable.notification_material_bg_dim);
         mDimmedAlpha = Color.alpha(mContext.getColor(
                 R.color.notification_material_background_dimmed_color));
+        initBackground();
         updateBackground();
         updateBackgroundTint();
         updateOutlineAlpha();
     }
 
+    /**
+     * Sets the custom backgrounds on {@link #mBackgroundNormal} and {@link #mBackgroundDimmed}.
+     * This method can also be used to reload the backgrounds on both of those views, which can
+     * be useful in a configuration change.
+     */
+    protected void initBackground() {
+        mBackgroundNormal.setCustomBackground(R.drawable.notification_material_bg);
+        mBackgroundDimmed.setCustomBackground(R.drawable.notification_material_bg_dim);
+    }
+
     private final Runnable mTapTimeoutRunnable = new Runnable() {
         @Override
         public void run() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
index 6abf35f..429d5ab 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
@@ -848,6 +848,7 @@
     public void onDensityOrFontScaleChanged() {
         super.onDensityOrFontScaleChanged();
         initDimens();
+        initBackground();
         // Let's update our childrencontainer. This is intentionally not guarded with
         // mIsSummaryWithChildren since we might have had children but not anymore.
         if (mChildrenContainer != null) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ConfigurationControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ConfigurationControllerImpl.java
index 85d2d73d..a2bbb03 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ConfigurationControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ConfigurationControllerImpl.java
@@ -36,11 +36,16 @@
     private final Configuration mLastConfig = new Configuration();
     private int mDensity;
     private float mFontScale;
+    private boolean mInCarMode;
+    private int mUiMode;
 
     public ConfigurationControllerImpl(Context context) {
         Configuration currentConfig = context.getResources().getConfiguration();
         mFontScale = currentConfig.fontScale;
         mDensity = currentConfig.densityDpi;
+        mInCarMode = (currentConfig.uiMode  & Configuration.UI_MODE_TYPE_MASK)
+                == Configuration.UI_MODE_TYPE_CAR;
+        mUiMode = currentConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK;
     }
 
     @Override
@@ -55,7 +60,9 @@
         });
         final float fontScale = newConfig.fontScale;
         final int density = newConfig.densityDpi;
-        if (density != mDensity || mFontScale != fontScale) {
+        int uiMode = newConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK;
+        if (density != mDensity || fontScale != mFontScale
+                || (mInCarMode && uiMode != mUiMode)) {
             listeners.forEach(l -> {
                 if (mListeners.contains(l)) {
                     l.onDensityOrFontScaleChanged();
@@ -63,6 +70,7 @@
             });
             mDensity = density;
             mFontScale = fontScale;
+            mUiMode = uiMode;
         }
 
         if ((mLastConfig.updateFrom(newConfig) & ActivityInfo.CONFIG_ASSETS_PATHS) != 0) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
index 7d69a34..9b0307d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
@@ -94,6 +94,7 @@
     private boolean mLastBouncerDismissible;
     protected boolean mLastRemoteInputActive;
     private boolean mLastDozing;
+    private boolean mLastDeferScrimFadeOut;
 
     private OnDismissAction mAfterKeyguardGoneAction;
     private final ArrayList<Runnable> mAfterKeyguardGoneRunnables = new ArrayList<>();
@@ -371,7 +372,6 @@
             mStatusBar.setKeyguardFadingAway(startTime, delay, fadeoutDuration);
             mFingerprintUnlockController.startKeyguardFadingAway();
             mBouncer.hide(true /* destroyView */);
-            updateStates();
             if (wakeUnlockPulsing) {
                 mStatusBarWindowManager.setKeyguardFadingAway(true);
                 mStatusBar.fadeKeyguardWhilePulsing();
@@ -403,6 +403,7 @@
                     mFingerprintUnlockController.finishKeyguardFadingAway();
                 }
             }
+            updateStates();
             mStatusBarWindowManager.setKeyguardShowing(false);
             mViewMediatorCallback.keyguardGone();
         }
@@ -574,7 +575,7 @@
         mLastBouncerDismissible = bouncerDismissible;
         mLastRemoteInputActive = remoteInputActive;
         mLastDozing = mDozing;
-
+        mLastDeferScrimFadeOut = mDeferScrimFadeOut;
         mStatusBar.onKeyguardViewManagerStatesUpdated();
     }
 
@@ -582,15 +583,16 @@
      * @return Whether the navigation bar should be made visible based on the current state.
      */
     protected boolean isNavBarVisible() {
-        return !(mShowing && !mOccluded) && !mDozing || mBouncer.isShowing() || mRemoteInputActive;
+        return (!(mShowing && !mOccluded) && !mDozing || mBouncer.isShowing() || mRemoteInputActive)
+                && !mDeferScrimFadeOut;
     }
 
     /**
      * @return Whether the navigation bar was made visible based on the last known state.
      */
     protected boolean getLastNavBarVisible() {
-        return !(mLastShowing && !mLastOccluded) && !mLastDozing || mLastBouncerShowing
-                || mLastRemoteInputActive;
+        return (!(mLastShowing && !mLastOccluded) && !mLastDozing || mLastBouncerShowing
+                || mLastRemoteInputActive) && !mLastDeferScrimFadeOut;
     }
 
     public boolean shouldDismissOnMenuPressed() {
diff --git a/services/core/java/com/android/server/AppOpsService.java b/services/core/java/com/android/server/AppOpsService.java
index 1a5ec61..c8e6e2e 100644
--- a/services/core/java/com/android/server/AppOpsService.java
+++ b/services/core/java/com/android/server/AppOpsService.java
@@ -2445,6 +2445,28 @@
         }
     }
 
+    @Override
+    public boolean isOperationActive(int code, int uid, String packageName) {
+        verifyIncomingUid(uid);
+        verifyIncomingOp(code);
+        String resolvedPackageName = resolvePackageName(uid, packageName);
+        if (resolvedPackageName == null) {
+            return false;
+        }
+        synchronized (this) {
+            for (int i = mClients.size() - 1; i >= 0; i--) {
+                final ClientState client = mClients.valueAt(i);
+                if (client.mStartedOps == null) continue;
+
+                for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
+                    final Op op = client.mStartedOps.get(j);
+                    if (op.op == code && op.uid == uid) return true;
+                }
+            }
+        }
+        return false;
+    }
+
     private void removeUidsForUserLocked(int userHandle) {
         for (int i = mUidStates.size() - 1; i >= 0; --i) {
             final int uid = mUidStates.keyAt(i);
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index 35b452a..f718e80 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -90,14 +90,12 @@
 import android.util.Log;
 import android.util.Pair;
 import android.util.Slog;
-import android.util.SparseArray;
 import android.util.TimeUtils;
 import android.util.Xml;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.app.IMediaContainerService;
 import com.android.internal.os.AppFuseMount;
-import com.android.internal.os.FuseAppLoop;
 import com.android.internal.os.FuseUnavailableMountException;
 import com.android.internal.os.SomeArgs;
 import com.android.internal.os.Zygote;
@@ -143,7 +141,6 @@
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Objects;
-import java.util.concurrent.ArrayBlockingQueue;
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
@@ -3291,20 +3288,41 @@
         }
     }
 
-    @Override
-    public long getAllocatableBytes(String volumeUuid, int flags) {
-        final StorageManager storage = mContext.getSystemService(StorageManager.class);
-        final StorageStatsManager stats = mContext.getSystemService(StorageStatsManager.class);
-
-        // Apps can't defy reserved space
-        flags &= ~StorageManager.FLAG_ALLOCATE_DEFY_RESERVED;
-
-        final boolean aggressive = (flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
-        if (aggressive) {
+    private int adjustAllocateFlags(int flags, int callingUid, String callingPackage) {
+        // Require permission to allocate aggressively
+        if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
             mContext.enforceCallingOrSelfPermission(
                     android.Manifest.permission.ALLOCATE_AGGRESSIVE, TAG);
         }
 
+        // Apps normally can't directly defy reserved space
+        flags &= ~StorageManager.FLAG_ALLOCATE_DEFY_ALL_RESERVED;
+        flags &= ~StorageManager.FLAG_ALLOCATE_DEFY_HALF_RESERVED;
+
+        // However, if app is actively using the camera, then we're willing to
+        // clear up to half of the reserved cache space, since the user might be
+        // trying to capture an important memory.
+        final AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
+        final long token = Binder.clearCallingIdentity();
+        try {
+            if (appOps.isOperationActive(AppOpsManager.OP_CAMERA, callingUid, callingPackage)) {
+                Slog.d(TAG, "UID " + callingUid + " is actively using camera;"
+                        + " letting them defy reserved cached data");
+                flags |= StorageManager.FLAG_ALLOCATE_DEFY_HALF_RESERVED;
+            }
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+
+        return flags;
+    }
+
+    @Override
+    public long getAllocatableBytes(String volumeUuid, int flags, String callingPackage) {
+        flags = adjustAllocateFlags(flags, Binder.getCallingUid(), callingPackage);
+
+        final StorageManager storage = mContext.getSystemService(StorageManager.class);
+        final StorageStatsManager stats = mContext.getSystemService(StorageStatsManager.class);
         final long token = Binder.clearCallingIdentity();
         try {
             // In general, apps can allocate as much space as they want, except
@@ -3319,18 +3337,18 @@
 
             if (stats.isQuotaSupported(volumeUuid)) {
                 final long cacheTotal = stats.getCacheBytes(volumeUuid);
-                final long cacheReserved = storage.getStorageCacheBytes(path);
+                final long cacheReserved = storage.getStorageCacheBytes(path, flags);
                 final long cacheClearable = Math.max(0, cacheTotal - cacheReserved);
 
-                if (aggressive) {
-                    return Math.max(0, (usable + cacheTotal) - fullReserved);
+                if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
+                    return Math.max(0, (usable + cacheClearable) - fullReserved);
                 } else {
                     return Math.max(0, (usable + cacheClearable) - lowReserved);
                 }
             } else {
                 // When we don't have fast quota information, we ignore cached
                 // data and only consider unused bytes.
-                if (aggressive) {
+                if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
                     return Math.max(0, usable - fullReserved);
                 } else {
                     return Math.max(0, usable - lowReserved);
@@ -3344,20 +3362,16 @@
     }
 
     @Override
-    public void allocateBytes(String volumeUuid, long bytes, int flags) {
-        final StorageManager storage = mContext.getSystemService(StorageManager.class);
+    public void allocateBytes(String volumeUuid, long bytes, int flags, String callingPackage) {
+        flags = adjustAllocateFlags(flags, Binder.getCallingUid(), callingPackage);
 
-        // Apps can't defy reserved space
-        flags &= ~StorageManager.FLAG_ALLOCATE_DEFY_RESERVED;
-
-        // This method call will enforce FLAG_ALLOCATE_AGGRESSIVE permissions so
-        // we don't have to enforce them locally
-        final long allocatableBytes = getAllocatableBytes(volumeUuid, flags);
+        final long allocatableBytes = getAllocatableBytes(volumeUuid, flags, callingPackage);
         if (bytes > allocatableBytes) {
             throw new ParcelableException(new IOException("Failed to allocate " + bytes
                     + " because only " + allocatableBytes + " allocatable"));
         }
 
+        final StorageManager storage = mContext.getSystemService(StorageManager.class);
         final long token = Binder.clearCallingIdentity();
         try {
             // Free up enough disk space to satisfy both the requested allocation
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 76456f3..1402062 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -94,6 +94,7 @@
 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER;
 import static android.provider.Settings.System.FONT_SCALE;
 import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
+import static android.text.format.DateUtils.DAY_IN_MILLIS;
 import static android.view.Display.DEFAULT_DISPLAY;
 import static android.view.Display.INVALID_DISPLAY;
 import static com.android.internal.util.XmlUtils.readBooleanAttribute;
@@ -2742,7 +2743,7 @@
         File dataDir = Environment.getDataDirectory();
         File systemDir = new File(dataDir, "system");
         systemDir.mkdirs();
-        mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
+        mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler);
         mBatteryStatsService.getActiveStatistics().readLocked();
         mBatteryStatsService.scheduleWriteToDisk();
         mOnBattery = DEBUG_POWER ? true
@@ -2845,7 +2846,7 @@
         removeAllProcessGroups();
         mProcessCpuThread.start();
 
-        mBatteryStatsService.publish(mContext);
+        mBatteryStatsService.publish();
         mAppOpsService.publish(mContext);
         Slog.d("AppOps", "AppOpsService published");
         LocalServices.addService(ActivityManagerInternal.class, new LocalService());
@@ -5462,8 +5463,8 @@
         boolean useTombstonedForJavaTraces = false;
         File tracesFile;
 
-        final String tracesDir = SystemProperties.get("dalvik.vm.stack-trace-dir", "");
-        if (tracesDir.isEmpty()) {
+        final String tracesDirProp = SystemProperties.get("dalvik.vm.stack-trace-dir", "");
+        if (tracesDirProp.isEmpty()) {
             // When dalvik.vm.stack-trace-dir is not set, we are using the "old" trace
             // dumping scheme. All traces are written to a global trace file (usually
             // "/data/anr/traces.txt") so the code below must take care to unlink and recreate
@@ -5491,15 +5492,17 @@
                 return null;
             }
         } else {
+            File tracesDir = new File(tracesDirProp);
             // When dalvik.vm.stack-trace-dir is set, we use the "new" trace dumping scheme.
             // Each set of ANR traces is written to a separate file and dumpstate will process
             // all such files and add them to a captured bug report if they're recent enough.
-            //
+            maybePruneOldTraces(tracesDir);
+
             // NOTE: We should consider creating the file in native code atomically once we've
             // gotten rid of the old scheme of dumping and lot of the code that deals with paths
             // can be removed.
             try {
-                tracesFile = File.createTempFile("anr_", "", new File(tracesDir));
+                tracesFile = File.createTempFile("anr_", "", tracesDir);
                 FileUtils.setPermissions(tracesFile.getAbsolutePath(), 0600, -1, -1); // -rw-------
             } catch (IOException ioe) {
                 Slog.w(TAG, "Unable to create ANR traces file: ", ioe);
@@ -5515,6 +5518,28 @@
     }
 
     /**
+     * Prune all trace files that are more than a day old.
+     *
+     * NOTE: It might make sense to move this functionality to tombstoned eventually, along with a
+     * shift away from anr_XX and tombstone_XX to a more descriptive name. We do it here for now
+     * since it's the system_server that creates trace files for most ANRs.
+     */
+    private static void maybePruneOldTraces(File tracesDir) {
+        final long now = System.currentTimeMillis();
+        final File[] traceFiles = tracesDir.listFiles();
+
+        if (traceFiles != null) {
+            for (File file : traceFiles) {
+                if ((now - file.lastModified()) > DAY_IN_MILLIS)  {
+                    if (!file.delete()) {
+                        Slog.w(TAG, "Unable to prune stale trace file: " + file);
+                    }
+                }
+            }
+        }
+    }
+
+    /**
      * Legacy code, do not use. Existing users will be deleted.
      *
      * @deprecated
diff --git a/services/core/java/com/android/server/am/BatteryExternalStatsWorker.java b/services/core/java/com/android/server/am/BatteryExternalStatsWorker.java
new file mode 100644
index 0000000..eb84adc
--- /dev/null
+++ b/services/core/java/com/android/server/am/BatteryExternalStatsWorker.java
@@ -0,0 +1,388 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ */
+package com.android.server.am;
+
+import android.annotation.Nullable;
+import android.bluetooth.BluetoothActivityEnergyInfo;
+import android.bluetooth.BluetoothAdapter;
+import android.content.Context;
+import android.net.wifi.IWifiManager;
+import android.net.wifi.WifiActivityEnergyInfo;
+import android.os.BatteryStats;
+import android.os.Parcelable;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.SynchronousResultReceiver;
+import android.os.SystemClock;
+import android.telephony.ModemActivityInfo;
+import android.telephony.TelephonyManager;
+import android.util.IntArray;
+import android.util.Slog;
+import android.util.TimeUtils;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.internal.os.BatteryStatsImpl;
+
+import libcore.util.EmptyArray;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * A Worker that fetches data from external sources (WiFi controller, bluetooth chipset) on a
+ * dedicated thread and updates BatteryStatsImpl with that information.
+ *
+ * As much work as possible is done without holding the BatteryStatsImpl lock, and only the
+ * readily available data is pushed into BatteryStatsImpl with the lock held.
+ */
+class BatteryExternalStatsWorker implements BatteryStatsImpl.ExternalStatsSync {
+    private static final String TAG = "BatteryExternalStatsWorker";
+    private static final boolean DEBUG = false;
+
+    /**
+     * How long to wait on an individual subsystem to return its stats.
+     */
+    private static final long EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS = 2000;
+
+    // There is some accuracy error in wifi reports so allow some slop in the results.
+    private static final long MAX_WIFI_STATS_SAMPLE_ERROR_MILLIS = 750;
+
+    private final ExecutorService mExecutorService = Executors.newSingleThreadExecutor(
+            (ThreadFactory) r -> {
+                Thread t = new Thread(r, "batterystats-worker");
+                t.setPriority(Thread.NORM_PRIORITY);
+                return t;
+            });
+
+    private final Context mContext;
+    private final BatteryStatsImpl mStats;
+
+    @GuardedBy("this")
+    private int mUpdateFlags = 0;
+
+    @GuardedBy("this")
+    private Future<?> mCurrentFuture = null;
+
+    @GuardedBy("this")
+    private String mCurrentReason = null;
+
+    @GuardedBy("this")
+    private final IntArray mUidsToRemove = new IntArray();
+
+    private final Object mWorkerLock = new Object();
+
+    @GuardedBy("mWorkerLock")
+    private IWifiManager mWifiManager = null;
+
+    @GuardedBy("mWorkerLock")
+    private TelephonyManager mTelephony = null;
+
+    // WiFi keeps an accumulated total of stats, unlike Bluetooth.
+    // Keep the last WiFi stats so we can compute a delta.
+    @GuardedBy("mWorkerLock")
+    private WifiActivityEnergyInfo mLastInfo =
+            new WifiActivityEnergyInfo(0, 0, 0, new long[]{0}, 0, 0, 0);
+
+    BatteryExternalStatsWorker(Context context, BatteryStatsImpl stats) {
+        mContext = context;
+        mStats = stats;
+    }
+
+    @Override
+    public synchronized Future<?> scheduleSync(String reason, int flags) {
+        return scheduleSyncLocked(reason, flags);
+    }
+
+    @Override
+    public synchronized Future<?> scheduleCpuSyncDueToRemovedUid(int uid) {
+        mUidsToRemove.add(uid);
+        return scheduleSyncLocked("remove-uid", UPDATE_CPU);
+    }
+
+    public synchronized Future<?> scheduleWrite() {
+        scheduleSyncLocked("write", UPDATE_ALL);
+        // Since we use a single threaded executor, we can assume the next scheduled task's
+        // Future finishes after the sync.
+        return mExecutorService.submit(mWriteTask);
+    }
+
+    /**
+     * Schedules a task to run on the BatteryExternalStatsWorker thread. If scheduling more work
+     * within the task, never wait on the resulting Future. This will result in a deadlock.
+     */
+    public synchronized void scheduleRunnable(Runnable runnable) {
+        mExecutorService.submit(runnable);
+    }
+
+    public void shutdown() {
+        mExecutorService.shutdownNow();
+    }
+
+    private Future<?> scheduleSyncLocked(String reason, int flags) {
+        if (mCurrentFuture == null) {
+            mUpdateFlags = flags;
+            mCurrentReason = reason;
+            mCurrentFuture = mExecutorService.submit(mSyncTask);
+        }
+        mUpdateFlags |= flags;
+        return mCurrentFuture;
+    }
+
+    private final Runnable mSyncTask = new Runnable() {
+        @Override
+        public void run() {
+            // Capture a snapshot of the state we are meant to process.
+            final int updateFlags;
+            final String reason;
+            final int[] uidsToRemove;
+            synchronized (BatteryExternalStatsWorker.this) {
+                updateFlags = mUpdateFlags;
+                reason = mCurrentReason;
+                uidsToRemove = mUidsToRemove.size() > 0 ? mUidsToRemove.toArray() : EmptyArray.INT;
+                mUpdateFlags = 0;
+                mCurrentReason = null;
+                mUidsToRemove.clear();
+                mCurrentFuture = null;
+            }
+
+            synchronized (mWorkerLock) {
+                if (DEBUG) {
+                    Slog.d(TAG, "begin updateExternalStatsSync reason=" + reason);
+                }
+                try {
+                    updateExternalStatsLocked(reason, updateFlags);
+                } finally {
+                    if (DEBUG) {
+                        Slog.d(TAG, "end updateExternalStatsSync");
+                    }
+                }
+            }
+
+            // Clean up any UIDs if necessary.
+            synchronized (mStats) {
+                for (int uid : uidsToRemove) {
+                    mStats.removeIsolatedUidLocked(uid);
+                }
+            }
+        }
+    };
+
+    private final Runnable mWriteTask = new Runnable() {
+        @Override
+        public void run() {
+            synchronized (mStats) {
+                mStats.writeAsyncLocked();
+            }
+        }
+    };
+
+    private void updateExternalStatsLocked(final String reason, int updateFlags) {
+        // We will request data from external processes asynchronously, and wait on a timeout.
+        SynchronousResultReceiver wifiReceiver = null;
+        SynchronousResultReceiver bluetoothReceiver = null;
+        SynchronousResultReceiver modemReceiver = null;
+
+        if ((updateFlags & BatteryStatsImpl.ExternalStatsSync.UPDATE_WIFI) != 0) {
+            // We were asked to fetch WiFi data.
+            if (mWifiManager == null) {
+                mWifiManager = IWifiManager.Stub.asInterface(ServiceManager.getService(
+                        Context.WIFI_SERVICE));
+            }
+
+            if (mWifiManager != null) {
+                try {
+                    wifiReceiver = new SynchronousResultReceiver("wifi");
+                    mWifiManager.requestActivityInfo(wifiReceiver);
+                } catch (RemoteException e) {
+                    // Oh well.
+                }
+            }
+        }
+
+        if ((updateFlags & BatteryStatsImpl.ExternalStatsSync.UPDATE_BT) != 0) {
+            // We were asked to fetch Bluetooth data.
+            final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
+            if (adapter != null) {
+                bluetoothReceiver = new SynchronousResultReceiver("bluetooth");
+                adapter.requestControllerActivityEnergyInfo(bluetoothReceiver);
+            }
+        }
+
+        if ((updateFlags & BatteryStatsImpl.ExternalStatsSync.UPDATE_RADIO) != 0) {
+            // We were asked to fetch Telephony data.
+            if (mTelephony == null) {
+                mTelephony = TelephonyManager.from(mContext);
+            }
+
+            if (mTelephony != null) {
+                modemReceiver = new SynchronousResultReceiver("telephony");
+                mTelephony.requestModemActivityInfo(modemReceiver);
+            }
+        }
+
+        final WifiActivityEnergyInfo wifiInfo = awaitControllerInfo(wifiReceiver);
+        final BluetoothActivityEnergyInfo bluetoothInfo = awaitControllerInfo(bluetoothReceiver);
+        final ModemActivityInfo modemInfo = awaitControllerInfo(modemReceiver);
+
+        synchronized (mStats) {
+            mStats.addHistoryEventLocked(
+                    SystemClock.elapsedRealtime(),
+                    SystemClock.uptimeMillis(),
+                    BatteryStats.HistoryItem.EVENT_COLLECT_EXTERNAL_STATS,
+                    reason, 0);
+
+            if ((updateFlags & UPDATE_CPU) != 0) {
+                mStats.updateCpuTimeLocked(true /* updateCpuFreqData */);
+                mStats.updateKernelWakelocksLocked();
+                mStats.updateKernelMemoryBandwidthLocked();
+            }
+
+            if (bluetoothInfo != null) {
+                if (bluetoothInfo.isValid()) {
+                    mStats.updateBluetoothStateLocked(bluetoothInfo);
+                } else {
+                    Slog.e(TAG, "bluetooth info is invalid: " + bluetoothInfo);
+                }
+            }
+        }
+
+        // WiFi and Modem state are updated without the mStats lock held, because they
+        // do some network stats retrieval before internally grabbing the mStats lock.
+
+        if (wifiInfo != null) {
+            if (wifiInfo.isValid()) {
+                mStats.updateWifiState(extractDeltaLocked(wifiInfo));
+            } else {
+                Slog.e(TAG, "wifi info is invalid: " + wifiInfo);
+            }
+        }
+
+        if (modemInfo != null) {
+            if (modemInfo.isValid()) {
+                mStats.updateMobileRadioState(modemInfo);
+            } else {
+                Slog.e(TAG, "modem info is invalid: " + modemInfo);
+            }
+        }
+    }
+
+    /**
+     * Helper method to extract the Parcelable controller info from a
+     * SynchronousResultReceiver.
+     */
+    private static <T extends Parcelable> T awaitControllerInfo(
+            @Nullable SynchronousResultReceiver receiver) {
+        if (receiver == null) {
+            return null;
+        }
+
+        try {
+            final SynchronousResultReceiver.Result result =
+                    receiver.awaitResult(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS);
+            if (result.bundle != null) {
+                // This is the final destination for the Bundle.
+                result.bundle.setDefusable(true);
+
+                final T data = result.bundle.getParcelable(
+                        BatteryStats.RESULT_RECEIVER_CONTROLLER_KEY);
+                if (data != null) {
+                    return data;
+                }
+            }
+            Slog.e(TAG, "no controller energy info supplied for " + receiver.getName());
+        } catch (TimeoutException e) {
+            Slog.w(TAG, "timeout reading " + receiver.getName() + " stats");
+        }
+        return null;
+    }
+
+    private WifiActivityEnergyInfo extractDeltaLocked(WifiActivityEnergyInfo latest) {
+        final long timePeriodMs = latest.mTimestamp - mLastInfo.mTimestamp;
+        final long lastIdleMs = mLastInfo.mControllerIdleTimeMs;
+        final long lastTxMs = mLastInfo.mControllerTxTimeMs;
+        final long lastRxMs = mLastInfo.mControllerRxTimeMs;
+        final long lastEnergy = mLastInfo.mControllerEnergyUsed;
+
+        // We will modify the last info object to be the delta, and store the new
+        // WifiActivityEnergyInfo object as our last one.
+        final WifiActivityEnergyInfo delta = mLastInfo;
+        delta.mTimestamp = latest.getTimeStamp();
+        delta.mStackState = latest.getStackState();
+
+        final long txTimeMs = latest.mControllerTxTimeMs - lastTxMs;
+        final long rxTimeMs = latest.mControllerRxTimeMs - lastRxMs;
+        final long idleTimeMs = latest.mControllerIdleTimeMs - lastIdleMs;
+
+        if (txTimeMs < 0 || rxTimeMs < 0) {
+            // The stats were reset by the WiFi system (which is why our delta is negative).
+            // Returns the unaltered stats.
+            delta.mControllerEnergyUsed = latest.mControllerEnergyUsed;
+            delta.mControllerRxTimeMs = latest.mControllerRxTimeMs;
+            delta.mControllerTxTimeMs = latest.mControllerTxTimeMs;
+            delta.mControllerIdleTimeMs = latest.mControllerIdleTimeMs;
+            Slog.v(TAG, "WiFi energy data was reset, new WiFi energy data is " + delta);
+        } else {
+            final long totalActiveTimeMs = txTimeMs + rxTimeMs;
+            long maxExpectedIdleTimeMs;
+            if (totalActiveTimeMs > timePeriodMs) {
+                // Cap the max idle time at zero since the active time consumed the whole time
+                maxExpectedIdleTimeMs = 0;
+                if (totalActiveTimeMs > timePeriodMs + MAX_WIFI_STATS_SAMPLE_ERROR_MILLIS) {
+                    StringBuilder sb = new StringBuilder();
+                    sb.append("Total Active time ");
+                    TimeUtils.formatDuration(totalActiveTimeMs, sb);
+                    sb.append(" is longer than sample period ");
+                    TimeUtils.formatDuration(timePeriodMs, sb);
+                    sb.append(".\n");
+                    sb.append("Previous WiFi snapshot: ").append("idle=");
+                    TimeUtils.formatDuration(lastIdleMs, sb);
+                    sb.append(" rx=");
+                    TimeUtils.formatDuration(lastRxMs, sb);
+                    sb.append(" tx=");
+                    TimeUtils.formatDuration(lastTxMs, sb);
+                    sb.append(" e=").append(lastEnergy);
+                    sb.append("\n");
+                    sb.append("Current WiFi snapshot: ").append("idle=");
+                    TimeUtils.formatDuration(latest.mControllerIdleTimeMs, sb);
+                    sb.append(" rx=");
+                    TimeUtils.formatDuration(latest.mControllerRxTimeMs, sb);
+                    sb.append(" tx=");
+                    TimeUtils.formatDuration(latest.mControllerTxTimeMs, sb);
+                    sb.append(" e=").append(latest.mControllerEnergyUsed);
+                    Slog.wtf(TAG, sb.toString());
+                }
+            } else {
+                maxExpectedIdleTimeMs = timePeriodMs - totalActiveTimeMs;
+            }
+            // These times seem to be the most reliable.
+            delta.mControllerTxTimeMs = txTimeMs;
+            delta.mControllerRxTimeMs = rxTimeMs;
+            // WiFi calculates the idle time as a difference from the on time and the various
+            // Rx + Tx times. There seems to be some missing time there because this sometimes
+            // becomes negative. Just cap it at 0 and ensure that it is less than the expected idle
+            // time from the difference in timestamps.
+            // b/21613534
+            delta.mControllerIdleTimeMs = Math.min(maxExpectedIdleTimeMs, Math.max(0, idleTimeMs));
+            delta.mControllerEnergyUsed = Math.max(0, latest.mControllerEnergyUsed - lastEnergy);
+        }
+
+        mLastInfo = latest;
+        return delta;
+    }
+}
diff --git a/services/core/java/com/android/server/am/BatteryStatsService.java b/services/core/java/com/android/server/am/BatteryStatsService.java
index 06ab75a..cf322d7 100644
--- a/services/core/java/com/android/server/am/BatteryStatsService.java
+++ b/services/core/java/com/android/server/am/BatteryStatsService.java
@@ -16,34 +16,22 @@
 
 package com.android.server.am;
 
-import static com.android.internal.os.BatteryStatsImpl.ExternalStatsSync.UPDATE_CPU;
-import static com.android.internal.os.BatteryStatsImpl.ExternalStatsSync.UPDATE_RADIO;
-import static com.android.internal.os.BatteryStatsImpl.ExternalStatsSync.UPDATE_WIFI;
-
-import android.annotation.Nullable;
 import android.bluetooth.BluetoothActivityEnergyInfo;
-import android.bluetooth.BluetoothAdapter;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
-import android.net.wifi.IWifiManager;
 import android.net.wifi.WifiActivityEnergyInfo;
 import android.os.PowerSaveState;
 import android.os.BatteryStats;
 import android.os.Binder;
 import android.os.Handler;
 import android.os.IBinder;
-import android.os.Looper;
-import android.os.Message;
 import android.os.Parcel;
 import android.os.ParcelFileDescriptor;
 import android.os.ParcelFormatException;
-import android.os.Parcelable;
 import android.os.PowerManagerInternal;
 import android.os.Process;
-import android.os.RemoteException;
 import android.os.ServiceManager;
-import android.os.SynchronousResultReceiver;
 import android.os.SystemClock;
 import android.os.UserHandle;
 import android.os.WorkSource;
@@ -54,18 +42,14 @@
 import android.telephony.ModemActivityInfo;
 import android.telephony.SignalStrength;
 import android.telephony.TelephonyManager;
-import android.util.IntArray;
 import android.util.Slog;
-import android.util.TimeUtils;
 
-import com.android.internal.annotations.GuardedBy;
 import com.android.internal.app.IBatteryStats;
 import com.android.internal.os.BatteryStatsHelper;
 import com.android.internal.os.BatteryStatsImpl;
 import com.android.internal.os.PowerProfile;
 import com.android.internal.util.DumpUtils;
 import com.android.server.LocalServices;
-import com.android.server.ServiceThread;
 import com.android.server.power.BatterySaverPolicy.ServiceType;
 
 import java.io.File;
@@ -79,7 +63,8 @@
 import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
 import java.util.List;
-import java.util.concurrent.TimeoutException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
 
 /**
  * All information we are collecting about things that can happen that impact
@@ -91,101 +76,11 @@
     static final String TAG = "BatteryStatsService";
     static final boolean DBG = false;
 
-    /**
-     * How long to wait on an individual subsystem to return its stats.
-     */
-    private static final long EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS = 2000;
-
-    // There is some accuracy error in wifi reports so allow some slop in the results.
-    private static final long MAX_WIFI_STATS_SAMPLE_ERROR_MILLIS = 750;
-
     private static IBatteryStats sService;
 
     final BatteryStatsImpl mStats;
-    private final BatteryStatsHandler mHandler;
-    private Context mContext;
-    private IWifiManager mWifiManager;
-    private TelephonyManager mTelephony;
-
-    // Lock acquired when extracting data from external sources.
-    private final Object mExternalStatsLock = new Object();
-
-    // WiFi keeps an accumulated total of stats, unlike Bluetooth.
-    // Keep the last WiFi stats so we can compute a delta.
-    @GuardedBy("mExternalStatsLock")
-    private WifiActivityEnergyInfo mLastInfo =
-            new WifiActivityEnergyInfo(0, 0, 0, new long[]{0}, 0, 0, 0);
-
-    class BatteryStatsHandler extends Handler implements BatteryStatsImpl.ExternalStatsSync {
-        public static final int MSG_SYNC_EXTERNAL_STATS = 1;
-        public static final int MSG_WRITE_TO_DISK = 2;
-
-        private int mUpdateFlags = 0;
-        private IntArray mUidsToRemove = new IntArray();
-
-        public BatteryStatsHandler(Looper looper) {
-            super(looper);
-        }
-
-        @Override
-        public void handleMessage(Message msg) {
-            switch (msg.what) {
-                case MSG_SYNC_EXTERNAL_STATS:
-                    final int updateFlags;
-                    synchronized (this) {
-                        removeMessages(MSG_SYNC_EXTERNAL_STATS);
-                        updateFlags = mUpdateFlags;
-                        mUpdateFlags = 0;
-                    }
-                    updateExternalStatsSync((String)msg.obj, updateFlags);
-
-                    // other parts of the system could be calling into us
-                    // from mStats in order to report of changes. We must grab the mStats
-                    // lock before grabbing our own or we'll end up in a deadlock.
-                    synchronized (mStats) {
-                        synchronized (this) {
-                            final int numUidsToRemove = mUidsToRemove.size();
-                            for (int i = 0; i < numUidsToRemove; i++) {
-                                mStats.removeIsolatedUidLocked(mUidsToRemove.get(i));
-                            }
-                        }
-                        mUidsToRemove.clear();
-                    }
-                    break;
-
-                case MSG_WRITE_TO_DISK:
-                    updateExternalStatsSync("write", UPDATE_ALL);
-                    if (DBG) Slog.d(TAG, "begin writeAsyncLocked");
-                    synchronized (mStats) {
-                        mStats.writeAsyncLocked();
-                    }
-                    if (DBG) Slog.d(TAG, "end writeAsyncLocked");
-                    break;
-            }
-        }
-
-        @Override
-        public void scheduleSync(String reason, int updateFlags) {
-            synchronized (this) {
-                scheduleSyncLocked(reason, updateFlags);
-            }
-        }
-
-        @Override
-        public void scheduleCpuSyncDueToRemovedUid(int uid) {
-            synchronized (this) {
-                scheduleSyncLocked("remove-uid", UPDATE_CPU);
-                mUidsToRemove.add(uid);
-            }
-        }
-
-        private void scheduleSyncLocked(String reason, int updateFlags) {
-            if (mUpdateFlags == 0) {
-                sendMessage(Message.obtain(this, MSG_SYNC_EXTERNAL_STATS, reason));
-            }
-            mUpdateFlags |= updateFlags;
-        }
-    }
+    private final Context mContext;
+    private final BatteryExternalStatsWorker mWorker;
 
     private native int getPlatformLowPowerStats(ByteBuffer outBuffer);
     private native int getSubsystemLowPowerStats(ByteBuffer outBuffer);
@@ -242,29 +137,34 @@
         }
     }
 
-    BatteryStatsService(File systemDir, Handler handler) {
-        // Our handler here will be accessing the disk, use a different thread than
-        // what the ActivityManagerService gave us (no I/O on that one!).
-        final ServiceThread thread = new ServiceThread("batterystats-sync",
-                Process.THREAD_PRIORITY_DEFAULT, true);
-        thread.start();
-        mHandler = new BatteryStatsHandler(thread.getLooper());
-
+    BatteryStatsService(Context context, File systemDir, Handler handler) {
         // BatteryStatsImpl expects the ActivityManagerService handler, so pass that one through.
-        mStats = new BatteryStatsImpl(systemDir, handler, mHandler, this);
+        mContext = context;
+        mStats = new BatteryStatsImpl(systemDir, handler, this);
+        mWorker = new BatteryExternalStatsWorker(context, mStats);
+        mStats.setExternalStatsSyncLocked(mWorker);
+        mStats.setRadioScanningTimeoutLocked(mContext.getResources().getInteger(
+                com.android.internal.R.integer.config_radioScanningTimeout) * 1000L);
+        mStats.setPowerProfileLocked(new PowerProfile(context));
     }
 
-    public void publish(Context context) {
-        mContext = context;
-        synchronized (mStats) {
-            mStats.setRadioScanningTimeoutLocked(mContext.getResources().getInteger(
-                    com.android.internal.R.integer.config_radioScanningTimeout)
-                    * 1000L);
-            mStats.setPowerProfileLocked(new PowerProfile(context));
-        }
+    public void publish() {
         ServiceManager.addService(BatteryStats.SERVICE_NAME, asBinder());
     }
 
+    private static void awaitUninterruptibly(Future<?> future) {
+        while (true) {
+            try {
+                future.get();
+                return;
+            } catch (ExecutionException e) {
+                return;
+            } catch (InterruptedException e) {
+                // Keep looping
+            }
+        }
+    }
+
     /**
      * At the time when the constructor runs, the power manager has not yet been
      * initialized.  So we initialize the low power observer later.
@@ -283,13 +183,14 @@
     public void shutdown() {
         Slog.w("BatteryStats", "Writing battery stats before shutdown...");
 
-        updateExternalStatsSync("shutdown", BatteryStatsImpl.ExternalStatsSync.UPDATE_ALL);
+        awaitUninterruptibly(mWorker.scheduleSync("shutdown", BatteryExternalStatsWorker.UPDATE_ALL));
+
         synchronized (mStats) {
             mStats.shutdownLocked();
         }
 
         // Shutdown the thread we made.
-        mHandler.getLooper().quit();
+        mWorker.shutdown();
     }
     
     public static IBatteryStats getService() {
@@ -327,7 +228,7 @@
      * object to update with the latest info, then write to disk.
      */
     public void scheduleWriteToDisk() {
-        mHandler.sendEmptyMessage(BatteryStatsHandler.MSG_WRITE_TO_DISK);
+        mWorker.scheduleWrite();
     }
 
     // These are for direct use by the activity manager...
@@ -391,7 +292,7 @@
         //Slog.i("foo", "SENDING BATTERY INFO:");
         //mStats.dumpLocked(new LogPrinter(Log.INFO, "foo", Log.LOG_ID_SYSTEM));
         Parcel out = Parcel.obtain();
-        updateExternalStatsSync("get-stats", BatteryStatsImpl.ExternalStatsSync.UPDATE_ALL);
+        awaitUninterruptibly(mWorker.scheduleSync("get-stats", BatteryExternalStatsWorker.UPDATE_ALL));
         synchronized (mStats) {
             mStats.writeToParcel(out, 0);
         }
@@ -406,7 +307,7 @@
         //Slog.i("foo", "SENDING BATTERY INFO:");
         //mStats.dumpLocked(new LogPrinter(Log.INFO, "foo", Log.LOG_ID_SYSTEM));
         Parcel out = Parcel.obtain();
-        updateExternalStatsSync("get-stats", BatteryStatsImpl.ExternalStatsSync.UPDATE_ALL);
+        awaitUninterruptibly(mWorker.scheduleSync("get-stats", BatteryExternalStatsWorker.UPDATE_ALL));
         synchronized (mStats) {
             mStats.writeToParcel(out, 0);
         }
@@ -635,13 +536,13 @@
 
     public void noteMobileRadioPowerState(int powerState, long timestampNs, int uid) {
         enforceCallingPermission();
-        boolean update;
+        final boolean update;
         synchronized (mStats) {
             update = mStats.noteMobileRadioPowerStateLocked(powerState, timestampNs, uid);
         }
 
         if (update) {
-            mHandler.scheduleSync("modem-data", UPDATE_RADIO);
+            mWorker.scheduleSync("modem-data", BatteryExternalStatsWorker.UPDATE_RADIO);
         }
     }
 
@@ -792,8 +693,7 @@
                 final String type = (powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH ||
                         powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM) ? "active"
                         : "inactive";
-                mHandler.scheduleSync("wifi-data: " + type,
-                        UPDATE_WIFI);
+                mWorker.scheduleSync("wifi-data: " + type, BatteryExternalStatsWorker.UPDATE_WIFI);
             }
             mStats.noteWifiRadioPowerState(powerState, tsNanos, uid);
         }
@@ -951,7 +851,11 @@
     @Override
     public void noteNetworkStatsEnabled() {
         enforceCallingPermission();
-        mHandler.scheduleSync("network-stats-enabled", UPDATE_RADIO | UPDATE_WIFI);
+        // During device boot, qtaguid isn't enabled until after the inital
+        // loading of battery stats. Now that they're enabled, take our initial
+        // snapshot for future delta calculation.
+        mWorker.scheduleSync("network-stats-enabled",
+                BatteryExternalStatsWorker.UPDATE_RADIO | BatteryExternalStatsWorker.UPDATE_WIFI);
     }
 
     @Override
@@ -1028,9 +932,7 @@
             return;
         }
 
-        synchronized (mStats) {
-            mStats.updateBluetoothStateLocked(info);
-        }
+        mStats.updateBluetoothStateLocked(info);
     }
 
     @Override
@@ -1057,28 +959,29 @@
 
         // BatteryService calls us here and we may update external state. It would be wrong
         // to block such a low level service like BatteryService on external stats like WiFi.
-        mHandler.post(new Runnable() {
-            @Override
-            public void run() {
-                synchronized (mStats) {
-                    final boolean onBattery = plugType == BatteryStatsImpl.BATTERY_PLUGGED_NONE;
-                    if (mStats.isOnBattery() == onBattery) {
-                        // The battery state has not changed, so we don't need to sync external
-                        // stats immediately.
-                        mStats.setBatteryStateLocked(status, health, plugType, level, temp, volt,
-                                chargeUAh, chargeFullUAh);
-                        return;
-                    }
+        mWorker.scheduleRunnable(() -> {
+            synchronized (mStats) {
+                final boolean onBattery = plugType == BatteryStatsImpl.BATTERY_PLUGGED_NONE;
+                if (mStats.isOnBattery() == onBattery) {
+                    // The battery state has not changed, so we don't need to sync external
+                    // stats immediately.
+                    mStats.setBatteryStateLocked(status, health, plugType, level, temp, volt,
+                            chargeUAh, chargeFullUAh);
+                    return;
                 }
+            }
 
-                // Sync external stats first as the battery has changed states. If we don't sync
-                // immediately here, we may not collect the relevant data later.
-                updateExternalStatsSync("battery-state", BatteryStatsImpl.ExternalStatsSync.UPDATE_ALL);
+            // Sync external stats first as the battery has changed states. If we don't sync
+            // before changing the state, we may not collect the relevant data later.
+            // Order here is guaranteed since we're scheduling from the same thread and we are
+            // using a single threaded executor.
+            mWorker.scheduleSync("battery-state", BatteryExternalStatsWorker.UPDATE_ALL);
+            mWorker.scheduleRunnable(() -> {
                 synchronized (mStats) {
                     mStats.setBatteryStateLocked(status, health, plugType, level, temp, volt,
                             chargeUAh, chargeFullUAh);
                 }
-            }
+            });
         });
     }
     
@@ -1260,9 +1163,10 @@
                         pw.println("Battery stats reset.");
                         noOutput = true;
                     }
-                    updateExternalStatsSync("dump", BatteryStatsImpl.ExternalStatsSync.UPDATE_ALL);
+                    mWorker.scheduleSync("dump", BatteryExternalStatsWorker.UPDATE_ALL);
                 } else if ("--write".equals(arg)) {
-                    updateExternalStatsSync("dump", BatteryStatsImpl.ExternalStatsSync.UPDATE_ALL);
+                    awaitUninterruptibly(mWorker.scheduleSync("dump",
+                            BatteryExternalStatsWorker.UPDATE_ALL));
                     synchronized (mStats) {
                         mStats.writeSyncLocked();
                         pw.println("Battery stats written.");
@@ -1326,7 +1230,7 @@
                 flags |= BatteryStats.DUMP_DEVICE_WIFI_ONLY;
             }
             // Fetch data from external sources and update the BatteryStatsImpl object with them.
-            updateExternalStatsSync("dump", BatteryStatsImpl.ExternalStatsSync.UPDATE_ALL);
+            awaitUninterruptibly(mWorker.scheduleSync("dump", BatteryExternalStatsWorker.UPDATE_ALL));
         } finally {
             Binder.restoreCallingIdentity(ident);
         }
@@ -1391,229 +1295,6 @@
         }
     }
 
-    private WifiActivityEnergyInfo extractDelta(WifiActivityEnergyInfo latest) {
-        final long timePeriodMs = latest.mTimestamp - mLastInfo.mTimestamp;
-        final long lastIdleMs = mLastInfo.mControllerIdleTimeMs;
-        final long lastTxMs = mLastInfo.mControllerTxTimeMs;
-        final long lastRxMs = mLastInfo.mControllerRxTimeMs;
-        final long lastEnergy = mLastInfo.mControllerEnergyUsed;
-
-        // We will modify the last info object to be the delta, and store the new
-        // WifiActivityEnergyInfo object as our last one.
-        final WifiActivityEnergyInfo delta = mLastInfo;
-        delta.mTimestamp = latest.getTimeStamp();
-        delta.mStackState = latest.getStackState();
-
-        final long txTimeMs = latest.mControllerTxTimeMs - lastTxMs;
-        final long rxTimeMs = latest.mControllerRxTimeMs - lastRxMs;
-        final long idleTimeMs = latest.mControllerIdleTimeMs - lastIdleMs;
-
-        if (txTimeMs < 0 || rxTimeMs < 0) {
-            // The stats were reset by the WiFi system (which is why our delta is negative).
-            // Returns the unaltered stats.
-            delta.mControllerEnergyUsed = latest.mControllerEnergyUsed;
-            delta.mControllerRxTimeMs = latest.mControllerRxTimeMs;
-            delta.mControllerTxTimeMs = latest.mControllerTxTimeMs;
-            delta.mControllerIdleTimeMs = latest.mControllerIdleTimeMs;
-            Slog.v(TAG, "WiFi energy data was reset, new WiFi energy data is " + delta);
-        } else {
-            final long totalActiveTimeMs = txTimeMs + rxTimeMs;
-            long maxExpectedIdleTimeMs;
-            if (totalActiveTimeMs > timePeriodMs) {
-                // Cap the max idle time at zero since the active time consumed the whole time
-                maxExpectedIdleTimeMs = 0;
-                if (totalActiveTimeMs > timePeriodMs + MAX_WIFI_STATS_SAMPLE_ERROR_MILLIS) {
-                    StringBuilder sb = new StringBuilder();
-                    sb.append("Total Active time ");
-                    TimeUtils.formatDuration(totalActiveTimeMs, sb);
-                    sb.append(" is longer than sample period ");
-                    TimeUtils.formatDuration(timePeriodMs, sb);
-                    sb.append(".\n");
-                    sb.append("Previous WiFi snapshot: ").append("idle=");
-                    TimeUtils.formatDuration(lastIdleMs, sb);
-                    sb.append(" rx=");
-                    TimeUtils.formatDuration(lastRxMs, sb);
-                    sb.append(" tx=");
-                    TimeUtils.formatDuration(lastTxMs, sb);
-                    sb.append(" e=").append(lastEnergy);
-                    sb.append("\n");
-                    sb.append("Current WiFi snapshot: ").append("idle=");
-                    TimeUtils.formatDuration(latest.mControllerIdleTimeMs, sb);
-                    sb.append(" rx=");
-                    TimeUtils.formatDuration(latest.mControllerRxTimeMs, sb);
-                    sb.append(" tx=");
-                    TimeUtils.formatDuration(latest.mControllerTxTimeMs, sb);
-                    sb.append(" e=").append(latest.mControllerEnergyUsed);
-                    Slog.wtf(TAG, sb.toString());
-                }
-            } else {
-                maxExpectedIdleTimeMs = timePeriodMs - totalActiveTimeMs;
-            }
-            // These times seem to be the most reliable.
-            delta.mControllerTxTimeMs = txTimeMs;
-            delta.mControllerRxTimeMs = rxTimeMs;
-            // WiFi calculates the idle time as a difference from the on time and the various
-            // Rx + Tx times. There seems to be some missing time there because this sometimes
-            // becomes negative. Just cap it at 0 and ensure that it is less than the expected idle
-            // time from the difference in timestamps.
-            // b/21613534
-            delta.mControllerIdleTimeMs = Math.min(maxExpectedIdleTimeMs, Math.max(0, idleTimeMs));
-            delta.mControllerEnergyUsed = Math.max(0, latest.mControllerEnergyUsed - lastEnergy);
-        }
-
-        mLastInfo = latest;
-        return delta;
-    }
-
-    /**
-     * Helper method to extract the Parcelable controller info from a
-     * SynchronousResultReceiver.
-     */
-    private static <T extends Parcelable> T awaitControllerInfo(
-            @Nullable SynchronousResultReceiver receiver) throws TimeoutException {
-        if (receiver == null) {
-            return null;
-        }
-
-        final SynchronousResultReceiver.Result result =
-                receiver.awaitResult(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS);
-        if (result.bundle != null) {
-            // This is the final destination for the Bundle.
-            result.bundle.setDefusable(true);
-
-            final T data = result.bundle.getParcelable(BatteryStats.RESULT_RECEIVER_CONTROLLER_KEY);
-            if (data != null) {
-                return data;
-            }
-        }
-        Slog.e(TAG, "no controller energy info supplied");
-        return null;
-    }
-
-    /**
-     * Fetches data from external sources (WiFi controller, bluetooth chipset) and updates
-     * batterystats with that information.
-     *
-     * We first grab a lock specific to this method, then once all the data has been collected,
-     * we grab the mStats lock and update the data.
-     *
-     * @param reason The reason why this collection was requested. Useful for debugging.
-     * @param updateFlags Which external stats to update. Can be a combination of
-     *                    {@link BatteryStatsImpl.ExternalStatsSync#UPDATE_CPU},
-     *                    {@link BatteryStatsImpl.ExternalStatsSync#UPDATE_RADIO},
-     *                    {@link BatteryStatsImpl.ExternalStatsSync#UPDATE_WIFI},
-     *                    and {@link BatteryStatsImpl.ExternalStatsSync#UPDATE_BT}.
-     */
-    void updateExternalStatsSync(final String reason, int updateFlags) {
-        SynchronousResultReceiver wifiReceiver = null;
-        SynchronousResultReceiver bluetoothReceiver = null;
-        SynchronousResultReceiver modemReceiver = null;
-
-        if (DBG) Slog.d(TAG, "begin updateExternalStatsSync reason=" + reason);
-        synchronized (mExternalStatsLock) {
-            if (mContext == null) {
-                // Don't do any work yet.
-                if (DBG) Slog.d(TAG, "end updateExternalStatsSync");
-                return;
-            }
-
-            if ((updateFlags & UPDATE_WIFI) != 0) {
-                if (mWifiManager == null) {
-                    mWifiManager = IWifiManager.Stub.asInterface(
-                            ServiceManager.getService(Context.WIFI_SERVICE));
-                }
-
-                if (mWifiManager != null) {
-                    try {
-                        wifiReceiver = new SynchronousResultReceiver();
-                        mWifiManager.requestActivityInfo(wifiReceiver);
-                    } catch (RemoteException e) {
-                        // Oh well.
-                    }
-                }
-            }
-
-            if ((updateFlags & BatteryStatsImpl.ExternalStatsSync.UPDATE_BT) != 0) {
-                final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-                if (adapter != null) {
-                    bluetoothReceiver = new SynchronousResultReceiver();
-                    adapter.requestControllerActivityEnergyInfo(bluetoothReceiver);
-                }
-            }
-
-            if ((updateFlags & BatteryStatsImpl.ExternalStatsSync.UPDATE_RADIO) != 0) {
-                if (mTelephony == null) {
-                    mTelephony = TelephonyManager.from(mContext);
-                }
-
-                if (mTelephony != null) {
-                    modemReceiver = new SynchronousResultReceiver();
-                    mTelephony.requestModemActivityInfo(modemReceiver);
-                }
-            }
-
-            WifiActivityEnergyInfo wifiInfo = null;
-            BluetoothActivityEnergyInfo bluetoothInfo = null;
-            ModemActivityInfo modemInfo = null;
-            try {
-                wifiInfo = awaitControllerInfo(wifiReceiver);
-            } catch (TimeoutException e) {
-                Slog.w(TAG, "Timeout reading wifi stats");
-            }
-
-            try {
-                bluetoothInfo = awaitControllerInfo(bluetoothReceiver);
-            } catch (TimeoutException e) {
-                Slog.w(TAG, "Timeout reading bt stats");
-            }
-
-            try {
-                modemInfo = awaitControllerInfo(modemReceiver);
-            } catch (TimeoutException e) {
-                Slog.w(TAG, "Timeout reading modem stats");
-            }
-
-            synchronized (mStats) {
-                mStats.addHistoryEventLocked(
-                        SystemClock.elapsedRealtime(),
-                        SystemClock.uptimeMillis(),
-                        BatteryStats.HistoryItem.EVENT_COLLECT_EXTERNAL_STATS,
-                        reason, 0);
-
-                if ((updateFlags & UPDATE_CPU) != 0) {
-                    mStats.updateCpuTimeLocked(true /* updateCpuFreqData */);
-                }
-                mStats.updateKernelWakelocksLocked();
-                mStats.updateKernelMemoryBandwidthLocked();
-
-                if (bluetoothInfo != null) {
-                    if (bluetoothInfo.isValid()) {
-                        mStats.updateBluetoothStateLocked(bluetoothInfo);
-                    } else {
-                        Slog.e(TAG, "bluetooth info is invalid: " + bluetoothInfo);
-                    }
-                }
-            }
-
-            if (wifiInfo != null) {
-                if (wifiInfo.isValid()) {
-                    mStats.updateWifiState(extractDelta(wifiInfo));
-                } else {
-                    Slog.e(TAG, "wifi info is invalid: " + wifiInfo);
-                }
-            }
-
-            if (modemInfo != null) {
-                if (modemInfo.isValid()) {
-                    mStats.updateMobileRadioState(modemInfo);
-                } else {
-                    Slog.e(TAG, "modem info is invalid: " + modemInfo);
-                }
-            }
-        }
-        if (DBG) Slog.d(TAG, "end updateExternalStatsSync");
-    }
-
     /**
      * Gets a snapshot of the system health for a particular uid.
      */
@@ -1625,8 +1306,8 @@
         }
         long ident = Binder.clearCallingIdentity();
         try {
-            updateExternalStatsSync("get-health-stats-for-uid",
-                    BatteryStatsImpl.ExternalStatsSync.UPDATE_ALL);
+            awaitUninterruptibly(mWorker.scheduleSync("get-health-stats-for-uids",
+                    BatteryExternalStatsWorker.UPDATE_ALL));
             synchronized (mStats) {
                 return getHealthStatsForUidLocked(requestUid);
             }
@@ -1650,8 +1331,8 @@
         long ident = Binder.clearCallingIdentity();
         int i=-1;
         try {
-            updateExternalStatsSync("get-health-stats-for-uids",
-                    BatteryStatsImpl.ExternalStatsSync.UPDATE_ALL);
+            awaitUninterruptibly(mWorker.scheduleSync("get-health-stats-for-uids",
+                    BatteryExternalStatsWorker.UPDATE_ALL));
             synchronized (mStats) {
                 final int N = requestUids.length;
                 final HealthStatsParceler[] results = new HealthStatsParceler[N];
diff --git a/services/core/java/com/android/server/connectivity/Tethering.java b/services/core/java/com/android/server/connectivity/Tethering.java
index a452404..e1ae0fd 100644
--- a/services/core/java/com/android/server/connectivity/Tethering.java
+++ b/services/core/java/com/android/server/connectivity/Tethering.java
@@ -832,30 +832,41 @@
                     case WifiManager.WIFI_AP_STATE_DISABLING:
                     case WifiManager.WIFI_AP_STATE_FAILED:
                     default:
-                        disableWifiIpServingLocked(curState);
+                        disableWifiIpServingLocked(ifname, curState);
                         break;
                 }
             }
         }
     }
 
-    // TODO: Pass in the interface name and, if non-empty, only turn down IP
-    // serving on that one interface.
-    private void disableWifiIpServingLocked(int apState) {
-        if (DBG) Log.d(TAG, "Canceling WiFi tethering request - AP_STATE=" + apState);
+    private void disableWifiIpServingLocked(String ifname, int apState) {
+        mLog.log("Canceling WiFi tethering request - AP_STATE=" + apState);
 
-        // Tell appropriate interface state machines that they should tear
-        // themselves down.
+        // Regardless of whether we requested this transition, the AP has gone
+        // down.  Don't try to tether again unless we're requested to do so.
+        // TODO: Remove this altogether, once Wi-Fi reliably gives us an
+        // interface name with every broadcast.
+        mWifiTetherRequested = false;
+
+        if (!TextUtils.isEmpty(ifname)) {
+            final TetherState ts = mTetherStates.get(ifname);
+            if (ts != null) {
+                ts.stateMachine.unwanted();
+                return;
+            }
+        }
+
         for (int i = 0; i < mTetherStates.size(); i++) {
             TetherInterfaceStateMachine tism = mTetherStates.valueAt(i).stateMachine;
             if (tism.interfaceType() == ConnectivityManager.TETHERING_WIFI) {
-                tism.sendMessage(TetherInterfaceStateMachine.CMD_TETHER_UNREQUESTED);
-                break;  // There should be at most one of these.
+                tism.unwanted();
+                return;
             }
         }
-        // Regardless of whether we requested this transition, the AP has gone
-        // down.  Don't try to tether again unless we're requested to do so.
-        mWifiTetherRequested = false;
+
+        mLog.log("Error disabling Wi-Fi IP serving; " +
+                (TextUtils.isEmpty(ifname) ? "no interface name specified"
+                                           : "specified interface: " + ifname));
     }
 
     private void enableWifiIpServingLocked(String ifname, int wifiIpMode) {
@@ -1248,9 +1259,9 @@
             protected void chooseUpstreamType(boolean tryCell) {
                 updateConfiguration(); // TODO - remove?
 
-                final int upstreamType = mUpstreamNetworkMonitor.selectPreferredUpstreamType(
+                final NetworkState ns = mUpstreamNetworkMonitor.selectPreferredUpstreamType(
                         mConfig.preferredUpstreamIfaceTypes);
-                if (upstreamType == ConnectivityManager.TYPE_NONE) {
+                if (ns == null) {
                     if (tryCell) {
                         mUpstreamNetworkMonitor.registerMobileNetworkRequest();
                         // We think mobile should be coming up; don't set a retry.
@@ -1258,40 +1269,30 @@
                         sendMessageDelayed(CMD_RETRY_UPSTREAM, UPSTREAM_SETTLE_TIME_MS);
                     }
                 }
-                setUpstreamByType(upstreamType);
+                setUpstreamByType(ns);
             }
 
-            protected void setUpstreamByType(int upType) {
-                final ConnectivityManager cm = getConnectivityManager();
-                Network network = null;
+            protected void setUpstreamByType(NetworkState ns) {
                 String iface = null;
-                if (upType != ConnectivityManager.TYPE_NONE) {
-                    LinkProperties linkProperties = cm.getLinkProperties(upType);
-                    if (linkProperties != null) {
-                        // Find the interface with the default IPv4 route. It may be the
-                        // interface described by linkProperties, or one of the interfaces
-                        // stacked on top of it.
-                        Log.i(TAG, "Finding IPv4 upstream interface on: " + linkProperties);
-                        RouteInfo ipv4Default = RouteInfo.selectBestRoute(
-                            linkProperties.getAllRoutes(), Inet4Address.ANY);
-                        if (ipv4Default != null) {
-                            iface = ipv4Default.getInterface();
-                            Log.i(TAG, "Found interface " + ipv4Default.getInterface());
-                        } else {
-                            Log.i(TAG, "No IPv4 upstream interface, giving up.");
-                        }
-                    }
-
-                    if (iface != null) {
-                        network = cm.getNetworkForType(upType);
-                        if (network == null) {
-                            Log.e(TAG, "No Network for upstream type " + upType + "!");
-                        }
-                        setDnsForwarders(network, linkProperties);
+                if (ns != null && ns.linkProperties != null) {
+                    // Find the interface with the default IPv4 route. It may be the
+                    // interface described by linkProperties, or one of the interfaces
+                    // stacked on top of it.
+                    Log.i(TAG, "Finding IPv4 upstream interface on: " + ns.linkProperties);
+                    RouteInfo ipv4Default = RouteInfo.selectBestRoute(
+                        ns.linkProperties.getAllRoutes(), Inet4Address.ANY);
+                    if (ipv4Default != null) {
+                        iface = ipv4Default.getInterface();
+                        Log.i(TAG, "Found interface " + ipv4Default.getInterface());
+                    } else {
+                        Log.i(TAG, "No IPv4 upstream interface, giving up.");
                     }
                 }
+
+                if (iface != null) {
+                    setDnsForwarders(ns.network, ns.linkProperties);
+                }
                 notifyTetheredOfNewUpstreamIface(iface);
-                NetworkState ns = mUpstreamNetworkMonitor.lookup(network);
                 if (ns != null && pertainsToCurrentUpstream(ns)) {
                     // If we already have NetworkState for this network examine
                     // it immediately, because there likely will be no second
diff --git a/services/core/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachine.java b/services/core/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachine.java
index 82b9ca0..9eb342c 100644
--- a/services/core/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachine.java
+++ b/services/core/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachine.java
@@ -132,6 +132,8 @@
 
     public void stop() { sendMessage(CMD_INTERFACE_DOWN); }
 
+    public void unwanted() { sendMessage(CMD_TETHER_UNREQUESTED); }
+
     // configured when we start tethering and unconfig'd on error or conclusion
     private boolean configureIfaceIp(boolean enabled) {
         if (VDBG) Log.d(TAG, "configureIfaceIp(" + enabled + ")");
diff --git a/services/core/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java b/services/core/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java
index b2d5051..9ebfaf7 100644
--- a/services/core/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java
+++ b/services/core/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java
@@ -174,10 +174,6 @@
         mMobileNetworkCallback = null;
     }
 
-    public NetworkState lookup(Network network) {
-        return (network != null) ? mNetworkMap.get(network) : null;
-    }
-
     // So many TODOs here, but chief among them is: make this functionality an
     // integral part of this class such that whenever a higher priority network
     // becomes available and useful we (a) file a request to keep it up as
@@ -185,7 +181,7 @@
     // passing LinkProperties up to Tethering).
     //
     // Next TODO: return NetworkState instead of just the type.
-    public int selectPreferredUpstreamType(Iterable<Integer> preferredTypes) {
+    public NetworkState selectPreferredUpstreamType(Iterable<Integer> preferredTypes) {
         final TypeStatePair typeStatePair = findFirstAvailableUpstreamByType(
                 mNetworkMap.values(), preferredTypes);
 
@@ -210,7 +206,7 @@
                 break;
         }
 
-        return typeStatePair.type;
+        return typeStatePair.ns;
     }
 
     private void handleAvailable(int callbackType, Network network) {
diff --git a/services/core/java/com/android/server/pm/InstantAppResolver.java b/services/core/java/com/android/server/pm/InstantAppResolver.java
index 34cc6e3..d0d306c 100644
--- a/services/core/java/com/android/server/pm/InstantAppResolver.java
+++ b/services/core/java/com/android/server/pm/InstantAppResolver.java
@@ -121,8 +121,11 @@
                 resolutionStatus = RESOLUTION_FAILURE;
             }
         }
-        logMetrics(ACTION_INSTANT_APP_RESOLUTION_PHASE_ONE, startTime, token,
-                resolutionStatus);
+        // Only log successful instant application resolution
+        if (resolutionStatus == RESOLUTION_SUCCESS) {
+            logMetrics(ACTION_INSTANT_APP_RESOLUTION_PHASE_ONE, startTime, token,
+                    resolutionStatus);
+        }
         if (DEBUG_EPHEMERAL && resolveInfo == null) {
             if (resolutionStatus == RESOLUTION_BIND_TIMEOUT) {
                 Log.d(TAG, "[" + token + "] Phase1; bind timed out");
diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java
index 6f07973..bf64f64 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerService.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerService.java
@@ -81,8 +81,10 @@
 import android.util.Slog;
 import android.util.SparseArray;
 import android.util.SparseBooleanArray;
+import android.util.SparseIntArray;
 import android.util.Xml;
 
+import java.io.CharArrayWriter;
 import libcore.io.IoUtils;
 
 import com.android.internal.R;
@@ -195,7 +197,10 @@
 
     /** Historical sessions kept around for debugging purposes */
     @GuardedBy("mSessions")
-    private final SparseArray<PackageInstallerSession> mHistoricalSessions = new SparseArray<>();
+    private final List<String> mHistoricalSessions = new ArrayList<>();
+
+    @GuardedBy("mSessions")
+    private final SparseIntArray mHistoricalSessionsByInstaller = new SparseIntArray();
 
     /** Sessions allocated to legacy users */
     @GuardedBy("mSessions")
@@ -371,7 +376,7 @@
                             // Since this is early during boot we don't send
                             // any observer events about the session, but we
                             // keep details around for dumpsys.
-                            mHistoricalSessions.put(session.sessionId, session);
+                            addHistoricalSessionLocked(session);
                         }
                         mAllocatedSessions.put(session.sessionId, true);
                     }
@@ -386,6 +391,18 @@
         }
     }
 
+    private void addHistoricalSessionLocked(PackageInstallerSession session) {
+        CharArrayWriter writer = new CharArrayWriter();
+        IndentingPrintWriter pw = new IndentingPrintWriter(writer, "    ");
+        session.dump(pw);
+        mHistoricalSessions.add(writer.toString());
+
+        // Increment the number of sessions by this installerUid.
+        mHistoricalSessionsByInstaller.put(
+                session.installerUid,
+                mHistoricalSessionsByInstaller.get(session.installerUid) + 1);
+    }
+
     private PackageInstallerSession readSessionLocked(XmlPullParser in) throws IOException,
             XmlPullParserException {
         final int sessionId = readIntAttribute(in, ATTR_SESSION_ID);
@@ -676,7 +693,7 @@
                 throw new IllegalStateException(
                         "Too many active sessions for UID " + callingUid);
             }
-            final int historicalCount = getSessionCount(mHistoricalSessions, callingUid);
+            final int historicalCount = mHistoricalSessionsByInstaller.get(callingUid);
             if (historicalCount >= MAX_HISTORICAL_SESSIONS) {
                 throw new IllegalStateException(
                         "Too many historical sessions for UID " + callingUid);
@@ -1228,8 +1245,7 @@
             pw.increaseIndent();
             N = mHistoricalSessions.size();
             for (int i = 0; i < N; i++) {
-                final PackageInstallerSession session = mHistoricalSessions.valueAt(i);
-                session.dump(pw);
+                pw.print(mHistoricalSessions.get(i));
                 pw.println();
             }
             pw.println();
@@ -1264,7 +1280,7 @@
                 public void run() {
                     synchronized (mSessions) {
                         mSessions.remove(session.sessionId);
-                        mHistoricalSessions.put(session.sessionId, session);
+                        addHistoricalSessionLocked(session);
 
                         final File appIconFile = buildAppIconFile(session.sessionId);
                         if (appIconFile.exists()) {
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 48b9c7d..9c04801 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -4258,10 +4258,7 @@
                     volumeUuid);
             final boolean aggressive = (storageFlags
                     & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
-            final boolean defyReserved = (storageFlags
-                    & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
-            final long reservedBytes = (aggressive || defyReserved) ? 0
-                    : storage.getStorageCacheBytes(file);
+            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
 
             // 1. Pre-flight to determine if we have any chance to succeed
             // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 4bc3725..126e3ec 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -3052,13 +3052,18 @@
         if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
               + ": transit=" + transit);
         if (win == mStatusBar) {
-            boolean isKeyguard = (win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
+            final boolean isKeyguard = (win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
+            final boolean expanded = win.getAttrs().height == MATCH_PARENT
+                    && win.getAttrs().width == MATCH_PARENT;
+            if (isKeyguard || expanded) {
+                return -1;
+            }
             if (transit == TRANSIT_EXIT
                     || transit == TRANSIT_HIDE) {
-                return isKeyguard ? -1 : R.anim.dock_top_exit;
+                return R.anim.dock_top_exit;
             } else if (transit == TRANSIT_ENTER
                     || transit == TRANSIT_SHOW) {
-                return isKeyguard ? -1 : R.anim.dock_top_enter;
+                return R.anim.dock_top_enter;
             }
         } else if (win == mNavigationBar) {
             if (win.getAttrs().windowAnimations != 0) {
@@ -6793,7 +6798,9 @@
 
     @Override
     public boolean isScreenOn() {
-        return mScreenOnFully;
+        synchronized (mLock) {
+            return mScreenOnEarly;
+        }
     }
 
     /** {@inheritDoc} */
diff --git a/services/core/java/com/android/server/power/ShutdownThread.java b/services/core/java/com/android/server/power/ShutdownThread.java
index 864e83e..28ffc94 100644
--- a/services/core/java/com/android/server/power/ShutdownThread.java
+++ b/services/core/java/com/android/server/power/ShutdownThread.java
@@ -256,7 +256,7 @@
         ProgressDialog pd = new ProgressDialog(context);
 
         // Path 1: Reboot to recovery for update
-        //   Condition: mReason == REBOOT_RECOVERY_UPDATE
+        //   Condition: mReason startswith REBOOT_RECOVERY_UPDATE
         //
         //  Path 1a: uncrypt needed
         //   Condition: if /cache/recovery/uncrypt_file exists but
@@ -276,7 +276,9 @@
         // Path 3: Regular reboot / shutdown
         //   Condition: Otherwise
         //   UI: spinning circle only (no progress bar)
-        if (PowerManager.REBOOT_RECOVERY_UPDATE.equals(mReason)) {
+
+        // mReason could be "recovery-update" or "recovery-update,quiescent".
+        if (mReason != null && mReason.startsWith(PowerManager.REBOOT_RECOVERY_UPDATE)) {
             // We need the progress bar if uncrypt will be invoked during the
             // reboot, which might be time-consuming.
             mRebootHasProgressBar = RecoverySystem.UNCRYPT_PACKAGE_FILE.exists()
@@ -295,7 +297,7 @@
                 pd.setMessage(context.getText(
                             com.android.internal.R.string.reboot_to_update_reboot));
             }
-        } else if (PowerManager.REBOOT_RECOVERY.equals(mReason)) {
+        } else if (mReason != null && mReason.equals(PowerManager.REBOOT_RECOVERY)) {
             // Factory reset path. Set the dialog message accordingly.
             pd.setTitle(context.getText(com.android.internal.R.string.reboot_to_reset_title));
             pd.setMessage(context.getText(
diff --git a/services/core/java/com/android/server/radio/TunerCallback.java b/services/core/java/com/android/server/radio/TunerCallback.java
index fcc874b..d10f2c6 100644
--- a/services/core/java/com/android/server/radio/TunerCallback.java
+++ b/services/core/java/com/android/server/radio/TunerCallback.java
@@ -20,6 +20,7 @@
 import android.hardware.radio.ITuner;
 import android.hardware.radio.ITunerCallback;
 import android.hardware.radio.RadioManager;
+import android.hardware.radio.RadioMetadata;
 import android.hardware.radio.RadioTuner;
 import android.os.IBinder;
 import android.os.RemoteException;
@@ -57,6 +58,18 @@
         nativeDetach(mNativeContext);
     }
 
+    private interface RunnableThrowingRemoteException {
+        void run() throws RemoteException;
+    }
+
+    private void dispatch(RunnableThrowingRemoteException func) {
+        try {
+            func.run();
+        } catch (RemoteException e) {
+            Slog.e(TAG, "client died", e);
+        }
+    }
+
     // called from native side
     private void handleHwFailure() {
         onError(RadioTuner.ERROR_HARDWARE_FAILURE);
@@ -65,29 +78,52 @@
 
     @Override
     public void onError(int status) {
-        try {
-            mClientCallback.onError(status);
-        } catch (RemoteException e) {
-            Slog.e(TAG, "client died", e);
-        }
+        dispatch(() -> mClientCallback.onError(status));
     }
 
     @Override
     public void onConfigurationChanged(RadioManager.BandConfig config) {
-        try {
-            mClientCallback.onConfigurationChanged(config);
-        } catch (RemoteException e) {
-            Slog.e(TAG, "client died", e);
-        }
+        dispatch(() -> mClientCallback.onConfigurationChanged(config));
     }
 
     @Override
     public void onProgramInfoChanged(RadioManager.ProgramInfo info) {
-        try {
-            mClientCallback.onProgramInfoChanged(info);
-        } catch (RemoteException e) {
-            Slog.e(TAG, "client died", e);
-        }
+        dispatch(() -> mClientCallback.onProgramInfoChanged(info));
+    }
+
+    @Override
+    public void onMetadataChanged(RadioMetadata metadata) {
+        dispatch(() -> mClientCallback.onMetadataChanged(metadata));
+    }
+
+    @Override
+    public void onTrafficAnnouncement(boolean active) {
+        dispatch(() -> mClientCallback.onTrafficAnnouncement(active));
+    }
+
+    @Override
+    public void onEmergencyAnnouncement(boolean active) {
+        dispatch(() -> mClientCallback.onEmergencyAnnouncement(active));
+    }
+
+    @Override
+    public void onAntennaState(boolean connected) {
+        dispatch(() -> mClientCallback.onAntennaState(connected));
+    }
+
+    @Override
+    public void onBackgroundScanAvailabilityChange(boolean isAvailable) {
+        dispatch(() -> mClientCallback.onBackgroundScanAvailabilityChange(isAvailable));
+    }
+
+    @Override
+    public void onBackgroundScanComplete() {
+        dispatch(() -> mClientCallback.onBackgroundScanComplete());
+    }
+
+    @Override
+    public void onProgramListChanged() {
+        dispatch(() -> mClientCallback.onProgramListChanged());
     }
 
     @Override
diff --git a/services/core/java/com/android/server/wm/BoundsAnimationController.java b/services/core/java/com/android/server/wm/BoundsAnimationController.java
index 410efcd..7d13889 100644
--- a/services/core/java/com/android/server/wm/BoundsAnimationController.java
+++ b/services/core/java/com/android/server/wm/BoundsAnimationController.java
@@ -20,6 +20,8 @@
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
+import android.animation.AnimationHandler;
+import android.animation.AnimationHandler.AnimationFrameCallbackProvider;
 import android.animation.Animator;
 import android.animation.ValueAnimator;
 import android.annotation.IntDef;
@@ -30,11 +32,13 @@
 import android.os.Debug;
 import android.util.ArrayMap;
 import android.util.Slog;
+import android.view.Choreographer;
 import android.view.animation.AnimationUtils;
 import android.view.animation.Interpolator;
 import android.view.WindowManagerInternal;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.graphics.SfVsyncFrameCallbackProvider;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -49,7 +53,7 @@
  *
  * The object that is resized needs to implement {@link BoundsAnimationTarget} interface.
  *
- * NOTE: All calls to methods in this class should be done on the UI thread
+ * NOTE: All calls to methods in this class should be done on the Animation thread
  */
 public class BoundsAnimationController {
     private static final boolean DEBUG_LOCAL = false;
@@ -111,20 +115,24 @@
     private final AppTransitionNotifier mAppTransitionNotifier = new AppTransitionNotifier();
     private final Interpolator mFastOutSlowInInterpolator;
     private boolean mFinishAnimationAfterTransition = false;
+    private final AnimationHandler mAnimationHandler;
 
     private static final int WAIT_FOR_DRAW_TIMEOUT_MS = 3000;
 
-    BoundsAnimationController(Context context, AppTransition transition, Handler handler) {
+    BoundsAnimationController(Context context, AppTransition transition, Handler handler,
+            AnimationHandler animationHandler) {
         mHandler = handler;
         mAppTransition = transition;
         mAppTransition.registerListenerLocked(mAppTransitionNotifier);
         mFastOutSlowInInterpolator = AnimationUtils.loadInterpolator(context,
                 com.android.internal.R.interpolator.fast_out_slow_in);
+        mAnimationHandler = animationHandler;
     }
 
     @VisibleForTesting
     final class BoundsAnimator extends ValueAnimator
             implements ValueAnimator.AnimatorUpdateListener, ValueAnimator.AnimatorListener {
+
         private final BoundsAnimationTarget mTarget;
         private final Rect mFrom = new Rect();
         private final Rect mTo = new Rect();
@@ -350,6 +358,14 @@
         public void onAnimationRepeat(Animator animation) {
             // Do nothing
         }
+
+        @Override
+        public AnimationHandler getAnimationHandler() {
+            if (mAnimationHandler != null) {
+                return mAnimationHandler;
+            }
+            return super.getAnimationHandler();
+        }
     }
 
     public void animateBounds(final BoundsAnimationTarget target, Rect from, Rect to,
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 336a7f3..12d6d4d 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -103,6 +103,7 @@
 
 import android.Manifest;
 import android.Manifest.permission;
+import android.animation.AnimationHandler;
 import android.animation.ValueAnimator;
 import android.annotation.IntDef;
 import android.annotation.NonNull;
@@ -212,6 +213,7 @@
 
 import com.android.internal.R;
 import com.android.internal.app.IAssistScreenshotReceiver;
+import com.android.internal.graphics.SfVsyncFrameCallbackProvider;
 import com.android.internal.os.IResultReceiver;
 import com.android.internal.policy.IKeyguardDismissCallback;
 import com.android.internal.policy.IShortcutService;
@@ -1049,8 +1051,10 @@
         mAppTransition = new AppTransition(context, this);
         mAppTransition.registerListenerLocked(mActivityManagerAppTransitionNotifier);
 
+        final AnimationHandler animationHandler = new AnimationHandler();
+        animationHandler.setProvider(new SfVsyncFrameCallbackProvider());
         mBoundsAnimationController = new BoundsAnimationController(context, mAppTransition,
-                UiThread.getHandler());
+                AnimationThread.getHandler(), animationHandler);
 
         mActivityManager = ActivityManager.getService();
         mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
diff --git a/services/core/jni/com_android_server_radio_Tuner_TunerCallback.cpp b/services/core/jni/com_android_server_radio_Tuner_TunerCallback.cpp
index 1290c7a..a3cfeff 100644
--- a/services/core/jni/com_android_server_radio_Tuner_TunerCallback.cpp
+++ b/services/core/jni/com_android_server_radio_Tuner_TunerCallback.cpp
@@ -53,6 +53,13 @@
         jmethodID onError;
         jmethodID onConfigurationChanged;
         jmethodID onProgramInfoChanged;
+        jmethodID onMetadataChanged;
+        jmethodID onTrafficAnnouncement;
+        jmethodID onEmergencyAnnouncement;
+        jmethodID onAntennaState;
+        jmethodID onBackgroundScanAvailabilityChange;
+        jmethodID onBackgroundScanComplete;
+        jmethodID onProgramListChanged;
     } TunerCallback;
 } gjni;
 
@@ -63,6 +70,8 @@
     CANCELLED = 2,
     SCAN_TIMEOUT = 3,
     CONFIG = 4,
+    BACKGROUND_SCAN_UNAVAILABLE = 5,
+    BACKGROUND_SCAN_FAILED = 6,
 };
 
 static Mutex gContextMutex;
@@ -191,48 +200,93 @@
 }
 
 Return<void> NativeCallback::afSwitch(const V1_0::ProgramInfo& info) {
-    ALOGE("Not implemented: afSwitch");
-    return Return<void>();
+    ALOGV("afSwitch()");
+    return tuneComplete(Result::OK, info);
 }
 
 Return<void> NativeCallback::afSwitch_1_1(const V1_1::ProgramInfo& info) {
-    ALOGE("Not implemented: afSwitch_1_1");
-    return Return<void>();
+    ALOGV("afSwitch_1_1()");
+    return tuneComplete_1_1(Result::OK, info);
 }
 
 Return<void> NativeCallback::antennaStateChange(bool connected) {
-    ALOGE("Not implemented: antennaStateChange");
+    ALOGV("antennaStateChange(%d)", connected);
+
+    mCallbackThread.enqueue([this, connected](JNIEnv *env) {
+        env->CallVoidMethod(mJCallback, gjni.TunerCallback.onAntennaState, connected);
+    });
+
     return Return<void>();
 }
 
 Return<void> NativeCallback::trafficAnnouncement(bool active) {
-    ALOGE("Not implemented: trafficAnnouncement");
+    ALOGV("trafficAnnouncement(%d)", active);
+
+    mCallbackThread.enqueue([this, active](JNIEnv *env) {
+        env->CallVoidMethod(mJCallback, gjni.TunerCallback.onTrafficAnnouncement, active);
+    });
+
     return Return<void>();
 }
 
 Return<void> NativeCallback::emergencyAnnouncement(bool active) {
-    ALOGE("Not implemented: emergencyAnnouncement");
+    ALOGV("emergencyAnnouncement(%d)", active);
+
+    mCallbackThread.enqueue([this, active](JNIEnv *env) {
+        env->CallVoidMethod(mJCallback, gjni.TunerCallback.onEmergencyAnnouncement, active);
+    });
+
     return Return<void>();
 }
 
 Return<void> NativeCallback::newMetadata(uint32_t channel, uint32_t subChannel,
         const hidl_vec<MetaData>& metadata) {
-    ALOGE("Not implemented: newMetadata");
+    // channel and subChannel are not used
+    ALOGV("newMetadata(%d, %d)", channel, subChannel);
+
+    mCallbackThread.enqueue([this, metadata](JNIEnv *env) {
+        auto jMetadata = convert::MetadataFromHal(env, metadata);
+        if (jMetadata == nullptr) return;
+        env->CallVoidMethod(mJCallback, gjni.TunerCallback.onMetadataChanged, jMetadata.get());
+    });
+
     return Return<void>();
 }
 
 Return<void> NativeCallback::backgroundScanAvailable(bool isAvailable) {
-    ALOGE("Not implemented: backgroundScanAvailable");
+    ALOGV("backgroundScanAvailable(%d)", isAvailable);
+
+    mCallbackThread.enqueue([this, isAvailable](JNIEnv *env) {
+        env->CallVoidMethod(mJCallback,
+                gjni.TunerCallback.onBackgroundScanAvailabilityChange, isAvailable);
+    });
+
     return Return<void>();
 }
 
 Return<void> NativeCallback::backgroundScanComplete(ProgramListResult result) {
-    ALOGE("Not implemented: backgroundScanComplete");
+    ALOGV("backgroundScanComplete(%d)", result);
+
+    mCallbackThread.enqueue([this, result](JNIEnv *env) {
+        if (result == ProgramListResult::OK) {
+            env->CallVoidMethod(mJCallback, gjni.TunerCallback.onBackgroundScanComplete);
+        } else {
+            auto cause = (result == ProgramListResult::UNAVAILABLE) ?
+                    TunerError::BACKGROUND_SCAN_UNAVAILABLE : TunerError::BACKGROUND_SCAN_FAILED;
+            env->CallVoidMethod(mJCallback, gjni.TunerCallback.onError, cause);
+        }
+    });
+
     return Return<void>();
 }
 
 Return<void> NativeCallback::programListChanged() {
-    ALOGE("Not implemented: programListChanged");
+    ALOGV("programListChanged()");
+
+    mCallbackThread.enqueue([this](JNIEnv *env) {
+        env->CallVoidMethod(mJCallback, gjni.TunerCallback.onProgramListChanged);
+    });
+
     return Return<void>();
 }
 
@@ -310,6 +364,20 @@
             "onConfigurationChanged", "(Landroid/hardware/radio/RadioManager$BandConfig;)V");
     gjni.TunerCallback.onProgramInfoChanged = GetMethodIDOrDie(env, tunerCbClass,
             "onProgramInfoChanged", "(Landroid/hardware/radio/RadioManager$ProgramInfo;)V");
+    gjni.TunerCallback.onMetadataChanged = GetMethodIDOrDie(env, tunerCbClass,
+            "onMetadataChanged", "(Landroid/hardware/radio/RadioMetadata;)V");
+    gjni.TunerCallback.onTrafficAnnouncement = GetMethodIDOrDie(env, tunerCbClass,
+            "onTrafficAnnouncement", "(Z)V");
+    gjni.TunerCallback.onEmergencyAnnouncement = GetMethodIDOrDie(env, tunerCbClass,
+            "onEmergencyAnnouncement", "(Z)V");
+    gjni.TunerCallback.onAntennaState = GetMethodIDOrDie(env, tunerCbClass,
+            "onAntennaState", "(Z)V");
+    gjni.TunerCallback.onBackgroundScanAvailabilityChange = GetMethodIDOrDie(env, tunerCbClass,
+            "onBackgroundScanAvailabilityChange", "(Z)V");
+    gjni.TunerCallback.onBackgroundScanComplete = GetMethodIDOrDie(env, tunerCbClass,
+            "onBackgroundScanComplete", "()V");
+    gjni.TunerCallback.onProgramListChanged = GetMethodIDOrDie(env, tunerCbClass,
+            "onProgramListChanged", "()V");
 
     auto res = jniRegisterNativeMethods(env, "com/android/server/radio/TunerCallback",
             gTunerCallbackMethods, NELEM(gTunerCallbackMethods));
diff --git a/services/core/jni/com_android_server_radio_convert.cpp b/services/core/jni/com_android_server_radio_convert.cpp
index 19abf8a..3f24a36 100644
--- a/services/core/jni/com_android_server_radio_convert.cpp
+++ b/services/core/jni/com_android_server_radio_convert.cpp
@@ -254,7 +254,7 @@
     return directionDown ? Direction::DOWN : Direction::UP;
 }
 
-static JavaRef<jobject> MetadataFromHal(JNIEnv *env, const hidl_vec<V1_0::MetaData> metadata) {
+JavaRef<jobject> MetadataFromHal(JNIEnv *env, const hidl_vec<V1_0::MetaData> &metadata) {
     ALOGV("MetadataFromHal()");
     EnvWrapper wrap(env);
 
diff --git a/services/core/jni/com_android_server_radio_convert.h b/services/core/jni/com_android_server_radio_convert.h
index 6f6774b..f2e7f92 100644
--- a/services/core/jni/com_android_server_radio_convert.h
+++ b/services/core/jni/com_android_server_radio_convert.h
@@ -39,6 +39,7 @@
 
 V1_0::Direction DirectionToHal(bool directionDown);
 
+JavaRef<jobject> MetadataFromHal(JNIEnv *env, const hardware::hidl_vec<V1_0::MetaData> &metadata);
 JavaRef<jobject> ProgramInfoFromHal(JNIEnv *env, const V1_0::ProgramInfo &info);
 JavaRef<jobject> ProgramInfoFromHal(JNIEnv *env, const V1_1::ProgramInfo &info);
 
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 9a756b1..d5e1993 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -441,7 +441,7 @@
             // If '/cache/recovery/block.map' hasn't been created, stop the
             // reboot which will fail for sure, and get a chance to capture a
             // bugreport when that's still feasible. (Bug: 26444951)
-            if (PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
+            if (reason != null && reason.startsWith(PowerManager.REBOOT_RECOVERY_UPDATE)) {
                 File packageFile = new File(UNCRYPT_PACKAGE_FILE);
                 if (packageFile.exists()) {
                     String filename = null;
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/MockStorageManager.java b/services/tests/servicestests/src/com/android/server/locksettings/MockStorageManager.java
index 89e18b4..40e114b 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/MockStorageManager.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/MockStorageManager.java
@@ -491,12 +491,12 @@
     }
 
     @Override
-    public long getAllocatableBytes(String path, int flags) {
+    public long getAllocatableBytes(String path, int flags, String callingPackage) {
         throw new UnsupportedOperationException();
     }
 
     @Override
-    public void allocateBytes(String path, long bytes, int flags) {
+    public void allocateBytes(String path, long bytes, int flags, String callingPackage) {
         throw new UnsupportedOperationException();
     }
 
@@ -504,5 +504,4 @@
     public void secdiscard(String path) throws RemoteException {
         throw new UnsupportedOperationException();
     }
-
 }
diff --git a/services/tests/servicestests/src/com/android/server/wm/BoundsAnimationControllerTests.java b/services/tests/servicestests/src/com/android/server/wm/BoundsAnimationControllerTests.java
index ee09f4b..9d32496 100644
--- a/services/tests/servicestests/src/com/android/server/wm/BoundsAnimationControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/BoundsAnimationControllerTests.java
@@ -395,7 +395,7 @@
         mMockAppTransition = new MockAppTransition(context);
         mMockAnimator = new MockValueAnimator();
         mTarget = new TestBoundsAnimationTarget();
-        mController = new BoundsAnimationController(context, mMockAppTransition, handler);
+        mController = new BoundsAnimationController(context, mMockAppTransition, handler, null);
         mDriver = new BoundsAnimationDriver(mController, mTarget);
     }
 
diff --git a/services/usage/java/com/android/server/usage/StorageStatsService.java b/services/usage/java/com/android/server/usage/StorageStatsService.java
index 562443f..9f4fb85 100644
--- a/services/usage/java/com/android/server/usage/StorageStatsService.java
+++ b/services/usage/java/com/android/server/usage/StorageStatsService.java
@@ -197,7 +197,7 @@
             // logic should be kept in sync with getAllocatableBytes().
             if (isQuotaSupported(volumeUuid, callingPackage)) {
                 final long cacheTotal = getCacheBytes(volumeUuid, callingPackage);
-                final long cacheReserved = mStorage.getStorageCacheBytes(path);
+                final long cacheReserved = mStorage.getStorageCacheBytes(path, 0);
                 final long cacheClearable = Math.max(0, cacheTotal - cacheReserved);
 
                 return path.getUsableSpace() + cacheClearable;
diff --git a/telephony/java/android/telephony/ims/stub/ImsCallSessionListenerImplBase.java b/telephony/java/android/telephony/ims/stub/ImsCallSessionListenerImplBase.java
index 12228a1..6c18935 100644
--- a/telephony/java/android/telephony/ims/stub/ImsCallSessionListenerImplBase.java
+++ b/telephony/java/android/telephony/ims/stub/ImsCallSessionListenerImplBase.java
@@ -196,6 +196,23 @@
     }
 
     /**
+     * Notifies of a case where a {@link com.android.ims.internal.ImsCallSession} may potentially
+     * handover from one radio technology to another.
+     * @param session
+     * @param srcAccessTech The source radio access technology; one of the access technology
+     *                      constants defined in {@link android.telephony.ServiceState}.  For
+     *                      example {@link android.telephony.ServiceState#RIL_RADIO_TECHNOLOGY_LTE}.
+     * @param targetAccessTech The target radio access technology; one of the access technology
+     *                      constants defined in {@link android.telephony.ServiceState}.  For
+     *                      example {@link android.telephony.ServiceState#RIL_RADIO_TECHNOLOGY_LTE}.
+     */
+    @Override
+    public void callSessionMayHandover(IImsCallSession session, int srcAccessTech,
+            int targetAccessTech) {
+        // no-op
+    }
+
+    /**
      * Notifies of handover information for this call
      */
     @Override
diff --git a/telephony/java/com/android/ims/internal/IImsCallSessionListener.aidl b/telephony/java/com/android/ims/internal/IImsCallSessionListener.aidl
index ad59c1d8..831ab12 100644
--- a/telephony/java/com/android/ims/internal/IImsCallSessionListener.aidl
+++ b/telephony/java/com/android/ims/internal/IImsCallSessionListener.aidl
@@ -106,6 +106,8 @@
             in int srcAccessTech, in int targetAccessTech, in ImsReasonInfo reasonInfo);
     void callSessionHandoverFailed(in IImsCallSession session,
             in int srcAccessTech, in int targetAccessTech, in ImsReasonInfo reasonInfo);
+    void callSessionMayHandover(in IImsCallSession session,
+            in int srcAccessTech, in int targetAccessTech);
 
     /**
      * Notifies the TTY mode change by remote party.
diff --git a/telephony/java/com/android/ims/internal/ImsCallSession.java b/telephony/java/com/android/ims/internal/ImsCallSession.java
index f20f7c8..1736b80 100644
--- a/telephony/java/com/android/ims/internal/ImsCallSession.java
+++ b/telephony/java/com/android/ims/internal/ImsCallSession.java
@@ -345,6 +345,24 @@
         }
 
         /**
+         * Called when an {@link ImsCallSession} may handover from one radio technology to another.
+         * For example, the session may handover from WIFI to LTE if conditions are right.
+         * <p>
+         * If handover is attempted,
+         * {@link #callSessionHandover(ImsCallSession, int, int, ImsReasonInfo)} or
+         * {@link #callSessionHandoverFailed(ImsCallSession, int, int, ImsReasonInfo)} will be
+         * called to indicate the success or failure of the handover.
+         *
+         * @param session IMS session object
+         * @param srcAccessTech original access technology
+         * @param targetAccessTech new access technology
+         */
+        public void callSessionMayHandover(ImsCallSession session, int srcAccessTech,
+                int targetAccessTech) {
+            // no-op
+        }
+
+        /**
          * Called when session access technology changes
          *
          * @param session IMS session object
@@ -1281,6 +1299,28 @@
         }
 
         /**
+         * Notifies of a case where a {@link com.android.ims.internal.ImsCallSession} may
+         * potentially handover from one radio technology to another.
+         * @param session
+         * @param srcAccessTech The source radio access technology; one of the access technology
+         *                      constants defined in {@link android.telephony.ServiceState}.  For
+         *                      example
+         *                      {@link android.telephony.ServiceState#RIL_RADIO_TECHNOLOGY_LTE}.
+         * @param targetAccessTech The target radio access technology; one of the access technology
+         *                      constants defined in {@link android.telephony.ServiceState}.  For
+         *                      example
+         *                      {@link android.telephony.ServiceState#RIL_RADIO_TECHNOLOGY_LTE}.
+         */
+        @Override
+        public void callSessionMayHandover(IImsCallSession session,
+                int srcAccessTech, int targetAccessTech) {
+            if (mListener != null) {
+                mListener.callSessionMayHandover(ImsCallSession.this, srcAccessTech,
+                        targetAccessTech);
+            }
+        }
+
+        /**
          * Notifies of handover information for this call
          */
         @Override
diff --git a/tests/net/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitorTest.java b/tests/net/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitorTest.java
index fb6066e..fb5c577 100644
--- a/tests/net/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitorTest.java
+++ b/tests/net/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitorTest.java
@@ -47,6 +47,7 @@
 import android.net.Network;
 import android.net.NetworkCapabilities;
 import android.net.NetworkRequest;
+import android.net.NetworkState;
 import android.net.util.SharedLog;
 
 import android.support.test.filters.SmallTest;
@@ -253,31 +254,32 @@
 
         mUNM.start();
         // There are no networks, so there is nothing to select.
-        assertEquals(TYPE_NONE, mUNM.selectPreferredUpstreamType(preferredTypes));
+        assertSatisfiesLegacyType(TYPE_NONE, mUNM.selectPreferredUpstreamType(preferredTypes));
 
         final TestNetworkAgent wifiAgent = new TestNetworkAgent(mCM, TRANSPORT_WIFI);
         wifiAgent.fakeConnect();
         // WiFi is up, we should prefer it.
-        assertEquals(TYPE_WIFI, mUNM.selectPreferredUpstreamType(preferredTypes));
+        assertSatisfiesLegacyType(TYPE_WIFI, mUNM.selectPreferredUpstreamType(preferredTypes));
         wifiAgent.fakeDisconnect();
         // There are no networks, so there is nothing to select.
-        assertEquals(TYPE_NONE, mUNM.selectPreferredUpstreamType(preferredTypes));
+        assertSatisfiesLegacyType(TYPE_NONE, mUNM.selectPreferredUpstreamType(preferredTypes));
 
         final TestNetworkAgent cellAgent = new TestNetworkAgent(mCM, TRANSPORT_CELLULAR);
         cellAgent.fakeConnect();
-        assertEquals(TYPE_NONE, mUNM.selectPreferredUpstreamType(preferredTypes));
+        assertSatisfiesLegacyType(TYPE_NONE, mUNM.selectPreferredUpstreamType(preferredTypes));
 
         preferredTypes.add(TYPE_MOBILE_DUN);
         // This is coupled with preferred types in TetheringConfiguration.
         mUNM.updateMobileRequiresDun(true);
         // DUN is available, but only use regular cell: no upstream selected.
-        assertEquals(TYPE_NONE, mUNM.selectPreferredUpstreamType(preferredTypes));
+        assertSatisfiesLegacyType(TYPE_NONE, mUNM.selectPreferredUpstreamType(preferredTypes));
         preferredTypes.remove(TYPE_MOBILE_DUN);
         // No WiFi, but our preferred flavour of cell is up.
         preferredTypes.add(TYPE_MOBILE_HIPRI);
         // This is coupled with preferred types in TetheringConfiguration.
         mUNM.updateMobileRequiresDun(false);
-        assertEquals(TYPE_MOBILE_HIPRI, mUNM.selectPreferredUpstreamType(preferredTypes));
+        assertSatisfiesLegacyType(TYPE_MOBILE_HIPRI,
+                mUNM.selectPreferredUpstreamType(preferredTypes));
         // Check to see we filed an explicit request.
         assertEquals(1, mCM.requested.size());
         NetworkRequest netReq = (NetworkRequest) mCM.requested.values().toArray()[0];
@@ -286,25 +288,26 @@
 
         wifiAgent.fakeConnect();
         // WiFi is up, and we should prefer it over cell.
-        assertEquals(TYPE_WIFI, mUNM.selectPreferredUpstreamType(preferredTypes));
+        assertSatisfiesLegacyType(TYPE_WIFI, mUNM.selectPreferredUpstreamType(preferredTypes));
         assertEquals(0, mCM.requested.size());
 
         preferredTypes.remove(TYPE_MOBILE_HIPRI);
         preferredTypes.add(TYPE_MOBILE_DUN);
         // This is coupled with preferred types in TetheringConfiguration.
         mUNM.updateMobileRequiresDun(true);
-        assertEquals(TYPE_WIFI, mUNM.selectPreferredUpstreamType(preferredTypes));
+        assertSatisfiesLegacyType(TYPE_WIFI, mUNM.selectPreferredUpstreamType(preferredTypes));
 
         final TestNetworkAgent dunAgent = new TestNetworkAgent(mCM, TRANSPORT_CELLULAR);
         dunAgent.networkCapabilities.addCapability(NET_CAPABILITY_DUN);
         dunAgent.fakeConnect();
 
         // WiFi is still preferred.
-        assertEquals(TYPE_WIFI, mUNM.selectPreferredUpstreamType(preferredTypes));
+        assertSatisfiesLegacyType(TYPE_WIFI, mUNM.selectPreferredUpstreamType(preferredTypes));
 
         // WiFi goes down, cell and DUN are still up but only DUN is preferred.
         wifiAgent.fakeDisconnect();
-        assertEquals(TYPE_MOBILE_DUN, mUNM.selectPreferredUpstreamType(preferredTypes));
+        assertSatisfiesLegacyType(TYPE_MOBILE_DUN,
+                mUNM.selectPreferredUpstreamType(preferredTypes));
         // Check to see we filed an explicit request.
         assertEquals(1, mCM.requested.size());
         netReq = (NetworkRequest) mCM.requested.values().toArray()[0];
@@ -312,6 +315,16 @@
         assertTrue(netReq.networkCapabilities.hasCapability(NET_CAPABILITY_DUN));
     }
 
+    private void assertSatisfiesLegacyType(int legacyType, NetworkState ns) {
+        if (legacyType == TYPE_NONE) {
+            assertTrue(ns == null);
+            return;
+        }
+
+        final NetworkCapabilities nc = ConnectivityManager.networkCapabilitiesForType(legacyType);
+        assertTrue(nc.satisfiedByNetworkCapabilities(ns.networkCapabilities));
+    }
+
     private void assertUpstreamTypeRequested(int upstreamType) throws Exception {
         assertEquals(1, mCM.requested.size());
         assertEquals(1, mCM.legacyTypeMap.size());
diff --git a/tools/aapt2/ResourceParser_test.cpp b/tools/aapt2/ResourceParser_test.cpp
index c6382b1..e189144 100644
--- a/tools/aapt2/ResourceParser_test.cpp
+++ b/tools/aapt2/ResourceParser_test.cpp
@@ -25,11 +25,17 @@
 #include "test/Test.h"
 #include "xml/XmlPullParser.h"
 
+using ::aapt::test::StrValueEq;
 using ::aapt::test::ValueEq;
+using ::android::ResTable_map;
+using ::android::Res_value;
 using ::android::StringPiece;
 using ::testing::Eq;
+using ::testing::IsEmpty;
+using ::testing::IsNull;
 using ::testing::NotNull;
 using ::testing::Pointee;
+using ::testing::SizeIs;
 
 namespace aapt {
 
@@ -74,31 +80,26 @@
 };
 
 TEST_F(ResourceParserTest, ParseQuotedString) {
-  std::string input = "<string name=\"foo\">   \"  hey there \" </string>";
-  ASSERT_TRUE(TestParse(input));
+  ASSERT_TRUE(TestParse(R"(<string name="foo">   "  hey there " </string>)"));
 
   String* str = test::GetValue<String>(&table_, "string/foo");
-  ASSERT_NE(nullptr, str);
-  EXPECT_EQ(std::string("  hey there "), *str->value);
-  EXPECT_TRUE(str->untranslatable_sections.empty());
+  ASSERT_THAT(str, NotNull());
+  EXPECT_THAT(*str, StrValueEq("  hey there "));
+  EXPECT_THAT(str->untranslatable_sections, IsEmpty());
 }
 
 TEST_F(ResourceParserTest, ParseEscapedString) {
-  std::string input = "<string name=\"foo\">\\?123</string>";
-  ASSERT_TRUE(TestParse(input));
+  ASSERT_TRUE(TestParse(R"(<string name="foo">\?123</string>)"));
 
   String* str = test::GetValue<String>(&table_, "string/foo");
-  ASSERT_NE(nullptr, str);
-  EXPECT_EQ(std::string("?123"), *str->value);
-  EXPECT_TRUE(str->untranslatable_sections.empty());
+  ASSERT_THAT(str, NotNull());
+  EXPECT_THAT(*str, StrValueEq("?123"));
+  EXPECT_THAT(str->untranslatable_sections, IsEmpty());
 }
 
 TEST_F(ResourceParserTest, ParseFormattedString) {
-  std::string input = "<string name=\"foo\">%d %s</string>";
-  ASSERT_FALSE(TestParse(input));
-
-  input = "<string name=\"foo\">%1$d %2$s</string>";
-  ASSERT_TRUE(TestParse(input));
+  ASSERT_FALSE(TestParse(R"(<string name="foo">%d %s</string>)"));
+  ASSERT_TRUE(TestParse(R"(<string name="foo">%1$d %2$s</string>)"));
 }
 
 TEST_F(ResourceParserTest, ParseStyledString) {
@@ -109,98 +110,93 @@
   ASSERT_TRUE(TestParse(input));
 
   StyledString* str = test::GetValue<StyledString>(&table_, "string/foo");
-  ASSERT_NE(nullptr, str);
+  ASSERT_THAT(str, NotNull());
 
-  const std::string expected_str = "This is my aunt\u2019s fickle string";
-  EXPECT_EQ(expected_str, *str->value->str);
-  EXPECT_EQ(2u, str->value->spans.size());
-  EXPECT_TRUE(str->untranslatable_sections.empty());
+  EXPECT_THAT(*str->value->str, Eq("This is my aunt\u2019s fickle string"));
+  EXPECT_THAT(str->value->spans, SizeIs(2));
+  EXPECT_THAT(str->untranslatable_sections, IsEmpty());
 
-  EXPECT_EQ(std::string("b"), *str->value->spans[0].name);
-  EXPECT_EQ(17u, str->value->spans[0].first_char);
-  EXPECT_EQ(30u, str->value->spans[0].last_char);
+  EXPECT_THAT(*str->value->spans[0].name, Eq("b"));
+  EXPECT_THAT(str->value->spans[0].first_char, Eq(17u));
+  EXPECT_THAT(str->value->spans[0].last_char, Eq(30u));
 
-  EXPECT_EQ(std::string("small"), *str->value->spans[1].name);
-  EXPECT_EQ(24u, str->value->spans[1].first_char);
-  EXPECT_EQ(30u, str->value->spans[1].last_char);
+  EXPECT_THAT(*str->value->spans[1].name, Eq("small"));
+  EXPECT_THAT(str->value->spans[1].first_char, Eq(24u));
+  EXPECT_THAT(str->value->spans[1].last_char, Eq(30u));
 }
 
 TEST_F(ResourceParserTest, ParseStringWithWhitespace) {
-  std::string input = "<string name=\"foo\">  This is what  I think  </string>";
-  ASSERT_TRUE(TestParse(input));
+  ASSERT_TRUE(TestParse(R"(<string name="foo">  This is what  I think  </string>)"));
 
   String* str = test::GetValue<String>(&table_, "string/foo");
-  ASSERT_NE(nullptr, str);
-  EXPECT_EQ(std::string("This is what I think"), *str->value);
-  EXPECT_TRUE(str->untranslatable_sections.empty());
+  ASSERT_THAT(str, NotNull());
+  EXPECT_THAT(*str->value, Eq("This is what I think"));
+  EXPECT_THAT(str->untranslatable_sections, IsEmpty());
 
-  input = "<string name=\"foo2\">\"  This is what  I think  \"</string>";
-  ASSERT_TRUE(TestParse(input));
+  ASSERT_TRUE(TestParse(R"(<string name="foo2">"  This is what  I think  "</string>)"));
 
   str = test::GetValue<String>(&table_, "string/foo2");
-  ASSERT_NE(nullptr, str);
-  EXPECT_EQ(std::string("  This is what  I think  "), *str->value);
+  ASSERT_THAT(str, NotNull());
+  EXPECT_THAT(*str, StrValueEq("  This is what  I think  "));
 }
 
 TEST_F(ResourceParserTest, IgnoreXliffTagsOtherThanG) {
-  std::string input = R"EOF(
+  std::string input = R"(
       <string name="foo" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-          There are <xliff:source>no</xliff:source> apples</string>)EOF";
+          There are <xliff:source>no</xliff:source> apples</string>)";
   ASSERT_TRUE(TestParse(input));
 
   String* str = test::GetValue<String>(&table_, "string/foo");
-  ASSERT_NE(nullptr, str);
-  EXPECT_EQ(StringPiece("There are no apples"), StringPiece(*str->value));
-  EXPECT_TRUE(str->untranslatable_sections.empty());
+  ASSERT_THAT(str, NotNull());
+  EXPECT_THAT(*str, StrValueEq("There are no apples"));
+  EXPECT_THAT(str->untranslatable_sections, IsEmpty());
 }
 
 TEST_F(ResourceParserTest, NestedXliffGTagsAreIllegal) {
-  std::string input = R"EOF(
+  std::string input = R"(
       <string name="foo" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-          Do not <xliff:g>translate <xliff:g>this</xliff:g></xliff:g></string>)EOF";
+          Do not <xliff:g>translate <xliff:g>this</xliff:g></xliff:g></string>)";
   EXPECT_FALSE(TestParse(input));
 }
 
 TEST_F(ResourceParserTest, RecordUntranslateableXliffSectionsInString) {
-  std::string input = R"EOF(
+  std::string input = R"(
       <string name="foo" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-          There are <xliff:g id="count">%1$d</xliff:g> apples</string>)EOF";
+          There are <xliff:g id="count">%1$d</xliff:g> apples</string>)";
   ASSERT_TRUE(TestParse(input));
 
   String* str = test::GetValue<String>(&table_, "string/foo");
-  ASSERT_NE(nullptr, str);
-  EXPECT_EQ(StringPiece("There are %1$d apples"), StringPiece(*str->value));
-
-  ASSERT_EQ(1u, str->untranslatable_sections.size());
+  ASSERT_THAT(str, NotNull());
+  EXPECT_THAT(*str, StrValueEq("There are %1$d apples"));
+  ASSERT_THAT(str->untranslatable_sections, SizeIs(1));
 
   // We expect indices and lengths that span to include the whitespace
   // before %1$d. This is due to how the StringBuilder withholds whitespace unless
   // needed (to deal with line breaks, etc.).
-  EXPECT_EQ(9u, str->untranslatable_sections[0].start);
-  EXPECT_EQ(14u, str->untranslatable_sections[0].end);
+  EXPECT_THAT(str->untranslatable_sections[0].start, Eq(9u));
+  EXPECT_THAT(str->untranslatable_sections[0].end, Eq(14u));
 }
 
 TEST_F(ResourceParserTest, RecordUntranslateableXliffSectionsInStyledString) {
-  std::string input = R"EOF(
+  std::string input = R"(
       <string name="foo" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-          There are <b><xliff:g id="count">%1$d</xliff:g></b> apples</string>)EOF";
+          There are <b><xliff:g id="count">%1$d</xliff:g></b> apples</string>)";
   ASSERT_TRUE(TestParse(input));
 
   StyledString* str = test::GetValue<StyledString>(&table_, "string/foo");
-  ASSERT_NE(nullptr, str);
-  EXPECT_EQ(StringPiece("There are %1$d apples"), StringPiece(*str->value->str));
-
-  ASSERT_EQ(1u, str->untranslatable_sections.size());
+  ASSERT_THAT(str, NotNull());
+  EXPECT_THAT(*str->value->str, Eq("There are %1$d apples"));
+  ASSERT_THAT(str->untranslatable_sections, SizeIs(1));
 
   // We expect indices and lengths that span to include the whitespace
   // before %1$d. This is due to how the StringBuilder withholds whitespace unless
   // needed (to deal with line breaks, etc.).
-  EXPECT_EQ(9u, str->untranslatable_sections[0].start);
-  EXPECT_EQ(14u, str->untranslatable_sections[0].end);
+  EXPECT_THAT(str->untranslatable_sections[0].start, Eq(9u));
+  EXPECT_THAT(str->untranslatable_sections[0].end, Eq(14u));
 }
 
 TEST_F(ResourceParserTest, ParseNull) {
-  std::string input = "<integer name=\"foo\">@null</integer>";
+  std::string input = R"(<integer name="foo">@null</integer>)";
   ASSERT_TRUE(TestParse(input));
 
   // The Android runtime treats a value of android::Res_value::TYPE_NULL as
@@ -211,38 +207,36 @@
   ASSERT_THAT(null_ref, NotNull());
   EXPECT_FALSE(null_ref->name);
   EXPECT_FALSE(null_ref->id);
-  EXPECT_EQ(Reference::Type::kResource, null_ref->reference_type);
+  EXPECT_THAT(null_ref->reference_type, Eq(Reference::Type::kResource));
 }
 
 TEST_F(ResourceParserTest, ParseEmpty) {
-  std::string input = "<integer name=\"foo\">@empty</integer>";
+  std::string input = R"(<integer name="foo">@empty</integer>)";
   ASSERT_TRUE(TestParse(input));
 
   BinaryPrimitive* integer = test::GetValue<BinaryPrimitive>(&table_, "integer/foo");
-  ASSERT_NE(nullptr, integer);
-  EXPECT_EQ(uint16_t(android::Res_value::TYPE_NULL), integer->value.dataType);
-  EXPECT_EQ(uint32_t(android::Res_value::DATA_NULL_EMPTY), integer->value.data);
+  ASSERT_THAT(integer, NotNull());
+  EXPECT_THAT(integer->value.dataType, Eq(Res_value::TYPE_NULL));
+  EXPECT_THAT(integer->value.data, Eq(Res_value::DATA_NULL_EMPTY));
 }
 
 TEST_F(ResourceParserTest, ParseAttr) {
-  std::string input =
-      "<attr name=\"foo\" format=\"string\"/>\n"
-      "<attr name=\"bar\"/>";
+  std::string input = R"(
+      <attr name="foo" format="string"/>
+      <attr name="bar"/>)";
   ASSERT_TRUE(TestParse(input));
 
   Attribute* attr = test::GetValue<Attribute>(&table_, "attr/foo");
-  ASSERT_NE(nullptr, attr);
-  EXPECT_EQ(uint32_t(android::ResTable_map::TYPE_STRING), attr->type_mask);
+  ASSERT_THAT(attr, NotNull());
+  EXPECT_THAT(attr->type_mask, Eq(ResTable_map::TYPE_STRING));
 
   attr = test::GetValue<Attribute>(&table_, "attr/bar");
-  ASSERT_NE(nullptr, attr);
-  EXPECT_EQ(uint32_t(android::ResTable_map::TYPE_ANY), attr->type_mask);
+  ASSERT_THAT(attr, NotNull());
+  EXPECT_THAT(attr->type_mask, Eq(ResTable_map::TYPE_ANY));
 }
 
-// Old AAPT allowed attributes to be defined under different configurations, but
-// ultimately
-// stored them with the default configuration. Check that we have the same
-// behavior.
+// Old AAPT allowed attributes to be defined under different configurations, but ultimately
+// stored them with the default configuration. Check that we have the same behavior.
 TEST_F(ResourceParserTest, ParseAttrAndDeclareStyleableUnderConfigButRecordAsNoConfig) {
   const ConfigDescription watch_config = test::ParseConfigOrDie("watch");
   std::string input = R"(
@@ -252,583 +246,519 @@
       </declare-styleable>)";
   ASSERT_TRUE(TestParse(input, watch_config));
 
-  EXPECT_EQ(nullptr, test::GetValueForConfig<Attribute>(&table_, "attr/foo", watch_config));
-  EXPECT_EQ(nullptr, test::GetValueForConfig<Attribute>(&table_, "attr/baz", watch_config));
-  EXPECT_EQ(nullptr, test::GetValueForConfig<Styleable>(&table_, "styleable/bar", watch_config));
+  EXPECT_THAT(test::GetValueForConfig<Attribute>(&table_, "attr/foo", watch_config), IsNull());
+  EXPECT_THAT(test::GetValueForConfig<Attribute>(&table_, "attr/baz", watch_config), IsNull());
+  EXPECT_THAT(test::GetValueForConfig<Styleable>(&table_, "styleable/bar", watch_config), IsNull());
 
-  EXPECT_NE(nullptr, test::GetValue<Attribute>(&table_, "attr/foo"));
-  EXPECT_NE(nullptr, test::GetValue<Attribute>(&table_, "attr/baz"));
-  EXPECT_NE(nullptr, test::GetValue<Styleable>(&table_, "styleable/bar"));
+  EXPECT_THAT(test::GetValue<Attribute>(&table_, "attr/foo"), NotNull());
+  EXPECT_THAT(test::GetValue<Attribute>(&table_, "attr/baz"), NotNull());
+  EXPECT_THAT(test::GetValue<Styleable>(&table_, "styleable/bar"), NotNull());
 }
 
 TEST_F(ResourceParserTest, ParseAttrWithMinMax) {
-  std::string input =
-      "<attr name=\"foo\" min=\"10\" max=\"23\" format=\"integer\"/>";
+  std::string input = R"(<attr name="foo" min="10" max="23" format="integer"/>)";
   ASSERT_TRUE(TestParse(input));
 
   Attribute* attr = test::GetValue<Attribute>(&table_, "attr/foo");
-  ASSERT_NE(nullptr, attr);
-  EXPECT_EQ(uint32_t(android::ResTable_map::TYPE_INTEGER), attr->type_mask);
-  EXPECT_EQ(10, attr->min_int);
-  EXPECT_EQ(23, attr->max_int);
+  ASSERT_THAT(attr, NotNull());
+  EXPECT_THAT(attr->type_mask, Eq(ResTable_map::TYPE_INTEGER));
+  EXPECT_THAT(attr->min_int, Eq(10));
+  EXPECT_THAT(attr->max_int, Eq(23));
 }
 
 TEST_F(ResourceParserTest, FailParseAttrWithMinMaxButNotInteger) {
-  std::string input =
-      "<attr name=\"foo\" min=\"10\" max=\"23\" format=\"string\"/>";
-  ASSERT_FALSE(TestParse(input));
+  ASSERT_FALSE(TestParse(R"(<attr name="foo" min="10" max="23" format="string"/>)"));
 }
 
 TEST_F(ResourceParserTest, ParseUseAndDeclOfAttr) {
-  std::string input =
-      "<declare-styleable name=\"Styleable\">\n"
-      "  <attr name=\"foo\" />\n"
-      "</declare-styleable>\n"
-      "<attr name=\"foo\" format=\"string\"/>";
+  std::string input = R"(
+      <declare-styleable name="Styleable">
+        <attr name="foo" />
+      </declare-styleable>
+      <attr name="foo" format="string"/>)";
   ASSERT_TRUE(TestParse(input));
 
   Attribute* attr = test::GetValue<Attribute>(&table_, "attr/foo");
-  ASSERT_NE(nullptr, attr);
-  EXPECT_EQ(uint32_t(android::ResTable_map::TYPE_STRING), attr->type_mask);
+  ASSERT_THAT(attr, NotNull());
+  EXPECT_THAT(attr->type_mask, Eq(ResTable_map::TYPE_STRING));
 }
 
 TEST_F(ResourceParserTest, ParseDoubleUseOfAttr) {
-  std::string input =
-      "<declare-styleable name=\"Theme\">"
-      "  <attr name=\"foo\" />\n"
-      "</declare-styleable>\n"
-      "<declare-styleable name=\"Window\">\n"
-      "  <attr name=\"foo\" format=\"boolean\"/>\n"
-      "</declare-styleable>";
+  std::string input = R"(
+      <declare-styleable name="Theme">
+        <attr name="foo" />
+      </declare-styleable>
+      <declare-styleable name="Window">
+        <attr name="foo" format="boolean"/>
+      </declare-styleable>)";
   ASSERT_TRUE(TestParse(input));
 
   Attribute* attr = test::GetValue<Attribute>(&table_, "attr/foo");
-  ASSERT_NE(nullptr, attr);
-  EXPECT_EQ(uint32_t(android::ResTable_map::TYPE_BOOLEAN), attr->type_mask);
+  ASSERT_THAT(attr, NotNull());
+  EXPECT_THAT(attr->type_mask, Eq(ResTable_map::TYPE_BOOLEAN));
 }
 
 TEST_F(ResourceParserTest, ParseEnumAttr) {
-  std::string input =
-      "<attr name=\"foo\">\n"
-      "  <enum name=\"bar\" value=\"0\"/>\n"
-      "  <enum name=\"bat\" value=\"1\"/>\n"
-      "  <enum name=\"baz\" value=\"2\"/>\n"
-      "</attr>";
+  std::string input = R"(
+      <attr name="foo">
+        <enum name="bar" value="0"/>
+        <enum name="bat" value="1"/>
+        <enum name="baz" value="2"/>
+      </attr>)";
   ASSERT_TRUE(TestParse(input));
 
   Attribute* enum_attr = test::GetValue<Attribute>(&table_, "attr/foo");
-  ASSERT_NE(enum_attr, nullptr);
-  EXPECT_EQ(enum_attr->type_mask, android::ResTable_map::TYPE_ENUM);
-  ASSERT_EQ(enum_attr->symbols.size(), 3u);
+  ASSERT_THAT(enum_attr, NotNull());
+  EXPECT_THAT(enum_attr->type_mask, Eq(ResTable_map::TYPE_ENUM));
+  ASSERT_THAT(enum_attr->symbols, SizeIs(3));
 
-  AAPT_ASSERT_TRUE(enum_attr->symbols[0].symbol.name);
-  EXPECT_EQ(enum_attr->symbols[0].symbol.name.value().entry, "bar");
-  EXPECT_EQ(enum_attr->symbols[0].value, 0u);
+  ASSERT_TRUE(enum_attr->symbols[0].symbol.name);
+  EXPECT_THAT(enum_attr->symbols[0].symbol.name.value().entry, Eq("bar"));
+  EXPECT_THAT(enum_attr->symbols[0].value, Eq(0u));
 
-  AAPT_ASSERT_TRUE(enum_attr->symbols[1].symbol.name);
-  EXPECT_EQ(enum_attr->symbols[1].symbol.name.value().entry, "bat");
-  EXPECT_EQ(enum_attr->symbols[1].value, 1u);
+  ASSERT_TRUE(enum_attr->symbols[1].symbol.name);
+  EXPECT_THAT(enum_attr->symbols[1].symbol.name.value().entry, Eq("bat"));
+  EXPECT_THAT(enum_attr->symbols[1].value, Eq(1u));
 
-  AAPT_ASSERT_TRUE(enum_attr->symbols[2].symbol.name);
-  EXPECT_EQ(enum_attr->symbols[2].symbol.name.value().entry, "baz");
-  EXPECT_EQ(enum_attr->symbols[2].value, 2u);
+  ASSERT_TRUE(enum_attr->symbols[2].symbol.name);
+  EXPECT_THAT(enum_attr->symbols[2].symbol.name.value().entry, Eq("baz"));
+  EXPECT_THAT(enum_attr->symbols[2].value, Eq(2u));
 }
 
 TEST_F(ResourceParserTest, ParseFlagAttr) {
-  std::string input =
-      "<attr name=\"foo\">\n"
-      "  <flag name=\"bar\" value=\"0\"/>\n"
-      "  <flag name=\"bat\" value=\"1\"/>\n"
-      "  <flag name=\"baz\" value=\"2\"/>\n"
-      "</attr>";
+  std::string input = R"(
+      <attr name="foo">
+        <flag name="bar" value="0"/>
+        <flag name="bat" value="1"/>
+        <flag name="baz" value="2"/>
+      </attr>)";
   ASSERT_TRUE(TestParse(input));
 
   Attribute* flag_attr = test::GetValue<Attribute>(&table_, "attr/foo");
-  ASSERT_NE(nullptr, flag_attr);
-  EXPECT_EQ(flag_attr->type_mask, android::ResTable_map::TYPE_FLAGS);
-  ASSERT_EQ(flag_attr->symbols.size(), 3u);
+  ASSERT_THAT(flag_attr, NotNull());
+  EXPECT_THAT(flag_attr->type_mask, Eq(ResTable_map::TYPE_FLAGS));
+  ASSERT_THAT(flag_attr->symbols, SizeIs(3));
 
-  AAPT_ASSERT_TRUE(flag_attr->symbols[0].symbol.name);
-  EXPECT_EQ(flag_attr->symbols[0].symbol.name.value().entry, "bar");
-  EXPECT_EQ(flag_attr->symbols[0].value, 0u);
+  ASSERT_TRUE(flag_attr->symbols[0].symbol.name);
+  EXPECT_THAT(flag_attr->symbols[0].symbol.name.value().entry, Eq("bar"));
+  EXPECT_THAT(flag_attr->symbols[0].value, Eq(0u));
 
-  AAPT_ASSERT_TRUE(flag_attr->symbols[1].symbol.name);
-  EXPECT_EQ(flag_attr->symbols[1].symbol.name.value().entry, "bat");
-  EXPECT_EQ(flag_attr->symbols[1].value, 1u);
+  ASSERT_TRUE(flag_attr->symbols[1].symbol.name);
+  EXPECT_THAT(flag_attr->symbols[1].symbol.name.value().entry, Eq("bat"));
+  EXPECT_THAT(flag_attr->symbols[1].value, Eq(1u));
 
-  AAPT_ASSERT_TRUE(flag_attr->symbols[2].symbol.name);
-  EXPECT_EQ(flag_attr->symbols[2].symbol.name.value().entry, "baz");
-  EXPECT_EQ(flag_attr->symbols[2].value, 2u);
+  ASSERT_TRUE(flag_attr->symbols[2].symbol.name);
+  EXPECT_THAT(flag_attr->symbols[2].symbol.name.value().entry, Eq("baz"));
+  EXPECT_THAT(flag_attr->symbols[2].value, Eq(2u));
 
   std::unique_ptr<BinaryPrimitive> flag_value =
       ResourceUtils::TryParseFlagSymbol(flag_attr, "baz|bat");
-  ASSERT_NE(nullptr, flag_value);
-  EXPECT_EQ(flag_value->value.data, 1u | 2u);
+  ASSERT_THAT(flag_value, NotNull());
+  EXPECT_THAT(flag_value->value.data, Eq(1u | 2u));
 }
 
 TEST_F(ResourceParserTest, FailToParseEnumAttrWithNonUniqueKeys) {
-  std::string input =
-      "<attr name=\"foo\">\n"
-      "  <enum name=\"bar\" value=\"0\"/>\n"
-      "  <enum name=\"bat\" value=\"1\"/>\n"
-      "  <enum name=\"bat\" value=\"2\"/>\n"
-      "</attr>";
+  std::string input = R"(
+      <attr name="foo">
+        <enum name="bar" value="0"/>
+        <enum name="bat" value="1"/>
+        <enum name="bat" value="2"/>
+      </attr>)";
   ASSERT_FALSE(TestParse(input));
 }
 
 TEST_F(ResourceParserTest, ParseStyle) {
-  std::string input =
-      "<style name=\"foo\" parent=\"@style/fu\">\n"
-      "  <item name=\"bar\">#ffffffff</item>\n"
-      "  <item name=\"bat\">@string/hey</item>\n"
-      "  <item name=\"baz\"><b>hey</b></item>\n"
-      "</style>";
+  std::string input = R"(
+      <style name="foo" parent="@style/fu">
+        <item name="bar">#ffffffff</item>
+        <item name="bat">@string/hey</item>
+        <item name="baz"><b>hey</b></item>
+      </style>)";
   ASSERT_TRUE(TestParse(input));
 
   Style* style = test::GetValue<Style>(&table_, "style/foo");
-  ASSERT_NE(nullptr, style);
-  AAPT_ASSERT_TRUE(style->parent);
-  AAPT_ASSERT_TRUE(style->parent.value().name);
-  EXPECT_EQ(test::ParseNameOrDie("style/fu"),
-            style->parent.value().name.value());
-  ASSERT_EQ(3u, style->entries.size());
+  ASSERT_THAT(style, NotNull());
+  ASSERT_TRUE(style->parent);
+  EXPECT_THAT(style->parent.value().name, Eq(make_value(test::ParseNameOrDie("style/fu"))));
+  ASSERT_THAT(style->entries, SizeIs(3));
 
-  AAPT_ASSERT_TRUE(style->entries[0].key.name);
-  EXPECT_EQ(test::ParseNameOrDie("attr/bar"),
-            style->entries[0].key.name.value());
-
-  AAPT_ASSERT_TRUE(style->entries[1].key.name);
-  EXPECT_EQ(test::ParseNameOrDie("attr/bat"),
-            style->entries[1].key.name.value());
-
-  AAPT_ASSERT_TRUE(style->entries[2].key.name);
-  EXPECT_EQ(test::ParseNameOrDie("attr/baz"),
-            style->entries[2].key.name.value());
+  EXPECT_THAT(style->entries[0].key.name, Eq(make_value(test::ParseNameOrDie("attr/bar"))));
+  EXPECT_THAT(style->entries[1].key.name, Eq(make_value(test::ParseNameOrDie("attr/bat"))));
+  EXPECT_THAT(style->entries[2].key.name, Eq(make_value(test::ParseNameOrDie("attr/baz"))));
 }
 
 TEST_F(ResourceParserTest, ParseStyleWithShorthandParent) {
-  std::string input = "<style name=\"foo\" parent=\"com.app:Theme\"/>";
-  ASSERT_TRUE(TestParse(input));
+  ASSERT_TRUE(TestParse(R"(<style name="foo" parent="com.app:Theme"/>)"));
 
   Style* style = test::GetValue<Style>(&table_, "style/foo");
-  ASSERT_NE(nullptr, style);
-  AAPT_ASSERT_TRUE(style->parent);
-  AAPT_ASSERT_TRUE(style->parent.value().name);
-  EXPECT_EQ(test::ParseNameOrDie("com.app:style/Theme"),
-            style->parent.value().name.value());
+  ASSERT_THAT(style, NotNull());
+  ASSERT_TRUE(style->parent);
+  EXPECT_THAT(style->parent.value().name, Eq(make_value(test::ParseNameOrDie("com.app:style/Theme"))));
 }
 
 TEST_F(ResourceParserTest, ParseStyleWithPackageAliasedParent) {
-  std::string input =
-      "<style xmlns:app=\"http://schemas.android.com/apk/res/android\"\n"
-      "       name=\"foo\" parent=\"app:Theme\"/>";
+  std::string input = R"(
+      <style xmlns:app="http://schemas.android.com/apk/res/android"
+          name="foo" parent="app:Theme"/>)";
   ASSERT_TRUE(TestParse(input));
 
   Style* style = test::GetValue<Style>(&table_, "style/foo");
-  ASSERT_NE(nullptr, style);
-  AAPT_ASSERT_TRUE(style->parent);
-  AAPT_ASSERT_TRUE(style->parent.value().name);
-  EXPECT_EQ(test::ParseNameOrDie("android:style/Theme"),
-            style->parent.value().name.value());
+  ASSERT_THAT(style, NotNull());
+  ASSERT_TRUE(style->parent);
+  ASSERT_TRUE(style->parent.value().name);
+  EXPECT_THAT(style->parent.value().name, Eq(make_value(test::ParseNameOrDie("android:style/Theme"))));
 }
 
 TEST_F(ResourceParserTest, ParseStyleWithPackageAliasedItems) {
-  std::string input =
-      "<style xmlns:app=\"http://schemas.android.com/apk/res/android\" "
-      "name=\"foo\">\n"
-      "  <item name=\"app:bar\">0</item>\n"
-      "</style>";
+  std::string input = R"(
+      <style xmlns:app="http://schemas.android.com/apk/res/android" name="foo">
+        <item name="app:bar">0</item>
+      </style>)";
   ASSERT_TRUE(TestParse(input));
 
   Style* style = test::GetValue<Style>(&table_, "style/foo");
-  ASSERT_NE(nullptr, style);
-  ASSERT_EQ(1u, style->entries.size());
-  EXPECT_EQ(test::ParseNameOrDie("android:attr/bar"),
-            style->entries[0].key.name.value());
+  ASSERT_THAT(style, NotNull());
+  ASSERT_THAT(style->entries, SizeIs(1));
+  EXPECT_THAT(style->entries[0].key.name, Eq(make_value(test::ParseNameOrDie("android:attr/bar"))));
 }
 
 TEST_F(ResourceParserTest, ParseStyleWithInferredParent) {
-  std::string input = "<style name=\"foo.bar\"/>";
-  ASSERT_TRUE(TestParse(input));
+  ASSERT_TRUE(TestParse(R"(<style name="foo.bar"/>)"));
 
   Style* style = test::GetValue<Style>(&table_, "style/foo.bar");
-  ASSERT_NE(nullptr, style);
-  AAPT_ASSERT_TRUE(style->parent);
-  AAPT_ASSERT_TRUE(style->parent.value().name);
-  EXPECT_EQ(style->parent.value().name.value(),
-            test::ParseNameOrDie("style/foo"));
+  ASSERT_THAT(style, NotNull());
+  ASSERT_TRUE(style->parent);
+  EXPECT_THAT(style->parent.value().name, Eq(make_value(test::ParseNameOrDie("style/foo"))));
   EXPECT_TRUE(style->parent_inferred);
 }
 
-TEST_F(ResourceParserTest,
-       ParseStyleWithInferredParentOverridenByEmptyParentAttribute) {
-  std::string input = "<style name=\"foo.bar\" parent=\"\"/>";
-  ASSERT_TRUE(TestParse(input));
+TEST_F(ResourceParserTest, ParseStyleWithInferredParentOverridenByEmptyParentAttribute) {
+  ASSERT_TRUE(TestParse(R"(<style name="foo.bar" parent=""/>)"));
 
   Style* style = test::GetValue<Style>(&table_, "style/foo.bar");
-  ASSERT_NE(nullptr, style);
-  AAPT_EXPECT_FALSE(style->parent);
+  ASSERT_THAT(style, NotNull());
+  EXPECT_FALSE(style->parent);
   EXPECT_FALSE(style->parent_inferred);
 }
 
 TEST_F(ResourceParserTest, ParseStyleWithPrivateParentReference) {
-  std::string input =
-      R"EOF(<style name="foo" parent="*android:style/bar" />)EOF";
-  ASSERT_TRUE(TestParse(input));
+  ASSERT_TRUE(TestParse(R"(<style name="foo" parent="*android:style/bar" />)"));
 
   Style* style = test::GetValue<Style>(&table_, "style/foo");
-  ASSERT_NE(nullptr, style);
-  AAPT_ASSERT_TRUE(style->parent);
+  ASSERT_THAT(style, NotNull());
+  ASSERT_TRUE(style->parent);
   EXPECT_TRUE(style->parent.value().private_reference);
 }
 
 TEST_F(ResourceParserTest, ParseAutoGeneratedIdReference) {
-  std::string input = "<string name=\"foo\">@+id/bar</string>";
-  ASSERT_TRUE(TestParse(input));
-
-  Id* id = test::GetValue<Id>(&table_, "id/bar");
-  ASSERT_NE(id, nullptr);
+  ASSERT_TRUE(TestParse(R"(<string name="foo">@+id/bar</string>)"));
+  ASSERT_THAT(test::GetValue<Id>(&table_, "id/bar"), NotNull());
 }
 
 TEST_F(ResourceParserTest, ParseAttributesDeclareStyleable) {
-  std::string input =
-      "<declare-styleable name=\"foo\">\n"
-      "  <attr name=\"bar\" />\n"
-      "  <attr name=\"bat\" format=\"string|reference\"/>\n"
-      "  <attr name=\"baz\">\n"
-      "    <enum name=\"foo\" value=\"1\"/>\n"
-      "  </attr>\n"
-      "</declare-styleable>";
+  std::string input = R"(
+      <declare-styleable name="foo">
+        <attr name="bar" />
+        <attr name="bat" format="string|reference"/>
+        <attr name="baz">
+          <enum name="foo" value="1"/>
+        </attr>
+      </declare-styleable>)";
   ASSERT_TRUE(TestParse(input));
 
   Maybe<ResourceTable::SearchResult> result =
       table_.FindResource(test::ParseNameOrDie("styleable/foo"));
-  AAPT_ASSERT_TRUE(result);
-  EXPECT_EQ(SymbolState::kPublic, result.value().entry->symbol_status.state);
+  ASSERT_TRUE(result);
+  EXPECT_THAT(result.value().entry->symbol_status.state, Eq(SymbolState::kPublic));
 
   Attribute* attr = test::GetValue<Attribute>(&table_, "attr/bar");
-  ASSERT_NE(attr, nullptr);
+  ASSERT_THAT(attr, NotNull());
   EXPECT_TRUE(attr->IsWeak());
 
   attr = test::GetValue<Attribute>(&table_, "attr/bat");
-  ASSERT_NE(attr, nullptr);
+  ASSERT_THAT(attr, NotNull());
   EXPECT_TRUE(attr->IsWeak());
 
   attr = test::GetValue<Attribute>(&table_, "attr/baz");
-  ASSERT_NE(attr, nullptr);
+  ASSERT_THAT(attr, NotNull());
   EXPECT_TRUE(attr->IsWeak());
-  EXPECT_EQ(1u, attr->symbols.size());
+  EXPECT_THAT(attr->symbols, SizeIs(1));
 
-  EXPECT_NE(nullptr, test::GetValue<Id>(&table_, "id/foo"));
+  EXPECT_THAT(test::GetValue<Id>(&table_, "id/foo"), NotNull());
 
   Styleable* styleable = test::GetValue<Styleable>(&table_, "styleable/foo");
-  ASSERT_NE(styleable, nullptr);
-  ASSERT_EQ(3u, styleable->entries.size());
+  ASSERT_THAT(styleable, NotNull());
+  ASSERT_THAT(styleable->entries, SizeIs(3));
 
-  EXPECT_EQ(test::ParseNameOrDie("attr/bar"),
-            styleable->entries[0].name.value());
-  EXPECT_EQ(test::ParseNameOrDie("attr/bat"),
-            styleable->entries[1].name.value());
+  EXPECT_THAT(styleable->entries[0].name, Eq(make_value(test::ParseNameOrDie("attr/bar"))));
+  EXPECT_THAT(styleable->entries[1].name, Eq(make_value(test::ParseNameOrDie("attr/bat"))));
+  EXPECT_THAT(styleable->entries[2].name, Eq(make_value(test::ParseNameOrDie("attr/baz"))));
 }
 
 TEST_F(ResourceParserTest, ParsePrivateAttributesDeclareStyleable) {
-  std::string input =
-      "<declare-styleable name=\"foo\" "
-      "xmlns:privAndroid=\"http://schemas.android.com/apk/prv/res/android\">\n"
-      "  <attr name=\"*android:bar\" />\n"
-      "  <attr name=\"privAndroid:bat\" />\n"
-      "</declare-styleable>";
+  std::string input = R"(
+      <declare-styleable xmlns:privAndroid="http://schemas.android.com/apk/prv/res/android"
+          name="foo">
+        <attr name="*android:bar" />
+        <attr name="privAndroid:bat" />
+      </declare-styleable>)";
   ASSERT_TRUE(TestParse(input));
   Styleable* styleable = test::GetValue<Styleable>(&table_, "styleable/foo");
-  ASSERT_NE(nullptr, styleable);
-  ASSERT_EQ(2u, styleable->entries.size());
+  ASSERT_THAT(styleable, NotNull());
+  ASSERT_THAT(styleable->entries, SizeIs(2));
 
   EXPECT_TRUE(styleable->entries[0].private_reference);
-  AAPT_ASSERT_TRUE(styleable->entries[0].name);
-  EXPECT_EQ(std::string("android"), styleable->entries[0].name.value().package);
+  ASSERT_TRUE(styleable->entries[0].name);
+  EXPECT_THAT(styleable->entries[0].name.value().package, Eq("android"));
 
   EXPECT_TRUE(styleable->entries[1].private_reference);
-  AAPT_ASSERT_TRUE(styleable->entries[1].name);
-  EXPECT_EQ(std::string("android"), styleable->entries[1].name.value().package);
+  ASSERT_TRUE(styleable->entries[1].name);
+  EXPECT_THAT(styleable->entries[1].name.value().package, Eq("android"));
 }
 
 TEST_F(ResourceParserTest, ParseArray) {
-  std::string input =
-      "<array name=\"foo\">\n"
-      "  <item>@string/ref</item>\n"
-      "  <item>hey</item>\n"
-      "  <item>23</item>\n"
-      "</array>";
+  std::string input = R"(
+      <array name="foo">
+        <item>@string/ref</item>
+        <item>hey</item>
+        <item>23</item>
+      </array>)";
   ASSERT_TRUE(TestParse(input));
 
   Array* array = test::GetValue<Array>(&table_, "array/foo");
-  ASSERT_NE(array, nullptr);
-  ASSERT_EQ(3u, array->items.size());
+  ASSERT_THAT(array, NotNull());
+  ASSERT_THAT(array->items, SizeIs(3));
 
-  EXPECT_NE(nullptr, ValueCast<Reference>(array->items[0].get()));
-  EXPECT_NE(nullptr, ValueCast<String>(array->items[1].get()));
-  EXPECT_NE(nullptr, ValueCast<BinaryPrimitive>(array->items[2].get()));
+  EXPECT_THAT(ValueCast<Reference>(array->items[0].get()), NotNull());
+  EXPECT_THAT(ValueCast<String>(array->items[1].get()), NotNull());
+  EXPECT_THAT(ValueCast<BinaryPrimitive>(array->items[2].get()), NotNull());
 }
 
 TEST_F(ResourceParserTest, ParseStringArray) {
-  std::string input = R"EOF(
+  std::string input = R"(
       <string-array name="foo">
         <item>"Werk"</item>"
-      </string-array>)EOF";
+      </string-array>)";
   ASSERT_TRUE(TestParse(input));
-  EXPECT_NE(nullptr, test::GetValue<Array>(&table_, "array/foo"));
+  EXPECT_THAT(test::GetValue<Array>(&table_, "array/foo"), NotNull());
 }
 
 TEST_F(ResourceParserTest, ParseArrayWithFormat) {
-  std::string input = R"EOF(
+  std::string input = R"(
       <array name="foo" format="string">
         <item>100</item>
-      </array>)EOF";
+      </array>)";
   ASSERT_TRUE(TestParse(input));
 
   Array* array = test::GetValue<Array>(&table_, "array/foo");
-  ASSERT_NE(nullptr, array);
-
-  ASSERT_EQ(1u, array->items.size());
+  ASSERT_THAT(array, NotNull());
+  ASSERT_THAT(array->items, SizeIs(1));
 
   String* str = ValueCast<String>(array->items[0].get());
-  ASSERT_NE(nullptr, str);
-  EXPECT_EQ(std::string("100"), *str->value);
+  ASSERT_THAT(str, NotNull());
+  EXPECT_THAT(*str, StrValueEq("100"));
 }
 
 TEST_F(ResourceParserTest, ParseArrayWithBadFormat) {
-  std::string input = R"EOF(
+  std::string input = R"(
       <array name="foo" format="integer">
         <item>Hi</item>
-      </array>)EOF";
+      </array>)";
   ASSERT_FALSE(TestParse(input));
 }
 
 TEST_F(ResourceParserTest, ParsePlural) {
-  std::string input =
-      "<plurals name=\"foo\">\n"
-      "  <item quantity=\"other\">apples</item>\n"
-      "  <item quantity=\"one\">apple</item>\n"
-      "</plurals>";
+  std::string input = R"(
+      <plurals name="foo">
+        <item quantity="other">apples</item>
+        <item quantity="one">apple</item>
+      </plurals>)";
   ASSERT_TRUE(TestParse(input));
 
   Plural* plural = test::GetValue<Plural>(&table_, "plurals/foo");
-  ASSERT_NE(nullptr, plural);
-  EXPECT_EQ(nullptr, plural->values[Plural::Zero]);
-  EXPECT_EQ(nullptr, plural->values[Plural::Two]);
-  EXPECT_EQ(nullptr, plural->values[Plural::Few]);
-  EXPECT_EQ(nullptr, plural->values[Plural::Many]);
+  ASSERT_THAT(plural, NotNull());
+  EXPECT_THAT(plural->values[Plural::Zero], IsNull());
+  EXPECT_THAT(plural->values[Plural::Two], IsNull());
+  EXPECT_THAT(plural->values[Plural::Few], IsNull());
+  EXPECT_THAT(plural->values[Plural::Many], IsNull());
 
-  EXPECT_NE(nullptr, plural->values[Plural::One]);
-  EXPECT_NE(nullptr, plural->values[Plural::Other]);
+  EXPECT_THAT(plural->values[Plural::One], NotNull());
+  EXPECT_THAT(plural->values[Plural::Other], NotNull());
 }
 
 TEST_F(ResourceParserTest, ParseCommentsWithResource) {
-  std::string input =
-      "<!--This is a comment-->\n"
-      "<string name=\"foo\">Hi</string>";
+  std::string input = R"(
+      <!--This is a comment-->
+      <string name="foo">Hi</string>)";
   ASSERT_TRUE(TestParse(input));
 
   String* value = test::GetValue<String>(&table_, "string/foo");
-  ASSERT_NE(nullptr, value);
-  EXPECT_EQ(value->GetComment(), "This is a comment");
+  ASSERT_THAT(value, NotNull());
+  EXPECT_THAT(value->GetComment(), Eq("This is a comment"));
 }
 
 TEST_F(ResourceParserTest, DoNotCombineMultipleComments) {
-  std::string input =
-      "<!--One-->\n"
-      "<!--Two-->\n"
-      "<string name=\"foo\">Hi</string>";
+  std::string input = R"(
+      <!--One-->
+      <!--Two-->
+      <string name="foo">Hi</string>)";
 
   ASSERT_TRUE(TestParse(input));
 
   String* value = test::GetValue<String>(&table_, "string/foo");
-  ASSERT_NE(nullptr, value);
-  EXPECT_EQ(value->GetComment(), "Two");
+  ASSERT_THAT(value, NotNull());
+  EXPECT_THAT(value->GetComment(), Eq("Two"));
 }
 
 TEST_F(ResourceParserTest, IgnoreCommentBeforeEndTag) {
-  std::string input =
-      "<!--One-->\n"
-      "<string name=\"foo\">\n"
-      "  Hi\n"
-      "<!--Two-->\n"
-      "</string>";
-
+  std::string input = R"(
+      <!--One-->
+      <string name="foo">
+        Hi
+      <!--Two-->
+      </string>)";
   ASSERT_TRUE(TestParse(input));
 
   String* value = test::GetValue<String>(&table_, "string/foo");
-  ASSERT_NE(nullptr, value);
-  EXPECT_EQ(value->GetComment(), "One");
+  ASSERT_THAT(value, NotNull());
+  EXPECT_THAT(value->GetComment(), Eq("One"));
 }
 
 TEST_F(ResourceParserTest, ParseNestedComments) {
   // We only care about declare-styleable and enum/flag attributes because
-  // comments
-  // from those end up in R.java
-  std::string input = R"EOF(
-        <declare-styleable name="foo">
-          <!-- The name of the bar -->
-          <attr name="barName" format="string|reference" />
-        </declare-styleable>
+  // comments from those end up in R.java
+  std::string input = R"(
+      <declare-styleable name="foo">
+        <!-- The name of the bar -->
+        <attr name="barName" format="string|reference" />
+      </declare-styleable>
 
-        <attr name="foo">
-          <!-- The very first -->
-          <enum name="one" value="1" />
-        </attr>)EOF";
+      <attr name="foo">
+        <!-- The very first -->
+        <enum name="one" value="1" />
+      </attr>)";
   ASSERT_TRUE(TestParse(input));
 
   Styleable* styleable = test::GetValue<Styleable>(&table_, "styleable/foo");
-  ASSERT_NE(nullptr, styleable);
-  ASSERT_EQ(1u, styleable->entries.size());
-
-  EXPECT_EQ(StringPiece("The name of the bar"),
-            styleable->entries.front().GetComment());
+  ASSERT_THAT(styleable, NotNull());
+  ASSERT_THAT(styleable->entries, SizeIs(1));
+  EXPECT_THAT(styleable->entries[0].GetComment(), Eq("The name of the bar"));
 
   Attribute* attr = test::GetValue<Attribute>(&table_, "attr/foo");
-  ASSERT_NE(nullptr, attr);
-  ASSERT_EQ(1u, attr->symbols.size());
-
-  EXPECT_EQ(StringPiece("The very first"),
-            attr->symbols.front().symbol.GetComment());
+  ASSERT_THAT(attr, NotNull());
+  ASSERT_THAT(attr->symbols, SizeIs(1));
+  EXPECT_THAT(attr->symbols[0].symbol.GetComment(), Eq("The very first"));
 }
 
-/*
- * Declaring an ID as public should not require a separate definition
- * (as an ID has no value).
- */
+// Declaring an ID as public should not require a separate definition (as an ID has no value).
 TEST_F(ResourceParserTest, ParsePublicIdAsDefinition) {
-  std::string input = "<public type=\"id\" name=\"foo\"/>";
-  ASSERT_TRUE(TestParse(input));
-
-  Id* id = test::GetValue<Id>(&table_, "id/foo");
-  ASSERT_NE(nullptr, id);
+  ASSERT_TRUE(TestParse(R"(<public type="id" name="foo"/>)"));
+  ASSERT_THAT(test::GetValue<Id>(&table_, "id/foo"), NotNull());
 }
 
 TEST_F(ResourceParserTest, KeepAllProducts) {
-  std::string input = R"EOF(
-        <string name="foo" product="phone">hi</string>
-        <string name="foo" product="no-sdcard">ho</string>
-        <string name="bar" product="">wee</string>
-        <string name="baz">woo</string>
-        <string name="bit" product="phablet">hoot</string>
-        <string name="bot" product="default">yes</string>
-    )EOF";
+  std::string input = R"(
+      <string name="foo" product="phone">hi</string>
+      <string name="foo" product="no-sdcard">ho</string>
+      <string name="bar" product="">wee</string>
+      <string name="baz">woo</string>
+      <string name="bit" product="phablet">hoot</string>
+      <string name="bot" product="default">yes</string>)";
   ASSERT_TRUE(TestParse(input));
 
-  EXPECT_NE(nullptr, test::GetValueForConfigAndProduct<String>(
-                         &table_, "string/foo",
-                         ConfigDescription::DefaultConfig(), "phone"));
-  EXPECT_NE(nullptr, test::GetValueForConfigAndProduct<String>(
-                         &table_, "string/foo",
-                         ConfigDescription::DefaultConfig(), "no-sdcard"));
-  EXPECT_NE(nullptr,
-            test::GetValueForConfigAndProduct<String>(
-                &table_, "string/bar", ConfigDescription::DefaultConfig(), ""));
-  EXPECT_NE(nullptr,
-            test::GetValueForConfigAndProduct<String>(
-                &table_, "string/baz", ConfigDescription::DefaultConfig(), ""));
-  EXPECT_NE(nullptr, test::GetValueForConfigAndProduct<String>(
-                         &table_, "string/bit",
-                         ConfigDescription::DefaultConfig(), "phablet"));
-  EXPECT_NE(nullptr, test::GetValueForConfigAndProduct<String>(
-                         &table_, "string/bot",
-                         ConfigDescription::DefaultConfig(), "default"));
+  ASSERT_THAT(test::GetValueForConfigAndProduct<String>(&table_, "string/foo", ConfigDescription::DefaultConfig(), "phone"), NotNull());
+  ASSERT_THAT(test::GetValueForConfigAndProduct<String>(&table_, "string/foo",ConfigDescription::DefaultConfig(), "no-sdcard"), NotNull());
+  ASSERT_THAT(test::GetValueForConfigAndProduct<String>(&table_, "string/bar", ConfigDescription::DefaultConfig(), ""), NotNull());
+  ASSERT_THAT(test::GetValueForConfigAndProduct<String>(&table_, "string/baz", ConfigDescription::DefaultConfig(), ""), NotNull());
+  ASSERT_THAT(test::GetValueForConfigAndProduct<String>(&table_, "string/bit", ConfigDescription::DefaultConfig(), "phablet"), NotNull());
+  ASSERT_THAT(test::GetValueForConfigAndProduct<String>(&table_, "string/bot", ConfigDescription::DefaultConfig(), "default"), NotNull());
 }
 
 TEST_F(ResourceParserTest, AutoIncrementIdsInPublicGroup) {
-  std::string input = R"EOF(
-    <public-group type="attr" first-id="0x01010040">
-      <public name="foo" />
-      <public name="bar" />
-    </public-group>)EOF";
+  std::string input = R"(
+      <public-group type="attr" first-id="0x01010040">
+        <public name="foo" />
+        <public name="bar" />
+      </public-group>)";
   ASSERT_TRUE(TestParse(input));
 
-  Maybe<ResourceTable::SearchResult> result =
-      table_.FindResource(test::ParseNameOrDie("attr/foo"));
-  AAPT_ASSERT_TRUE(result);
+  Maybe<ResourceTable::SearchResult> result = table_.FindResource(test::ParseNameOrDie("attr/foo"));
+  ASSERT_TRUE(result);
 
-  AAPT_ASSERT_TRUE(result.value().package->id);
-  AAPT_ASSERT_TRUE(result.value().type->id);
-  AAPT_ASSERT_TRUE(result.value().entry->id);
+  ASSERT_TRUE(result.value().package->id);
+  ASSERT_TRUE(result.value().type->id);
+  ASSERT_TRUE(result.value().entry->id);
   ResourceId actual_id(result.value().package->id.value(),
                        result.value().type->id.value(),
                        result.value().entry->id.value());
-  EXPECT_EQ(ResourceId(0x01010040), actual_id);
+  EXPECT_THAT(actual_id, Eq(ResourceId(0x01010040)));
 
   result = table_.FindResource(test::ParseNameOrDie("attr/bar"));
-  AAPT_ASSERT_TRUE(result);
+  ASSERT_TRUE(result);
 
-  AAPT_ASSERT_TRUE(result.value().package->id);
-  AAPT_ASSERT_TRUE(result.value().type->id);
-  AAPT_ASSERT_TRUE(result.value().entry->id);
+  ASSERT_TRUE(result.value().package->id);
+  ASSERT_TRUE(result.value().type->id);
+  ASSERT_TRUE(result.value().entry->id);
   actual_id = ResourceId(result.value().package->id.value(),
                          result.value().type->id.value(),
                          result.value().entry->id.value());
-  EXPECT_EQ(ResourceId(0x01010041), actual_id);
+  EXPECT_THAT(actual_id, Eq(ResourceId(0x01010041)));
 }
 
 TEST_F(ResourceParserTest, ExternalTypesShouldOnlyBeReferences) {
-  std::string input =
-      R"EOF(<item type="layout" name="foo">@layout/bar</item>)EOF";
-  ASSERT_TRUE(TestParse(input));
-
-  input = R"EOF(<item type="layout" name="bar">"this is a string"</item>)EOF";
-  ASSERT_FALSE(TestParse(input));
+  ASSERT_TRUE(TestParse(R"(<item type="layout" name="foo">@layout/bar</item>)"));
+  ASSERT_FALSE(TestParse(R"(<item type="layout" name="bar">"this is a string"</item>)"));
 }
 
 TEST_F(ResourceParserTest, AddResourcesElementShouldAddEntryWithUndefinedSymbol) {
-  std::string input = R"EOF(<add-resource name="bar" type="string" />)EOF";
-  ASSERT_TRUE(TestParse(input));
+  ASSERT_TRUE(TestParse(R"(<add-resource name="bar" type="string" />)"));
 
   Maybe<ResourceTable::SearchResult> result =
       table_.FindResource(test::ParseNameOrDie("string/bar"));
-  AAPT_ASSERT_TRUE(result);
+  ASSERT_TRUE(result);
   const ResourceEntry* entry = result.value().entry;
-  ASSERT_NE(nullptr, entry);
-  EXPECT_EQ(SymbolState::kUndefined, entry->symbol_status.state);
+  ASSERT_THAT(entry, NotNull());
+  EXPECT_THAT(entry->symbol_status.state, Eq(SymbolState::kUndefined));
   EXPECT_TRUE(entry->symbol_status.allow_new);
 }
 
 TEST_F(ResourceParserTest, ParseItemElementWithFormat) {
-  std::string input = R"(<item name="foo" type="integer" format="float">0.3</item>)";
-  ASSERT_TRUE(TestParse(input));
+  ASSERT_TRUE(TestParse(R"(<item name="foo" type="integer" format="float">0.3</item>)"));
 
   BinaryPrimitive* val = test::GetValue<BinaryPrimitive>(&table_, "integer/foo");
   ASSERT_THAT(val, NotNull());
-  EXPECT_THAT(val->value.dataType, Eq(android::Res_value::TYPE_FLOAT));
+  EXPECT_THAT(val->value.dataType, Eq(Res_value::TYPE_FLOAT));
 
-  input = R"(<item name="bar" type="integer" format="fraction">100</item>)";
-  ASSERT_FALSE(TestParse(input));
+  ASSERT_FALSE(TestParse(R"(<item name="bar" type="integer" format="fraction">100</item>)"));
 }
 
 // An <item> without a format specifier accepts all types of values.
 TEST_F(ResourceParserTest, ParseItemElementWithoutFormat) {
-  std::string input = R"(<item name="foo" type="integer">100%p</item>)";
-  ASSERT_TRUE(TestParse(input));
+  ASSERT_TRUE(TestParse(R"(<item name="foo" type="integer">100%p</item>)"));
 
   BinaryPrimitive* val = test::GetValue<BinaryPrimitive>(&table_, "integer/foo");
   ASSERT_THAT(val, NotNull());
-  EXPECT_THAT(val->value.dataType, Eq(android::Res_value::TYPE_FRACTION));
+  EXPECT_THAT(val->value.dataType, Eq(Res_value::TYPE_FRACTION));
 }
 
 TEST_F(ResourceParserTest, ParseConfigVaryingItem) {
-  std::string input = R"EOF(<item name="foo" type="configVarying">Hey</item>)EOF";
-  ASSERT_TRUE(TestParse(input));
-  ASSERT_NE(nullptr, test::GetValue<String>(&table_, "configVarying/foo"));
+  ASSERT_TRUE(TestParse(R"(<item name="foo" type="configVarying">Hey</item>)"));
+  ASSERT_THAT(test::GetValue<String>(&table_, "configVarying/foo"), NotNull());
 }
 
 TEST_F(ResourceParserTest, ParseBagElement) {
-  std::string input =
-      R"EOF(<bag name="bag" type="configVarying"><item name="test">Hello!</item></bag>)EOF";
+  std::string input = R"(
+      <bag name="bag" type="configVarying">
+        <item name="test">Hello!</item>
+      </bag>)";
   ASSERT_TRUE(TestParse(input));
 
   Style* val = test::GetValue<Style>(&table_, "configVarying/bag");
-  ASSERT_NE(nullptr, val);
+  ASSERT_THAT(val, NotNull());
+  ASSERT_THAT(val->entries, SizeIs(1));
 
-  ASSERT_EQ(1u, val->entries.size());
-  EXPECT_EQ(Reference(test::ParseNameOrDie("attr/test")), val->entries[0].key);
-  EXPECT_NE(nullptr, ValueCast<RawString>(val->entries[0].value.get()));
+  EXPECT_THAT(val->entries[0].key, Eq(Reference(test::ParseNameOrDie("attr/test"))));
+  EXPECT_THAT(ValueCast<RawString>(val->entries[0].value.get()), NotNull());
 }
 
 TEST_F(ResourceParserTest, ParseElementWithNoValue) {
@@ -840,12 +770,11 @@
 
   String* str = test::GetValue<String>(&table_, "string/foo");
   ASSERT_THAT(str, NotNull());
-  EXPECT_THAT(*str->value, Eq(""));
+  EXPECT_THAT(*str, StrValueEq(""));
 }
 
 TEST_F(ResourceParserTest, ParsePlatformIndependentNewline) {
-  std::string input = R"(<string name="foo">%1$s %n %2$s</string>)";
-  ASSERT_TRUE(TestParse(input));
+  ASSERT_TRUE(TestParse(R"(<string name="foo">%1$s %n %2$s</string>)"));
 }
 
 }  // namespace aapt
diff --git a/tools/aapt2/ResourceTable_test.cpp b/tools/aapt2/ResourceTable_test.cpp
index e2b37be..2a3c131 100644
--- a/tools/aapt2/ResourceTable_test.cpp
+++ b/tools/aapt2/ResourceTable_test.cpp
@@ -24,6 +24,8 @@
 #include <ostream>
 #include <string>
 
+using ::testing::NotNull;
+
 namespace aapt {
 
 TEST(ResourceTableTest, FailToAddResourceWithBadName) {
@@ -56,7 +58,7 @@
       test::ValueBuilder<Id>().SetSource("test/path/file.xml", 23u).Build(),
       test::GetDiagnostics()));
 
-  ASSERT_NE(nullptr, test::GetValue<Id>(&table, "android:attr/id"));
+  EXPECT_THAT(test::GetValue<Id>(&table, "android:attr/id"), NotNull());
 }
 
 TEST(ResourceTableTest, AddMultipleResources) {
@@ -88,11 +90,10 @@
           .Build(),
       test::GetDiagnostics()));
 
-  ASSERT_NE(nullptr, test::GetValue<Id>(&table, "android:attr/layout_width"));
-  ASSERT_NE(nullptr, test::GetValue<Id>(&table, "android:attr/id"));
-  ASSERT_NE(nullptr, test::GetValue<Id>(&table, "android:string/ok"));
-  ASSERT_NE(nullptr, test::GetValueForConfig<BinaryPrimitive>(
-                         &table, "android:string/ok", language_config));
+  EXPECT_THAT(test::GetValue<Id>(&table, "android:attr/layout_width"), NotNull());
+  EXPECT_THAT(test::GetValue<Id>(&table, "android:attr/id"), NotNull());
+  EXPECT_THAT(test::GetValue<Id>(&table, "android:string/ok"), NotNull());
+  EXPECT_THAT(test::GetValueForConfig<BinaryPrimitive>(&table, "android:string/ok", language_config), NotNull());
 }
 
 TEST(ResourceTableTest, OverrideWeakResourceValue) {
@@ -103,7 +104,7 @@
       util::make_unique<Attribute>(true), test::GetDiagnostics()));
 
   Attribute* attr = test::GetValue<Attribute>(&table, "android:attr/foo");
-  ASSERT_NE(nullptr, attr);
+  ASSERT_THAT(attr, NotNull());
   EXPECT_TRUE(attr->IsWeak());
 
   ASSERT_TRUE(table.AddResource(
@@ -111,7 +112,7 @@
       util::make_unique<Attribute>(false), test::GetDiagnostics()));
 
   attr = test::GetValue<Attribute>(&table, "android:attr/foo");
-  ASSERT_NE(nullptr, attr);
+  ASSERT_THAT(attr, NotNull());
   EXPECT_FALSE(attr->IsWeak());
 }
 
@@ -127,16 +128,12 @@
                                 util::make_unique<Id>(),
                                 test::GetDiagnostics()));
 
-  EXPECT_NE(nullptr, test::GetValueForConfigAndProduct<Id>(
-                         &table, "android:string/foo",
-                         test::ParseConfigOrDie("land"), "tablet"));
-  EXPECT_NE(nullptr, test::GetValueForConfigAndProduct<Id>(
-                         &table, "android:string/foo",
-                         test::ParseConfigOrDie("land"), "phone"));
+  EXPECT_THAT(test::GetValueForConfigAndProduct<Id>(&table, "android:string/foo",test::ParseConfigOrDie("land"), "tablet"), NotNull());
+  EXPECT_THAT(test::GetValueForConfigAndProduct<Id>(&table, "android:string/foo",test::ParseConfigOrDie("land"), "phone"), NotNull());
 
   Maybe<ResourceTable::SearchResult> sr =
       table.FindResource(test::ParseNameOrDie("android:string/foo"));
-  AAPT_ASSERT_TRUE(sr);
+  ASSERT_TRUE(sr);
   std::vector<ResourceConfigValue*> values =
       sr.value().entry->FindAllValues(test::ParseConfigOrDie("land"));
   ASSERT_EQ(2u, values.size());
diff --git a/tools/aapt2/ResourceUtils_test.cpp b/tools/aapt2/ResourceUtils_test.cpp
index cdc34f1..3a5e685e 100644
--- a/tools/aapt2/ResourceUtils_test.cpp
+++ b/tools/aapt2/ResourceUtils_test.cpp
@@ -20,96 +20,88 @@
 #include "test/Test.h"
 
 using ::aapt::test::ValueEq;
+using ::android::Res_value;
+using ::android::ResTable_map;
+using ::testing::Eq;
+using ::testing::NotNull;
 using ::testing::Pointee;
 
 namespace aapt {
 
 TEST(ResourceUtilsTest, ParseBool) {
-  EXPECT_EQ(Maybe<bool>(true), ResourceUtils::ParseBool("true"));
-  EXPECT_EQ(Maybe<bool>(true), ResourceUtils::ParseBool("TRUE"));
-  EXPECT_EQ(Maybe<bool>(true), ResourceUtils::ParseBool("True"));
-  EXPECT_EQ(Maybe<bool>(false), ResourceUtils::ParseBool("false"));
-  EXPECT_EQ(Maybe<bool>(false), ResourceUtils::ParseBool("FALSE"));
-  EXPECT_EQ(Maybe<bool>(false), ResourceUtils::ParseBool("False"));
+  EXPECT_THAT(ResourceUtils::ParseBool("true"), Eq(Maybe<bool>(true)));
+  EXPECT_THAT(ResourceUtils::ParseBool("TRUE"), Eq(Maybe<bool>(true)));
+  EXPECT_THAT(ResourceUtils::ParseBool("True"), Eq(Maybe<bool>(true)));
+
+  EXPECT_THAT(ResourceUtils::ParseBool("false"), Eq(Maybe<bool>(false)));
+  EXPECT_THAT(ResourceUtils::ParseBool("FALSE"), Eq(Maybe<bool>(false)));
+  EXPECT_THAT(ResourceUtils::ParseBool("False"), Eq(Maybe<bool>(false)));
 }
 
 TEST(ResourceUtilsTest, ParseResourceName) {
   ResourceNameRef actual;
   bool actual_priv = false;
-  EXPECT_TRUE(ResourceUtils::ParseResourceName("android:color/foo", &actual,
-                                               &actual_priv));
-  EXPECT_EQ(ResourceNameRef("android", ResourceType::kColor, "foo"), actual);
+  EXPECT_TRUE(ResourceUtils::ParseResourceName("android:color/foo", &actual, &actual_priv));
+  EXPECT_THAT(actual, Eq(ResourceNameRef("android", ResourceType::kColor, "foo")));
   EXPECT_FALSE(actual_priv);
 
-  EXPECT_TRUE(
-      ResourceUtils::ParseResourceName("color/foo", &actual, &actual_priv));
-  EXPECT_EQ(ResourceNameRef({}, ResourceType::kColor, "foo"), actual);
+  EXPECT_TRUE(ResourceUtils::ParseResourceName("color/foo", &actual, &actual_priv));
+  EXPECT_THAT(actual, Eq(ResourceNameRef({}, ResourceType::kColor, "foo")));
   EXPECT_FALSE(actual_priv);
 
-  EXPECT_TRUE(ResourceUtils::ParseResourceName("*android:color/foo", &actual,
-                                               &actual_priv));
-  EXPECT_EQ(ResourceNameRef("android", ResourceType::kColor, "foo"), actual);
+  EXPECT_TRUE(ResourceUtils::ParseResourceName("*android:color/foo", &actual, &actual_priv));
+  EXPECT_THAT(actual, Eq(ResourceNameRef("android", ResourceType::kColor, "foo")));
   EXPECT_TRUE(actual_priv);
 
   EXPECT_FALSE(ResourceUtils::ParseResourceName(android::StringPiece(), &actual, &actual_priv));
 }
 
 TEST(ResourceUtilsTest, ParseReferenceWithNoPackage) {
-  ResourceNameRef expected({}, ResourceType::kColor, "foo");
   ResourceNameRef actual;
   bool create = false;
   bool private_ref = false;
-  EXPECT_TRUE(ResourceUtils::ParseReference("@color/foo", &actual, &create,
-                                            &private_ref));
-  EXPECT_EQ(expected, actual);
+  EXPECT_TRUE(ResourceUtils::ParseReference("@color/foo", &actual, &create, &private_ref));
+  EXPECT_THAT(actual, Eq(ResourceNameRef({}, ResourceType::kColor, "foo")));
   EXPECT_FALSE(create);
   EXPECT_FALSE(private_ref);
 }
 
 TEST(ResourceUtilsTest, ParseReferenceWithPackage) {
-  ResourceNameRef expected("android", ResourceType::kColor, "foo");
   ResourceNameRef actual;
   bool create = false;
   bool private_ref = false;
-  EXPECT_TRUE(ResourceUtils::ParseReference("@android:color/foo", &actual,
-                                            &create, &private_ref));
-  EXPECT_EQ(expected, actual);
+  EXPECT_TRUE(ResourceUtils::ParseReference("@android:color/foo", &actual, &create, &private_ref));
+  EXPECT_THAT(actual, Eq(ResourceNameRef("android", ResourceType::kColor, "foo")));
   EXPECT_FALSE(create);
   EXPECT_FALSE(private_ref);
 }
 
 TEST(ResourceUtilsTest, ParseReferenceWithSurroundingWhitespace) {
-  ResourceNameRef expected("android", ResourceType::kColor, "foo");
   ResourceNameRef actual;
   bool create = false;
   bool private_ref = false;
-  EXPECT_TRUE(ResourceUtils::ParseReference("\t @android:color/foo\n \n\t",
-                                            &actual, &create, &private_ref));
-  EXPECT_EQ(expected, actual);
+  EXPECT_TRUE(ResourceUtils::ParseReference("\t @android:color/foo\n \n\t", &actual, &create, &private_ref));
+  EXPECT_THAT(actual, Eq(ResourceNameRef("android", ResourceType::kColor, "foo")));
   EXPECT_FALSE(create);
   EXPECT_FALSE(private_ref);
 }
 
 TEST(ResourceUtilsTest, ParseAutoCreateIdReference) {
-  ResourceNameRef expected("android", ResourceType::kId, "foo");
   ResourceNameRef actual;
   bool create = false;
   bool private_ref = false;
-  EXPECT_TRUE(ResourceUtils::ParseReference("@+android:id/foo", &actual,
-                                            &create, &private_ref));
-  EXPECT_EQ(expected, actual);
+  EXPECT_TRUE(ResourceUtils::ParseReference("@+android:id/foo", &actual, &create, &private_ref));
+  EXPECT_THAT(actual, Eq(ResourceNameRef("android", ResourceType::kId, "foo")));
   EXPECT_TRUE(create);
   EXPECT_FALSE(private_ref);
 }
 
 TEST(ResourceUtilsTest, ParsePrivateReference) {
-  ResourceNameRef expected("android", ResourceType::kId, "foo");
   ResourceNameRef actual;
   bool create = false;
   bool private_ref = false;
-  EXPECT_TRUE(ResourceUtils::ParseReference("@*android:id/foo", &actual,
-                                            &create, &private_ref));
-  EXPECT_EQ(expected, actual);
+  EXPECT_TRUE(ResourceUtils::ParseReference("@*android:id/foo", &actual, &create, &private_ref));
+  EXPECT_THAT(actual, Eq(ResourceNameRef("android", ResourceType::kId, "foo")));
   EXPECT_FALSE(create);
   EXPECT_TRUE(private_ref);
 }
@@ -118,8 +110,7 @@
   bool create = false;
   bool private_ref = false;
   ResourceNameRef actual;
-  EXPECT_FALSE(ResourceUtils::ParseReference("@+android:color/foo", &actual,
-                                             &create, &private_ref));
+  EXPECT_FALSE(ResourceUtils::ParseReference("@+android:color/foo", &actual, &create, &private_ref));
 }
 
 TEST(ResourceUtilsTest, ParseAttributeReferences) {
@@ -143,82 +134,69 @@
 }
 
 TEST(ResourceUtilsTest, ParseStyleParentReference) {
-  const ResourceName kAndroidStyleFooName("android", ResourceType::kStyle,
-                                          "foo");
+  const ResourceName kAndroidStyleFooName("android", ResourceType::kStyle, "foo");
   const ResourceName kStyleFooName({}, ResourceType::kStyle, "foo");
 
   std::string err_str;
-  Maybe<Reference> ref =
-      ResourceUtils::ParseStyleParentReference("@android:style/foo", &err_str);
-  AAPT_ASSERT_TRUE(ref);
-  EXPECT_EQ(ref.value().name.value(), kAndroidStyleFooName);
+  Maybe<Reference> ref = ResourceUtils::ParseStyleParentReference("@android:style/foo", &err_str);
+  ASSERT_TRUE(ref);
+  EXPECT_THAT(ref.value().name, Eq(make_value(kAndroidStyleFooName)));
 
   ref = ResourceUtils::ParseStyleParentReference("@style/foo", &err_str);
-  AAPT_ASSERT_TRUE(ref);
-  EXPECT_EQ(ref.value().name.value(), kStyleFooName);
+  ASSERT_TRUE(ref);
+  EXPECT_THAT(ref.value().name, Eq(make_value(kStyleFooName)));
 
-  ref =
-      ResourceUtils::ParseStyleParentReference("?android:style/foo", &err_str);
-  AAPT_ASSERT_TRUE(ref);
-  EXPECT_EQ(ref.value().name.value(), kAndroidStyleFooName);
+  ref = ResourceUtils::ParseStyleParentReference("?android:style/foo", &err_str);
+  ASSERT_TRUE(ref);
+  EXPECT_THAT(ref.value().name, Eq(make_value(kAndroidStyleFooName)));
 
   ref = ResourceUtils::ParseStyleParentReference("?style/foo", &err_str);
-  AAPT_ASSERT_TRUE(ref);
-  EXPECT_EQ(ref.value().name.value(), kStyleFooName);
+  ASSERT_TRUE(ref);
+  EXPECT_THAT(ref.value().name, Eq(make_value(kStyleFooName)));
 
   ref = ResourceUtils::ParseStyleParentReference("android:style/foo", &err_str);
-  AAPT_ASSERT_TRUE(ref);
-  EXPECT_EQ(ref.value().name.value(), kAndroidStyleFooName);
+  ASSERT_TRUE(ref);
+  EXPECT_THAT(ref.value().name, Eq(make_value(kAndroidStyleFooName)));
 
   ref = ResourceUtils::ParseStyleParentReference("android:foo", &err_str);
-  AAPT_ASSERT_TRUE(ref);
-  EXPECT_EQ(ref.value().name.value(), kAndroidStyleFooName);
+  ASSERT_TRUE(ref);
+  EXPECT_THAT(ref.value().name, Eq(make_value(kAndroidStyleFooName)));
 
   ref = ResourceUtils::ParseStyleParentReference("@android:foo", &err_str);
-  AAPT_ASSERT_TRUE(ref);
-  EXPECT_EQ(ref.value().name.value(), kAndroidStyleFooName);
+  ASSERT_TRUE(ref);
+  EXPECT_THAT(ref.value().name, Eq(make_value(kAndroidStyleFooName)));
 
   ref = ResourceUtils::ParseStyleParentReference("foo", &err_str);
-  AAPT_ASSERT_TRUE(ref);
-  EXPECT_EQ(ref.value().name.value(), kStyleFooName);
+  ASSERT_TRUE(ref);
+  EXPECT_THAT(ref.value().name, Eq(make_value(kStyleFooName)));
 
-  ref =
-      ResourceUtils::ParseStyleParentReference("*android:style/foo", &err_str);
-  AAPT_ASSERT_TRUE(ref);
-  EXPECT_EQ(ref.value().name.value(), kAndroidStyleFooName);
+  ref = ResourceUtils::ParseStyleParentReference("*android:style/foo", &err_str);
+  ASSERT_TRUE(ref);
+  EXPECT_THAT(ref.value().name, Eq(make_value(kAndroidStyleFooName)));
   EXPECT_TRUE(ref.value().private_reference);
 }
 
 TEST(ResourceUtilsTest, ParseEmptyFlag) {
   std::unique_ptr<Attribute> attr =
       test::AttributeBuilder(false)
-          .SetTypeMask(android::ResTable_map::TYPE_FLAGS)
+          .SetTypeMask(ResTable_map::TYPE_FLAGS)
           .AddItem("one", 0x01)
           .AddItem("two", 0x02)
           .Build();
 
-  std::unique_ptr<BinaryPrimitive> result =
-      ResourceUtils::TryParseFlagSymbol(attr.get(), "");
-  ASSERT_NE(nullptr, result);
-  EXPECT_EQ(0u, result->value.data);
+  std::unique_ptr<BinaryPrimitive> result = ResourceUtils::TryParseFlagSymbol(attr.get(), "");
+  ASSERT_THAT(result, NotNull());
+  EXPECT_THAT(result->value.data, Eq(0u));
 }
 
 TEST(ResourceUtilsTest, NullIsEmptyReference) {
-  auto null_value = ResourceUtils::MakeNull();
-  ASSERT_THAT(null_value, Pointee(ValueEq(Reference())));
-
-  auto value = ResourceUtils::TryParseNullOrEmpty("@null");
-  ASSERT_THAT(value, Pointee(ValueEq(Reference())));
+  ASSERT_THAT(ResourceUtils::MakeNull(), Pointee(ValueEq(Reference())));
+  ASSERT_THAT(ResourceUtils::TryParseNullOrEmpty("@null"), Pointee(ValueEq(Reference())));
 }
 
 TEST(ResourceUtilsTest, EmptyIsBinaryPrimitive) {
-  auto empty_value = ResourceUtils::MakeEmpty();
-  ASSERT_THAT(empty_value, Pointee(ValueEq(BinaryPrimitive(android::Res_value::TYPE_NULL,
-                                                           android::Res_value::DATA_NULL_EMPTY))));
-
-  auto value = ResourceUtils::TryParseNullOrEmpty("@empty");
-  ASSERT_THAT(value, Pointee(ValueEq(BinaryPrimitive(android::Res_value::TYPE_NULL,
-                                                     android::Res_value::DATA_NULL_EMPTY))));
+  ASSERT_THAT(ResourceUtils::MakeEmpty(), Pointee(ValueEq(BinaryPrimitive(Res_value::TYPE_NULL, Res_value::DATA_NULL_EMPTY))));
+  ASSERT_THAT(ResourceUtils::TryParseNullOrEmpty("@empty"), Pointee(ValueEq(BinaryPrimitive(Res_value::TYPE_NULL, Res_value::DATA_NULL_EMPTY))));
 }
 
 }  // namespace aapt
diff --git a/tools/aapt2/compile/IdAssigner_test.cpp b/tools/aapt2/compile/IdAssigner_test.cpp
index d465091..5cff004 100644
--- a/tools/aapt2/compile/IdAssigner_test.cpp
+++ b/tools/aapt2/compile/IdAssigner_test.cpp
@@ -64,12 +64,12 @@
   // Expect to fill in the gaps between 0x0101XXXX and 0x0104XXXX.
 
   maybe_result = table->FindResource(test::ParseNameOrDie("android:dimen/two"));
-  AAPT_ASSERT_TRUE(maybe_result);
+  ASSERT_TRUE(maybe_result);
   EXPECT_EQ(make_value<uint8_t>(2), maybe_result.value().type->id);
 
   maybe_result =
       table->FindResource(test::ParseNameOrDie("android:integer/three"));
-  AAPT_ASSERT_TRUE(maybe_result);
+  ASSERT_TRUE(maybe_result);
   EXPECT_EQ(make_value<uint8_t>(3), maybe_result.value().type->id);
 
   // Expect to bypass the reserved 0x0104XXXX IDs and use the next 0x0105XXXX
@@ -77,17 +77,17 @@
 
   maybe_result =
       table->FindResource(test::ParseNameOrDie("android:string/five"));
-  AAPT_ASSERT_TRUE(maybe_result);
+  ASSERT_TRUE(maybe_result);
   EXPECT_EQ(make_value<uint8_t>(5), maybe_result.value().type->id);
 
   // Expect to fill in the gaps between 0x01040000 and 0x01040006.
 
   maybe_result = table->FindResource(test::ParseNameOrDie("android:attr/bar"));
-  AAPT_ASSERT_TRUE(maybe_result);
+  ASSERT_TRUE(maybe_result);
   EXPECT_EQ(make_value<uint16_t>(1), maybe_result.value().entry->id);
 
   maybe_result = table->FindResource(test::ParseNameOrDie("android:attr/baz"));
-  AAPT_ASSERT_TRUE(maybe_result);
+  ASSERT_TRUE(maybe_result);
   EXPECT_EQ(make_value<uint16_t>(2), maybe_result.value().entry->id);
 }
 
@@ -121,7 +121,7 @@
   ASSERT_TRUE(VerifyIds(table.get()));
   Maybe<ResourceTable::SearchResult> result =
       table->FindResource(test::ParseNameOrDie("android:attr/foo"));
-  AAPT_ASSERT_TRUE(result);
+  ASSERT_TRUE(result);
 
   const ResourceTable::SearchResult& search_result = result.value();
   EXPECT_EQ(make_value<uint8_t>(0x01), search_result.package->id);
diff --git a/tools/aapt2/flatten/TableFlattener_test.cpp b/tools/aapt2/flatten/TableFlattener_test.cpp
index 6d1350d..4fdb2ec 100644
--- a/tools/aapt2/flatten/TableFlattener_test.cpp
+++ b/tools/aapt2/flatten/TableFlattener_test.cpp
@@ -26,6 +26,9 @@
 
 using namespace android;
 
+using ::testing::IsNull;
+using ::testing::NotNull;
+
 namespace aapt {
 
 class TableFlattenerTest : public ::testing::Test {
@@ -235,13 +238,12 @@
   ResourceTable result;
   ASSERT_TRUE(Flatten(context_.get(), {}, table.get(), &result));
 
-  Attribute* actualAttr =
-      test::GetValue<Attribute>(&result, "android:attr/foo");
-  ASSERT_NE(nullptr, actualAttr);
-  EXPECT_EQ(attr.IsWeak(), actualAttr->IsWeak());
-  EXPECT_EQ(attr.type_mask, actualAttr->type_mask);
-  EXPECT_EQ(attr.min_int, actualAttr->min_int);
-  EXPECT_EQ(attr.max_int, actualAttr->max_int);
+  Attribute* actual_attr = test::GetValue<Attribute>(&result, "android:attr/foo");
+  ASSERT_THAT(actual_attr, NotNull());
+  EXPECT_EQ(attr.IsWeak(), actual_attr->IsWeak());
+  EXPECT_EQ(attr.type_mask, actual_attr->type_mask);
+  EXPECT_EQ(attr.min_int, actual_attr->min_int);
+  EXPECT_EQ(attr.max_int, actual_attr->max_int);
 }
 
 static std::unique_ptr<ResourceTable> BuildTableWithSparseEntries(
@@ -303,15 +305,13 @@
 
   auto value = test::GetValueForConfig<BinaryPrimitive>(&sparse_table, "android:string/foo_0",
                                                         sparse_config);
-  ASSERT_NE(nullptr, value);
+  ASSERT_THAT(value, NotNull());
   EXPECT_EQ(0u, value->value.data);
 
-  ASSERT_EQ(nullptr, test::GetValueForConfig<BinaryPrimitive>(&sparse_table, "android:string/foo_1",
-                                                              sparse_config));
+  ASSERT_THAT(test::GetValueForConfig<BinaryPrimitive>(&sparse_table, "android:string/foo_1", sparse_config), IsNull());
 
-  value = test::GetValueForConfig<BinaryPrimitive>(&sparse_table, "android:string/foo_4",
-                                                   sparse_config);
-  ASSERT_NE(nullptr, value);
+  value = test::GetValueForConfig<BinaryPrimitive>(&sparse_table, "android:string/foo_4", sparse_config);
+  ASSERT_THAT(value, NotNull());
   EXPECT_EQ(4u, value->value.data);
 }
 
@@ -372,7 +372,7 @@
 
   Maybe<ResourceTable::SearchResult> search_result =
       result.FindResource(test::ParseNameOrDie("lib:id/foo"));
-  AAPT_ASSERT_TRUE(search_result);
+  ASSERT_TRUE(search_result);
   EXPECT_EQ(0x00u, search_result.value().package->id.value());
 
   auto iter = result.included_packages_.find(0x00);
@@ -398,7 +398,7 @@
   ASSERT_TRUE(Flatten(context.get(), {}, table.get(), &result));
 
   const DynamicRefTable* dynamic_ref_table = result.getDynamicRefTableForCookie(1);
-  ASSERT_NE(nullptr, dynamic_ref_table);
+  ASSERT_THAT(dynamic_ref_table, NotNull());
 
   const KeyedVector<String16, uint8_t>& entries = dynamic_ref_table->entries();
 
@@ -423,7 +423,7 @@
   ASSERT_TRUE(Flatten(context.get(), {}, table.get(), &result));
 
   const DynamicRefTable* dynamic_ref_table = result.getDynamicRefTableForCookie(1);
-  ASSERT_NE(nullptr, dynamic_ref_table);
+  ASSERT_THAT(dynamic_ref_table, NotNull());
 
   const KeyedVector<String16, uint8_t>& entries = dynamic_ref_table->entries();
   ssize_t idx = entries.indexOfKey(android::String16("app"));
diff --git a/tools/aapt2/link/AutoVersioner_test.cpp b/tools/aapt2/link/AutoVersioner_test.cpp
index 755af0a..49639f8 100644
--- a/tools/aapt2/link/AutoVersioner_test.cpp
+++ b/tools/aapt2/link/AutoVersioner_test.cpp
@@ -19,43 +19,34 @@
 #include "ConfigDescription.h"
 #include "test/Test.h"
 
+using ::testing::NotNull;
+
 namespace aapt {
 
 TEST(AutoVersionerTest, GenerateVersionedResources) {
   const ConfigDescription land_config = test::ParseConfigOrDie("land");
-  const ConfigDescription sw600dp_land_config =
-      test::ParseConfigOrDie("sw600dp-land");
+  const ConfigDescription sw600dp_land_config = test::ParseConfigOrDie("sw600dp-land");
 
   ResourceEntry entry("foo");
-  entry.values.push_back(util::make_unique<ResourceConfigValue>(
-      ConfigDescription::DefaultConfig(), ""));
-  entry.values.push_back(
-      util::make_unique<ResourceConfigValue>(land_config, ""));
-  entry.values.push_back(
-      util::make_unique<ResourceConfigValue>(sw600dp_land_config, ""));
+  entry.values.push_back(util::make_unique<ResourceConfigValue>(ConfigDescription::DefaultConfig(), ""));
+  entry.values.push_back(util::make_unique<ResourceConfigValue>(land_config, ""));
+  entry.values.push_back(util::make_unique<ResourceConfigValue>(sw600dp_land_config, ""));
 
-  EXPECT_TRUE(ShouldGenerateVersionedResource(
-      &entry, ConfigDescription::DefaultConfig(), 17));
+  EXPECT_TRUE(ShouldGenerateVersionedResource(&entry, ConfigDescription::DefaultConfig(), 17));
   EXPECT_TRUE(ShouldGenerateVersionedResource(&entry, land_config, 17));
 }
 
 TEST(AutoVersionerTest, GenerateVersionedResourceWhenHigherVersionExists) {
-  const ConfigDescription sw600dp_v13_config =
-      test::ParseConfigOrDie("sw600dp-v13");
+  const ConfigDescription sw600dp_v13_config = test::ParseConfigOrDie("sw600dp-v13");
   const ConfigDescription v21_config = test::ParseConfigOrDie("v21");
 
   ResourceEntry entry("foo");
-  entry.values.push_back(util::make_unique<ResourceConfigValue>(
-      ConfigDescription::DefaultConfig(), ""));
-  entry.values.push_back(
-      util::make_unique<ResourceConfigValue>(sw600dp_v13_config, ""));
-  entry.values.push_back(
-      util::make_unique<ResourceConfigValue>(v21_config, ""));
+  entry.values.push_back(util::make_unique<ResourceConfigValue>(ConfigDescription::DefaultConfig(), ""));
+  entry.values.push_back(util::make_unique<ResourceConfigValue>(sw600dp_v13_config, ""));
+  entry.values.push_back(util::make_unique<ResourceConfigValue>(v21_config, ""));
 
-  EXPECT_TRUE(ShouldGenerateVersionedResource(
-      &entry, ConfigDescription::DefaultConfig(), 17));
-  EXPECT_FALSE(ShouldGenerateVersionedResource(
-      &entry, ConfigDescription::DefaultConfig(), 22));
+  EXPECT_TRUE(ShouldGenerateVersionedResource(&entry, ConfigDescription::DefaultConfig(), 17));
+  EXPECT_FALSE(ShouldGenerateVersionedResource(&entry, ConfigDescription::DefaultConfig(), 22));
 }
 
 TEST(AutoVersionerTest, VersionStylesForTable) {
@@ -92,46 +83,28 @@
   AutoVersioner versioner;
   ASSERT_TRUE(versioner.Consume(context.get(), table.get()));
 
-  Style* style = test::GetValueForConfig<Style>(table.get(), "app:style/Foo",
-                                                test::ParseConfigOrDie("v4"));
-  ASSERT_NE(style, nullptr);
+  Style* style = test::GetValueForConfig<Style>(table.get(), "app:style/Foo", test::ParseConfigOrDie("v4"));
+  ASSERT_THAT(style, NotNull());
   ASSERT_EQ(style->entries.size(), 1u);
-  AAPT_ASSERT_TRUE(style->entries.front().key.name);
-  EXPECT_EQ(style->entries.front().key.name.value(),
-            test::ParseNameOrDie("android:attr/onClick"));
+  EXPECT_EQ(make_value(test::ParseNameOrDie("android:attr/onClick")), style->entries.front().key.name);
 
-  style = test::GetValueForConfig<Style>(table.get(), "app:style/Foo",
-                                         test::ParseConfigOrDie("v13"));
-  ASSERT_NE(style, nullptr);
+  style = test::GetValueForConfig<Style>(table.get(), "app:style/Foo", test::ParseConfigOrDie("v13"));
+  ASSERT_THAT(style, NotNull());
   ASSERT_EQ(style->entries.size(), 2u);
-  AAPT_ASSERT_TRUE(style->entries[0].key.name);
-  EXPECT_EQ(style->entries[0].key.name.value(),
-            test::ParseNameOrDie("android:attr/onClick"));
-  AAPT_ASSERT_TRUE(style->entries[1].key.name);
-  EXPECT_EQ(style->entries[1].key.name.value(),
-            test::ParseNameOrDie("android:attr/requiresSmallestWidthDp"));
+  EXPECT_EQ(make_value(test::ParseNameOrDie("android:attr/onClick")),style->entries[0].key.name);
+  EXPECT_EQ(make_value(test::ParseNameOrDie("android:attr/requiresSmallestWidthDp")), style->entries[1].key.name);
 
-  style = test::GetValueForConfig<Style>(table.get(), "app:style/Foo",
-                                         test::ParseConfigOrDie("v17"));
-  ASSERT_NE(style, nullptr);
+  style = test::GetValueForConfig<Style>(table.get(), "app:style/Foo", test::ParseConfigOrDie("v17"));
+  ASSERT_THAT(style, NotNull());
   ASSERT_EQ(style->entries.size(), 3u);
-  AAPT_ASSERT_TRUE(style->entries[0].key.name);
-  EXPECT_EQ(style->entries[0].key.name.value(),
-            test::ParseNameOrDie("android:attr/onClick"));
-  AAPT_ASSERT_TRUE(style->entries[1].key.name);
-  EXPECT_EQ(style->entries[1].key.name.value(),
-            test::ParseNameOrDie("android:attr/requiresSmallestWidthDp"));
-  AAPT_ASSERT_TRUE(style->entries[2].key.name);
-  EXPECT_EQ(style->entries[2].key.name.value(),
-            test::ParseNameOrDie("android:attr/paddingStart"));
+  EXPECT_EQ(make_value(test::ParseNameOrDie("android:attr/onClick")), style->entries[0].key.name);
+  EXPECT_EQ(make_value(test::ParseNameOrDie("android:attr/requiresSmallestWidthDp")), style->entries[1].key.name);
+  EXPECT_EQ(make_value(test::ParseNameOrDie("android:attr/paddingStart")), style->entries[2].key.name);
 
-  style = test::GetValueForConfig<Style>(table.get(), "app:style/Foo",
-                                         test::ParseConfigOrDie("v21"));
-  ASSERT_NE(style, nullptr);
-  ASSERT_EQ(style->entries.size(), 1u);
-  AAPT_ASSERT_TRUE(style->entries.front().key.name);
-  EXPECT_EQ(style->entries.front().key.name.value(),
-            test::ParseNameOrDie("android:attr/paddingEnd"));
+  style = test::GetValueForConfig<Style>(table.get(), "app:style/Foo", test::ParseConfigOrDie("v21"));
+  ASSERT_THAT(style, NotNull());
+  ASSERT_EQ(1u, style->entries.size());
+  EXPECT_EQ(make_value(test::ParseNameOrDie("android:attr/paddingEnd")), style->entries.front().key.name);
 }
 
 }  // namespace aapt
diff --git a/tools/aapt2/link/ReferenceLinker_test.cpp b/tools/aapt2/link/ReferenceLinker_test.cpp
index d8e33a4..72a9168 100644
--- a/tools/aapt2/link/ReferenceLinker_test.cpp
+++ b/tools/aapt2/link/ReferenceLinker_test.cpp
@@ -19,6 +19,7 @@
 #include "test/Test.h"
 
 using android::ResTable_map;
+using ::testing::NotNull;
 
 namespace aapt {
 
@@ -54,18 +55,18 @@
   ASSERT_TRUE(linker.Consume(context.get(), table.get()));
 
   Reference* ref = test::GetValue<Reference>(table.get(), "com.app.test:string/foo");
-  ASSERT_NE(nullptr, ref);
-  AAPT_ASSERT_TRUE(ref->id);
+  ASSERT_THAT(ref, NotNull());
+  ASSERT_TRUE(ref->id);
   EXPECT_EQ(ResourceId(0x7f020001), ref->id.value());
 
   ref = test::GetValue<Reference>(table.get(), "com.app.test:string/bar");
-  ASSERT_NE(nullptr, ref);
-  AAPT_ASSERT_TRUE(ref->id);
+  ASSERT_THAT(ref, NotNull());
+  ASSERT_TRUE(ref->id);
   EXPECT_EQ(ResourceId(0x7f020002), ref->id.value());
 
   ref = test::GetValue<Reference>(table.get(), "com.app.test:string/baz");
-  ASSERT_NE(nullptr, ref);
-  AAPT_ASSERT_TRUE(ref->id);
+  ASSERT_THAT(ref, NotNull());
+  ASSERT_TRUE(ref->id);
   EXPECT_EQ(ResourceId(0x01040034), ref->id.value());
 }
 
@@ -84,10 +85,9 @@
 
   {
     // We need to fill in the value for the attribute android:attr/bar after we
-    // build the
-    // table, because we need access to the string pool.
+    // build the table, because we need access to the string pool.
     Style* style = test::GetValue<Style>(table.get(), "com.app.test:style/Theme");
-    ASSERT_NE(nullptr, style);
+    ASSERT_THAT(style, NotNull());
     style->entries.back().value =
         util::make_unique<RawString>(table->string_pool.MakeRef("one|two"));
   }
@@ -118,20 +118,20 @@
   ASSERT_TRUE(linker.Consume(context.get(), table.get()));
 
   Style* style = test::GetValue<Style>(table.get(), "com.app.test:style/Theme");
-  ASSERT_NE(nullptr, style);
-  AAPT_ASSERT_TRUE(style->parent);
-  AAPT_ASSERT_TRUE(style->parent.value().id);
+  ASSERT_THAT(style, NotNull());
+  ASSERT_TRUE(style->parent);
+  ASSERT_TRUE(style->parent.value().id);
   EXPECT_EQ(ResourceId(0x01060000), style->parent.value().id.value());
 
   ASSERT_EQ(2u, style->entries.size());
 
-  AAPT_ASSERT_TRUE(style->entries[0].key.id);
+  ASSERT_TRUE(style->entries[0].key.id);
   EXPECT_EQ(ResourceId(0x01010001), style->entries[0].key.id.value());
-  ASSERT_NE(nullptr, ValueCast<BinaryPrimitive>(style->entries[0].value.get()));
+  ASSERT_THAT(ValueCast<BinaryPrimitive>(style->entries[0].value.get()), NotNull());
 
-  AAPT_ASSERT_TRUE(style->entries[1].key.id);
+  ASSERT_TRUE(style->entries[1].key.id);
   EXPECT_EQ(ResourceId(0x01010002), style->entries[1].key.id.value());
-  ASSERT_NE(nullptr, ValueCast<BinaryPrimitive>(style->entries[1].value.get()));
+  ASSERT_THAT(ValueCast<BinaryPrimitive>(style->entries[1].value.get()), NotNull());
 }
 
 TEST(ReferenceLinkerTest, LinkMangledReferencesAndAttributes) {
@@ -165,9 +165,9 @@
   ASSERT_TRUE(linker.Consume(context.get(), table.get()));
 
   Style* style = test::GetValue<Style>(table.get(), "com.app.test:style/Theme");
-  ASSERT_NE(nullptr, style);
+  ASSERT_THAT(style, NotNull());
   ASSERT_EQ(1u, style->entries.size());
-  AAPT_ASSERT_TRUE(style->entries.front().key.id);
+  ASSERT_TRUE(style->entries.front().key.id);
   EXPECT_EQ(ResourceId(0x7f010000), style->entries.front().key.id.value());
 }
 
@@ -266,7 +266,7 @@
   const CallSite call_site{ResourceNameRef("com.app.test", ResourceType::kString, "foo")};
   const SymbolTable::Symbol* symbol = ReferenceLinker::ResolveSymbolCheckVisibility(
       *test::BuildReference("com.app.test:string/foo"), call_site, &table, &error);
-  ASSERT_NE(nullptr, symbol);
+  ASSERT_THAT(symbol, NotNull());
   EXPECT_TRUE(error.empty());
 }
 
@@ -283,12 +283,12 @@
   std::string error;
   const CallSite call_site{ResourceNameRef("com.app.ext", ResourceType::kLayout, "foo")};
 
-  AAPT_EXPECT_FALSE(ReferenceLinker::CompileXmlAttribute(
+  EXPECT_FALSE(ReferenceLinker::CompileXmlAttribute(
       *test::BuildReference("com.app.test:attr/foo"), call_site, &table, &error));
   EXPECT_FALSE(error.empty());
 
   error = "";
-  AAPT_ASSERT_TRUE(ReferenceLinker::CompileXmlAttribute(
+  ASSERT_TRUE(ReferenceLinker::CompileXmlAttribute(
       *test::BuildReference("com.app.test:attr/public_foo"), call_site, &table, &error));
   EXPECT_TRUE(error.empty());
 }
diff --git a/tools/aapt2/link/XmlReferenceLinker_test.cpp b/tools/aapt2/link/XmlReferenceLinker_test.cpp
index de81e73..228cfb9 100644
--- a/tools/aapt2/link/XmlReferenceLinker_test.cpp
+++ b/tools/aapt2/link/XmlReferenceLinker_test.cpp
@@ -18,6 +18,9 @@
 
 #include "test/Test.h"
 
+using ::testing::IsNull;
+using ::testing::NotNull;
+
 namespace aapt {
 
 class XmlReferenceLinkerTest : public ::testing::Test {
@@ -90,56 +93,48 @@
   ASSERT_TRUE(linker.Consume(context_.get(), doc.get()));
 
   xml::Element* view_el = xml::FindRootElement(doc.get());
-  ASSERT_NE(nullptr, view_el);
+  ASSERT_THAT(view_el, NotNull());
 
   xml::Attribute* xml_attr = view_el->FindAttribute(xml::kSchemaAndroid, "layout_width");
-  ASSERT_NE(nullptr, xml_attr);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute.value().id);
-  EXPECT_EQ(ResourceId(0x01010000), xml_attr->compiled_attribute.value().id.value());
-  ASSERT_NE(nullptr, xml_attr->compiled_value);
-  ASSERT_NE(nullptr, ValueCast<BinaryPrimitive>(xml_attr->compiled_value.get()));
+  ASSERT_THAT(xml_attr, NotNull());
+  ASSERT_TRUE(xml_attr->compiled_attribute);
+  EXPECT_EQ(make_value(ResourceId(0x01010000)), xml_attr->compiled_attribute.value().id);
+  EXPECT_THAT(ValueCast<BinaryPrimitive>(xml_attr->compiled_value.get()), NotNull());
 
   xml_attr = view_el->FindAttribute(xml::kSchemaAndroid, "background");
-  ASSERT_NE(nullptr, xml_attr);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute.value().id);
-  EXPECT_EQ(ResourceId(0x01010001), xml_attr->compiled_attribute.value().id.value());
-  ASSERT_NE(nullptr, xml_attr->compiled_value);
+  ASSERT_THAT(xml_attr, NotNull());
+  ASSERT_TRUE(xml_attr->compiled_attribute);
+  EXPECT_EQ(make_value(ResourceId(0x01010001)), xml_attr->compiled_attribute.value().id);
   Reference* ref = ValueCast<Reference>(xml_attr->compiled_value.get());
-  ASSERT_NE(nullptr, ref);
-  AAPT_ASSERT_TRUE(ref->name);
-  EXPECT_EQ(test::ParseNameOrDie("color/green"), ref->name.value());  // Make sure the name
-                                                                      // didn't change.
-  AAPT_ASSERT_TRUE(ref->id);
-  EXPECT_EQ(ResourceId(0x7f020000), ref->id.value());
+  ASSERT_THAT(ref, NotNull());
+  EXPECT_EQ(make_value(test::ParseNameOrDie("color/green")), ref->name);  // Make sure the name
+                                                                          // didn't change.
+  EXPECT_EQ(make_value(ResourceId(0x7f020000)), ref->id);
 
   xml_attr = view_el->FindAttribute(xml::kSchemaAndroid, "text");
-  ASSERT_NE(nullptr, xml_attr);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute);
-  ASSERT_FALSE(xml_attr->compiled_value);  // Strings don't get compiled for memory sake.
+  ASSERT_THAT(xml_attr, NotNull());
+  EXPECT_TRUE(xml_attr->compiled_attribute);
+  EXPECT_THAT(xml_attr->compiled_value, IsNull());  // Strings don't get compiled for memory sake.
 
   xml_attr = view_el->FindAttribute(xml::kSchemaAndroid, "attr");
-  ASSERT_NE(nullptr, xml_attr);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute);
-  ASSERT_FALSE(xml_attr->compiled_value);  // Should be a plain string.
+  ASSERT_THAT(xml_attr, NotNull());
+  EXPECT_TRUE(xml_attr->compiled_attribute);
+  EXPECT_THAT(xml_attr->compiled_value, IsNull());  // Should be a plain string.
 
   xml_attr = view_el->FindAttribute("", "nonAaptAttr");
-  ASSERT_NE(nullptr, xml_attr);
-  AAPT_ASSERT_FALSE(xml_attr->compiled_attribute);
-  ASSERT_NE(nullptr, xml_attr->compiled_value);
-  ASSERT_NE(nullptr, ValueCast<BinaryPrimitive>(xml_attr->compiled_value.get()));
+  ASSERT_THAT(xml_attr, NotNull());
+  EXPECT_FALSE(xml_attr->compiled_attribute);
+  EXPECT_THAT(ValueCast<BinaryPrimitive>(xml_attr->compiled_value.get()), NotNull());
 
   xml_attr = view_el->FindAttribute("", "nonAaptAttrRef");
-  ASSERT_NE(nullptr, xml_attr);
-  AAPT_ASSERT_FALSE(xml_attr->compiled_attribute);
-  ASSERT_NE(nullptr, xml_attr->compiled_value);
-  ASSERT_NE(nullptr, ValueCast<Reference>(xml_attr->compiled_value.get()));
+  ASSERT_THAT(xml_attr, NotNull());
+  EXPECT_FALSE(xml_attr->compiled_attribute);
+  EXPECT_THAT(ValueCast<Reference>(xml_attr->compiled_value.get()), NotNull());
 
   xml_attr = view_el->FindAttribute("", "class");
-  ASSERT_NE(nullptr, xml_attr);
-  AAPT_ASSERT_FALSE(xml_attr->compiled_attribute);
-  ASSERT_EQ(nullptr, xml_attr->compiled_value);
+  ASSERT_THAT(xml_attr, NotNull());
+  EXPECT_FALSE(xml_attr->compiled_attribute);
+  EXPECT_THAT(xml_attr->compiled_value, IsNull());
 }
 
 TEST_F(XmlReferenceLinkerTest, PrivateSymbolsAreNotLinked) {
@@ -169,15 +164,14 @@
   ASSERT_TRUE(linker.Consume(context_.get(), doc.get()));
 
   xml::Element* view_el = xml::FindRootElement(doc.get());
-  ASSERT_NE(view_el, nullptr);
+  ASSERT_THAT(view_el, NotNull());
 
   xml::Attribute* xml_attr =
       view_el->FindAttribute(xml::BuildPackageNamespace("com.android.support"), "colorAccent");
-  ASSERT_NE(xml_attr, nullptr);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute.value().id);
-  EXPECT_EQ(xml_attr->compiled_attribute.value().id.value(), ResourceId(0x7f010001));
-  ASSERT_NE(ValueCast<BinaryPrimitive>(xml_attr->compiled_value.get()), nullptr);
+  ASSERT_THAT(xml_attr, NotNull());
+  ASSERT_TRUE(xml_attr->compiled_attribute);
+  EXPECT_EQ(make_value(ResourceId(0x7f010001)), xml_attr->compiled_attribute.value().id);
+  EXPECT_THAT(ValueCast<BinaryPrimitive>(xml_attr->compiled_value.get()), NotNull());
 }
 
 TEST_F(XmlReferenceLinkerTest, LinkAutoResReference) {
@@ -189,18 +183,16 @@
   ASSERT_TRUE(linker.Consume(context_.get(), doc.get()));
 
   xml::Element* view_el = xml::FindRootElement(doc.get());
-  ASSERT_NE(view_el, nullptr);
+  ASSERT_THAT(view_el, NotNull());
 
   xml::Attribute* xml_attr = view_el->FindAttribute(xml::kSchemaAuto, "colorAccent");
-  ASSERT_NE(xml_attr, nullptr);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute.value().id);
-  EXPECT_EQ(xml_attr->compiled_attribute.value().id.value(), ResourceId(0x7f010000));
+  ASSERT_THAT(xml_attr, NotNull());
+  ASSERT_TRUE(xml_attr->compiled_attribute);
+  EXPECT_EQ(make_value(ResourceId(0x7f010000)), xml_attr->compiled_attribute.value().id);
   Reference* ref = ValueCast<Reference>(xml_attr->compiled_value.get());
-  ASSERT_NE(ref, nullptr);
-  AAPT_ASSERT_TRUE(ref->name);
-  AAPT_ASSERT_TRUE(ref->id);
-  EXPECT_EQ(ref->id.value(), ResourceId(0x7f020001));
+  ASSERT_THAT(ref, NotNull());
+  ASSERT_TRUE(ref->name);
+  EXPECT_EQ(make_value(ResourceId(0x7f020001)), ref->id);
 }
 
 TEST_F(XmlReferenceLinkerTest, LinkViewWithShadowedPackageAlias) {
@@ -215,35 +207,31 @@
   ASSERT_TRUE(linker.Consume(context_.get(), doc.get()));
 
   xml::Element* view_el = xml::FindRootElement(doc.get());
-  ASSERT_NE(view_el, nullptr);
+  ASSERT_THAT(view_el, NotNull());
 
   // All attributes and references in this element should be referring to
   // "android" (0x01).
   xml::Attribute* xml_attr = view_el->FindAttribute(xml::kSchemaAndroid, "attr");
-  ASSERT_NE(xml_attr, nullptr);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute.value().id);
-  EXPECT_EQ(xml_attr->compiled_attribute.value().id.value(), ResourceId(0x01010002));
+  ASSERT_THAT(xml_attr, NotNull());
+  ASSERT_TRUE(xml_attr->compiled_attribute);
+  EXPECT_EQ(make_value(ResourceId(0x01010002)), xml_attr->compiled_attribute.value().id);
   Reference* ref = ValueCast<Reference>(xml_attr->compiled_value.get());
-  ASSERT_NE(ref, nullptr);
-  AAPT_ASSERT_TRUE(ref->id);
-  EXPECT_EQ(ref->id.value(), ResourceId(0x01030000));
+  ASSERT_THAT(ref, NotNull());
+  EXPECT_EQ(make_value(ResourceId(0x01030000)), ref->id);
 
   ASSERT_FALSE(view_el->GetChildElements().empty());
   view_el = view_el->GetChildElements().front();
-  ASSERT_NE(view_el, nullptr);
+  ASSERT_THAT(view_el, NotNull());
 
   // All attributes and references in this element should be referring to
   // "com.app.test" (0x7f).
   xml_attr = view_el->FindAttribute(xml::BuildPackageNamespace("com.app.test"), "attr");
-  ASSERT_NE(xml_attr, nullptr);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute.value().id);
-  EXPECT_EQ(xml_attr->compiled_attribute.value().id.value(), ResourceId(0x7f010002));
+  ASSERT_THAT(xml_attr, NotNull());
+  ASSERT_TRUE(xml_attr->compiled_attribute);
+  EXPECT_EQ(make_value(ResourceId(0x7f010002)), xml_attr->compiled_attribute.value().id);
   ref = ValueCast<Reference>(xml_attr->compiled_value.get());
-  ASSERT_NE(ref, nullptr);
-  AAPT_ASSERT_TRUE(ref->id);
-  EXPECT_EQ(ref->id.value(), ResourceId(0x7f030000));
+  ASSERT_THAT(ref, NotNull());
+  EXPECT_EQ(make_value(ResourceId(0x7f030000)), ref->id);
 }
 
 TEST_F(XmlReferenceLinkerTest, LinkViewWithLocalPackageAndAliasOfTheSameName) {
@@ -255,20 +243,17 @@
   ASSERT_TRUE(linker.Consume(context_.get(), doc.get()));
 
   xml::Element* view_el = xml::FindRootElement(doc.get());
-  ASSERT_NE(view_el, nullptr);
+  ASSERT_THAT(view_el, NotNull());
 
   // All attributes and references in this element should be referring to
   // "com.app.test" (0x7f).
-  xml::Attribute* xml_attr =
-      view_el->FindAttribute(xml::BuildPackageNamespace("com.app.test"), "attr");
-  ASSERT_NE(xml_attr, nullptr);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute);
-  AAPT_ASSERT_TRUE(xml_attr->compiled_attribute.value().id);
-  EXPECT_EQ(xml_attr->compiled_attribute.value().id.value(), ResourceId(0x7f010002));
+  xml::Attribute* xml_attr = view_el->FindAttribute(xml::BuildPackageNamespace("com.app.test"), "attr");
+  ASSERT_THAT(xml_attr, NotNull());
+  ASSERT_TRUE(xml_attr->compiled_attribute);
+  EXPECT_EQ(make_value(ResourceId(0x7f010002)), xml_attr->compiled_attribute.value().id);
   Reference* ref = ValueCast<Reference>(xml_attr->compiled_value.get());
-  ASSERT_NE(ref, nullptr);
-  AAPT_ASSERT_TRUE(ref->id);
-  EXPECT_EQ(ref->id.value(), ResourceId(0x7f030000));
+  ASSERT_THAT(ref, NotNull());
+  EXPECT_EQ(make_value(ResourceId(0x7f030000)), ref->id);
 }
 
 }  // namespace aapt
diff --git a/tools/aapt2/proto/TableProtoSerializer_test.cpp b/tools/aapt2/proto/TableProtoSerializer_test.cpp
index e6ce6d3..3ebb08e 100644
--- a/tools/aapt2/proto/TableProtoSerializer_test.cpp
+++ b/tools/aapt2/proto/TableProtoSerializer_test.cpp
@@ -20,6 +20,7 @@
 #include "test/Test.h"
 
 using ::google::protobuf::io::StringOutputStream;
+using ::testing::NotNull;
 
 namespace aapt {
 
@@ -46,8 +47,7 @@
 
   // Make a plural.
   std::unique_ptr<Plural> plural = util::make_unique<Plural>();
-  plural->values[Plural::One] =
-      util::make_unique<String>(table->string_pool.MakeRef("one"));
+  plural->values[Plural::One] = util::make_unique<String>(table->string_pool.MakeRef("one"));
   ASSERT_TRUE(table->AddResource(test::ParseNameOrDie("com.app.a:plurals/hey"),
                                  ConfigDescription{}, {}, std::move(plural),
                                  context->GetDiagnostics()));
@@ -77,19 +77,19 @@
                                  context->GetDiagnostics()));
 
   std::unique_ptr<pb::ResourceTable> pb_table = SerializeTableToPb(table.get());
-  ASSERT_NE(nullptr, pb_table);
+  ASSERT_THAT(pb_table, NotNull());
 
   std::unique_ptr<ResourceTable> new_table = DeserializeTableFromPb(
       *pb_table, Source{"test"}, context->GetDiagnostics());
-  ASSERT_NE(nullptr, new_table);
+  ASSERT_THAT(new_table, NotNull());
 
   Id* new_id = test::GetValue<Id>(new_table.get(), "com.app.a:id/foo");
-  ASSERT_NE(nullptr, new_id);
+  ASSERT_THAT(new_id, NotNull());
   EXPECT_EQ(id->IsWeak(), new_id->IsWeak());
 
   Maybe<ResourceTable::SearchResult> result =
       new_table->FindResource(test::ParseNameOrDie("com.app.a:layout/main"));
-  AAPT_ASSERT_TRUE(result);
+  ASSERT_TRUE(result);
   EXPECT_EQ(SymbolState::kPublic, result.value().type->symbol_status.state);
   EXPECT_EQ(SymbolState::kPublic, result.value().entry->symbol_status.state);
 
@@ -101,18 +101,18 @@
   // Find the product-dependent values
   BinaryPrimitive* prim = test::GetValueForConfigAndProduct<BinaryPrimitive>(
       new_table.get(), "com.app.a:integer/one", test::ParseConfigOrDie("land"), "");
-  ASSERT_NE(nullptr, prim);
+  ASSERT_THAT(prim, NotNull());
   EXPECT_EQ(123u, prim->value.data);
 
   prim = test::GetValueForConfigAndProduct<BinaryPrimitive>(
       new_table.get(), "com.app.a:integer/one", test::ParseConfigOrDie("land"), "tablet");
-  ASSERT_NE(nullptr, prim);
+  ASSERT_THAT(prim, NotNull());
   EXPECT_EQ(321u, prim->value.data);
 
   Reference* actual_ref = test::GetValue<Reference>(new_table.get(), "com.app.a:layout/abc");
-  ASSERT_NE(nullptr, actual_ref);
-  AAPT_ASSERT_TRUE(actual_ref->name);
-  AAPT_ASSERT_TRUE(actual_ref->id);
+  ASSERT_THAT(actual_ref, NotNull());
+  ASSERT_TRUE(actual_ref->name);
+  ASSERT_TRUE(actual_ref->id);
   EXPECT_EQ(expected_ref.name.value(), actual_ref->name.value());
   EXPECT_EQ(expected_ref.id.value(), actual_ref->id.value());
 }
@@ -159,7 +159,7 @@
 
   std::unique_ptr<ResourceFile> file = DeserializeCompiledFileFromPb(
       new_pb_file, Source("test"), context->GetDiagnostics());
-  ASSERT_NE(nullptr, file);
+  ASSERT_THAT(file, NotNull());
 
   uint64_t offset, len;
   ASSERT_TRUE(in_file_stream.ReadDataMetaData(&offset, &len));
@@ -171,16 +171,14 @@
   EXPECT_EQ(0u, offset & 0x03);
 
   ASSERT_EQ(1u, file->exported_symbols.size());
-  EXPECT_EQ(test::ParseNameOrDie("id/unchecked"),
-            file->exported_symbols[0].name);
+  EXPECT_EQ(test::ParseNameOrDie("id/unchecked"), file->exported_symbols[0].name);
 
   // Read the second compiled file.
 
   ASSERT_TRUE(in_file_stream.ReadCompiledFile(&new_pb_file));
 
-  file = DeserializeCompiledFileFromPb(new_pb_file, Source("test"),
-                                       context->GetDiagnostics());
-  ASSERT_NE(nullptr, file);
+  file = DeserializeCompiledFileFromPb(new_pb_file, Source("test"), context->GetDiagnostics());
+  ASSERT_THAT(file, NotNull());
 
   ASSERT_TRUE(in_file_stream.ReadDataMetaData(&offset, &len));
 
diff --git a/tools/aapt2/test/Builders.h b/tools/aapt2/test/Builders.h
index f3da780..6b82076 100644
--- a/tools/aapt2/test/Builders.h
+++ b/tools/aapt2/test/Builders.h
@@ -212,8 +212,7 @@
   }
 
   StyleBuilder& AddItem(const android::StringPiece& str, std::unique_ptr<Item> value) {
-    style_->entries.push_back(
-        Style::Entry{Reference(ParseNameOrDie(str)), std::move(value)});
+    style_->entries.push_back(Style::Entry{Reference(ParseNameOrDie(str)), std::move(value)});
     return *this;
   }
 
@@ -224,7 +223,9 @@
     return *this;
   }
 
-  std::unique_ptr<Style> Build() { return std::move(style_); }
+  std::unique_ptr<Style> Build() {
+    return std::move(style_);
+  }
 
  private:
   DISALLOW_COPY_AND_ASSIGN(StyleBuilder);
diff --git a/tools/aapt2/test/Common.h b/tools/aapt2/test/Common.h
index 0585148..bc8d274 100644
--- a/tools/aapt2/test/Common.h
+++ b/tools/aapt2/test/Common.h
@@ -34,15 +34,6 @@
 #include "io/File.h"
 #include "process/IResourceTableConsumer.h"
 
-//
-// GTEST 1.7 doesn't explicitly cast to bool, which causes explicit operators to
-// fail to compile.
-//
-#define AAPT_ASSERT_TRUE(v) ASSERT_TRUE(bool(v))
-#define AAPT_ASSERT_FALSE(v) ASSERT_FALSE(bool(v))
-#define AAPT_EXPECT_TRUE(v) EXPECT_TRUE(bool(v))
-#define AAPT_EXPECT_FALSE(v) EXPECT_FALSE(bool(v))
-
 namespace aapt {
 namespace test {
 
@@ -150,6 +141,10 @@
   return arg.Equals(&a);
 }
 
+MATCHER_P(StrValueEq, a, std::string(negation ? "isn't" : "is") + " equal to " + ::testing::PrintToString(a)) {
+  return *(arg.value) == a;
+}
+
 }  // namespace test
 }  // namespace aapt
 
diff --git a/tools/aapt2/util/BigBuffer_test.cpp b/tools/aapt2/util/BigBuffer_test.cpp
index 12c0b3e..a7776e3 100644
--- a/tools/aapt2/util/BigBuffer_test.cpp
+++ b/tools/aapt2/util/BigBuffer_test.cpp
@@ -18,12 +18,14 @@
 
 #include "test/Test.h"
 
+using ::testing::NotNull;
+
 namespace aapt {
 
 TEST(BigBufferTest, AllocateSingleBlock) {
   BigBuffer buffer(4);
 
-  EXPECT_NE(nullptr, buffer.NextBlock<char>(2));
+  EXPECT_THAT(buffer.NextBlock<char>(2), NotNull());
   EXPECT_EQ(2u, buffer.size());
 }
 
@@ -31,10 +33,10 @@
   BigBuffer buffer(16);
 
   char* b1 = buffer.NextBlock<char>(8);
-  EXPECT_NE(nullptr, b1);
+  EXPECT_THAT(b1, NotNull());
 
   char* b2 = buffer.NextBlock<char>(4);
-  EXPECT_NE(nullptr, b2);
+  EXPECT_THAT(b2, NotNull());
 
   EXPECT_EQ(b1 + 8, b2);
 }
@@ -42,7 +44,7 @@
 TEST(BigBufferTest, AllocateExactSizeBlockIfLargerThanBlockSize) {
   BigBuffer buffer(16);
 
-  EXPECT_NE(nullptr, buffer.NextBlock<char>(32));
+  EXPECT_THAT(buffer.NextBlock<char>(32), NotNull());
   EXPECT_EQ(32u, buffer.size());
 }
 
@@ -50,13 +52,13 @@
   BigBuffer buffer(16);
 
   uint32_t* b1 = buffer.NextBlock<uint32_t>();
-  ASSERT_NE(nullptr, b1);
+  ASSERT_THAT(b1, NotNull());
   *b1 = 33;
 
   {
     BigBuffer buffer2(16);
     b1 = buffer2.NextBlock<uint32_t>();
-    ASSERT_NE(nullptr, b1);
+    ASSERT_THAT(b1, NotNull());
     *b1 = 44;
 
     buffer.AppendBuffer(std::move(buffer2));
@@ -83,7 +85,7 @@
 TEST(BigBufferTest, PadAndAlignProperly) {
   BigBuffer buffer(16);
 
-  ASSERT_NE(buffer.NextBlock<char>(2), nullptr);
+  ASSERT_THAT(buffer.NextBlock<char>(2), NotNull());
   ASSERT_EQ(2u, buffer.size());
   buffer.Pad(2);
   ASSERT_EQ(4u, buffer.size());
diff --git a/tools/aapt2/util/Maybe_test.cpp b/tools/aapt2/util/Maybe_test.cpp
index ca14793..2057ddc 100644
--- a/tools/aapt2/util/Maybe_test.cpp
+++ b/tools/aapt2/util/Maybe_test.cpp
@@ -80,22 +80,22 @@
 
 TEST(MaybeTest, MakeNothing) {
   Maybe<int> val = make_nothing<int>();
-  AAPT_EXPECT_FALSE(val);
+  EXPECT_FALSE(val);
 
   Maybe<std::string> val2 = make_nothing<std::string>();
-  AAPT_EXPECT_FALSE(val2);
+  EXPECT_FALSE(val2);
 
   val2 = make_nothing<std::string>();
-  AAPT_EXPECT_FALSE(val2);
+  EXPECT_FALSE(val2);
 }
 
 TEST(MaybeTest, MakeSomething) {
   Maybe<int> val = make_value(23);
-  AAPT_ASSERT_TRUE(val);
+  ASSERT_TRUE(val);
   EXPECT_EQ(23, val.value());
 
   Maybe<std::string> val2 = make_value(std::string("hey"));
-  AAPT_ASSERT_TRUE(val2);
+  ASSERT_TRUE(val2);
   EXPECT_EQ(std::string("hey"), val2.value());
 }
 
diff --git a/tools/aapt2/util/Util_test.cpp b/tools/aapt2/util/Util_test.cpp
index e49aee5..a09001a 100644
--- a/tools/aapt2/util/Util_test.cpp
+++ b/tools/aapt2/util/Util_test.cpp
@@ -147,54 +147,48 @@
 
 TEST(UtilTest, FullyQualifiedClassName) {
   Maybe<std::string> res = util::GetFullyQualifiedClassName("android", ".asdf");
-  AAPT_ASSERT_TRUE(res);
+  ASSERT_TRUE(res);
   EXPECT_EQ(res.value(), "android.asdf");
 
   res = util::GetFullyQualifiedClassName("android", ".a.b");
-  AAPT_ASSERT_TRUE(res);
+  ASSERT_TRUE(res);
   EXPECT_EQ(res.value(), "android.a.b");
 
   res = util::GetFullyQualifiedClassName("android", "a.b");
-  AAPT_ASSERT_TRUE(res);
+  ASSERT_TRUE(res);
   EXPECT_EQ(res.value(), "a.b");
 
   res = util::GetFullyQualifiedClassName("", "a.b");
-  AAPT_ASSERT_TRUE(res);
+  ASSERT_TRUE(res);
   EXPECT_EQ(res.value(), "a.b");
 
   res = util::GetFullyQualifiedClassName("android", "Class");
-  AAPT_ASSERT_TRUE(res);
+  ASSERT_TRUE(res);
   EXPECT_EQ(res.value(), "android.Class");
 
   res = util::GetFullyQualifiedClassName("", "");
-  AAPT_ASSERT_FALSE(res);
+  ASSERT_FALSE(res);
 
   res = util::GetFullyQualifiedClassName("android", "./Apple");
-  AAPT_ASSERT_FALSE(res);
+  ASSERT_FALSE(res);
 }
 
 TEST(UtilTest, ExtractResourcePathComponents) {
   StringPiece prefix, entry, suffix;
-  ASSERT_TRUE(util::ExtractResFilePathParts("res/xml-sw600dp/entry.xml",
-                                            &prefix, &entry, &suffix));
+  ASSERT_TRUE(util::ExtractResFilePathParts("res/xml-sw600dp/entry.xml", &prefix, &entry, &suffix));
   EXPECT_EQ(prefix, "res/xml-sw600dp/");
   EXPECT_EQ(entry, "entry");
   EXPECT_EQ(suffix, ".xml");
 
-  ASSERT_TRUE(util::ExtractResFilePathParts("res/xml-sw600dp/entry.9.png",
-                                            &prefix, &entry, &suffix));
-
+  ASSERT_TRUE(util::ExtractResFilePathParts("res/xml-sw600dp/entry.9.png", &prefix, &entry, &suffix));
   EXPECT_EQ(prefix, "res/xml-sw600dp/");
   EXPECT_EQ(entry, "entry");
   EXPECT_EQ(suffix, ".9.png");
 
-  EXPECT_FALSE(util::ExtractResFilePathParts("AndroidManifest.xml", &prefix,
-                                             &entry, &suffix));
-  EXPECT_FALSE(
-      util::ExtractResFilePathParts("res/.xml", &prefix, &entry, &suffix));
+  EXPECT_FALSE(util::ExtractResFilePathParts("AndroidManifest.xml", &prefix, &entry, &suffix));
+  EXPECT_FALSE(util::ExtractResFilePathParts("res/.xml", &prefix, &entry, &suffix));
 
-  ASSERT_TRUE(
-      util::ExtractResFilePathParts("res//.", &prefix, &entry, &suffix));
+  ASSERT_TRUE(util::ExtractResFilePathParts("res//.", &prefix, &entry, &suffix));
   EXPECT_EQ(prefix, "res//");
   EXPECT_EQ(entry, "");
   EXPECT_EQ(suffix, ".");
diff --git a/tools/aapt2/xml/XmlActionExecutor_test.cpp b/tools/aapt2/xml/XmlActionExecutor_test.cpp
index 7110c90..0fe7ab0 100644
--- a/tools/aapt2/xml/XmlActionExecutor_test.cpp
+++ b/tools/aapt2/xml/XmlActionExecutor_test.cpp
@@ -18,6 +18,8 @@
 
 #include "test/Test.h"
 
+using ::testing::NotNull;
+
 namespace aapt {
 namespace xml {
 
@@ -42,12 +44,11 @@
       test::BuildXmlDom("<manifest><application /></manifest>");
 
   StdErrDiagnostics diag;
-  ASSERT_TRUE(
-      executor.Execute(XmlActionExecutorPolicy::kNone, &diag, doc.get()));
-  ASSERT_NE(nullptr, manifest_el);
+  ASSERT_TRUE(executor.Execute(XmlActionExecutorPolicy::kNone, &diag, doc.get()));
+  ASSERT_THAT(manifest_el, NotNull());
   EXPECT_EQ(std::string("manifest"), manifest_el->name);
 
-  ASSERT_NE(nullptr, application_el);
+  ASSERT_THAT(application_el, NotNull());
   EXPECT_EQ(std::string("application"), application_el->name);
 }
 
@@ -58,8 +59,7 @@
   std::unique_ptr<XmlResource> doc =
       test::BuildXmlDom("<manifest><application /><activity /></manifest>");
   StdErrDiagnostics diag;
-  ASSERT_FALSE(
-      executor.Execute(XmlActionExecutorPolicy::kWhitelist, &diag, doc.get()));
+  ASSERT_FALSE(executor.Execute(XmlActionExecutorPolicy::kWhitelist, &diag, doc.get()));
 }
 
 }  // namespace xml
diff --git a/tools/aapt2/xml/XmlDom_test.cpp b/tools/aapt2/xml/XmlDom_test.cpp
index fb18ea3..c1aa10b 100644
--- a/tools/aapt2/xml/XmlDom_test.cpp
+++ b/tools/aapt2/xml/XmlDom_test.cpp
@@ -21,6 +21,8 @@
 
 #include "test/Test.h"
 
+using ::testing::NotNull;
+
 namespace aapt {
 
 constexpr const char* kXmlPreamble =
@@ -41,10 +43,10 @@
   const Source source = {"test.xml"};
   StdErrDiagnostics diag;
   std::unique_ptr<xml::XmlResource> doc = xml::Inflate(&in, &diag, source);
-  ASSERT_NE(doc, nullptr);
+  ASSERT_THAT(doc, NotNull());
 
   xml::Namespace* ns = xml::NodeCast<xml::Namespace>(doc->root.get());
-  ASSERT_NE(ns, nullptr);
+  ASSERT_THAT(ns, NotNull());
   EXPECT_EQ(ns->namespace_uri, xml::kSchemaAndroid);
   EXPECT_EQ(ns->namespace_prefix, "android");
 }
@@ -55,19 +57,19 @@
       <element value="\?hello" pattern="\\d{5}">\\d{5}</element>)EOF");
 
   xml::Element* el = xml::FindRootElement(doc->root.get());
-  ASSERT_NE(nullptr, el);
+  ASSERT_THAT(el, NotNull());
 
   xml::Attribute* attr = el->FindAttribute({}, "pattern");
-  ASSERT_NE(nullptr, attr);
+  ASSERT_THAT(attr, NotNull());
   EXPECT_EQ("\\\\d{5}", attr->value);
 
   attr = el->FindAttribute({}, "value");
-  ASSERT_NE(nullptr, attr);
+  ASSERT_THAT(attr, NotNull());
   EXPECT_EQ("\\?hello", attr->value);
 
   ASSERT_EQ(1u, el->children.size());
   xml::Text* text = xml::NodeCast<xml::Text>(el->children[0].get());
-  ASSERT_NE(nullptr, text);
+  ASSERT_THAT(text, NotNull());
   EXPECT_EQ("\\\\d{5}", text->text);
 }
 
diff --git a/tools/aapt2/xml/XmlUtil_test.cpp b/tools/aapt2/xml/XmlUtil_test.cpp
index 5eecc8f..cbded8f 100644
--- a/tools/aapt2/xml/XmlUtil_test.cpp
+++ b/tools/aapt2/xml/XmlUtil_test.cpp
@@ -21,37 +21,30 @@
 namespace aapt {
 
 TEST(XmlUtilTest, ExtractPackageFromNamespace) {
-  AAPT_ASSERT_FALSE(xml::ExtractPackageFromNamespace("com.android"));
-  AAPT_ASSERT_FALSE(
-      xml::ExtractPackageFromNamespace("http://schemas.android.com/apk"));
-  AAPT_ASSERT_FALSE(
-      xml::ExtractPackageFromNamespace("http://schemas.android.com/apk/res"));
-  AAPT_ASSERT_FALSE(
-      xml::ExtractPackageFromNamespace("http://schemas.android.com/apk/res/"));
-  AAPT_ASSERT_FALSE(xml::ExtractPackageFromNamespace(
-      "http://schemas.android.com/apk/prv/res/"));
+  ASSERT_FALSE(xml::ExtractPackageFromNamespace("com.android"));
+  ASSERT_FALSE(xml::ExtractPackageFromNamespace("http://schemas.android.com/apk"));
+  ASSERT_FALSE(xml::ExtractPackageFromNamespace("http://schemas.android.com/apk/res"));
+  ASSERT_FALSE(xml::ExtractPackageFromNamespace("http://schemas.android.com/apk/res/"));
+  ASSERT_FALSE(xml::ExtractPackageFromNamespace("http://schemas.android.com/apk/prv/res/"));
 
   Maybe<xml::ExtractedPackage> p =
       xml::ExtractPackageFromNamespace("http://schemas.android.com/apk/res/a");
-  AAPT_ASSERT_TRUE(p);
+  ASSERT_TRUE(p);
   EXPECT_EQ(std::string("a"), p.value().package);
   EXPECT_FALSE(p.value().private_namespace);
 
-  p = xml::ExtractPackageFromNamespace(
-      "http://schemas.android.com/apk/prv/res/android");
-  AAPT_ASSERT_TRUE(p);
+  p = xml::ExtractPackageFromNamespace("http://schemas.android.com/apk/prv/res/android");
+  ASSERT_TRUE(p);
   EXPECT_EQ(std::string("android"), p.value().package);
   EXPECT_TRUE(p.value().private_namespace);
 
-  p = xml::ExtractPackageFromNamespace(
-      "http://schemas.android.com/apk/prv/res/com.test");
-  AAPT_ASSERT_TRUE(p);
+  p = xml::ExtractPackageFromNamespace("http://schemas.android.com/apk/prv/res/com.test");
+  ASSERT_TRUE(p);
   EXPECT_EQ(std::string("com.test"), p.value().package);
   EXPECT_TRUE(p.value().private_namespace);
 
-  p = xml::ExtractPackageFromNamespace(
-      "http://schemas.android.com/apk/res-auto");
-  AAPT_ASSERT_TRUE(p);
+  p = xml::ExtractPackageFromNamespace("http://schemas.android.com/apk/res-auto");
+  ASSERT_TRUE(p);
   EXPECT_EQ(std::string(), p.value().package);
   EXPECT_TRUE(p.value().private_namespace);
 }
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareSession.java b/wifi/java/android/net/wifi/aware/WifiAwareSession.java
index babbed0..428c8bb 100644
--- a/wifi/java/android/net/wifi/aware/WifiAwareSession.java
+++ b/wifi/java/android/net/wifi/aware/WifiAwareSession.java
@@ -67,6 +67,7 @@
      * An application may re-attach after a destroy using
      * {@link WifiAwareManager#attach(AttachCallback, Handler)} .
      */
+    @Override
     public void close() {
         WifiAwareManager mgr = mMgr.get();
         if (mgr == null) {
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pManager.java b/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
index 7f085f71..f596eef 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
@@ -683,7 +683,7 @@
         private DnsSdTxtRecordListener mDnsSdTxtListener;
         private UpnpServiceResponseListener mUpnpServRspListener;
         private HashMap<Integer, Object> mListenerMap = new HashMap<Integer, Object>();
-        private Object mListenerMapLock = new Object();
+        private final Object mListenerMapLock = new Object();
         private int mListenerKey = 0;
 
         private AsyncChannel mAsyncChannel;