前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >10分钟完成一个最最简单的BLE蓝牙接收数据的DEMO

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

作者头像
用户3112896
发布2019-09-26 15:18:52
2.3K0
发布2019-09-26 15:18:52
举报
文章被收录于专栏:安卓圈

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

不需要什么特定的UUID,

不需要什么断开重连,

不需要什么多连接等等,

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

注意:

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

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

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

代码:

代码语言:javascript
复制
<uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-05-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 安卓圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档