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);
原文地址:https://www.cnblogs.com/zadomn0920/p/6194931.html