Cherry-pick: 'Fix test case testLockTask_exitIfNoLongerWhitelisted'

'Test case has some timing issue while checking for test lock mode removal.
Sleep has been added to avoid the issue.'

Bug: 146396674
Fixes: 158236157
Test: run cts -m CtsDevicePolicyManagerTestCases -t
      com.android.cts.devicepolicy.MixedProfileOwnerTest#testLockTask_exitIfNoLongerWhitelisted
Change-Id: I6f6852a3107ee6d7b81d8793163dd7b6fe31408a
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/LockTaskHostDrivenTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/LockTaskHostDrivenTest.java
index 409b076..4321f38 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/LockTaskHostDrivenTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/LockTaskHostDrivenTest.java
@@ -26,6 +26,7 @@
 import android.content.pm.ResolveInfo;
 import android.os.Build;
 import android.os.Bundle;
+import android.os.SystemClock;
 import android.support.test.uiautomator.By;
 import android.support.test.uiautomator.UiDevice;
 import android.support.test.uiautomator.Until;
@@ -47,6 +48,7 @@
 
     private static final String TAG = LockTaskHostDrivenTest.class.getName();
     private static final int ACTIVITY_RESUMED_TIMEOUT_MILLIS = 20000;  // 20 seconds
+    private static final int LOCK_TASK_STATE_CHANGE_TIMEOUT_MILLIS = 10000;  // 10 seconds
     private static final String ACTION_EMERGENCY_DIAL = "com.android.phone.EmergencyDialer.DIAL";
     private static final String LOCK_TASK_ACTIVITY
             = LockTaskUtilityActivityIfWhitelisted.class.getName();
@@ -114,6 +116,25 @@
         mUiDevice.waitForIdle();
     }
 
+    /**
+      * Poll for {@link ActivityManager#getLockTaskModeState()} to equal
+      * {@link ActivityManager#LOCK_TASK_MODE_NONE}
+      *
+      * <p>This will check every 500 milliseconds for a maximum of
+     * {@link #LOCK_TASK_STATE_CHANGE_TIMEOUT_MILLIS} milliseconds.
+      */
+    private void waitForLockTaskModeStateNone() {
+        long delayed = 0;
+        long delay = 500;
+        while (delayed <= LOCK_TASK_STATE_CHANGE_TIMEOUT_MILLIS) {
+            if (mActivityManager.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_NONE) {
+                break;
+            }
+            SystemClock.sleep(delay);
+            delayed += delay;
+        }
+    }
+
     public void testLockTaskIsExitedIfNotWhitelisted() throws Exception {
         Log.d(TAG, "testLockTaskIsExitedIfNotWhitelisted on host-driven test");
 
@@ -129,6 +150,7 @@
 
         // Remove it from whitelist
         setLockTaskPackages();
+        waitForLockTaskModeStateNone();
         mUiDevice.waitForIdle();
 
         // The activity should be finished and exit lock task mode