蓝牙API笔记
常用API :
- BluetoothAdapter
- BluetoothDevice
- BluetoothSocket
BluetoothAdapter 代表一个蓝牙适配器硬件
通过BluetoothAdapter 可以打开/关闭蓝牙适配器 扫描周边蓝牙设备…
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
打开/关闭 蓝牙设备
bluetoothAdapter.enable(); bluetoothAdapter.disable();
操作蓝牙设备需要权限
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
扫描/停止扫描蓝牙设备
bluetoothAdapter.startDiscovery(); bluetoothAdapter.cancelDiscovery();
系统发现周边的蓝牙设备会发一个广播
BluetoothDevice.ACTION_FOUND
监听BluetoothDevice.ACTION_FOUND广播 收到广播后可以从intent中获取到蓝牙设备
- BluetoothDevice 代表一个可以连接的蓝牙硬件对象
通过BluetoothDevice可以获得 BluetoothSocket对象
socket = device.createRfcommSocketToServiceRecord(UUID.fromString( "00001101-0000-1000-8000-00805f9b34fb"));
- 获得BluetoothSocket对象之后可以调用 connect();方法跟服务端创建连接
连接创建后可以通过 BluetoothSocket对象获得输入输出流
创建蓝牙连接步骤
① 通过BluetoothAdapter打开蓝牙适配器 ② 通过bluetoothAdapter.startDiscovery();扫描硬件 ③ 创建广播接收者监听BluetoothDevice.ACTION_FOUND广播 获得BluetoothDevice对象 ④ 通过device.createRfcommSocketToServiceRecord(UUID uuid);获得BluetoothSocket ⑤ BluetoothSocket 的connect();方法 连接到蓝牙设备 ⑥ 通过BluetoothSocket获得输入输出流 通过流传递数据