NoSuchMethod Exception

时间:2016-07-07 02:05:20

标签: java android android-5.0-lollipop bluetooth-lowenergy nosuchmethoderror

我正在使用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引发了一个nosuchmethod异常:

     选择器&#34; getBluetoothLeScanner&#34;

方法查找失败同   签名&#34;()Landroid / bluetooth / le / BluetoothLeScanner;&#34;

2 个答案:

答案 0 :(得分:1)

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

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

mBluetoothLeScanner.startScan(new ScanCallback() {….

}

答案 1 :(得分:0)

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