react-native-background-task
Advanced tools
Comparing version 0.1.2 to 0.2.0
{ | ||
"name": "react-native-background-task", | ||
"version": "0.1.2", | ||
"version": "0.2.0", | ||
"author": "James Isaac <james.isaac@gmail.com>", | ||
@@ -19,2 +19,3 @@ "description": "Periodic background tasks for React Native apps, cross-platform (iOS and Android), which run even when the app is closed.", | ||
"license": "MIT", | ||
"main": "js/index", | ||
"repository": { | ||
@@ -25,12 +26,13 @@ "type": "git", | ||
"scripts": { | ||
"flow": "flow || exit 0" | ||
"flow": "flow || exit 0", | ||
"prettier": "prettier --no-semi --single-quote --trailing-comma es5 --write \"js/**/*.js\"" | ||
}, | ||
"devDependencies": { | ||
"flow-bin": "^0.39.0" | ||
"flow-bin": "^0.50.0", | ||
"prettier": "^1.5.3" | ||
}, | ||
"peerDependencies": { | ||
"react-native": "*", | ||
"react-native-background-fetch": "*", | ||
"react-native-background-job": ">=1.1.0 <1.1.3" | ||
"react-native": ">=0.36.0", | ||
"react-native-background-fetch": "2.0.x" | ||
} | ||
} |
182
README.md
# react-native-background-task | ||
**WORK IN PROGRESS / NOT YET READY FOR PRODUCTION USE** | ||
[![npm version](https://img.shields.io/npm/v/react-native-background-task.svg)](https://www.npmjs.com/package/react-native-background-task) | ||
[![license](https://img.shields.io/github/license/jamesisaac/react-native-background-task.svg)](https://opensource.org/licenses/MIT) | ||
[![npm downloads](https://img.shields.io/npm/dm/react-native-background-task.svg)](https://www.npmjs.com/package/react-native-background-task) | ||
Periodic background tasks for React Native apps, cross-platform (iOS and Android), which run even when the app is closed. | ||
Periodic background tasks for React Native apps, cross-platform (iOS and | ||
Android), which run even when the app is closed. | ||
This builds on top of the native modules provided by the following two libraries: | ||
This library allows the scheduling of a single periodic task, which executes | ||
when the app is in the background or closed, no more frequently than every 15 | ||
minutes. Network, AsyncStorage etc can be used (anything except UI), so | ||
perfect for things like a background data sync for offline support. | ||
- **iOS**: [react-native-background-fetch](https://github.com/transistorsoft/react-native-background-fetch), which uses the iOS-specific `Background Fetch` technique. | ||
- **Android**: [react-native-background-job](https://github.com/vikeri/react-native-background-job), which provides a job scheduler on RN's built-in [Headless JS](https://facebook.github.io/react-native/docs/headless-js-android.html) (Android only). | ||
Behind the scenes, this library takes a different approach with each platform: | ||
To achieve a unified API, this package exposes the lowest common denominator (e.g. only support for a single task, even though Android can support multiple). | ||
- **Android**: A native implementation, which provides scheduling on top of | ||
RN's built-in [Headless JS](https://facebook.github.io/react-native/docs/headless-js-android.html) | ||
(Android only). | ||
- Min API level: 16 (Android 4.1). | ||
- **iOS**: [react-native-background-fetch](https://github.com/transistorsoft/react-native-background-fetch), | ||
which uses the iOS-specific `Background Fetch` technique. | ||
For more per-platform flexibility, those libraries should be used individually. | ||
To achieve a unified API, this library exposes the lowest common denominator | ||
(e.g. only support for a single task, even though Android can support multiple). | ||
For more per-platform flexibility, there are other platform-specific libraries | ||
with more granular customisation. | ||
## Installation | ||
```bash | ||
$ npm install --save react-native-background-task | ||
$ npm install react-native-background-task --save | ||
``` | ||
### Android | ||
* **iOS**: Follow native iOS module installation instructions from | ||
[react-native-background-fetch](https://github.com/transistorsoft/react-native-background-fetch) | ||
* **Android**: Follow native Android module installation instructions from | ||
[react-native-background-job](https://github.com/vikeri/react-native-background-job) | ||
* Recommended version: v1.1.0 (API has changed as of v1.1.3) | ||
1. The linking of the library can be done automatically by running: | ||
```bash | ||
$ react-native link react-native-background-task | ||
``` | ||
2. One manual step is still needed - in your project file | ||
`android/app/src/main/java/myapp/MainApplication.java`, add the following to | ||
the end of the `onCreate()` method: | ||
```java | ||
BackgroundTaskPackage.useContext(this); | ||
``` | ||
### iOS | ||
For iOS support, this library relies on version 2.0.x of | ||
[react-native-background-fetch](https://github.com/transistorsoft/react-native-background-fetch) | ||
which can be installed as follows: | ||
```bash | ||
$ npm install react-native-background-fetch@2.0.x --save | ||
$ react-native link react-native-background-fetch | ||
``` | ||
This library will behave correctly on iOS as long as `react-native-background-fetch` | ||
is installed alongside it, and has been linked with your project. | ||
## API | ||
### `register(task, options)` | ||
### `define(task)` | ||
Define the task that this module should be executing. | ||
Define the JS code that this module should be executing. | ||
- Will overwrite any previously registered task. | ||
- Should be called at the root of your main app entrypoint file. | ||
- Should `console.error` if it can't register the task | ||
- Should be called at the top level of your JS, **not** inside a component. | ||
This is because in headless mode no components are mounted, but the code | ||
still needs to be accessible. | ||
- Will overwrite any previously defined task. | ||
Parameters: | ||
* **`task`**: **required** `() => void` - Function to be executed in the background | ||
* **`options`**: `?object` - Any configuration you want to be set with | ||
- **`task`**: **required** `() => void` - Function to be executed in the background | ||
### `schedule(options)` | ||
Specify the scheduling options for the task, and register it with the | ||
platform's scheduler. | ||
- Should be called from inside a component (e.g. your App's | ||
`componentDidMount`). This is to avoid double-scheduling when the task | ||
launches in headless mode. | ||
- Will `console.warn` if the device is task was unable to be scheduled. | ||
Parameters: | ||
- **`options?`**: `Object` - Any configuration you want to be set with | ||
the task. Note that most of these will only work on one platform. | ||
* **`period`** `number` - (Android only) Desired number of seconds between each | ||
- **`period?`** `number` - (Android only) Desired number of seconds between each | ||
execution of the task. Even on Android, the OS will only take this as a | ||
recommendation, and will likely enforce a minimum of 15 minutes (similar to | ||
iOS). Default is 900 (15 minutes) | ||
* **`timeout`** `number` - (Android only) Number of seconds the task will have | ||
recommendation, and will enforce a minimum of 15 minutes (similar to iOS). | ||
Default is 900 (15 minutes) | ||
- **`timeout?`** `number` - (Android only) Number of seconds the task will have | ||
to execute. iOS has a hardcoded limit of 30 seconds. Default 30 seconds. | ||
### `finish()` | ||
**Must be called at the end of your task** to indicate to the OS that it's | ||
finished. (Only required on iOS, no-op on Android). | ||
### `cancel()` | ||
Cancels any currently registered task. | ||
Cancels any currently scheduled task. | ||
### `finish()` | ||
### `statusAsync()` | ||
Must be called at the end of your task to indicate to the OS that it's | ||
finished. (Only required on iOS, no-op on Android). | ||
Query the status of background tasks within this app. Returns a Promise with | ||
an object of the following shape: | ||
## Example | ||
- **`available`** `boolean` - Whether background tasks are available to the app. | ||
On Android this will always be true, but on iOS background tasks could be | ||
blocked (see [UIBackgroundRefreshStatus](https://developer.apple.com/documentation/uikit/uibackgroundrefreshstatus)). | ||
- **`unavailableReason?`** `string` - If unavailable, gives the reason: | ||
- **`BackgroundTask.UNAVAILABLE_DENIED`** - The user explicitly disabled | ||
background behavior for this app or for the whole system. | ||
- **`BackgroundTask.UNAVAILABLE_RESTRICTED`** - Background updates | ||
unavailable and can't be enabled by the user (e.g. parental controls). | ||
## Caveats | ||
- The exact timings of tasks are unpredictable (depends on device sleep state | ||
etc.), and cannot be more frequent than every 15 minutes. This library | ||
should only be used for tasks that can have inexact timing, such as the | ||
periodic background syncing of data. | ||
Android: | ||
- Tasks will not run while the app is in the foreground, and scheduling can be | ||
made even more imprecise when the app goes in/out of the foreground (as tasks | ||
are rescheduled as soon as the app goes into the background). | ||
iOS: | ||
- iOS Background Fetch does not work in the simulator. It must be tested on a | ||
real device. | ||
- The user can disable Background App Refresh for your app from their Settings | ||
(use `statusAsync()` to check for this). | ||
## Examples | ||
### Simple | ||
@@ -69,3 +156,3 @@ | ||
BackgroundTask.register(() => { | ||
BackgroundTask.define(() => { | ||
console.log('Hello from a background task') | ||
@@ -76,2 +163,6 @@ BackgroundTask.finish() | ||
class MyApp extends React.Component { | ||
componentDidMount() { | ||
BackgroundTask.schedule() | ||
} | ||
render() { | ||
@@ -87,6 +178,6 @@ return <Text>Hello world</Text> | ||
import React from 'react' | ||
import { AsyncStorage, Button, Text } from 'react-native' | ||
import { Alert, AsyncStorage, Button } from 'react-native' | ||
import BackgroundTask from 'react-native-background-task' | ||
BackgroundTask.register(async () => { | ||
BackgroundTask.define(async () => { | ||
// Fetch some data over the network which we want the user to have an up-to- | ||
@@ -102,7 +193,30 @@ // date copy of, even if they have no network when using the app | ||
BackgroundTask.finish() | ||
}, { | ||
period: 1800, // Aim to run every 30 mins - more conservative on battery | ||
}) | ||
class MyApp extends React.Component { | ||
componentDidMount() { | ||
BackgroundTask.schedule({ | ||
period: 1800, // Aim to run every 30 mins - more conservative on battery | ||
}) | ||
// Optional: Check if the device is blocking background tasks or not | ||
this.checkStatus() | ||
} | ||
async checkStatus() { | ||
const status = await BackgroundTask.statusAsync() | ||
if (status.available) { | ||
// Everything's fine | ||
return | ||
} | ||
const reason = status.unavailableReason | ||
if (reason === BackgroundTask.UNAVAILABLE_DENIED) { | ||
Alert.alert('Denied', 'Please enable background "Background App Refresh" for this app') | ||
} else if (reason === BackgroundTask.UNAVAILABLE_RESTRICTED) { | ||
Alert.alert('Restricted', 'Background tasks are restricted on your device') | ||
} | ||
} | ||
render() { | ||
@@ -109,0 +223,0 @@ return ( |
20
types.js
// @flow | ||
export type RegisterOptions = { | ||
/** | ||
* See README.md for documentation | ||
*/ | ||
export type ScheduleOptions = { | ||
period?: number, | ||
timeout?: number, | ||
flex?: number, | ||
} | ||
export type StatusResponse = { | ||
available: boolean, | ||
unavailableReason?: 'denied' | 'restricted', | ||
} | ||
/** | ||
* See README.md for documentation | ||
*/ | ||
export type BackgroundTaskInterface = { | ||
register: (task: () => void, options?: RegisterOptions) => void, | ||
define: (task: () => void) => void, | ||
schedule: (options?: ScheduleOptions) => void, | ||
finish: () => void, | ||
cancel: () => void, | ||
finish: () => void, | ||
statusAsync: () => Promise<StatusResponse>, | ||
} |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
23271
2
16
122
232
2
1