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

news/2024/7/1 7:26:58

上一篇文章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;
}

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


http://lihuaxi.xjx100.cn/news/1888543.html

相关文章

linux中堡垒机

堡垒机 堡垒机概念目的 安装Jumpserver使用资产管理资产列表创建需要管理的服务器创建用户权限管理页面进行资产授权操作视频 应用管理应用管理页面创建需要管理的应用&#xff0c;这里用数据库mysql举例进入后点击创建资产管理创建登录应用所需的用户选择创建mysql关系型数据库…

点击进入全屏事件

//点击进入全屏事件 this.launchFullscreen(document.documentElement);launchFullscreen(element){if(element.requestFullscreen) {element.requestFullscreen();} else if(element.mozRequestFullScreen) {element.mozRequestFullScreen();} else if(element.webkitRequestF…

AI日报:人工智能与新材料的发现

文章目录 总览人工智能正在革命性地发现新的或更强的材料&#xff0c;这将改变制造业。更坚韧的合金问题研究解决方案 新材料人工智能存在的挑战方法探索 日本的研究人员正在使用人工智能制造更强的金属合金或发现新材料&#xff0c;并彻底改变制造过程 总览 日本的研究人员开…

Python的sort()与sorted()排序函数的区别

文章目录 一、工具二、需求三、简单的使用例子四、原理分析Timsort算法主要特点&#xff1a;Timsort算法的工作原理&#xff1a;sort() 方法和 sorted() 函数的差异&#xff1a; 五、Python中的单例实现简单示例 一、工具 Python 3.10.0 pycharm 2022 二、需求 最近做项目的…

《C++新经典设计模式》之第22章 总结

《C新经典设计模式》之第22章 总结 面向对象程序设计原则 开放封闭原则&#xff1a;扩展开放&#xff0c;修改封闭&#xff0c;增加新功能时&#xff0c;已有代码不变&#xff0c;增加新类、新成员函数实现。依赖倒置原则&#xff1a;高层组件不应该依赖于底层组件&#xff08…

nginx使用bat命令快速启动

.bat文件代码 echo off D: ::进入nginx安装目录 cd D:\enviroment\nginx-1.24.0 ::start nginx -c ./conf/nginx.confrem 如果启动前已经启动nginx并记录下pid文件&#xff0c;会kill指定进程 nginx.exe -s stoprem 测试配置文件语法正确性 nginx.exe -t -c conf/nginx.confre…

视频号小店与小商店有什么区别?一篇文章带你了解!

我是电商珠珠 视频号小店和小商店都是腾讯开发出来的电商平台&#xff0c;视频号小店出现的比小商店要晚一些&#xff0c;所以很多想入驻的新手&#xff0c;在这两者之间容易混淆。 下面我就来跟大家详细的讲一下&#xff0c;这两者之间区别。 1、团队不同 虽然都是腾讯公司…

ANSYS 应力和应变(EPTO)

目录 EPTO 应力和应变 Maximum, Middle, and Minimum Principal 最大、中间和最小主应力&#xff08;主应变&#xff09; Intensity 强度 Equivalent Total Strain等效总应变 Equivalent (von Mises)冯米塞斯等效应力&#xff08;应变&#xff09; 参考 EPTO EPTO X,…