项目作者: Karewan

项目描述 :
A simple BLE Android client
高级语言: Java
项目地址: git://github.com/Karewan/KnBle.git
创建时间: 2019-09-27T20:46:07Z
项目社区:https://github.com/Karewan/KnBle

开源协议:MIT License

下载


KnBle


API
License: MIT

A simple BLE Android client

Installation

  1. allprojects {
  2. repositories {
  3. ...
  4. maven { url 'https://jitpack.io' }
  5. }
  6. }
  1. android {
  2. compileOptions {
  3. sourceCompatibility JavaVersion.VERSION_11
  4. targetCompatibility JavaVersion.VERSION_11
  5. }
  6. }
  7. dependencies {
  8. implementation 'com.github.Karewan:KnBle:2.4.7'
  9. }

Do not forget to add internet permissions in manifest

  1. <!-- For all Android versions -->
  2. <uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
  3. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>
  4. <!-- Android 6+: Needed for BLE scan -->
  5. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
  6. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
  7. <!-- Android 10+: For background BLE scan (Optional) -->
  8. <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"></uses-permission>
  9. <!-- Android 12+: BLE scan -->
  10. <uses-permission android:name="android.permission.BLUETOOTH_SCAN" ></uses-permission>
  11. <!-- Android 12+: BLE connect to already paired device -->
  12. <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" ></uses-permission>

Then initialize

  1. boolean success = KnBle.gi().init(getApplicationContext());

Verify is init correctly, return false if device is not BLE compatible

  1. boolean isInit = KnBle.gi().isInit();

Scanning operations

Start scan

  1. KnBle.gi().startScan(new BleScanCallback() {
  2. @Override
  3. public void onScanStarted() {
  4. }
  5. @Override
  6. public void onScanFailed(int error) {
  7. // BleScanCallback.BT_DISABLED
  8. // BleScanCallback.LOCATION_DISABLED
  9. // BleScanCallback.SCANNER_UNAVAILABLE
  10. // BleScanCallback.UNKNOWN_ERROR
  11. // BleScanCallback.SCAN_FEATURE_UNSUPPORTED
  12. }
  13. @Override
  14. public void onScanResult(@NonNull BleDevice bleDevice) {
  15. }
  16. @Override
  17. public void onDeviceUpdated(@NonNull BleDevice bleDevice) {
  18. }
  19. @Override
  20. public void onScanFinished(@NonNull HashMap<String, BleDevice> scanResult) {
  21. }
  22. });

Stop scan

  1. KnBle.gi().stopScan();

Set scan settings (before start scan)

  1. // Check ScanSettings class to see all settings
  2. ScanSettings settings = new ScanSettings.Builder().build();
  3. KnBle.gi().setScanSettings(settings);

Set scan filters (before start scan)

  1. // Check ScanFilters class to see all filters
  2. ScanFilters filters = new ScanFilters.Builder().build();
  3. KnBle.gi().setScanFilter(filters);

Check if currently scanning

  1. boolean isScanning = KnBle.gi().isScanning();

Get last scan error

  1. int error = KnBle.gi().getLastError();

Get current scan settings

  1. ScanSettings settings = KnBle.gi().getScanSettings();

Get current scan filters

  1. ScanFilters filters = KnBle.gi().getScanFilters();

Get all scanned devices (string is the mac address)

  1. HashMap<String, BleDevice> devices = KnBle.gi().getScannedDevices();

Clear scanned devices

  1. KnBle.gi().clearScannedDevices();

Stop and reset scan completely (boolean resetSettings, boolean resetFilters)

  1. KnBle.gi().resetScan(true, true);

Device operations

Get device from MAC address

  1. BleDevice device = KnBle.gi().getBleDeviceFromMac("FF:FF:FF:FF:FF:FF");

Get list of connected devices

  1. List<BleDevice> devices = KnBle.gi().getConnectedDevices();

Check if device is connected

  1. boolean connected = KnBle.gi().isConnected(device);

Connect to a device

  1. KnBle.gi().connect(device, new BleGattCallback() {
  2. @Override
  3. public void onConnecting() {
  4. }
  5. @Override
  6. public void onConnectFailed() {
  7. }
  8. @Override
  9. public void onConnectSuccess(List<BluetoothGattService> services) {
  10. }
  11. @Override
  12. public void onDisconnected() {
  13. }
  14. });

