zoukankan      html  css  js  c++  java
  • BLE编程中关键步骤

    获取权限

    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

    获取蓝牙适配器的实例

    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();

    BLE搜索:实例化回调函数->启动/停止扫描

    1、实例化回调函数

    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
                byte[] scanRecord) {
            runOnUiThread(new Runnable() {
               @Override
               public void run() {
                   //得到蓝牙设备实例
               }
           });
       }
    };

    2、启动/停止扫描

    mBluetoothAdapter.startLeScan(mLeScanCallback);  //开始扫描
    mBluetoothAdapter.stopLeScan(mLeScanCallback);  //停止扫描

    BLE连接:实例化回调函数 -> 连接并绑定回调函数

    1、实例化回调函数

    private final BluetoothGattCallback mGattCallback =
                new BluetoothGattCallback() {
    
             //当连接状态发生改变时会触发
            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status,
                    int newState) {
                String intentAction;
                if (newState == BluetoothProfile.STATE_CONNECTED) {
                     //当蓝牙设备已经连接
                     ... 
                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                     //当设备无法连接
                     ...
                }
            }
    
             // 发现新服务时会触发
            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    ...
                } else {
                    ...
                }
            }
             
             // 读写特性
            @Override
            public void onCharacteristicRead(BluetoothGatt gatt,
                    BluetoothGattCharacteristic characteristic,
                    int status) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    ...
                }
            }
         ...
        };

    2、获取蓝牙设备实例,并连接该蓝牙设备实例。


    //
    蓝牙地址实例化一个蓝牙设备,或通过上述扫描传入一个引用。 final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    //涉及的三个参数:一个Context对象,自动连接(boolean值,表示只要BLE设备可用是否自动连接到它),和BluetoothGattCallback调用。 private BluetoothGatt mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
  • 相关阅读:
    spring各个版本开发包下载
    not value specified for parameter问题解决方案
    Ajax的重构
    Ajax中与服务器的通信【发送请求与处理响应】
    Ajax技术之XMLHttpRequest(二)【XMLHttpRequest常用方法和属性】
    “AI”项目日记
    英语学习笔记
    贺费德勒20冠,和关于程序员中年危机的思考
    《领域驱动设计:软件核心复杂性应对之道》读书笔记
    ERP系统知识笔记
  • 原文地址:https://www.cnblogs.com/zadomn0920/p/6194931.html
Copyright © 2011-2022 走看看