Template version: v0.4.0
react-native-background-fetch
This project is based on react-native-background-fetch.
This third-party library has been migrated to AtomGit and is now available for direct download from npm, the new package name is:@react-native-ohos/react-native-background-fetch.The version correspondence details are as follows:
| Name | Version | Release Information | Supported RN Version | Supported Autolink | Compile API Version | Community Baseline Version | npm Address |
|---|---|---|---|---|---|---|---|
| @react-native-ohos/react-native-background-fetch | ~ 4.4.0 | AtomGit Releases | 0.82.* | Yes | API12+ | 4.2.8 | Npm Address |
| @react-native-ohos/react-native-background-fetch | ~ 4.3.0 | AtomGit Releases | 0.77.* | No | API12+ | 4.2.8 | Npm Address |
| @react-native-ohos/react-native-background-fetch | ~ 4.2.6 | AtomGit Releases | 0.72.* | Yes | API12+ | 4.2.5 | Npm Address |
| @react-native-oh-tpl/react-native-background-fetch | <= 4.2.5-0.0.2@deprecated | Github Releases(deprecated) | 0.72.* | No | API12+ | 4.2.5 | Npm Address |
1. Installation and Usage
Go to the project directory and execute the following instruction:
npm
npm install @react-native-ohos/react-native-background-fetch
yarn
yarn add @react-native-ohos/react-native-background-fetch
The following code shows the basic use scenario of the repository:
The name of the imported repository remains unchanged.
import React from "react";
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
FlatList,
StatusBar,
Button,
} from "react-native";
import { Header, Colors } from "react-native/Libraries/NewAppScreen";
import BackgroundFetch from "react-native-background-fetch";
import {
BackgroundFetchConfig,
BackgroundFetchStatus,
TaskConfig,
NetworkType,
} from "react-native-background-fetch/src/RNBackgroundFetch";
function generateRandomString(length: number): string {
let result = "";
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
class App extends React.Component {
constructor(props: {}) {
super(props);
this.state = {
events: [],
};
}
componentDidMount() {
// Initialize BackgroundFetch ONLY ONCE when component mounts.
this.initBackgroundFetch();
}
async initBackgroundFetch(options?: BackgroundFetchConfig) {
// BackgroundFetch event handler.
const onEvent = async (taskId: string) => {
console.log("[BackgroundFetch] task: ", taskId);
// Do your background work...
await this.addEvent(taskId);
// IMPORTANT: You must signal to the OS that your task is complete.
BackgroundFetch.finish(taskId);
};
// Timeout callback is executed when your Task has exceeded its allowed running-time.
// You must stop what you're doing immediately BackgroundFetch.finish(taskId)
const onTimeout = async (taskId: string) => {
console.warn("[BackgroundFetch] TIMEOUT task: ", taskId);
BackgroundFetch.finish(taskId);
};
// Initialize BackgroundFetch only once when component mounts.
let status = await BackgroundFetch.configure(
{ minimumFetchInterval: 20, ...options },
onEvent,
onTimeout
);
}
scheduleTask(taskId: string, options?: TaskConfig) {
BackgroundFetch.scheduleTask({
taskId,
delay: 20 * 60 * 1000, // <-- milliseconds
...options,
});
}
// Add a BackgroundFetch event to <FlatList>
addEvent(taskId: string) {
// Simulate a possibly long-running asynchronous task with a Promise.
return new Promise((resolve, reject) => {
this.setState((state) => ({
events: [
...state.events,
{
taskId: taskId,
timestamp: new Date().toString(),
},
],
}));
resolve(true);
});
}
render() {
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}
>
<Header />
<View style={styles.body}>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>BackgroundFetch Demo</Text>
</View>
</View>
</ScrollView>
<View style={styles.sectionContainer}>
<FlatList
data={this.state.events}
renderItem={({ item }) => (
<Text>
[{item.taskId}]: {item.timestamp}
</Text>
)}
keyExtractor={(item) => generateRandomString(10)}
/>
</View>
</SafeAreaView>
</>
);
}
}
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
body: {
backgroundColor: Colors.white,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: "600",
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: "400",
color: Colors.dark,
},
});
export default App;
2. Link
| Is supported autolink | Supported RN Version | |
|---|---|---|
| ~4.4.0 | Yes | 0.82 |
| ~4.3.0 | No | 0.77 |
| ~4.2.6 | Yes | 0.72 |
| <= 4.2.5-0.0.2@deprecated | No | 0.72 |
Projects using AutoLink need to be configured according to this document, AutoLink framework guide.: https://atomgit.com/CPF-RN/ohos_react_native/blob/master/docs/zh-cn/Autolinking.md
If the version you are using supports Autolink and the project has integrated Autolink, you can skip the ManualLink configuration.
ManualLink: This step provides guidance for manually configuring native dependencies.
Open the harmony directory of the HarmonyOS project in DevEco Studio.
2.1. Overrides RN SDK
To ensure the project relies on the same version of the RN SDK, you need to add an overrides field in the project's root oh-package.json5 file, specifying the RN SDK version to be used. The replacement version can be a specific version number, a semver range, or a locally available HAR package or source directory.
For more information about the purpose of this field, please refer to the official documentation.
{
...
"overrides": {
"@rnoh/react-native-openharmony" : "./react_native_openharmony"
}
}
2.2. Introducing Native Code
Currently, two methods are available:
- Use the HAR file.
- Directly link to the source code.
Method 1 (recommended): Use the HAR file.
The HAR file is stored in the `harmony` directory in the installation path of the third-party library.
Open entry/oh-package.json5 file and add the following dependencies:
"dependencies": {
"@rnoh/react-native-openharmony": "file:../react_native_openharmony",
"@react-native-ohos/react-native-background-fetch": "file:../../node_modules/@react-native-ohos/react-native-background-fetch/harmony/background_fetch.har"
}
Click the sync button in the upper right corner.
Alternatively, run the following instruction on the terminal:
cd entry
ohpm install
Method 2: Directly link to the source code.
For details, see [Directly Linking Source Code](./link-source-code.md).
2.3. Configure CMakeLists and Introducing RNBackgroundFetchPackage
If you are using version <= 4.2.5-0.0.2, please skip this chapter.
open entry/src/main/cpp/CMakeLists.txt,add:
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
# RNOH_BEGIN: manual_package_linking_1
+ add_subdirectory("${OH_MODULES}/@react-native-ohos/react-native-background-fetch/src/main/cpp" ./background_fetch)
# RNOH_END: manual_package_linking_1
# RNOH_BEGIN: manual_package_linking_2
+ target_link_libraries(rnoh_app PUBLIC rnoh_background_fetch)
# RNOH_END: manual_package_linking_2
Open entry/src/main/cpp/PackageProvider.cpp and add the following code:
#include "RNOH/PackageProvider.h"
#include "generated/RNOHGeneratedPackage.h"
+ #include "RNBackgroundFetchPackage.h"
using namespace rnoh;
std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx)
{
return {
std::make_shared<RNOHGeneratedPackage>(ctx),
+ std::make_shared<RNBackgroundFetchPackage>(ctx)
};
}
2.4. Introducing RNBackgroundFetchPackage to ArkTS
Open the entry/src/main/ets/RNPackagesFactory.ts file and add the following code:
...
+ import { RNBackgroundFetchPackage } from "@react-native-ohos/react-native-background-fetch/ts";
export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
return [
new SamplePackage(ctx),
+ new RNBackgroundFetchPackage(ctx)
];
}
2.5. Necessary configuration items
The content of this module cannot be automatically generated by autolink and must always be manually configured.
2.5.1. Introducing RNBackgroundFetchExtensionAbility to ArkTS(This module always requires manual configuration)
- Open'entry/src/main/ets', create a new directory and ArkTS file, and create a new directory and name it WorkSchedulerExtension. In the WorkSchedulerExtension directory, create an ArkTS file and name it WorkSchedulerExtension.ets to implement the delayed task callback interface.
import { workScheduler } from "@kit.BackgroundTasksKit";
import RNBackgroundFetchExtensionAbility from "@react-native-ohos/react-native-background-fetch/src/main/ets/WorkSchedulerExtension/WorkSchedulerExtension";
export default class MyWorkSchedulerExtensionAbility extends RNBackgroundFetchExtensionAbility {
onWorkStart(workInfo: workScheduler.WorkInfo) {
super.onWorkStart(workInfo);
}
onWorkStop(workInfo: workScheduler.WorkInfo) {
super.onWorkStop(workInfo);
}
}
- Register WorkSchedulerExtensionAbility in the
entry/src/main/module.json5configuration file and set the following tags:
{
"module": {
"extensionAbilities": [
{
"name": "MyWorkSchedulerExtensionAbility",
"srcEntry": "./ets/WorkSchedulerExtension/WorkSchedulerExtension.ets",
"type": "workScheduler"
}
]
}
}
2.6 Running
Click the sync button in the upper right corner.
Alternatively, run the following instruction on the terminal:
cd entry
ohpm install
Then build and run the code.
3. Constraints
3.1. Compatibility
This document is verified based on the following versions:
- RNOH: 0.72.96; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;
- RNOH: 0.72.33; SDK: HarmonyOS NEXT B1; IDE: DevEco Studio: 5.0.3.900; ROM: Next.0.0.71;
- RNOH: 0.77.18; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;
- RNOH: 0.82.1; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;
4. API
The **Platform** column indicates the platform where the properties are supported in the original third-party library.
If the value of **HarmonyOS Support** is **yes**, it means that the HarmonyOS platform supports this property; **no** means the opposite; **partially** means some capabilities of this property are supported. The usage method is the same on different platforms and the effect is the same as that of iOS or Android.
BackgroundFetch
| Name | Description | Type | Required | Platform | HarmonyOS Support |
|---|---|---|---|---|---|
| configure | Initial configuration of BackgroundFetch, including config-options and Fetch-callback. The [[start]] method will automatically be executed. | Function | yes | all | partially |
| scheduleTask | Add an extra fetch event listener in addition to the one initially provided to [[configure]]. | Function | no | all | partially |
| start | Start subscribing to fetch events. | Function | no | all | yes |
| stop | Stop subscribing to fetch events. | Function | no | all | yes |
| finish | You must execute [[finish]] within your fetch-callback to signal completion of your task. | Function | no | all | yes |
| status | Query the BackgroundFetch API status | Function | no | all | yes |
This table lists all interfaces. For detailed parameter descriptions, please refer to the sections below.
BackgroundFetch.configure()
BackgroundFetch.configure(config: BackgroundFetchConfig, onEvent: (taskId:string) => void, onTimeout?:(taskId:string) => void): Promise<BackgroundFetchStatus>;
| Name | Description | Type | Required | Platform | HarmonyOS Support |
|---|---|---|---|---|---|
BackgroundFetchConfig.minimumFetchInterval |
The minimum interval in minutes to execute background fetch events. Defaults to 15 minutes. Minimum is 15 minutes. | number |
no | all | yes |
BackgroundFetchConfig.stopOnTerminate |
Set false to continue background-fetch events after user terminates the app. Default to true. | boolean |
no | Android | no |
BackgroundFetchConfig.startOnBoot |
Set true to initiate background-fetch events when the device is rebooted. Defaults to false. | boolean |
no | Android | no |
BackgroundFetchConfig.enableHeadless |
Set true to enable Headless mechanism for handling fetch events after app termination. | boolean |
no | Android | no |
BackgroundFetchConfig.forceAlarmManager |
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. | boolean |
no | Android | no |
BackgroundFetchConfig.requiredNetworkType |
Set detailed description of the kind of network your job requires. | NetworkType |
no | Android | partially (NETWORK_TYPE_ANY, NETWORK_TYPE_CELLULAR, NETWORK_TYPE_UNMETERED) |
BackgroundFetchConfig.requiresBatteryNotLow |
Specify that to run this job, the device's battery level must not be low. | boolean |
no | Android | yes |
BackgroundFetchConfig.requiresStorageNotLow |
Specify that to run this job, the device's available storage must not be low. | boolean |
no | Android | yes |
BackgroundFetchConfig.requiresCharging |
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). | boolean |
no | Android | yes |
BackgroundFetchConfig.requiresDeviceIdle |
When set true, ensure that this job will not run if the device is in active use. | boolean |
no | Android | yes |
BackgroundFetch.scheduleTask()
BackgroundFetch.scheduleTask(config: TaskConfig): Promise<boolean>;
| Name | Description | Type | Required | Platform | HarmonyOS Support |
|---|---|---|---|---|---|
TaskConfig.taskId |
The name of the task. | string |
yes | all | yes |
TaskConfig.delay |
The minimum interval in milliseconds to execute this task. | number |
yes | all | yes |
TaskConfig.periodic |
Whether this task will continue executing or just a "one-shot". | boolean |
no | all | yes |
TaskConfig.requiresNetworkConnectivity |
When set true, ensure that this job will run if the device has network connection | boolean |
no | all | no |
TaskConfig.stopOnTerminate |
Set false to continue background-fetch events after user terminates the app. Default to true. | boolean |
no | Android | no |
TaskConfig.startOnBoot |
Set true to initiate background-fetch events when the device is rebooted. Defaults to false. | boolean |
no | Android | no |
TaskConfig.enableHeadless |
Set true to enable Headless mechanism for handling fetch events after app termination. | boolean |
no | Android | no |
TaskConfig.forceAlarmManager |
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. | boolean |
no | Android | no |
TaskConfig.requiredNetworkType |
Set detailed description of the kind of network your job requires. | NetworkType |
no | Android | partially (NETWORK_TYPE_ANY, NETWORK_TYPE_CELLULAR, NETWORK_TYPE_UNMETERED) |
TaskConfig.requiresBatteryNotLow |
Specify that to run this job, the device's battery level must not be low. | boolean |
no | Android | yes |
TaskConfig.requiresStorageNotLow |
Specify that to run this job, the device's available storage must not be low. | boolean |
no | Android | yes |
TaskConfig.requiresCharging |
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). | boolean |
no | Android | yes |
TaskConfig.requiresDeviceIdle |
When set true, ensure that this job will not run if the device is in active use. | boolean |
no | Android | yes |
BackgroundFetch.stop()
BackgroundFetch.stop(taskId?: string): Promise<boolean>;
| Name | Description | Type | Required | Platform | HarmonyOS Support |
|---|---|---|---|---|---|
taskId |
The name of the task. | string |
no | all | yes |
BackgroundFetch.finish()
BackgroundFetch.finish(taskId: string): void;
| Name | Description | Type | Required | Platform | HarmonyOS Support |
|---|---|---|---|---|---|
taskId |
The name of the task. | string |
yes | all | yes |
BackgroundFetch.status()
BackgroundFetch.status(callback?: (status: BackgroundFetchStatus) => void): Promise<BackgroundFetchStatus>;
| Name | Description | Type | Required | Platform | HarmonyOS Support |
|---|---|---|---|---|---|
callback |
Query the BackgroundFetch API status. | Function |
no | all | yes |
BackgroundFetchStatus
| Name | Description | Type | Required | Platform | HarmonyOS Support |
|---|---|---|---|---|---|
BackgroundFetchStatus.STATUS_RESTRICTED |
Background fetch updates are unavailable and the user cannot enable them again. For example, this status can occur when parental controls are in effect for the current user. | BackgroundFetchStatus |
yes | iOS | no |
BackgroundFetchStatus.STATUS_DENIED |
The user explicitly disabled background behavior for this app or for the whole system. | BackgroundFetchStatus |
yes | iOS | no |
BackgroundFetchStatus.STATUS_AVAILABLE |
Background fetch is available and enabled. | BackgroundFetchStatus |
yes | all | yes |
5. Known Issues
6. Others
- On iOS, it may take several days for the machine learning algorithm to start and begin triggering regular events. Meanwhile, you should regularly bring the app to the foreground to train the iOS machine learning algorithm with user behavior. Only then will iOS execute tasks regularly.
- On Android, no machine learning algorithm is involved; the configure function can be called every 15 minutes, and scheduleTask can be called every 1 minute at minimum.
- On HarmonyOS, the system schedules tasks uniformly based on factors such as memory, power consumption, device temperature, and user usage habits. For example, if system memory resources are insufficient or the temperature reaches a certain level, the system will delay scheduling the task. If you set it to execute after 20 minutes, the first task may not execute exactly at 20 minutes—it could execute in around a dozen minutes, and subsequent tasks will only execute after at least 2 hours. For more details, please refer to the link below: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/work-scheduler-V5
7. License
This project is licensed under The MIT License (MIT).