react-native-background-fetch-hive
v2.4.1
Published
iOS & Android BackgroundFetch API implementation for React Native
Downloads
3
Maintainers
Readme
react-native-background-fetch ·
By Transistor Software, creators of React Native Background Geolocation
Background Fetch is a very simple plugin which will awaken an app in the background about every 15 minutes, providing a short period of background running-time. This plugin will execute your provided callbackFn
whenever a background-fetch event occurs.
There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently.
The Android plugin provides a HeadlessJS implementation allowing you to continue handling events even after app-termination (see @config enableHeadless
)
Installing the plugin
$ npm install react-native-background-fetch --save
iOS Setup
Android Setup
:information_source: Solving Android Gradle Conflicts.
Once of the most common build-issues with Android apps are gradle conflicts between modules specifying different versions of:
compileSdkVersion
buildToolsVersion
- Google
play-services
/firebase
version. - Google support libraries (ie
appcompat-v4
,appcompat-v7
)
For more information, see the Wiki Solving Android Gradle Conflicts
Config
Common Options
@param {Integer} minimumFetchInterval [15]
The minimum interval in minutes to execute background fetch events. Defaults to 15
minutes. Note: Background-fetch events will never occur at a frequency higher than every 15 minutes. Apple uses a secret algorithm to adjust the frequency of fetch events, presumably based upon usage patterns of the app. Fetch events can occur less often than your configured minimumFetchInterval
.
Android Options
@config {Boolean} stopOnTerminate [true]
Set false
to continue background-fetch events after user terminates the app. Default to true
.
@config {Boolean} startOnBoot [false]
Set true
to initiate background-fetch events when the device is rebooted. Defaults to false
.
:exclamation: NOTE: startOnBoot
requires stopOnTerminate: false
.
@config {Boolean} forceReload [false]
Set true
to automatically relaunch the application (if it was terminated) — the application will launch to the foreground then immediately minimize. Defaults to false
.
@config {Boolean} enableHeadless [false]
Set true
to enable React Native's Headless JS mechanism, for handling fetch events after app termination.
- :open_file_folder:
index.js
import BackgroundFetch from "react-native-background-fetch";
let MyHeadlessTask = async (event) => {
console.log('- BackgroundFetch HeadlessTask start');
// Important: await asychronous tasks when using HeadlessJS.
await doAction();
// Required: Signal to native code that your task is complete.
// If you don't do this, your app could be terminated and/or assigned
// battery-blame for consuming too much time in background.
BackgroundFetch.finish();
console.log('- BackgroundFetch HeadlessTask finished');
}
// Simulate a long-running task (eg: HTTP request)
function doAction() {
let timeout = 5000;
return new Promise(resolve => {
setTimeout(() => {
console.log('*** TIMEOUT ***');
resolve();
}, timeout);
});
}
// Register your BackgroundFetch HeadlessTask
AppRegistry.registerHeadlessTask('BackgroundFetch', () => MyHeadlessTask);
Methods
| Method Name | Arguments | Notes
|---|---|---|
| configure
| {config}
, callbackFn
, failureFn
| Configures the plugin's fetch callbackFn
. This callback will fire each time an iOS background-fetch event occurs (typically every 15 min). The failureFn
will be called if the device doesn't support background-fetch. |
| status
| callbackFn
| Your callback will be executed with the current status (Integer)
0: Restricted
, 1: Denied
, 2: Available
. These constants are defined as BackgroundFetch.STATUS_RESTRICTED
, BackgroundFetch.STATUS_DENIED
, BackgroundFetch.STATUS_AVAILABLE
(NOTE: Android will always return STATUS_AVAILABLE
)|
| finish
| none | You MUST call this method in your fetch callbackFn
provided to #configure
in order to signal to iOS that your fetch action is complete. iOS provides only 30s of background-time for a fetch-event -- if you exceed this 30s, iOS will kill your app. |
| start
| successFn
, failureFn
| Start the background-fetch API. Your callbackFn
provided to #configure
will be executed each time a background-fetch event occurs. NOTE the #configure
method automatically calls #start
. You do not have to call this method after you #configure
the plugin |
| stop
| successFn
, failureFn
| Stop the background-fetch API from firing fetch events. Your callbackFn
provided to #configure
will no longer be executed. |
Example
import BackgroundFetch from "react-native-background-fetch";
export default class App extends Component {
componentDidMount() {
// Configure it.
BackgroundFetch.configure({
minimumFetchInterval: 15, // <-- minutes (15 is minimum allowed)
stopOnTerminate: false, // <-- Android-only,
startOnBoot: true // <-- Android-only
}, () => {
console.log("[js] Received background-fetch event");
// Required: Signal completion of your task to native code
// If you fail to do this, the OS can terminate your app
// or assign battery-blame for consuming too much background-time
BackgroundFetch.finish();
}, (error) => {
console.log("[js] RNBackgroundFetch failed to start");
});
// Optional: Query the authorization status.
BackgroundFetch.status((status) => {
switch(status) {
case BackgroundFetch.STATUS_RESTRICTED:
console.log("BackgroundFetch restricted");
break;
case BackgroundFetch.STATUS_DENIED:
console.log("BackgroundFetch denied");
break;
case BackgroundFetch.STATUS_AVAILABLE:
console.log("BackgroundFetch is enabled");
break;
}
});
}
};
Debugging
iOS
- Simulate background fetch events in XCode using
Debug->Simulate Background Fetch
- iOS can take some hours or even days to start a consistently scheduling background-fetch events since iOS schedules fetch events based upon the user's patterns of activity. If Simulate Background Fetch works, your can be sure that everything is working fine. You just need to wait.
Android
- Observe plugin logs in
$ adb logcat
:
$ adb logcat *:S ReactNative:V ReactNativeJS:V TSBackgroundFetch:V
- Simulate a background-fetch event on a device (insert <your.application.id>) (only works for sdk
21+
:
$ adb shell cmd jobscheduler run -f <your.application.id> 999
- For devices with sdk
<21
, simulate a "Headless JS" event with (insert <your.application.id>)
$ adb shell am broadcast -a <your.application.id>.event.BACKGROUND_FETCH
Implementation
iOS
Implements performFetchWithCompletionHandler, firing a custom event subscribed-to in cordova plugin.
Android
Android implements background fetch using two different mechanisms, depending on the Android SDK version. Where the SDK version is >= LOLLIPOP
, the new JobScheduler
API is used. Otherwise, the old AlarmManager
will be used.
Unlike iOS, the Android implementation can continue to operate after application terminate (stopOnTerminate: false
) or device reboot (startOnBoot: true
).
Licence
The MIT License
Copyright (c) 2013 Chris Scott, Transistor Software [email protected] http://transistorsoft.com
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.