【问题标题】:Prevent NPE on BluetoothAdapter's onScanResult防止 BluetoothAdapter 的 onScanResult 上的 NPE
【发布时间】:2014-03-20 07:38:36
【问题描述】:

在装有 Android 4.4 的 Nexus 7 上运行时,onScanResult 会引发 NullPointerException,如下面的日志所示:

03-18 17:59:34.170: D/BluetoothAdapter(5092): onScanResult() - Device=78:4B:08:02:7C:91 RSSI=-77
03-18 17:59:34.170: W/BluetoothAdapter(5092): Unhandled exception: java.lang.NullPointerException

但是,其他设备没有这样的问题。

我在googlesource找到了这个

    public void onScanResult(String address, int rssi, byte[] advData) {
        if (DBG) Log.d(TAG, "onScanResult() - Device=" + address + " RSSI=" +rssi);

        // Check null in case the scan has been stopped
        synchronized(this) {
            if (mLeHandle <= 0) return;
        }
        try {
            BluetoothAdapter adapter = mBluetoothAdapter.get();
            if (adapter == null) {
                Log.d(TAG, "onScanResult, BluetoothAdapter null");
                return;
            }
            mLeScanCb.onLeScan(adapter.getRemoteDevice(address), rssi, advData);
        } catch (Exception ex) {
            Log.w(TAG, "Unhandled exception: " + ex);
        }
    }

这有许多潜在的罪魁祸首,但我当然不能为这些变量设置值。

为什么 Nexus 7 会失败,而其他设备则不会?任何解决方法的想法?

【问题讨论】:

    标签: android bluetooth-lowenergy android-bluetooth


    【解决方案1】:

    Android 4.3, 4.4: BLE filtering in startLeScan(UUIDs, callback) doesn't work for 128-bit UUIDs

    它适用于三星 s5,在 Android 4.4.2 上进行了测试,但由于某种原因,它在 Nexus 上失败。等待 Google 堆栈的此修复。

    如果您只想搜索特定地址,您可以使用this 解决方案。基本上,您必须使用 scanRec[],花费额外的精力来解析它,然后将具有匹配地址的设备添加到列表适配器中。

    [我知道,....希望这个简单的 API 能够工作! :P]

    【讨论】:

      【解决方案2】:

      关闭 WIFI:

      我也可以确认,关闭 WIFI 会使蓝牙 4.0 更加稳定,尤其是在 Google Nexus 上(我有一个 Nexus 7)。 问题

      是我正在开发的应用程序需要 WIFI 和持续的蓝牙 LE 扫描。所以关闭WIFI对我来说是没有选择的。

      此外,我意识到持续的蓝牙 LE 扫描实际上可以杀死 WIFI 连接,并使 WIFI 适配器无法重新连接到任何 WIFI 网络,直到 BLE 扫描打开。 (我不确定移动网络和移动互联网)。 这肯定发生在以下设备上:

      Nexus 7
      Motorola Moto G
      

      然而,开启 WIFI 的 BLE 扫描似乎相当稳定:

      Samsung S4
      HTC One
      

      我的解决方法

      我在短时间内扫描 BLE 3-4 秒,然后关闭扫描 3-4 秒。然后再次开启。

      Obviously I always turn BLE scan OFF when I'm connecting to a BLE device.
      When I disconnect from a device I restart BLE (turn adapter OFF and then ON) to reset the stack before starting scan again.
      I also reset BLE when discovering services or characteristics fails.
      When I get advertisement data from a device that the app should connect to (lets say 500 times without being able to connect - thats about 5-10 seconds of advertising) I reset BLE again.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-06
        • 2019-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-09
        相关资源
        最近更新 更多