低功耗蓝牙的配置和使用(BluetoothGattCallback出现133问题)

低功耗蓝牙的配置和使用
原文https://yq.aliyun.com/articles/668987
第二步里面有遇到133问题的解决方案,希望你们也有效

第一步(获取蓝牙适配管理类,检查是否开启蓝牙权限)

 //获取系统蓝牙适配器管理类
 private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
            .getDefaultAdapter();

 private void initBluetooth() {
        // 询问打开蓝牙
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android M Permission check
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        }
        if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        } else {
            //拥有权限开始搜索低功耗蓝牙
            mBluetoothAdapter.startLeScan(callback);

        }

    }


// 申请打开蓝牙请求的回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                //蓝牙已经开启
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                    mBluetoothAdapter.startDiscovery();
                }
            } else if (resultCode == RESULT_CANCELED) {
                finish();
            }
        }
    }

第二步(获取扫描到的设备信息,通过device可以获取address和name,根据这个判断是否为目标device)

// 获取搜索到的蓝牙设备
  private BluetoothAdapter.LeScanCallback callback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(BluetoothDevice device, int arg1, byte[] arg2) {

            //device为扫描到的BLE设备
            if (device.getAddress() != null && device.getName() != null && device.getName().startsWith("regex")) {
                //获取目标设备
                tagDevice = device;
                mBluetoothAdapter.stopLeScan(callback);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    //Android6.0以上需要调用这个方法,如果6.0以上不用这个方法而是选择下面那个方法会出现133错误
                    mBluetoothGatt = tagDevice.connectGatt(ElectronicScale2Activity.this, false, gattCallback, TRANSPORT_LE);
                }else{
                    mBluetoothGatt = tagDevice.connectGatt(ElectronicScale2Activity.this, false, gattCallback);
                }
                return;
            }
        }
    };

6.0及以上系统的手机要使用bluetoothDevice.connectGatt(MainActivity.this,true, gattCallback, TRANSPORT_LE),其中TRANSPORT_LE参数是设置传输层模式。传输层模式有三种TRANSPORT_AUTO 、TRANSPORT_BREDR 和TRANSPORT_LE。如果不传默认TRANSPORT_AUTO,6.0系统及以上需要使用TRANSPORT_LE这种传输模式,可能是因为Android6.0及以上系统重新定义了蓝牙BLE的传输模式必须使用TRANSPORT_LE这种方式

第三步(在下面的onCharacteristicChanged方法里面可以拿到设备发出的数据,根据规定格式解析即可)

   private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                            int newState) {
            if (status==BluetoothGatt.GATT_SUCCESS){
                //连接成功
                if (newState== BluetoothGatt.STATE_CONNECTED){
                    Log.e("Bluetooth","连接成功");
                    //发现服务
                    gatt.discoverServices();
                }
            }else{
                //连接失败
                Log.e("Bluetooth","失败=="+status);
                mBluetoothGatt.close();
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                                          BluetoothGattCharacteristic characteristic, int status) {

            super.onCharacteristicWrite(gatt, characteristic, status);

        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt,
                                      BluetoothGattDescriptor descriptor, int status) {


        }

        ;

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            //获取初始化服务和特征值
            initServiceAndChara();
            //订阅通知
            mBluetoothGatt.setCharacteristicNotification(mBluetoothGatt
                    .getService(notify_UUID_service).getCharacteristic(notify_UUID_chara),true);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            // value为设备发送的数据,根据数据协议进行解析
            byte[] value = characteristic.getValue();

        }
    };

//通过Android拿得到对应UUID
  private void initServiceAndChara(){
        List bluetoothGattServices= mBluetoothGatt.getServices();
        for (BluetoothGattService bluetoothGattService:bluetoothGattServices){
            List characteristics=bluetoothGattService.getCharacteristics();
            for (BluetoothGattCharacteristic characteristic:characteristics){
                int charaProp = characteristic.getProperties();
                if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                    read_UUID_chara =characteristic.getUuid();
                    read_UUID_service =bluetoothGattService.getUuid();
                    //Log.e(TAG,"read_chara="+ read_UUID_chara +"----read_service="+ read_UUID_service);
                }
                if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
                    write_UUID_chara =characteristic.getUuid();
                    write_UUID_service =bluetoothGattService.getUuid();
                    //Log.e(TAG,"write_chara="+ write_UUID_chara +"----write_service="+ write_UUID_service);
                }
                if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0) {
                    write_UUID_chara =characteristic.getUuid();
                    write_UUID_service =bluetoothGattService.getUuid();
                    //Log.e(TAG,"write_chara="+ write_UUID_chara +"----write_service="+ write_UUID_service);

                }
                if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                    notify_UUID_chara =characteristic.getUuid();
                    notify_UUID_service =bluetoothGattService.getUuid();
                    //Log.e(TAG,"notify_chara="+ notify_UUID_chara +"----notify_service="+ notify_UUID_service);
                }
                if ((charaProp & BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0) {
                    indicate_UUID_chara =characteristic.getUuid();
                    indicate_UUID_service =bluetoothGattService.getUuid();
                    //Log.e(TAG,"indicate_chara="+ indicate_UUID_chara +"----indicate_service="+ indicate_UUID_service);

                }
            }
        }
    }

读写操作什么暂时没用上,需要的去看原文吧,这篇文章仅用于自己记录观看
(原文https://yq.aliyun.com/articles/668987)

你可能感兴趣的:(低功耗蓝牙的配置和使用(BluetoothGattCallback出现133问题))