Android Beacon Library - correct use of BluetoothMedic?

巧了我就是萌 提交于 2019-12-01 14:23:40

The Android Beacon Library's BluetoothMedic is designed to detect symptoms of the Android bluetooth stack getting into a bad state, and then optionally cycle power to bluetooth to get out of it. The Medic looks for two OS-level error codes that come back from attempting to scan for a Bluetooth LE device or transmit a Bluetooth LE advertisement. These error codes are known to be associated with a bad state of the bluetooth stack from which recovery generally does not happen without intervention.

The simplest way to set it up is passively like this:

BluetoothMedic medic = BluetoothMedic.getInstance();
medic.enablePowerCycleOnFailures(context);

The above two lines will start the medic listening for any bluetooth errors that happen as a result of regular use of the library's functions (scanning and/or transmitting) by the enclosing app. If these are detected, it will cycle power in an attempt to recover.

This is generally safe to do, but cycling power can cause problems to other functions like classic bluetooth -- if the phone is using a bluetooth speaker when this happens, it will obviously disconnect. Bluetooth LE functions are less likely to be adversely affected by a power cycle, as the error condition in the bluetooth stack probably prevents the functions form working, anyway.

As you have seen, you can also set up the BluetoothMedic to run its own test periodically. This may be a a good idea if you app only periodically works with beacons, and you want to proactively recover from any error conditions before your app needs to use them. To set this up, call:

medic.enablePeriodicTests(context, BluetoothMedic.SCAN_TEST | BluetoothMedic.TRANSMIT_TEST);

You can also call the tests directly, but this is an advanced usage which is not the primary design. If you decide to do so, you should definitely do this on a new thread as they will otherwise block the UI thread until the test completes. This will cause problems like you describe.

If there are no BLE devices in the vicinity during the scan test, then the test "times out" and the results are inconclusive -- you don't know for sure that the bluetooth stack is in a good state. The debug line is an indication of that fact.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!