BLE Android 如何传递特性以在 Fragment 中使用

如何解决BLE Android 如何传递特性以在 Fragment 中使用

我有一个 BLE 教程。我可以在 SPS 服务上发送和接收数据,这个数据 TX RX 在 Dialog_BTLE_Characteristics 中完成。看起来特征和服务是使用以下命令从 Activity_BTLE_Services 传递到 Dialog_BTLE_Characteristic 类的。

Dialog_BTLE_Characteristic dialog_btle_characteristic = new Dialog_BTLE_Characteristic();
dialog_btle_characteristic.setTitle(uuid);
dialog_btle_characteristic.setService(mBTLE_Service);
dialog_btle_characteristic.setCharacteristic(characteristic);

然后在Dialog_BTLE_Characteristic类中使用特性来发送数据(输出):

characteristic.setValue(output);
service.writeCharacteristic(characteristic);

现在我想在 Fragment 中发送和接收数据。我如何将这些特征和服务传递给 Fragment?

你的帮助会很大。 海军陆战队

解决方法

在片段中执行 BLE 操作是不好的做法。创建一个执行 BLE 操作的辅助类,并且仅将解码数据发送到片段/活动以进行显示。

,

我认为如果您将代码分成不同的文件,您可能会更好地移动。

我建议您将特征和设备 ID 传递给 fragment using a bundle

    public static MyFragment newInstance(int someInt) {
        MyFragment myFragment = new MyFragment();

        Bundle args = new Bundle();
        args.putString("someInt",someString);
        myFragment.setArguments(args);

        return myFragment;
    }

    //-------

    // In the fragment

    getArguments().getInt("someString");

