好厚米们,我又来了!
这次分享的是蓝牙设备执行配对动作时Android源码的执行流程。
下面先来说下,应用层是如何发起蓝牙配对的:
( ps:大多数业务逻辑,都是扫描到可用设备后,点击可用设备 -> 发起配对。)
这里我直接略过点击可用设备的步骤哈,扫描到第一个可用设备后,我直接通过扫描信息进行配对。
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
private BluetoothDevice mBluetoothDevice;
private BluetoothLeScanner scanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ScanCallback scanCallback = new ScanCallback() {
@SuppressLint("MissingPermission")
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
//将扫描到的设备信息取出来,为蓝牙设备赋值
mBluetoothDevice = result.getDevice();
//通过蓝牙设备,调用配对方法
mBluetoothDevice.createBond();
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
// 扫描失败处理
}
};
// 开始扫描
if (scanner != null) {
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
// 添加过滤条件
List<ScanFilter> filters = new ArrayList<>();
//权限检查
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
scanner.startScan(filters, settings, scanCallback);
}
// 停止扫描
if (scanner != null) {
scanner.stopScan(scanCallback);
}
mBluetoothAdapter.startDiscovery();
}
}
由上面的代码可以看出,配对动作的执行依赖
//通过蓝牙设备,调用配对方法
BluetoothDevice.createBond();
下面就进入到了FWK层
执行BluetoothDevice.createBond()后,会进入到BluetoothDevice.java中执行
public boolean createBond() {
final IBluetooth service = sService;
if (service == null) {
Log.e(TAG, "BT not enabled. Cannot create bond to Remote Device");
return false;
}
try {
Log.i(TAG, "createBond() for device " + getAddress()
+ " called by pid: " + Process.myPid()
+ " tid: " + Process.myTid());
//通过service接口执行配对动作
return service.createBond(this, TRANSPORT_AUTO);
} catch (RemoteException e) {
Log.e(TAG, "", e);
}
return false;
}
而这个service,我们来看下其声明
private static volatile IBluetooth sService;
//后来在上面的配对方法中,为此接口赋值
final IBluetooth service = sService;
本质上就是IBluetooth接口,不过在Android 10中,IBluetooth接口一共有两个。
应用层下发配对动作时,所用的IBludetooth接口是/system/bt/service/common/android/bluetooth/
此接口的具体代码如下(太多了,各位厚米自己点连接看下就行):
IBluetooth.aidl - OpenGrok cross reference for /system/bt/binder/android/bluetooth/IBluetooth.aidl
即通过这个AIDL接口调用蓝牙远程服务。
下面进入了Bluetooth 服务层
而这个接口的实现