Convert Figma logo to code with AI

Jasonchenlijian logoFastBle

Android Bluetooth Low Energy (BLE) Fast Development Framework. It uses simple ways to filter, scan, connect, read ,write, notify, readRssi, setMTU, and multiConnection.

5,480
1,244
5,480
247

Top Related Projects

An Android Bluetooth Low Energy (BLE) Library with RxJava3 interface

A library that makes working with Bluetooth LE on Android a pleasure. Seriously.

Quick Overview

FastBle is an Android Bluetooth Low Energy (BLE) library designed to simplify BLE operations. It provides an easy-to-use interface for scanning, connecting, and communicating with BLE devices, making it ideal for developers working on Android apps that require BLE functionality.

Pros

  • Simple and intuitive API for BLE operations
  • Supports multiple simultaneous connections
  • Includes automatic reconnection and error handling
  • Well-documented with clear examples

Cons

  • Limited to Android platform
  • May not support all advanced BLE features
  • Requires careful management of device connections to avoid resource issues
  • Some users report occasional stability issues with certain devices

Code Examples

Scanning for BLE devices:

BleManager.getInstance().scan(new BleScanCallback() {
    @Override
    public void onScanStarted(boolean success) {
        // Scan started
    }

    @Override
    public void onScanning(BleDevice bleDevice) {
        // Device found
    }

    @Override
    public void onScanFinished(List<BleDevice> scanResultList) {
        // Scan finished
    }
});

Connecting to a BLE device:

BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
    @Override
    public void onStartConnect() {
        // Connection attempt started
    }

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

    @Override
    public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
        // Connection successful
    }
});

Reading characteristic data:

BleManager.getInstance().read(
    bleDevice,
    serviceUUID,
    characteristicUUID,
    new BleReadCallback() {
        @Override
        public void onReadSuccess(byte[] data) {
            // Data read successfully
        }

        @Override
        public void onReadFailure(BleException exception) {
            // Read operation failed
        }
    }
);

Getting Started

  1. Add the FastBle dependency to your build.gradle file:
dependencies {
    implementation 'com.clj.fastble:FastBleLib:2.3.4'
}
  1. Initialize BleManager in your Application class:
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        BleManager.getInstance().init(this);
    }
}
  1. Add necessary permissions to your AndroidManifest.xml:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  1. Start using FastBle in your activities or fragments to scan, connect, and communicate with BLE devices.

Competitor Comparisons

An Android Bluetooth Low Energy (BLE) Library with RxJava3 interface

Pros of RxAndroidBle

  • Built on RxJava, providing powerful reactive programming capabilities
  • Robust error handling and automatic retry mechanisms
  • Extensive documentation and community support

Cons of RxAndroidBle

  • Steeper learning curve due to RxJava integration
  • Larger library size compared to FastBle
  • May be overkill for simple BLE applications

Code Comparison

RxAndroidBle:

rxBleClient.scanBleDevices()
    .subscribe { scanResult ->
        // Handle scan result
    }

FastBle:

BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
    .build();
BleManager.getInstance().initScanRule(scanRuleConfig);
BleManager.getInstance().scan(new BleScanCallback() {
    @Override
    public void onScanStarted(boolean success) {
        // Scan started
    }
    @Override
    public void onScanning(BleDevice bleDevice) {
        // Handle scan result
    }
});

RxAndroidBle offers a more concise and reactive approach to BLE operations, while FastBle provides a more traditional callback-based API. RxAndroidBle's reactive nature allows for easier composition of complex BLE operations, but may require more setup and understanding of reactive programming concepts. FastBle's simpler API might be more approachable for developers new to BLE or those working on less complex projects.

A library that makes working with Bluetooth LE on Android a pleasure. Seriously.

Error generating comparison

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

FastBle

FastBle

Android Bluetooth Low Energy fast development framework

API License Version Platform

Filtering, scanning, connecting, reading, writing, notification — all in a simple way.

Wiki · Download APK · Source Analysis


Table of Contents


Features

  • Scan with custom filter rules (name / MAC / UUID)
  • Multi-device simultaneous connections
  • Read, write, notify, indicate operations
  • Signal strength (RSSI) reading & MTU configuration
  • Auto reconnection with configurable retry count and interval
  • Configurable timeouts for connect & operations
  • Modern BluetoothLeScanner + ScanCallback API internally
  • Supports Android 5.0 ~ 15 (API 21 ~ 35)

Requirements

ItemMinimum
Android SDKAPI 21 (Android 5.0)
Java17
Android StudioLadybug (2024.2) or later

Preview

Getting Started

Gradle

Step 1. Add JitPack to your root build.gradle (or settings.gradle):

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Step 2. Add the dependency:

dependencies {
    implementation 'com.github.Jasonchenlijian:FastBle:2.5.0'
}

Permissions

FastBle declares all required permissions in its own manifest. You do NOT need to add them again.

However, you must request runtime permissions before scanning:

private void checkPermissions() {
    List<String> denied = new ArrayList<>();

    // Android 12+
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        if (checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PERMISSION_GRANTED)
            denied.add(Manifest.permission.BLUETOOTH_SCAN);
        if (checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PERMISSION_GRANTED)
            denied.add(Manifest.permission.BLUETOOTH_CONNECT);
    }

    // All versions
    if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PERMISSION_GRANTED)
        denied.add(Manifest.permission.ACCESS_FINE_LOCATION);

    if (!denied.isEmpty()) {
        requestPermissions(denied.toArray(new String[0]), REQUEST_CODE);
    } else {
        startScan();
    }
}

Note: On Android 6.0 ~ 11, GPS must be enabled for BLE scanning. On Android 12+, this is no longer required.

Usage

Init

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

Scan

// Configure scan rules
BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
        .setServiceUuids(serviceUuids)
        .setDeviceName(true, names)
        .setDeviceMac(mac)
        .setAutoConnect(isAutoConnect)
        .setScanTimeOut(10000)
        .build();
BleManager.getInstance().initScanRule(scanRuleConfig);

// Start scanning
BleManager.getInstance().scan(new BleScanCallback() {
    @Override
    public void onScanStarted(boolean success) { }

    @Override
    public void onScanning(BleDevice bleDevice) { }

    @Override
    public void onScanFinished(List<BleDevice> scanResultList) { }
});

Connect

// Connect by BleDevice
BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
    @Override
    public void onStartConnect() { }

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

    @Override
    public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) { }

    @Override
    public void onDisConnected(boolean isActiveDisConnected, BleDevice device,
                               BluetoothGatt gatt, int status) { }
});

// Or connect directly by MAC address
BleManager.getInstance().connect(mac, bleGattCallback);

// Or scan and auto-connect the first matched device
BleManager.getInstance().scanAndConnect(bleScanAndConnectCallback);

Notify / Indicate

// Subscribe to notifications
BleManager.getInstance().notify(bleDevice, uuid_service, uuid_notify,
        new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() { }

            @Override
            public void onNotifyFailure(BleException exception) { }

            @Override
            public void onCharacteristicChanged(byte[] data) { }
        });

// Stop notifications
BleManager.getInstance().stopNotify(bleDevice, uuid_service, uuid_notify);

// Indicate works the same way
BleManager.getInstance().indicate(bleDevice, uuid_service, uuid_indicate, bleIndicateCallback);
BleManager.getInstance().stopIndicate(bleDevice, uuid_service, uuid_indicate);

Read / Write

// Write data
BleManager.getInstance().write(bleDevice, uuid_service, uuid_write, data,
        new BleWriteCallback() {
            @Override
            public void onWriteSuccess(int current, int total, byte[] justWrite) { }

            @Override
            public void onWriteFailure(BleException exception) { }
        });

// Read data
BleManager.getInstance().read(bleDevice, uuid_service, uuid_read,
        new BleReadCallback() {
            @Override
            public void onReadSuccess(byte[] data) { }

            @Override
            public void onReadFailure(BleException exception) { }
        });

Tip: Data longer than 20 bytes is automatically split into packets. Use write(bleDevice, uuid_service, uuid_write, data, split, callback) to control this behavior.

RSSI / MTU

// Read signal strength (device must be connected)
BleManager.getInstance().readRssi(bleDevice, new BleRssiCallback() {
    @Override
    public void onRssiSuccess(int rssi) { }

    @Override
    public void onRssiFailure(BleException exception) { }
});

// Set MTU (range: 23 ~ 512, requires device support)
BleManager.getInstance().setMtu(bleDevice, mtu, new BleMtuChangedCallback() {
    @Override
    public void onMtuChanged(int mtu) { }

    @Override
    public void onSetMTUFailure(BleException exception) { }
});

Other APIs

MethodDescription
isSupportBle()Check if device supports BLE
enableBluetooth()Enable Bluetooth (deprecated on Android 13+)
getAllConnectedDevice()Get all connected devices
isConnected(bleDevice)Check connection state
getConnectState(bleDevice)Get detailed connection state
getBluetoothGatt(bleDevice)Get BluetoothGatt object
getBluetoothGattServices(bleDevice)Get all services
getBluetoothGattCharacteristics(service)Get all characteristics
disconnect(bleDevice)Disconnect a device
disconnectAllDevice()Disconnect all devices
destroy()Release all resources
convertBleDevice(bluetoothDevice)Convert to BleDevice object
requestConnectionPriority(bleDevice, priority)Request connection priority

Changelog

v2.5.0

  • Build: Gradle 8.13, AGP 8.5.0, compileSdk/targetSdk 35, minSdk 21, Java 17
  • Android 12+: Add BLUETOOTH_SCAN / BLUETOOTH_CONNECT runtime permissions
  • Scan API: Replace deprecated startLeScan() with BluetoothLeScanner + ScanCallback
  • Thread safety: Use ConcurrentHashMap for GATT callback maps
  • Bug fixes: Null device name crash, SplitWriter cleanup order, Parcel.readParcelable deprecation
  • Cleanup: Remove unnecessary API version checks (minSdk is now 21)

Star History

Star History Chart

Contact

Channel
WeChatchenlijian1216
Emailjasonchenlijian@gmail.com

License

Copyright 2016 chenlijian

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.