[安卓] 20、基于蓝牙BLE的广播包高频快速搜索


前言:

之前介绍过很多蓝牙beacon、搜索、连接、通讯的文章。不过最近我发现:之前写的蓝牙广播包搜索的工程,搜索频率太慢,而且不能一直保持搜索状态。因此,这里探讨下高频蓝牙广播包扫描 —— 蓝牙BLE扫描。

注:本文将从对比之前慢的和现在快的两个工程进行展开

?

1、初始化-onCreate

新的:

// Get the local Bluetooth adapter
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

老的:

// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);

// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();

可见:老的是通过注册广播过滤条件BluetoothDevice.ACTION_FOUNDBluetoothAdapter.ACTION_DISCOVERY_FINISHED,来实现监听蓝牙设备扫描的发现和停止扫描事件。而mReceiver则是回调函数,接下来会介绍;新的暂时看不出啥头绪,仅仅获得bluetoothManagermBluetoothAdapter,接下来会用到。

?

2、开始扫描-doDiscovery

新的:

// Start device discover with the BluetoothAdapter
private void doDiscovery() {
    // If we're already discovering, stop it
    if (mBluetoothAdapter.isDiscovering()) {
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
    // Request discover from BluetoothAdapter
    //use filter not work!!!!!!!!!!
    //UUID[] uuid_arrays = new UUID[1];
    //uuid_arrays[0] = ParcelUuid.fromString(UUID_SERVICE).getUuid();
    //mBluetoothAdapter.startLeScan(uuid_arrays,mLeScanCallback);
    //Log.d("RSSI",uuid_arrays[0].toString() + "  " + UUID.randomUUID().toString());
    mBluetoothAdapter.startLeScan(mLeScanCallback);
}

老的:

// Start device discover with the BluetoothAdapter
private void doDiscovery() {
    // If we're already discovering, stop it
    if (mBtAdapter.isDiscovering()) {
        mBtAdapter.cancelDiscovery();
    }
    // Request discover from BluetoothAdapter
    mBtAdapter.startDiscovery();
}

可见:区别在于一个是BLE操作、一个是普通蓝牙操作。

?

3、监听

新的:

// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
    new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
            byte[] scanRecord) {
                runOnUiThread(new Runnable() {
                    @Override
            public void run() {
                if(device_filter(device)){
                    //mDevicesNameVector.add(device.getName());
                    //mDevicesAddrVector.add(device.getAddress());
                    //mRSSIVector.add((short)rssi);
                    Log.d("RSSI",device.getAddress() + " " + device.getName() + " " + String.valueOf(rssi));
                    ...
                }
            }
        });
    }
};

老的:

// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
//【查找蓝牙设备】
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("onReceive","OK");
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            mDevicesNameVector.add(device.getName());
            mDevicesAddrVector.add(device.getAddress());
            short rssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);
            mRSSIVector.add(rssi);
            Log.d("RSSI",device.getName()+"  "+String.valueOf(rssi));
            // When discovery is finished, change the Activity title
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            setProgressBarIndeterminateVisibility(false);
            if (mDevicesNameVector.size() != 0) {
                Message msg = new Message();//消息
                Bundle bundle = new Bundle();
                bundle.clear();Log.d("onReceive","1");
                msg.what = 0x01;//消息类别
                bundle.putShort("msg",(short) 0);Log.d("onReceive","2");
                    msg.setData(bundle);Log.d("onReceive","3");
                    myHandler.sendMessage(msg);Log.d("onReceive","4");
            }
        }
    }
};

可见:新的相对比较简单、可以持续不断的扫描获取(同一个设备会被不断的扫描到);老的则分为两步:第一步是每次扫描到一次新设备都会有一个FOUND事件、最后停止扫描了还有个FINISH事件,这里我在FINISH事件结束时发出一个msg来通知进行其他操作。

?

4、权限文件配置

新的:

<uses-permission a:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission a:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission a:name="android.permission.BLUETOOTH"/>
<uses-permission a:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-feature a:name="android.hardware.bluetooth_le" a:required="true"/>

老的:

<uses-permission a:name="android.permission.BLUETOOTH" />
<uses-permission a:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission a:name="android.permission.ACCESS_COARSE_LOCATION" />

可见:相差不大,新的比老的多了bluetooth_le说明。

?

5、最后说明

当你尝试使用BLE SCAN之后,你会感觉有一种飞一般的感觉,几乎同一个设备每一秒都会被扫描到多次。拿这些高频扫描的大量数据,就可以做类似beacon、距离估算、定位等小应用了!效果会比老的scan方法要好很多~


LINKS

[1]. 本项目GITHUB链接地址
[2]. 在Linux下搭建安卓APP的开发烧写环境(makefile版)—— 在Linux上用命令行+VIM开发安卓APP
[3]. android developer TextView
[4]. android developer Vector
[5]. android developer String
[6]. android developer Formatter
[7]. android developer Matcher
[8]. android developer Pattern
[9]. 等宽字体-Android 设置字体的三种方法(TypeFace)
[10]. Android 设置TextView滑动滚动条和滑动效果


@beautifulzzzz
智能硬件、物联网,热爱技术,关注产品
博客:http://blog.beautifulzzzz.com
园友交流群:414948975

原文地址:https://www.cnblogs.com/zjutlitao/p/10100212.html

时间: 2024-08-01 22:46:59

[安卓] 20、基于蓝牙BLE的广播包高频快速搜索的相关文章

[蓝牙] 2、蓝牙BLE协议及架构浅析&amp;&amp;基于广播超时待机说广播事件

