react-native-background-guardian
v1.0.0
Published
A cross-platform React Native library that prevents Android from killing background processes through Wake Locks, battery optimization exemptions, and OEM-specific protections. iOS-safe with no-op implementation.
Maintainers
Readme
react-native-background-guardian
A cross-platform React Native library that prevents Android from killing background processes through Wake Locks, battery optimization exemptions, and OEM-specific protections. iOS-safe with no-op implementation.
Features
- Wake Lock Management - Keep CPU running during background tasks
- Battery Optimization Exemption - Request Doze mode whitelist
- OEM-Specific Settings - Navigate to manufacturer battery settings (Xiaomi, Samsung, Huawei, etc.)
- Cross-Platform - Safe no-op implementation for iOS
- TypeScript Support - Full type definitions included
- New Architecture Ready - Built as a Turbo Module
Installation
npm install react-native-background-guardian
# or
yarn add react-native-background-guardianiOS
cd ios && pod installAndroid
No additional setup required. Permissions are automatically merged via the Android manifest.
API Reference
acquireWakeLock(tag?: string): Promise<boolean>
Acquires a partial wake lock to keep the CPU running while the screen is off.
import BackgroundGuardian from 'react-native-background-guardian';
// Acquire wake lock before starting background work
const acquired = await BackgroundGuardian.acquireWakeLock('MyBackgroundTask');
if (acquired) {
// Perform background work
await doBackgroundWork();
// Release when done
await BackgroundGuardian.releaseWakeLock();
}| Platform | Behavior |
|----------|----------|
| Android | Acquires PARTIAL_WAKE_LOCK via PowerManager |
| iOS | No-op, returns true |
releaseWakeLock(): Promise<boolean>
Releases a previously acquired wake lock.
const released = await BackgroundGuardian.releaseWakeLock();
console.log('Wake lock released:', released);| Platform | Behavior |
|----------|----------|
| Android | Releases the wake lock if held |
| iOS | No-op, returns true |
isIgnoringBatteryOptimizations(): Promise<boolean>
Checks if the app is exempt from battery optimizations (Doze mode whitelist).
const isIgnoring = await BackgroundGuardian.isIgnoringBatteryOptimizations();
if (!isIgnoring) {
// Prompt user to exempt the app
await BackgroundGuardian.requestBatteryOptimizationExemption();
}| Platform | Behavior |
|----------|----------|
| Android | Checks via PowerManager.isIgnoringBatteryOptimizations() |
| iOS | No-op, returns true |
requestBatteryOptimizationExemption(): Promise<boolean>
Opens the system dialog to request battery optimization exemption.
const dialogShown = await BackgroundGuardian.requestBatteryOptimizationExemption();
if (dialogShown) {
console.log('User was prompted for battery optimization exemption');
}| Platform | Behavior |
|----------|----------|
| Android | Shows ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS dialog |
| iOS | No-op, returns true |
Note: Google Play has restrictions on using
REQUEST_IGNORE_BATTERY_OPTIMIZATIONS. Only use if your app genuinely requires background execution (messaging, health tracking, device management, etc.).
openOEMSettings(): Promise<boolean>
Opens OEM-specific battery or background settings if available.
const manufacturer = await BackgroundGuardian.getDeviceManufacturer();
console.log(`Device: ${manufacturer}`);
const opened = await BackgroundGuardian.openOEMSettings();
if (opened) {
console.log('OEM battery settings opened');
} else {
console.log('No OEM-specific settings available');
}| Platform | Behavior |
|----------|----------|
| Android | Opens OEM settings or falls back to battery optimization settings |
| iOS | No-op, returns false |
getDeviceManufacturer(): Promise<string | null>
Gets the device manufacturer name.
const manufacturer = await BackgroundGuardian.getDeviceManufacturer();
if (manufacturer?.toLowerCase() === 'xiaomi') {
// Show MIUI-specific instructions
showMIUIInstructions();
}| Platform | Behavior |
|----------|----------|
| Android | Returns Build.MANUFACTURER (lowercase) |
| iOS | Returns "Apple" |
OEM Compatibility
Many Android manufacturers implement aggressive battery optimization that can kill apps even when standard Android battery optimizations are disabled. openOEMSettings() supports the following manufacturers:
| Manufacturer | Brand/OS | Supported | |--------------|----------|-----------| | Xiaomi | MIUI | ✅ | | Huawei | EMUI | ✅ | | Honor | Magic UI | ✅ | | Samsung | OneUI | ✅ | | Oppo | ColorOS | ✅ | | Vivo | FuntouchOS | ✅ | | OnePlus | OxygenOS | ✅ | | Realme | Realme UI | ✅ | | Asus | ZenUI | ✅ | | Lenovo | - | ✅ | | Meizu | Flyme | ✅ | | Nokia | - | ✅ | | Other | Stock Android | ⚡ Fallback |
Fallback behavior: For unsupported manufacturers, the library falls back to:
ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS(battery optimization list)ACTION_APPLICATION_DETAILS_SETTINGS(app details page)
Usage Examples
Background Audio Player
import BackgroundGuardian from 'react-native-background-guardian';
async function startAudioPlayback() {
// Acquire wake lock to prevent CPU sleep
await BackgroundGuardian.acquireWakeLock('AudioPlayer');
// Start audio playback
await audioPlayer.play();
}
async function stopAudioPlayback() {
// Stop audio playback
await audioPlayer.stop();
// Release wake lock
await BackgroundGuardian.releaseWakeLock();
}Background Location Tracking
import BackgroundGuardian from 'react-native-background-guardian';
import { AppState } from 'react-native';
async function setupBackgroundTracking() {
// Check battery optimization status
const isIgnoring = await BackgroundGuardian.isIgnoringBatteryOptimizations();
if (!isIgnoring) {
// Request exemption for reliable background execution
await BackgroundGuardian.requestBatteryOptimizationExemption();
}
// For aggressive OEMs, guide user to additional settings
const manufacturer = await BackgroundGuardian.getDeviceManufacturer();
if (['xiaomi', 'huawei', 'oppo', 'vivo'].includes(manufacturer ?? '')) {
// Show instructions and open OEM settings
Alert.alert(
'Additional Setup Required',
'Please enable "Autostart" and disable battery optimization for this app.',
[{ text: 'Open Settings', onPress: () => BackgroundGuardian.openOEMSettings() }]
);
}
}Complete Integration Example
import { useEffect, useState, useCallback } from 'react';
import { AppState } from 'react-native';
import BackgroundGuardian from 'react-native-background-guardian';
export function useBackgroundGuardian() {
const [isReady, setIsReady] = useState(false);
const [manufacturer, setManufacturer] = useState<string | null>(null);
const [isIgnoringBatteryOpt, setIsIgnoringBatteryOpt] = useState(false);
const refreshStatus = useCallback(async () => {
const ignoring = await BackgroundGuardian.isIgnoringBatteryOptimizations();
setIsIgnoringBatteryOpt(ignoring);
}, []);
useEffect(() => {
async function init() {
const mfr = await BackgroundGuardian.getDeviceManufacturer();
setManufacturer(mfr);
await refreshStatus();
setIsReady(true);
}
init();
}, [refreshStatus]);
// Refresh status when app comes to foreground
useEffect(() => {
const subscription = AppState.addEventListener('change', (state) => {
if (state === 'active') {
refreshStatus();
}
});
return () => subscription.remove();
}, [refreshStatus]);
const requestExemption = useCallback(async () => {
await BackgroundGuardian.requestBatteryOptimizationExemption();
await refreshStatus();
}, [refreshStatus]);
return {
isReady,
manufacturer,
isIgnoringBatteryOpt,
requestExemption,
openOEMSettings: BackgroundGuardian.openOEMSettings,
acquireWakeLock: BackgroundGuardian.acquireWakeLock,
releaseWakeLock: BackgroundGuardian.releaseWakeLock,
};
}Android Permissions
The library automatically adds the following permissions to your Android manifest:
<!-- Required for Wake Lock functionality -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Required for requesting battery optimization exemption -->
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />Troubleshooting
Wake lock not working
- Ensure you're testing on a real device (emulators may behave differently)
- Verify the wake lock is acquired using ADB:
adb shell dumpsys power | grep "BackgroundGuardian" - Make sure you're calling
releaseWakeLock()when done
Battery optimization status not updating
After the user accepts or rejects the battery optimization dialog, they are taken to the system settings. Use AppState to refresh the status when the app returns to the foreground:
useEffect(() => {
const subscription = AppState.addEventListener('change', (state) => {
if (state === 'active') {
refreshBatteryStatus();
}
});
return () => subscription.remove();
}, []);OEM settings not opening
Some OEM activities may not exist on all device variants or OS versions. The library tries multiple activities per manufacturer and falls back gracefully. If no OEM settings are found, it opens the standard battery optimization settings.
Google Play policy considerations
The REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission is restricted by Google Play. Only use it if your app falls into one of these categories:
- VoIP apps
- Messaging apps
- Health/fitness tracking
- IoT/device management
- Task automation apps
- Other apps that genuinely require background execution
Limitations
- iOS: All methods are no-ops that return safe default values. iOS handles background execution differently through Background Modes.
- Android < 6.0 (API 23): Battery optimization APIs are not available. Methods return appropriate defaults.
- OEM Settings: May not work on all device variants as manufacturers frequently change their system app packages.
Contributing
See the contributing guide to learn how to contribute to the repository and the development workflow.
License
MIT
Made with create-react-native-library
