summaryrefslogtreecommitdiff
path: root/apps/CtsVerifier/src/com/android/cts/verifier/companion/CompanionDeviceServiceTestActivity.java
blob: b8b96023cb7a163fb41d646ec7e8a34d7bf0d029 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*
 * Copyright (C) 2021 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 com.android.cts.verifier.companion;

import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;

import android.companion.AssociationInfo;
import android.companion.AssociationRequest;
import android.companion.BluetoothDeviceFilter;
import android.companion.CompanionDeviceManager;
import android.companion.CompanionDeviceService;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.compatibility.common.util.CddTest;
import com.android.cts.verifier.PassFailButtons;
import com.android.cts.verifier.R;

import java.util.ArrayList;

/**
 * Test that Companion Device Awake {@link CompanionDeviceService} API is functional.
 */
@CddTest(requirements = {"3.16/C-1-2", "C-1-3", "H-1-1"})
public class CompanionDeviceServiceTestActivity extends PassFailButtons.Activity {
    private static final String LOG_TAG = "CDMServiceTestActivity";
    private static final int REQUEST_CODE_CHOOSER = 0;

    private final ArrayList<TestStep> mTests = new ArrayList<>();

    private CompanionDeviceManager mCompanionDeviceManager;

    private TextView mTestTitle;
    private TextView mTestDescription;
    private ViewGroup mTestStepButtonLayout;
    private Button mTestAction;
    private Button mTestStepPassed;
    private Button mTestStepFailed;
    private int mCurrentTestIndex;
    private AssociationInfo mCurrentAssociation;

