Merge "[NetworkSuggestion] Fix getEnterpriseConfig" into rvc-qpr-dev
diff --git a/core/java/android/content/pm/PermissionInfo.java b/core/java/android/content/pm/PermissionInfo.java
index 5f6befd..e990fd7 100644
--- a/core/java/android/content/pm/PermissionInfo.java
+++ b/core/java/android/content/pm/PermissionInfo.java
@@ -525,6 +525,9 @@
         if ((level & PermissionInfo.PROTECTION_FLAG_APP_PREDICTOR) != 0) {
             protLevel += "|appPredictor";
         }
+        if ((level & PermissionInfo.PROTECTION_FLAG_COMPANION) != 0) {
+            protLevel += "|companion";
+        }
         if ((level & PermissionInfo.PROTECTION_FLAG_RETAIL_DEMO) != 0) {
             protLevel += "|retailDemo";
         }
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 64d9c9d..f395569 100755
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -10770,17 +10770,6 @@
        public static final String MODE_RINGER = "mode_ringer";
 
         /**
-         * Specifies whether Enhanced Connectivity is enabled or not. This setting allows the
-         * Connectivity Thermal Power Manager to actively help the device to save power in 5G
-         * scenarios
-         * Type: int 1 is enabled, 0 is disabled
-         *
-         * @hide
-         */
-        public static final String ENHANCED_CONNECTIVITY_ENABLED =
-                "enhanced_connectivity_enable";
-
-        /**
          * Overlay display devices setting.
          * The associated value is a specially formatted string that describes the
          * size and density of simulated secondary display devices.
diff --git a/core/java/android/view/FocusFinder.java b/core/java/android/view/FocusFinder.java
index 713cfb4..064bc69 100644
--- a/core/java/android/view/FocusFinder.java
+++ b/core/java/android/view/FocusFinder.java
@@ -311,6 +311,9 @@
         }
 
         final int count = focusables.size();
+        if (count < 2) {
+            return null;
+        }
         switch (direction) {
             case View.FOCUS_FORWARD:
                 return getNextFocusable(focused, focusables, count);
@@ -373,29 +376,29 @@
     }
 
     private static View getNextFocusable(View focused, ArrayList<View> focusables, int count) {
+        if (count < 2) {
+            return null;
+        }
         if (focused != null) {
             int position = focusables.lastIndexOf(focused);
             if (position >= 0 && position + 1 < count) {
                 return focusables.get(position + 1);
             }
         }
-        if (!focusables.isEmpty()) {
-            return focusables.get(0);
-        }
-        return null;
+        return focusables.get(0);
     }
 
     private static View getPreviousFocusable(View focused, ArrayList<View> focusables, int count) {
+        if (count < 2) {
+            return null;
+        }
         if (focused != null) {
             int position = focusables.indexOf(focused);
             if (position > 0) {
                 return focusables.get(position - 1);
             }
         }
-        if (!focusables.isEmpty()) {
-            return focusables.get(count - 1);
-        }
-        return null;
+        return focusables.get(count - 1);
     }
 
     private static View getNextKeyboardNavigationCluster(
diff --git a/core/java/android/view/inputmethod/InlineSuggestionsRequest.java b/core/java/android/view/inputmethod/InlineSuggestionsRequest.java
index cce1090..6300320 100644
--- a/core/java/android/view/inputmethod/InlineSuggestionsRequest.java
+++ b/core/java/android/view/inputmethod/InlineSuggestionsRequest.java
@@ -47,6 +47,9 @@
     /**
      * Max number of suggestions expected from the response. It must be a positive value.
      * Defaults to {@code SUGGESTION_COUNT_UNLIMITED} if not set.
+     *
+     * <p>In practice, it is recommended that the max suggestion count does not exceed <b>5</b>
+     * for performance reasons.</p>
      */
     private final int mMaxSuggestionCount;
 
@@ -67,6 +70,9 @@
     /**
      * The IME provided locales for the request. If non-empty, the inline suggestions should
      * return languages from the supported locales. If not provided, it'll default to system locale.
+     *
+     * <p>Note for Autofill Providers: It is <b>recommended</b> for the returned inline suggestions
+     * to have one locale to guarantee consistent UI rendering.</p>
      */
     private @NonNull LocaleList mSupportedLocales;
 
