Merge "Set system gesture exclusion rects for Bubbles" into qt-dev am: 0f6b976405
am: 0b0b2787f7

Change-Id: I3a010ad7e9cf766658b1dcdbe0e14bcdfb49bedc
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index 4b0b8cb..2946e5f 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -333,7 +333,9 @@
     public static int resolveFirstUnrestrictedUidState(int op) {
         switch (op) {
             case OP_FINE_LOCATION:
-            case OP_COARSE_LOCATION: {
+            case OP_COARSE_LOCATION:
+            case OP_MONITOR_LOCATION:
+            case OP_MONITOR_HIGH_POWER_LOCATION: {
                 return UID_STATE_FOREGROUND_SERVICE_LOCATION;
             }
         }
diff --git a/core/java/android/app/ApplicationLoaders.java b/core/java/android/app/ApplicationLoaders.java
index 2e59b90..faa30f3 100644
--- a/core/java/android/app/ApplicationLoaders.java
+++ b/core/java/android/app/ApplicationLoaders.java
@@ -145,7 +145,8 @@
      */
     public void createAndCacheNonBootclasspathSystemClassLoaders(SharedLibraryInfo[] libs) {
         if (mSystemLibsCacheMap != null) {
-            throw new IllegalStateException("Already cached.");
+            Log.wtf(TAG, "Already cached.");
+            return;
         }
 
         mSystemLibsCacheMap = new HashMap<String, CachedClassLoader>();
@@ -158,8 +159,7 @@
     /**
      * Caches a single non-bootclasspath class loader.
      *
-     * All of this library's dependencies must have previously been cached. Otherwise, an exception
-     * is thrown.
+     * All of this library's dependencies must have previously been cached.
      */
     private void createAndCacheNonBootclasspathSystemClassLoader(SharedLibraryInfo lib) {
         String path = lib.getPath();
@@ -174,8 +174,9 @@
                 CachedClassLoader cached = mSystemLibsCacheMap.get(dependencyPath);
 
                 if (cached == null) {
-                    throw new IllegalStateException("Failed to find dependency " + dependencyPath
-                            + " of cachedlibrary " + path);
+                    Log.e(TAG, "Failed to find dependency " + dependencyPath
+                            + " of cached library " + path);
+                    return;
                 }
 
                 sharedLibraries.add(cached.loader);
@@ -188,8 +189,8 @@
                 null /*cacheKey*/, null /*classLoaderName*/, sharedLibraries /*sharedLibraries*/);
 
         if (classLoader == null) {
-            // bad configuration or break in classloading code
-            throw new IllegalStateException("Failed to cache " + path);
+            Log.e(TAG, "Failed to cache " + path);
+            return;
         }
 
         CachedClassLoader cached = new CachedClassLoader();
@@ -214,7 +215,7 @@
      *
      * If there is an error or the cache is not available, this returns null.
      */
-    public ClassLoader getCachedNonBootclasspathSystemLib(String zip, ClassLoader parent,
+    private ClassLoader getCachedNonBootclasspathSystemLib(String zip, ClassLoader parent,
             String classLoaderName, List<ClassLoader> sharedLibraries) {
         if (mSystemLibsCacheMap == null) {
             return null;
diff --git a/core/java/android/hardware/display/ColorDisplayManager.java b/core/java/android/hardware/display/ColorDisplayManager.java
index 0c07a67..ce71db6 100644
--- a/core/java/android/hardware/display/ColorDisplayManager.java
+++ b/core/java/android/hardware/display/ColorDisplayManager.java
@@ -392,6 +392,26 @@
     }
 
     /**
+     * Enables or disables display white balance.
+     *
+     * @hide
+     */
+    @RequiresPermission(android.Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS)
+    public boolean setDisplayWhiteBalanceEnabled(boolean enabled) {
+        return mManager.setDisplayWhiteBalanceEnabled(enabled);
+    }
+
+    /**
+     * Returns whether display white balance is currently enabled. Even if enabled, it may or may
+     * not be active, if another transform with higher priority is active.
+     *
+     * @hide
+     */
+    public boolean isDisplayWhiteBalanceEnabled() {
+        return mManager.isDisplayWhiteBalanceEnabled();
+    }
+
+    /**
      * Returns {@code true} if Night Display is supported by the device.
      *
      * @hide
@@ -616,6 +636,22 @@
             }
         }
 
+        boolean isDisplayWhiteBalanceEnabled() {
+            try {
+                return mCdm.isDisplayWhiteBalanceEnabled();
+            } catch (RemoteException e) {
+                throw e.rethrowFromSystemServer();
+            }
+        }
+
+        boolean setDisplayWhiteBalanceEnabled(boolean enabled) {
+            try {
+                return mCdm.setDisplayWhiteBalanceEnabled(enabled);
+            } catch (RemoteException e) {
+                throw e.rethrowFromSystemServer();
+            }
+        }
+
         int getColorMode() {
             try {
                 return mCdm.getColorMode();
diff --git a/core/java/android/hardware/display/IColorDisplayManager.aidl b/core/java/android/hardware/display/IColorDisplayManager.aidl
index 88b59a6..7b1033d 100644
--- a/core/java/android/hardware/display/IColorDisplayManager.aidl
+++ b/core/java/android/hardware/display/IColorDisplayManager.aidl
@@ -42,4 +42,7 @@
 
     int getColorMode();
     void setColorMode(int colorMode);
+
+    boolean isDisplayWhiteBalanceEnabled();
+    boolean setDisplayWhiteBalanceEnabled(boolean enabled);
 }
\ No newline at end of file
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index 00d522b..ecd16dd 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -266,8 +266,11 @@
      *   - Fixed bug in min learned capacity updating process.
      * New in version 34:
      *   - Deprecated STATS_SINCE_UNPLUGGED and STATS_CURRENT.
+     * New in version 35:
+     *   - Fixed bug that was not reporting high cellular tx power correctly
+     *   - Added out of service and emergency service modes to data connection types
      */
-    static final int CHECKIN_VERSION = 34;
+    static final int CHECKIN_VERSION = 35;
 
     /**
      * Old version, we hit 9 and ran out of room, need to remove.
@@ -2371,18 +2374,21 @@
      */
     public abstract int getMobileRadioActiveUnknownCount(int which);
 
-    public static final int DATA_CONNECTION_NONE = 0;
-    public static final int DATA_CONNECTION_OTHER = TelephonyManager.MAX_NETWORK_TYPE + 1;
+    public static final int DATA_CONNECTION_OUT_OF_SERVICE = 0;
+    public static final int DATA_CONNECTION_EMERGENCY_SERVICE =
+            TelephonyManager.MAX_NETWORK_TYPE + 1;
+    public static final int DATA_CONNECTION_OTHER = DATA_CONNECTION_EMERGENCY_SERVICE + 1;
+
 
     static final String[] DATA_CONNECTION_NAMES = {
-        "none", "gprs", "edge", "umts", "cdma", "evdo_0", "evdo_A",
+        "oos", "gprs", "edge", "umts", "cdma", "evdo_0", "evdo_A",
         "1xrtt", "hsdpa", "hsupa", "hspa", "iden", "evdo_b", "lte",
         "ehrpd", "hspap", "gsm", "td_scdma", "iwlan", "lte_ca", "nr",
-        "other"
+        "emngcy", "other"
     };
 
     @UnsupportedAppUsage
-    public static final int NUM_DATA_CONNECTION_TYPES = DATA_CONNECTION_OTHER+1;
+    public static final int NUM_DATA_CONNECTION_TYPES = DATA_CONNECTION_OTHER + 1;
 
     /**
      * Returns the time in microseconds that the phone has been running with
@@ -6564,6 +6570,10 @@
                 }
                 oldState = rec.states;
                 oldState2 = rec.states2;
+                // Clear High Tx Power Flag for volta positioning
+                if ((rec.states2 & HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG) != 0) {
+                    rec.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
+                }
             }
 
             return item.toString();
@@ -7865,9 +7875,9 @@
         // Phone data connection (DATA_CONNECTION_TIME_DATA and DATA_CONNECTION_COUNT_DATA)
         for (int i = 0; i < NUM_DATA_CONNECTION_TYPES; ++i) {
             // Map OTHER to TelephonyManager.NETWORK_TYPE_UNKNOWN and mark NONE as a boolean.
-            boolean isNone = (i == DATA_CONNECTION_NONE);
+            boolean isNone = (i == DATA_CONNECTION_OUT_OF_SERVICE);
             int telephonyNetworkType = i;
-            if (i == DATA_CONNECTION_OTHER) {
+            if (i == DATA_CONNECTION_OTHER || i == DATA_CONNECTION_EMERGENCY_SERVICE) {
                 telephonyNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
             }
             final long pdcToken = proto.start(SystemProto.DATA_CONNECTION);
diff --git a/core/java/android/os/ZygoteProcess.java b/core/java/android/os/ZygoteProcess.java
index 3420007..bd70f23 100644
--- a/core/java/android/os/ZygoteProcess.java
+++ b/core/java/android/os/ZygoteProcess.java
@@ -77,9 +77,11 @@
     private static final String LOG_TAG = "ZygoteProcess";
 
     /**
-     * The default value for enabling the unspecialized app process (USAP) pool.
+     * The default value for enabling the unspecialized app process (USAP) pool.  This value will
+     * not be used if the devices has a DeviceConfig profile pushed to it that contains a value for
+     * this key.
      */
-    private static final String USAP_POOL_ENABLED_DEFAULT = "false";
+    private static final String USAP_POOL_ENABLED_DEFAULT = "true";
 
     /**
      * The name of the socket used to communicate with the primary zygote.
diff --git a/core/java/android/view/InsetsSourceConsumer.java b/core/java/android/view/InsetsSourceConsumer.java
index 1383463..a780158 100644
--- a/core/java/android/view/InsetsSourceConsumer.java
+++ b/core/java/android/view/InsetsSourceConsumer.java
@@ -153,6 +153,7 @@
             return;
         }
         mVisible = visible;
+        applyHiddenToControl();
         applyLocalVisibilityOverride();
         mController.notifyVisibilityChanged();
     }
diff --git a/core/java/com/android/internal/app/IBatteryStats.aidl b/core/java/com/android/internal/app/IBatteryStats.aidl
index 114d31f..9f860e2 100644
--- a/core/java/com/android/internal/app/IBatteryStats.aidl
+++ b/core/java/com/android/internal/app/IBatteryStats.aidl
@@ -106,7 +106,7 @@
     void notePhoneOn();
     void notePhoneOff();
     void notePhoneSignalStrength(in SignalStrength signalStrength);
-    void notePhoneDataConnectionState(int dataType, boolean hasData);
+    void notePhoneDataConnectionState(int dataType, boolean hasData, int serviceType);
     void notePhoneState(int phoneState);
     void noteWifiOn();
     void noteWifiOff();
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 1fc7635..8f37d81 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -907,8 +907,6 @@
     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
     protected StopwatchTimer mBluetoothScanTimer;
 
-    boolean mIsCellularTxPowerHigh = false;
-
     int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
     long mMobileRadioActiveStartTime;
     StopwatchTimer mMobileRadioActiveTimer;
@@ -5275,16 +5273,26 @@
     }
 
     @UnsupportedAppUsage
-    public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
+    public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData, int serviceType) {
         // BatteryStats uses 0 to represent no network type.
         // Telephony does not have a concept of no network type, and uses 0 to represent unknown.
         // Unknown is included in DATA_CONNECTION_OTHER.
-        int bin = DATA_CONNECTION_NONE;
+        int bin = DATA_CONNECTION_OUT_OF_SERVICE;
         if (hasData) {
             if (dataType > 0 && dataType <= TelephonyManager.MAX_NETWORK_TYPE) {
                 bin = dataType;
             } else {
-                bin = DATA_CONNECTION_OTHER;
+                switch (serviceType) {
+                    case ServiceState.STATE_OUT_OF_SERVICE:
+                        bin = DATA_CONNECTION_OUT_OF_SERVICE;
+                        break;
+                    case ServiceState.STATE_EMERGENCY_ONLY:
+                        bin = DATA_CONNECTION_EMERGENCY_SERVICE;
+                        break;
+                    default:
+                        bin = DATA_CONNECTION_OTHER;
+                        break;
+                }
             }
         }
         if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
@@ -11198,19 +11206,9 @@
             }
         }
         if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
-            if (!mIsCellularTxPowerHigh) {
-                mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
-                addHistoryRecordLocked(elapsedRealtime, uptime);
-                mIsCellularTxPowerHigh = true;
-            }
-            return;
-        }
-        if (mIsCellularTxPowerHigh) {
-            mHistoryCur.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
+            mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
             addHistoryRecordLocked(elapsedRealtime, uptime);
-            mIsCellularTxPowerHigh = false;
         }
-        return;
     }
 
     private final class BluetoothActivityInfoCache {
@@ -13670,7 +13668,6 @@
         mCameraOnTimer.readSummaryFromParcelLocked(in);
         mBluetoothScanNesting = 0;
         mBluetoothScanTimer.readSummaryFromParcelLocked(in);
-        mIsCellularTxPowerHigh = false;
 
         int NRPMS = in.readInt();
         if (NRPMS > 10000) {
@@ -14654,7 +14651,6 @@
         mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
         mBluetoothScanNesting = 0;
         mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
-        mIsCellularTxPowerHigh = false;
         mDischargeUnplugLevel = in.readInt();
         mDischargePlugLevel = in.readInt();
         mDischargeCurrentLevel = in.readInt();
diff --git a/core/jni/android_view_CompositionSamplingListener.cpp b/core/jni/android_view_CompositionSamplingListener.cpp
index 1c885e3..d489ae0 100644
--- a/core/jni/android_view_CompositionSamplingListener.cpp
+++ b/core/jni/android_view_CompositionSamplingListener.cpp
@@ -43,15 +43,22 @@
 
 struct CompositionSamplingListener : public BnRegionSamplingListener {
     CompositionSamplingListener(JNIEnv* env, jobject listener)
-            : mListener(env->NewGlobalRef(listener)) {}
+            : mListener(env->NewWeakGlobalRef(listener)) {}
 
     void onSampleCollected(float medianLuma) override {
         JNIEnv* env = AndroidRuntime::getJNIEnv();
         LOG_ALWAYS_FATAL_IF(env == nullptr, "Unable to retrieve JNIEnv in onSampleCollected.");
 
+        jobject listener = env->NewGlobalRef(mListener);
+        if (listener == NULL) {
+            // Weak reference went out of scope
+            return;
+        }
         env->CallStaticVoidMethod(gListenerClassInfo.mClass,
-                gListenerClassInfo.mDispatchOnSampleCollected, mListener,
+                gListenerClassInfo.mDispatchOnSampleCollected, listener,
                 static_cast<jfloat>(medianLuma));
+        env->DeleteGlobalRef(listener);
+
         if (env->ExceptionCheck()) {
             ALOGE("CompositionSamplingListener.onSampleCollected() failed.");
             LOGE_EX(env);
@@ -62,11 +69,11 @@
 protected:
     virtual ~CompositionSamplingListener() {
         JNIEnv* env = AndroidRuntime::getJNIEnv();
-        env->DeleteGlobalRef(mListener);
+        env->DeleteWeakGlobalRef(mListener);
     }
 
 private:
-    jobject mListener;
+    jweak mListener;
 };
 
 jlong nativeCreate(JNIEnv* env, jclass clazz, jobject obj) {
diff --git a/core/proto/android/stats/enums.proto b/core/proto/android/stats/enums.proto
index 2320a01..8f8055e 100644
--- a/core/proto/android/stats/enums.proto
+++ b/core/proto/android/stats/enums.proto
@@ -22,4 +22,8 @@
 enum EventType {
   // Unknown.
   TYPE_UNKNOWN = 0;
+  CONTENT_SUGGESTIONS_CLASSIFY_CONTENT_CALL_SUCCEEDED = 1;
+  CONTENT_SUGGESTIONS_CLASSIFY_CONTENT_CALL_FAILED = 2;
+  CONTENT_SUGGESTIONS_SUGGEST_CONTENT_CALL_SUCCEEDED = 3;
+  CONTENT_SUGGESTIONS_SUGGEST_CONTENT_CALL_FAILED = 4;
 }
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index fb92fbf..c7a60cf 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -3440,6 +3440,11 @@
     <permission android:name="android.permission.OBSERVE_ROLE_HOLDERS"
                 android:protectionLevel="signature|installer" />
 
+    <!-- Allows an application to manage the companion devices.
+         @hide -->
+    <permission android:name="android.permission.MANAGE_COMPANION_DEVICES"
+                android:protectionLevel="signature" />
+
     <!-- @SystemApi Allows an application to use SurfaceFlinger's low level features.
          <p>Not for use by third-party applications.
          @hide
diff --git a/core/tests/coretests/src/android/app/ApplicationLoadersTest.java b/core/tests/coretests/src/android/app/ApplicationLoadersTest.java
deleted file mode 100644
index 5aee4d3..0000000
--- a/core/tests/coretests/src/android/app/ApplicationLoadersTest.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.app;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-
-import android.content.pm.SharedLibraryInfo;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.ArrayList;
-
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class ApplicationLoadersTest {
-
-    // a library installed onto the device with no dependencies
-    private static final String LIB_A = "/system/framework/android.hidl.base-V1.0-java.jar";
-    // a library installed onto the device which only depends on A
-    private static final String LIB_DEP_A = "/system/framework/android.hidl.manager-V1.0-java.jar";
-
-    private static SharedLibraryInfo createLib(String zip) {
-        return new SharedLibraryInfo(
-                zip, null /*packageName*/, null /*codePaths*/, null /*name*/, 0 /*version*/,
-                SharedLibraryInfo.TYPE_BUILTIN, null /*declaringPackage*/,
-                null /*dependentPackages*/, null /*dependencies*/);
-    }
-
-    @Test
-    public void testGetNonExistentLib() {
-        ApplicationLoaders loaders = new ApplicationLoaders();
-        assertEquals(null, loaders.getCachedNonBootclasspathSystemLib(
-                "/system/framework/nonexistentlib.jar", null, null, null));
-    }
-
-    @Test
-    public void testCacheExistentLib() {
-        ApplicationLoaders loaders = new ApplicationLoaders();
-        SharedLibraryInfo libA = createLib(LIB_A);
-
-        loaders.createAndCacheNonBootclasspathSystemClassLoaders(new SharedLibraryInfo[]{libA});
-
-        assertNotEquals(null, loaders.getCachedNonBootclasspathSystemLib(
-                LIB_A, null, null, null));
-    }
-
-    @Test
-    public void testNonNullParent() {
-        ApplicationLoaders loaders = new ApplicationLoaders();
-        SharedLibraryInfo libA = createLib(LIB_A);
-
-        ClassLoader parent = ClassLoader.getSystemClassLoader();
-        assertNotEquals(null, parent);
-
-        loaders.createAndCacheNonBootclasspathSystemClassLoaders(new SharedLibraryInfo[]{libA});
-
-        assertEquals(null, loaders.getCachedNonBootclasspathSystemLib(
-                LIB_A, parent, null, null));
-    }
-
-    @Test
-    public void testNonNullClassLoaderNamespace() {
-        ApplicationLoaders loaders = new ApplicationLoaders();
-        SharedLibraryInfo libA = createLib(LIB_A);
-
-        loaders.createAndCacheNonBootclasspathSystemClassLoaders(new SharedLibraryInfo[]{libA});
-
-        assertEquals(null, loaders.getCachedNonBootclasspathSystemLib(
-                LIB_A, null, "other classloader", null));
-    }
-
-    @Test
-    public void testDifferentSharedLibraries() {
-        ApplicationLoaders loaders = new ApplicationLoaders();
-        SharedLibraryInfo libA = createLib(LIB_A);
-
-        // any other existent lib
-        ClassLoader dep = ClassLoader.getSystemClassLoader();
-        ArrayList<ClassLoader> sharedLibraries = new ArrayList<>();
-        sharedLibraries.add(dep);
-
-        loaders.createAndCacheNonBootclasspathSystemClassLoaders(new SharedLibraryInfo[]{libA});
-
-        assertEquals(null, loaders.getCachedNonBootclasspathSystemLib(
-                LIB_A, null, null, sharedLibraries));
-    }
-
-    @Test
-    public void testDependentLibs() {
-        ApplicationLoaders loaders = new ApplicationLoaders();
-        SharedLibraryInfo libA = createLib(LIB_A);
-        SharedLibraryInfo libB = createLib(LIB_DEP_A);
-        libB.addDependency(libA);
-
-        loaders.createAndCacheNonBootclasspathSystemClassLoaders(
-                new SharedLibraryInfo[]{libA, libB});
-
-        ClassLoader loadA = loaders.getCachedNonBootclasspathSystemLib(
-                LIB_A, null, null, null);
-        assertNotEquals(null, loadA);
-
-        ArrayList<ClassLoader> sharedLibraries = new ArrayList<>();
-        sharedLibraries.add(loadA);
-
-        assertNotEquals(null, loaders.getCachedNonBootclasspathSystemLib(
-                LIB_DEP_A, null, null, sharedLibraries));
-    }
-
-    @Test(expected = IllegalStateException.class)
-    public void testDependentLibsWrongOrder() {
-        ApplicationLoaders loaders = new ApplicationLoaders();
-        SharedLibraryInfo libA = createLib(LIB_A);
-        SharedLibraryInfo libB = createLib(LIB_DEP_A);
-        libB.addDependency(libA);
-
-        loaders.createAndCacheNonBootclasspathSystemClassLoaders(
-                new SharedLibraryInfo[]{libB, libA});
-    }
-}
diff --git a/libs/androidfw/Asset.cpp b/libs/androidfw/Asset.cpp
index 9a95fdf..92125c9 100644
--- a/libs/androidfw/Asset.cpp
+++ b/libs/androidfw/Asset.cpp
@@ -253,8 +253,10 @@
 
     pAsset = new _FileAsset;
     result = pAsset->openChunk(NULL, fd, offset, length);
-    if (result != NO_ERROR)
+    if (result != NO_ERROR) {
+        delete pAsset;
         return NULL;
+    }
 
     pAsset->mAccessMode = mode;
     return pAsset;
@@ -273,8 +275,10 @@
     pAsset = new _CompressedAsset;
     result = pAsset->openChunk(fd, offset, compressionMethod,
                 uncompressedLen, compressedLen);
-    if (result != NO_ERROR)
+    if (result != NO_ERROR) {
+        delete pAsset;
         return NULL;
+    }
 
     pAsset->mAccessMode = mode;
     return pAsset;
@@ -328,8 +332,10 @@
 
     pAsset = new _CompressedAsset;
     result = pAsset->openChunk(dataMap, uncompressedLen);
-    if (result != NO_ERROR)
+    if (result != NO_ERROR) {
+        delete pAsset;
         return NULL;
+    }
 
     pAsset->mAccessMode = mode;
     return pAsset;
diff --git a/media/java/android/media/AudioAttributes.java b/media/java/android/media/AudioAttributes.java
index 55f1911..3a33678 100644
--- a/media/java/android/media/AudioAttributes.java
+++ b/media/java/android/media/AudioAttributes.java
@@ -558,7 +558,7 @@
         private int mContentType = CONTENT_TYPE_UNKNOWN;
         private int mSource = MediaRecorder.AudioSource.AUDIO_SOURCE_INVALID;
         private int mFlags = 0x0;
-        private boolean mMuteHapticChannels = false;
+        private boolean mMuteHapticChannels = true;
         private HashSet<String> mTags = new HashSet<String>();
         private Bundle mBundle;
 
@@ -889,7 +889,7 @@
 
         /**
          * Specifying if haptic should be muted or not when playing audio-haptic coupled data.
-         * By default, haptic channels are enabled.
+         * By default, haptic channels are disabled.
          * @param muted true to force muting haptic channels.
          * @return the same Builder instance.
          */
diff --git a/media/java/android/media/audiopolicy/AudioProductStrategy.java b/media/java/android/media/audiopolicy/AudioProductStrategy.java
index 48500e01..c1c255f 100644
--- a/media/java/android/media/audiopolicy/AudioProductStrategy.java
+++ b/media/java/android/media/audiopolicy/AudioProductStrategy.java
@@ -262,7 +262,7 @@
                 || (attr.getContentType() == refAttr.getContentType()))
             && ((refAttr.getAllFlags() == 0)
                 || (attr.getAllFlags() != 0
-                && (attr.getAllFlags() & refAttr.getAllFlags()) == attr.getAllFlags()))
+                && (attr.getAllFlags() & refAttr.getAllFlags()) == refAttr.getAllFlags()))
             && ((refFormattedTags.length() == 0) || refFormattedTags.equals(cliFormattedTags));
     }
 
