美文网首页
Android Ble

Android Ble

作者: 皮皮铭 | 来源:发表于2019-08-22 16:44 被阅读0次

首先了解一下BLE 重要的几个类
BluetoothAdapter表示本地设备蓝牙适配器。
BluetoothDevice表示远程蓝牙设备。
BluetoothGatt提供蓝牙GATT功能,以实现与蓝牙智能或智能就绪设备的通信。
BluetoothGattServer提供蓝牙GATT服务器角色功能,允许应用程序创建和通告蓝牙智能服务和特性。
BluetoothGattCharacteristic代表蓝牙GATT特性,通信的关键。

开启BLE扫描

private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

adapter.startLeScan(callback);

callback 开始扫描的回调方法

 private BluetoothDevice mBluetoothDevice;

 private BluetoothAdapter.LeScanCallback callback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int arg1, byte[] arg2) {
            mBluetoothDevice = device;
            try {
//我是根据名字来连接,具体根据你们的业务来写
                if (mBluetoothDevice .getName().equals("蓝牙")) {
                    Log.e(TAG, "onLeScan:停止 ");
//停止扫描,不停止一直扫描会非常消耗资源,电量会咻咻咻的没了
                    adapter.stopLeScan(callback);
                    try {
                        Thread.sleep(200);
                        mBluetoothGatt = mBluetoothDevice.connectGatt(MainActivity.this, false, gattCallback);
                    } catch (Exception e) {

                    }
                }
            } catch (Exception e) {
            }
        }
    };

connectGatt 之后就会到BluetoothGattCallback回调,有9个回调,具体看官方的API文档

    //BluetoothGattCallback回调
    private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        //连接状态的回调
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            Log.e(TAG, "onConnectionStateChange:status " + status);
            Log.e(TAG, "onConnectionStateChange:newState " + newState);
          //连接成功
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                Log.e(TAG, "设备连接上 开始扫描服务");
                // 开始扫描服务,安卓蓝牙开发重要步骤之一
                try {
                    Thread.sleep(300);
                    //进入onServicesDiscovered()方法
                    mBluetoothGatt.discoverServices();
                } catch (Exception e) {

                }
            } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
              //连接断开的操作,重连或释放资源
        }
        //回调指示描述符写操作的结果。
        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            Log.e(TAG, "onDescriptorWrite: " + status);
        }
        //回调报告描述符读取操作的结果。
        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
            Log.e(TAG, "onDescriptorRead: " + status);
        }
        //当远程设备的远程服务,特征和描述符列表已更新时,即已发现新服务时,将调用回调。如果status为129,重新打开蓝牙,如果一直是129,换设备吧,这是因为Gatt的底层服务有问题。
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            //获取服务列表
            Log.e(TAG, "onServicesDiscovered:进入服务列表 " + status);
            BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("问硬件工程师拿UUID"));
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("问硬件工程师拿UUID"));
            try {
                Thread.sleep(300);
                //进入onCharacteristicRead()方法
                gatt.readCharacteristic(characteristic);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //回调报告描述符读取操作的结果。
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            Log.e(TAG, "onCharacteristicRead:进入可读 " + status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                byte[] data = characteristic.getValue();
                Log.e(TAG, "读取成功" + data);
                mBluetoothGatt.setCharacteristicNotification(characteristic, true);
                //将指令放置进来
                characteristic.setValue(new byte[]{(byte) 0xdb, 0x02....});
                //设置回复形式             characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
                //开始写数据
                try {
                    Thread.sleep(300);
                    //进入onCharacteristicWrite回调
                    mBluetoothGatt.writeCharacteristic(characteristic);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
        //回调指示特征写操作的结果。
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            Log.e(TAG, "onCharacteristicWrite: " + status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                //写入数据的回调
            }

        }
        //完成可靠的写入事务时调用回调。
        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
            super.onReliableWriteCompleted(gatt, status);
            Log.e(TAG, "onReliableWriteCompleted: " + status);
        }
        //数据返回的回调
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            Log.e("AAAAAAAA", String.valueOf(characteristic.getValue()));
        }
    };

这样就完成扫描到写入的过程,不需要的蓝牙要断开,bluetoothGatt.disconnect(),该方法可以调用connect()方法进行重连,close(),须调用BluetoothDevice的connectGatt()方法,不建议调用disconnect()又接着调用close(),因为调用close()会回调无法回到onConnectionStateChange(),BluetoothGatt.STATE_DISCONNECTED里,建议调用disconnect(),在onConnectionStateChange(),BluetoothGatt.STATE_DISCONNECTED里close()。

对于onConnectionStateChange()133问题,一般是因为Android只能连接6个左右的设备,所以不需要的设备一点要close(),释放资源。

相关文章

网友评论

      本文标题:Android Ble

      本文链接:https://www.haomeiwen.com/subject/wuvnjctx.html