Android开发之低功耗蓝牙(原生使用)之一

2023-12-13 17:06:35

上一篇文章http://t.csdnimg.cn/pAwZE主要讲解利用三方库进行的低功耗蓝牙的讲解,本篇文章主要进行原生对低功耗蓝牙的操作。

在使用蓝牙之前我们首先要先进行蓝牙权限的获取,上篇文章已讲解怎么获取蓝牙权限,本篇文章就不讲解了,下面主要讲解蓝牙的使用:

第一步:创建一个BluetoothLeService extends Service

添加属性:

public final static String ACTION_GATT_CONNECTED =
? ? ? ? ? ? "包名.ACTION_GATT_CONNECTED";
? ? public final static String ACTION_GATT_DISCONNECTED =
? ? ? ? ? ? "包名.ACTION_GATT_DISCONNECTED";
? ? public final static String ACTION_GATT_SERVICES_DISCOVERED =
? ? ? ? ? ? "包名.ACTION_GATT_SERVICES_DISCOVERED";
? ? public final static String ACTION_DATA_AVAILABLE =
? ? ? ? ? ? "包名.ACTION_DATA_AVAILABLE";
? ? public final static String EXTRA_DATA =
? ? ? ? ? ? "包名.EXTRA_DATA";

设置UUID:

?public final static UUID UUID_NOTIFY =
? ? ? ? ? ? UUID.fromString("蓝牙设备对应的读的UUID");
? ? public final static UUID UUID_SERVICE =
? ? ? ? ? ? UUID.fromString("蓝牙设备对应的服务的UUID");
? ? public final static UUID UUID_WRITE=
? ? ? ? ? ? UUID.fromString("蓝牙设备对应的写入的UUID");
? ? 第二步:连接蓝牙的操作:

public boolean connect(final String address) {
    if (mBluetoothAdapter == null || address == null) {
        Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
        return false;
    }
    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    if (device == null) {
        Log.w(TAG, "Device not found.  Unable to connect.");
        return false;
    }
    if(mBluetoothGatt != null)
    {
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
    Log.e(TAG, "Trying to create a new connection.");

    return true;
}

第三步:接口回调

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        String intentAction;
        Log.e(TAG, "oldStatus=" + status + " NewStates=" + newState);
      /*  if(status == BluetoothGatt.GATT_SUCCESS||status == 8)
        {*/

            if (newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                broadcastUpdate(intentAction);
                Log.e(TAG, "Connected to GATT server.");
                Log.e(TAG, "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                mBluetoothGatt.close();
                mBluetoothGatt = null;
                Log.e(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }
       /* }*/
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.e(TAG, "GATT_SUCCESS  onServicesDiscovered received: " + status);
            findService(gatt.getServices());
        } else {
            if(mBluetoothGatt.getDevice().getUuids() == null)
                Log.e(TAG, "onServicesDiscovered received: " + status);
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
        Log.e(TAG, "onCharacteristicRead  GATT_SUCCESS");
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.e(TAG, "onCharacteristicRead");
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }
    }

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

    }

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


    @Override
    public void onDescriptorRead(BluetoothGatt gatt,
                                 BluetoothGattDescriptor bd,
                                 int status) {
       Log.e(TAG, "onDescriptorRead");
    }

    @Override
    public void onDescriptorWrite(BluetoothGatt gatt,
                                  BluetoothGattDescriptor bd,
                                  int status) {
        Log.e(TAG, "onDescriptorWrite");
    }

    @Override
    public void onReadRemoteRssi(BluetoothGatt gatt, int a, int b)
    {
       Log.e(TAG, "onReadRemoteRssi");
    }

    @Override
    public void onReliableWriteCompleted(BluetoothGatt gatt, int a)
    {
        Log.e(TAG, "onReliableWriteCompleted");
    }

};

回调里面引用的方法:

public void findService(List<BluetoothGattService> gattServices)
{
    Log.e(TAG, "Count is:" + gattServices.size());
    for (BluetoothGattService gattService : gattServices)
    {

        Log.e(TAG, gattService.getUuid().toString());
        Log.e(TAG, UUID_SERVICE.toString());
        if(gattService.getUuid().toString().equalsIgnoreCase(UUID_SERVICE.toString()))
        {
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            Log.e(TAG, "Count is:" + gattCharacteristics.size());
            Log.e(TAG, "UUID_SERVICE"+UUID_SERVICE.toString());
            for (final BluetoothGattCharacteristic gattCharacteristic :
                    gattCharacteristics)
            {
                if(gattCharacteristic.getUuid().toString().equalsIgnoreCase(UUID_NOTIFY.toString()))
                {
                    Log.e(TAG, gattCharacteristic.getUuid().toString());
                    Log.e(TAG, "UUID_NOTIFY:"+UUID_NOTIFY.toString());
                    mNotifyCharacteristic = gattCharacteristic;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            setCharacteristicNotification(gattCharacteristic, true);
                            broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
                        }
                    }).start();

                    return;
                }
            }
        }
    }
}

private void broadcastUpdate(final String action) {
    final Intent intent = new Intent(action);
    sendBroadcast(intent);
}

private void broadcastUpdate(final String action,
                             final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    final byte[] data = characteristic.getValue();

    if (data != null && data.length > 0) {
        intent.putExtra(EXTRA_DATA, data);


    }
    sendBroadcast(intent);
}

public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                          boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.e(TAG, "BluetoothAdapter not initialized");
        return;
    }
  mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLTENT_CHARACTERISTIC_CONFIG);
    if (descriptor != null) {

        Log.e("TAG"," 订阅");
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    }
}

第四步? 断开连接

public void disconnect() {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.disconnect();
}

第五步:关闭连接

public void close() {
    if (mBluetoothGatt == null) {
        return;
    }
    mBluetoothGatt.close();
    mBluetoothGatt = null;
}

以上就是对低功耗蓝牙的初步讲解,预知下回如何,敬请期待。

文章来源:https://blog.csdn.net/qq_36451275/article/details/134972813
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。