1 /*
2  * Copyright (C) 2021 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.location.cts.common;
18 
19 import android.app.AppOpsManager;
20 import android.os.Looper;
21 
22 import java.util.concurrent.LinkedBlockingQueue;
23 import java.util.concurrent.TimeUnit;
24 
25 public class OpActiveChangedCapture implements AppOpsManager.OnOpActiveChangedListener,
26         AutoCloseable {
27 
28     private final AppOpsManager mAppOps;
29     private final String mOp;
30     private final LinkedBlockingQueue<Boolean> mActives;
31 
OpActiveChangedCapture(AppOpsManager appOps, String op)32     public OpActiveChangedCapture(AppOpsManager appOps, String op) {
33         mAppOps = appOps;
34         mOp = op;
35         mActives = new LinkedBlockingQueue<>();
36     }
37 
getNextActive(long timeoutMs)38     public Boolean getNextActive(long timeoutMs) throws InterruptedException {
39         if (Looper.myLooper() == Looper.getMainLooper()) {
40             throw new AssertionError("getNextActive() called from main thread");
41         }
42 
43         return mActives.poll(timeoutMs, TimeUnit.MILLISECONDS);
44     }
45 
46     @Override
close()47     public void close() {
48         mAppOps.stopWatchingActive(this);
49     }
50 
51     @Override
onOpActiveChanged(String op, int uid, String packageName, boolean active)52     public void onOpActiveChanged(String op, int uid, String packageName, boolean active) {
53         if (op.equals(mOp)) {
54             mActives.add(active);
55         }
56     }
57 }
58