diff --git a/media/jni/Android.bp b/media/jni/Android.bp
index 5c3d780..04545e8 100644
--- a/media/jni/Android.bp
+++ b/media/jni/Android.bp
@@ -93,7 +93,7 @@
 
     shared_libs: [
         "liblog",
-        "libmedia_omx",
+        "libgui",
         "libnativewindow",
         "libui",
         "libutils",
diff --git a/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt b/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt
index 239b1d4..eff02d2 100644
--- a/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt
+++ b/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt
@@ -173,6 +173,7 @@
     }
 
     override fun draw(c: Canvas) {
+        c.saveLayer(null, null)
         unifiedPath.reset()
         levelPath.reset()
         levelRect.set(fillRect)
@@ -243,6 +244,7 @@
             // And draw the plus sign on top of the fill
             c.drawPath(scaledPlus, errorPaint)
         }
+        c.restore()
     }
 
     private fun batteryColorForLevel(level: Int): Int {
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index 2a9456d..6ac2b30 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -178,6 +178,7 @@
     <uses-permission android:name="android.permission.READ_CLIPBOARD_IN_BACKGROUND" />
     <!-- Permission needed to wipe the device for Test Harness Mode -->
     <uses-permission android:name="android.permission.ENABLE_TEST_HARNESS_MODE" />
+    <uses-permission android:name="android.permission.MANAGE_COMPANION_DEVICES" />
 
     <uses-permission android:name="android.permission.MANAGE_APPOPS" />
 
diff --git a/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java b/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
index 62b0542..de64cf8 100644
--- a/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
+++ b/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
@@ -176,10 +176,6 @@
         setClipChildren(false);
         setClipToPadding(false);
         Dependency.get(ConfigurationController.class).observe(viewAttachLifecycle(this), this);
-
-        // Needed for PorderDuff.Mode.CLEAR operations to work properly, but redraws don't happen
-        // enough to justify a hardware layer.
-        setLayerType(LAYER_TYPE_SOFTWARE, null);
     }
 
     private void setupLayoutTransition() {
diff --git a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
index a3e7d36..e9c3850 100644
--- a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
+++ b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
@@ -657,6 +657,11 @@
                 + "associate USER_ID PACKAGE MAC_ADDRESS\n"
                 + "disassociate USER_ID PACKAGE MAC_ADDRESS";
 
+        ShellCmd() {
+            getContext().enforceCallingOrSelfPermission(
+                    android.Manifest.permission.MANAGE_COMPANION_DEVICES, "ShellCmd");
+        }
+
         @Override
         public int onCommand(String cmd) {
             switch (cmd) {
diff --git a/services/core/java/com/android/server/DynamicSystemService.java b/services/core/java/com/android/server/DynamicSystemService.java
index 99bbcf8..7a1697f 100644
--- a/services/core/java/com/android/server/DynamicSystemService.java
+++ b/services/core/java/com/android/server/DynamicSystemService.java
@@ -18,16 +18,23 @@
 
 import android.content.Context;
 import android.content.pm.PackageManager;
+import android.gsi.GsiInstallParams;
 import android.gsi.GsiProgress;
 import android.gsi.IGsiService;
+import android.os.Environment;
 import android.os.IBinder;
 import android.os.IBinder.DeathRecipient;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.SystemProperties;
+import android.os.UserHandle;
 import android.os.image.IDynamicSystemService;
+import android.os.storage.StorageManager;
+import android.os.storage.StorageVolume;
 import android.util.Slog;
 
+import java.io.File;
+
 /**
  * DynamicSystemService implements IDynamicSystemService. It provides permission check before
  * passing requests to gsid
@@ -36,7 +43,7 @@
     private static final String TAG = "DynamicSystemService";
     private static final String NO_SERVICE_ERROR = "no gsiservice";
     private static final int GSID_ROUGH_TIMEOUT_MS = 8192;
-
+    private static final String PATH_DEFAULT = "/data/gsi";
     private Context mContext;
     private volatile IGsiService mGsiService;
 
@@ -100,7 +107,32 @@
 
     @Override
     public boolean startInstallation(long systemSize, long userdataSize) throws RemoteException {
-        return getGsiService().startGsiInstall(systemSize, userdataSize, true) == 0;
+        // priority from high to low: sysprop -> sdcard -> /data
+        String path = SystemProperties.get("os.aot.path");
+        if (path.isEmpty()) {
+            final int userId = UserHandle.myUserId();
+            final StorageVolume[] volumes =
+                    StorageManager.getVolumeList(userId, StorageManager.FLAG_FOR_WRITE);
+            for (StorageVolume volume : volumes) {
+                if (volume.isEmulated()) continue;
+                if (!volume.isRemovable()) continue;
+                if (!Environment.MEDIA_MOUNTED.equals(volume.getState())) continue;
+                File sdCard = volume.getPathFile();
+                if (sdCard.isDirectory()) {
+                    path = sdCard.getPath();
+                    break;
+                }
+            }
+            if (path.isEmpty()) {
+                path = PATH_DEFAULT;
+            }
+            Slog.i(TAG, "startInstallation -> " + path);
+        }
+        GsiInstallParams installParams = new GsiInstallParams();
+        installParams.installDir = path;
+        installParams.gsiSize = systemSize;
+        installParams.userdataSize = userdataSize;
+        return getGsiService().beginGsiInstall(installParams) == 0;
     }
 
     @Override
diff --git a/services/core/java/com/android/server/am/BatteryStatsService.java b/services/core/java/com/android/server/am/BatteryStatsService.java
index f86ba27..ae3324c 100644
--- a/services/core/java/com/android/server/am/BatteryStatsService.java
+++ b/services/core/java/com/android/server/am/BatteryStatsService.java
@@ -720,10 +720,10 @@
         }
     }
 
-    public void notePhoneDataConnectionState(int dataType, boolean hasData) {
+    public void notePhoneDataConnectionState(int dataType, boolean hasData, int serviceType) {
         enforceCallingPermission();
         synchronized (mStats) {
-            mStats.notePhoneDataConnectionStateLocked(dataType, hasData);
+            mStats.notePhoneDataConnectionStateLocked(dataType, hasData, serviceType);
         }
     }
 
diff --git a/services/core/java/com/android/server/appop/AppOpsService.java b/services/core/java/com/android/server/appop/AppOpsService.java
index c9e7cfa..eaedc21 100644
--- a/services/core/java/com/android/server/appop/AppOpsService.java
+++ b/services/core/java/com/android/server/appop/AppOpsService.java
@@ -341,7 +341,7 @@
 
         int evalMode(int op, int mode) {
             if (mode == AppOpsManager.MODE_FOREGROUND) {
-                return state <= AppOpsManager.resolveLastRestrictedUidState(op)
+                return state <= AppOpsManager.resolveFirstUnrestrictedUidState(op)
                         ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED;
             }
             return mode;
@@ -782,13 +782,20 @@
                 final int[] changedUids = intent.getIntArrayExtra(Intent.EXTRA_CHANGED_UID_LIST);
                 final String[] changedPkgs = intent.getStringArrayExtra(
                         Intent.EXTRA_CHANGED_PACKAGE_LIST);
-                final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(OP_PLAY_AUDIO);
+                ArraySet<ModeCallback> callbacks;
+                synchronized (AppOpsService.this) {
+                    callbacks = mOpModeWatchers.get(OP_PLAY_AUDIO);
+                    if (callbacks == null) {
+                        return;
+                    }
+                    callbacks = new ArraySet<>(callbacks);
+                }
                 for (int i = 0; i < changedUids.length; i++) {
                     final int changedUid = changedUids[i];
                     final String changedPkg = changedPkgs[i];
-                    // We trust packagemanager to insert matching uid and packageNames in the extras
-                    mHandler.sendMessage(PooledLambda.obtainMessage(AppOpsService::notifyOpChanged,
-                            AppOpsService.this, callbacks, OP_PLAY_AUDIO, changedUid, changedPkg));
+                    // We trust packagemanager to insert matching uid and packageNames in the
+                    // extras
+                    notifyOpChanged(callbacks, OP_PLAY_AUDIO, changedUid, changedPkg);
                 }
             }
         }, packageSuspendFilter);
@@ -915,9 +922,12 @@
             if (uidState != null && uidState.pendingState != newState) {
                 final int oldPendingState = uidState.pendingState;
                 uidState.pendingState = newState;
-                if (newState < uidState.state || newState <= UID_STATE_MAX_LAST_NON_RESTRICTED) {
-                    // We are moving to a more important state, or the new state is in the
-                    // foreground, then always do it immediately.
+                if (newState < uidState.state
+                        || (newState <= UID_STATE_MAX_LAST_NON_RESTRICTED
+                                && uidState.state > UID_STATE_MAX_LAST_NON_RESTRICTED)) {
+                    // We are moving to a more important state, or the new state may be in the
+                    // foreground and the old state is in the background, then always do it
+                    // immediately.
                     commitUidPendingStateLocked(uidState);
                 } else if (uidState.pendingStateCommitTime == 0) {
                     // We are moving to a less important state for the first time,
@@ -2414,9 +2424,7 @@
     }
 
     private void commitUidPendingStateLocked(UidState uidState) {
-        final boolean lastForeground = uidState.state <= UID_STATE_MAX_LAST_NON_RESTRICTED;
-        final boolean nowForeground = uidState.pendingState <= UID_STATE_MAX_LAST_NON_RESTRICTED;
-        if (uidState.hasForegroundWatchers && lastForeground != nowForeground) {
+        if (uidState.hasForegroundWatchers) {
             for (int fgi = uidState.foregroundOps.size() - 1; fgi >= 0; fgi--) {
                 if (!uidState.foregroundOps.valueAt(fgi)) {
                     continue;
diff --git a/services/core/java/com/android/server/connectivity/DataConnectionStats.java b/services/core/java/com/android/server/connectivity/DataConnectionStats.java
index 227ab23..4990ea1 100644
--- a/services/core/java/com/android/server/connectivity/DataConnectionStats.java
+++ b/services/core/java/com/android/server/connectivity/DataConnectionStats.java
@@ -91,7 +91,8 @@
         if (DEBUG) Log.d(TAG, String.format("Noting data connection for network type %s: %svisible",
                 networkType, visible ? "" : "not "));
         try {
-            mBatteryStats.notePhoneDataConnectionState(networkType, visible);
+            mBatteryStats.notePhoneDataConnectionState(networkType, visible,
+                    mServiceState.getState());
         } catch (RemoteException e) {
             Log.w(TAG, "Error noting data connection state", e);
         }
diff --git a/services/core/java/com/android/server/display/DisplayPowerController.java b/services/core/java/com/android/server/display/DisplayPowerController.java
index e2ea42e..5fb67dd 100644
--- a/services/core/java/com/android/server/display/DisplayPowerController.java
+++ b/services/core/java/com/android/server/display/DisplayPowerController.java
@@ -572,9 +572,6 @@
     public void onSwitchUser(@UserIdInt int newUserId) {
         handleSettingsChange(true /* userSwitch */);
         mBrightnessTracker.onSwitchUser(newUserId);
-        if (mDisplayWhiteBalanceSettings != null) {
-            mDisplayWhiteBalanceSettings.onSwitchUser();
-        }
     }
 
     public ParceledListSlice<AmbientBrightnessDayStats> getAmbientBrightnessStats(
diff --git a/services/core/java/com/android/server/display/color/ColorDisplayService.java b/services/core/java/com/android/server/display/color/ColorDisplayService.java
index 4f81c03..9590f81 100644
--- a/services/core/java/com/android/server/display/color/ColorDisplayService.java
+++ b/services/core/java/com/android/server/display/color/ColorDisplayService.java
@@ -105,10 +105,12 @@
      */
     private static final long TRANSITION_DURATION = 3000L;
 
-    private static final int MSG_APPLY_NIGHT_DISPLAY_IMMEDIATE = 0;
-    private static final int MSG_APPLY_NIGHT_DISPLAY_ANIMATED = 1;
-    private static final int MSG_APPLY_GLOBAL_SATURATION = 2;
-    private static final int MSG_APPLY_DISPLAY_WHITE_BALANCE = 3;
+    private static final int MSG_USER_CHANGED = 0;
+    private static final int MSG_SET_UP = 1;
+    private static final int MSG_APPLY_NIGHT_DISPLAY_IMMEDIATE = 2;
+    private static final int MSG_APPLY_NIGHT_DISPLAY_ANIMATED = 3;
+    private static final int MSG_APPLY_GLOBAL_SATURATION = 4;
+    private static final int MSG_APPLY_DISPLAY_WHITE_BALANCE = 5;
 
     /**
      * Return value if a setting has not been set.
@@ -186,7 +188,7 @@
 
             // Register listeners now that boot is complete.
             if (mCurrentUser != UserHandle.USER_NULL && mUserSetupObserver == null) {
-                setUp();
+                mHandler.sendEmptyMessage(MSG_SET_UP);
             }
         }
     }
@@ -196,7 +198,9 @@
         super.onStartUser(userHandle);
 
         if (mCurrentUser == UserHandle.USER_NULL) {
-            onUserChanged(userHandle);
+            final Message message = mHandler.obtainMessage(MSG_USER_CHANGED);
+            message.arg1 = userHandle;
+            mHandler.sendMessage(message);
         }
     }
 
@@ -204,7 +208,9 @@
     public void onSwitchUser(int userHandle) {
         super.onSwitchUser(userHandle);
 
-        onUserChanged(userHandle);
+        final Message message = mHandler.obtainMessage(MSG_USER_CHANGED);
+        message.arg1 = userHandle;
+        mHandler.sendMessage(message);
     }
 
     @Override
@@ -212,7 +218,9 @@
         super.onStopUser(userHandle);
 
         if (mCurrentUser == userHandle) {
-            onUserChanged(UserHandle.USER_NULL);
+            final Message message = mHandler.obtainMessage(MSG_USER_CHANGED);
+            message.arg1 = UserHandle.USER_NULL;
+            mHandler.sendMessage(message);
         }
     }
 
@@ -262,7 +270,7 @@
 
         // Listen for external changes to any of the settings.
         if (mContentObserver == null) {
-            mContentObserver = new ContentObserver(new Handler(DisplayThread.get().getLooper())) {
+            mContentObserver = new ContentObserver(mHandler) {
                 @Override
                 public void onChange(boolean selfChange, Uri uri) {
                     super.onChange(selfChange, uri);
@@ -467,6 +475,9 @@
      * Apply the accessibility daltonizer transform based on the settings value.
      */
     private void onAccessibilityDaltonizerChanged() {
+        if (mCurrentUser == UserHandle.USER_NULL) {
+            return;
+        }
         final boolean enabled = Secure.getIntForUser(getContext().getContentResolver(),
                 Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0, mCurrentUser) != 0;
         final int daltonizerMode = enabled ? Secure.getIntForUser(getContext().getContentResolver(),
@@ -490,6 +501,9 @@
      * Apply the accessibility inversion transform based on the settings value.
      */
     private void onAccessibilityInversionChanged() {
+        if (mCurrentUser == UserHandle.USER_NULL) {
+            return;
+        }
         final boolean enabled = Secure.getIntForUser(getContext().getContentResolver(),
                 Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, 0, mCurrentUser) != 0;
         final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
@@ -596,7 +610,19 @@
         }
     }
 
+    private boolean setDisplayWhiteBalanceSettingEnabled(boolean enabled) {
+        if (mCurrentUser == UserHandle.USER_NULL) {
+            return false;
+        }
+        return Secure.putIntForUser(getContext().getContentResolver(),
+                Secure.DISPLAY_WHITE_BALANCE_ENABLED,
+                enabled ? 1 : 0, mCurrentUser);
+    }
+
     private boolean isDisplayWhiteBalanceSettingEnabled() {
+        if (mCurrentUser == UserHandle.USER_NULL) {
+            return false;
+        }
         return Secure.getIntForUser(getContext().getContentResolver(),
                 Secure.DISPLAY_WHITE_BALANCE_ENABLED, 0, mCurrentUser) == 1;
     }
@@ -648,6 +674,9 @@
     }
 
     private int getNightDisplayAutoModeRawInternal() {
+        if (mCurrentUser == UserHandle.USER_NULL) {
+            return NOT_SET;
+        }
         return Secure
                 .getIntForUser(getContext().getContentResolver(), Secure.NIGHT_DISPLAY_AUTO_MODE,
                         NOT_SET, mCurrentUser);
@@ -1214,6 +1243,13 @@
         }
 
         /**
+         * Returns whether Display white balance is currently enabled.
+         */
+        public boolean isDisplayWhiteBalanceEnabled() {
+            return isDisplayWhiteBalanceSettingEnabled();
+        }
+
+        /**
          * Adds a {@link WeakReference<ColorTransformController>} for a newly started activity, and
          * invokes {@link ColorTransformController#applyAppSaturation(float[], float[])} if needed.
          */
@@ -1233,7 +1269,7 @@
          * Notify that the display white balance status has changed, either due to preemption by
          * another transform or the feature being turned off.
          */
-        void onDisplayWhiteBalanceStatusChanged(boolean enabled);
+        void onDisplayWhiteBalanceStatusChanged(boolean activated);
     }
 
     private final class TintHandler extends Handler {
@@ -1245,6 +1281,12 @@
         @Override
         public void handleMessage(Message msg) {
             switch (msg.what) {
+                case MSG_USER_CHANGED:
+                    onUserChanged(msg.arg1);
+                    break;
+                case MSG_SET_UP:
+                    setUp();
+                    break;
                 case MSG_APPLY_GLOBAL_SATURATION:
                     mGlobalSaturationTintController.setMatrix(msg.arg1);
                     applyTint(mGlobalSaturationTintController, false);
@@ -1500,6 +1542,29 @@
         }
 
         @Override
+        public boolean setDisplayWhiteBalanceEnabled(boolean enabled) {
+            getContext().enforceCallingOrSelfPermission(
+                    Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
+                    "Permission required to set night display activated");
+            final long token = Binder.clearCallingIdentity();
+            try {
+                return setDisplayWhiteBalanceSettingEnabled(enabled);
+            } finally {
+                Binder.restoreCallingIdentity(token);
+            }
+        }
+
+        @Override
+        public boolean isDisplayWhiteBalanceEnabled() {
+            final long token = Binder.clearCallingIdentity();
+            try {
+                return isDisplayWhiteBalanceSettingEnabled();
+            } finally {
+                Binder.restoreCallingIdentity(token);
+            }
+        }
+
+        @Override
         public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
             if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) {
                 return;
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceSettings.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceSettings.java
index 1b7251c..6e78894 100644
--- a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceSettings.java
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceSettings.java
@@ -18,13 +18,9 @@
 
 import android.annotation.NonNull;
 import android.content.Context;
-import android.database.ContentObserver;
-import android.net.Uri;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.Message;
-import android.os.UserHandle;
-import android.provider.Settings.Secure;
 import android.util.Slog;
 
 import com.android.internal.util.Preconditions;
@@ -46,22 +42,19 @@
     protected static final String TAG = "DisplayWhiteBalanceSettings";
     protected boolean mLoggingEnabled;
 
-    private static final String SETTING_URI = Secure.DISPLAY_WHITE_BALANCE_ENABLED;
-    private static final int SETTING_DEFAULT = 0;
-    private static final int SETTING_ENABLED = 1;
-
     private static final int MSG_SET_ACTIVE = 1;
 
     private final Context mContext;
     private final Handler mHandler;
-    private final SettingsObserver mSettingsObserver;
+
+    private final ColorDisplayServiceInternal mCdsi;
 
     // To decouple the DisplayPowerController from the DisplayWhiteBalanceSettings, the DPC
     // implements Callbacks and passes itself to the DWBS so it can call back into it without
     // knowing about it.
     private Callbacks mCallbacks;
 
-    private int mSetting;
+    private boolean mEnabled;
     private boolean mActive;
 
     /**
@@ -79,18 +72,12 @@
         mLoggingEnabled = false;
         mContext = context;
         mHandler = new DisplayWhiteBalanceSettingsHandler(handler.getLooper());
-        mSettingsObserver = new SettingsObserver(mHandler);
-        mSetting = getSetting();
-        mActive = false;
         mCallbacks = null;
 
-        mContext.getContentResolver().registerContentObserver(
-                Secure.getUriFor(SETTING_URI), false /* notifyForDescendants */, mSettingsObserver,
-                UserHandle.USER_ALL);
-
-        ColorDisplayServiceInternal cds =
-                LocalServices.getService(ColorDisplayServiceInternal.class);
-        cds.setDisplayWhiteBalanceListener(this);
+        mCdsi = LocalServices.getService(ColorDisplayServiceInternal.class);
+        setEnabled(mCdsi.isDisplayWhiteBalanceEnabled());
+        final boolean isActive = mCdsi.setDisplayWhiteBalanceListener(this);
+        setActive(isActive);
     }
 
     /**
@@ -99,7 +86,7 @@
      * @param callbacks
      *      The object to call back to.
      *
-     * @return Whether the method suceeded or not.
+     * @return Whether the method succeeded or not.
      */
     public boolean setCallbacks(Callbacks callbacks) {
         if (mCallbacks == callbacks) {
@@ -131,14 +118,7 @@
      * @return Whether display white-balance is enabled.
      */
     public boolean isEnabled() {
-        return (mSetting == SETTING_ENABLED) && mActive;
-    }
-
-    /**
-     * Re-evaluate state after switching to a new user.
-     */
-    public void onSwitchUser() {
-        handleSettingChange();
+        return mEnabled && mActive;
     }
 
     /**
@@ -152,15 +132,14 @@
         writer.println("  mLoggingEnabled=" + mLoggingEnabled);
         writer.println("  mContext=" + mContext);
         writer.println("  mHandler=" + mHandler);
-        writer.println("  mSettingsObserver=" + mSettingsObserver);
-        writer.println("  mSetting=" + mSetting);
+        writer.println("  mEnabled=" + mEnabled);
         writer.println("  mActive=" + mActive);
         writer.println("  mCallbacks=" + mCallbacks);
     }
 
     @Override
-    public void onDisplayWhiteBalanceStatusChanged(boolean active) {
-        Message msg = mHandler.obtainMessage(MSG_SET_ACTIVE, active ? 1 : 0, 0);
+    public void onDisplayWhiteBalanceStatusChanged(boolean activated) {
+        Message msg = mHandler.obtainMessage(MSG_SET_ACTIVE, activated ? 1 : 0, 0);
         msg.sendToTarget();
     }
 
@@ -169,20 +148,14 @@
         Preconditions.checkNotNull(handler, "handler must not be null");
     }
 
-    private int getSetting() {
-        return Secure.getIntForUser(mContext.getContentResolver(), SETTING_URI, SETTING_DEFAULT,
-                UserHandle.USER_CURRENT);
-    }
-
-    private void handleSettingChange() {
-        final int setting = getSetting();
-        if (mSetting == setting) {
+    private void setEnabled(boolean enabled) {
+        if (mEnabled == enabled) {
             return;
         }
         if (mLoggingEnabled) {
-            Slog.d(TAG, "Setting: " + setting);
+            Slog.d(TAG, "Setting: " + enabled);
         }
-        mSetting = setting;
+        mEnabled = enabled;
         if (mCallbacks != null) {
             mCallbacks.updateWhiteBalance();
         }
@@ -201,17 +174,6 @@
         }
     }
 
-    private final class SettingsObserver extends ContentObserver {
-        SettingsObserver(Handler handler) {
-            super(handler);
-        }
-
-        @Override
-        public void onChange(boolean selfChange, Uri uri) {
-            handleSettingChange();
-        }
-    }
-
     private final class DisplayWhiteBalanceSettingsHandler extends Handler {
         DisplayWhiteBalanceSettingsHandler(Looper looper) {
             super(looper, null, true /* async */);
@@ -222,6 +184,7 @@
             switch (msg.what) {
                 case MSG_SET_ACTIVE:
                     setActive(msg.arg1 != 0);
+                    setEnabled(mCdsi.isDisplayWhiteBalanceEnabled());
                     break;
             }
         }
diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
index b64abdb..10ae782 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@@ -224,6 +224,7 @@
 import android.view.RemoteAnimationAdapter;
 import android.view.RemoteAnimationDefinition;
 import android.view.WindowManager;
+import android.view.inputmethod.InputMethodSystemProperty;
 
 import com.android.internal.R;
 import com.android.internal.annotations.VisibleForTesting;
@@ -6436,6 +6437,10 @@
          */
         @Override
         public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
+            // Update display configuration for IME process only when Single-client IME window
+            // moving to another display.
+            if (!InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
+
             if (pid == MY_PID || pid < 0) {
                 if (DEBUG_CONFIGURATION) {
                     Slog.w(TAG,
diff --git a/services/usage/java/com/android/server/usage/UsageStatsXmlV1.java b/services/usage/java/com/android/server/usage/UsageStatsXmlV1.java
index e39cd87..565ca9e 100644
--- a/services/usage/java/com/android/server/usage/UsageStatsXmlV1.java
+++ b/services/usage/java/com/android/server/usage/UsageStatsXmlV1.java
@@ -219,7 +219,7 @@
         try {
             event.mInstanceId = XmlUtils.readIntAttribute(parser, INSTANCE_ID_ATTR);
         } catch (IOException e) {
-            Log.e(TAG, "Failed to parse mInstanceId", e);
+            Log.i(TAG, "Failed to parse mInstanceId");
         }
 
         switch (event.mEventType) {
@@ -390,13 +390,13 @@
         try {
             statsOut.majorVersion = XmlUtils.readIntAttribute(parser, MAJOR_VERSION_ATTR);
         } catch (IOException e) {
-            Log.e(TAG, "Failed to parse majorVersion", e);
+            Log.i(TAG, "Failed to parse majorVersion");
         }
 
         try {
             statsOut.minorVersion = XmlUtils.readIntAttribute(parser, MINOR_VERSION_ATTR);
         } catch (IOException e) {
-            Log.e(TAG, "Failed to parse minorVersion", e);
+            Log.i(TAG, "Failed to parse minorVersion");
         }
 
         int eventCode;
diff --git a/tests/AppLaunch/src/com/android/tests/applaunch/AppLaunch.java b/tests/AppLaunch/src/com/android/tests/applaunch/AppLaunch.java
index 9d7319f..95b8f67 100644
--- a/tests/AppLaunch/src/com/android/tests/applaunch/AppLaunch.java
+++ b/tests/AppLaunch/src/com/android/tests/applaunch/AppLaunch.java
@@ -78,6 +78,7 @@
     private static final String KEY_SIMPLEPERF_CMD = "simpleperf_cmd";
     private static final String KEY_SIMPLEPERF_APP = "simpleperf_app";
     private static final String KEY_CYCLE_CLEAN = "cycle_clean";
+    private static final String KEY_TRACE_ALL = "trace_all";
     private static final String KEY_TRACE_ITERATIONS = "trace_iterations";
     private static final String KEY_LAUNCH_DIRECTORY = "launch_directory";
     private static final String KEY_TRACE_DIRECTORY = "trace_directory";
@@ -111,7 +112,7 @@
     private static final String SUCCESS_MESSAGE = "Status: ok";
     private static final String TOTAL_TIME_MESSAGE = "TotalTime:";
     private static final String COMPILE_SUCCESS = "Success";
-    private static final String LAUNCH_ITERATION = "LAUNCH_ITERATION - %d";
+    private static final String LAUNCH_ITERATION = "LAUNCH_ITERATION-%d";
     private static final String TRACE_ITERATION = "TRACE_ITERATION-%d";
     private static final String LAUNCH_ITERATION_PREFIX = "LAUNCH_ITERATION";
     private static final String TRACE_ITERATION_PREFIX = "TRACE_ITERATION";
@@ -142,6 +143,7 @@
     private String[] mCompilerFilters = null;
     private String mLastAppName = "";
     private boolean mCycleCleanUp = false;
+    private boolean mTraceAll = false;
     private boolean mIterationCycle = false;
     private long mCycleTime = 0;
     private StringBuilder mCycleTimes = new StringBuilder();
@@ -296,18 +298,40 @@
                         // skip if the app has failures while launched first
                         continue;
                     }
-                    // In the "applaunch.txt" file app launches are referenced using
-                    // "LAUNCH_ITERATION - ITERATION NUM"
-                    launchResults = startApp(launch.getApp(), launch.getLaunchReason());
-                    if (launchResults.mLaunchTime < 0) {
-                        addLaunchResult(launch, new AppLaunchResult());
-                        // if it fails once, skip the rest of the launches
-                        continue;
-                    } else {
-                        mCycleTime += launchResults.mLaunchTime;
-                        addLaunchResult(launch, launchResults);
+                    AtraceLogger atraceLogger = null;
+                    if (mTraceAll) {
+                        Log.i(TAG, "Started tracing " + launch.getApp());
+                        atraceLogger = AtraceLogger
+                                .getAtraceLoggerInstance(getInstrumentation());
                     }
-                    sleep(POST_LAUNCH_IDLE_TIMEOUT);
+                    try {
+                        // Start the trace
+                        if (atraceLogger != null) {
+                            atraceLogger.atraceStart(traceCategoriesSet, traceBufferSize,
+                                    traceDumpInterval, rootTraceSubDir,
+                                    String.format("%s-%s-%s", launch.getApp(),
+                                            launch.getCompilerFilter(), launch.getLaunchReason()));
+                        }
+                        // In the "applaunch.txt" file app launches are referenced using
+                        // "LAUNCH_ITERATION - ITERATION NUM"
+                        launchResults = startApp(launch.getApp(), launch.getLaunchReason());
+                        if (launchResults.mLaunchTime < 0) {
+                            addLaunchResult(launch, new AppLaunchResult());
+                            // if it fails once, skip the rest of the launches
+                            continue;
+                        } else {
+                            mCycleTime += launchResults.mLaunchTime;
+                            addLaunchResult(launch, launchResults);
+                        }
+                        sleep(POST_LAUNCH_IDLE_TIMEOUT);
+                    } finally {
+                        // Stop the trace
+                        if (atraceLogger != null) {
+                            Log.i(TAG, "Stopped tracing " + launch.getApp());
+                            atraceLogger.atraceStop();
+                        }
+                    }
+
                 }
 
                 // App launch times for trace launch will not be used for final
@@ -534,6 +558,7 @@
         mLaunchOrder = args.getString(KEY_LAUNCH_ORDER, LAUNCH_ORDER_CYCLIC);
         mSimplePerfAppOnly = Boolean.parseBoolean(args.getString(KEY_SIMPLEPERF_APP));
         mCycleCleanUp = Boolean.parseBoolean(args.getString(KEY_CYCLE_CLEAN));
+        mTraceAll = Boolean.parseBoolean(args.getString(KEY_TRACE_ALL));
         mTrialLaunch = mTrialLaunch || Boolean.parseBoolean(args.getString(KEY_TRIAL_LAUNCH));
 
         if (mSimplePerfCmd != null && mSimplePerfAppOnly) {