蓝牙开发相关
使用Android Bluetooth APIs将设备通过蓝牙连接并通信,设置蓝牙,查找蓝牙设备,配对蓝牙设备
连接并传输数据,以下是Android系统提供的蓝牙相关的类和接口
BluetoothAdapter
BluetoothDevice
BluetoothSocket
BluetoothServerSocket
BluetoothClass
BluetoothProfile
BluetoothHeadset
BluetoothA2dp
BluetoothHealth
BluetoothHealthCallback
BluetoothHealthAppConfiguration
BluetoothProfile.ServiceListener
蓝牙权限
使用蓝牙功能,需要在AndroidManifest.xml中声明蓝牙相关的权限
建立蓝牙
初始化连接
在通过蓝牙通信之前,需要先确定设备是否支持蓝牙功能,先初始化一个BluetoothAdapter的实例,
BluetoothAdapter提供了一个静态方法getDefaultAdapter()来获得BluetoothAdapter的实例
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// 设备不支持蓝牙功能
}
打开蓝牙
下一步就是打开蓝牙,调用isEnabled()方法检查蓝牙功能是否已经打开,返回true说明蓝牙已开启,
返回false说明蓝牙功能未开启,开启蓝牙可以通过发送广播ACTION_REQUEST_ENABLE,也可以通过方法
enable()直接打开,这两种方法都会有蓝牙权限的提示,选择允许,否则无法打开蓝牙
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);</