zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    一些业内有名的网站收集
    WCF重载
    FCKEditor fckconfig.js配置,添加字体和大小 附:中文字体乱码问题解决
    查询第几条到第几条的数据的SQL语句
    SPOJ 9939 Eliminate the Conflict
    UVA 10534 Wavio Sequence
    HDU 3474 Necklace
    POJ 2823 Sliding Window
    UVA 437 The Tower of Babylon
    UVA 825 Walking on the Safe Side
  • 原文地址:https://www.cnblogs.com/anni-qianqian/p/10875533.html
Copyright © 2011-2022 走看看