RxAndroidBle库scanBleDevices方法调用报错问题求助
Hey there! Let's break down the issues you're facing with RxAndroidBle 1.10.0 in Kotlin and fix them step by step.
First Issue: Error in Java-style scanBleDevices call
The core problem here is Kotlin doesn't use Java's new keyword for object instantiation. Your original code uses new ScanSettings.Builder() which is invalid in Kotlin. Here's the corrected version:
// Initialize RxBleClient correctly val rxBleClient = RxBleClient.create(this) // Build scan settings without the 'new' keyword val scanSettings = ScanSettings.Builder() // Uncomment these if needed // .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) .build() // Start scan - no filters added here, but you can add them later val scanSubscription = rxBleClient.scanBleDevices(scanSettings) .subscribe( { scanResult -> // Process your scan result here println("Discovered device: ${scanResult.bleDevice.macAddress}") }, { error -> // Handle scan errors here error.printStackTrace() } ) // Don't forget to dispose when you're done scanning // scanSubscription.dispose()
Second Issue: Observable type error & scanBleDevices parameter mismatch
You're hitting two separate problems here:
Observable type error: Make sure you're importing the correct RxJava 2 Observable (RxAndroidBle 1.x relies on RxJava 2). Double-check your imports include:
import io.reactivex.Observable import com.polidea.rxandroidble2.scan.ScanResultUsing the wrong Observable class (like RxJava 3 or Java's built-in Observable) will cause the "No type arguments expected" error.
Parameter mismatch for scanBleDevices: The method expects
ScanSettingsplus avararg ScanFilter(variable number of filters). In Kotlin, to pass a single filter to avarargparameter, you need to use the spread operator (*). Here's the fixed function:
private fun scanBleDevices(): Observable<ScanResult> { val scanSettings = ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) .build() val scanFilter = ScanFilter.Builder() // .setDeviceAddress("B4:99:4C:34:DC:8B") // Uncomment if filtering by address .build() // Use spread operator to pass the single filter to vararg parameter return rxBleClient.scanBleDevices(scanSettings, *arrayOf(scanFilter)) // If you don't need any filters, you can simplify to: // return rxBleClient.scanBleDevices(scanSettings) }
Quick Additional Check
Don't forget to ensure your app has the necessary BLE permissions in AndroidManifest.xml (and request runtime location permission for Android 6.0+):
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-feature android:name="android.hardware.bluetooth_le" android:required="true" />
内容的提问来源于stack exchange,提问作者Alejandro Gorgues