第一章 BLE基本概念了解 一.蓝牙4.0和BLE区别 蓝牙4.0是一种应用非常广泛.基于2.4G射频的低功耗无线通讯技术.蓝牙低功耗(Bluetooth Low Energy ),人们又常称之为BlueTooth Smart,是由SIG( the Bluetooth Special Interest Group) 在2010年6月起草,在原有标准的蓝牙4.0核心协议上添加的一种低功耗技术. 蓝牙低功耗不等同于蓝牙4.0,只是蓝牙4.0的一个分支.蓝牙4.0是蓝牙3.0+ HS(高速蓝牙)规范的

【转】蓝牙ble app开发(三) -- 抓包

原文网址:http://blog.csdn.net/lckj686/article/details/43156617 关于android 蓝牙app开发抓包的重要性在 android 蓝牙ble app开发(二) -- 关键概念,连接参数,连接请求 中已经详细描述就不再熬述了固件基于cc2540  cc2541 1.环境 需要一个抓包器几十块钱, USBdongle 装Packet Sniffer软件进行抓包. 环境搭建可以参考:http://blog.csdn.net/mzy202/artic

蓝牙BLE以太网网关在智能家居中的应用(基于W5500)

 已刊登至<无线电>六月刊 早在1994年爱立信公司就创立了蓝牙技术,并制定了基本的技术规范,原意是创造一种设备间通讯的标准化协议,以解决设备间通讯不兼容的情况,规范公布后得到大量移动设备制造商的支持,并于1999年成立蓝牙技术联盟(Bluetooth Special Interest Group),该联盟制定并维护蓝牙无线规范,并对设备制造厂商提供Bluetooth认证与授权. 当前影响最广的版本应该是蓝牙4.0,本标准中增加了Bluetooth Smart和Bluetooth Smar

蓝牙4.0BLE抓包(二) – 广播包解析

本文转自:http://www.cnblogs.com/aikm/p/5022502.html 感谢原创作者! SleepingBug评论:这篇文档写的相当好,受教了,多谢了!   作者:强光手电[艾克姆科技-无线事业部] 在使用EN-Dongle捕获和解析广播包之前,我们先了解一下BLE报文的结构,之后,再对捕获的广播包进行分析.在学习BLE的时候,下面两个文档是极其重要的,这是SIG发布的蓝牙的核心协议和核心协议增补. 核心协议Core_v4.2. 核心协议增补CSS v6. 虽然这两个文档

蓝牙BLE数据包格式汇总

以蓝牙4.0为例说明: BLE包格式有:广播包.扫描包.初始化连接包.链路层控制包(LL层数据包).逻辑链路控制和自适应协议数据包(即L2CAP数据包)等: 其中广播包又分为:定向广播包和非定向广播包: 逻辑链路控制和自适应协议数据包又分为:ATT指令包.信令指令包.SMP包: 1. 首先,所有的包都符合如下格式: 2. 广播包: 3. 非定向广播包: 4. 定向广播包: 5. 扫描包: 6. 初始化连接包: 7. 链路层数据包: 8. 链路层控制包: 9. L2CAP层数据包: 10. 信令指

使用RPM包离线安装MariaDB 10.0.20 , 基于CentOS 6.6-x86-64

使用RPM包[离线]安装 MariaDB 10.0.20,基于CentOS 6.6-x86-64 Minimal 湘中朱生 2015-07-01 于深圳福田 QQ: 872007255 MariaDB交流群: 198111730 文档说明: 1. 网上有很多关于MariaDB/Mysql数据库的安装技术博客文档,主要有源码编译安装和Yum源安装,有些写得很规范优秀,但很少有基于离线RPM包安装的. 2. 源码编译安装对于初学者而言门槛过高, 很容易打击MariaDB初学者学习探索的积极性; Yu

微信小程序之蓝牙 BLE 踩坑记录

前言 前段时间接手了一个微信小程序的开发,主要使用了小程序在今年 3 月开放的蓝牙 API ,此过程踩坑无数,特此记录一下跳坑过程.顺便开了另一个相关的小项目,欢迎 start 和 fork: BLE_MiniProgram API简介 微信小程序目前有蓝牙 API 共 18 个,其中操作蓝牙适配器的共有 4 个,分别是 wx.openBluetoothAdapter 初始化蓝牙适配器 wx.closeBluetoothAdapter 关闭蓝牙模块 wx.getBluetoothAdapterS

&lt;转&gt;主流蓝牙BLE控制芯片详解(4):Nordic nRF51822

导读] nRF51822 是功能强大.高灵活性的多协议 SoC,非常适用于 Bluetooth® 低功耗和 2.4GHz 超低功耗无线应用. 同系列芯片资料推荐:    主流蓝牙BLE控制芯片详解(1):TI CC2540    主流蓝牙BLE控制芯片详解(2):CSR BC6130    主流蓝牙BLE控制芯片详解(3):创杰 IS1685S Nordic nRF51822简介 nRF51822 是功能强大.高灵活性的多协议 SoC,非常适用于 Bluetooth® 低功耗和 2.4GHz 超

深入浅出低功耗蓝牙(BLE)协议栈

BLE协议栈为什么要分层?怎么理解BLE"连接"?如果BLE协议只有ATT层没有GATT层会发生什么? 协议栈框架 一般而言,我们把某个协议的实现代码称为协议栈(protocol stack),BLE协议栈就是实现低功耗蓝牙协议的代码,理解和掌握BLE协议是实现BLE协议栈的前提.在深入BLE协议栈各个组成部分之前,我们先看一下BLE协议栈整体架构. 如上图所述,要实现一个BLE应用,首先需要一个支持BLE射频的芯片,然后还需要提供一个与此芯片配套的BLE协议栈,最后在协议栈上开发自己