从ANDROID3.0开始,BLUETOOTH API提供了Bluetooth profile协议的支持。目前ANDROID4.0的蓝牙API提供了五种蓝牙无线接口规范(Bluetooth profile)的支持,用来在设备之间通过蓝牙实现特定功能:包括 Headset和Hands-Freeprofile(实现蓝牙耳机功能),A2dpprofile(第二代蓝牙声音设备协议,用来在蓝牙设备之间实现高质量的声音传输),InputDeviceprofile(实现蓝牙输入设备功能),Bluetooth Panprofile(实现蓝牙个人局域网功能),Bluetooth Healthprofile(实现蓝牙健康设备规范,用来与支持蓝牙健康设备规范的设备进行蓝牙通讯)。另外还有Bluetooth Pbapprofile(实现蓝牙电话本功能),但接口和其它profile实现不一致。
ANDROID对 Bluetooth profile API的实现主要采用了中介模式、代理模式及状态模式等。
应用通过一个统一的类BluetoothAdapter(蓝牙本地适配器类)与这些蓝牙设备协议对应的BLUETOOTH API进行交互。
BluetoothAdapter是所有蓝牙对象交互和执行蓝牙操作的入口:包括调用BLUETOOTH profile API,发现其它蓝牙设备、查询配对成功的设备、使用已知的MAC地址实例化蓝牙设备、创建一个BluetoothServerSocket对象来监听其它蓝牙设备以及根据地址实例化蓝牙设备等操作。
应用为了使用蓝牙功能,JELLY_BEAN_MR1以下的版本使用如下方式获得BluetoothAdapter单例对象。
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
JELLY_BEAN_MR2以后的版本,使用如下方式来调用蓝牙API。
BluetoothManager bluetoothManager =
(BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mAdpter=bluetoothManager.getAdapter();
几乎所有的蓝牙对象和所有的蓝牙服务都维护一个BluetoothAdapter单例对象,BluetoothAdapter单例对象通过BluetoothAdapter类提供的getDefaultAdapter函数获得。BluetoothAdapter对象可以说是整个系统交互的中介,是中介设计模式的采用。
而几个蓝牙设备协议的实现借助几个ANDROID服务来实现,并通过代理对象对外提供BLUETOOTH API。Headset对应的代理对象为BluetoothHeadset,A2dp对应的代理对象为BluetoothA2dp&#x