@@ -227,6 +233,9 @@
     /**
      * Max number of suggestions expected from the response. It must be a positive value.
      * Defaults to {@code SUGGESTION_COUNT_UNLIMITED} if not set.
+     *
+     * <p>In practice, it is recommended that the max suggestion count does not exceed <b>5</b>
+     * for performance reasons.</p>
      */
     @DataClass.Generated.Member
     public int getMaxSuggestionCount() {
@@ -256,6 +265,9 @@
     /**
      * The IME provided locales for the request. If non-empty, the inline suggestions should
      * return languages from the supported locales. If not provided, it'll default to system locale.
+     *
+     * <p>Note for Autofill Providers: It is <b>recommended</b> for the returned inline suggestions
+     * to have one locale to guarantee consistent UI rendering.</p>
      */
     @DataClass.Generated.Member
     public @NonNull LocaleList getSupportedLocales() {
@@ -458,6 +470,9 @@
         /**
          * Max number of suggestions expected from the response. It must be a positive value.
          * Defaults to {@code SUGGESTION_COUNT_UNLIMITED} if not set.
+         *
+         * <p>In practice, it is recommended that the max suggestion count does not exceed <b>5</b>
+         * for performance reasons.</p>
          */
         @DataClass.Generated.Member
         public @NonNull Builder setMaxSuggestionCount(int value) {
@@ -508,6 +523,9 @@
         /**
          * The IME provided locales for the request. If non-empty, the inline suggestions should
          * return languages from the supported locales. If not provided, it'll default to system locale.
+         *
+         * <p>Note for Autofill Providers: It is <b>recommended</b> for the returned inline suggestions
+         * to have one locale to guarantee consistent UI rendering.</p>
          */
         @DataClass.Generated.Member
         public @NonNull Builder setSupportedLocales(@NonNull LocaleList value) {
@@ -604,7 +622,7 @@
     }
 
     @DataClass.Generated(
-            time = 1588109685838L,
+            time = 1595457701315L,
             codegenVersion = "1.0.15",
             sourceFile = "frameworks/base/core/java/android/view/inputmethod/InlineSuggestionsRequest.java",
             inputSignatures = "public static final  int SUGGESTION_COUNT_UNLIMITED\nprivate final  int mMaxSuggestionCount\nprivate final @android.annotation.NonNull java.util.List<android.widget.inline.InlinePresentationSpec> mInlinePresentationSpecs\nprivate @android.annotation.NonNull java.lang.String mHostPackageName\nprivate @android.annotation.NonNull android.os.LocaleList mSupportedLocales\nprivate @android.annotation.NonNull android.os.Bundle mExtras\nprivate @android.annotation.Nullable android.os.IBinder mHostInputToken\nprivate  int mHostDisplayId\npublic  void setHostInputToken(android.os.IBinder)\nprivate  boolean extrasEquals(android.os.Bundle)\nprivate  void parcelHostInputToken(android.os.Parcel,int)\nprivate @android.annotation.Nullable android.os.IBinder unparcelHostInputToken(android.os.Parcel)\npublic  void setHostDisplayId(int)\nprivate  void onConstructed()\npublic  void filterContentTypes()\nprivate static  int defaultMaxSuggestionCount()\nprivate static  java.lang.String defaultHostPackageName()\nprivate static  android.os.LocaleList defaultSupportedLocales()\nprivate static @android.annotation.Nullable android.os.IBinder defaultHostInputToken()\nprivate static @android.annotation.Nullable int defaultHostDisplayId()\nprivate static @android.annotation.NonNull android.os.Bundle defaultExtras()\nclass InlineSuggestionsRequest extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genToString=true, genBuilder=true)\nabstract  android.view.inputmethod.InlineSuggestionsRequest.Builder setInlinePresentationSpecs(java.util.List<android.widget.inline.InlinePresentationSpec>)\nabstract  android.view.inputmethod.InlineSuggestionsRequest.Builder setHostPackageName(java.lang.String)\nabstract  android.view.inputmethod.InlineSuggestionsRequest.Builder setHostInputToken(android.os.IBinder)\nabstract  android.view.inputmethod.InlineSuggestionsRequest.Builder setHostDisplayId(int)\nclass BaseBuilder extends java.lang.Object implements []")
diff --git a/core/java/android/view/inputmethod/InlineSuggestionsResponse.java b/core/java/android/view/inputmethod/InlineSuggestionsResponse.java
index be833df..b393c67 100644
--- a/core/java/android/view/inputmethod/InlineSuggestionsResponse.java
+++ b/core/java/android/view/inputmethod/InlineSuggestionsResponse.java
@@ -32,7 +32,18 @@
  */
 @DataClass(genEqualsHashCode = true, genToString = true, genHiddenConstructor = true)
 public final class InlineSuggestionsResponse implements Parcelable {
-    private final @NonNull List<InlineSuggestion> mInlineSuggestions;
+    /**
+     * List of {@link InlineSuggestion}s returned as a part of this response.
+     *
+     * <p>When the host app requests to inflate this <b>ordered</b> list of inline suggestions by
+     * calling {@link InlineSuggestion#inflate}, it is the host's responsibility to track the
+     * order of the inflated {@link android.view.View}s. These views are to be added in
+     * order to the view hierarchy, because the inflation calls will return asynchronously.</p>
+     *
+     * <p>The inflation ordering does not apply to the pinned icon.</p>
+     */
+    @NonNull
+    private final List<InlineSuggestion> mInlineSuggestions;
 
     /**
      * Creates a new {@link InlineSuggestionsResponse}, for testing purpose.
@@ -48,7 +59,7 @@
 
 
 
-    // Code below generated by codegen v1.0.14.
+    // Code below generated by codegen v1.0.15.
     //
     // DO NOT MODIFY!
     // CHECKSTYLE:OFF Generated code
@@ -64,6 +75,15 @@
     /**
      * Creates a new InlineSuggestionsResponse.
      *
+     * @param inlineSuggestions
+     *   List of {@link InlineSuggestion}s returned as a part of this response.
+     *
+     *   <p>When the host app requests to inflate this <b>ordered</b> list of inline suggestions by
+     *   calling {@link InlineSuggestion#inflate}, it is the host's responsibility to track the
+     *   order of the inflated {@link android.view.View}s. These views are to be added in
+     *   order to the view hierarchy, because the inflation calls will return asynchronously.</p>
+     *
+     *   <p>The inflation ordering does not apply to the pinned icon.</p>
      * @hide
      */
     @DataClass.Generated.Member
@@ -76,6 +96,16 @@
         // onConstructed(); // You can define this method to get a callback
     }
 
+    /**
+     * List of {@link InlineSuggestion}s returned as a part of this response.
+     *
+     * <p>When the host app requests to inflate this <b>ordered</b> list of inline suggestions by
+     * calling {@link InlineSuggestion#inflate}, it is the host's responsibility to track the
+     * order of the inflated {@link android.view.View}s. These views are to be added in
+     * order to the view hierarchy, because the inflation calls will return asynchronously.</p>
+     *
+     * <p>The inflation ordering does not apply to the pinned icon.</p>
+     */
     @DataClass.Generated.Member
     public @NonNull List<InlineSuggestion> getInlineSuggestions() {
         return mInlineSuggestions;
@@ -164,8 +194,8 @@
     };
 
     @DataClass.Generated(
-            time = 1578972149519L,
-            codegenVersion = "1.0.14",
+            time = 1595891876037L,
+            codegenVersion = "1.0.15",
             sourceFile = "frameworks/base/core/java/android/view/inputmethod/InlineSuggestionsResponse.java",
             inputSignatures = "private final @android.annotation.NonNull java.util.List<android.view.inputmethod.InlineSuggestion> mInlineSuggestions\npublic static @android.annotation.TestApi @android.annotation.NonNull android.view.inputmethod.InlineSuggestionsResponse newInlineSuggestionsResponse(java.util.List<android.view.inputmethod.InlineSuggestion>)\nclass InlineSuggestionsResponse extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genToString=true, genHiddenConstructor=true)")
     @Deprecated
diff --git a/core/res/res/drawable-car-night/car_dialog_button_background.xml b/core/res/res/drawable-car-night/car_dialog_button_background.xml
deleted file mode 100644
index 138cb38..0000000
--- a/core/res/res/drawable-car-night/car_dialog_button_background.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2020 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.
-  -->
-<selector xmlns:android="http://schemas.android.com/apk/res/android">
-    <item android:state_focused="true">
-        <ripple android:color="#2371cd">
-            <item android:id="@android:id/mask">
-                <color android:color="@*android:color/car_white_1000"/>
-            </item>
-        </ripple>
-    </item>
-    <item>
-        <ripple android:color="?android:attr/colorControlHighlight">
-            <item android:id="@android:id/mask">
-                <color android:color="@*android:color/car_white_1000"/>
-            </item>
-        </ripple>
-    </item>
-</selector>
diff --git a/core/res/res/drawable-car/car_dialog_button_background.xml b/core/res/res/drawable-car/car_dialog_button_background.xml
index a7d40bcd..72e5af3 100644
--- a/core/res/res/drawable-car/car_dialog_button_background.xml
+++ b/core/res/res/drawable-car/car_dialog_button_background.xml
@@ -16,11 +16,18 @@
   -->
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_focused="true">
-        <ripple android:color="#4b9eff">
-            <item android:id="@android:id/mask">
-                <color android:color="@*android:color/car_white_1000"/>
+        <layer-list>
+            <item>
+                <shape android:shape="rectangle">
+                    <solid android:color="#3D94CBFF"/>
+                </shape>
             </item>
-        </ripple>
+            <item>
+                <shape android:shape="rectangle">
+                    <stroke android:width="8dp" android:color="#94CBFF"/>
+                </shape>
+            </item>
+        </layer-list>
     </item>
     <item>
         <ripple android:color="?android:attr/colorControlHighlight">
diff --git a/core/res/res/values-fr/strings.xml b/core/res/res/values-fr/strings.xml
index 7b3a7f2..ba67e0b 100644
--- a/core/res/res/values-fr/strings.xml
+++ b/core/res/res/values-fr/strings.xml
@@ -1937,7 +1937,7 @@
       <item quantity="other"><xliff:g id="COUNT">%1$s</xliff:g> suggestions de saisie automatique</item>
     </plurals>
     <string name="autofill_save_title" msgid="7719802414283739775">"Enregistrer dans "<b>"<xliff:g id="LABEL">%1$s</xliff:g>"</b>" ?"</string>
-    <string name="autofill_save_title_with_type" msgid="3002460014579799605">"Enregistrer <xliff:g id="TYPE">%1$s</xliff:g> dans "<b>"<xliff:g id="LABEL">%2$s</xliff:g>"</b>" ?"</string>
+    <string name="autofill_save_title_with_type" msgid="3002460014579799605">"Enregistrer la <xliff:g id="TYPE">%1$s</xliff:g> dans "<b>"<xliff:g id="LABEL">%2$s</xliff:g>"</b>" ?"</string>
     <string name="autofill_save_title_with_2types" msgid="3783270967447869241">"Enregistrer <xliff:g id="TYPE_0">%1$s</xliff:g> et <xliff:g id="TYPE_1">%2$s</xliff:g> dans "<b>"<xliff:g id="LABEL">%3$s</xliff:g>"</b>" ?"</string>
     <string name="autofill_save_title_with_3types" msgid="6598228952100102578">"Enregistrer <xliff:g id="TYPE_0">%1$s</xliff:g>, <xliff:g id="TYPE_1">%2$s</xliff:g> et <xliff:g id="TYPE_2">%3$s</xliff:g> dans "<b>"<xliff:g id="LABEL">%4$s</xliff:g>"</b>" ?"</string>
     <string name="autofill_update_title" msgid="3630695947047069136">"Mettre à jour cet élément dans "<b>"<xliff:g id="LABEL">%1$s</xliff:g>"</b>" ?"</string>
diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml
index 8e8368f..03161d0 100644
--- a/packages/SettingsLib/res/values/strings.xml
+++ b/packages/SettingsLib/res/values/strings.xml
@@ -659,9 +659,6 @@
     <!-- Setting Checkbox title for enabling Bluetooth Gabeldorsche. [CHAR LIMIT=40] -->
     <string name="bluetooth_enable_gabeldorsche">Enable Gabeldorsche</string>
 
-    <!-- Setting Checkbox title for enabling Enhanced Connectivity [CHAR LIMIT=80] -->
-    <string name="enhanced_connectivity">Enhanced Connectivity</string>
-
     <!-- UI debug setting: Select Bluetooth AVRCP Version -->
     <string name="bluetooth_select_avrcp_version_string">Bluetooth AVRCP Version</string>
     <!-- UI debug setting: Select Bluetooth AVRCP Version -->
diff --git a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
index eb7ad72..36f9f9f 100644
--- a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
+++ b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
@@ -270,7 +270,6 @@
                     Settings.Global.SMART_REPLIES_IN_NOTIFICATIONS_FLAGS,
                     Settings.Global.SMART_SUGGESTIONS_IN_NOTIFICATIONS_FLAGS,
                     Settings.Global.ENABLE_ADB_INCREMENTAL_INSTALL_DEFAULT,
-                    Settings.Global.ENHANCED_CONNECTIVITY_ENABLED,
                     Settings.Global.ENHANCED_4G_MODE_ENABLED,
                     Settings.Global.EPHEMERAL_COOKIE_MAX_SIZE_BYTES,
                     Settings.Global.ERROR_LOGCAT_PREFIX,
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index ec24014..82abb98 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -3318,6 +3318,10 @@
     @Override
     public boolean setProcessMemoryTrimLevel(String process, int userId, int level)
             throws RemoteException {
+        if (!isCallerShell()) {
+            EventLog.writeEvent(0x534e4554, 160390416, Binder.getCallingUid(), "");
+            throw new SecurityException("Only shell can call it");
+        }
         synchronized (this) {
             final ProcessRecord app = findProcessLocked(process, userId, "setProcessMemoryTrimLevel");
             if (app == null) {
diff --git a/services/core/java/com/android/server/pm/BackgroundDexOptService.java b/services/core/java/com/android/server/pm/BackgroundDexOptService.java
index 5415967..d48570f 100644
--- a/services/core/java/com/android/server/pm/BackgroundDexOptService.java
+++ b/services/core/java/com/android/server/pm/BackgroundDexOptService.java
@@ -337,6 +337,7 @@
     private int idleOptimizePackages(PackageManagerService pm, ArraySet<String> pkgs,
             long lowStorageThreshold) {
         ArraySet<String> updatedPackages = new ArraySet<>();
+        ArraySet<String> updatedPackagesDueToSecondaryDex = new ArraySet<>();
 
         try {
             final boolean supportSecondaryDex = supportSecondaryDex();
@@ -391,11 +392,14 @@
             }
 
             int secondaryResult = optimizePackages(pm, pkgs, lowStorageThreshold,
-                    /*isForPrimaryDex*/ false, updatedPackages);
+                    /*isForPrimaryDex*/ false, updatedPackagesDueToSecondaryDex);
             return secondaryResult;
         } finally {
             // Always let the pinner service know about changes.
             notifyPinService(updatedPackages);
+            // Only notify IORap the primary dex opt, because we don't want to
+            // invalidate traces unnecessary due to b/161633001 and that it's
+            // better to have a trace than no trace at all.
             notifyPackagesUpdated(updatedPackages);
         }
     }
diff --git a/services/core/java/com/android/server/storage/StorageUserConnection.java b/services/core/java/com/android/server/storage/StorageUserConnection.java
index 361a506..1c29c69 100644
--- a/services/core/java/com/android/server/storage/StorageUserConnection.java
+++ b/services/core/java/com/android/server/storage/StorageUserConnection.java
@@ -29,6 +29,7 @@
 import android.content.Intent;
 import android.content.ServiceConnection;
 import android.os.Bundle;
+import android.os.HandlerThread;
 import android.os.IBinder;
 import android.os.ParcelFileDescriptor;
 import android.os.ParcelableException;
@@ -64,9 +65,6 @@
     private static final String TAG = "StorageUserConnection";
 
     private static final int DEFAULT_REMOTE_TIMEOUT_SECONDS = 20;
-    // TODO(b/161702661): Workaround for demo user to have shorter timeout.
-    // This allows the DevicePolicyManagerService#enableSystemApp call to succeed without ANR.
-    private static final int DEMO_USER_REMOTE_TIMEOUT_SECONDS = 5;
 
     private final Object mLock = new Object();
     private final Context mContext;
@@ -75,6 +73,7 @@
     private final ActiveConnection mActiveConnection = new ActiveConnection();
     private final boolean mIsDemoUser;
     @GuardedBy("mLock") private final Map<String, Session> mSessions = new HashMap<>();
+    @GuardedBy("mLock") @Nullable private HandlerThread mHandlerThread;
 
     public StorageUserConnection(Context context, int userId, StorageSessionController controller) {
         mContext = Objects.requireNonNull(context);
@@ -82,6 +81,10 @@
         mSessionController = controller;
         mIsDemoUser = LocalServices.getService(UserManagerInternal.class)
                 .getUserInfo(userId).isDemo();
+        if (mIsDemoUser) {
+            mHandlerThread = new HandlerThread("StorageUserConnectionThread-" + mUserId);
+            mHandlerThread.start();
+        }
     }
 
     /**
@@ -188,6 +191,9 @@
      */
     public void close() {
         mActiveConnection.close();
+        if (mIsDemoUser) {
+            mHandlerThread.quit();
+        }
     }
 
     /** Returns all created sessions. */
@@ -207,8 +213,7 @@
 
     private void waitForLatch(CountDownLatch latch, String reason) throws TimeoutException {
         try {
-            if (!latch.await(mIsDemoUser ? DEMO_USER_REMOTE_TIMEOUT_SECONDS
-                            : DEFAULT_REMOTE_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
+            if (!latch.await(DEFAULT_REMOTE_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
                 // TODO(b/140025078): Call ActivityManager ANR API?
                 Slog.wtf(TAG, "Failed to bind to the ExternalStorageService for user " + mUserId);
                 throw new TimeoutException("Latch wait for " + reason + " elapsed");
@@ -424,15 +429,32 @@
                 };
 
                 Slog.i(TAG, "Binding to the ExternalStorageService for user " + mUserId);
-                if (mContext.bindServiceAsUser(new Intent().setComponent(name), mServiceConnection,
-                        Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
-                        UserHandle.of(mUserId))) {
-                    Slog.i(TAG, "Bound to the ExternalStorageService for user " + mUserId);
-                    return mLatch;
+                if (mIsDemoUser) {
+                    // Schedule on a worker thread for demo user to avoid deadlock
+                    if (mContext.bindServiceAsUser(new Intent().setComponent(name),
+                                    mServiceConnection,
+                                    Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
+                                    mHandlerThread.getThreadHandler(),
+                                    UserHandle.of(mUserId))) {
+                        Slog.i(TAG, "Bound to the ExternalStorageService for user " + mUserId);
+                        return mLatch;
+                    } else {
+                        mIsConnecting = false;
+                        throw new ExternalStorageServiceException(
+                                "Failed to bind to the ExternalStorageService for user " + mUserId);
+                    }
                 } else {
-                    mIsConnecting = false;
-                    throw new ExternalStorageServiceException(
-                            "Failed to bind to the ExternalStorageService for user " + mUserId);
+                    if (mContext.bindServiceAsUser(new Intent().setComponent(name),
+                                    mServiceConnection,
+                                    Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
+                                    UserHandle.of(mUserId))) {
+                        Slog.i(TAG, "Bound to the ExternalStorageService for user " + mUserId);
+                        return mLatch;
+                    } else {
+                        mIsConnecting = false;
+                        throw new ExternalStorageServiceException(
+                                "Failed to bind to the ExternalStorageService for user " + mUserId);
+                    }
                 }
             }
         }