10分钟完成一个最最简单的BLE蓝牙接收数据的DEMO

这两天在研究蓝牙,网上有关蓝牙的内容非常有限,Github上的蓝牙框架也很少很复杂,为此我特地写了一个最最简单的DEMO,实现BLE蓝牙接收数据的问题,

不需要什么特定的UUID,

不需要什么断开重连,

不需要什么多连接等等,

网上都把BLE蓝牙写的好复杂好复杂,那不是我想要的,我只想为新手提供一个最基本的例子

注意:

1.本DEMO运行前提是蓝牙已经配对成功,如果想实现自动配对可以期待我的下一篇文章

2.修改代码中的“你想要接收数据的已配对设备名称”为你真实的蓝牙设备

3.复制粘贴下面的代码,日志TAG是“BLE”

代码:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import java.util.List;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    private BluetoothAdapter adapter;
    private BluetoothGatt bluetoothGatt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        openBlueToothLe();
    }

    //打开蓝牙
    private void openBlueToothLe() {
        adapter = BluetoothAdapter.getDefaultAdapter();
        if (null == adapter) {
            Toast.makeText(this, "没有蓝牙功能", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!adapter.isEnabled()) {
            adapter.enable();
        }
        startScan();
    }

    //开始扫描
    private void startScan() {
        Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices();
        for (BluetoothDevice bondedDevice : bondedDevices) {
            if ("你想要接收数据的已配对设备名称".equals(bondedDevice.getName().trim())) {
                connectDevice(bondedDevice);
            }
        }
    }

    //连接设备
    private void connectDevice(BluetoothDevice bondedDevice) {
        bluetoothGatt = bondedDevice.connectGatt(this, false, new BluetoothGattCallback() {
            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                super.onConnectionStateChange(gatt, status, newState);
                if (BluetoothGatt.STATE_CONNECTED == newState) {
                    bluetoothGatt = gatt;
                    gatt.discoverServices();
                } else if (BluetoothGatt.STATE_DISCONNECTED == newState) {
                    gatt.close();
                }
            }

            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                super.onServicesDiscovered(gatt, status);
                List<BluetoothGattService> services = gatt.getServices();
                for (BluetoothGattService service : services) {
                    List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                    for (BluetoothGattCharacteristic character : characteristics) {
                        enableNotification(gatt, service.getUuid(), character.getUuid());
                    }
                }
            }

            @Override
            public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                super.onCharacteristicChanged(gatt, characteristic);
                byte[] value = characteristic.getValue();
                Log.i("BLE", "receive value ----------------------------");
                for (int i = 0; i < value.length; i++) {
                    Log.i("BLE", "character_value = " + value[i]);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bluetoothGatt.disconnect();
    }

    public boolean enableNotification(BluetoothGatt gatt, UUID serviceUUID, UUID characteristicUUID) {
        boolean success = false;
        BluetoothGattService service = gatt.getService(serviceUUID);
        if (service != null) {
            BluetoothGattCharacteristic characteristic = findNotifyCharacteristic(service, characteristicUUID);
            if (characteristic != null) {
                success = gatt.setCharacteristicNotification(characteristic, true);
                if (success) {
                    // 来源:http://stackoverflow.com/questions/38045294/oncharacteristicchanged-not-called-with-ble
                    for (BluetoothGattDescriptor dp : characteristic.getDescriptors()) {
                        if (dp != null) {
                            if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
                                dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                            } else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
                                dp.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                            }
                            gatt.writeDescriptor(dp);
                        }
                    }
                }
            }
        }
        return success;
    }

    private BluetoothGattCharacteristic findNotifyCharacteristic(BluetoothGattService service, UUID characteristicUUID) {
        BluetoothGattCharacteristic characteristic = null;
        List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
        for (BluetoothGattCharacteristic c : characteristics) {
            if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0
                    && characteristicUUID.equals(c.getUuid())) {
                characteristic = c;
                break;
            }
        }
        if (characteristic != null)
            return characteristic;
        for (BluetoothGattCharacteristic c : characteristics) {
            if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0
                    && characteristicUUID.equals(c.getUuid())) {
                characteristic = c;
                break;
            }
        }
        return characteristic;
    }
}

对,就是这么简单,一个类足以,接下来就可以在Android studio的Logcat看到打印的返回值了

Github地址:https://github.com/king1039/BlueToothLe

欢迎关注我的微信公众号:安卓圈

转载于:https://www.cnblogs.com/anni-qianqian/p/10875533.html

这里给出一个简单的 Android BLE 获取体温数据的蓝牙app代码示例。 首先,需要在项目的 `AndroidManifest.xml` 文件中添加 BLE 权限: ```xml <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> ``` 然后,在 `MainActivity.java` 中,进行 BLE 的初始化、连接和数据读取: ```java public class MainActivity extends AppCompatActivity { private BluetoothManager bluetoothManager; private BluetoothAdapter bluetoothAdapter; private BluetoothGatt bluetoothGatt; private BluetoothGattCharacteristic temperatureCharacteristic; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); BluetoothDevice device = bluetoothAdapter.getRemoteDevice("00:11:22:33:44:55"); bluetoothGatt = device.connectGatt(this, false, gattCallback); } private BluetoothGattCallback gattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { gatt.discoverServices(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { // 断开连接 } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { BluetoothGattService service = gatt.getService(UUID.fromString("00001809-0000-1000-8000-00805f9b34fb")); temperatureCharacteristic = service.getCharacteristic(UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb")); gatt.setCharacteristicNotification(temperatureCharacteristic, true); } } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { if (characteristic == temperatureCharacteristic) { // 解析温度数据 byte[] data = characteristic.getValue(); float temperature = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getFloat(); Log.d(TAG, "Temperature: " + temperature); } } }; } ``` 在上面的代码中,我们首先通过 `BluetoothManager` 和 `BluetoothAdapter` 初始化 BLE,连接指定的设备,然后在 GATT 回调函数中,发现可用服务和特征,设置特征的通知,最后在特征值改变时读取并解析温度数据。 需要注意的是,这只是一个简单的示例,实际的实现可能会更加复杂,需要根据具体的硬件设计和数据格式进行适当的修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值