Android Bluetooth蓝牙技术初体验

2019-12-10 19:08:18王冬梅

startDiscovery()开始搜索,这是搜索的第一步

BluetoothDevice:远程蓝牙设备

createRfcommSocketToServiceRecord(UUIDuuid)根据UUID创建并返回一个BluetoothSocket,这个方法也是我们获取BluetoothDevice
的目的——创建BluetoothSocket

这个类其他的方法,如getAddress()、getName()等,同BluetoothAdapter。

BluetoothSocket:客户端

//这个类一共有6个方法
close()关闭
connect()连接
isConnected()判断是否连接
getInptuStream()获取输入流
getOutputStream()获取输出流
getRemoteDevice()获取BluetoothSocket指定连接的远程蓝牙设备

BluetoothServerSocket:服务端

//这个类一共有4个方法
accept()
accept(int timeout)
close()关闭
getChannel()返回这个套接字绑定的通道

两者的区别在于后面的方法指定了过时时间,需要注意的是,执行这两个方法的时候,直到接收到了客户端的请求(或是过期之后),都会阻塞线程,应该放在新线程里运行。还有一点需要注意的是,这两个方法都返回一个BluetoothSocket,最后的连接也是服务器端与客户端的两个BluetoothSocket的连接

三:数据传输

蓝牙数据传输——服务器端

1、获得BluetoothAdapter。 
2、通过BluetoothAdapter.listenUsingRfcommWithServiceRecord(name,UUID uuid)方法创建BluetoothServerSocket对象。 
3、通过luetoothServerSocket.accept()方法返回一个BluetoothSocket对象。由于该方法处于阻塞状态,需要开启线程来处理。 
4、通过BluetoothSocket.getInputStream()和BluetoothSocket.getOutputStream()方法获得读写数据的InputStream和OutputStream对象。 
5、通过InputStream.read()方法来读数据。通过OutputStream.write()方法来写数据。

蓝牙数据传输——客户端

1、获得BluetoothAdapter。 
2、通过BluetoothAdapter.getRemoteDevice(String address)获得指定地址的BluetoothDevice对象。