【Android】蓝牙开发—— 经典蓝牙连接方法

一、官方API

Android官方API给出的经典蓝牙连接方法有2个

  • createRfcommSocketToServiceRecord
    该方法建立的是一种安全的连接。意思就是,与蓝牙设备建立连接时,如果与蓝牙设备没有建立过配对关系,那么连接时会先去建立配对关系,然后再执行连接;如果与蓝牙设备已建立了配对关系,那么就会直接执行连接。
    调用的结果是,连接成功的同时也配对成功了。
//建立安全的蓝牙连接
BluetoothSocket BluetoothSocket 
= bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
  • createInsecureRfcommSocketToServiceRecord
    该方法建立的是一种非安全的连接。意思就是,与蓝牙设备建立连接时,如果与蓝牙设备没有建立过配对关系,就会跳过配对过程,直接执行连接。
    调用的结果是,连接成功了,但是没有建立配对关系。
//建立不安全的蓝牙连接
BluetoothSocket BluetoothSocket 
= bluetoothDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(uuid));
二、通过反射获取的串口号连接的方法

反射方法获取的通过串口号连接方法有2个:

BluetoothSocket BluetoothSocket 
= (BluetoothSocket)mmDevice.getClass().getMethod("createRfcommSocket",new Class[] {int.class}).invoke(bluetoothDevice,channel);
BluetoothSocket BluetoothSocket 
= (BluetoothSocket) mmDevice.getClass().getMethod("createInsecureRfcommSocket",new Class[] {int.class}).invoke(bluetoothDevice,channel);

默认串口号为1,如果实际过程指定了串口号连接,需要使用指定的串口号连接。

发布了29 篇原创文章 · 获赞 14 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章