由于 iOS 和 Android 的蓝牙发现和通信代码实现方式不同,因此需要分别列出。

iOS 蓝牙发现和通信代码

  1. 导入 CoreBluetooth 框架
  2. 实现 CBCentralManagerDelegate 协议和 CBPeripheralDelegate 协议
  3. 初始化 CBCentralManager 对象
  4. 扫描周围的蓝牙设备
  5. 连接蓝牙设备
  6. 发现蓝牙设备的服务和特征
  7. 读取和写入蓝牙设备的数据

下面是 iOS 蓝牙发现和通信的代码示例:

#import <CoreBluetooth/CoreBluetooth.h>

@interface ViewController () <CBCentralManagerDelegate, CBPeripheralDelegate>

@property (nonatomic, strong) CBCentralManager *centralManager;
@property (nonatomic, strong) CBPeripheral *peripheral;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}

#pragma mark - CBCentralManagerDelegate

- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    if (central.state == CBManagerStatePoweredOn) {
        [central scanForPeripheralsWithServices:nil options:nil];
    }
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
    if ([peripheral.name isEqualToString:'MyDevice']) {
        self.peripheral = peripheral;
        [central stopScan];
        [central connectPeripheral:peripheral options:nil];
    }
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    peripheral.delegate = self;
    [peripheral discoverServices:nil];
}

#pragma mark - CBPeripheralDelegate

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    for (CBService *service in peripheral.services) {
        [peripheral discoverCharacteristics:nil forService:service];
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    for (CBCharacteristic *characteristic in service.characteristics) {
        if (characteristic.properties & CBCharacteristicPropertyRead) {
            [peripheral readValueForCharacteristic:characteristic];
        }
        if (characteristic.properties & CBCharacteristicPropertyNotify) {
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:'MyCharacteristicUUID']]) {
        NSData *data = characteristic.value;
        // 处理接收到的数据
    }
}

@end

Android 蓝牙发现和通信代码

  1. 导入 android.bluetooth 包
  2. 初始化 BluetoothAdapter 对象
  3. 扫描周围的蓝牙设备
  4. 连接蓝牙设备
  5. 发现蓝牙设备的服务和特征
  6. 读取和写入蓝牙设备的数据

下面是 Android 蓝牙发现和通信的代码示例:

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = null;

// 扫描周围的蓝牙设备
adapter.startDiscovery();
BroadcastReceiver receiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device.getName().equals('MyDevice')) {
                adapter.cancelDiscovery();
                connectDevice(device);
            }
        }
    }
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);

// 连接蓝牙设备
private void connectDevice(BluetoothDevice device) {
    BluetoothSocket socket = null;
    try {
        socket = device.createRfcommSocketToServiceRecord(UUID.fromString('MyUUID'));
        socket.connect();
        discoverServices(socket);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// 发现蓝牙设备的服务和特征
private void discoverServices(BluetoothSocket socket) {
    BluetoothDevice device = socket.getRemoteDevice();
    BluetoothGatt gatt = device.connectGatt(this, false, new BluetoothGattCallback() {
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            BluetoothGattService service = gatt.getService(UUID.fromString('MyServiceUUID'));
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString('MyCharacteristicUUID'));
            gatt.setCharacteristicNotification(characteristic, true);
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString('MyDescriptorUUID'));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            gatt.writeDescriptor(descriptor);
        }
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            byte[] data = characteristic.getValue();
            // 处理接收到的数据
        }
    });
}

// 读取和写入蓝牙设备的数据
private void sendData(BluetoothSocket socket, String data) {
    OutputStream outputStream = socket.getOutputStream();
    outputStream.write(data.getBytes());
    InputStream inputStream = socket.getInputStream();
    byte[] buffer = new byte[1024];
    int byteCount = inputStream.read(buffer);
    String receivedData = new String(buffer, 0, byteCount);
}
iOS 和 Android 蓝牙发现和通信代码实现

原文地址: https://www.cveoy.top/t/topic/lHCz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录