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 com.android.bips.util;
18 
19 import android.content.BroadcastReceiver;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentFilter;
23 
24 /**
25  * A stoppable receiver for broadcast messages
26  */
27 public class BroadcastMonitor extends BroadcastReceiver {
28     BroadcastReceiver mReceiver;
29     Context mContext;
30 
31     /**
32      * Deliver specified broadcast intents to the receiver until stopped.
33      *
34      * @param receiver Listener to receive all broadcast messages of interest
35      * @param actions  Broadcast intent action names to listen for
36      */
BroadcastMonitor(Context context, BroadcastReceiver receiver, String... actions)37     public BroadcastMonitor(Context context, BroadcastReceiver receiver, String... actions) {
38         IntentFilter filter = new IntentFilter();
39         for (String action : actions) {
40             filter.addAction(action);
41         }
42         mContext = context;
43         mReceiver = receiver;
44         mContext.registerReceiver(this, filter);
45     }
46 
47     /** Stop monitoring for broadcast intents */
close()48     public void close() {
49         if (mReceiver != null) {
50             mReceiver = null;
51             mContext.unregisterReceiver(this);
52         }
53     }
54 
55     @Override
onReceive(Context context, Intent intent)56     public void onReceive(Context context, Intent intent) {
57         if (intent.getAction() != null && mReceiver != null) {
58             mReceiver.onReceive(context, intent);
59         }
60     }
61 }
62