首先需要确保设备上已启用BLE功能。然后,在需要连接Socket时,使用BLE作为通信协议建立连接。具体实现方法如下:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothLeScanner mBluetoothScanner = mBluetoothAdapter.getBluetoothLeScanner();
ScanFilter filter = new ScanFilter.Builder()
.setServiceUuid(new ParcelUuid(SERVICE_UUID))
.build();
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
connectToDevice(result.getDevice());
}
};
mBluetoothScanner.startScan(Collections.singletonList(filter), settings, mScanCallback);
private void connectToDevice(BluetoothDevice device) {
BluetoothGatt mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
}
Socket mSocket = new Socket();
mSocket.connect(new InetSocketAddress("192.168.0.2", 1234), CONNECT_TIMEOUT_MS);
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
BluetoothGattService service = gatt.getService(SERVICE_UUID);
mBluetoothGatt.setCharacteristicNotification(service.getCharacteristic(CHARACTERISTIC_UUID), true);
BluetoothDevice device = gatt.getDevice();
mSocket.getOutputStream().write("Socket connected from BLE device: " + device.getName());
}
}
};
上一篇:BLEL2CAP层-分段与分片
下一篇:BLE连接缓冲区大小与数据包长度