首页 > 编程知识 正文

android 蓝牙配对,安卓手机苹果手机蓝牙如何配对

时间:2023-05-04 10:37:09 阅读:196414 作者:3599

Android简单的蓝牙配对与连接

需要注意的是蓝牙配对不等于连接,这是两个不同的操作,连接是在配对成功的基础上进行的!

蓝牙搜索

通过

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关闭

基本的配对与连接差不多就这样了。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。