美文网首页
Android 蓝牙开发

Android 蓝牙开发

作者: 帝王鲨kingcp | 来源:发表于2023-03-09 09:33 被阅读0次

    低功耗蓝牙就是我们常说是的蓝牙4.0 ,蓝牙之间的通讯每次只能传20个字节。

    1.判断蓝牙是否打开

        /**
         * 判断蓝牙是否打开
         */
        private fun isOpenBluetooth(): Boolean {
            val manager = activity.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
            if (manager.adapter == null) return false
            val adapter = manager.adapter
            return adapter.isEnabled
        }
    

    没有打开需要去请求打开蓝牙,这里会区分android12系统以上和以下,打开有所区别

        /**
         * 打开蓝牙
         */
        fun openBlueTooth() {  
            //是Android12
            if (isAndroid12()) {
                //检查是否有BLUETOOTH_CONNECT权限
                if (hasPermission(Manifest.permission.BLUETOOTH_CONNECT)) {
                    //打开蓝牙
                    openPhoneBluetooth()
                } else {
                    //请求权限
                    requestBluetoothConnect.launch(Manifest.permission.BLUETOOTH_CONNECT)
                }
                return
            }
            //不是Android12 直接打开蓝牙
            openPhoneBluetooth()
        }
    
        fun openPhoneBluetooth(){
            val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            activity.startActivityForResult(intent, REQUEST_ENABLE_BT)
        }
    

    2.扫描蓝牙

    扫描之前需要一些权限,Android也是会区分12以上和以下,不同的手机还有不同要求,比如华为手机12以上也要定位权限。有的手机没有适配,所以建议如下处理(权限多要一点)

        private void requestPermission() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                // Android 版本大于等于 Android12 时
                // 只包括蓝牙这部分的权限,其余的需要什么权限自己添加
                mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
                mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
                mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
                // 目前知道hw手机需要
                mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            } else {
                // Android 版本小于 Android12 及以下版本
                mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
    
            if (mPermissionList.size() > 0) {
                ActivityCompat.requestPermissions(this, mPermissionList.toArray(new String[0]), 1001);
            }
        }
    

    开始扫描蓝牙

    扫描结果在回调中返回

        //获取系统蓝牙适配器
        var mBluetoothAdapter: BluetoothAdapter? = null
        //扫描者
        private var scanner: BluetoothLeScanner? = null
                
        mBluetoothAdapter = (activity.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
        scanner = mBluetoothAdapter?.bluetoothLeScanner
    
        //扫描结果回调
        private var scanCallback: ScanCallback? = object : ScanCallback() {
            override fun onScanResult(callbackType: Int, result: ScanResult) {
                addScanResult(result)
            }
        }
    
        /**
         * 开始蓝牙扫描
         */
        @SuppressLint("MissingPermission")
        fun startScan() {
            if (!isScanning && scanner != null) {
                LogUtil.d(" Thread = " + Thread.currentThread().name, "开始启动蓝牙扫描 ")
                scanner!!.startScan(null, ScanSettings.Builder().setScanMode(SCAN_MODE_LOW_LATENCY).build(), scanCallback)
            }
            isScanning = true
        }
    
        /**
         * 停止蓝牙扫描
         */
        @SuppressLint("MissingPermission")
        fun stopScan() {
            if (isScanning && scanner!= null) {
                scanner!!.stopScan(scanCallback)
            }
            isScanning = false
        }
    
    

    3.连接蓝牙

    蓝牙连接需要在主线程中进行,三星手机非主线程中连接也可以成功,但是华为手机非主线就会出现连接失败问题.

    status 状态:
    • 0 (连接成功),
    • 133(蓝牙不在范围内连接失败,连接超时,及时关掉BluetoothGatt,避免出现257错误,下次连接靠近到蓝牙返回内一般就可以连接成功)
    • 257(这个错误码出现后,一般再就连不上,需要重新开始蓝牙扫描流程)
        @SuppressLint("MissingPermission")
        private fun connectBlueToothGatt(scanResult: ScanResult, device: BluetoothDevice) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
               // 1.连接蓝牙
                bluetoothGatt = device.connectGatt(activity, false, object : BluetoothGattCallback() {
                    override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            if (newState == BluetoothProfile.STATE_CONNECTED) {
                                mainHandler.post{
                                    // 2.去发现服务
                                    gatt!!.discoverServices()
                                }
                            } else{
                                 // 连接失败的处理
                            }
                        }else{
                            if(status == BluetoothGatt.GATT_FAILURE){
                              // 257错误处理
                            }
                            gatt.close()
                        }
                    }
    
                    override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
                        super.onServicesDiscovered(gatt, status)
                        // 3.发现服务
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            //获取DeviceInfoService
                            val mDeviceInfoService = gatt.getService(UUID.fromString(BLUE_TOOTH_GATT_SERVICE_UUID))
                            if (mDeviceInfoService == null) {
                                gatt.connect()
                                return
                            }
                            //获取一个主设备需要去读的特征(Characteristic),获取从设备发送过来的数据0000fff2-0000-1000-8000-00805f9b34fb
                            val readGattCharacteristic = mDeviceInfoService.getCharacteristic(UUID.fromString(READ_GATT_CHARACTERISTIC_UUID))
                            //注册特征(Characteristic)值改变的监听
                            val isEnableNotify = gatt.setCharacteristicNotification(readGattCharacteristic, true)
                            if (isEnableNotify) {
                               val descriptors = readGattCharacteristic.descriptors
                               for (descriptor in descriptors) {
                                    descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                                    val isWriteDescriptor = gatt.writeDescriptor(descriptor)
                               }
                            }
                           //获取一个特征(Characteristic),这是从设备定义好的,我通过这个Characteristic去写从设备感兴趣的值0000fff1-0000-1000-8000-00805f9b34fb
                           val writeGattCharacteristic = mDeviceInfoService.getCharacteristic(UUID.fromString(WRITE_GATT_CHARACTERISTIC_UUID))
                        }
                        } else {
                            gatt.connect()
                        }
                    }
    
                    override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
                        super.onCharacteristicRead(gatt, characteristic, status)
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                           // 读成功在这里回调
                        } else {
                            gatt.connect()
                        }
                    }
    
                    override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
                        super.onCharacteristicWrite(gatt, characteristic, status)
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                           // 写成功在这里回调
                        } else {
                            gatt.connect()
                        }
                    }
    
                    override fun onDescriptorRead(gatt: BluetoothGatt?, descriptor: BluetoothGattDescriptor?, status: Int) {
                        super.onDescriptorRead(gatt, descriptor, status)
                        // 特征值读成功,这里回调
    
                    }
    
                    override fun onDescriptorWrite(gatt: BluetoothGatt?, descriptor: BluetoothGattDescriptor?, status: Int) {
                        super.onDescriptorWrite(gatt, descriptor, status)
                        // 特征值写成功,这里回调
                    }
    
                    override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
                        super.onCharacteristicChanged(gatt, characteristic)
                        // 蓝牙发送过来的数据
                        val uuid = characteristic.uuid
                        val receiveData = characteristic.valu
                    }
                }, BluetoothDevice.TRANSPORT_LE)
            } else {
                // ....
            }
    
        }
    

    向蓝牙发送数据

    4.开发中碰的问题

    • 30秒内蓝牙连续停止扫描5次,再次扫描就会扫描不到设备,这里系统进行了限制。源码
    • 蓝牙通讯需要设备不忙时进行读写,在上面onCharacteristicWrite,onCharacteristicRead,onDescriptorWrite,onCharacteristicChanged这些回调后设备是不忙的状态。具体看源码,关注mDeviceBusy
    • 华为手机无论是否android12以上系统都需要位置权限

    相关文章

      网友评论

          本文标题:Android 蓝牙开发

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