1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.media.audio.cts;
18 
19 import static org.junit.Assert.assertNotNull;
20 
21 import android.media.AudioManager;
22 import android.util.Log;
23 
24 import java.util.concurrent.CountDownLatch;
25 import java.util.concurrent.TimeUnit;
26 
27 
28 final class AudioVolumeGroupCallbackHelper extends AudioManager.VolumeGroupCallback {
29     private static final String TAG = "AudioVolumeGroupCallbackHelper";
30     public static final long ASYNC_TIMEOUT_MS = 800;
31 
32     private int mExpectedVolumeGroupId;
33 
34     private CountDownLatch mVolumeGroupChanged = null;
35 
setExpectedVolumeGroup(int group)36     void setExpectedVolumeGroup(int group) {
37         mVolumeGroupChanged = new CountDownLatch(1);
38         mExpectedVolumeGroupId = group;
39     }
40 
41     @Override
onAudioVolumeGroupChanged(int group, int flags)42     public void onAudioVolumeGroupChanged(int group, int flags) {
43         if (group != mExpectedVolumeGroupId) {
44             return;
45         }
46         if (mVolumeGroupChanged == null) {
47             Log.wtf(TAG, "Received callback but object not initialized");
48             return;
49         }
50         if (mVolumeGroupChanged.getCount() <= 0) {
51             Log.i(TAG, "callback for group: " + group + " already received");
52             return;
53         }
54         mVolumeGroupChanged.countDown();
55     }
56 
waitForExpectedVolumeGroupChanged(long timeOutMs)57     public boolean waitForExpectedVolumeGroupChanged(long timeOutMs) {
58         assertNotNull("Call first setExpectedVolumeGroup before waiting...", mVolumeGroupChanged);
59         long startTimeMs = System.currentTimeMillis();
60         long elapsedTimeMs = 0;
61         while (elapsedTimeMs < ASYNC_TIMEOUT_MS && mVolumeGroupChanged.getCount() > 0) {
62             try {
63                 mVolumeGroupChanged.await(ASYNC_TIMEOUT_MS, TimeUnit.MILLISECONDS);
64             } catch (InterruptedException e) {
65                 Log.w(TAG, "wait interrupted");
66             }
67             elapsedTimeMs = System.currentTimeMillis() - startTimeMs;
68         }
69         return mVolumeGroupChanged.getCount() <= 0;
70     }
71 }
72