栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android ble(低功耗蓝牙)开发基础代码及常见问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android ble(低功耗蓝牙)开发基础代码及常见问题

目录

一、声明权限

二、蓝牙基础代码

1、蓝牙单例类BleManager.java:

 2、界面中使用ble单例类相关代码

三、常见问题(坑)更新中。。。

1、connectGatt(context, false, bluetoothGattCallback)方法


一、声明权限

清单文件 AndroidManifest.xml:

    
    
    
    
    
    
    
    

 以上为最基本的蓝牙权限

android 12及以上还要声明scan和connect等权限,不过一开始可以先不考虑,因为容易出错,比如在鸿蒙的系统下使用会一直显示没有权限。。。

二、蓝牙基础代码

1、蓝牙单例类BleManager.java:

public class BleManager {
    //单例对象
    public static volatile BleManager bleManager;

    //调用到上下文对象
    private FragmentActivity context;

    //蓝牙适配器
    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;

    //设备扫描
    private BluetoothLeScanner bleScanner;

    //扫描回调 区分高低版本 H为安卓5.0及以上版本
    private ScanCallback scanCallbackH;
    private BluetoothAdapter.LeScanCallback scanCallbackL;

    //蓝牙gatt服务对象和回调
    private BluetoothGatt bluetoothGatt;
    private BluetoothGattCallback bluetoothGattCallback;

    //读设备到app的特征值
    private BluetoothGattCharacteristic readCharacteristic;
    private BluetoothGattCharacteristic writeCharacteristic;
    private BluetoothGattDescriptor readDescriptor;

    //判断是否正在扫描和是否连接设备
    public boolean isScanning = false;
    public boolean isConnect = false;

    //子线程
    private Handler workHandler;
    private HandlerThread handlerThread;

    //主线程
    private Handler mainHandler;
    
    //存放扫描到的设备     
    private List devicesList;
    //存放配对的设备名字和mac地址
    private SharedPreferences sp;


    //服务和特征值ID(由ble设备软硬件工程师提供)
    private final String SERVICE_UUID = "0000xxxx-0000-1000-8000-xxxxxxxxxxxx";
    private final String CHARACTERISTIC_UUID1 = "0000xxxx-0000-1000-8000-xxxxxxxxxxxx";
    private final String CHARACTERISTIC_UUID2 = "0000xxxx-0000-1000-8000-xxxxxxxxxxxx";
    private final String READ_DESCRIPTOR_UUID = "00002902-0000-1000-8000-00805f9b34fb";

    //已配对的蓝牙设备
    private BluetoothDevice bleDevice;
    //设备名字和Mac地址
    private String DEVICE_NAME;
    private String DEVICE_ADDRESS;

    //ble状态码用来多线程处理
    private static final int START_SCAN = 1;
    private static final int STOP_SCAN = 2;
    private static final int CONNECT_GATT = 3;
    private static final int DISCONNECT_GATT = 4;
    private static final int CLOSE_GATT = 5;
    private static final int DISCOVER_SERVICES = 6;
    private static final int SEND_DATA = 7;


    //蓝牙连接状态改变监听接口
    private OnBleConnectCallback onBleConnectCallback;


    public interface OnBleConnectCallback {
        //扫描到设备
        void bleScan();

        //蓝牙设备连接和断开
        void bleConnect();

        void bleDisConnect();

        //获取设备电量
        void getBleEleQue(int ele);
    }

    //获取单例模式(懒汉式)
    public static BleManager getInstance() {
        //双重校验锁(提高效率)
        if (bleManager == null)
            synchronized (BleManager.class) {
                if (bleManager == null)
                    bleManager = new BleManager();
            }
        return bleManager;
    }

    //初始化蓝牙ble相关
    @SuppressLint({"MissingPermission", "ObsoleteSdkInt"})
    public void initBle(FragmentActivity activity) {
        this.context = activity;
        devicesList = new ArrayList<>();
        //通过蓝牙管理器获取适配器
        bluetoothManager = (BluetoothManager) activity.getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(activity, "当前设备不支持蓝牙!", Toast.LENGTH_LONG).show();
            return;
        }
        //android 5.0以上API需要的ble扫描类
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            //初始化scanner
            bleScanner = bluetoothAdapter.getBluetoothLeScanner();

        //初始化已配对设备名和地址
        sp = activity.getApplicationContext().getSharedPreferences("sp_ble", Context.MODE_PRIVATE);
        DEVICE_NAME = sp.getString("bleName", null);
        DEVICE_ADDRESS = sp.getString("bleAddress", null);

        //初始化线程
        initHandler();

        //初始化高版本api扫描回调
        scanCallbackH = new ScanCallback() {
            @SuppressLint("MissingPermission")
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
                //连接蓝牙
                //进行扫描到的设备过滤
                if (result.getDevice().getName() == null)
                    return;
//                Log.e("test","nowName "+DEVICE_NAME+" scanName "+bleDevice.getName() +" if="+bleDevice.getName().equals(DEVICE_NAME));
                //这里根据设备名进行连接(可以使用mac地址)
                if (result.getDevice().getName().equals(DEVICE_NAME)) {
                    bleDevice = result.getDevice();
                    mainHandler.sendEmptyMessage(CONNECT_GATT);
                }
                Log.e("test", "name:" + result.getDevice().getName() + " rssi:" + result.getRssi() + " address:" + result.getDevice().getAddress());
                if (devicesList.contains(result.getDevice().getName()))
                    return;
                //将扫描到到设备添加到集合中用于显示
                devicesList.add(result.getDevice().getName());
                //回调连接接口的扫描方法
                onBleConnectCallback.bleScan();
       
            }
        };

        //初始化低版本api扫描回调
        scanCallbackL = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {    
            //内容同上onScanResult方法

            }
        };


        //初始化蓝牙gatt回调
        bluetoothGattCallback = new
                BluetoothGattCallback() {
                    @SuppressLint("MissingPermission")
                    @Override
                    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                        super.onConnectionStateChange(gatt, status, newState);
                        Log.e("test", "onConnectionStateChange " + newState);
                        //连接蓝牙成功后发现可读写的服务
                        if (newState == BluetoothGatt.STATE_CONNECTED) {
                            //连接成功后停止扫描
                            workHandler.sendEmptyMessage(STOP_SCAN);
                            DEVICE_NAME = gatt.getDevice().getName();
//                            onBleConnectCallback.bleConnect();
                            DEVICE_ADDRESS = gatt.getDevice().getAddress();
                            Log.e("test", "connect name :" + DEVICE_NAME + " address---" + DEVICE_ADDRESS);
                            isConnect = true;
                            //将已连接的设备名存储到SharedPreferences中
                            //先从sp中获取ble设备信息
                            SharedPreferences.Editor editor = sp.edit();
                            editor.putString("bleName", DEVICE_NAME);
                            editor.apply();
                            //延迟后回调否则扫描失败没有回调
//                            handler.postDelayed(gatt::discoverServices, 100);
                            workHandler.sendEmptyMessage(DISCOVER_SERVICES);
                            return;
                        }
                        if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                            onBleConnectCallback.bleDisConnect();
                            isConnect = false;
                            mainHandler.sendEmptyMessage(CLOSE_GATT);
                            return;
                        }
                        //避免其他情况出现,断开连接
                        mainHandler.sendEmptyMessage(DISCONNECT_GATT);
                    }

                    @SuppressLint("MissingPermission")
                    @Override
                    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                        super.onServicesDiscovered(gatt, status);
                        //发现服务成功后寻找特征值
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            UUID serviceUuid = UUID.fromString(SERVICE_UUID);
                            //读设备到app的特征值uuid
                            UUID characteristicUuid1 = UUID.fromString(CHARACTERISTIC_UUID1);
                            //写app到设备的特征值uuid
                            UUID characteristicUuid2 = UUID.fromString(CHARACTERISTIC_UUID2);
                            bluetoothGatt.getServices();
                            BluetoothGattService gattService = bluetoothGatt.getService(serviceUuid);
                            if (gattService != null) {
                                //根据uuid获取相应特征值
                                readCharacteristic = gattService.getCharacteristic(characteristicUuid1);
                                writeCharacteristic = gattService.getCharacteristic(characteristicUuid2);
                                //获取根据uuid获取相应描述
                                readDescriptor = readCharacteristic.getDescriptor(UUID.fromString(READ_DESCRIPTOR_UUID));
                                //设置描述和特征值通知
                                readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                                bluetoothGatt.writeDescriptor(readDescriptor);
                                bluetoothGatt.setCharacteristicNotification(readCharacteristic, true);
                                //获取电量
//                                handler.postDelayed(() -> writeBleHexStrValue("A102010055"), 200);
                            }
                        }
                    }

                    //读取数据回调,接收数据
                    @Override
                    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic
                            characteristic, int status) {
                        super.onCharacteristicRead(gatt, characteristic, status);
                        if (characteristic.getUuid().toString().equals(CHARACTERISTIC_UUID1)) {
                            byte[] value = characteristic.getValue();
                            Log.e("test", "Read" + Arrays.toString(value));
                        }
                    }

                    //发送数据回调
                    @Override
                    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic
                            characteristic, int status) {
                        super.onCharacteristicWrite(gatt, characteristic, status);
                        byte[] value = characteristic.getValue();
                        Log.e("test", "Write" + Arrays.toString(value));
                    }

                    //蓝牙设备改变特征值后接收修改的信息
                    @Override
                    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic
                            characteristic) {
                        super.onCharacteristicChanged(gatt, characteristic);
                        //判断是否为指定的特征值
                        if (characteristic.getUuid().toString().equals(CHARACTERISTIC_UUID1)) {
                            byte[] value = characteristic.getValue();
                            //判断返回的数据是否非空且为电量
                            if (value == null || value.length <= 0 || value[1] != 0x02)
                                return;
                            electricQuantity = value[3] & 0xFF;
                        }
                        byte[] value = characteristic.getValue();
                        Log.e("test", "CharacteristicChanged " + Arrays.toString(value));
                        onBleConnectCallback.getBleEleQue(electricQuantity);
                    }

                    //设置描述符后回调
                    @Override
                    public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                        super.onDescriptorWrite(gatt, descriptor, status);
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            Log.e("test", "onDescriptorWrite success");
              
                        }

                    }
                }

        ;
    }

    //初始化线程
    private void initHandler() {
        //初始化主线程
        mainHandler = new Handler(context.getMainLooper()) {
            @SuppressLint("MissingPermission")
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case CONNECT_GATT:
                        bluetoothGatt = bleDevice.connectGatt(context, false, bluetoothGattCallback);
                        break;
                    case DISCONNECT_GATT:
                        if (bluetoothGatt != null)
                            bluetoothGatt.disconnect();
                        break;
                    case CLOSE_GATT:
                        bluetoothGatt.close();
                        bluetoothGatt = null;
                        break;
                    case DISCOVER_SERVICES:
                        postDelayed(() -> bluetoothGatt.discoverServices(), 100);
                        break;
                }
            }
        };

        //初始化工作子线程
        handlerThread = new HandlerThread("BleWorkHandlerThread");
        handlerThread.start();
        workHandler = new Handler(handlerThread.getLooper()) {
            @SuppressLint("MissingPermission")
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                //根据消息类别进行相应处理
                switch (msg.what) {
                    case START_SCAN:
                        startBleScan();
                        break;
                    case STOP_SCAN:
                        stopBleScan();
                        //线程休眠确保ble停止搜索完成
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        break;
                    case SEND_DATA:
                        writeBleHexStrValue((String) msg.obj);
                        break;
                }
            }
        };

    }

    //搜索蓝牙设备方法
    public void scanLeDevice() {
        workHandler.sendEmptyMessage(START_SCAN);
    }

    //向蓝牙设备写入数据方法
    @SuppressLint("MissingPermission")
    public void writeBleHexStrValue(String hexStr) {
        //判断是否连接和数据值是否为空
        if (!isConnect || hexStr == null || hexStr.equals(""))
            return;
        //判断写特征值和服务对象是否为空
        if (writeCharacteristic == null || bluetoothGatt == null)
            return;
        byte[] value = hexStrToBytes(hexStr);
        writeCharacteristic.setValue(value);
        bluetoothGatt.writeCharacteristic(writeCharacteristic);
    }

    //发送数据到BLE设备
    private void sendData2Ble(String data) {
        Message message = new Message();
        message.what = SEND_DATA;
        message.obj = data;
        workHandler.sendMessage(message);
    }

    //16进制字符串转字节数组
    public static byte[] hexStrToBytes(String hexStr) {
        String hex = "0123456789ABCDEF";
        if (hexStr == null || hexStr.equals(""))
            return null;
        //全部转化为大写字母
        hexStr = hexStr.toUpperCase();
        //字节数组长度
        int length = hexStr.length() / 2;
        //转化为字符数组
        byte[] value = new byte[length];
        char[] hexChar = hexStr.toCharArray();
        for (int i = 0; i < length; i++) {
            int p = i * 2;
            //右移4位得到字节高位再和下一个字符或得到位
            value[i] = (byte) (hex.indexOf(hexChar[p]) << 4 | hex.indexOf(hexChar[p + 1]));
        }
        return value;
    }


    //设置回调接口
    public void setOnBleConnectCallback(OnBleConnectCallback onBleConnectCallback) {
        this.onBleConnectCallback = onBleConnectCallback;
    }

    //停止蓝牙扫描
    @SuppressLint({"MissingPermission", "ObsoleteSdkInt"})
    public void stopBleScan() {
        if (isScanning) {
            Log.e("test", "stopBleScan: ");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                bleScanner.stopScan(scanCallbackH);
            else
                bluetoothAdapter.stopLeScan(scanCallbackL);
            isScanning = false;
        }
    }

    //开始扫描蓝牙
    @SuppressLint({"MissingPermission", "ObsoleteSdkInt"})
    public void startBleScan() {
        if (!isScanning) {
            isScanning = true;
            Log.e("test", "扫描");
            //开始扫描
            //如果安卓版本高于5.0使用高版本api
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                bleScanner.startScan(scanCallbackH);
            else
                bluetoothAdapter.startLeScan(scanCallbackL);
        }
    }

    //判断蓝牙打开状态
    public boolean isEnabled() {
        return bluetoothAdapter.isEnabled();
    }

    //getter和setter 方法
    public BluetoothAdapter getBluetoothAdapter() {
        return bluetoothAdapter;
    }

 2、界面中使用ble单例类相关代码

onCreate方法中

 private BleManager ble;

        ble = BleManager.getInstance();
        ble.initBle(MainActivity.this);
        //ble连接回调
        bleConnectCallback = new BleManager.OnBleConnectCallback() {
            @Override
            public void bleScan() {

            }

            @Override
            public void bleConnect() {

            }

            @Override
            public void bleDisConnect() {

            }

            @Override
            public void getBleEleQue(int ele) {

            }
        };
        ble.setOnBleConnectCallback(bleConnectCallback);

开启蓝牙和扫描相关代码

//打开蓝牙方法,根据蓝牙状态设置提示
    @SuppressLint("MissingPermission")
    public void openBluetooth() {
        //先检查各权限
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
                Log.e("test", "权限:" + permission);
                // 没有权限会弹出对话框申请
                ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
                return;
            }
        }
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE) && ble.getBluetoothAdapter() == null) {
            showToast("当前设备不支持蓝牙功能!");
            return;
        }
        //检查是否打开蓝牙和gps
        if (ble.isEnabled() && checkGps()) {
            ble.scanLeDevice();
        } else {
            //如果用户有蓝牙连接权限直接申请开启蓝牙
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_ADMIN) == PackageManager.PERMISSION_GRANTED) {
                ble.getBluetoothAdapter().enable();
            }
        }
    }

 检查权限相关代码

//用来检测权限
    @SuppressLint("ObsoleteSdkInt")
    public void checkPermission(String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            if (ActivityCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
                // 没有权限会弹出对话框申请
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, 1);
            }
    }

    //检查和打开GPS
    private boolean checkGps() {
        checkPermission(permissions[1]);
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        //GPS卫星定位,级别高
        boolean gps = locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
        //通过WLAN和移动网络定位,辅助GPS定位
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        //提示并打开定位功能
        showToast("请先打开定位功能");
        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        return false;
    }

    //权限回调用来提示用户设置权限
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (String permission : permissions) {
                //用户选择了禁止且不再询问
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permission) && ActivityCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
                    Log.e("test", "权限2:" + permission);
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("获取权限")
                            .setMessage("设置允许权限后才可以使用")
                            .setPositiveButton("设置", (dialog, id) -> {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                                finish();
                            }).setNegativeButton("取消", null);
                    //弹出对话框提示
                    AlertDialog mDialog = builder.create();
                    mDialog.setCanceledOnTouchOutside(false);
                    mDialog.show();
                }
            }
        }
    }

三、常见问题(坑)更新中。。。

1、connectGatt(context, false, bluetoothGattCallback)方法

第二个参数自动连接一般设为false,设置为true有时候会导致连接成功但无法读写数据的情况(也可能我自己写的有点问题,反正不好用~)。自动连接的效率也很低,不如自己写回连逻辑。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/978134.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号