Android手机间通过蓝牙方式进行通信,有两种常见的方式,一种是socket方式,另一种是通过Gatt Server(Android 5.0以后)通信,socket方式最为简单,但是很多低功耗的蓝牙设备,如单片机上的蓝牙模块可能不支持。而Gatt方式说起来就比较复杂,我研究了好会儿,搜索了不少资料,走了不少弯路才总结出来。
- 首先来看比较简单的socket方式
其实无论是socket方式还是Gatt,Android设备间蓝牙通信都是一种CS(client-server)模式。
1)socket服务端:
使用listenUsingInsecureRfcommWithServiceRecord接口开启监听,其他同一般的socket网络通信没区别:
init{
mSocket = mBleAdapter.listenUsingInsecureRfcommWithServiceRecord("GomeServer", Constants.BLE_SERVICE_UUID)
}
override fun run() {
var socket: BluetoothSocket?
try{
while(running) {
socket = mSocket.accept()
if(socket != null) {
val inputStream = socket.inputStream
val os = socket.outputStream
var read:Int
val byteArray = ByteArray(1024) {
0}
while(socket.isConnected) {
read = inputStream.read(byteArray)
if(read == -1) break
val byte = ByteArray(read){
byteArray[it] }
val message = Message.obtain()
message.obj = String(byte)
mHandler.sendMessage(message)
//Thread.sleep(2000)
break
}
os.close()
socket.close()
}
}
} catch(e:IOException) {
e.printStackTrace()
}
}
2)socket客户端
客户端对应的接口是createRfcommSocketToServiceRecord:
private void connectBleDeviceSocket(final BluetoothDevice device, final String content) {
if(sSocket != null) {
try {
sSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
sSocket = null;
}
OutputStream out = null;
try {
sSocket = device.createRfcommSocketToServiceRecord(Constants.MY_SERVICE_UUID);
if(sSocket != null) {
sSocket.connect();
out = sSocket.getOutputStream();
out.write(content.getBytes());
Thread.sleep(100);
}
} catch (IOException | InterruptedException e) {
Log.e(TAG,"stack:", e);
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(sSocket != null) {
try {
sSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
至于device可以直接通过mac获取:
BluetoothDevice de