Android 9-BluetoothAdapter startDiscovery()找不到先前找到的设备

时间:2018-11-30 16:38:38

标签: android bluetooth

我有一个使用了几年的Android应用程序,并且一直运行到Android9。我的应用程序将扫描本地蓝牙设备,并在应用程序上显示它们。为此,它将在默认的BluetoothAdapter上执行startDiscovery(),然后通过为BluetoothDevice.ACTION_FOUND注册一个BroadcastReceiver来捕获所有找到的设备。

Android 9之前的版本运行正常。我不确定这个确切的Android版本是否会停止运行,也许Android 8也已损坏。

发布Android 9后,它只能运行一次。意思是在我的第一个startDiscovery()上,我将为所有设备获取Bluetooth.ACTION_FOUND,但是如果我退出应用程序并执行第二个startDiscovery(),则不会再找到该设备。就像Android 9正在缓存结果,而没有给我一种清除缓存或从缓存中获取结果的方法。如果禁用然后重新启用蓝牙设备,它将获得新的扫描结果。

这是我的代码,用于注册BroadcastReceiver(基本上是Google提供的演示代码):

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...

    // Register for broadcasts when a device is discovered.
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter);
}

// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Discovery has found a device. Get the BluetoothDevice
            // object and its info from the Intent.
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress(); // MAC address
        }
    }
};

@Override
protected void onDestroy() {
    super.onDestroy();
    ...

    // Don't forget to unregister the ACTION_FOUND receiver.
    unregisterReceiver(mReceiver);
}

startLeScan()和BluetoothLeScanner.startScan()可以正常工作,但是我无法使用这些功能,因为该应用程序还支持非BLE设备。

我一定缺少简单的东西。

0 个答案:

没有答案