rntpc_react-native-compass-heading:基于 react-native-compass-heading 的 OpenHarmony 适配版,罗盘方向(磁力计朝向)监听

基于 react-native-compass-heading 的 OpenHarmony 适配版,罗盘方向(磁力计朝向)监听

Branch4Tags7

Document Template: v0.4.2

react-native-compass-heading

This project is developed based on react-native-compass-heading.

The repository of this third-party library has been migrated to GitCode, and it supports direct download from npm. The new package name is @react-native-ohos/react-native-compass-heading. The version correspondence is 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-compass-heading ~2.1.0 GitCode Releases 0.82.*/0.84.*/0.86.* Yes API12+ 2.0.2 master
@react-native-ohos/react-native-compass-heading ~2.0.3 GitCode Releases 0.77.* No API12+ 2.0.2 br_rnoh0.77
@react-native-ohos/react-native-compass-heading ~1.5.1 GitCode Releases 0.72.* Yes API12+ 1.5.0 br_rnoh0.72
@react-native-oh-tpl/react-native-compass-heading <=1.5.0-0.0.2@deprecated Github Releases(deprecated) 0.72.* No API12+ 1.5.0 Github(deprecated)

Introduction

react-native-compass-heading is used to listen to the device's compass heading information. After registering a callback via the start() interface, developers can obtain the device's heading and accuracy in real time; the stop() interface stops listening and releases sensor resources. It is applicable to map navigation orientation, AR pointing and compass applications.

Installation

Enter the project directory and run the following command:

npm

npm install @react-native-ohos/react-native-compass-heading

yarn

yarn add @react-native-ohos/react-native-compass-heading
Support AutoLink RN Framework Version
~2.1.0 Yes 0.82/0.84/0.86
~2.0.3 No 0.77
~1.5.1 Yes 0.72
<=1.5.0-0.0.2@deprecated No 0.72

For projects using AutoLink, please refer to the Autolinking guide: https://gitcode.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 is a guide for manually configuring native dependencies

First, open the OpenHarmony project harmony in the project using DevEco Studio.

1. Overrides RN SDK

To make the project depend on the same version of the RN SDK, you need to add the overrides field in the root directory's oh-package.json5 of the project, pointing to the RN SDK version that the project needs to use.

Please read the official documentation for the function of this field.

{
  ...
  "overrides": {
    "@rnoh/react-native-openharmony" : "./react_native_openharmony"
  }
}

2. Introducing Native Code

There are currently two methods:

  • Import via har package;
  • Link source code directly.

Method 1: Import via har package (recommended)

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

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

"dependencies": {
    "@rnoh/react-native-openharmony": "file:../react_native_openharmony",
    "@react-native-ohos/react-native-compass-heading": "file:../../node_modules/@react-native-ohos/react-native-compass-heading/harmony/compass_heading.har"
  }

Click the sync button in the upper right corner, or execute in the command line terminal:

cd entry
ohpm install

Method 2: Link source code directly

To link source code directly, please refer to [Direct Source Code Linking Instructions](./link-source-code.md).

3. Configuring CMakeLists and Introducing RNCompassHeadingPackage

If you are using version <=1.5.0-0.0.2, please skip this chapter.

Open entry/src/main/cpp/CMakeLists.txt and 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-compass-heading/src/main/cpp" ./compass_heading)
# RNOH_END: manual_package_linking_1

# RNOH_BEGIN: manual_package_linking_2
+ target_link_libraries(rnoh_app PUBLIC rnoh_compass_heading)
# RNOH_END: manual_package_linking_2

Open entry/src/main/cpp/PackageProvider.cpp and add:

#include "RNOH/PackageProvider.h"
#include "generated/RNOHGeneratedPackage.h"
+ #include "RNCompassHeadingPackage.h"

using namespace rnoh;

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

4. Introducing RNCompassHeadingPackage on the ArkTS Side

Open entry/src/main/ets/RNPackagesFactory.ts and add:

  ...
+ import {RNCompassHeadingPackage} from '@react-native-ohos/react-native-compass-heading/ts';

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

Running

Click the sync button in the upper right corner, or execute in the command line terminal:

cd entry
ohpm install

Then compile and run the project.

Constraints

Compatibility

The content of this document has been verified on the following versions:

  1. RNOH: 0.86.1 (react-native 0.86.3); SDK: API12+; IDE: DevEco Studio 26.0.0; ROM: HarmonyOS 7.0.0.109(SP8C00E105R5P2);
  2. RNOH: 0.84.2; SDK: API12+; IDE: DevEco Studio 26.0.0; ROM: HarmonyOS 7.0.0.109(SP8C00E105R5P2);

