rntpc_react-native-background-fetch:基于 react-native-background-fetch 的 OpenHarmony 适配版,后台周期性任务唤醒

基于 react-native-background-fetch 的 OpenHarmony 适配版,后台周期性任务唤醒

Branch4Tags7

Document Template: v0.4.2

react-native-background-fetch

English | 简体中文

This project is based on react-native-background-fetch.

The repository for this third-party library has been migrated to AtomGit, and it now supports direct download from npm. The new package name is: @react-native-ohos/react-native-background-fetch. The specific version relationships are as follows:

Name Version(Npm Address) Release Information Supported RN Version Supported Autolink Compile API Version Community Baseline Version Source code address
@react-native-ohos/react-native-background-fetch ~4.4.0 (In development) AtomGit Releases 0.82.* Yes API12+ 4.2.8 br_rnoh0.82
@react-native-ohos/react-native-background-fetch ~4.3.0 AtomGit Releases 0.77.* No API12+ 4.2.8 br_rnoh0.77
@react-native-ohos/react-native-background-fetch ~4.2.7 AtomGit Releases 0.72.* Yes API12+ 4.2.5 br_rnoh0.72
@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 sig

Introduction

react-native-background-fetch is a React Native background task scheduling library that provides periodic Background Fetch capabilities on iOS and Android.
The OpenHarmony side is implemented based on the system Work Scheduler (workScheduler) mechanism. It supports configuring the minimum fetch interval and task constraints such as network type, charging status, storage space, and device idle state, and requires calling BackgroundFetch.finish to notify the system when a task is complete.

Installation

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
Supported Autolink Supported RN Version
~ 4.4.0 Yes 0.82.*

Projects using Autolink need to be configured according to this document, Autolink framework guide: https://atomgit.com/CPF-RN/ohos_react_native/blob/main/docs/en/02-development/02-development-guide/autolinking.md

If the version you are using supports Autolink, no further operations are required, and you can skip this chapter.

ManualLink: This step provides guidance for manually configuring native dependencies.

Open the harmony directory of the OpenHarmony project in DevEco Studio.

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" : "file:../node_modules/@react-native-oh/react-native-harmony/react_native_openharmony.har" // a locally available HAR package
    // "@rnoh/react-native-openharmony": "~0.82.18" // ohpm version
    // "@rnoh/react-native-openharmony" : "./react_native_openharmony" // source code directory
  }
}

2. Introducing Native Code

Currently, two methods are available:

  • Introduce through the har package.
  • Directly link to the source code.

Method 1 (recommended): Introduce through the har package.

The har package is located in the `harmony` folder of the third-party library installation path.

Open entry/oh-package.json5 file and add the following dependencies:

"dependencies": {
    "@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](https://atomgit.com/CPF-RN/usage-docs/blob/master/en/link-source-code.md).

3. Configuring CMakeLists and Introducing RNBackgroundFetchPackage

Open entry/src/main/cpp/CMakeLists.txt and add the following code:

project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(NODE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../node_modules")
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../react-native-harmony/harmony/cpp")
set(LOG_VERBOSITY_LEVEL 1)
set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie")
set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
add_compile_definitions(WITH_HITRACE_SYSTRACE)

add_subdirectory("${RNOH_CPP_DIR}" ./rn)

# RNOH_BEGIN: manual_package_linking_1
add_subdirectory("../../../../sample_package/src/main/cpp" ./sample-package)
+ add_subdirectory("${OH_MODULES}/@react-native-ohos/react-native-background-fetch/src/main/cpp" ./background_fetch)
# RNOH_END: manual_package_linking_1

file(GLOB GENERATED_CPP_FILES "./generated/*.cpp")

add_library(rnoh_app SHARED
    ${GENERATED_CPP_FILES}
    "./PackageProvider.cpp"
    "${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)
target_link_libraries(rnoh_app PUBLIC rnoh)

# RNOH_BEGIN: manual_package_linking_2
target_link_libraries(rnoh_app PUBLIC rnoh_sample_package)
+ 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 "SamplePackage.h"
+ #include "RNBackgroundFetchPackage.h"

using namespace rnoh;

std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
    return {
      std::make_shared<SamplePackage>(ctx),
+     std::make_shared<RNBackgroundFetchPackage>(ctx)
    };
}

4. Introducing RNBackgroundFetchPackage to ArkTS

Open entry/src/main/ets/RNPackagesFactory.ets and add the following code:

  ...
+ import { RNBackgroundFetchPackage } from '@react-native-ohos/react-native-background-fetch/ts';

export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
  return [
+   new RNBackgroundFetchPackage(ctx)
  ];
}

Necessary Configuration

The content of this module cannot be automatically generated by autolink and must always be manually configured.

Introducing RNBackgroundFetchExtensionAbility to ArkTS (This module always requires manual configuration)

  1. Open entry/src/main/ets, 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 {
  // Callback when the delayed task starts
  onWorkStart(workInfo: workScheduler.WorkInfo) {
    super.onWorkStart(workInfo);
  }

  // Callback when the delayed task stops
  onWorkStop(workInfo: workScheduler.WorkInfo) {
    super.onWorkStop(workInfo);
  }
}
  1. Register WorkSchedulerExtensionAbility in the entry/src/main/module.json5 configuration file and set the following tags:
{
  "module": {
    "extensionAbilities": [
      {
        "name": "MyWorkSchedulerExtensionAbility",
        "srcEntry": "./ets/WorkSchedulerExtension/WorkSchedulerExtension.ets",
        "type": "workScheduler"
      }
    ]
  }
}

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.

Constraints

Compatibility

This document is verified based on the following versions:

  1. RNOH: 0.82.1; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;

API requirements

All versions of the current third-party library have implemented version isolation, supporting compilation in `API12+` projects and execution on `API12+` ROMs.

Example

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,
} from "react-native";
import { Header, Colors } from "react-native/Libraries/NewAppScreen";
import BackgroundFetch from "react-native-background-fetch";
import {
  BackgroundFetchConfig,
  TaskConfig,
} from "react-native-background-fetch/src/RNBackgroundFetch";

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) => `${item.taskId}-${item.timestamp}`}
            />
          </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;

How to Use

Initializing the background fetch task

import BackgroundFetch from "react-native-background-fetch";

// BackgroundFetch event handler
const onEvent = async (taskId) => {
  console.log("[BackgroundFetch] task: ", taskId);
  // Do your background work...
  // IMPORTANT: You must call finish to signal that your task is complete
  BackgroundFetch.finish(taskId);
};

// Timeout callback: executed when your task has exceeded its allowed running time
const onTimeout = async (taskId) => {
  console.warn("[BackgroundFetch] TIMEOUT task: ", taskId);
  BackgroundFetch.finish(taskId);
};

// Initialize BackgroundFetch when the component mounts
// minimumFetchInterval is in minutes; on OpenHarmony the default and minimum value is 20 minutes
let status = await BackgroundFetch.configure(
  { minimumFetchInterval: 20 },
  onEvent,
  onTimeout
);

Scheduling a custom task

BackgroundFetch.scheduleTask({
  taskId: "com.foo.customtask",
  delay: 20 * 60 * 1000, // minimum interval in milliseconds
  periodic: false,       // false means a one-shot task
  requiresCharging: false,
  requiredNetworkType: BackgroundFetch.NETWORK_TYPE_ANY,
});

Querying the background fetch status

const status = await BackgroundFetch.status();
if (status === BackgroundFetch.STATUS_AVAILABLE) {
  // Background fetch is available and enabled
} else if (status === BackgroundFetch.STATUS_DENIED) {
  // The user explicitly disabled background behavior
}

Stopping the fetch events

// Stop a specific task
await BackgroundFetch.stop("com.foo.customtask");
// Stop all fetch events when taskId is omitted
await BackgroundFetch.stop();

Available APIs

The **Platform** column indicates the platform where the properties are supported in the original third-party library.