    // Test state verification loop will be launched on a new thread.
    // Null until first verification is required.
    private Runnable mVerifier;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.companion_service_test_main);

        mTestTitle = findViewById(R.id.companion_service_test_title);
        mTestDescription = findViewById(R.id.companion_service_test_description);
        mTestAction = findViewById(R.id.companion_service_test_button);
        mTestStepButtonLayout = findViewById(R.id.button_layout);
        mTestStepPassed = findViewById(R.id.test_step_passed);
        mTestStepFailed = findViewById(R.id.test_step_failed);

        mCurrentTestIndex = -1;
        mCurrentAssociation = null;
        mVerifier = null;
        mHandler = new Handler(Looper.myLooper());

        mCompanionDeviceManager = getSystemService(CompanionDeviceManager.class);

        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
            // Cannot move forward if bluetooth feature is not supported on the device.
            mTests.add(new BluetoothFeatureTestStep());
        } else {
            // Add tests.
            mTests.add(new DeviceAssociationTestStep());
            mTests.add(new DevicePresentTestStep());
            mTests.add(new DeviceGoneTestStep());
            mTests.add(new DeviceDisassociationTestStep());
        }

        setPassFailButtonClickListeners();
        getPassButton().setEnabled(false);
        setInfoResources(R.string.companion_service_test, R.string.companion_service_test_info, -1);
        runNextTestOrShowSummary();
        cleanUp();
    }

    /**
     * Get association info with matching ID. Returns null if no match.
     */
    private AssociationInfo getAssociation(int id) {
        for (AssociationInfo association : mCompanionDeviceManager.getMyAssociations()) {
            if (association.getId() == id) return association;
        }
        return null;
    }

    /** Stop observing to associated device and then disassociate. */
    private void disassociate(AssociationInfo association) {
        String deviceAddress = association.getDeviceMacAddressAsString();
        mCompanionDeviceManager.stopObservingDevicePresence(deviceAddress);
        mCompanionDeviceManager.disassociate(association.getId());
        Log.d(LOG_TAG, "Disassociated with device: " + deviceAddress);
    }

    /** Clean up any associated devices from this app. */
    private void cleanUp() {
        for (AssociationInfo association : mCompanionDeviceManager.getMyAssociations()) {
            disassociate(association);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // On "associate()" success
        if (requestCode == REQUEST_CODE_CHOOSER) {
            if (resultCode != RESULT_OK) {
                fail("Activity result code " + resultCode);
                return;
            }
            AssociationInfo association =
                    data.getParcelableExtra(CompanionDeviceManager.EXTRA_ASSOCIATION,
                    AssociationInfo.class);
            String deviceAddress = association.getDeviceMacAddressAsString();

            // This test is for bluetooth devices, which should all have a MAC address.
            if (deviceAddress == null) fail("The device was present but its address was null.");

            mCompanionDeviceManager.startObservingDevicePresence(deviceAddress);
            mCurrentAssociation = getAssociation(association.getId());
            Log.d(LOG_TAG, "Associated with device: " + deviceAddress);
        } else super.onActivityResult(requestCode, resultCode, data);
    }

    private void fail(Throwable reason) {
        Log.e(LOG_TAG, "Test failed", reason);
        fail(reason.getMessage());
    }

    private void fail(CharSequence reason) {
        Toast.makeText(this, reason, Toast.LENGTH_LONG).show();
        Log.e(LOG_TAG, reason.toString());
        cleanUp();
        setTestResultAndFinish(false);
    }

    private TestStep getCurrentTest() {
        return mTests.get(mCurrentTestIndex);
    }

    private void runNextTestOrShowSummary() {
        if (mCurrentTestIndex + 1 >= mTests.size()) {
            updateViewForCompletionSummary();
        } else {
            mCurrentTestIndex++;
            updateViewForTest(getCurrentTest());
        }
    }

    /** Populates the UI based on the provided test step. */
    private void updateViewForTest(TestStep test) {
        mTestStepButtonLayout.setVisibility(VISIBLE);
        mTestTitle.setText(test.mTitleResId);
        mTestDescription.setText(test.mDescriptionResId);

        // Can't pass until test result is verified.
        mTestStepPassed.setEnabled(false);

        mTestStepPassed.setOnClickListener(v -> getCurrentTest().onPass());
        mTestStepFailed.setOnClickListener(v -> getCurrentTest().onFail());
        mTestAction.setOnClickListener(v -> getCurrentTest().performTestAction());

        if (mVerifier != null) {
            mHandler.removeCallbacks(mVerifier);
        }

        // Display test action button if specified.
        if (test.mButtonTextResId != 0) {
            mTestAction.setText(test.mButtonTextResId);
            mTestAction.setVisibility(VISIBLE);
        } else {
            mTestAction.setVisibility(INVISIBLE);
        }

        // Wait for test verification.
        mVerifier = new Runnable() {
            @Override
            public void run() {
                if (test.verify()) {
                    mTestStepPassed.setEnabled(true);
                } else {
                    mHandler.postDelayed(this, 3000);
                }
            }
        };
        mHandler.postDelayed(mVerifier, 1000);
    }

    /** Populates the UI indicating results of test & updates test buttons as needed */
    private void updateViewForCompletionSummary() {
        // No longer need any of these buttons
        mTestStepButtonLayout.setVisibility(INVISIBLE);
        mTestAction.setVisibility(INVISIBLE);

        // Can only reach here if all other tests passed. Enable pass button.
        getPassButton().setEnabled(true);
        mTestTitle.setText(R.string.companion_service_test_summary_title);
        mTestDescription.setText(R.string.companion_service_test_summary);
    }

    /**
     * This activity specifically tests for CDM interactions with bluetooth devices.
     * Pass the test if device does not support bluetooth.
     */
    private class BluetoothFeatureTestStep extends TestStep {
        BluetoothFeatureTestStep() {
            super(R.string.companion_service_bluetooth_feature_title,
                    R.string.companion_service_bluetooth_feature_text);
        }

        @Override
        boolean verify() {
            return true;
        }
    }

    /**
     * Tests that an association can be made with a device and that the app can subscribe
     * to its presence.
     */
    private class DeviceAssociationTestStep extends TestStep {
        final CompanionDeviceManager.Callback mCallback =
                new CompanionDeviceManager.Callback() {
            @Override
            public void onAssociationPending(IntentSender chooserLauncher) {
                try {
                    startIntentSenderForResult(chooserLauncher,
                            REQUEST_CODE_CHOOSER, null, 0, 0, 0);
                } catch (IntentSender.SendIntentException error) {
                    fail(error);
                }
            }

            @Override
            public void onFailure(CharSequence error) {
                fail(error);
            }
        };

        DeviceAssociationTestStep() {
            super(R.string.companion_service_associate_title,
                    R.string.companion_service_associate_text,
                    R.string.companion_service_associate_button);
        }

        @Override
        void performTestAction() {
            AssociationRequest request = new AssociationRequest.Builder()
                    .addDeviceFilter(new BluetoothDeviceFilter.Builder().build())
                    .build();
            mCompanionDeviceManager.associate(request, mCallback, null);
        }

        @Override
        boolean verify() {
            // Check that it is associated and being observed.
            return mCurrentAssociation != null && mCurrentAssociation.isNotifyOnDeviceNearby();
        }
    }

    /**
     * Tests that app can correctly detect associated device's presence.
     */
    private class DevicePresentTestStep extends TestStep {
        DevicePresentTestStep() {
            super(R.string.companion_service_present_title,
                    R.string.companion_service_present_text);
        }

        @Override
        boolean verify() {
            return DevicePresenceListener.isDeviceNearby(mCurrentAssociation.getId());
        }
    }

    /**
     * Tests that app can correctly detect device's disappearance.
     */
    private class DeviceGoneTestStep extends TestStep {
        DeviceGoneTestStep() {
            super(R.string.companion_service_gone_title,
                    R.string.companion_service_gone_text);
        }

        @Override
        public boolean verify() {
            return !DevicePresenceListener.isDeviceNearby(mCurrentAssociation.getId());
        }
    }

    /**
     * Tests that device can be correctly disassociated from the app.
     */
    private class DeviceDisassociationTestStep extends TestStep {
        DeviceDisassociationTestStep() {
            super(R.string.companion_service_disassociate_title,
                    R.string.companion_service_disassociate_text,
                    R.string.companion_service_disassociate_button);
        }

        @Override
        void performTestAction() {
            disassociate(mCurrentAssociation);
        }

        @Override
        boolean verify() {
            // Check that it is no longer associated.
            return getAssociation(mCurrentAssociation.getId()) == null;
        }
    }

    /**
     * Interface for individual test steps.
     */
    private abstract class TestStep {
        final int mTitleResId;
        final int mDescriptionResId;
        final int mButtonTextResId;

        TestStep(int titleResId, int descriptionResId) {
            this(titleResId, descriptionResId, 0);
        }

        TestStep(int titleResId, int descriptionResId, int buttonTextResId) {
            this.mTitleResId = titleResId;
            this.mDescriptionResId = descriptionResId;
            this.mButtonTextResId = buttonTextResId;
        }

        /** Code to run when the button is activated; only used if {@link #mButtonTextResId} != 0 */
        void performTestAction() {
            // optional
        }

        /** Checks device state to see if the test passed.  */
        abstract boolean verify();

        /**
         * Code to run on failure.
         */
        void onPass() {
            runNextTestOrShowSummary();
        }

        /**
         * Code to run on failure.
         */
        void onFail() {
            cleanUp();
            fail("Test failed manually.");
        }
    }
}