React Native Background Tasks

A powerful React Native package for running continuous background services on both Android and iOS with persistent notifications, location-based execution, and WebSocket support.
✨ Features
- 🚀 Cross-Platform: Full support for both Android and iOS
- 🔄 Continuous Execution: Background services that survive app kills and system restarts
- 📱 Sticky Notifications: Persistent notifications that keep services alive
- 🎯 Multiple Services: Support for multiple background services with unique task IDs
- 🔗 Auto-linking: Zero configuration setup for React Native 0.60+
- 📝 TypeScript: Complete TypeScript support with type definitions
- 🛡️ Battery Optimization: Handles battery optimization and doze mode
- 📍 Location Integration: iOS location-based background execution
- ⚡ Easy API: Simple start/stop/status checking methods
📦 Installation
npm install @amrshbib/react-native-background-tasks
yarn add @amrshbib/react-native-background-tasks
Note: This package is currently in version 1.0.0 and ready for use. The package supports both Android and iOS platforms with comprehensive background service capabilities.
React Native 0.60+
This package supports auto-linking. No additional configuration is required.
React Native < 0.60
For older React Native versions, you'll need to manually link the package:
react-native link @amrshbib/react-native-background-tasks
🚀 Quick Start
import Background from "@amrshbib/react-native-background-tasks";
const startService = async () => {
try {
await Background.start(
() => {
console.log("Background task executing...");
},
{
taskId: "my-service",
title: "My App Service",
description: "Keeping your data synchronized",
intervalMs: 5000,
}
);
console.log("Background service started successfully!");
} catch (error) {
console.error("Failed to start service:", error);
}
};
const stopService = async () => {
try {
await Background.stop("my-service");
console.log("Background service stopped!");
} catch (error) {
console.error("Failed to stop service:", error);
}
};
const checkStatus = async () => {
const isRunning = await Background.isRunning("my-service");
console.log("Service running:", isRunning);
};
📖 API Reference
Background.start(taskFunction, options)
Starts a background service with the specified configuration.
Parameters:
taskFunction (Function): The function to execute in the background
options (Object):
taskId (string): Unique identifier for the service
title (string): Notification title
description (string): Notification description
intervalMs (number, optional): Execution interval in milliseconds (default: 5000)
Returns: Promise<string> - Resolves when service starts successfully
Example:
await Background.start(
() => {
fetchDataFromAPI();
},
{
taskId: "data-sync",
title: "Data Sync",
description: "Syncing your data in background",
intervalMs: 10000,
}
);
Background.stop(taskId)
Stops a running background service.
Parameters:
taskId (string): The unique identifier of the service to stop
Returns: Promise<string> - Resolves when service stops successfully
Example:
await Background.stop("data-sync");
Background.isRunning(taskId)
Checks if a background service is currently running.
Parameters:
taskId (string): The unique identifier of the service to check
Returns: Promise<boolean> - True if service is running, false otherwise
Example:
const isRunning = await Background.isRunning("data-sync");
🔧 Platform-Specific Setup
Android Setup
The package automatically handles Android configuration, but you may need to add additional permissions to your android/app/src/main/AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<application>
<service
android:name="com.amrshbib.reactnativebackgroundtasks.BackgroundService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="dataSync" />
</application>
</manifest>
iOS Setup
For iOS, you need to add background modes to your ios/YourApp/Info.plist:
<key>UIBackgroundModes</key>
<array>
<string>background-processing</string>
<string>background-fetch</string>
<string>location</string>
</array>
Optional: For location-based background execution, add location usage description:
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs location access to maintain background services.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs location access to maintain background services.</string>
🎯 Use Cases
- WebSocket Connections: Maintain persistent WebSocket connections
- Data Synchronization: Sync data with servers in background
- Location Tracking: Track user location continuously
- Push Notifications: Handle push notifications and background processing
- File Uploads: Upload files in background
- Health Monitoring: Monitor device health metrics
- Chat Applications: Maintain chat connections
📱 Example Implementation
import React, { useEffect, useState } from "react";
import { View, Text, TouchableOpacity, Alert } from "react-native";
import Background from "@amrshbib/react-native-background-tasks";
const App = () => {
const [isRunning, setIsRunning] = useState(false);
const [logs, setLogs] = useState([]);
const addLog = (message) => {
const timestamp = new Date().toLocaleTimeString();
setLogs((prev) => [`[${timestamp}] ${message}`, ...prev]);
};
const startService = async () => {
try {
await Background.start(
() => {
addLog("Background task executing...");
},
{
taskId: "example-service",
title: "Example Service",
description: "Running example background task",
intervalMs: 3000,
}
);
setIsRunning(true);
addLog("Service started successfully!");
} catch (error) {
Alert.alert("Error", `Failed to start service: ${error.message}`);
}
};
const stopService = async () => {
try {
await Background.stop("example-service");
setIsRunning(false);
addLog("Service stopped!");
} catch (error) {
Alert.alert("Error", `Failed to stop service: ${error.message}`);
}
};
useEffect(() => {
Background.isRunning("example-service").then(setIsRunning);
}, []);
return (
<View style={{ flex: 1, padding: 20 }}>
<Text style={{ fontSize: 24, marginBottom: 20 }}>Background Service Demo</Text>
<TouchableOpacity
onPress={isRunning ? stopService : startService}
style={{
backgroundColor: isRunning ? "#ff4444" : "#44ff44",
padding: 15,
borderRadius: 8,
marginBottom: 20,
}}
>
<Text style={{ color: "white", textAlign: "center", fontSize: 18 }}>{isRunning ? "Stop Service" : "Start Service"}</Text>
</TouchableOpacity>
<Text style={{ fontSize: 18, marginBottom: 10 }}>Logs:</Text>
<View style={{ flex: 1, backgroundColor: "#f0f0f0", padding: 10 }}>
{logs.map((log, index) => (
<Text key={index} style={{ fontFamily: "monospace", fontSize: 12 }}>
{log}
</Text>
))}
</View>
</View>
);
};
export default App;
⚠️ Important Notes
Android
- Services may be killed by the system in extreme battery optimization scenarios
- Users can disable battery optimization for your app in device settings
- Foreground services require a persistent notification
iOS
- Background execution is limited by iOS system policies
- Location-based background execution is more reliable than timer-based
- Background app refresh must be enabled by the user
🔧 Troubleshooting
Service Not Starting
- Check if all required permissions are granted
- Verify the taskId is unique
- Ensure the app has necessary background modes (iOS)
Service Stops Unexpectedly
- Check battery optimization settings
- Verify notification permissions
- Test on different devices and OS versions
Performance Issues
- Optimize your background task function
- Consider increasing the intervalMs value
- Monitor memory usage in background tasks
📋 Requirements
- React Native 0.60+
- Android API 21+ (Android 5.0+)
- iOS 10.0+
- Kotlin support (Android)
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
Made with ❤️ for the React Native community