@ammarahmed/react-native-background-fetch 4.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/.yarnignore +7 -0
  2. package/LICENSE +21 -0
  3. package/README.md +502 -0
  4. package/RNBackgroundFetch.podspec +25 -0
  5. package/android/build.gradle +40 -0
  6. package/android/proguard-rules.pro +2 -0
  7. package/android/src/main/AndroidManifest.xml +15 -0
  8. package/android/src/main/java/com/transistorsoft/rnbackgroundfetch/HeadlessTask.java +119 -0
  9. package/android/src/main/java/com/transistorsoft/rnbackgroundfetch/RNBackgroundFetchModule.java +185 -0
  10. package/android/src/main/java/com/transistorsoft/rnbackgroundfetch/RNBackgroundFetchPackage.java +29 -0
  11. package/android/src/main/java/com/transistorsoft/tsbackgroundfetch/BGTask.java +305 -0
  12. package/android/src/main/java/com/transistorsoft/tsbackgroundfetch/BackgroundFetch.java +297 -0
  13. package/android/src/main/java/com/transistorsoft/tsbackgroundfetch/BackgroundFetchConfig.java +362 -0
  14. package/android/src/main/java/com/transistorsoft/tsbackgroundfetch/BootReceiver.java +24 -0
  15. package/android/src/main/java/com/transistorsoft/tsbackgroundfetch/FetchAlarmReceiver.java +40 -0
  16. package/android/src/main/java/com/transistorsoft/tsbackgroundfetch/FetchJobService.java +106 -0
  17. package/android/src/main/java/com/transistorsoft/tsbackgroundfetch/LifecycleManager.java +225 -0
  18. package/app.plugin.js +1 -0
  19. package/index.d.ts +185 -0
  20. package/index.js +119 -0
  21. package/ios/RNBackgroundFetch/RNBackgroundFetch+AppDelegate.m +22 -0
  22. package/ios/RNBackgroundFetch/RNBackgroundFetch.h +18 -0
  23. package/ios/RNBackgroundFetch/RNBackgroundFetch.m +167 -0
  24. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/Info.plist +57 -0
  25. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_armv7/TSBackgroundFetch.framework/Headers/TSBackgroundFetch.h +47 -0
  26. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_armv7/TSBackgroundFetch.framework/Info.plist +0 -0
  27. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_armv7/TSBackgroundFetch.framework/Modules/module.modulemap +6 -0
  28. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_armv7/TSBackgroundFetch.framework/TSBackgroundFetch +0 -0
  29. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_i386_x86_64-simulator/TSBackgroundFetch.framework/Headers/TSBackgroundFetch.h +47 -0
  30. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_i386_x86_64-simulator/TSBackgroundFetch.framework/Info.plist +0 -0
  31. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_i386_x86_64-simulator/TSBackgroundFetch.framework/Modules/module.modulemap +6 -0
  32. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_i386_x86_64-simulator/TSBackgroundFetch.framework/TSBackgroundFetch +0 -0
  33. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_i386_x86_64-simulator/TSBackgroundFetch.framework/_CodeSignature/CodeDirectory +0 -0
  34. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_i386_x86_64-simulator/TSBackgroundFetch.framework/_CodeSignature/CodeRequirements +0 -0
  35. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_i386_x86_64-simulator/TSBackgroundFetch.framework/_CodeSignature/CodeRequirements-1 +0 -0
  36. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_i386_x86_64-simulator/TSBackgroundFetch.framework/_CodeSignature/CodeResources +132 -0
  37. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_i386_x86_64-simulator/TSBackgroundFetch.framework/_CodeSignature/CodeSignature +0 -0
  38. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_x86_64-maccatalyst/TSBackgroundFetch.framework/Headers/TSBackgroundFetch.h +47 -0
  39. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_x86_64-maccatalyst/TSBackgroundFetch.framework/Modules/module.modulemap +6 -0
  40. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_x86_64-maccatalyst/TSBackgroundFetch.framework/Resources/Info.plist +52 -0
  41. package/ios/RNBackgroundFetch/TSBackgroundFetch.xcframework/ios-arm64_x86_64-maccatalyst/TSBackgroundFetch.framework/TSBackgroundFetch +0 -0
  42. package/ios/RNBackgroundFetch.xcodeproj/project.pbxproj +310 -0
  43. package/ios/RNBackgroundFetch.xcodeproj/project.xcworkspace/contents.xcworkspacedata +7 -0
  44. package/ios/RNBackgroundFetch.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +8 -0
  45. package/ios/RNBackgroundFetch.xcodeproj/project.xcworkspace/xcuserdata/chris.xcuserdatad/UserInterfaceState.xcuserstate +0 -0
  46. package/package.json +32 -0
