记一次BLE(低功耗蓝牙)扫描周围设备慢的一个坑

版权声明:本文为博主原创文章,遵循 CC 4.0 BY 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/a_zhon/article/details/100018719

在这里插入图片描述

BLE蓝牙开发不太清楚的可以看下这篇文章

一、先来看下扫描蓝牙的代码

BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();

//扫描蓝牙
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
    if (scanner != null) {
        scanner.startScan(scanCallback);
    }
} else {
    bluetoothAdapter.startLeScan(leScanCallback);
}
  • 由于编译器提示~~startLeScan()~~是过时的API,所以写成如上代码
    在这里插入图片描述

  • 然后每次扫描发现,扫描到自己的设备总是的那么慢。

二、突发想到GitHub上有个FastBle开源项目,特意安装Demo试试扫描看会不会很快。结果就是每次都是很快的扫描到了设备这让我很是纳闷;就直接看他的源代码了,发现他用的扫描API就是startLeScan()

  • 也就是扫描代码不使用BluetoothLeScannerAPI
bluetoothAdapter.startLeScan(leScanCallback);

这样改改也就愉快的解决了,不得不说真是坑死人不偿命啊!新的API扫描速度竟然比过失API还慢,唉!又少了一嘬头发…

展开阅读全文

Android如何扫描周围设备

07-18

[code=Java] alert.setPositiveButton("扫描设备",rn new DialogInterface.OnClickListener() rnrn public void onClick(DialogInterface dialog,rn int which) rn // TODO Auto-generated method stubrn // Create a BroadcastReceiver for ACTION_FOUNDrn try rn rn Intent intent = new Intent(rn BluetoothAdapter.ACTION_REQUEST_ENABLE);rn // 设置蓝牙可见性,最多300秒rn intent.putExtra(rn BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,rn 300);rn startActivity(intent);//请求是否打开蓝牙rn final Field field = dialog.getClass()rn .getSuperclass()rn .getDeclaredField("mShowing");rn field.setAccessible(true);rn adapter.startDiscovery();//开始扫描rn alert.setTitle("正在扫描...").show();rn mReceiver = new BroadcastReceiver() rn public void onReceive(Context context,rn Intent intent) rn // Register the BroadcastReceiverrn IntentFilter filter = new IntentFilter(rn BluetoothDevice.ACTION_FOUND);rn registerReceiver(mReceiver, filter);//注册rnrn isCane = adapter.isDiscovering();rnrn String action = intent.getAction();rnrn if (BluetoothDevice.ACTION_FOUNDrn .equals(action)) rnrn BluetoothDevice device = intentrn .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);rnrn if (device.getBondState() != BluetoothDevice.BOND_BONDED) rnrn HashMap map = new HashMap();rn map.put(device.getName(),rn device.getAddress());rn listItem.add(map);rn listItemAdapterrn .notifyDataSetChanged();rn rn else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHEDrn .equals(action)) rn alert.setTitle("搜索完成").show();rn adapter.cancelDiscovery();rn rn rn ;rn if (isCane) rn field.set(dialog, false);rn else rn field.set(dialog, true);rn rnrn catch (Exception e) rn e.printStackTrace();rn rn rn );rn AlertDialog ad = alert.create();rn ad.show();rn rn );[/code]rnrn大神看看有什么问题! 论坛

没有更多推荐了,返回首页