Merge "Add a function to wait for the setting of preferred payment" into android12-tests-dev
diff --git a/tests/tests/nfc/src/android/nfc/cts/NfcPreferredPaymentTest.java b/tests/tests/nfc/src/android/nfc/cts/NfcPreferredPaymentTest.java
index f25be15..c769a09 100644
--- a/tests/tests/nfc/src/android/nfc/cts/NfcPreferredPaymentTest.java
+++ b/tests/tests/nfc/src/android/nfc/cts/NfcPreferredPaymentTest.java
@@ -48,6 +48,9 @@
     private static final ComponentName CtsNfcTestService =
             new ComponentName("android.nfc.cts", "android.nfc.cts.CtsMyHostApduService");
 
+    private static final int MAX_TIMEOUT_MS = 5000;
+    private static final int TEST_DURATION_MS = 100;
+
     private NfcAdapter mAdapter;
     private CardEmulation mCardEmulation;
     private Context mContext;
@@ -67,6 +70,7 @@
         Settings.Secure.putString(mContext.getContentResolver(),
                 NFC_PAYMENT_DEFAULT_COMPONENT,
                 CtsNfcTestService.flattenToString());
+        waitPreferredPaymentSettingDone();
     }
 
     @After
@@ -146,4 +150,29 @@
             fail("Unexpected Exception " + e);
         }
     }
+
+    public void waitPreferredPaymentSettingDone() {
+        try {
+            for (int i = 0; i < MAX_TIMEOUT_MS / TEST_DURATION_MS; i++) {
+                CharSequence description =
+                        mCardEmulation.getDescriptionForPreferredPaymentService();
+
+                if (description != null && description.toString().equals(mDescription)) return;
+
+                msleep(TEST_DURATION_MS);
+            }
+
+            fail("Unable to set the preferred payment service");
+        } catch (Exception e) {
+            fail("Unexpected Exception " + e);
+        }
+    }
+
+    private void msleep(int millis) {
+        try {
+            Thread.sleep(millis);
+        } catch (InterruptedException e) {
+            fail("Unexpected Exception " + e);
+        }
+    }
 }