> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/ivangonzalezg/react-native-background-guardian/llms.txt
> Use this file to discover all available pages before exploring further.

# Quickstart

> Get started with React Native Background Guardian in minutes with this step-by-step guide.

## 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.

<Steps>
  <Step title="Install the library">
    Add React Native Background Guardian to your project:

    <CodeGroup>
      ```bash npm theme={null}
      npm install react-native-background-guardian
      ```

      ```bash yarn theme={null}
      yarn add react-native-background-guardian
      ```

      ```bash pnpm theme={null}
      pnpm add react-native-background-guardian
      ```
    </CodeGroup>

    For iOS projects, install pods:

    ```bash theme={null}
    cd ios && pod install
    ```
  </Step>

  <Step title="Import and use wake locks">
    Import the library and use wake locks to keep the CPU running during background tasks:

    ```typescript theme={null}
    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();
    }
    ```

    <Tip>
      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.
    </Tip>
  </Step>

  <Step title="Check battery optimization status">
    Check if your app is exempt from battery optimizations and request exemption if needed:

    ```typescript theme={null}
    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' }
          ]
        );
      }
    }
    ```

    <Warning>
      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.).
    </Warning>
  </Step>

  <Step title="Handle OEM-specific settings">
    Many Android manufacturers have additional battery optimization settings. Guide users to these settings for devices with aggressive battery management:

    ```typescript theme={null}
    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' }
          ]
        );
      }
    }
    ```

    <Note>
      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.
    </Note>
  </Step>

  <Step title="Monitor power save mode">
    Check if Battery Saver mode is active, as it affects all apps regardless of exemption status:

    ```typescript theme={null}
    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' }
          ]
        );
      }
    }
    ```

    <Tip>
      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.
    </Tip>
  </Step>
</Steps>

## Complete example

Here's a complete example using a React hook to manage background guardian functionality:

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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

<CardGroup cols={2}>
  <Card title="API Reference" icon="code" href="/api/overview">
    Explore all available methods and their parameters
  </Card>

  <Card title="Android Doze Mode" icon="moon" href="/concepts/doze-and-app-standby">
    Learn how to survive Android's battery optimization features
  </Card>
</CardGroup>