package/.yarnignore ADDED
@@ -0,0 +1,7 @@
1
+ .DS_Store
2
+ docs/
3
+ example/
4
+ *.md
5
+ node_modules
6
+ .github/
7
+
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Transistor Software
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,502 @@
1
+ | <img src="https://dl.dropbox.com/s/gxl3sr8znhkrtah/expo-logo.png?dl=1" alt="alt text" width="32" /> | Now with *Expo* support |
2
+ | --- | --- |
3
+
4
+ react-native-background-fetch &middot; [![npm](https://img.shields.io/npm/dm/react-native-background-fetch.svg)]() [![npm](https://img.shields.io/npm/v/react-native-background-fetch.svg)]()
5
+ ==============================================================================
6
+
7
+ [![](https://dl.dropboxusercontent.com/s/nm4s5ltlug63vv8/logo-150-print.png?dl=1)](https://www.transistorsoft.com)
8
+
9
+ By [**Transistor Software**](http://transistorsoft.com), creators of [**React Native Background Geolocation**](http://www.transistorsoft.com/shop/products/react-native-background-geolocation)
10
+
11
+ ------------------------------------------------------------------------------
12
+
13
+ Background Fetch is a *very* simple plugin which attempts to 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.
14
+
15
+ There is **no way** to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible &mdash; 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 or if an iOS user disables background refresh they may not happen at all.
16
+
17
+ :new: Background Fetch now provides a [__`scheduleTask`__](#executing-custom-tasks) method for scheduling arbitrary "one-shot" or periodic tasks.
18
+
19
+ ### iOS
20
+ - There is **no way** to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible &mdash; 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.
21
+ - [__`scheduleTask`__](#executing-custom-tasks) seems only to fire when the device is plugged into power.
22
+ - ⚠️ When your app is **terminated**, iOS *no longer fires events* &mdash; There is *no such thing* as **`stopOnTerminate: false`** for iOS.
23
+ - iOS can take *days* before Apple's machine-learning algorithm settles in and begins regularly firing events. Do not sit staring at your logs waiting for an event to fire. If your [*simulated events*](#debugging) work, that's all you need to know that everything is correctly configured.
24
+ - If the user doesn't open your *iOS* app for long periods of time, *iOS* will **stop firing events**.
25
+
26
+ ### Android
27
+ - The Android plugin provides a [HeadlessJS](https://reactnative.dev/docs/headless-js-android) implementation allowing you to continue handling events even after app-termination (see **[`@config enableHeadless`](#config-boolean-enableheadless-false)**)
28
+
29
+ -------------------------------------------------------------
30
+
31
+ # Contents
32
+ - ### :books: [API Documentation](#api-documentation)
33
+ - [Config](#config)
34
+ - [Methods](#methods)
35
+ - ### [Installing the Plugin](#installing-the-plugin)
36
+ - ### [Setup Guides](#setup-guides)
37
+ - [iOS Setup](#ios-setup)
38
+ - [Android Setup](#android-setup)
39
+ - ### [Example](#example)
40
+ - ### [Debugging](#debugging)
41
+
42
+ -------------------------------------------------------------
43
+
44
+ ## Installing the plugin
45
+
46
+ ### With *Expo*
47
+
48
+ ```bash
49
+ $ npx expo install react-native-background-fetch
50
+ ```
51
+
52
+ ### With `yarn`
53
+
54
+ ```bash
55
+ $ yarn add react-native-background-fetch
56
+ ```
57
+
58
+ ### With `npm`
59
+ ```bash
60
+ $ npm install --save react-native-background-fetch
61
+ ```
62
+
63
+ ## Setup Guides
64
+
65
+ ### *Expo* Setup
66
+
67
+ - [Expo Setup](docs/INSTALL-EXPO.md)
68
+
69
+ ### iOS Setup
70
+
71
+ - [Auto-linking Setup](docs/INSTALL-AUTO-IOS.md)
72
+
73
+ ### Android Setup
74
+
75
+ - [Auto-linking Setup](docs/INSTALL-AUTO-ANDROID.md)
76
+
77
+ ## Example ##
78
+
79
+ :information_source: This repo contains its own *Example App*. See [`/example`](./example/README.md)
80
+
81
+ ```javascript
82
+ import React from 'react';
83
+ import {
84
+ SafeAreaView,
85
+ StyleSheet,
86
+ ScrollView,
87
+ View,
88
+ Text,
89
+ FlatList,
90
+ StatusBar,
91
+ } from 'react-native';
92
+
93
+ import {
94
+ Header,
95
+ Colors
96
+ } from 'react-native/Libraries/NewAppScreen';
97
+
98
+ import BackgroundFetch from "react-native-background-fetch";
99
+
100
+ class App extends React.Component {
101
+ constructor(props) {
102
+ super(props);
103
+ this.state = {
104
+ events: []
105
+ };
106
+ }
107
+
108
+ componentDidMount() {
109
+ // Initialize BackgroundFetch ONLY ONCE when component mounts.
110
+ this.initBackgroundFetch();
111
+ }
112
+
113
+ async initBackgroundFetch() {
114
+ // BackgroundFetch event handler.
115
+ const onEvent = async (taskId) => {
116
+ console.log('[BackgroundFetch] task: ', taskId);
117
+ // Do your background work...
118
+ await this.addEvent(taskId);
119
+ // IMPORTANT: You must signal to the OS that your task is complete.
120
+ BackgroundFetch.finish(taskId);
121
+ }
122
+
123
+ // Timeout callback is executed when your Task has exceeded its allowed running-time.
124
+ // You must stop what you're doing immediately BackgroundFetch.finish(taskId)
125
+ const onTimeout = async (taskId) => {
126
+ console.warn('[BackgroundFetch] TIMEOUT task: ', taskId);
127
+ BackgroundFetch.finish(taskId);
128
+ }
129
+
130
+ // Initialize BackgroundFetch only once when component mounts.
131
+ let status = await BackgroundFetch.configure({minimumFetchInterval: 15}, onEvent, onTimeout);
132
+
133
+ console.log('[BackgroundFetch] configure status: ', status);
134
+ }
135
+
136
+ // Add a BackgroundFetch event to <FlatList>
137
+ addEvent(taskId) {
138
+ // Simulate a possibly long-running asynchronous task with a Promise.
139
+ return new Promise((resolve, reject) => {
140
+ this.setState(state => ({
141
+ events: [...state.events, {
142
+ taskId: taskId,
143
+ timestamp: (new Date()).toString()
144
+ }]
145
+ }));
146
+ resolve();
147
+ });
148
+ }
149
+
150
+ render() {
151
+ return (
152
+ <>
153
+ <StatusBar barStyle="dark-content" />
154
+ <SafeAreaView>
155
+ <ScrollView
156
+ contentInsetAdjustmentBehavior="automatic"
157
+ style={styles.scrollView}>
158
+ <Header />
159
+
160
+ <View style={styles.body}>
161
+ <View style={styles.sectionContainer}>
162
+ <Text style={styles.sectionTitle}>BackgroundFetch Demo</Text>
163
+ </View>
164
+ </View>
165
+ </ScrollView>
166
+ <View style={styles.sectionContainer}>
167
+ <FlatList
168
+ data={this.state.events}
169
+ renderItem={({item}) => (<Text>[{item.taskId}]: {item.timestamp}</Text>)}
170
+ keyExtractor={item => item.timestamp}
171
+ />
172
+ </View>
173
+ </SafeAreaView>
174
+ </>
175
+ );
176
+ }
177
+ }
178
+
179
+ const styles = StyleSheet.create({
180
+ scrollView: {
181
+ backgroundColor: Colors.lighter,
182
+ },
183
+ body: {
184
+ backgroundColor: Colors.white,
185
+ },
186
+ sectionContainer: {
187
+ marginTop: 32,
188
+ paddingHorizontal: 24,
189
+ },
190
+ sectionTitle: {
191
+ fontSize: 24,
192
+ fontWeight: '600',
193
+ color: Colors.black,
194
+ },
195
+ sectionDescription: {
196
+ marginTop: 8,
197
+ fontSize: 18,
198
+ fontWeight: '400',
199
+ color: Colors.dark,
200
+ },
201
+ });
202
+
203
+ export default App;
204
+ ```
205
+
206
+ ### Executing Custom Tasks
207
+
208
+ In addition to the default background-fetch task defined by `BackgroundFetch.configure`, you may also execute your own arbitrary "oneshot" or periodic tasks (iOS requires additional [Setup Instructions](#iOS-Setup)). However, all events will be fired into the Callback provided to **`BackgroundFetch#configure`**:
209
+
210
+ ### ⚠️ iOS:
211
+ - `scheduleTask` on *iOS* seems only to run when the device is plugged into power.
212
+ - `scheduleTask` on *iOS* are designed for *low-priority* tasks, such as purging cache files &mdash; they tend to be **unreliable for mission-critical tasks**. `scheduleTask` will *never* run as frequently as you want.
213
+ - The default `fetch` event is much more reliable and fires far more often.
214
+ - `scheduleTask` on *iOS* stop when the *user* terminates the app. There is no such thing as `stopOnTerminate: false` for *iOS*.
215
+
216
+ ```javascript
217
+ // Step 1: Configure BackgroundFetch as usual.
218
+ let status = await BackgroundFetch.configure({
219
+ minimumFetchInterval: 15
220
+ }, async (taskId) => { // <-- Event callback
221
+ // This is the fetch-event callback.
222
+ console.log("[BackgroundFetch] taskId: ", taskId);
223
+
224
+ // Use a switch statement to route task-handling.
225
+ switch (taskId) {
226
+ case 'com.foo.customtask':
227
+ print("Received custom task");
228
+ break;
229
+ default:
230
+ print("Default fetch task");
231
+ }
232
+ // Finish, providing received taskId.
233
+ BackgroundFetch.finish(taskId);
234
+ }, async (taskId) => { // <-- Task timeout callback
235
+ // This task has exceeded its allowed running-time.
236
+ // You must stop what you're doing and immediately .finish(taskId)
237
+ BackgroundFetch.finish(taskId);
238
+ });
239
+
240
+ // Step 2: Schedule a custom "oneshot" task "com.foo.customtask" to execute 5000ms from now.
241
+ BackgroundFetch.scheduleTask({
242
+ taskId: "com.foo.customtask",
243
+ forceAlarmManager: true,
244
+ delay: 5000 // <-- milliseconds
245
+ });
246
+ ```
247
+
248
+ # API Documentation
249
+
250
+ ## Config
251
+
252
+ ### Common Options
253
+
254
+ #### `@param {Integer} minimumFetchInterval [15]`
255
+
256
+ 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`.
257
+
258
+ #### `@param {Integer} delay (milliseconds)`
259
+
260
+ :information_source: Valid only for `BackgroundFetch.scheduleTask`. The minimum number of milliseconds in future that task should execute.
261
+
262
+ #### `@param {Boolean} periodic [false]`
263
+
264
+ :information_source: Valid only for `BackgroundFetch.scheduleTask`. Defaults to `false`. Set true to execute the task repeatedly. When `false`, the task will execute **just once**.
265
+
266
+ ### Android Options
267
+
268
+ #### `@config {Boolean} stopOnTerminate [true]`
269
+
270
+ Set `false` to continue background-fetch events after user terminates the app. Default to `true`.
271
+
272
+ #### `@config {Boolean} startOnBoot [false]`
273
+
274
+ Set `true` to initiate background-fetch events when the device is rebooted. Defaults to `false`.
275
+
276
+ :exclamation: **NOTE:** `startOnBoot` requires `stopOnTerminate: false`.
277
+
278
+ #### `@config {Boolean} forceAlarmManager [false]`
279
+
280
+ By default, the plugin will use Android's `JobScheduler` when possible. The `JobScheduler` API prioritizes for battery-life, throttling task-execution based upon device usage and battery level.
281
+
282
+ Configuring `forceAlarmManager: true` will bypass `JobScheduler` to use Android's older `AlarmManager` API, resulting in more accurate task-execution at the cost of **higher battery usage**.
283
+
284
+ ```javascript
285
+ let status = await BackgroundFetch.configure({
286
+ minimumFetchInterval: 15,
287
+ forceAlarmManager: true
288
+ }, async (taskId) => { // <-- Event callback
289
+ console.log("[BackgroundFetch] taskId: ", taskId);
290
+ BackgroundFetch.finish(taskId);
291
+ }, async (taskId) => { // <-- Task timeout callback
292
+ // This task has exceeded its allowed running-time.
293
+ // You must stop what you're doing and immediately .finish(taskId)
294
+ BackgroundFetch.finish(taskId);
295
+ });
296
+ .
297
+ .
298
+ .
299
+ // And with with #scheduleTask
300
+ BackgroundFetch.scheduleTask({
301
+ taskId: 'com.foo.customtask',
302
+ delay: 5000, // milliseconds
303
+ forceAlarmManager: true,
304
+ periodic: false
305
+ });
306
+ ```
307
+
308
+ #### `@config {Boolean} enableHeadless [false]`
309
+
310
+ Set `true` to enable React Native's [Headless JS](https://reactnative.dev/docs/headless-js-android) mechanism, for handling fetch events after app termination.
311
+
312
+ * :open_file_folder: **`index.js`** (**MUST BE IN `index.js`**):
313
+ ```javascript
314
+ import BackgroundFetch from "react-native-background-fetch";
315
+
316
+ let MyHeadlessTask = async (event) => {
317
+ // Get task id from event {}:
318
+ let taskId = event.taskId;
319
+ let isTimeout = event.timeout; // <-- true when your background-time has expired.
320
+ if (isTimeout) {
321
+ // This task has exceeded its allowed running-time.
322
+ // You must stop what you're doing immediately finish(taskId)
323
+ console.log('[BackgroundFetch] Headless TIMEOUT:', taskId);
324
+ BackgroundFetch.finish(taskId);
325
+ return;
326
+ }
327
+ console.log('[BackgroundFetch HeadlessTask] start: ', taskId);
328
+
329
+ // Perform an example HTTP request.
330
+ // Important: await asychronous tasks when using HeadlessJS.
331
+ let response = await fetch('https://reactnative.dev/movies.json');
332
+ let responseJson = await response.json();
333
+ console.log('[BackgroundFetch HeadlessTask] response: ', responseJson);
334
+
335
+ // Required: Signal to native code that your task is complete.
336
+ // If you don't do this, your app could be terminated and/or assigned
337
+ // battery-blame for consuming too much time in background.
338
+ BackgroundFetch.finish(taskId);
339
+ }
340
+
341
+ // Register your BackgroundFetch HeadlessTask
342
+ BackgroundFetch.registerHeadlessTask(MyHeadlessTask);
343
+ ```
344
+
345
+
346
+ #### `@config {integer} requiredNetworkType [BackgroundFetch.NETWORK_TYPE_NONE]`
347
+
348
+ Set basic description of the kind of network your job requires.
349
+
350
+ If your job doesn't need a network connection, you don't need to use this option as the default value is `BackgroundFetch.NETWORK_TYPE_NONE`.
351
+
352
+ | NetworkType | Description |
353
+ |---------------------------------------|---------------------------------------------------------------------|
354
+ | `BackgroundFetch.NETWORK_TYPE_NONE` | This job doesn't care about network constraints, either any or none.|
355
+ | `BackgroundFetch.NETWORK_TYPE_ANY` | This job requires network connectivity. |
356
+ | `BackgroundFetch.NETWORK_TYPE_CELLULAR` | This job requires network connectivity that is a cellular network. |
357
+ | `BackgroundFetch.NETWORK_TYPE_UNMETERED` | This job requires network connectivity that is unmetered. Most WiFi networks are unmetered, as in "you can upload as much as you like". |
358
+ | `BackgroundFetch.NETWORK_TYPE_NOT_ROAMING` | This job requires network connectivity that is not roaming (being outside the country of origin) |
359
+
360
+ #### `@config {Boolean} requiresBatteryNotLow [false]`
361
+
362
+ Specify that to run this job, the device's battery level must not be low.
363
+
364
+ This defaults to false. If true, the job will only run when the battery level is not low, which is generally the point where the user is given a "low battery" warning.
365
+
366
+ #### `@config {Boolean} requiresStorageNotLow [false]`
367
+
368
+ Specify that to run this job, the device's available storage must not be low.
369
+
370
+ This defaults to false. If true, the job will only run when the device is not in a low storage state, which is generally the point where the user is given a "low storage" warning.
371
+
372
+ #### `@config {Boolean} requiresCharging [false]`
373
+
374
+ Specify that to run this job, the device must be charging (or be a non-battery-powered device connected to permanent power, such as Android TV devices). This defaults to false.
375
+
376
+ #### `@config {Boolean} requiresDeviceIdle [false]`
377
+
378
+ When set true, ensure that this job will not run if the device is in active use.
379
+
380
+ The default state is false: that is, the for the job to be runnable even when someone is interacting with the device.
381
+
382
+ This state is a loose definition provided by the system. In general, it means that the device is not currently being used interactively, and has not been in use for some time. As such, it is a good time to perform resource heavy jobs. Bear in mind that battery usage will still be attributed to your application, and shown to the user in battery stats.
383
+
384
+ -----------------------------------------------------------------------------------------------------
385
+
386
+ ## Methods
387
+
388
+ | Method Name | Arguments | Returns | Notes
389
+ |---|---|---|---|
390
+ | `configure` | `{FetchConfig}`, `callbackFn`, `timeoutFn` | `Promise<BackgroundFetchStatus>` | Configures the plugin's `callbackFn` and `timeoutFn`. This callback will fire each time a background-fetch event occurs in addition to events from `#scheduleTask`. The `timeoutFn` will be called when the OS reports your task is nearing the end of its allowed background-time. |
391
+ | `scheduleTask` | `{TaskConfig}` | `Promise<boolean>` | Executes a custom task. The task will be executed in the same `Callback` function provided to `#configure`. |
392
+ | `status` | `callbackFn` | `Promise<BackgroundFetchStatus>` | 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`)|
393
+ | `finish` | `String taskId` | `Void` | You **MUST** call this method in your `callbackFn` provided to `#configure` in order to signal to the OS that your task is complete. iOS provides **only** 30s of background-time for a fetch-event -- if you exceed this 30s, iOS will kill your app. |
394
+ | `start` | `none` | `Promise<BackgroundFetchStatus>` | 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 |
395
+ | `stop` | `[taskId:String]` | `Promise<boolean>` | Stop the background-fetch API and all `#scheduleTask` from firing events. Your `callbackFn` provided to `#configure` will no longer be executed. If you provide an optional `taskId`, only that `#scheduleTask` will be stopped.|
396
+
397
+
398
+ ## Debugging
399
+
400
+ ### iOS
401
+
402
+ #### :new: `BGTaskScheduler` API for iOS 13+
403
+
404
+ - :warning: At the time of writing, the new task simulator does not yet work in Simulator; Only real devices.
405
+ - See Apple docs [Starting and Terminating Tasks During Development](https://developer.apple.com/documentation/backgroundtasks/starting_and_terminating_tasks_during_development?language=objc)
406
+ - After running your app in XCode, Click the `[||]` button to initiate a *Breakpoint*.
407
+ - In the console `(lldb)`, paste the following command (**Note:** use cursor up/down keys to cycle through previously run commands):
408
+ ```obj-c
409
+ e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.transistorsoft.fetch"]
410
+ ```
411
+ - Click the `[ > ]` button to continue. The task will execute and the Callback function provided to **`BackgroundFetch.configure`** will receive the event.
412
+
413
+
414
+ ![](https://dl.dropboxusercontent.com/s/zr7w3g8ivf71u32/ios-simulate-bgtask-pause.png?dl=1)
415
+
416
+ ![](https://dl.dropboxusercontent.com/s/87c9uctr1ka3s1e/ios-simulate-bgtask-paste.png?dl=1)
417
+
418
+ ![](https://dl.dropboxusercontent.com/s/bsv0avap5c2h7ed/ios-simulate-bgtask-play.png?dl=1)
419
+
420
+ #### Simulating task-timeout events
421
+
422
+ - Only the new `BGTaskScheduler` api supports *simulated* task-timeout events. To simulate a task-timeout, your `fetchCallback` must not call `BackgroundFetch.finish(taskId)`:
423
+
424
+ ```javascript
425
+ let status = await BackgroundFetch.configure({
426
+ minimumFetchInterval: 15
427
+ }, async (taskId) => { // <-- Event callback.
428
+ // This is the task callback.
429
+ console.log("[BackgroundFetch] taskId", taskId);
430
+ //BackgroundFetch.finish(taskId); // <-- Disable .finish(taskId) when simulating an iOS task timeout
431
+ }, async (taskId) => { // <-- Event timeout callback
432
+ // This task has exceeded its allowed running-time.
433
+ // You must stop what you're doing and immediately .finish(taskId)
434
+ print("[BackgroundFetch] TIMEOUT taskId:", taskId);
435
+ BackgroundFetch.finish(taskId);
436
+ });
437
+ ```
438
+
439
+ - Now simulate an iOS task timeout as follows, in the same manner as simulating an event above:
440
+ ```obj-c
441
+ e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateExpirationForTaskWithIdentifier:@"com.transistorsoft.fetch"]
442
+ ```
443
+
444
+ #### Old `BackgroundFetch` API
445
+ - Simulate background fetch events in XCode using **`Debug->Simulate Background Fetch`**
446
+ - 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, you can be **sure** that everything is working fine. You just need to wait.
447
+
448
+ ### Android
449
+
450
+ - Observe plugin logs in `$ adb logcat`:
451
+ ```bash
452
+ $ adb logcat *:S ReactNative:V ReactNativeJS:V TSBackgroundFetch:V
453
+ ```
454
+ - Simulate a background-fetch event on a device (insert *&lt;your.application.id&gt;*) (only works for sdk `21+`:
455
+ ```bash
456
+ $ adb shell cmd jobscheduler run -f <your.application.id> 999
457
+ ```
458
+
459
+ - Simulating `scheduleTask` events:
460
+ 1. Observe `adb logcat` for the `registerTask` log-entry and copy the `jobId`.
461
+
462
+ ```
463
+ // from adb logcat *:S TSBackgroundFetch
464
+ TSBackgroundFetch: - registerTask: com.your.package.name (jobId: -359368280) <--
465
+ ```
466
+
467
+ ```
468
+ 2. Now paste that `jobId` from logcat into the `adb shell` command to simulate a `JobScheduler` event:
469
+ ```bash
470
+ $ adb shell cmd jobscheduler run -f com.your.package.name -359368280
471
+ ```
472
+
473
+ - For devices with sdk `<21`, simulate a "Headless JS" event with (insert *&lt;your.application.id&gt;*)
474
+ ```bash
475
+ $ adb shell am broadcast -a <your.application.id>.event.BACKGROUND_FETCH
476
+
477
+ ```
478
+
479
+ ## Licence
480
+
481
+ The MIT License
482
+
483
+ Copyright (c) 2013 Chris Scott, Transistor Software <chris@transistorsoft.com>
484
+ http://transistorsoft.com
485
+
486
+ Permission is hereby granted, free of charge, to any person obtaining a copy
487
+ of this software and associated documentation files (the "Software"), to deal
488
+ in the Software without restriction, including without limitation the rights
489
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
490
+ copies of the Software, and to permit persons to whom the Software is
491
+ furnished to do so, subject to the following conditions:
492
+
493
+ The above copyright notice and this permission notice shall be included in
494
+ all copies or substantial portions of the Software.
495
+
496
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
497
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
498
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
499
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
500
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
501
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
502
+ THE SOFTWARE.
@@ -0,0 +1,25 @@
1
+ require 'json'
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.cocoapods_version = '>= 1.10.0'
7
+ s.name = 'RNBackgroundFetch'
8
+ s.version = package['version']
9
+ s.summary = package['description']
10
+ s.description = <<-DESC
11
+ iOS BackgroundFetch API Implementation
12
+ DESC
13
+ s.homepage = package['homepage']
14
+ s.license = package['license']
15
+ s.author = package['author']
16
+ s.source = { :git => 'https://github.com/transistorsoft/react-native-background-fetch.git', :tag => s.version }
17
+
18
+ s.requires_arc = true
19
+ s.platform = :ios, '8.0'
20
+
21
+ s.dependency 'React-Core'
22
+ s.preserve_paths = 'docs', 'CHANGELOG.md', 'LICENSE', 'package.json', 'RNBackgroundFetch.ios.js'
23
+ s.source_files = 'ios/RNBackgroundFetch/RNBackgroundFetch.h', 'ios/RNBackgroundFetch/RNBackgroundFetch.m'
24
+ s.vendored_frameworks = 'ios/RNBackgroundFetch/TSBackgroundFetch.xcframework'
25
+ end
@@ -0,0 +1,40 @@
1
+ apply plugin: 'com.android.library'
2
+
3
+ def DEFAULT_COMPILE_SDK_VERSION = 31
4
+ def DEFAULT_TARGET_SDK_VERSION = 30
5
+ def DEFAULT_MIN_SDK_VERSION = 16
6
+ def DEFAULT_LIFE_CYCLE_RUNTIME_VERSION = "2.4.1"
7
+ def DEFAULT_LIFE_CYCLE_EXTENSIONS_VERSION = "2.2.0"
8
+
9
+ def safeExtGet(prop, fallback) {
10
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
11
+ }
12
+
13
+ android {
14
+ if (project.android.hasProperty("namespace")) {
15
+ namespace("com.transistorsoft.rnbackgroundfetch")
16
+ }
17
+
18
+ compileSdkVersion safeExtGet('compileSdkVersion', DEFAULT_COMPILE_SDK_VERSION)
19
+
20
+ defaultConfig {
21
+ minSdkVersion safeExtGet('minSdkVersion', DEFAULT_MIN_SDK_VERSION)
22
+ targetSdkVersion safeExtGet('targetSdkVersion', DEFAULT_TARGET_SDK_VERSION)
23
+ versionCode 1
24
+ versionName "1.0"
25
+ }
26
+ }
27
+
28
+ repositories{
29
+ mavenCentral()
30
+ }
31
+
32
+ dependencies {
33
+ def lifeCycleRuntimeVersion = safeExtGet('lifeCycleRuntimeVersion', DEFAULT_LIFE_CYCLE_RUNTIME_VERSION)
34
+ def lifeCycleExtensionsVersion = safeExtGet('lifeCycleExtensionsVersion', DEFAULT_LIFE_CYCLE_EXTENSIONS_VERSION)
35
+
36
+ implementation "com.facebook.react:react-native:${safeExtGet('reactNativeVersion', '+')}"
37
+ // LifeCycleObserver
38
+ implementation "androidx.lifecycle:lifecycle-runtime:$lifeCycleRuntimeVersion"
39
+ implementation "androidx.lifecycle:lifecycle-extensions:$lifeCycleExtensionsVersion"
40
+ }
@@ -0,0 +1,2 @@
1
+ # [react-native-background-fetch]
2
+ -keep class com.transistorsoft.rnbackgroundfetch.HeadlessTask { *; }
@@ -0,0 +1,15 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2
+ package="com.transistorsoft.rnbackgroundfetch">
3
+
4
+ <application>
5
+ <receiver android:name="com.transistorsoft.tsbackgroundfetch.FetchAlarmReceiver" android:exported="false" />
6
+ <service android:name="com.transistorsoft.tsbackgroundfetch.FetchJobService" android:permission="android.permission.BIND_JOB_SERVICE" android:exported="true" />
7
+ <receiver android:name="com.transistorsoft.tsbackgroundfetch.BootReceiver" android:exported="false">
8
+ <intent-filter>
9
+ <action android:name="android.intent.action.BOOT_COMPLETED" />
10
+ <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
11
+ </intent-filter>
12
+ </receiver>
13
+ </application>
14
+
15
+ </manifest>