Fixes switch-user -w command.

We handle failures better and exit early if already switched to a current user.

Fixes: 150019926
Test: manual verification
Change-Id: Ib3d70d21cc379f136983f9ddcda31f5bab3f045e
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index c7f5f63..8c7cf98 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -1763,6 +1763,12 @@
     }
 
     private boolean switchUserAndWaitForComplete(int userId) throws RemoteException {
+        UserInfo currentUser = mInterface.getCurrentUser();
+        if (currentUser != null && userId == currentUser.id) {
+            // Already switched to the correct user, exit early.
+            return true;
+        }
+
         // Register switch observer.
         final CountDownLatch switchLatch = new CountDownLatch(1);
         mInterface.registerUserSwitchObserver(
@@ -1777,13 +1783,18 @@
 
         // Switch.
         boolean switched = mInterface.switchUser(userId);
+        if (!switched) {
+            // Switching failed, don't wait for the user switch observer.
+            return false;
+        }
 
         // Wait.
         try {
-            switchLatch.await(USER_OPERATION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+            switched = switchLatch.await(USER_OPERATION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
         } catch (InterruptedException e) {
-            getErrPrintWriter().println("Thread interrupted unexpectedly.");
+            getErrPrintWriter().println("Error: Thread interrupted unexpectedly.");
         }
+
         return switched;
     }
 
@@ -1815,7 +1826,7 @@
         if (switched) {
             return 0;
         } else {
-            pw.printf("Failed to switch to user %d\n", userId);
+            pw.printf("Error: Failed to switch to user %d\n", userId);
             return 1;
         }
     }