1 /*
2  * Copyright (C) 2017 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.app.cts.android.app.cts.tools;
18 
19 import android.content.BroadcastReceiver;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentFilter;
23 import android.os.SystemClock;
24 
25 /**
26  * Helper to wait for a broadcast to be sent.
27  */
28 public class WaitForBroadcast {
29     final Context mContext;
30 
31     String mWaitingAction;
32     boolean mHasResult;
33     Intent mReceivedIntent;
34 
35     final BroadcastReceiver mReceiver = new BroadcastReceiver() {
36         @Override public void onReceive(Context context, Intent intent) {
37             synchronized (WaitForBroadcast.this) {
38                 mReceivedIntent = intent;
39                 mHasResult = true;
40                 WaitForBroadcast.this.notifyAll();
41             }
42         }
43     };
44 
WaitForBroadcast(Context context)45     public WaitForBroadcast(Context context) {
46         mContext = context;
47     }
48 
prepare(String action)49     public void prepare(String action) {
50         if (mWaitingAction != null) {
51             throw new IllegalStateException("Already prepared");
52         }
53         mWaitingAction = action;
54         IntentFilter filter = new IntentFilter();
55         filter.addAction(action);
56         mContext.registerReceiver(mReceiver, filter);
57     }
58 
doWait(long timeout)59     public Intent doWait(long timeout) {
60         final long endTime = SystemClock.uptimeMillis() + timeout;
61 
62         synchronized (this) {
63             while (!mHasResult) {
64                 final long now = SystemClock.uptimeMillis();
65                 if (now >= endTime) {
66                     String action = mWaitingAction;
67                     cleanup();
68                     throw new IllegalStateException("Timed out waiting for broadcast " + action);
69                 }
70                 try {
71                     wait(endTime - now);
72                 } catch (InterruptedException e) {
73                 }
74             }
75             cleanup();
76             return mReceivedIntent;
77         }
78     }
79 
cleanup()80     void cleanup() {
81         if (mWaitingAction != null) {
82             mContext.unregisterReceiver(mReceiver);
83             mWaitingAction = null;
84         }
85     }
86 }
87