react-native-ble-manager

repository·master·Indexed 25 days ago

https://github.com/innoveit/react-native-ble-manager

A React Native library for interacting with Bluetooth Low Energy (BLE) devices, providing a bridge to native OS BLE APIs. It supports iOS 15.1+ and Android API 23+, with specific version compatibility for React Native ranging from 0.30 to 0.76+. The library includes support for the New Architecture in RN 0.76+ and provides an Expo config plugin for development builds in versions 12.1.x and later.

Tokens
14.1K
Snippets
44
Records
77
Agent score
80%

What's inside react-native-ble-manager

  1. Setup the React Native BLE Manager Example app

    master

    The example application uses Expo to simplify management. To set up the environment and generate the necessary native projects, install the dependencies and run the Expo prebuild command.

    1. Install dependencies: npm i
    2. Generate native projects: npx expo prebuild
    npm i
    npx expo prebuild
  2. Listen to BLE events using listener methods

    master

    Since React Native version 0.76, events are handled via specific methods on the BleManager instance that return a listener object. To prevent memory leaks, you must call .remove() on the returned listener when the component unmounts.

    Example of subscribing to the onStopScan event:

    useEffect(() => {
      const onStopListener = BleManager.onStopScan((args) => {
        // Scanning is stopped args.status
      });
    
      return () => {
        onStopListener.remove();
      };
        
    }, []);
  3. Configure Android Bluetooth permissions

    master

    To use BLE on Android, you must update your android/app/src/main/AndroidManifest.xml file with the necessary permissions.

    Important Notes:

    • For Android 12+ (API 31+), you must include BLUETOOTH_SCAN, BLUETOOTH_CONNECT, and/or BLUETOOTH_ADVERTISE.
    • If your app uses Bluetooth scan results to derive physical location, do not use the neverForLocation flag on BLUETOOTH_SCAN.
    • If you are working with Beacons, remove android:usesPermissionFlags="neverForLocation".
    • If you need communication while the app is in the background, you must also add the ACCESS_BACKGROUND_LOCATION permission.
  4. Configure iOS Bluetooth permissions

    master

    Update your Info.plist file to include the required usage descriptions for Bluetooth:

    • iOS 13 and higher: Add the NSBluetoothAlwaysUsageDescription key.
    • Earlier than iOS 13: Add the NSBluetoothPeripheralUsageDescription key.
    • Background Usage: To allow Bluetooth communication in the background, add central-peripheral to the UIBackgroundModes key.
  5. Use react-native-ble-manager in Expo via Development Builds

    master

    To use react-native-ble-manager in an Expo project, you must use a development build. Standard Expo Go does not support the native modules required by this library.

    Starting with version 12.x, the library supports the new React Native architecture. For versions 12.1.x and later, you can use the Expo config plugin to automate native configuration by adding it to your app.json or app.config.js file.

    {
        ...
        "plugins" : [
            ...
            ["react-native-ble-manager", { options }]
        ],
    }
  6. Generate Android native code from specs

    master

    To generate Android code via codegen, you must use a React Native project (the provided example folder is used here).

    1. In the example folder, generate the Android project from Expo: npx expo prebuild --platform android.
    2. In the example/android folder, run the codegen command: ./gradlew generateCodegenArtifactsFromSchema.

    Troubleshooting: If you encounter issues with the Gradle cache, run:

    cd android && ./gradlew --stop && rm -rf ~/.gradle/caches
  7. Generate iOS native code from specs

    master

    To generate iOS code via codegen, use the example folder.

    1. In the example folder, generate the iOS project from Expo: npx expo prebuild --platform ios.
    2. Codegen runs during the first build. If you need to trigger it again, run pod install inside the ios folder.
  8. Request Android Bluetooth runtime permissions

    master

    In addition to manifest declarations, you must request runtime permissions during app execution on Android. The following pattern handles permission requests based on the Android API version:

    • API 23 to 30: Requests ACCESS_FINE_LOCATION.
    • API 31+: Requests BLUETOOTH_SCAN and BLUETOOTH_CONNECT.
    /**
     * Request runtime permission.
     * @returns {boolean} 
     */
    async function requestBluetoothPermissions() {
      if (Platform.OS === 'android') {
        const permissions = [];
        if (Platform.Version >= 23 && Platform.Version <= 30) {
          permissions.push(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
        } else if (Platform.Version >= 31) {
          permissions.push(
            PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
            PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
          );
        }
    
        if (permissions.length === 0) {
          return true;
        }
        const granted = await PermissionsAndroid.requestMultiple(permissions);
        return Object.values(granted).every(
          result => result === PermissionsAndroid.RESULTS.GRANTED,
        );
      }
      return true;
    }
  9. Check requirements and platform support for react-native-ble-manager

    master

    Before using react-native-ble-manager, ensure your environment meets the following requirements:

    React Native Version Compatibility

    • RN 0.76+: Only the New Architecture is supported.
    • RN 0.60 - 0.75: Supported up to version 11.5.X.
    • RN 0.40 - 0.59: Supported up to version 6.7.X.
    • RN 0.30 - 0.39: Supported up to version 2.4.3.

    Supported Operating Systems

    • iOS: 15.1+
    • Android: API level 23+
  10. Initialize the BLE Manager with start()

    master
    Before using any BLE functionality, you must initialize the library using the start() method. This initialization can be performed during the application launch sequence or immediately before you begin interacting with Bluetooth Low Energy devices. Failure to call start() before other API calls may result in errors.