Permission Requirements

  • Compass heading data depends on the system orientation sensor. The application needs to apply for sensor permissions in entry/src/main/module.json5:
requestPermissions: [
  {
    name: "ohos.permission.ACCELEROMETER",
  },
  {
    name: "ohos.permission.GYROSCOPE",
  },
],

Example

The following code demonstrates a basic usage scenario of this library:

The library name in the import statement remains unchanged.

import * as React from "react";
import { useState, useEffect } from "react";
import { StyleSheet, View, Text, ScrollView } from "react-native";
import CompassHeading from "react-native-compass-heading";

const App = () => {
  const [heading, setHeading] = useState(0);
  const [accuracy, setAccuracy] = useState(0);

  useEffect(() => {
    const degree_update_rate = 3;
    CompassHeading.start(degree_update_rate, (data) => {
      setHeading(data.heading);
      setAccuracy(data.accuracy);
    });
    return () => {
      CompassHeading.stop();
    };
  }, []);

  return (
    <ScrollView>
      <View style={styles.container}>
        <Text>{"heading: " + heading}</Text>
        <Text>{"accuracy: " + accuracy}</Text>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
    height: 400,
  },
});

export default App;

How to Use

Start Listening

Call the start() interface to subscribe to compass data. filter is the refresh threshold in degrees; a callback is triggered only when the heading changes by more than this value, and null is treated as 0. If a listener already exists, the old one is stopped automatically before the new one is registered.

import CompassHeading from "react-native-compass-heading";

const degree_update_rate = 3; // refresh threshold: report only when heading changes by more than 3 degrees

CompassHeading.start(degree_update_rate, ({ heading, accuracy }) => {
  // heading: orientation angle (0-360, with screen rotation compensation)
  // accuracy: sensor precision
  console.log(heading, accuracy);
});

Handling Callback Data

The callback data contains heading and accuracy. heading indicates the direction the top of the device points to (0-360), with rotation compensation applied on orientation changes so the semantics stay consistent.

import CompassHeading from "react-native-compass-heading";

CompassHeading.start(3, (data) => {
  const heading = data.heading;   // orientation angle (0-360, with rotation compensation)
  const accuracy = data.accuracy; // sensor precision
  console.log(heading, accuracy);
});

Stop Listening

Call the stop() interface when leaving the page or when compass data is no longer needed. It stops event delivery and releases sensor resources, and is safe to call even when not started.

import CompassHeading from "react-native-compass-heading";

CompassHeading.stop(); // stop listening and release resources directly

Available APIs

The "Platform" column indicates the platforms supported by the original third-party library.

The "OpenHarmony Platform Support" column: yes means the property is supported on the OpenHarmony platform; no means not supported; partially means partially supported. The usage is consistent across platforms, and the effect is benchmarked against iOS or Android.

Components

None.

Properties

None.

API

Name Type Parameter Type Return Value Required Platform OpenHarmony Platform Support Description
start function filter: number; callback: (data: {heading: number, accuracy: number}) => void Promise<void> Yes Android/iOS Yes Start the compass, subscribe to the orientation sensor and register the HeadingUpdated event callback; null filter is treated as 0; calling it again stops the previous listener first.
stop function none Promise<void> No Android/iOS Yes Stop the compass, remove the event listener and unregister the sensor subscription; safe to call when not started.
addListener function eventName: string void No Android/iOS Yes Event contract method invoked by the RNOH event mechanism; developers do not need to call it directly.
removeListeners function count: number void No Android/iOS Yes Event contract method invoked by the RNOH event mechanism; developers do not need to call it directly.

Known Issues

None.

Other

None.

Directory Structure

/rntpc_react-native-compass-heading  # Project root directory
├── harmony              # Adaptation code
│    └─ compass_heading.har   # har package
│    └─ compass_heading       # Core adaptation code
│          └─ src/main/ets
│              └─ RNCompassHeadingPackage.ets   # Package registration
│              └─ RNCompassHeadingTurboModule.ts # TurboModule implementation
├── src                  # RN code
│    └─ index.tsx  # Entry file
│    └─ NativeCompassHeading.tsx # TurboModule type definitions
├── jest.config.js       # Jest configuration (referenced by the test script via --config)
├── xts                  # JS unit tests
│    └─ jest.setup.js # Test setup (mocks react-native)
│    └─ index.test.js # Test cases
├── README.md           # Chinese installation and usage instructions
├── README_en.md        # English installation and usage instructions

How to Contribute

If you encounter any problems during use, you can submit an Issue. Of course, PRs are also very welcome.

License

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

Introduction

基于 react-native-compass-heading 的 OpenHarmony 适配版,罗盘方向(磁力计朝向)监听

Customize your domain