UNPKG

@amrshbib/react-native-background-tasks

Version:

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

83 lines (65 loc) 2.61 kB
import { NativeEventEmitter, NativeModules, Platform } from "react-native"; const { BackgroundModule } = NativeModules; class BackgroundService { static eventEmitter = null; static taskFunctions = new Map(); static start(taskFunction, options = {}) { if (Platform.OS !== "android" && Platform.OS !== "ios") { console.warn("Background service is only supported on Android and iOS"); return Promise.resolve("Background service is only supported on Android and iOS"); } const { taskId, title, description, intervalMs = 5000 } = options; if (!taskId) { throw new Error("taskId is required"); } if (!title) { throw new Error("title is required"); } if (!description) { throw new Error("description is required"); } // Store the task function this.taskFunctions.set(taskId, taskFunction); // Set up event listener if not already done if (!this.eventEmitter) { this.eventEmitter = new NativeEventEmitter(BackgroundModule); this.eventEmitter.addListener("BackgroundTaskExecuted", (data) => { console.log("Received BackgroundTaskExecuted event:", data); const { taskId: eventTaskId } = data; const taskFn = this.taskFunctions.get(eventTaskId); console.log("Task function found for", eventTaskId, ":", !!taskFn); if (taskFn) { try { console.log("Executing background task function for", eventTaskId); taskFn(); } catch (error) { console.error(`Error executing background task ${eventTaskId}:`, error); } } else { console.warn(`No task function found for taskId: ${eventTaskId}`); } }); } console.log("Starting background service with intervalMs:", intervalMs); return BackgroundModule.startBackgroundService(taskId, title, description, intervalMs); } static stop(taskId) { if (Platform.OS !== "android" && Platform.OS !== "ios") { console.warn("Background service is only supported on Android and iOS"); return Promise.resolve("Background service is only supported on Android and iOS"); } if (!taskId) { throw new Error("taskId is required"); } // Clean up the task function this.taskFunctions.delete(taskId); return BackgroundModule.stopBackgroundService(taskId); } static isRunning(taskId) { if (Platform.OS !== "android" && Platform.OS !== "ios") { return Promise.resolve(false); } return BackgroundModule.isBackgroundServiceRunning(taskId); } } export default BackgroundService;