0
点赞
收藏
分享

微信扫一扫

【Android -- 蓝牙】蓝牙配对和蓝牙连接


文章目录

  • ​​一、蓝牙配对​​
  • ​​二、蓝牙连接​​

一、蓝牙配对

【Android -- 蓝牙】蓝牙配对和蓝牙连接_搜索


搜索到蓝牙设备后,将设备信息填充到listview中,点击listiew则请求配对

蓝牙配对有点击配对和自动配对,点击配对就是我们选择设备两个手机弹出配对确认框,点击确认后配对

自动配对就是搜索到蓝牙设备后自动配对不需要输入pin码,但在基本开发中都不采用这种方式,所以这里说的是第一种配对方式

点击配对,调用

BluetoothDevice.class.getMethod

进行配对,代码如下:

Method method = BluetoothDevice.class.getMethod("createBond");
Log.e(getPackageName(), "开始配对");
method.invoke(listdevice.get(position));

同样的,如果我们想要配对的设备取消配对

只需要将 creatBond 改为 removeBond

二、蓝牙连接

配对成功之后,就可以进行蓝牙连接了,蓝牙连接操作比较耗时,可以在一个线程中进行:

1. 调用自己定义的

connect(listdevice.get(position));

同样传递的参数也是设备device

首先声明蓝牙套接字:

private BluetoothSocket mBluetoothSocket;
...
mBluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(BltContant.SPP_UUID);

BltContant.SPP_UUID 是一个 UUID 常量,至于 UUID 是什么,大家可以自行百度,因为详细的文章已经很多了。

连接的时候要先判断蓝牙是否在扫描,如果在扫描就停止扫描,并且没有连接才进行连接,代码如下:

if (bluetoothadapter.isDiscovering()) {
bluetoothadapter.cancelDiscovery();
}
if (!mBluetoothSocket.isConnected()) {
mBluetoothSocket.connect();
}

当连接成功时,我们要让被连接的那部手机也自动跳转到聊天页面,所以我们要开启蓝牙服务端等待设备的连接,当设备连接时,自动跳转页面,蓝牙服务端代码如下:

/**
* 开启服务端
*/
public void startBluService() {

while (true) {
try {
if (getBluetoothServerSocket() == null){
Log.e("在这里获取的为空","在这里获取的为空");
}
bluetoothSocket = getBluetoothServerSocket().accept();
if (bluetoothSocket != null) {
APP.bluetoothSocket = bluetoothSocket;
EventBus.getDefault().post(new BluRxBean(SERVER_ACCEPT, bluetoothSocket.getRemoteDevice()));
//如果你的蓝牙设备只是一对一的连接,则执行以下代码
getBluetoothServerSocket().close();
//如果你的蓝牙设备是一对多的,则应该调用break;跳出循环
//break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}


举报

相关推荐

0 条评论