项目需求
1.打开蓝牙之后等待别的蓝牙设备进行连接。
2.连接之后等待别的设备发送数据,然后接收数据。
3.跟别的蓝牙设备断开连接值进入到等待状态,等待别的蓝牙设备连接。
解决方式
java
//非手机终端的UUID
public static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9B34FB");
//手机终端的UUID
public static final UUID MOB_UUID = UUID.fromString("00001105-0000-1000-8000-00805f9B34FB");
java
private BluetoothServerSocket mSSocket;
private BluetoothSocket socket;
/**
* 监听客户端发起的连接
*/
public void listen() {
try {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
mSSocket = adapter.listenUsingRfcommWithServiceRecord(TAG, SPP_UUID); //加密传输,Android强制执行配对,弹窗显示配对码
// mSSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(TAG, MOB_UUID); //明文传输(不安全),无需配对
// 开启子线程
Util.EXECUTOR.execute(new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void run() {
try {
socket = mSSocket.accept(); // 监听连接
// mSSocket.close(); // 关闭监听,只连接一个设备
loopRead(socket); // 循环读取
} catch (Throwable e) {
close();
//当设备连接之后,对面设备断开蓝牙连接之后会出现一个 return -1 的异常
listen();
}
}
});
} catch (Throwable e) {
close();
}
}
public void close() {
super.close();
try {
if (socket != null) {
socket.close();
}
if (mSSocket != null) {
mSSocket.close();
}
} catch (Throwable e) {
e.printStackTrace();
}
}
java
private BluetoothSocket mSocket;
private DataOutputStream mOut;
/**
* 循环读取对方数据(若没有数据,则阻塞等待)
*/
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
void loopRead(BluetoothSocket socket) throws IOException {
mSocket = socket;
try {
if (!mSocket.isConnected())
mSocket.connect();
mOut = new DataOutputStream(mSocket.getOutputStream());
try (DataInputStream in = new DataInputStream(mSocket.getInputStream())) {
byte[] buffer = new byte[1024];
int bytesRead;
while (true) {
bytesRead = in.read(buffer);
if (bytesRead == -1) {
Log.e("test", "buff length: " + bytesRead);
} else {
byte[] data = new byte[bytesRead];
System.arraycopy(buffer, 0, data, 0, bytesRead);
String textData = new String(data);
Log.i("test", "Received data: " + textData);
}
}
}
} catch (IOException e) {
close();
Log.e("test", "error io:" + e.getMessage());
throw e; // 将捕获到的异常抛出
}
}