Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-native-background-actions

Package Overview
Dependencies
Maintainers
1
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-native-background-actions

React Native background service library for running background tasks forever in Android & iOS

  • 4.0.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
6.9K
decreased by-13.18%
Maintainers
1
Weekly downloads
 
Created
Source



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

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.

VersionReact Native versionAndroid (targetSdkVersion) versioniOS 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 backgound, it will not have any effect.

Options

PropertyTypeDescription
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.
parameters<any>Parameters to pass to the task.
taskIconOptions

Android only

PropertyTypeDescription
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

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

Example:

ProgressBar

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'

iOS only Listen for the iOS-only expiration handler that allows you to 'clean up' shortly before the app’s remaining background time reaches 0. Check the iOS documentation for more info.

BackgroundService.on('expiration', () => {
    console.log('I am being closed :(');
});

await BackgroundService.start(veryIntensiveTask, options);

Maintainers

Acknowledgments

License

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

Keywords

FAQs

Package last updated on 17 Jun 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc