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

后端 未结 4 984
灰色年华
灰色年华 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:14

    1. Create AbstractBluetoothLe class and IBleScanCallback interface. IBleScanCallback interface is a Marker Interface. In other saying, an interface with no methods. You can also add methods to interface if you need. These methods will do the same functionality for all type of scanCallbacks i.e. getListOfFoundBleDevices(), clearListOfFoundBleDevices() etc.
    2. Create BluetootLeLollipop, and BluetoothLeJellyBean classes which extend AbstractBluetoothLe class. Create also BluetootLeMarshmallow class which extends BluetootLeLollipopclass. AbstractBluetoothLe class has protected field mIBleScanCallback which is an IBleScanCallback object.
    3. Create BleScanCallbackBase class which implements IBleScanCallback.
    4. Create LollipopScanCallback class which extends ScanCallback class and implements IBleScanCallback interface. .This class has a protected field scanCallback which will be instantiated as BleScanCallbackBase object. Create also MarshmallowScanCallback class which extends LollipopScanCallback class.
    5. Create JellyBeanScanCallback class which extends BleScanCallbackBase and implements BluetoothAdapter.LeScanCallback
    6. In BleScanCallbackBase override the method: onScanCallback(...)
    7. In LollipoScanCallback override onScanResult(int callbackType, ScanResult result) and inside this method call the method onScanCallback(...) of the scanCallback object.
    8. In JellyBeanScanCallback override onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) and inside this method call onScanCallback(...)
    9. Finally, do whatever needs to be done when a device is found in onScanCallback(...)method of BleScanCallbackBase class.

    In short, read about composition over inheritance- I know this is not an answer to your question but this is a neat way of what you want to achieve in the end. Here is the class diagram:

提交回复
热议问题