几年来我一直在编写一些非常糟糕的代码,但它确实解决了很多繁重的工作:

    //By the way,I think this is the server,better known as "Central Module",not the peripheral. I've had this misunderstanding until recently and still need to change the code
    public class BLEPeripheral {

        private String deviceId;
        private BLEManager connector;
        private BluetoothAdapter bluetoothAdapter;
        private BluetoothLeScanner bluetoothLeScanner;
        private BluetoothGatt bluetoothGatt;
        private BluetoothGattService bluetoothGattService = null;
        private HashMap<String,Command<String>> subscriptions;

        private boolean connected = false;

        public boolean isConnected() {
            return connected;
        }

        public BLEPeripheral(BLEManager connector,String deviceId) {
            this.connector = connector;
            this.deviceId = deviceId;

            this.connector.onDisconnected();
            final BluetoothManager bluetoothManager = (BluetoothManager) this.connector.getContext().getSystemService(Context.BLUETOOTH_SERVICE);
            bluetoothAdapter = bluetoothManager.getAdapter();

            if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
                this.connector.enableBluetooth();
                return;
            }

            if (!this.connector.checkPermission()) return;

            scanForDevice();
        }

        public void scanForDevice() {
            connected = false;
            connector.log("BT ENABLED: SCANNING FOR DEVICES");
            connector.reportState(BleManagerStatus.SEARCH_START);
            bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
            bluetoothLeScanner.startScan(mLEScanCallback);
        }

        public void stopScan() {
            connector.reportState(BleManagerStatus.SCAN_CANCEL);
            bluetoothLeScanner.stopScan(mLEScanCallback);
        }

        private final ScanCallback mLEScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType,ScanResult result) {
                BluetoothDevice device = result.getDevice();
                ScanRecord record = result.getScanRecord();
                if (record == null) {
                    connector.log(String.format("Device [%s] has no scan record",device.getAddress()));
                    return;
                }

                String name = record.getDeviceName();
                String UUID = null;

                if (record.getServiceUuids() != null) {
                    for (ParcelUuid pId : record.getServiceUuids()) {
                        if (pId.getUuid().toString().equals(deviceId)) {
                            UUID = pId.getUuid().toString();
                        }
                    }
                }
                if (UUID == null) {
                    if (name != null) connector.log(String.format("Discovered Device [%s]. Continuing search",name));
                    return;
                }
                connector.log(String.format("Peripheral [%s] located on Device [%s]. Attempting connection",UUID,name));
                bluetoothGatt = device.connectGatt(connector.getContext(),true,mGattCallback);
                stopScan();
                connector.reportState(BleManagerStatus.DEVICE_FOUND);
                super.onScanResult(callbackType,result);
            }
        };

        private void closeGatt() {
            connector.reportState(BleManagerStatus.DICSONNECT);
            connector.onDisconnected();
            if (bluetoothGatt == null) {
                return;
            }
            bluetoothGatt.close();
            bluetoothGatt = null;
            scanForDevice();
        }

        private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
            StringBuilder buffer;
                    @Override
                    public void onConnectionStateChange(BluetoothGatt gatt,int status,int newState) {
                        connector.onConnectionStateChange(newState);
                        if (newState == BluetoothProfile.STATE_CONNECTED) {
                            connector.log("Connected to device GATT. Discovering services");
                            connector.reportState(BleManagerStatus.DEVICE_CONNECTED);
                            bluetoothGatt.discoverServices();
                        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                            connector.log("Disconnected from GATT server. Continuing scanning");
                            closeGatt();
                        }
                    }

                    @Override
                    public void onServicesDiscovered(BluetoothGatt gatt,int status) {
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            if (bluetoothGatt.getServices() != null) {
                                connector.log("Services discovered: ["+bluetoothGatt.getServices().size()+"]");
                                for (BluetoothGattService service : bluetoothGatt.getServices()) {
                                    if (service.getUuid().toString().equals(deviceId)) {
                                        bluetoothGattService = service;
                                        connector.onConnected();
                                        connector.log("Service discovered");
                                        connector.log("Attempting characteristic subscription");
                                        connector.subscribeToCharacteristics();
                                    }
                                }
                            }

                        } else {
                            connector.log(String.format("onServicesDiscovered received: [%s]",status));
                        }
                    }

                    @Override
                    public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic,int status) {
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            connector.log(String.format("onCharacteristicRead received: [%s] value: [%s]",characteristic.getUuid().toString(),new String(characteristic.getValue())));
                        } else {
                            connector.log(String.format("onCharacteristicRead fail received: [%s]",status));
                        }
                    }

                    @Override
                    public void onCharacteristicWrite(BluetoothGatt gatt,int status) {
                        super.onCharacteristicWrite(gatt,characteristic,status);
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            connector.log(String.format("onCharacteristicWrite received: [%s] value: [%s]",new String(characteristic.getValue())));
                        }
                    }

                    @Override
                    public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {
                        String packet = new String(characteristic.getValue());
                        if (packet.equals(String.valueOf((char)2))) {
                            buffer = new StringBuilder();
                        } else if (packet.equals(String.valueOf((char)3))) {
                            if (subscriptions == null || subscriptions.size() == 0) return;

                            Command<String> handler = subscriptions.get(characteristic.getUuid().toString());
                            if (handler != null) handler.execute(new String(buffer.toString()));
                        } else {
                            buffer.append(packet);
                        }
                    }
                };

        public BluetoothGattService getService() {
            return bluetoothGattService;
        }

        private BluetoothGattCharacteristic findCharacteristicById(String id) {
            if (bluetoothGattService.getCharacteristics() != null) {
                return bluetoothGattService.getCharacteristic(java.util.UUID.fromString(id));
            }
            return null;
        }

        public void subscribe(String characteristicId,Command<String> handler){
            if (subscriptions == null) subscriptions = new HashMap<>();
            BluetoothGattCharacteristic characteristic = findCharacteristicById(characteristicId);

            if (characteristic == null) {
                connector.log("Characteristic does not exist");
                return;
            }
            connected = true;
            connector.reportState(BleManagerStatus.CHARACTERISTIC_SUBSCRIBED);
            bluetoothGatt.setCharacteristicNotification(characteristic,true);
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            bluetoothGatt.writeDescriptor(descriptor);

            subscriptions.put(characteristicId,handler);
        }

        public void writeCharacteristic(String characteristicId,String data) {
            BluetoothGattCharacteristic characteristic = findCharacteristicById(characteristicId);
            if (characteristic != null) {
                characteristic.setValue(data);
                bluetoothGatt.writeCharacteristic(characteristic);
                connector.log(String.format("Wrote [%s] to [%s]",data,characteristicId));
            } else {
                connector.log(String.format("[%s] not found on device",characteristicId));
            }
        }

        public void readCharacteristic(String characteristicId) {
            BluetoothGattCharacteristic characteristic = findCharacteristicById(characteristicId);
            if (characteristic == null) return;
            bluetoothGatt.readCharacteristic(characteristic);
        }
    }

[SOURCE CODE]

然后我只需要传入一个BLEManager的实例,就是一个简单的接口:

    public interface BLEManager {
        void log(String message);
        void reportState(BleManagerStatus status);
        void onConnectionStateChange(int newState);
        Context getContext();
        void enableBluetooth();
        void onConnected();
        void subscribeToCharacteristics();
        void onDisconnected();
        boolean checkPermission();
    }

[SOURCE CODE]

您的片段/活动可以实现这一点。我认为这被称为 adapter pattern,因为我将 BLE 的实现从 Android 生命周期中抽象出来。

  1. this a video of one of the things I did with it。我也建造了坦克:)
  2. here is the Raspberry Pi part

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-