If the **OpenHarmony Platform Support** is **Yes**, it means that the OpenHarmony 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 Type Parameter Type Return Value Required Platform OpenHarmony Platform Support Description
configure function (config: BackgroundFetchConfig, onEvent: (taskId: string) => void, onTimeout?: (taskId: string) => void) Promise<BackgroundFetchStatus> Yes All Partially Initial configuration of BackgroundFetch, including config-options and Fetch-callback. The start method will automatically be executed.
scheduleTask function (config: TaskConfig) Promise<boolean> No All Partially Add an extra fetch event listener in addition to the one initially provided to configure.
start function / Promise<BackgroundFetchStatus> No All Yes Start subscribing to fetch events.
stop function (taskId?: string) Promise<boolean> No All Yes Stop subscribing to fetch events.
finish function (taskId: string) void No All Yes You must execute finish within your fetch-callback to signal completion of your task.
status function (callback?: (status: BackgroundFetchStatus) => void) Promise<BackgroundFetchStatus> No All Yes Query the BackgroundFetch API status

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 Parameter Type Default Value Required Platform OpenHarmony Platform Support Description
BackgroundFetchConfig.minimumFetchInterval number 15 No All Yes The minimum interval in minutes to execute background fetch events. Defaults to 15 minutes. Minimum is 15 minutes. On the OpenHarmony side, both the default and the minimum are 20 minutes.
BackgroundFetchConfig.stopOnTerminate boolean true No Android No Set false to continue background-fetch events after user terminates the app. Default to true.
BackgroundFetchConfig.startOnBoot boolean false No Android No Set true to initiate background-fetch events when the device is rebooted. Defaults to false.
BackgroundFetchConfig.enableHeadless boolean None No Android No Set true to enable Headless mechanism for handling fetch events after app termination.
BackgroundFetchConfig.forceAlarmManager boolean None No Android No 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.
BackgroundFetchConfig.requiredNetworkType NetworkType None No Android Partially (NETWORK_TYPE_ANY, NETWORK_TYPE_CELLULAR, NETWORK_TYPE_UNMETERED) Set detailed description of the kind of network your job requires.
BackgroundFetchConfig.requiresBatteryNotLow boolean None No Android Yes Specify that to run this job, the device's battery level must not be low.
BackgroundFetchConfig.requiresStorageNotLow boolean None No Android Yes Specify that to run this job, the device's available storage must not be low.
BackgroundFetchConfig.requiresCharging boolean None No Android Yes 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).
BackgroundFetchConfig.requiresDeviceIdle boolean None No Android Yes When set true, ensure that this job will not run if the device is in active use.

BackgroundFetch.scheduleTask()

BackgroundFetch.scheduleTask(config: TaskConfig): Promise<boolean>;
Name Parameter Type Default Value Required Platform OpenHarmony Platform Support Description
TaskConfig.taskId string None Yes All Yes The name of the task.
TaskConfig.delay number None Yes All Yes The minimum interval in milliseconds to execute this task.
TaskConfig.periodic boolean None No All Yes Whether this task will continue executing or just a "one-shot".
TaskConfig.requiresNetworkConnectivity boolean None No All Yes When set true, ensure that this job will run if the device has network connection
TaskConfig.stopOnTerminate boolean true No Android No Set false to continue background-fetch events after user terminates the app. Default to true.
TaskConfig.startOnBoot boolean false No Android No Set true to initiate background-fetch events when the device is rebooted. Defaults to false.
TaskConfig.enableHeadless boolean None No Android No Set true to enable Headless mechanism for handling fetch events after app termination.
TaskConfig.forceAlarmManager boolean None No Android No 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.
TaskConfig.requiredNetworkType NetworkType None No Android Partially (NETWORK_TYPE_ANY, NETWORK_TYPE_CELLULAR, NETWORK_TYPE_UNMETERED) Set detailed description of the kind of network your job requires.
TaskConfig.requiresBatteryNotLow boolean None No Android Yes Specify that to run this task, the device's battery level must not be low.
TaskConfig.requiresStorageNotLow boolean None No Android Yes Specify that to run this task, the device's available storage must not be low.
TaskConfig.requiresCharging boolean None No Android Yes Specify that to run this task, the device must be charging (or be a non-battery-powered device connected to permanent power, such as Android TV devices).
TaskConfig.requiresDeviceIdle boolean None No Android Yes When set true, ensure that this task will not run if the device is in active use.

BackgroundFetch.stop()

