蓝牙4.0BLE的使用与封装

来源:互联网 发布:数据丢失 编辑:程序博客网 时间:2024/04/30 11:31

简单介绍

 蓝牙发展至今经历了各个版本的更新。1.1、1.2、2.0、2.1、3.0、4.0、4.1、4.2。4.x开始的蓝牙我们称之为低功耗蓝牙也就是蓝牙ble,当然4.x版本的蓝牙也是向下兼容的。低功耗蓝牙较传统蓝牙,传输速度更快,覆盖范围更广,安全性更高,延迟更短,耗电极低等等优点。传统蓝牙与低功耗蓝牙通信方式也有所不同:传统的一般通过socket方式,而低功耗蓝牙是通过Gatt协议来实现。若是之前没做过传统蓝牙开发,也是可以直接上手低功耗蓝牙开发的。因为它们在通信协议上都有所改变,关联不大。当然有兴趣的可以去下载些传统蓝牙开发的demo看看,在看看低功耗蓝牙的demo。两者的不同之处自然容易看出来。。低功耗蓝牙都称之为BLE。

简单介绍BLE

BLE分为三部分:

1、Service(服务)2、Characteristic(特征)3、Descriptor(描述符)这三部分都用UUID作为唯一标识符。UUID为这种格式:0000ffe1-0000-1000-8000-00805f9b34fb。比如有3个Service,那么就有三个不同的UUID与Service对应。这些UUID都写在硬件里,我们通过BLE提供的API可以读取到。一个BLE终端可以包含多个Service, 一个Service可以包含多个Characteristic,一个Characteristic包含一个value和多个Descriptor,一个Descriptor包含一个Value。Characteristic是比较重要的,是手机与BLE终端交换数据的关键,读取设置数据等操作都是操作Characteristic的相关属性。

android中的使用

1、注册权限<uses-permission android:name="android.permission.BLUETOOTH"/>  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>  想声明你的应用程序只能在支持BLE的设备上运行,可以将下面声明包含进你的应用程序manifest文件中:<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"></uses-feature> 2、检查设备是否支持BLEgetPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);3、获取BLE的适配器 BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();如果获取的mBluetoothAdapter为null则说明该设备不支持蓝牙功能4、启动蓝牙的方式有两种    1、使用对话框的方式:    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);      startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);  

}
在onActivityResult的方法中根据相应的需求码获取到的可以得到对应的结果码
resultCode == Activity.REQUEST_ENABLE_BT
蓝牙已经打开,!=蓝牙未打开

    2、直接启用:    mBluetoothAdapter.enable();    3、关闭蓝牙    mBluetoothAdapter.disable();4、搜索蓝牙设备://设备集合private ArrayList<BluetoothDevice> mDevices = new ArrayList<>();//数据记录的集合private ArrayList<byte[]> mRecords= new ArrayList<>();//信号强度的集合private ArrayList<Integer> mRSSIs= new ArrayList<>();    mBluetoothAdapter.startLeScan(mDeviceFoundCallback);private BluetoothAdapter.LeScanCallback mDeviceFoundCallback = new BluetoothAdapter.LeScanCallback() {    @Override    public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {        runOnUiThread(new Runnable(){            //添加设备到集合中            if(mDevices.contains(device)==false){            mDevices.add(device);            mRSSIs.add(rssi);            mRecords.add(scanRecord);            }        });    }};      
0 0
原创粉丝点击