[安卓] 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、监听

新的:

50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信