Android Bluetooth Low Energy code compatible with API>=21 AND API<21

后端 未结 4 997
灰色年华
灰色年华 2020-12-10 17:24

I\'m developing an app that have to connect with a BLE device, in my code I want to use the new Scan and ScanCallback for BLE implemented from API 21 (Android 5) but I have

4条回答
  •  没有蜡笔的小新
    2020-12-10 18:19

    I would like to share my idea to overcome this crash on devices below API 21. The ScanCallback class has support from API 21. So when you write a code to implement ScanCallback in your scan code it will cause a crash on lover APIs. I have fixed it the following way:

    I created one new abstract class which extending ScanCallback class as follows:

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)  
    public abstract class AppScanCallback extends ScanCallback {}
    

    Now I am using this class instance in my BluetoothService class as follow:

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private AppScanCallback mScanCallback;
    

    And using this variable as follow:

    public void startBleScan() {
        if (isEnabled()) {
            if (Build.VERSION.SDK_INT < 21) {
                _bluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
                mLEScanner = _bluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .build();
                filters = new ArrayList<>();
    
                mScanCallback = new AppScanCallback() {
                    @Override
                    public void onScanResult(int callbackType, ScanResult result) {
                        if (Build.VERSION.SDK_INT >= 21) {
                            BluetoothDevice btDevice = result.getDevice();
                            onLeScanResult(btDevice, result.getScanRecord().getBytes());
                        }
                    }
    
                    @Override
                    public void onBatchScanResults(List results) {
                        for (ScanResult sr : results) {
                            Log.i("ScanResult - Results", sr.toString());
                        }
                    }
                    @Override
                    public void onScanFailed(int errorCode) {
                        Log.e("Scan Failed", "Error Code: " + errorCode);
                    }
                };
                mLEScanner.startScan(filters, settings, mScanCallback);
            }
    
        }
    }
    

    and to stop scan

    public void stopBLEScan() {;
            if (Build.VERSION.SDK_INT < 21) {
                _bluetoothAdapter.stopLeScan(mLeScanCallback);
            } else {
                mLEScanner.stopScan(mScanCallback);
            }
    }
    

    Hope it will help you out.

提交回复
热议问题