蓝牙4.0BLE的使用与封装

简单介绍

 蓝牙发展至今经历了各个版本的更新。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、检查设备是否支持BLE
getPackageManager().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);
            }
        });
    }
};      
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值