1 /*
2  * Copyright (C) 2024 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.bedstead.nene.utils;
18 
19 import android.app.PendingIntent;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentFilter;
23 
24 import com.android.bedstead.nene.TestApis;
25 
26 import java.util.UUID;
27 
28 /**
29  * Provider of a blocking version of {@link PendingIntent}.
30  */
31 public class BlockingPendingIntent implements AutoCloseable {
32 
33     private PendingIntent mPendingIntent;
34     private BlockingBroadcastReceiver mBlockingBroadcastReceiver;
35 
BlockingPendingIntent()36     private BlockingPendingIntent() {
37     }
38 
39     /** Create and register a {@link BlockingPendingIntent}. */
getBroadcast()40     public static BlockingPendingIntent getBroadcast() {
41         BlockingPendingIntent blockingPendingIntent = new BlockingPendingIntent();
42         blockingPendingIntent.register();
43         return blockingPendingIntent;
44     }
45 
register()46     private void register() {
47         String intentAction = UUID.randomUUID().toString();
48         mPendingIntent = PendingIntent.getBroadcast(TestApis.context().instrumentedContext(), 0,
49                 new Intent(intentAction), PendingIntent.FLAG_UPDATE_CURRENT);
50         mBlockingBroadcastReceiver = new BlockingBroadcastReceiver(
51                 TestApis.context().instrumentedContext());
52         TestApis.context().instrumentedContext().registerReceiver(mBlockingBroadcastReceiver,
53                 new IntentFilter(intentAction), Context.RECEIVER_EXPORTED);
54     }
55 
56     /**
57      * Wait until the broadcast and return the received broadcast intent. {@code null} is returned
58      * if no broadcast with expected action is received within the given timeout.
59      */
await(long timeoutMillis)60     public Intent await(long timeoutMillis) {
61         return mBlockingBroadcastReceiver.awaitForBroadcast(timeoutMillis);
62     }
63 
64     /** Get the pending intent. */
pendingIntent()65     public PendingIntent pendingIntent() {
66         return mPendingIntent;
67     }
68 
69     @Override
close()70     public void close() throws Exception {
71         if (mBlockingBroadcastReceiver != null) {
72             mBlockingBroadcastReceiver.unregisterQuietly();
73         }
74     }
75 }
76