Android studio低功耗蓝牙代码
时间: 2023-12-20 11:07:00 浏览: 139
以下是一个简单的 Android Studio 低功耗蓝牙代码示例,用于连接和发送数据:
1. 首先,确保您的设备支持低功耗蓝牙,并在项目中添加以下权限:
```xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
```
2. 在您的活动中,声明以下变量:
```java
private BluetoothAdapter bluetoothAdapter;
private BluetoothGatt bluetoothGatt;
private BluetoothGattCharacteristic characteristic;
private boolean connected = false;
```
3. 初始化蓝牙适配器:
```java
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
```
4. 扫描和连接到设备:
```java
private void connectToDevice(String deviceAddress) {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
bluetoothGatt = device.connectGatt(this, false, gattCallback);
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
connected = true;
bluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
connected = false;
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
characteristic = gatt.getService(serviceUUID)
.getCharacteristic(characteristicUUID);
}
}
};
```
5. 发送数据:
```java
private void sendData(String data) {
if (connected && characteristic != null) {
byte[] bytes = data.getBytes(Charset.forName("UTF-8"));
characteristic.setValue(bytes);
bluetoothGatt.writeCharacteristic(characteristic);
}
}
```
请注意,上面的代码仅供参考,并且需要根据您的设备和需求进行修改。
阅读全文