0

我正在为 Android 开发 RSSI 扫描仪。我想通过不断扫描 BLE 设备来归档它。因此,如果要确定设备的 RSSI,则需要通过 BLE 进行广告宣传。测量设备以非常短的间隔开始扫描,当它找到广告商时,可以在扫描结果中读取 RSSI。这导致在广告客户方面出现以下代码:

fun beginAdvertise() {
    val advertiser = BluetoothAdapter.getDefaultAdapter().bluetoothLeAdvertiser
    val settings = AdvertiseSettings.Builder()
        .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
        .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
        .setConnectable(false)
        .build()

    val data = AdvertiseData.Builder()
        .setIncludeDeviceName(true)
        .build()

    val advertisingCallback = object : AdvertiseCallback() {
        override fun onStartFailure(errorCode: Int) {
            Log.e("BLE", "Advertising onStartFailure: " + errorCode);
            super.onStartFailure(errorCode)
        }
    }
    advertiser.startAdvertising(settings, data, advertisingCallback);
}

扫描设备的函数每 20 毫秒调用一次(我尝试了更长的延迟),如下所示:

private val onBluetoothLeDeviceFound = object : ScanCallback() {
    override fun onScanResult(callbackType: Int, result: ScanResult?) {
        result?.let {...}}

fun startScan() {
            val scanner = mBluetoothAdapter?.bluetoothLeScanner
            val scanSetting =
                ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE).build()
            scanner?.startScan(
                null,
                scanSetting,
                onBluetoothLeDeviceFound
            )
         }

此代码在我的 Pixel 2 设备上运行良好。但是,如果我在 Pixel 1(Android 9 上的一个,Android 10 上的另一个)设备上尝试它,则不会调用 onBluetoothLeDeviceFound 回调。我有这些权限:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCTION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

我真的不知道接下来我应该尝试什么。谢谢您的帮助!

4

1 回答 1

0

解决方案很简单,但很耗时。您不仅需要拥有位置权限,还必须启用位置服务!在 Pixel 2 设备上,它们是随机打开的,所以它在那里工作,但在 Pixel 1 上却不行。

于 2020-03-03T19:14:23.350 回答