扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

android钃濈墮浼犺緭鏁版嵁鍔熻兘鎬庝箞瀹炵幇

扬州沐宇科技
2023-10-07 20:17:45
android

鍦ˋndroid涓紝鍙互浣跨敤BluetoothAdapter绫绘潵瀹炵幇钃濈墮浼犺緭鏁版嵁鐨勫姛鑳姐€備互涓嬫槸瀹炵幇钃濈墮浼犺緭鏁版嵁鐨勫熀鏈楠わ細

  1. 妫€鏌ヨ澶囨槸鍚︽敮鎸佽摑鐗欏姛鑳斤細
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// 璁惧涓嶆敮鎸佽摑鐗欏姛鑳?/span>
}
  1. 鎵撳紑钃濈墮锛?/li>
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
  1. 鎵弿骞惰繛鎺ヨ摑鐗欒澶囷細
bluetoothAdapter.startDiscovery();
// 鍦˙roadcastReceiver涓鐞嗘壂鎻忓埌鐨勮澶?/span>
private final 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);
// 杩炴帴璁惧
device.connectGatt(context, false, gattCallback);
}
}
};
  1. 鏁版嵁浼犺緭锛?/li>
// 鍦˙luetoothGattCallback涓鐞嗘暟鎹紶杈?/span>
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
...
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
BluetoothGattService service = gatt.getService(SERVICE_UUID);
BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_UUID);
// 鍙戦€佹暟鎹?/span>
characteristic.setValue(data);
gatt.writeCharacteristic(characteristic);
// 鎺ユ敹鏁版嵁
gatt.setCharacteristicNotification(characteristic, true);
}
}
...
};

浠ヤ笂鏄熀鏈殑钃濈墮浼犺緭鏁版嵁鐨勫疄鐜版楠わ紝鍏蜂綋瀹炵幇杩橀渶鏍规嵁闇€姹傝繘琛岃繘涓€姝ュ鐞嗐€?/p>

扫码添加客服微信