npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@amrshbib/react-native-background-tasks

v1.0.1

Published

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

Readme

React Native Background Tasks

npm version License: MIT React Native

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

react-native link @amrshbib/react-native-background-tasks

🚀 Quick Start

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:

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:

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">
    <!-- 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:

<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...");
          // 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 [email protected]

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


Made with ❤️ for the React Native community