需要注意的是蓝牙配对不等于连接,这是两个不同的操作,连接是在配对成功的基础上进行的!
蓝牙搜索通过
BluetoothAdapter.getDefaultAdapter()获取BluetoothAdapter对象,然后通过
bluetoothAdapter.startDiscovery()搜索周围的蓝牙设备
取消搜索
bluetoothAdapter.cancelDiscovery()蓝牙的搜索结果是通过广播进行返回的,所以我们需要注册广播。主要是下面这两个:
BluetoothDevice.ACTION_FOUND(搜索,搜到一个设备就会发这个广播)BluetoothAdapter.ACTION_DISCOVERY_FINISHED(搜索完成时的广播)搜索完蓝牙后就要进行关键的配对了
蓝牙配对这里有个版本问题,在aip小于19的版本是没有配对方法可供调用的我们这能通过反射的方式配对
public boolean createBond(Class btClass, BluetoothDevice btDevice) throws Exception { Method createBondMethod = btClass.getMethod("createBond"); Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice); return returnValue.booleanValue();}api高于19的版本就很简单了
device.createBond();用这个方法直接搞定蓝牙的配对状态也是通过广播的方式进行通知的,我们需要注册下面这个广播
BluetoothDevice.ACTION_BOND_STATE_CHANGED分别有几种状态
BluetoothDevice.BOND_BONDING//正在配对BluetoothDevice.BOND_NONE//配对取消BluetoothDevice.BOND_BONDED//配对成功如果要取消配对只能通过反射的方式取消
public boolean cancelBondProcess(ClassbtClass,BluetoothDevice device)throws Exception{ Method createBondMethod = btClass.getMethod("cancelBondProcess"); Boolean returnValue = (Boolean) createBondMethod.invoke(device); return returnValue.booleanValue();} 蓝牙连接直接一个方法
final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";private void connect(BluetoothDevice btDev) { UUID uuid = UUID.fromString(SPP_UUID); try { BluetoothSocket socket = dev.createRfcommSocketToServiceRecord(uuid); socket.connect(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }完了后要把socket关闭
基本的配对与连接差不多就这样了。