Skip to content
Projects

Rapsssito/react-native-background-actions

View on GitHub

About

React Native background service library for running background tasks forever on Android and iOS.

Web & App Development

How these counts are measured

Measured star growth

in 24h
0
in 7 days
-1
in 15 days
-1
in 1 month
Collecting history

Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.

README.md

Original



React Native background service library for running background tasks forever in Android & iOS. Schedule a background job that will run your JavaScript when your app is in the background or foreground.

WARNING

  • Android: This library relies on React Native's HeadlessJS for Android. Before building your JS task, make sure to read all the documentation. The jobs will run even if the app has been closed. In Android 12+ you will not be able to launch background tasks from the background. A notification will be shown when the task is running, it is not possible to start the service without it. The notification will only be visible in Android.

  • iOS: This library relies on iOS's UIApplication beginBackgroundTaskWithName method, which won't keep your app in the background forever by itself. However, you can rely on other libraries like react-native-track-player that use audio, geolocalization, etc. to keep your app alive in the background while you excute the JS from this library.

Table of Contents

React Native / Android / iOS compatibility

To use this module you need to ensure you are using the correct version of React Native. If you are using an Android (targetSdkVersion) version lower than 31 (introduced in React Native 0.68.0) you will need to upgrade before attempting to use react-native-background-actions's latest version.

Version React Native version Android (targetSdkVersion) version iOS version
4.X.X >= Unknown >= 34 >= Unknown
3.X.X >= Unknown >= 31 >= Unknown
2.6.7 >= Unknown >= Unknown >= Unknown

Install

Go to INSTALL.md to see the how to install, compatibility with RN and Linking process.

Usage

Example Code

import BackgroundService from 'react-native-background-actions';

const sleep = (time) => new Promise((resolve) => setTimeout(() => resolve(), time));

// You can do anything in your task such as network requests, timers and so on,
// as long as it doesn't touch UI. Once your task completes (i.e. the promise is resolved),
// React Native will go into "paused" mode (unless there are other tasks running,
// or there is a foreground app).
const veryIntensiveTask = async (taskDataArguments) => {
    // Example of an infinite loop task
    const { delay } = taskDataArguments;
    await new Promise( async (resolve) => {
        for (let i = 0; BackgroundService.isRunning(); i++) {
            console.log(i);
            await sleep(delay);
        }
    });
};

const options = {
    taskName: 'Example',
    taskTitle: 'ExampleTask title',
    taskDesc: 'ExampleTask description',
    taskIcon: {
        name: 'ic_launcher',
        type: 'mipmap',
    },
    color: '#ff00ff',
    linkingURI: 'yourSchemeHere://chat/jane', // See Deep Linking for more info
    parameters: {
        delay: 1000,
    },
};


await BackgroundService.start(veryIntensiveTask, options);
await BackgroundService.updateNotification({taskDesc: 'New ExampleTask description'}); // Only Android, iOS will ignore this call
// iOS will also run everything here in the background until .stop() is called
await BackgroundService.stop();

If you call stop() on background no new tasks will be able to be started! Don't call .start() twice, as it will stop performing previous background tasks and start a new one. If .start() is called on the background, it will not have any effect on iOS. On Android 12+ it rejects with E_START_NOT_ALLOWED.

On Android, the promise returned by start() resolves once the service is actually running in the foreground, and rejects if it cannot get there. isRunning() then stays false. The rejection code is one of:

  • E_START_NOT_ALLOWED: Android refused to start a foreground service from the background (Android 12+).
  • E_PERMISSION: a runtime permission required by the foregroundServiceType is missing or was revoked (Android 14+).
  • E_START_FAILED: the service could not be started (the native error message is kept).
  • E_SUPERSEDED: start() was called again before this one was running.
  • E_STOPPED: stop() was called before this one was running.
try {
    await BackgroundService.start(veryIntensiveTask, options);
} catch (e) {
    console.warn('Background task not started:', e.code, e.message);
}

Options

Property Type Description
taskName <string> Task name for identification.
taskTitle <string> Android Required. Notification title.
taskDesc <string> Android Required. Notification description.
taskIcon <taskIconOptions> Android Required. Notification icon.
color <string> Notification color. Default: "#ffffff".
linkingURI <string> Link that will be called when the notification is clicked. Example: "yourSchemeHere://chat/jane". See Deep Linking for more info. Default: undefined.
progressBar <taskProgressBarOptions> Notification progress bar.
foregroundServiceType Array<foregroundServiceType> Android only. Array of foreground service types to combine. Must match android:foregroundServiceType in AndroidManifest.xml.
parameters <any> Parameters to pass to the task.

taskIconOptions

Android only

Property Type Description
name <string> Required. Icon name in res/ folder. Ex: ic_launcher.
type <string> Required. Icon type in res/ folder. Ex: mipmap.
package <string> Icon package where to search the icon. Ex: com.example.package. It defaults to the app's package. It is highly recommended to leave like that.

Example:

photo5837026843969041365

taskProgressBarOptions

Android only

Property Type Description
max <number> Required. Maximum value.
value <number> Required. Current value.
indeterminate <boolean> Display the progress status as indeterminate.

Example:

ProgressBar

foregroundServiceType

Android only (API 29+ / Android 10+)

Specifies the foreground service type(s) as an array of strings. Flags are OR-ed together, so multiple types can be combined. All values must match the android:foregroundServiceType declared in your AndroidManifest.xml. See INSTALL.md for the required manifest and permission setup.

Value Android API <uses-permission> required
"dataSync" 29 (Q) android.permission.FOREGROUND_SERVICE_DATA_SYNC
"mediaPlayback" 29 (Q) android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK
"phoneCall" 29 (Q) android.permission.FOREGROUND_SERVICE_PHONE_CALL
"location" 29 (Q) android.permission.FOREGROUND_SERVICE_LOCATION
"connectedDevice" 29 (Q) android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE
"mediaProjection" 29 (Q) android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION
"camera" 30 (R) android.permission.FOREGROUND_SERVICE_CAMERA
"microphone" 30 (R) android.permission.FOREGROUND_SERVICE_MICROPHONE
"health" 34 (U) android.permission.FOREGROUND_SERVICE_HEALTH
"remoteMessaging" 34 (U) android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING
"systemExempted" 34 (U) android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED
"shortService" 34 (U) android.permission.FOREGROUND_SERVICE_SHORT_SERVICE
"specialUse" 34 (U) android.permission.FOREGROUND_SERVICE_SPECIAL_USE

On Android versions below API 29 this option is ignored. If a requested value is not supported by the running Android version, it is silently ignored.

Examples:

foregroundServiceType: ['location'],
foregroundServiceType: ['location', 'microphone'],

Deep Linking

Android only

To handle incoming links when the notification is clicked by the user, first you need to modify your android/app/src/main/AndroidManifest.xml and add an <intent-filter> (fill yourSchemeHere with the name you prefer):

  <manifest ... >
      ...
      <application ... >
          <activity
              ...
              android:launchMode="singleTask"> // Add this if not present
                  ...
                  <intent-filter android:label="filter_react_native">
                      <action android:name="android.intent.action.VIEW" />
                      <category android:name="android.intent.category.DEFAULT" />
                      <category android:name="android.intent.category.BROWSABLE" />
                      <data android:scheme="yourSchemeHere" />
                  </intent-filter>
      </application>
    </manifest>

You must provide a linkingURI in the BackgroundService's options that matches the scheme you just added to android/app/src/main/AndroidManifest.xml:

const options = {
    taskName: 'Example',
    taskTitle: 'ExampleTask title',
    taskDesc: 'ExampleTask description',
    taskIcon: {
        name: 'ic_launcher',
        type: 'mipmap',
    },
    color: '#ff00ff',
    linkingURI: 'yourSchemeHere://chat/jane', // Add this
    parameters: {
        delay: 1000,
    },
};


await BackgroundService.start(veryIntensiveTask, options);

React Native provides a Linking class to get notified of incoming links. Your JavaScript code must then listen to the url using React Native Linking class:

import { Linking } from 'react-native';

Linking.addEventListener('url', handleOpenURL);

function handleOpenURL(evt) {
    // Will be called when the notification is pressed
    console.log(evt.url);
    // do something
}

Events

'expiration'

Listen for the OS forcibly stopping the background task, so you can 'clean up' or react to it. By the time this event fires, isRunning() already returns false, even though stop() was never called from JS.

The library cannot interrupt your task function: it keeps running until it returns. If it loops, check BackgroundService.isRunning() (or listen to this event) and exit, especially before starting a new task from this handler.

  • iOS: fired shortly before the app's remaining background time reaches 0. Check the iOS documentation for more info.
  • Android: fired when the OS kills the foreground service because it exceeded its type-specific time limit (Service.onTimeout, API 34+). On older Android versions there is no such time limit, so this event is never fired.
BackgroundService.on('expiration', () => {
    console.log('I am being closed :(');
});

await BackgroundService.start(veryIntensiveTask, options);

'stopped'

Android only. Listen for the native service stopping on its own, outside of an OS timeout (see 'expiration'), when no start() call is waiting for it, e.g. the service was restarted by the system and could not go back to the foreground. By the time this event fires, isRunning() already returns false. It is never fired by your own stop() call. As with 'expiration', your task function is not interrupted.

The listener receives { reason }, where reason is one of:

  • 'start_not_allowed': Android refused to start a foreground service from the background (Android 12+).
  • 'permission': a runtime permission required by the foregroundServiceType is missing or was revoked (Android 14+).
  • 'no_task_options': the service was started without its task options.
BackgroundService.on('stopped', ({ reason }) => {
    console.log('Background task stopped by the system:', reason);
});

Maintainers

Acknowledgments

License

The library is released under the MIT license. For more information see LICENSE.

Explore related projects

Loading…