Android Bluetooth Library-Simple Use of FastBle

Released from Kindem's blog Welcome to reprint, but note the source

Recently, in the course of Internet of Things, we need to use Android Bluetooth API, but the native Bluetooth API is a little troublesome. So I searched the Internet to see if there was a good Android Bluetooth library, and then I found this baby and shared it with you.

FastBle VS native Android Bluetooth API

The native Android Bluetooth API is a bit cumbersome to use. It's a bit cumbersome to get the Bluetooth adapter of the device first, then register the broadcasting to receive the Bluetooth device information, and cancel the broadcasting when it's used up.

Poor encapsulation can be said to be the most painful part of native Android, because the native Android code is not very independent, mixed with activities, broadcasting and so on. There are few Bluetooth libraries on the market. Looking at BleLib first, I feel that it's not easy to change soup or dressing, and it's not concise at all.

But FastLib encapsulation is very skillful, basically can control the granularity of an operation in one line, in addition, the code does not need to deal with threads, notifications and so on, the library has helped us to complete these complex things.

FastBle's Github project address is here, you can see: [FastBle - GitHub]( https://github.com/Jasonchenlijian/FastBle

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

Use of FastBle

0x00 to declare authority

As long as Bluetooth is used, it is essential to declare permissions. FastBle needs 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" />

One thing to note here is that if Android version is higher than 6.0, users also need to open location information (not only location permissions, but also location information) to scan through Bluetooth.

0x01 Initialization and Global Configuration

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

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

Global configuration can be executed immediately after initialization, although it doesn't matter if it's not configured, each option has a default value:

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

Details of each item can be found in official documents.

0x02 Open Bluetooth

There are many ways to open Bluetooth using the BleManager class in FastBle. Here we recommend the following way. This way will block the thread. If the user does not choose whether to open Bluetooth, the thread will pause execution:

BleManager.getInstance().enableBluetooth();

0x03 Scanning Equipment

When Bluetooth is turned on, the scanning device can be scanned. Before the formal scanning, the scanning rules can be customized, such as:

BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
  .setServiceUuids(serviceUuids)      // Scan only the device for the specified service, optional
  .setDeviceName(true, names)         // Scan only the device with the specified broadcast name, optional
  .setDeviceMac(mac)                  // Scan only the specified mac device, optional
  .setAutoConnect(isAutoConnect)      // autoConnect parameter at connection time, optional, default false
  .setScanTimeOut(10000)              // Scan timeout, optional, default 10 seconds; less than or equal to 0 means no limit on scan 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) {
        // Scanning callbacks to a device that hasn't been scanned before
    }

    @Override
    public void onScanFinished(List<BleDevice> scanResultList) {
        // There will be no duplicate devices in the list of callbacks that have been scanned
    }
});

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

Of course, anywhere, anytime, you can stop scanning directly by using the cancel scan function:

BleManager.getInstance().cancelScan();

0x04 Connecting Equipment

After scanning, you have acquired one or more BleDevice objects that you can use directly to initiate connections to the target device, such as:

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

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

    @Override
    public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
               // The Ble Device is the BLE device that is connected successfully.
    }

    @Override
    public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
               // Connection interruption, isActiveDisConnected means whether the disconnection method was actively invoked?
    }
});

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

Keywords: Android github Mac less

Added by zzman on Sat, 18 May 2019 14:11:16 +0300