Basis of Android Bluetooth Library FastBle

  • 2021-09-16 08:09:38
  • OfStack

Preface

Recently, I need to use Bluetooth API of Android in the course of doing Internet of Things, but it is a bit troublesome to use the native Bluetooth API. So search on the Internet to see if there is a good Android Bluetooth library, and then found this baby, and share it with everyone.

FastBle VS Native Android Bluetooth API

It is a bit troublesome to use the Bluetooth API of the native Android. It is a bit troublesome to obtain the Bluetooth adapter of the device first, then register the broadcast to receive the Bluetooth device information, and log out the broadcast when it is used up, which is relatively troublesome.

It is difficult to package, which can be said to be the most painful place of native Android, because the code of native Android is not very independent, and it is mixed with Activity and broadcasting. There are very few Bluetooth libraries on the market. After looking at BleLib first, I feel that it is not simple to use.

However, FastLib encapsulation is very skillful, which can basically control the granularity of an operation within one line. In addition, the code does not need to deal with threads and notifications. The library has already helped us finish these complicated things.

The Github project address of FastBle is here. You can see: [FastBle-GitHub] (https://github.com/Jasonchenlijian/FastBle (download locally)

Its documentation is relatively complete, you can check the official documentation to use it: FastBle-Document

Use of FastBle

0x00 Declaration Permission

As long as Bluetooth is used, it is necessary to declare permissions. FastBle requires the following permissions:


<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Note one point here. If Android version is higher than 6.0, users need to open location information (not only location permission, but also location information) before scanning through Bluetooth.

0x01 Initialization and Global Configuration

Initialization needs to be performed before any function in the library is called. Because the library uses singleton mode, it only needs to be initialized once and can be used anywhere. It is recommended to execute initialization code in onCreate:


BleManager.getInstance().init(getApplication());

Global configuration can be performed immediately after initialization. Of course, it doesn't matter if you don't configure it. Every 1 option has a default value:


BleManager.getInstance()
 .enableLog(true)
 .setReConnectCount(1, 5000)
 .setSplitWriteNum(20)
 .setConnectOverTime(10000)
 .setOperateTimeout(5000);

You can find the details of each item in the official document

0x02 Turn on Bluetooth

There are many ways to turn on Bluetooth using the BleManager class in FastBle. The following method is recommended here. This method will block the thread. If the user does not choose whether to turn on Bluetooth or not, the thread will suspend execution:


BleManager.getInstance().enableBluetooth();

0x03 scanning equipment

You can scan the device after turning on Bluetooth. Before the official scan, you can customize the scanning rules, like this:


BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
 .setServiceUuids(serviceUuids) //  Scan only the devices of the specified service, optional 
 .setDeviceName(true, names)  //  Scan only devices with the specified broadcast name, optional 
 .setDeviceMac(mac)   //  Scan only the specified mac Optional device for 
 .setAutoConnect(isAutoConnect) //  At the time of connection autoConnect Parameter, optional, default false
 .setScanTimeOut(10000)  //  Scan timeout, optional, default 10 Seconds; Less than or equal to 0 Indicates that there is no limit to scanning time 
 .build();

BleManager.getInstance().initScanRule(scanRuleConfig);

After setting the rules, you can start scanning, like this


BleManager.getInstance().scan(new BleScanCallBack() {
 @Override
 public void onScanStarted(boolean success) {
 //  Callback to start scanning 
 }

 @Override
 public void onScanning(BleDevice bleDevice) {
 //  Scan to 1 Callbacks to devices that have not been scanned before 
 }

 @Override
 public void onScanFinished(List<BleDevice> scanResultList) {
 //  After scanning the callback, there will be no duplicate devices in the list 
 }
});

These callbacks are safe and will automatically return to the main thread, so you can use them with confidence.

Of course, anywhere and at any time, you can stop scanning by directly using the Cancel Scan function:


BleManager.getInstance().cancelScan();

0x04 Connection Device

After scanning, you have obtained one or more BleDevice objects, which you can directly use to initiate a connection to the target device, like this:


BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
 @Override
 public void onStartConnect() {
 //  Start a connection 
 }

 @Override
 public void onConnectFail(BleDevice bleDevice, BleException exception) {
  //  Connection failed 
 }

 @Override
 public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
  //  Connection succeeded, BleDevice That is, the connected BLE Equipment 
 }

 @Override
 public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
  //  The connection is broken, isActiveDisConnected Indicates whether the disconnect method was called actively 
 }
});

Of course, there are many detailed instructions in the official documents. Here is a brief introduction to the basic use of FastBle. Please see the official documents for details.

Summarize


Related articles: