Add CTS test for useTargetActivityForQuickAccess() method in QAWService.

The test covers 3 cases:
* Metadata doesn't exist
* Metadata exists and is true
* Metadata exists and is false

In each case, we set the appropriate service as default, bind to it,
then call the method and assert the value.

This involves a bit of a change to TestQuickAccessWalletService:
* Added an override in onBind to count down when the device is bound.
  I think we probably meant to have this from the start, but we never
  did. We have the same thing for unbind, so I genuinely think this was
  a bug.

* Update the reference to the service in onBind instead of onCreate.
  This makes more sense semantically since we want the reference to be
  to the currently bound service, instead of the most recently created
  one.

Bug: 218860062
Test: atest QuickAccessWalletServiceTest
Test: atest
Change-Id: Ia779f382b0c2059e1c1ae47f0760ab944a9ab153
diff --git a/tests/quickaccesswallet/AndroidManifest.xml b/tests/quickaccesswallet/AndroidManifest.xml
index 5c48a39..b101531 100755
--- a/tests/quickaccesswallet/AndroidManifest.xml
+++ b/tests/quickaccesswallet/AndroidManifest.xml
@@ -92,6 +92,20 @@
                        android:resource="@xml/quickaccesswallet_configuration_usetargetactivityforquickaccess"/>;
         </service>
 
+        <service android:name="android.quickaccesswallet.DoNotUseTargetActivityForQuickAccessWalletService"
+                 android:enabled="false"
+                 android:label="@string/app_name"
+                 android:icon="@drawable/android"
+                 android:permission="android.permission.BIND_QUICK_ACCESS_WALLET_SERVICE"
+                 android:exported="true">
+            <intent-filter>
+                <action android:name="android.service.quickaccesswallet.QuickAccessWalletService"/>
+                <category android:name="android.intent.category.DEFAULT"/>
+            </intent-filter>
+            <meta-data android:name="android.quickaccesswallet"
+                       android:resource="@xml/quickaccesswallet_configuration_donotusetargetactivityforquickaccess"/>;
+        </service>
+
         <service android:name="android.quickaccesswallet.QuickAccessWalletDelegateTargetActivityService"
                  android:enabled="false"
                  android:label="@string/app_name"
diff --git a/tests/quickaccesswallet/res/xml/quickaccesswallet_configuration_donotusetargetactivityforquickaccess.xml b/tests/quickaccesswallet/res/xml/quickaccesswallet_configuration_donotusetargetactivityforquickaccess.xml
new file mode 100644
index 0000000..0ddbede
--- /dev/null
+++ b/tests/quickaccesswallet/res/xml/quickaccesswallet_configuration_donotusetargetactivityforquickaccess.xml
@@ -0,0 +1,20 @@
+<!--
+  ~ Copyright (C) 2022 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.
+  -->
+
+<quickaccesswallet-service
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:targetActivity="android.quickaccesswallet.QuickAccessWalletActivity"
+    android:useTargetActivityForQuickAccess="false"/>
\ No newline at end of file
diff --git a/tests/quickaccesswallet/src/android/quickaccesswallet/DoNotUseTargetActivityForQuickAccessWalletService.java b/tests/quickaccesswallet/src/android/quickaccesswallet/DoNotUseTargetActivityForQuickAccessWalletService.java
new file mode 100644
index 0000000..322a62c
--- /dev/null
+++ b/tests/quickaccesswallet/src/android/quickaccesswallet/DoNotUseTargetActivityForQuickAccessWalletService.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2022 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.quickaccesswallet;
+
+/**
+ * Extends {@link TestQuickAccessWalletService} to allow for a different manifest configuration.
+ */
+public class DoNotUseTargetActivityForQuickAccessWalletService
+        extends TestQuickAccessWalletService {}
diff --git a/tests/quickaccesswallet/src/android/quickaccesswallet/TestQuickAccessWalletService.java b/tests/quickaccesswallet/src/android/quickaccesswallet/TestQuickAccessWalletService.java
index 7aa2c3e..44784a6 100644
--- a/tests/quickaccesswallet/src/android/quickaccesswallet/TestQuickAccessWalletService.java
+++ b/tests/quickaccesswallet/src/android/quickaccesswallet/TestQuickAccessWalletService.java
@@ -20,6 +20,7 @@
 import android.content.Intent;
 import android.graphics.Bitmap;
 import android.graphics.drawable.Icon;
+import android.os.IBinder;
 import android.service.quickaccesswallet.GetWalletCardsCallback;
 import android.service.quickaccesswallet.GetWalletCardsError;
 import android.service.quickaccesswallet.GetWalletCardsRequest;
@@ -30,6 +31,9 @@
 import android.service.quickaccesswallet.WalletServiceEvent;
 import android.util.Log;
 
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.Collections;
@@ -58,24 +62,22 @@
         sRequestCountDownLatch = new CountDownLatch(0);
         sBindCounter = new CountDownLatch(0);
         sUnbindCounter = new CountDownLatch(0);
+        sServiceRef.clear();
     }
 
+    @Nullable
     @Override
-    public void onCreate() {
-        super.onCreate();
+    public IBinder onBind(@NonNull Intent intent) {
+        sBindCounter.countDown();
         sServiceRef = new WeakReference<>(this);
+        return super.onBind(intent);
     }
 
     @Override
     public boolean onUnbind(Intent intent) {
         sUnbindCounter.countDown();
-        return super.onUnbind(intent);
-    }
-
-    @Override
-    public void onDestroy() {
         sServiceRef.clear();
-        super.onDestroy();
+        return super.onUnbind(intent);
     }
 
     @Override
@@ -125,6 +127,14 @@
         }
     }
 
