蓝牙通讯协议有两种: GATT 和 SPP
之前已经介绍了 BLE 是如何进行简单的通讯,现在介绍 SPP 具体的方法。
- 连接
// 取消所有正在连接/已经连接的线程,然后重新建立连接
public synchronized void connect(BluetoothDevice device) {
if (D) Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == ConnectionState.SPP_CONNECTING) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device);
mConnectThread.start();
}
- 开启线程,进行连接。
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
private BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
if (device != null) {
mmDevice = device;
BluetoothSocket tmp = null;