BackgroundFetch.stop(taskId?: string): Promise<boolean>;
Name Parameter Type Default Value Required Platform OpenHarmony Platform Support Description
taskId string None No All Yes The name of the task.

BackgroundFetch.finish()

BackgroundFetch.finish(taskId: string): void;
Name Parameter Type Default Value Required Platform OpenHarmony Platform Support Description
taskId string None Yes All Yes The name of the task.

BackgroundFetch.status()

BackgroundFetch.status(callback?: (status: BackgroundFetchStatus) => void): Promise<BackgroundFetchStatus>;
Name Parameter Type Default Value Required Platform OpenHarmony Platform Support Description
callback Function None No All Yes Callback for the background fetch API status.

BackgroundFetchStatus

Name Parameter Type Default Value Required Platform OpenHarmony Platform Support Description
BackgroundFetchStatus.STATUS_RESTRICTED BackgroundFetchStatus None Yes iOS No 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.STATUS_DENIED BackgroundFetchStatus None Yes iOS No The user explicitly disabled background behavior for this app or for the whole system.
BackgroundFetchStatus.STATUS_AVAILABLE BackgroundFetchStatus None Yes All Yes Background fetch is available and enabled.

Known Issues

  • Some parameters of the configure interface do not support OpenHarmony: issue#2
  • Some parameters of the scheduleTask interface do not support OpenHarmony: issue#4
  • The values of requiredNetworkType are mapped by the native side to workScheduler network types: NETWORK_TYPE_UNMETERED falls back to NETWORK_TYPE_WIFI, and NETWORK_TYPE_NOT_ROAMING has no equivalent constraint (no effect after being set), so the actual behavior may differ from expectations

Other

  • 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 OpenHarmony, 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/en/doc/harmonyos-guides-V5/work-scheduler-V5

Directory Structure

/rntpc_react-native-background-fetch  # Project root directory
├── harmony                              # OpenHarmony adaptation code
│   ├── background_fetch.har             # har package
│   └── background_fetch                 # Core OpenHarmony adaptation code
│       ├── index.ets                    # Entry file of the OpenHarmony adaptation code
│       ├── ts.ets                       # TypeScript export entry
│       ├── oh-package.json5             # ohpm dependency configuration file
│       └── src/main
│           ├── ets                      # ArkTS side code
│           │   ├── RNBackgroundFetchPackage.ets        # Module registration Package
│           │   ├── RNBackgroundFetchModule.ts          # TurboModule implementation
│           │   ├── Type.ts                             # Type definitions
│           │   ├── Logger.ts                           # Logger utility
│           │   ├── WorkSchedulerExtension              # Delayed task callback directory
│           │   │   └── WorkSchedulerExtension.ets      # ExtensionAbility for delayed task callbacks
│           │   └── generated                           # Codegen generated code
│           ├── cpp                      # C++ adaptation code (RNBackgroundFetchPackage.h, CMakeLists.txt, generated, etc.)
│           ├── module.json5             # Module configuration file
│           └── resources                # Resource files
├── src
│   └── RNBackgroundFetch.ts             # TurboModule spec file
├── example                              # Example project
├── index.js                             # RN side entry file
├── index.d.ts                           # RN side type declaration file
├── app.plugin.js                        # Expo config plugin
├── RNBackgroundFetch.podspec            # iOS podspec configuration file
├── babel.config.js                      # babel configuration file
├── tsconfig.json                        # TypeScript configuration file
├── tsconfig.build.json                  # TypeScript build configuration file
├── CHANGELOG.md                         # Version change log
├── README.OpenSource                    # Open-source information statement
├── OAT.xml                              # Open-source audit tool configuration file
├── COMMITTERS.md                        # Committers list
├── LICENSE                              # License file
├── README.md                            # Chinese installation and usage instructions
├── README_en.md                          # English installation and usage instructions
└── package.json                         # Package configuration file

How to Contribute

If you find any problem during the use, you can submit an Issue. Of course, we also welcome you to submit a PR.

License

This project is based on The MIT License (MIT). Feel free to enjoy and participate in open source.

Introduction

基于 react-native-background-fetch 的 OpenHarmony 适配版,后台周期性任务唤醒

Customize your domain