+    public static boolean testGetUseTargetActivityForQuickAccess() {
+        TestQuickAccessWalletService service = sServiceRef.get();
+        if (service != null) {
+            return service.getUseTargetActivityForQuickAccess();
+        }
+        return false;
+    }
+
     public static List<SelectWalletCardRequest> getSelectRequests() {
         return new ArrayList<>(sSelectWalletCardRequests);
     }
diff --git a/tests/quickaccesswallet/src/android/quickaccesswallet/cts/QuickAccessWalletServiceTest.java b/tests/quickaccesswallet/src/android/quickaccesswallet/cts/QuickAccessWalletServiceTest.java
new file mode 100644
index 0000000..01b0212
--- /dev/null
+++ b/tests/quickaccesswallet/src/android/quickaccesswallet/cts/QuickAccessWalletServiceTest.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2022 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.quickaccesswallet.cts;
+
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.quickaccesswallet.DoNotUseTargetActivityForQuickAccessWalletService;
+import android.quickaccesswallet.TestHostApduService;
+import android.quickaccesswallet.TestQuickAccessWalletService;
+import android.quickaccesswallet.UseTargetActivityForQuickAccessWalletService;
+import android.service.quickaccesswallet.QuickAccessWalletClient;
+import android.service.quickaccesswallet.QuickAccessWalletService;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.platform.app.InstrumentationRegistry;
+import androidx.test.rule.ServiceTestRule;
+
+import com.android.compatibility.common.util.SettingsUtils;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.TimeUnit;
+
+
+/**
+ * Tests {@link android.service.quickaccesswallet.QuickAccessWalletService}.
+ */
+@RunWith(AndroidJUnit4.class)
+public class QuickAccessWalletServiceTest {
+
+    private static final String NFC_PAYMENT_DEFAULT_COMPONENT = "nfc_payment_default_component";
+
+    private Context mContext;
+    private String mDefaultPaymentApp;
+
+    @Rule
+    public final ServiceTestRule serviceRule = new ServiceTestRule();
+
+    @Before
+    public void setUp() throws Exception {
+        // Save current default payment app
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        mDefaultPaymentApp = SettingsUtils.get(NFC_PAYMENT_DEFAULT_COMPONENT);
+        ComponentName component =
+                ComponentName.createRelative(mContext, TestHostApduService.class.getName());
+        SettingsUtils.syncSet(mContext, NFC_PAYMENT_DEFAULT_COMPONENT,
+                component.flattenToString());
+        TestQuickAccessWalletService.resetStaticFields();
+    }
+
+    @After
+    public void tearDown() {
+        // Restore saved default payment app
+        SettingsUtils.syncSet(mContext, NFC_PAYMENT_DEFAULT_COMPONENT, mDefaultPaymentApp);
+
+        // Return all services to default state
+        setServiceState(TestQuickAccessWalletService.class,
+                PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
+        setServiceState(UseTargetActivityForQuickAccessWalletService.class,
+                PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
+        setServiceState(DoNotUseTargetActivityForQuickAccessWalletService.class,
+                PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
+        TestQuickAccessWalletService.resetStaticFields();
+    }
+
+    @Test
+    public void defaultTestQuickAccessWalletService_noMetadataItem_useTargetActivityIsFalse()
+            throws Exception {
+        bindToService();
+
+        assertThat(TestQuickAccessWalletService.testGetUseTargetActivityForQuickAccess()).isFalse();
+    }
+
+    @Test
+    public void testQuickAccessService_metadataSpecifiesToUseTarget_useTargetActivityIsTrue()
+            throws Exception {
+        setServiceState(UseTargetActivityForQuickAccessWalletService.class,
+                PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
+        setServiceState(TestQuickAccessWalletService.class,
+                PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
+
+        bindToService();
+
+        assertThat(UseTargetActivityForQuickAccessWalletService
+                .testGetUseTargetActivityForQuickAccess()).isTrue();
+
+    }
+
+    @Test
+    public void testQuickAccessService_metadataSpecifiesNotToUseTarget_useTargetActivityIsFalse()
+            throws Exception {
+        setServiceState(DoNotUseTargetActivityForQuickAccessWalletService.class,
+                PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
+        setServiceState(TestQuickAccessWalletService.class,
+                PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
+        bindToService();
+
+        assertThat(
+                DoNotUseTargetActivityForQuickAccessWalletService
+                        .testGetUseTargetActivityForQuickAccess()).isFalse();
+    }
+
+    private void bindToService() throws Exception {
+        // Creates a QuickAccessWalletClient that binds to the currently active service.
+        // This ensures that the value set in TestQuickAccessWallet's
+        // sServiceRef is the correct service.
+        TestQuickAccessWalletService.setExpectedBindCount(1);
+        QuickAccessWalletClient client = QuickAccessWalletClient.create(mContext);
+        client.notifyWalletDismissed();
+        TestQuickAccessWalletService.awaitBinding(3, TimeUnit.SECONDS);
+    }
+
+    private void setServiceState(
+            Class<? extends QuickAccessWalletService> cls, int state) {
+        ComponentName componentName = ComponentName.createRelative(mContext, cls.getName());
+        mContext.getPackageManager().setComponentEnabledSetting(
+                componentName, state, PackageManager.DONT_KILL_APP);
+    }
+}