Ble蓝牙API

Ble蓝牙API

1.获取蓝牙管理器

  • BluetoothManager buetoothManage = getSystemService(Context.BLUETOOTH_SERVICE);
    2.获取蓝牙适配器
  • BlueToothAdapter bluetoothAdapter = bluetoothManager.getAdapter();

3.获取蓝牙扫描器

  • bleScanner = bluetoothAdapter.getBluetoothLeScanner();
  • bleScanner.startScan(scanCallback);
// BLE扫描回调
    private final ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            
            BluetoothDevice device = result.getDevice();
            String deviceName = device.getName();
            
            // 过滤设备名称
            if (deviceName != null && deviceName.contains(DEVICE_NAME_FILTER) && 
                !deviceList.contains(device)) {
                
                deviceList.add(device);
                devicesAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        }
        
        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            statusText.setText("扫描失败: " + errorCode);
            scanning = false;
            btnScan.setText("扫描设备");
        }
    };

4.连接设备

   BluetoothGatt   bluetoothGatt ;
    private void connectDevice() {
        bluetoothGatt = selectedDevice.connectGatt(this, false, gattCallback);
    }

private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        /// 监听蓝牙连接
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                runOnUiThread(() -> {
                    statusText.setText("已连接,发现服务中...");
                });

            } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                runOnUiThread(() -> {
                    statusText.setText("已断开连接");

                });
            }
        }

        /// 发现BluetoothGatt服务
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
             List<BluetoothGattService> gattServices =gatt.getServices();
            BluetoothGattCharacteristic charData = bluetoothGatt.getService(SERVICE_UUID).getCharacteristic(DATA_UUID);
            BluetoothGattCharacteristic charHeartbeat = bluetoothGatt.getService(SERVICE_UUID).getCharacteristic(HEARTBEAT_UUID);
            //设置开启特性监听,这样onCharacteristicChanged才会有回调数据
            bluetoothGatt.setCharacteristicNotification(charData, true);
            bluetoothGatt.setCharacteristicNotification(charHeartbeat, true);

        }
        /// 特性变化时,收到通知
        @Override
        public void onCharacteristicChanged(
                BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic
        ) {
            super.onCharacteristicChanged(gatt, characteristic);
            // 这里处理从BLE设备接收到的数据
            byte[] data = characteristic.getValue();
            if (data != null && data.length > 0) {
                String receivedData = new String(data, StandardCharsets.UTF_8);

                // 在主线程更新UI
                runOnUiThread(() -> {
                    //parseAndDisplayData(receivedData);
                });
            }
        }
    };

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • """1.个性化消息: 将用户的姓名存到一个变量中,并向该用户显示一条消息。显示的消息应非常简单,如“Hello ...
    她即我命阅读 5,360评论 0 6
  • 1、expected an indented block 冒号后面是要写上一定的内容的(新手容易遗忘这一点); 缩...
    庵下桃花仙阅读 1,103评论 1 2
  • 一、工具箱(多种工具共用一个快捷键的可同时按【Shift】加此快捷键选取)矩形、椭圆选框工具 【M】移动工具 【V...
    墨雅丫阅读 1,620评论 0 0
  • 跟随樊老师和伙伴们一起学习心理知识提升自已,已经有三个月有余了,这一段时间因为天气的原因休课,顺便整理一下之前学习...
    学习思考行动阅读 1,024评论 0 2
  • 一脸愤怒的她躺在了床上,好几次甩开了他抱过来的双手,到最后还坚决的翻了个身,只留给他一个冷漠的背影。 多次尝试抱她...
    海边的蓝兔子阅读 1,026评论 1 4

友情链接更多精彩内容