Android 蓝牙 4.0 ble 基础通讯篇

这篇博客主要讲解 Android 蓝牙 BLE 基础通讯。


一、添加权限

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

不过在 Android 6.0之后 需要动态申请定位权限。

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

二、扫描

  • 首先初始化蓝牙适配器 
BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
     BluetoothAdapter  mBluetoothAdapter = bluetoothManager.getAdapter();
  • 根据 BluetoothAdapter  进行开始、停止扫描
 mBluetoothAdapter.startLeScan(mLeScanCallback);//开始扫描
 mBluetoothAdapter.stopLeScan(mLeScanCallback);//停止扫描

 private BluetoothAdapter.LeScanCallback mLeScanCallback =
         new BluetoothAdapter.LeScanCallback() {
         @Override
          public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
                    //这里不能做太多的操作,要抛到另外一个线程中去处理。
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //device:设备对象
                            //rssi 信号值
                            //scanRecord 广播包
                            
                        }
                    });
                }
            };

三、连接

在获取到设备的 MAC 地址之后,就可以进行连接

BluetoothGatt mGatt = device.connectGatt(mContext, false, new BluetoothGattCallback() {

    //连接状态改变时回调
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            Log.i(TAG, "连接成功");
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            Log.i(TAG, "连接已断开");
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {

    }

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

    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {

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

});

四、接收和发送

  • 接收

如果蓝牙设备具有 notifiy/indecation 功能,那么我们可以通过 onCharacteristicChanged() 回调获取数据,当然我们也是需要设置的。在蓝牙连接成功时,需要打开通知功能,告诉设备可以发信息给我们。

   //设置为Notifiy
    mGatt.setCharacteristicNotification(mCharacteristic, mEnable);  
    BluetoothGattDescriptor descriptor =             
    mCharacteristic.getDescriptor(UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG));
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    mGatt.writeDescriptor(descriptor);
  • 发送
    characteristicWrite.setValue(getAllDataOrder());
    mGatt.writeCharacteristic(characteristicWrite);

这里的 mGatt 是在连接成功之后的对象,需要设置成全局变量。

五、解析数据

    /**
     * byte[] 转 字符串
     * @param bytes
     * @return
     */
    public static String bytesToHexString(byte[] bytes) {
        String result = "";
        for (int i = 0; i < bytes.length; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);
            if (hexString.length() == 1) {
                hexString = '0' + hexString;
            }
            result += hexString.toUpperCase();
        }
        return result;
    }

好,简单介绍蓝牙 BLE 的扫描、连接、收发数据,就此到一段落。下次介绍 Android 蓝牙协议中 SPP 的开发。

发布了48 篇原创文章 · 获赞 10 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/jacksinrow/article/details/82793545