Check if device has a gatt service

  1. KnBle.gi().hasService(device, "service uuid", new BleCheckCallback() {
  2. @Override
  3. public void onResponse(boolean res) {
  4. }
  5. });

Check if device has a gatt characteristic

  1. KnBle.gi().hasCharacteristic(device, "service uuid", "characteristic uuid", new BleCheckCallback() {
  2. @Override
  3. public void onResponse(boolean res) {
  4. }
  5. });

Write data in gatt characteristic

  1. KnBle.gi().write(device, "service uuid", "characteristic uuid", data, new BleWriteCallback() {
  2. @Override
  3. public void onWriteFailed() {
  4. }
  5. @Override
  6. public void onWriteProgress(int current, int total) {
  7. }
  8. @Override
  9. public void onWriteSuccess() {
  10. }
  11. });
  12. // OR
  13. // true=split data
  14. // 20=split into packet of
  15. // true=if true send when android set last packet sent as success else send immediately
  16. // 25=interval between two packet
  17. KnBle.gi().write(device, "service uuid", "characteristic uuid", data, true, 20, true, 25, new BleWriteCallback() {
  18. @Override
  19. public void onWriteFailed() {
  20. }
  21. @Override
  22. public void onWriteProgress(int current, int total) {
  23. }
  24. @Override
  25. public void onWriteSuccess() {
  26. }
  27. });

Read gatt characteristic data

  1. KnBle.gi().read(device, "service uuid", "characteristic uuid", new BleReadCallback() {
  2. @Override
  3. public void onReadSuccess(byte[] data) {
  4. }
  5. @Override
  6. public void onReadFailed() {
  7. }
  8. });

Enable characteristic notification

  1. KnBle.gi().enableNotify(device, "service uuid", "characteristic uuid", new BleNotifyCallback() {
  2. @Override
  3. public void onNotifyEnabled() {
  4. }
  5. @Override
  6. public void onNotifyDisabled() {
  7. }
  8. @Override
  9. public void onNotify(byte[] data) {
  10. }
  11. });

Disable characteristic notification

  1. KnBle.gi().disableNotify(device);

Request connection priority

  1. KnBle.gi().requestConnectionPriority(device, connectionPriority);

Request MTU change

  1. KnBle.gi().requestMtu(device, mtu);

Get current MTU

  1. int mtu = KnBle.gi().getMtu(device);

Set prefered PHY

  1. KnBle.gi().setPreferredPhy(device, txPhy, rxPhy, phyOptions);

Change BleGattCallback of a device

  1. KnBle.gi().setGattCallback(device, newCallback);

Disconnect a device

  1. KnBle.gi().disconnect(device);

Disconnect all devices

  1. KnBle.gi().disconnectAll();

Get device connection state

  1. int state = KnBle.gi().getDeviceConnState(device);
  2. // BleGattCallback.DISCONNECTED
  3. // BleGattCallback.CONNECTING
  4. // BleGattCallback.CONNECTED

Get the BluetoothGatt of a device

  1. @Nullable
  2. BluetoothGatt gatt = KnBle.gi().getBluetoothGatt(device);

Get last gatt status code of a device

  1. int status = KnBle.gi().getLastGattStatusOfDevice(device);

Destroy all devices instances

  1. KnBle.gi().destroyAllDevices();

Others operations

Check if bluetooth adapter is enabled

  1. boolean enabled = KnBle.gi().isBluetoothEnabled();

Enable/Disable bluetooth adapter (Deprecated in Android 13+)

  1. // Enable
  2. KnBle.gi().enableBluetooth(true);
  3. // Disable
  4. KnBle.gi().enableBluetooth(false);

Get the bluetooth adapter

  1. BluetoothAdapter adapter = KnBle.gi().getBluetoothAdapter();

Get the bluetooth manager service

  1. BluetoothManager btManager = KnBle.gi().getBluetoothManager();

Get KnBle context

  1. Context ctx = KnBle.gi().getContext();

Toggle DEBUG

  1. KnBle.DEBUG = false;

License

  1. The MIT License (MIT)
  2. Copyright (c) 2019-2023 Florent VIALATTE
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.