NoSuchMethod 异常

NoSuchMethod Exception

我之前使用的是 BLE startLescan,但它现在已经过时了。现在我已经更改了 API level to 23 (from 20) 并为此目的使用了 BluetoothLeScanner。 我的开始扫描函数是:

public void startScan(){
    mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

     mBluetoothLeScanner.startScan(new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);

                String s = "\nRssi : "+result.getRssi()+"" +
                        "\nName (Get Device) : "+result.getDevice().getName()+"" +
                        "\nBytes"+result.getScanRecord().getBytes()+"" +
                        "\nGet Device : " + result.getDevice()+"" +
                        "\nAddress : "+result.getDevice().getAddress()+"" +
                        "\nService UUIds : "+result.getScanRecord().getServiceUuids().get(0)+"" +       //Unique
                        "\nName (Scan Record) : "+result.getScanRecord().getDeviceName()+"" +
                        "\nUuids device : "+result.getDevice().getUuids()+"" +
                        "\nDescribe contents : "+result.describeContents();

                //This will show you all the data in logs.
                Log.e("All Data",s);



            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                super.onBatchScanResults(results);
            }

            @Override
            public void onScanFailed(int errorCode) {
                super.onScanFailed(errorCode);
            }
        });

当我到达第一行时,

java throws a nosuchmethod exception:

method lookup failed for selector "getBluetoothLeScanner" with signature "()Landroid/bluetooth/le/BluetoothLeScanner;"

在这种情况下需要 BluetoothAdapter 的实例。做这样的事情:

Context mContext = getBaseContext();
BluetoothAdapter mBluetoothAdapter = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE).getAdapter();
BluetoothLeScanner mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

mBluetoothLeScanner.startScan(new ScanCallback() {….

}

如果您的设备 API 版本为 20 或更低版本,它将无法使用新的 API。因此,您需要根据设备 os 版本实施这两种扫描方法并检查应使用哪个版本。 (Kitkat 不支持新扫描 API!)