UNPKG

@amrshbib/react-native-background-tasks

Version:

React Native background service package for continuous background tasks with sticky notifications

370 lines (281 loc) 11.4 kB
# React Native Background Tasks [![npm version](https://badge.fury.io/js/@amrshbib/react-native-background-tasks.svg)](https://badge.fury.io/js/@amrshbib/react-native-background-tasks) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![React Native](https://img.shields.io/badge/React%20Native-0.60%2B-blue.svg)](https://reactnative.dev/) 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 ```bash npm install @amrshbib/react-native-background-tasks # or 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: ```bash react-native link @amrshbib/react-native-background-tasks ``` ## 🚀 Quick Start ```javascript import Background from "@amrshbib/react-native-background-tasks"; // Start a background service const startService = async () => { try { await Background.start( () => { console.log("Background task executing..."); // Your background logic here // e.g., WebSocket connection, data sync, location tracking }, { taskId: "my-service", title: "My App Service", description: "Keeping your data synchronized", intervalMs: 5000, // Execute every 5 seconds } ); console.log("Background service started successfully!"); } catch (error) { console.error("Failed to start service:", error); } }; // Stop the service const stopService = async () => { try { await Background.stop("my-service"); console.log("Background service stopped!"); } catch (error) { console.error("Failed to stop service:", error); } }; // Check if service is running 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:** ```javascript await Background.start( () => { // Your background task 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:** ```javascript 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:** ```javascript 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`: ```xml <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Required permissions --> <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 declaration --> <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`: ```xml <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: ```xml <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 ```javascript 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..."); // Your background logic here }, { 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(() => { // Check service status on app start 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 1. Check if all required permissions are granted 2. Verify the taskId is unique 3. Ensure the app has necessary background modes (iOS) ### Service Stops Unexpectedly 1. Check battery optimization settings 2. Verify notification permissions 3. Test on different devices and OS versions ### Performance Issues 1. Optimize your background task function 2. Consider increasing the intervalMs value 3. 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 The MIT License Copyright (c) 2024 Amr Shbib <amr.shbib@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## 🔗 Links - [npm Package](https://www.npmjs.com/package/@amrshbib/react-native-background-tasks) --- Made with ❤️ for the React Native community