随着智能设备的普及,蓝牙开发在手机应用端使用的越来越多。但是目前网上对蓝牙开发的介绍还相当少,刚开始接触蓝牙开发时,都是边网上搜边看源码,花费了不少功夫,总算是对蓝牙开发略知一二了。
蓝牙设备之间建立连接分为三个部分:1.Bond(Pair)、2.Profile、3.Socket
1.Bond,Bond即设备之间绑定(配对),这是蓝牙设备之间通信的基础。当搜索到需要bond的设备时,获取到设备对应的BluetoothDevice对象时,我们就可以进行bond操作了。查看BluetoothDevice源码,在其方法中可以找到一个叫“createBond()”方法,该方法即是蓝牙bond的核心方法,但需要注意的是,该方法在API19之前是@hide的,所以minSdk设置小于API19时,需要通过反射来调用该方法
/**
* Start the bonding (pairing) process with the remote device.
* <p>This is an asynchronous call, it will return immediately. Register
* for {@link #ACTION_BOND_STATE_CHANGED} intents to be notified when
* the bonding process completes, and its result.
* <p>Android system services will handle the necessary user interactions
* to confirm and complete the bonding process.
* <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
*
* @return false on immediate error, true if bonding will begin
*/
@RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
public boolean createBond() {
if (sService == null) {
Log.e(TAG, "BT not enabled. Cannot create bond to Remote Device");
return false;
}
try {
return sService.createBond(this, TRANSPORT_AUTO);
} catch (RemoteException e) {Log.e(TAG, "", e);}
return false;
}
通过查看源码,不难看出,createBond方法在执行时,调用了IPC,需要了解具体实现过程的,可以去查看“sService ”这个IPC类的源码,这里就不再深入。
2.Profile,Profile是蓝牙的一个很重要特性,Profile定义了设备如何实现一种连接或者应用,你可以把Profile理解为连接层或者应用层协。
下面来介绍Profile的连接:
在android framework层中,Profile同样是封装成了一个个IPC类,在BluetoothAdapter中提供了”getProfileProxy(Context context, BluetoothProfile.ServiceListener listener, int profile)”方法连接IPC实例获取到这些Profile服务的代理来操作这些profile以及”closeProfileProxy(int profile, BluetoothProfile profile)”来关闭这些Profile的代理
/**
* Get the profile proxy object associated with the profile.
*
* <p>Profile can be one