来自BluetoothAdapter.LeScanCallback的onLeScan未在Android Marshmallow中调用

Raf*_*ñoz 1 android bluetooth android-6.0-marshmallow

我刚刚更新了我的Nexus 5,我的应用程序功能已停止工作.

原因是接口LeScanCallback没有调用该函数onLeScan.在下面的代码中,我使用了一些弃用的代码,但是我需要这样做,因为我正在测试一些技术.这就是我启动蓝牙适配器的方法:

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

    // Check if the device has BLE
    if (!this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))
    {
        bleNotSupported();
        return;
    }

    // Initializes a Bluetooth adapter.
    final BluetoothManager bluetoothManager = (BluetoothManager)this.getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled())
    {
        bleNotEnabled();

        /*
        * Bluetooth can be enabled in app:
        *
        *    Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        *    btIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        *    mAppContext.startActivity(btIntent);
        */
        return;
    }

    boolean bluetoothScanning = mBluetoothAdapter.startLeScan(mScanCallback); // this is true as well
    progressBar.setVisibility(View.VISIBLE);
}

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

    if (mBluetoothAdapter != null)
    {
        mBluetoothAdapter.stopLeScan(mScanCallback);
    }
    progressBar.setVisibility(View.GONE);
    mDeviceAdapter.clearList();
}

BluetoothAdapter.LeScanCallback mScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord)
    {
//            if (previousBluetoothSelected == null)
        mDeviceAdapter.refreshList(device);

        if (device.getAddress().equalsIgnoreCase(previousBluetoothSelected)) {
            selectDeviceAndGo(device);
            mBluetoothAdapter.stopLeScan(this);
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

它适用于API <23的每个设备,但不适用于API = 23.

可能是什么原因?

非常感谢你提前.

问候.

拉斐尔.

Mao*_*dad 8

一些带有Marshmallow的Nexus 5手机有一个bug.在某些手机中,如果您的GPS关闭,扫描将无法启动.

  • 这不是 Nexus 5 的错误,而是 Marshmallow 的工作原理。蓝牙扫描或 WiFi 扫描需要打开定位服务,并且您的应用程序必须声明访问精细或粗略位置。 (2认同)