1 /*
2  * Copyright (C) 2018 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.rollback.lib;
18 
19 import android.content.BroadcastReceiver;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentFilter;
23 import android.util.Log;
24 
25 import androidx.test.InstrumentationRegistry;
26 
27 import java.util.concurrent.BlockingQueue;
28 import java.util.concurrent.LinkedBlockingQueue;
29 import java.util.concurrent.TimeUnit;
30 
31 /**
32  * A broadcast receiver that can be used to get
33  * ACTION_ROLLBACK_COMMITTED broadcasts.
34  */
35 public class RollbackBroadcastReceiver extends BroadcastReceiver {
36 
37     private static final String TAG = "RollbackTest";
38 
39     private final BlockingQueue<Intent> mRollbackBroadcasts = new LinkedBlockingQueue<>();
40 
41     /**
42      * Creates a RollbackBroadcastReceiver and registers it with the given
43      * context.
44      */
RollbackBroadcastReceiver()45     public RollbackBroadcastReceiver() {
46         IntentFilter filter = new IntentFilter();
47         filter.addAction(Intent.ACTION_ROLLBACK_COMMITTED);
48         InstrumentationRegistry.getContext().registerReceiver(this, filter);
49     }
50 
51     @Override
onReceive(Context context, Intent intent)52     public void onReceive(Context context, Intent intent) {
53         Log.i(TAG, "Received rollback broadcast intent");
54         mRollbackBroadcasts.add(intent);
55     }
56 
57     /**
58      * Polls for at most the given amount of time for the next rollback
59      * broadcast.
60      */
poll(long timeout, TimeUnit unit)61     public Intent poll(long timeout, TimeUnit unit) throws InterruptedException {
62         return mRollbackBroadcasts.poll(timeout, unit);
63     }
64 
65     /**
66      * Waits forever for the next rollback broadcast.
67      */
take()68     public Intent take() throws InterruptedException {
69         return mRollbackBroadcasts.take();
70     }
71 
72     /**
73      * Unregisters this broadcast receiver.
74      */
unregister()75     public void unregister() {
76         InstrumentationRegistry.getContext().unregisterReceiver(this);
77     }
78 }
79