1 /*
2  * Copyright (C) 2020 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 com.android.cts.devicepolicy;
18 
19 import static com.google.common.truth.Truth.assertWithMessage;
20 
21 import android.content.BroadcastReceiver;
22 import android.content.Context;
23 import android.content.Intent;
24 import android.util.Log;
25 
26 import java.util.concurrent.ArrayBlockingQueue;
27 import java.util.concurrent.BlockingQueue;
28 import java.util.concurrent.TimeUnit;
29 
30 public final class PermissionBroadcastReceiver extends BroadcastReceiver {
31 
32     private static final String TAG = "PermissionBroadcastReceiver";
33 
34     private static final String EXTRA_GRANT_STATE
35             = "com.android.cts.permission.extra.GRANT_STATE";
36     private static final int PERMISSION_ERROR = -2;
37 
38     private static final long TIMEOUT_SEC = 30;
39 
40     private final BlockingQueue<Integer> mResultsQueue = new ArrayBlockingQueue<>(1);
41 
42     @Override
onReceive(Context context, Intent intent)43     public void onReceive(Context context, Intent intent) {
44         Integer result = intent.getIntExtra(EXTRA_GRANT_STATE, PERMISSION_ERROR);
45         Log.d(TAG, "Grant state received " + result + " ("
46                 + PermissionUtils.permissionToString(result) + ")");
47         assertWithMessage("added %s to queue", result).that(mResultsQueue.add(result)).isTrue();
48     }
49 
waitForBroadcast()50     public int waitForBroadcast() throws Exception {
51         Integer result = mResultsQueue.poll(TIMEOUT_SEC, TimeUnit.SECONDS);
52         mResultsQueue.clear();
53         assertWithMessage("Expected broadcast to be received within %s seconds but did not get it",
54                 TIMEOUT_SEC).that(result).isNotNull();
55         Log.d(TAG, "Grant state retrieved " + result + " ("
56                 + PermissionUtils.permissionToString(result) + ")");
57         return result;
58     }
59 }