1 /* 2 * Copyright 2021 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.server.nearby.common.bluetooth.fastpair; 18 19 import static com.android.server.nearby.common.bluetooth.fastpair.BluetoothAddress.maskBluetoothAddress; 20 21 import android.bluetooth.BluetoothDevice; 22 import android.content.Context; 23 import android.content.Intent; 24 import android.util.Log; 25 26 /** 27 * Like {@link SimpleBroadcastReceiver}, but for intents about a certain {@link BluetoothDevice}. 28 */ 29 abstract class DeviceIntentReceiver extends SimpleBroadcastReceiver { 30 31 private static final String TAG = DeviceIntentReceiver.class.getSimpleName(); 32 33 private final BluetoothDevice mDevice; 34 oneShotReceiver( Context context, Preferences preferences, BluetoothDevice device, String... actions)35 static DeviceIntentReceiver oneShotReceiver( 36 Context context, Preferences preferences, BluetoothDevice device, String... actions) { 37 return new DeviceIntentReceiver(context, preferences, device, actions) { 38 @Override 39 protected void onReceiveDeviceIntent(Intent intent) throws Exception { 40 close(); 41 } 42 }; 43 } 44 45 /** 46 * @param context The context to use to register / unregister the receiver. 47 * @param device The interesting device. We ignore intents about other devices. 48 * @param actions The actions to include in our intent filter. 49 */ 50 protected DeviceIntentReceiver( 51 Context context, Preferences preferences, BluetoothDevice device, String... actions) { 52 super(context, preferences, actions); 53 this.mDevice = device; 54 } 55 56 /** 57 * Called with intents about the interesting device (see {@link #DeviceIntentReceiver}). Any 58 * exception thrown by this method will be delivered via {@link #await}. 59 */ 60 protected abstract void onReceiveDeviceIntent(Intent intent) throws Exception; 61 62 // incompatible types in argument. 63 @Override 64 protected void onReceive(Intent intent) throws Exception { 65 BluetoothDevice intentDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 66 if (mDevice == null || mDevice.equals(intentDevice)) { 67 onReceiveDeviceIntent(intent); 68 } else { 69 Log.v(TAG, 70 "Ignoring intent for device=" + maskBluetoothAddress(intentDevice) 71 + "(expected " 72 + maskBluetoothAddress(mDevice) + ")"); 73 } 74 } 75 } 76