React Native Bluetooth Low Energy library
npm install @sfourdrinier/react-native-ble-plx> Fork Notice: This library is forked from dotintent/react-native-ble-plx because the official library does not support Expo SDK 54+ and React Native 0.81+. We've updated it to work with modern React Native and converted it from Flow to TypeScript.
>
> Looking for maintainers! We're looking for volunteers to help maintain this fork. If you're interested, please open an issue or submit a PR.
> Maintainers note: This repo is managed with pnpm (not yarn/npm).
It supports:
- observing device's Bluetooth adapter state
- scanning BLE devices
- making connections to peripherals
- discovering services/characteristics
- reading/writing characteristics
- observing characteristic notifications/indications
- reading RSSI
- negotiating MTU
- background mode on iOS>)
- NEW: background mode on Android (foreground service)
- NEW: automatic reconnection with exponential backoff
- NEW: connection queue with retry logic
- turning the device's Bluetooth adapter on
It does NOT support:
- bluetooth classic devices.
- communicating between phones using BLE (Peripheral support)
- bonding peripherals
- beacons
1. Compatibility
2. Recent Changes
3. Documentation & Support
4. Configuration & Installation
5. iOS BLE State Restoration
6. Android Background Mode
7. Reliability Features
8. Troubleshooting
9. Releasing
10. Contributions
> Note: This is a fork of dotintent/react-native-ble-plx maintained at @sfourdrinier/react-native-ble-plx. It has been converted from Flow to TypeScript and updated for modern React Native.
Minimum Requirements (v3.5.0+):
- React Native 0.81.4+
- Expo SDK 54+
- Node.js 18+
| React Native | Expo SDK | This Fork |
| ------------ | -------- | --------- |
| 0.81.4+ | 54+ | :white_check_mark: |
| < 0.81 | < 54 | :x: Not supported |
For older React Native versions, use the upstream dotintent/react-native-ble-plx library.
3.7.7 (This Fork)
- Connection Manager: NEW unified ConnectionManager with retry logic, timeout support, and automatic reconnection
- Critical Bug Fixes (4 Stop-Ship Issues Resolved):
- ✅ Fixed promise coalescing hang when multiple callers connect to same device
- ✅ Fixed memory leak in destroy() for auto-reconnect subscriptions
- ✅ Fixed connection storms from repeated disconnect events
- ✅ Fixed race condition where cancel() + auto-reconnect could still trigger retries (attemptId pattern)
- Fixed foreground service crash on null intent restart (Android)
- Fixed ReconnectionManager race condition (callbacks after disable)
- Fixed ConnectionQueue blocking all devices during retry delays
- Added proper error normalization to BleError
- Android 12+ Compatibility (Production-Critical):
- ✅ Fixed STOP service crash (now uses stopService() instead of startService())
- ✅ Added foreground state check before starting service (prevents ForegroundServiceStartNotAllowedException)
- ✅ Safe UPDATE notification handling with try-catch
- ✅ Verified Android 14 (API 34) compliance with FOREGROUND_SERVICE_CONNECTED_DEVICE
- Improvements:
- Connection timeout support (prevents hangs)
- Concurrent connections to different devices
- Comprehensive test suite (8 tests covering all critical bugs)
- Production-grade error handling and cleanup
- Deprecated: ConnectionQueue and ReconnectionManager (use ConnectionManager instead)
3.7.6 (This Fork)
- Refactored iOS BLE restoration to work standalone without external dependencies
- Removed BleRestoration pod dependency, added bundled fallback registry
- Improved Expo config plugin to use autolinking config
3.7.0 (This Fork)
- Android Background Mode: Added foreground service support for reliable background BLE operations
- Connection Queue: ConnectionQueue class with automatic retry and exponential backoff
- Reconnection Manager: ReconnectionManager class for automatic reconnection on unexpected disconnects
- New Types: Added BackgroundModeOptions and ReconnectionOptions types
- Expo config plugin now supports androidEnableForegroundService option
3.5.x (This Fork)
- Converted from Flow to TypeScript
- Updated for React Native 0.81.4 and Expo SDK 54
- Added iOS BLE state restoration support (optional)
- Fixed TypeScript errors from Flow-to-TS conversion
- Dropped support for React Native < 0.81 and Expo < 54
3.2.0 (Upstream)
- Added Android Instance checking before calling its method, an error will be visible on the RN side
- Added information related to Android 14 to the documentation.
- Changed destroyClient, cancelTransaction, setLogLevel, startDeviceScan, stopDeviceScan calls to promises to allow error reporting if it occurs.
- Fixed one of the functions calls that clean up the BLE instance after it is destroyed.
Current version changes
All previous changes
Interested in React Native project involving Bluetooth Low Energy? We can help you!
Documentation can be found here.
Quick introduction can be found here
Contact us at intent.
> This package cannot be used in the "Expo Go" app because it requires custom native code.
> First install the package with yarn, npm, or npx expo install.
``bash`
npm install @sfourdrinier/react-native-ble-plxor
pnpm add @sfourdrinier/react-native-ble-plx
After installing, add the config plugin to the plugins array of your app.json or app.config.js:
`json`
{
"expo": {
"plugins": ["@sfourdrinier/react-native-ble-plx"]
}
}
Then you should build the version using native modules (e.g. with npx expo prebuild command).npx expo run:android
And install it directly into your device with .
You can find more details in the "Adding custom native code" guide.
The plugin provides props for extra customization. Every time you change the props or plugins, you'll need to rebuild (and prebuild) the native app. If no extra properties are added, defaults will be used.
- debug (_boolean_): Enable debug logging for the Expo config plugin. You can also set BLEPLX_PLUGIN_DEBUG=1 (or true/yes) in your environment to enable logs without changing config. Default false.BlePlxDebugLogging
- When enabled, this also stamps a runtime-native flag () into iOS Info.plist and Android AndroidManifest.xml metadata so native debug logs can be gated consistently across platforms.isBackgroundEnabled
- (_boolean_): Enable background BLE support on Android. Adds to the AndroidManifest.xml. Default false.neverForLocation
- (_boolean_): Set to true only if you can strongly assert that your app never derives physical location from Bluetooth scan results. The location permission will be still required on older Android devices. Note, that some BLE beacons are filtered from the scan results. Android SDK 31+. Default false. _WARNING: This parameter is experimental and BLE might not work. Make sure to test before releasing to production._modes
- (_string[]_): Adds iOS UIBackgroundModes to the Info.plist. Options are: peripheral, and central. Defaults to undefined.bluetoothAlwaysPermission
- (_string | false_): Sets the iOS NSBluetoothAlwaysUsageDescription permission message to the Info.plist. Setting false will skip adding the permission. Defaults to Allow $(PRODUCT_NAME) to connect to bluetooth devices.iosEnableRestoration
- (_boolean_): Opt-in to the iOS BLE state restoration subspec (disabled by default). When true, the Podfile will include react-native-ble-plx/Restoration and the adapter will register with a restoration registry if present.iosRestorationIdentifier
- (_string_): Custom CBCentralManager restoration identifier. Written to Info.plist as BlePlxRestoreIdentifier and passed to BleManager for state restoration. Defaults to com.reactnativebleplx.restore.androidEnableForegroundService
- (_boolean_): NEW Enable Android foreground service for background BLE operations. Adds necessary permissions (FOREGROUND_SERVICE, FOREGROUND_SERVICE_CONNECTED_DEVICE) and service declaration to AndroidManifest.xml. Default false.
> Expo SDK 48 supports iOS 13+ which means NSBluetoothPeripheralUsageDescription is fully deprecated. It is no longer setup in @config-plugins/react-native-ble-plx@5.0.0 and greater.
#### Example
`json`
{
"expo": {
"plugins": [
[
"@sfourdrinier/react-native-ble-plx",
{
"isBackgroundEnabled": true,
"modes": ["peripheral", "central"],
"bluetoothAlwaysPermission": "Allow $(PRODUCT_NAME) to connect to bluetooth devices",
"iosEnableRestoration": true,
"iosRestorationIdentifier": "com.example.myapp.bleplx",
"androidEnableForegroundService": true
}
]
]
}
}
1. Install the package: pnpm add @sfourdrinier/react-native-ble-plx (or npm install --save @sfourdrinier/react-native-ble-plx)ios
1. Enter folder and run pod updateNSBluetoothAlwaysUsageDescription
1. Add in info.plist file. (it is a requirement since iOS 13)Capabilities
1. If you want to support background mode:
- In your application target go to tab and enable Uses Bluetooth LE Accessories inBackground Modes
section.restoreStateIdentifier
- Pass and restoreStateFunction to BleManager constructor.
#### Optional: iOS BLE State Restoration (Restoration subspec)
- Opt-in via the config plugin: set iosEnableRestoration: true and optionally iosRestorationIdentifier to a stable string.BlePlxRestoreIdentifier
- The plugin writes into Info.plist and injects the react-native-ble-plx/Restoration subspec into your Podfile.BleManager
- In JS, pass the same identifier to :
`ts`
const manager = new BleManager({
restoreStateIdentifier: 'com.example.myapp.bleplx',
restoreStateFunction: (restoredState) => {
// Rehydrate your app, reconnect devices, etc.
},
});
- The Restoration subspec exposes a Swift adapter (BlePlxRestorationAdapter) that will register with any restoration registry present in the host app (for example, a shared BleRestorationRegistry). If no registry is present, it is a no-op.
1. Install the package: pnpm add @sfourdrinier/react-native-ble-plx (or npm install --save @sfourdrinier/react-native-ble-plx)build.gradle
1. In top level make sure that min SDK version is at least 23:
`groovy`
buildscript {
ext {
...
minSdkVersion = 23
...
1. In build.gradle make sure to add jitpack repository to known repositories:
`groovy`
allprojects {
repositories {
...
maven { url 'https://www.jitpack.io' }
}
}
1. In AndroidManifest.xml, add Bluetooth permissions and update :
`xml
...
...
`
1. (Optional) In SDK 31+ You can remove ACCESS_FINE_LOCATION (or mark it as android:maxSdkVersion="30" ) from AndroidManifest.xml and add neverForLocation flag into BLUETOOTH_SCAN permissions which says that you will not use location based on scanning eg:
`xml
...
`
With neverForLocation flag active, you no longer need to ask for ACCESS_FINE_LOCATION in your app
This fork includes optional support for iOS BLE state restoration, allowing your app to automatically reconnect to BLE devices after iOS terminates it in the background.
| Scenario | Without Restoration | With Restoration |
|----------|---------------------|------------------|
| App killed by iOS while connected | Connection lost, user must manually reconnect | Auto-reconnects when device sends data |
| Phone rebooted while wearing sensor | Must open app and reconnect | System restores connection automatically |
| Long recording session (hours) | Risk of disconnection if iOS reclaims memory | Seamless reconnection maintains session |
1. User connects to a BLE device and starts streaming data
2. User switches to another app or locks the phone
3. iOS terminates your app to free memory (not a crash - iOS reclaiming resources)
4. Later, the BLE device sends data (e.g., user is still wearing it)
5. iOS wakes your app in the background with the restoration state
6. BlePlxRestorationAdapter handles automatic reconnection
`json`
{
"expo": {
"plugins": [
[
"@sfourdrinier/react-native-ble-plx",
{
"isBackgroundEnabled": true,
"modes": ["central"],
"iosEnableRestoration": true,
"iosRestorationIdentifier": "com.yourapp.bleplx"
}
]
]
}
}
Then in your JavaScript code:
`typescript`
const manager = new BleManager({
restoreStateIdentifier: 'com.yourapp.bleplx', // Must match iosRestorationIdentifier
restoreStateFunction: (restoredState) => {
if (restoredState?.connectedPeripherals) {
console.log('Restored peripherals:', restoredState.connectedPeripherals);
// Reconnect to devices, resume streaming, etc.
}
},
});
1. Add the Restoration subspec to your Podfile:
`ruby`
pod 'react-native-ble-plx/Restoration', :path => '../node_modules/@sfourdrinier/react-native-ble-plx'
2. Add to your Info.plist:`
xml`
4. Enable background modes in Xcode: Capabilities → Background Modes → Uses Bluetooth LE accessories
No action needed. The restoration feature is entirely opt-in:
- The Restoration subspec is not included by defaultreact-native-ble-plx
- Native code uses runtime reflection - if restoration classes aren't present, it's a no-op
- No changes to the JavaScript API
- Works exactly like upstream
For apps using multiple BLE SDKs (e.g., Polar SDK + generic BLE-PLX), you can provide your own BleRestorationRegistry implementation with device-to-adapter routing. The bundled adapter uses reflection to find registries:
1. Bundled fallback: Works out of the box via BlePlxBundledRestorationRegistryBleRestorationRegistry
2. Custom registry: If you provide a class named , it takes priority
`swift
// Your custom BleRestorationRegistry implementation
@objc(BleRestorationRegistry)
public final class BleRestorationRegistry: NSObject {
@objc public static let shared = BleRestorationRegistry()
@objc(registerAdapter:)
public func registerAdapter(_ cls: AnyClass) { / ... / }
@objc(registerDevice:forAdapter:)
public func registerDevice(_ deviceId: String, for cls: AnyClass) { / ... / }
}
`
This ensures that when iOS restores the app, each device is reconnected by the appropriate SDK.
If you're targeting Android 12 (API 31) or higher, you MUST follow these requirements:
#### 1. Required Permissions in AndroidManifest.xml
`xml
tools:targetApi="upside_down_cake" />
`
#### 2. Call enableBackgroundMode() While App is in Foreground
Android 12+ restricts starting foreground services from background. You must call enableBackgroundMode() while your app is visible to the user:
`typescript
// ✅ CORRECT: Call while app is in foreground
const handleStartRecording = async () => {
// User just tapped "Start Recording" button - app is in foreground
await bleManager.enableBackgroundMode({
notificationTitle: 'Recording Session Active',
notificationText: 'Syncing sensor data...'
});
// Now you can safely background the app and BLE will continue
await connectAndStartRecording();
};
// ❌ WRONG: Calling from background task/timer
setTimeout(async () => {
// App may be backgrounded - this will throw on Android 12+
await bleManager.enableBackgroundMode({ / ... / });
}, 60000);
`
Error if violated: IllegalStateException: Cannot start foreground service from background on Android 12+
#### 3. Service Type Declaration (Expo Plugin Handles This)
If using the Expo config plugin with androidEnableForegroundService: true, the service type is configured automatically. For manual setup, ensure your service has:
`xml`
android:enabled="true"
android:exported="false"
android:foregroundServiceType="connectedDevice"
tools:targetApi="q" />
| Android Version | Min SDK | Target SDK | Requirements |
|----------------|---------|------------|--------------|
| Android 14+ (API 34+) | 24 | 34 | FOREGROUND_SERVICE_CONNECTED_DEVICE permission + service type |
| Android 12-13 (API 31-33) | 24 | 31+ | Foreground state check required |
| Android 8-11 (API 26-30) | 24 | 26+ | Standard foreground service |
| Android < 8 (API < 26) | 24 | - | No foreground service needed |
---
Android requires a foreground service to keep BLE operations alive when the app is in the background. This fork adds built-in support for this.
`json`
{
"expo": {
"plugins": [
[
"@sfourdrinier/react-native-ble-plx",
{
"isBackgroundEnabled": true,
"androidEnableForegroundService": true
}
]
]
}
}
`typescript
import { BleManager } from '@sfourdrinier/react-native-ble-plx';
const manager = new BleManager();
// Enable background mode before starting BLE operations
await manager.enableBackgroundMode({
notificationTitle: 'Connected to Heart Rate Monitor',
notificationText: 'Syncing health data...'
});
// ... perform BLE operations ...
// Update the notification while running
await manager.updateBackgroundNotification({
notificationTitle: 'Syncing Data',
notificationText: 'Progress: 75%'
});
// Check if background mode is active
const isEnabled = await manager.isBackgroundModeEnabled();
// Disable when done
await manager.disableBackgroundMode();
`
| Feature | iOS | Android | Notes |
|---------|-----|---------|-------|
| Background BLE Operations | ✅ Built-in via UIBackgroundModes | ✅ Foreground Service | Both platforms fully supported |
| Configuration | Info.plist + Expo plugin | Manifest permissions + Expo plugin | Platform-specific setup |
| enableBackgroundMode() API | ✅ No-op (graceful) | ✅ Required | Same API, platform-appropriate behavior |
| disableBackgroundMode() API | ✅ No-op (graceful) | ✅ Stops service | Same API, platform-appropriate behavior |
| updateBackgroundNotification() API | ✅ No-op (graceful) | ✅ Updates notification | iOS doesn't show notification |
| isBackgroundModeEnabled() API | ✅ Returns false | ✅ Returns true/false | Consistent return type |
| Connection Management | ✅ ConnectionManager | ✅ ConnectionManager | 100% API parity |
| Auto-reconnection | ✅ Full support | ✅ Full support | 100% feature parity |
| Retry Logic | ✅ Full support | ✅ Full support | 100% feature parity |
| Timeout Support | ✅ Full support | ✅ Full support | 100% feature parity |
Cross-Platform Code Example:
`typescript
// This exact code works on BOTH iOS and Android
await bleManager.enableBackgroundMode({
notificationTitle: 'Recording Active', // Shown on Android, ignored on iOS
notificationText: 'Syncing sensor data' // Shown on Android, ignored on iOS
});
// ConnectionManager has 100% API parity between platforms
const connectionManager = new ConnectionManager(bleManager);
await connectionManager.connect(deviceId, {
maxRetries: 5,
timeoutMs: 15000
});
`
> ✅ Platform Parity Guarantee: All ConnectionManager features, retry logic, auto-reconnection, and timeout support work identically on iOS and Android. Only background mode setup differs due to platform requirements.
Unified connection management with retry logic, timeout support, and automatic reconnection - all in one manager:
`typescript
import { BleManager, ConnectionManager } from '@sfourdrinier/react-native-ble-plx';
const bleManager = new BleManager();
const connectionManager = new ConnectionManager(bleManager);
// Connect with retry logic and timeout
const device = await connectionManager.connect('AA:BB:CC:DD:EE:FF', {
maxRetries: 5,
initialDelayMs: 1000,
timeoutMs: 15000, // Connection timeout
backoffMultiplier: 2
});
// Enable auto-reconnect for a device
connectionManager.enableAutoReconnect('AA:BB:CC:DD:EE:FF', {
maxRetries: 10,
initialDelayMs: 2000,
timeoutMs: 15000
}, {
onConnect: (device) => console.log('Connected!', device.id),
onDisconnect: (deviceId, error) => console.log('Disconnected', deviceId),
onConnectFailed: (deviceId, error) => console.log('Failed', deviceId, error)
});
// Set global callbacks for all devices
connectionManager.setGlobalCallbacks({
onConnect: (device) => console.log('Any device connected:', device.id),
onDisconnect: (deviceId) => console.log('Any device disconnected:', deviceId),
onConnecting: (deviceId, attempt, max) => {
console.log(Connecting ${deviceId}: attempt ${attempt}/${max});
}
});
// Check status
console.log('Is connecting:', connectionManager.isConnecting('AA:BB:CC:DD:EE:FF'));
console.log('Auto-reconnect enabled:', connectionManager.isAutoReconnectEnabled('AA:BB:CC:DD:EE:FF'));
console.log('Active connections:', connectionManager.activeCount);
// Cancel a connection
connectionManager.cancel('AA:BB:CC:DD:EE:FF');
// Disable auto-reconnect
connectionManager.disableAutoReconnect('AA:BB:CC:DD:EE:FF');
`
Key Features:
- ✅ Single state machine per device (no competing retry engines)
- ✅ Concurrent connections to different devices
- ✅ Configurable connection timeout (prevents hangs)
- ✅ Exponential backoff retry logic
- ✅ Automatic reconnection on unexpected disconnects
- ✅ Comprehensive event callbacks (onConnect, onDisconnect, onConnecting, onConnectFailed)
- ✅ Clean cancellation and lifecycle management
---
If you're using the deprecated ConnectionQueue and ReconnectionManager classes, here's how to migrate to the unified ConnectionManager:
#### Before (Separate Managers - Deprecated)
`typescript
import { BleManager, ConnectionQueue, ReconnectionManager } from '@sfourdrinier/react-native-ble-plx';
const bleManager = new BleManager();
const queue = new ConnectionQueue(bleManager);
const reconnectionManager = new ReconnectionManager(bleManager);
// Connect with retry
const device = await queue.connect(deviceId, {
maxRetries: 5,
initialDelayMs: 1000
});
// Enable auto-reconnect
reconnectionManager.enableAutoReconnect(deviceId, {
maxRetries: 10
}, {
onReconnect: (device) => console.log('Reconnected'),
onReconnectFailed: (id, error) => console.log('Failed')
});
`
#### After (Unified Manager - Recommended)
`typescript
import { BleManager, ConnectionManager } from '@sfourdrinier/react-native-ble-plx';
const bleManager = new BleManager();
const connectionManager = new ConnectionManager(bleManager);
// Connect with retry AND enable auto-reconnect in one step
connectionManager.enableAutoReconnect(deviceId, {
maxRetries: 10,
initialDelayMs: 2000,
timeoutMs: 15000 // NEW: connection timeout support
}, {
onConnect: (device) => console.log('Connected'), // Fires on initial connect AND reconnects
onDisconnect: (deviceId, error) => console.log('Disconnected'),
onConnectFailed: (deviceId, error) => console.log('Failed')
});
// Initial connection (auto-reconnect handles future disconnects)
const device = await connectionManager.connect(deviceId, {
maxRetries: 5,
timeoutMs: 15000
});
`
#### Key Benefits of Migration
| Feature | Old (Queue + Reconnection) | New (ConnectionManager) |
|---------|---------------------------|------------------------|
| State Management | Two competing retry engines | Single state machine per device |
| Connection Timeout | ❌ Not supported | ✅ Configurable timeoutMs |
| Race Conditions | ⚠️ Possible bugs | ✅ Fixed with attemptId pattern |
| Memory Leaks | ⚠️ destroy() leaked subscriptions | ✅ Fixed |
| Connection Storms | ⚠️ Repeated disconnects caused storms | ✅ Fixed with guards |
| Concurrent Connections | ⚠️ Queue blocked all devices | ✅ Per-device isolation |
| Event Callbacks | Split between two managers | Unified callbacks |
| Code Complexity | Manage 2 instances | Single instance |
---
> ⚠️ Deprecated: Use ConnectionManager instead for unified connection management.
Manage connection attempts with automatic retry logic and queue management:
`typescript
import { BleManager, ConnectionQueue } from '@sfourdrinier/react-native-ble-plx';
const manager = new BleManager();
const queue = new ConnectionQueue(manager);
// Connect with automatic retry on failure
const device = await queue.connect('AA:BB:CC:DD:EE:FF', {
maxRetries: 5,
initialDelayMs: 1000,
maxDelayMs: 30000,
backoffMultiplier: 2,
connectionOptions: { timeout: 10000 }
});
// Cancel a pending connection
queue.cancel('AA:BB:CC:DD:EE:FF');
// Cancel all pending connections
queue.cancelAll();
// Check queue status
console.log('Pending connections:', queue.pendingCount);
console.log('Is device pending:', queue.isPending('AA:BB:CC:DD:EE:FF'));
`
> ⚠️ Deprecated: Use ConnectionManager instead for unified connection management.
Automatically reconnect when devices disconnect unexpectedly:
`typescript
import { BleManager, ReconnectionManager } from '@sfourdrinier/react-native-ble-plx';
const manager = new BleManager();
const reconnectionManager = new ReconnectionManager(manager);
// Enable auto-reconnect for a device
reconnectionManager.enableAutoReconnect('AA:BB:CC:DD:EE:FF', {
maxRetries: 10,
initialDelayMs: 1000,
maxDelayMs: 60000,
backoffMultiplier: 1.5
}, {
onReconnect: (device) => {
console.log('Reconnected to', device.id);
},
onReconnectFailed: (deviceId, error) => {
console.log('Failed to reconnect to', deviceId, error);
}
});
// Set global callbacks for all devices
reconnectionManager.setGlobalCallbacks({
onReconnect: (device) => console.log('Any device reconnected:', device.id),
onReconnectFailed: (deviceId) => console.log('Any device failed:', deviceId),
onReconnecting: (deviceId, attempt, max) => {
console.log(Reconnecting ${deviceId}: attempt ${attempt}/${max});
}
});
// Check status
console.log('Is enabled:', reconnectionManager.isEnabled('AA:BB:CC:DD:EE:FF'));
console.log('Is reconnecting:', reconnectionManager.isReconnecting('AA:BB:CC:DD:EE:FF'));
console.log('Retry count:', reconnectionManager.getRetryCount('AA:BB:CC:DD:EE:FF'));
// Disable auto-reconnect
reconnectionManager.disableAutoReconnect('AA:BB:CC:DD:EE:FF');
// Or disable all
reconnectionManager.disableAll();
`
Use ConnectionManager with background mode for reliable, long-running connections:
`typescript
import {
BleManager,
ConnectionManager
} from '@sfourdrinier/react-native-ble-plx';
const bleManager = new BleManager();
const connectionManager = new ConnectionManager(bleManager);
async function startReliableSync(deviceId: string) {
// 1. Enable background mode (Android)
await bleManager.enableBackgroundMode({
notificationTitle: 'Syncing Data',
notificationText: 'Connected to device'
});
// 2. Connect with retry logic and auto-reconnect
connectionManager.enableAutoReconnect(deviceId, {
maxRetries: 10,
initialDelayMs: 2000,
timeoutMs: 15000
}, {
onConnect: async (device) => {
// Start or resume data sync when connected
await startDataSync(device);
},
onDisconnect: (deviceId, error) => {
console.log('Device disconnected, will auto-reconnect:', deviceId);
},
onConnectFailed: (deviceId, error) => {
console.error('Failed to reconnect after all retries:', deviceId, error);
}
});
// 3. Initial connection
const device = await connectionManager.connect(deviceId, {
maxRetries: 5,
initialDelayMs: 1000,
timeoutMs: 15000
});
// Auto-reconnect is now active and will handle disconnects automatically
}
`
To publish a new version of the package:
1. Ensure all tests pass:
`bash`
pnpm test:package
pnpm test:plugin
2. Commit your changes with a conventional commit message:
`bash`
git add .
git commit -m "fix: description of fix"
git push origin master
3. Bump version in package.json (follow semver):`
bash`
# Edit package.json to update version
git add package.json
git commit -m "chore: release X.Y.Z"
git push origin master
4. Create and push git tag:
`bash`
git tag vX.Y.Z -m "Release vX.Y.Z"
git push origin vX.Y.Z
5. Build and publish:
`bash`
pnpm run prepack
pnpm publish --access public --no-git-checks
Commit message conventions:
- fix: - Bug fixes (patch version)feat:
- - New features (minor version)chore:
- - Maintenance tasksdocs:` - Documentation updates
-
- Special thanks to @EvanBacon for supporting the expo config plugin.