Skip to main content

Quick start guide

This guide will walk you through the basic setup and usage of React Native Background Guardian to ensure your app can run reliably in the background on Android devices.
1

Install the library

Add React Native Background Guardian to your project:
npm install react-native-background-guardian
For iOS projects, install pods:
cd ios && pod install
2

Import and use wake locks

Import the library and use wake locks to keep the CPU running during background tasks:
import BackgroundGuardian from 'react-native-background-guardian';

// Acquire wake lock before starting background work
const acquired = await BackgroundGuardian.acquireWakeLock(
  'MyBackgroundTask',
  10 * 60 * 1000 // 10 minutes timeout
);

if (acquired) {
  // Perform background work
  await doBackgroundWork();
  
  // Release wake lock when done
  await BackgroundGuardian.releaseWakeLock();
}
The wake lock timeout defaults to 24 hours (86,400,000 ms). Always release the wake lock when your work is complete to preserve battery life.
3

Check battery optimization status

Check if your app is exempt from battery optimizations and request exemption if needed:
import BackgroundGuardian from 'react-native-background-guardian';
import { Alert } from 'react-native';

async function checkBatteryOptimization() {
  const isIgnoring = await BackgroundGuardian.isIgnoringBatteryOptimizations();
  
  if (!isIgnoring) {
    Alert.alert(
      'Battery Optimization',
      'For reliable background operation, please allow this app to run in the background.',
      [
        {
          text: 'Allow',
          onPress: async () => {
            await BackgroundGuardian.requestBatteryOptimizationExemption();
          }
        },
        { text: 'Cancel', style: 'cancel' }
      ]
    );
  }
}
Google Play restricts the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission. Only use it if your app genuinely requires background execution (messaging, health tracking, device management, etc.).
4

Handle OEM-specific settings

Many Android manufacturers have additional battery optimization settings. Guide users to these settings for devices with aggressive battery management:
import BackgroundGuardian from 'react-native-background-guardian';
import { Alert } from 'react-native';

async function setupOEMSettings() {
  const manufacturer = await BackgroundGuardian.getDeviceManufacturer();
  
  // Check if device has aggressive battery management
  if (['xiaomi', 'huawei', 'oppo', 'vivo', 'samsung'].includes(
    manufacturer?.toLowerCase() ?? ''
  )) {
    Alert.alert(
      'Additional Setup Required',
      `Your ${manufacturer} device requires additional settings to ensure reliable background operation. Please enable "Autostart" and disable battery optimization.`,
      [
        {
          text: 'Open Settings',
          onPress: async () => {
            const opened = await BackgroundGuardian.openOEMSettings();
            if (!opened) {
              console.log('Could not open OEM settings');
            }
          }
        },
        { text: 'Later', style: 'cancel' }
      ]
    );
  }
}
The library supports OEM settings for Xiaomi, Samsung, Huawei, Honor, OnePlus, Oppo, Vivo, Realme, Asus, and more. For unsupported manufacturers, it falls back to standard battery optimization settings.
5

Monitor power save mode

Check if Battery Saver mode is active, as it affects all apps regardless of exemption status:
import BackgroundGuardian from 'react-native-background-guardian';
import { Alert } from 'react-native';

async function checkPowerSaveMode() {
  const isPowerSave = await BackgroundGuardian.isPowerSaveMode();
  
  if (isPowerSave) {
    Alert.alert(
      'Battery Saver Active',
      'Background features may be limited while Battery Saver is enabled.',
      [
        {
          text: 'Open Settings',
          onPress: () => BackgroundGuardian.openPowerSaveModeSettings()
        },
        { text: 'OK', style: 'cancel' }
      ]
    );
  }
}
Power Save mode is different from battery optimization exemptions. An app can be exempt from Doze mode but still be affected by Power Save mode restrictions.

Complete example

Here’s a complete example using a React hook to manage background guardian functionality:
import { useCallback, useEffect, useState } 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,
  };
}

Common use cases

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();
}

Foreground kiosk mode

import BackgroundGuardian from 'react-native-background-guardian';

async function enterKioskMode() {
  // Keep the screen on while the app is in the foreground
  await BackgroundGuardian.enableScreenWakeLock();
}

async function exitKioskMode() {
  await BackgroundGuardian.disableScreenWakeLock();
}

Next steps

API Reference

Explore all available methods and their parameters

Android Doze Mode

Learn how to survive Android’s battery optimization features