### Start Metro Server
Source: https://github.com/auroramaster/ohos_react_native/blob/main/README.md
Starts the Metro server from the tester directory.
```bash
npm start
```
--------------------------------
### Start Packager
Source: https://github.com/auroramaster/ohos_react_native/blob/main/tester/harmony/react_native_openharmony/src/main/cpp/third-party/rn/ReactCommon/hermes/inspector/README.md
Starts the JavaScript packager, which is a prerequisite for testing integration with apps.
```bash
$ js1 run
```
--------------------------------
### Start Metro Server (Yarn)
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/FrameNodeSample/GenerateBundle/README.md
Start the Metro bundler using Yarn. This is required before running the application.
```bash
yarn start
```
--------------------------------
### Install Dependencies and Pack
Source: https://github.com/auroramaster/ohos_react_native/blob/main/README.md
Installs dependencies and packs the package for react-native-harmony-cli.
```bash
npm i && npm pack
```
--------------------------------
### Start Metro Bundler for Real-time Updates
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/Sample/README.md
Connect to a real device and run these commands to use the Metro service for real-time bundle updates. This forwards the necessary port and starts the Metro bundler.
```bash
hdc rport tcp:8081 tcp:8081
npm run start
```
--------------------------------
### onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Starts a new UIAbility instance after it has been started and running in the foreground and switched to the background.
```APIDOC
## onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam)
### Description
Starts a new UIAbility instance after it has been started and running in the foreground and switched to the background.
### Method
SDK Method
### Endpoint
rnInstancesCoordinator?.onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam)
### Parameters
#### Method Parameters
- **want** ([Want](https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-app-ability-want-V5)) - Required - Want information, such as the ability name and bundle name.
- **launchParam** ([AbilityConstant.LaunchParam](https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-app-ability-abilityconstant-V5#abilityconstantlaunchparam)) - Required - Reason for the UIAbility startup and the last abnormal exit.
```
--------------------------------
### Start Metro Server
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/Capture_bundle/ReactProject/README.md
Start the Metro bundler, which is essential for React Native development. Run this command from the root of your project.
```bash
# using npm
npm start
# OR using Yarn
yarn start
```
--------------------------------
### Start React DevTools
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/debugging.md
Run this command in a separate command line tool to start the standalone React DevTools.
```PowerShell
npx react-devtools
```
--------------------------------
### Image Path Example in Sandbox
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/faqs/usage-faqs.md
This example shows how to reference an image within a sandbox environment. The path is constructed using the bundle path as a prefix and the relative project path as a suffix. The 'assets' directory is not present in this scenario.
```javascript
```
--------------------------------
### onNewWant Method
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Starts a new UIAbility instance after it has been started and running in the foreground and switched to the background.
```typescript
rnInstancesCoordinator?.onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void
```
--------------------------------
### Project Setup and Variable Definitions
Source: https://github.com/auroramaster/ohos_react_native/blob/main/tester/harmony/entry/src/main/cpp/CMakeLists.txt
Sets up the project name, minimum CMake version, and defines key directories and build flags. This is essential for configuring the build environment.
```cmake
project(rnapp)
cmake_minimum_required(VERSION 3.5)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(NODE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../node_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../oh_modules/@rnoh/react-native-openharmony/src/main/cpp")
set(RNOH_GENERATED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/generated")
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)
set(OH_MODULES_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../oh_modules") # required by 'autolink_libraries' — TODO: consider passing as a parameter
```
--------------------------------
### Install React Native Harmony Dependency
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/Sample/README.md
Install the react-native-harmony dependency in the SampleProject/MainProject directory. Replace x.x.x with the specific version required.
```bash
npm i @react-native-oh/react-native-harmony@x.x.x
```
--------------------------------
### Install Dependencies in Tester Directory
Source: https://github.com/auroramaster/ohos_react_native/blob/main/README.md
Installs dependencies for the tester directory. Note the use of 'npm run i' instead of 'npm i'.
```bash
npm run i
```
--------------------------------
### Install Metro for React Native
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/rn-js-bundle.md
Install the latest version of Metro and metro-core as development dependencies using npm or yarn.
```powershell
npm install --save-dev metro metro-core
```
```powershell
yarn add --dev metro metro-core
```
--------------------------------
### RNInstance Configuration and Setup
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Configure and set up a React Native instance with various options including package management, feature flags, and initial properties. Ensure correct bundle loading sequence by checking bundle execution status.
```javascript
RNApp({
// Used to specify the configuration of the React Native instance.
rnInstanceConfig: {
// External function package management (providing additional functions and features for the framework)
createRNPackages,
// Whether to enable the C++ native text measuring API.
enableNDKTextMeasuring: true,
// Whether to enable the background executor.
enableBackgroundExecutor: false,
// Whether to use the CAPI architecture. Defaults to true.
enableCAPIArchitecture: true,
// Name of the custom ArkTS component
arkTsComponentNames,
},
// Pass the initial properties to the React Native application.
initialProps: { "foo": "bar" } as Record,
appKey: "app_name",
// Custom component builder
wrappedCustomRNComponentBuilder: wrappedCustomRNComponentBuilder,
// Call the method to be executed in 'RNInstance'. This callback is called before an rnInstance is created and a surface is visible.
onSetUp: (rnInstance) => {
rnInstance.enableFeatureFlag("ENABLE_RN_INSTANCE_CLEAN_UP")
},
// Used to specify the mode of providing the JavaScript bundle file.
jsBundleProvider: new TraceJSBundleProviderDecorator(
new AnyJSBundleProvider([
new MetroJSBundleProvider(),
/**
* Note: Load a bundle from '/data/app/el2/100/base/com.rnoh.tester/files/bundle.harmony.js'. Path mismatch is caused by the application sandbox on OpenHarmony.
*/
new FileJSBundleProvider('/data/storage/el2/base/files/bundle.harmony.js'),
new ResourceJSBundleProvider(this.rnohCoreContext.uiAbilityContext.resourceManager, 'hermes_bundle.hbc'),
new ResourceJSBundleProvider(this.rnohCoreContext.uiAbilityContext.resourceManager, 'bundle.harmony.js')
]),
this.rnohCoreContext.logger),
})
```
--------------------------------
### Project and Module Setup
Source: https://github.com/auroramaster/ohos_react_native/blob/main/tester/harmony/multi_surface/src/main/cpp/CMakeLists.txt
Initializes the CMake project, sets the minimum required version, and defines various source and module directories. It also configures build flags and defines preprocessor symbols.
```cmake
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(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules/@rnoh/react-native-openharmony/src/main/cpp")
set(LOG_VERBOSITY_LEVEL 1)
set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
add_compile_definitions(WITH_HITRACE_SYSTRACE)
```
--------------------------------
### Initialize React Native Project
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/environment-setup.md
Use this command to create a new React Native project with a specific version. This command is provided by Node.js and does not require separate installation.
```bash
npx react-native@0.72.5 init AwesomeProject --version 0.72.5
```
--------------------------------
### Install Hermes Engine
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/common-development-scenarios.md
Install the Hermes engine globally using npm. This is a prerequisite for converting JavaScript bundles to .hbc format.
```powershell
npm install -g hermes-engine
```
--------------------------------
### Install npm Packages
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/faqs/compilation-faqs.md
Run 'npm install' to resolve issues where 'react-native' is not recognized as an internal or external command. Ensure your package.json is correctly configured before running the command.
```powershell
npm install
```
--------------------------------
### Project and Source Directory Setup
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/FrameNodeSample/FrameNodeSampleApp/entry/src/main/cpp/CMakeLists.txt
Sets the project name, minimum CMake version, and defines source directories for the application and React Native components.
```cmake
project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
set(OH_MODULE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${OH_MODULE_DIR}/@rnoh/react-native-openharmony/src/main/cpp")
set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
add_subdirectory("${RNOH_CPP_DIR}" ./rn)
```
--------------------------------
### Install JSI Header Files
Source: https://github.com/auroramaster/ohos_react_native/blob/main/tester/harmony/react_native_openharmony/src/main/cpp/third-party/rn/ReactCommon/jsi/jsi/CMakeLists.txt
Installs JSI header files from the API/jsi directory to the 'include' destination, excluding files in 'test' subdirectories.
```cmake
install(DIRECTORY "${PROJECT_SOURCE_DIR}/API/jsi/" DESTINATION include
FILES_MATCHING PATTERN "*.h"
PATTERN "test" EXCLUDE)
```
--------------------------------
### Installing Failure Signal Handler
Source: https://github.com/auroramaster/ohos_react_native/blob/main/tester/harmony/react_native_openharmony/src/main/cpp/third-party/glog/doc/glog.html
Install a signal handler using google::InstallFailureSignalHandler() to dump useful information when the program crashes on certain signals like SIGSEGV. By default, it writes to standard error.
```cpp
google::InstallFailureSignalHandler();
```
--------------------------------
### Project and Module Path Setup
Source: https://github.com/auroramaster/ohos_react_native/blob/main/template/template/harmony/entry/src/main/cpp/CMakeLists.txt
Sets the project name, minimum CMake version, and defines directories for OHOS modules and React Native C++ source files.
```cmake
project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
set(OH_MODULE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../oh_modules")
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(RNOH_CPP_DIR "${OH_MODULE_DIR}/@rnoh/react-native-openharmony/src/main/cpp")
set(RNOH_GENERATED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/generated")
```
--------------------------------
### Install React Native OpenHarmony Package
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/environment-setup.md
Install the React Native OpenHarmony package using ohpm in the 'entry' directory of your project. This command generates the 'oh_modules' folder.
```Bash
ohpm i @rnoh/react-native-openharmony@x.x.x
```
--------------------------------
### Project Setup and Library Definition
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/demo_without_rnAbility/NativeProject/library/src/main/cpp/CMakeLists.txt
Configures the CMake project, sets directories for React Native OpenHarmony modules, and defines the main application library.
```cmake
# Copyright (c) 2024 Huawei Technologies Co., Ltd.
#
# This source code is licensed under the MIT license found in the
# LICENSE-MIT file in the root directory of this source tree.
project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
set(OH_MODULE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${OH_MODULE_DIR}/@rnoh/react-native-openharmony/src/main/cpp")
set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
add_subdirectory("${RNOH_CPP_DIR}" ./rn)
add_library(rnoh_app SHARED
"./PackageProvider.cpp"
"${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)
add_compile_definitions(WITH_HITRACE_SYSTRACE)
target_link_libraries(rnoh_app PUBLIC rnoh)
```
--------------------------------
### Run Android App (npm)
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/FrameNodeSample/GenerateBundle/README.md
Start the Android application using npm. Ensure the Metro server is running in a separate terminal.
```bash
npm run android
```
--------------------------------
### Registering NODE_ON_CLICK and NODE_ON_HOVER Events
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/architecture.md
Example of registering click and hover events for a stack node in C++.
```cpp
StackNode::StackNode()
:ArkUINode(NativeNodeAPi::getInstance()->createNode(ArkUI_NodeType::ARKUI_NODE_STACK)),
m_stackNodeDelegate(nullptr)
{
maybeThrow(NativeNodeApi::getInstance()->registerNodeEvent(m_nodeHandle,NODE_ON_CLICK,0,this));
maybeThrow(NativeNodeApi::getInstance()->registerNodeEvent(m_nodeHandle,NODE_ON_HOVER,0,this));
}
```
--------------------------------
### Run iOS App (npm)
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/FrameNodeSample/GenerateBundle/README.md
Start the iOS application using npm. Ensure the Metro server is running in a separate terminal.
```bash
npm run ios
```
--------------------------------
### Initialize React Native Project (Skip Install)
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/environment-setup.md
When initializing a React Native project on macOS, this command skips the initial download of iOS dependency libraries, which can be time-consuming. The libraries will be downloaded as needed, without affecting OpenHarmony project development.
```bash
npx react-native@0.72.5 init AwesomeProject --version 0.72.5 --skip-install
```
--------------------------------
### Configure Custom Metro Config in package.json
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/debugging.md
Specify a custom Metro configuration file for the start script in package.json. This allows for project-specific Metro settings.
```json
// package.json
···
"scripts": {
···
"start": "react-native start --config metro.config.harmony.js",
···
}
···
```
--------------------------------
### Set glog Flags via Command Line
Source: https://github.com/auroramaster/ohos_react_native/blob/main/tester/harmony/react_native_openharmony/src/main/cpp/third-party/glog/doc/glog.html
Demonstrates how to enable glog flags like 'logtostderr' using command-line arguments when Google gflags is installed.
```bash
./your_application --logtostderr=1
```
--------------------------------
### Configuring codegen-harmony Command
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/Codegen.md
Set up the `codegen-harmony` command in your `package.json` scripts for generating code. This example shows how to specify output paths for generated files.
```json
"scripts": {
...
"codegen": "react-native codegen-harmony --cpp-output-path ./entry/src/main/cpp/generated --rnoh-module-path ./entry/oh_modules/@rnoh/react-native-openharmony"
}
```
--------------------------------
### Run Android App (Yarn)
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/FrameNodeSample/GenerateBundle/README.md
Start the Android application using Yarn. Ensure the Metro server is running in a separate terminal.
```bash
yarn android
```
--------------------------------
### Configure Query Schemes in module.json5
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/zh-cn/faqs/使用类FAQ.md
To resolve issues with Linking.canOpenURL() returning false, ensure the target application's scheme is configured in the module.json5 file under the querySchemes field. For example, to launch a browser, include 'http' and 'https'.
```json5
"querySchemes": ["http", "https"],
```
--------------------------------
### Start and Finish Trace using hiTraceMeter
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/debugging.md
This ArkTS snippet demonstrates adding a trace using the @ohos.hiTraceMeter module, specifying a name and an identification flag.
```TypeScript
import hiTrace from '@ohos.hiTraceMeter';
...
hiTrace.startTrace(`myTrace`, 0)
// do something
hiTrace.finishTrace(`myTrace`, 0)
```
--------------------------------
### Initialize and Log with glog
Source: https://github.com/auroramaster/ohos_react_native/blob/main/tester/harmony/react_native_openharmony/src/main/cpp/third-party/glog/doc/glog.html
Initializes the glog library and demonstrates logging an INFO message. Requires including the glog/logging.h header.
```cpp
#include
int main(int argc, char* argv[]) {
// Initialize Google's logging library.
google::InitGoogleLogging(argv[0]);
// ...
LOG(INFO) << "Found " << num_cookies << " cookies";
}
```
--------------------------------
### OpenHarmony Bundle Command Example
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/rn-js-bundle.md
Execute the OpenHarmony bundle command to package your React Native application. This command supports various options for controlling the build process, such as entry file, development mode, and output paths.
```powershell
react-native bundle-harmony --entry-file index.harmony.js --dev false
```
--------------------------------
### Project Setup and Source Directories
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/FabricComponentSample/NativeProject/entry/src/main/cpp/CMakeLists.txt
Configures the project name, minimum CMake version, and defines source directories for the React Native OH project and its modules.
```cmake
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")
file(REAL_PATH "${NODE_MODULES}" NODE_MODULES)
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules/@rnoh/react-native-openharmony/src/main/cpp")
file(REAL_PATH "${RNOH_CPP_DIR}" RNOH_CPP_DIR)
set(RNOH_GENERATED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/generated")
```
--------------------------------
### Project and Directory Setup
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/Sandbox/SandBoxNativeProject/entry/src/main/cpp/CMakeLists.txt
Sets the project name, minimum CMake version, and defines key directories for the React Native OH App, including the module directory and generated files directory.
```cmake
project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
set(OH_MODULE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(RNOH_CPP_DIR "${OH_MODULE_DIR}/@rnoh/react-native-openharmony/src/main/cpp")
set(RNOH_GENERATED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/generated")
```
--------------------------------
### RNAbility Usage Example
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Example of how to extend the RNAbility class for a React Native application.
```APIDOC
## RNAbility Usage Example
### Description
This code snippet demonstrates how to extend the `RNAbility` class to create a custom ability for a React Native application. It shows how to define the entry page path.
### Class
`RNAbility`
### Usage
```ts
import {RNAbility} from '@rnoh/react-native-openharmony';
export default class EntryAbility extends RNAbility {
getPagePath() {
return 'pages/Index';
}
}
```
```
--------------------------------
### onWindowStageSetup
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Loads specific page content into the window stage.
```APIDOC
## onWindowStageSetup
### Description
This method is responsible for loading the specific page content into the current window stage. It is called during the window stage setup process.
### Method
`protected async onWindowStageSetup(windowStage: window.WindowStage): void`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **windowStage** (`window.WindowStage`) - The current window stage instance where content will be loaded.
```
--------------------------------
### onWindowSetup
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Customizes the window properties such as screen orientation and size.
```APIDOC
## onWindowSetup
### Description
This method allows for customization of the window's properties, including screen orientation and window size, before the window is displayed.
### Method
`protected async onWindowSetup(window: window.Window): void`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **window** (`window.Window`) - The current window instance to be configured.
```
--------------------------------
### onPrepareRNInstance
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Prepares the React Native instance by creating and loading the necessary core context and packages.
```APIDOC
## onPrepareRNInstance
### Description
This method is called to prepare the React Native instance. It is responsible for creating the `RNInstance` and loading the application package. The `RNAbility` class waits for this method to complete before loading the UI, which helps reduce flicker after the splash screen is hidden.
### Method
`protected async onPrepareRNInstance(rnohCoreContext: RNOHCoreContext): void`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **rnohCoreContext** (`RNOHCoreContext`) - The core context for the React Native instance.
```
--------------------------------
### onCreate
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Initializes the UIAbility instance and sets up core components for React Native.
```APIDOC
## onCreate
### Description
This method is the entry point for the ability's lifecycle. It is called by the system when the ability is created. In this implementation, it initializes `RNInstancesCoordinator` and `RNOHCoreContext`, and stores `RNOHCoreContext` globally for application-wide access.
### Method
`onCreate(want: Want, launchParam?: AbilityConstant.LaunchParam): void`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **want** (`Want`) - An object used for transferring information between application components.
- **launchParam** (`AbilityConstant.LaunchParam`, optional) - Parameters related to the application launch, including the reason for the launch and the previous exit reason.
```
--------------------------------
### Bundle Basic Entry File
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/rn-js-bundle.md
Use this command to bundle a basic entry file. Ensure the `--config` option points to your configuration file.
```powershell
react-native bundle-harmony --dev false --entry-file ./src/bundles/basic/basic.js --bundle-output ../../SampleApp/entry/src/main/resources/rawfile/bundle/basic/basic.harmony.bundle --config ./basic.config.js
```
--------------------------------
### RNApp
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
RNApp is a module used to start and manage RNInstance and RNSurface. It encapsulates the behavior of creating and starting a single RNInstance and a single RNSurface.
```APIDOC
## RNApp
### Introduction
`RNApp` is a module used to start and manage `RNInstance` and `RNSurface`. It encapsulates the behavior of creating and starting a single `RNInstance` and a single `RNSurface`. You do not need to consider when to load the JS bundle. If your application requires only a single `RNInstance` and a single `RNSurface`, you can use `RNApp`s to create an RN application, freeing you from complex operations. For applications with multiple surfaces, you can use `RNSurface`. This section describes the API types and usage of `RNApp`.
```
--------------------------------
### Start and Stop Trace using Logger
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/debugging.md
This ArkTS snippet shows how to start and stop a trace using a logger object, returning a function to stop the trace.
```TypeScript
const stopTracing = this.logger.clone("myTrace").startTracing()
// do something
stopTracing()
```
--------------------------------
### Generate Local Bundle
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/Sample/README.md
Run this command in the SampleProject/MainProject directory to generate the bundle and assets folders. These will be placed in the SampleApp/entry/src/main/resources/rawfile directory.
```bash
npm run dev:all
```
--------------------------------
### Directory Structure
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/MutilBundleSample/README.md
Illustrates the directory layout of the multi-bundle sample project, including front-end projects and the native OpenHarmony project.
```markdown
MutilBundleSample
├── FlightRN Flight front-end project
├── HotelRN Hotel front-end project
├── NativeProject OpenHarmony project
└── README.md
```
--------------------------------
### RNAbility onWindowStageSetup Method Signature
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Signature for the onWindowStageSetup method in RNAbility.
```typescript
protected async onWindowStageSetup(windowStage: window.WindowStage): void
```
--------------------------------
### RNAbility onWindowSetup Method Signature
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Signature for the onWindowSetup method in RNAbility.
```typescript
protected async onWindowSetup(window: window.Window): void
```
--------------------------------
### getAssetsDest
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Gets the assets path.
```APIDOC
## getAssetsDest
### Description
Gets the assets path.
### Method
```typescript
getAssetsDest(): string
```
```
--------------------------------
### Get RNOHCoreContext from RNInstancesCoordinator
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Retrieves the RNOHCoreContext associated with the RNInstancesCoordinator instance.
```typescript
rnInstancesCoordinator?.getRNOHCoreContext(): RNOHCoreContext
```
--------------------------------
### Get Assets Destination Path
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Retrieves the path where assets are stored.
```typescript
getAssetsDest(): string
```
--------------------------------
### Get UIAbility State
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/zh-cn/API接口说明.md
Returns the current state of the UIAbility, such as foreground or background.
```javascript
getUIAbilityState: () => UIAbilityState
```
--------------------------------
### SampleTurboModulePackage Implementation
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/custom-components.md
Implements methods in SampleTurboModulePackage to integrate custom components like MarqueeView.
```cpp
std::vector SampleTurboModulePackage::createComponentDescriptorProviders() {
return {
react::concreteComponentDescriptorProvider(),
};
}
EventEmitRequestHandlers SampleTurboModulePackage::createEventEmitRequestHandlers() {
return {std::make_shared()};
}
ComponentNapiBinderByString SampleTurboModulePackage::createComponentNapiBinderByName() {
return {{"MarqueeView", std::make_shared()}};
};
ComponentJSIBinderByString SampleTurboModulePackage::createComponentJSIBinderByName() {
return {{"MarqueeView", std::make_shared()}};
};
```
--------------------------------
### RNInstancesCoordinator.getBuildMode
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Gets the current build mode of the React Native instance, which can be RELEASE or DEBUG.
```APIDOC
## RNInstancesCoordinator.getBuildMode
### Description
Gets the build mode, which can be **RELEASE** or **DEBUG**.
### Signature
```typescript
rnInstancesCoordinator?.getBuildMode(): BuildMode
```
```
--------------------------------
### Get Display Metrics
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/zh-cn/API接口说明.md
Retrieves the current screen information, including dimensions and density.
```javascript
getDisplayMetrics: () => DisplayMetrics
```
--------------------------------
### Build Glog with CMake
Source: https://github.com/auroramaster/ohos_react_native/blob/main/tester/harmony/react_native_openharmony/src/main/cpp/third-party/glog/cmake/INSTALL.md
Navigate to a build directory and run CMake to configure the build for Glog. This prepares the project for compilation using generated build files (e.g., Makefiles).
```bash
cmake path/to/glog
```
--------------------------------
### Profiler Domain
Source: https://github.com/auroramaster/ohos_react_native/blob/main/tester/harmony/react_native_openharmony/src/main/cpp/third-party/rn/ReactCommon/hermes/inspector/tools/message_types.txt
Commands for starting and stopping CPU profiling to analyze JavaScript execution performance.
```APIDOC
## Profiler Domain
### Description
Enables CPU profiling to analyze the performance of JavaScript execution.
### Methods
- **start**: Starts CPU profiling.
- **stop**: Stops CPU profiling.
```
--------------------------------
### SampleTurboModulePackage Implementation
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/custom-components.md
Implements SampleTurboModulePackage methods in SampleTurboModulePackage.cpp. It includes a custom ButtonViewPackageComponentInstanceFactoryDelegate and registers the ButtonViewJSIBinder for the 'ButtonView' component.
```cpp
class ButtonViewPackageComponentInstanceFactoryDelegate : public ComponentInstanceFactoryDelegate {
public:
using ComponentInstanceFactoryDelegate::ComponentInstanceFactoryDelegate;
ComponentInstance::Shared create(ComponentInstance::Context ctx) override {
if (ctx.componentName == "CustomButtonView") {
return std::make_shared(std::move(ctx));
}
return nullptr;
}
};
···
ComponentJSIBinderByString SampleTurboModulePackage::createComponentJSIBinderByName() {
return {
{"MarqueeView", std::make_shared(),},
{"ButtonView", std::make_shared()}
};
};
ComponentInstanceFactoryDelegate::Shared SampleTurboModulePackage::createComponentInstanceFactoryDelegate() override {
return std::make_shared();
}
···
```
--------------------------------
### Get RNInstancesCoordinator Build Mode
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Retrieves the current build mode of the RNInstancesCoordinator, which can be either RELEASE or DEBUG.
```typescript
rnInstancesCoordinator?.getBuildMode(): BuildMode
```
--------------------------------
### Project and Build Configuration
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/RegisterFont/RegisterFontNativeProject/entry/src/main/cpp/CMakeLists.txt
Sets up the project name, minimum CMake version, skips build RPATH, and defines key directories for modules and the React Native OpenHarmony source.
```cmake
project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
set(OH_MODULE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
```
--------------------------------
### Windows Logging with GLOG_NO_ABBREVIATED_SEVERITIES (FlushLogFiles)
Source: https://github.com/auroramaster/ohos_react_native/blob/main/tester/harmony/react_native_openharmony/src/main/cpp/third-party/glog/doc/glog.html
Shows the correct way to call FlushLogFiles with specific severity levels on Windows when GLOG_NO_ABBREVIATED_SEVERITIES is defined, using the GLOG_ prefix for severity constants.
```cpp
#define GLOG_NO_ABBREVIATED_SEVERITIES
#include
#include
// ...
// This won't work.
// google::FlushLogFiles(google::ERROR);
// Use this instead.
google::FlushLogFiles(google::GLOG_ERROR);
```
--------------------------------
### Get Component Name from Descriptor Type
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Retrieves the component name associated with a given descriptor type.
```typescript
getComponentNameFromDescriptorType(descriptorType: string): string
```
--------------------------------
### Get Event Type and Node Handle
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/architecture.md
Retrieves the event type and the node handle that triggered the event.
```cpp
auto eventType = OHArkUI_NodeEvent_GetEventType(event);
auto node = OH_ArkUI_NodeEvent_GetNodeHandle(event);
```
--------------------------------
### Get Attached Developer Label
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Retrieves the custom developer-defined label previously set on the RNInstance using setAttachedLabel.
```typescript
getAttachedLabel(): string
```
--------------------------------
### Get TurboModule Instance
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Retrieves an instance of a TurboModule by its name. This allows access to native modules exposed to JavaScript.
```typescript
getTurboModule(name: string): T
```
--------------------------------
### Build and Run Chrome Tests
Source: https://github.com/auroramaster/ohos_react_native/blob/main/tester/harmony/react_native_openharmony/src/main/cpp/third-party/rn/ReactCommon/hermes/inspector/README.md
Builds the chrome tests using buck and then runs the executable. Debug logging is enabled by default.
```bash
$ buck build //xplat/js/react-native-github/packages/react-native/ReactCommon/hermes/inspector:chrome-tests
$ buck-out/gen/xplat/js/react-native-github/packages/react-native/ReactCommon/hermes/inspector/chrome-tests
[...]
```
--------------------------------
### Get Bundle Execution Status
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Retrieves the execution status of a specified bundle. It prevents duplicate loading of the same package.
```typescript
getBundleExecutionStatus(bundleURL: string) : BundleExecutionStatus | undefined
```
--------------------------------
### SampleTurboModulePackage Header
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/custom-components.md
Declares methods in SampleTurboModulePackage.h to support custom components, including creating a component instance factory delegate and a JSI binder map.
```cpp
#include "RNOH/Package.h"
namespace rnoh {
class SampleTurboModulePackage : public Package {
public:
ComponentInstanceFactoryDelegate::Shared createComponentInstanceFactoryDelegate() override;
ComponentJSIBinderByString createComponentJSIBinderByName() override;
// Common methods used in the ArkTS version
···
};
} // namespace rnoh
```
--------------------------------
### RNSurface API Usage
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Example of how to use the RNSurface API with SurfaceConfig2. Ensure you provide the correct context and surface configuration.
```typescript
RNSurface({
ctx: this.ctx, // Component context created in RNApp.
surfaceConfig: {
initialProps: this.initialProps ?? {},
appKey: this.appKey, // App name passed from RNApp.
} as SurfaceConfig2,
})
```
--------------------------------
### Configure Native Library Packaging in build-profile.json5
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/faqs/compilation-faqs.md
Add the 'nativeLib' configuration to 'entry/build-profile.json5' to ensure that native libraries like libhermes.so are correctly included in the final package. Set 'excludeFromHar' to false.
```json5
"nativeLib": {
"excludeFromHar": false
}
```
--------------------------------
### RNInstance Creation with RNOHCoreContext
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Demonstrates the creation and registration of an RNInstance using `createAndRegisterRNInstance` from `RNOHCoreContext`. This involves setting up `RNInstancesCoordinator` and storing the `RNOHCoreContext` globally.
```javascript
this.rnInstancesCoordinator = RNInstancesCoordinator.create({
fontSizeScale: this.context.config.fontSizeScale,
logger: this.createLogger(),
uiAbilityContext: this.context,
defaultBackPressHandler: () => {
this.defaultBackPressHandler()
},
}, {
launchURI: want.uri, onGetPackagerClientConfig: (buildMode) => buildMode === "DEBUG" ? {
host: "localhost",
port: 8081
} : undefined,
defaultHttpClient: this.onCreateDefaultHttpClient()
})
AppStorage.setOrCreate('RNOHCoreContext', this.rnInstancesCoordinator.getRNOHCoreContext())
```
--------------------------------
### Dispatch View Manager Command from RN
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/custom-components.md
Sends a command to the native component using UIManager.dispatchViewManagerCommand. 'toggleMarqueeState' is an example command.
```JavaScript
UIManager.dispatchViewManagerCommand(
findNodeHandle(nativeRef.current),
'toggleMarqueeState',
[],
)
```
--------------------------------
### Push Bundle to Rawfile Directory
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/Samples/Sandbox/sandbox-loading-bundle.md
Downloads a bundle from the rawfile directory and saves it to the application's sandbox. Ensure the bundle exists in the 'rawfile/bundle/bp/' path.
```javascript
// Download bundle.js and save it to the sandbox.
let uint8Array = await this.rnAbility.context.resourceManager.getRawFileContent('rawfile/bundle/bp/sandbox.harmony.bundle')
let rawBuffer = uint8Array.buffer
let num = rawBuffer.byteLength
// Obtain the sandbox path.
const sandboxDir = this.rnAbility.context.filesDir
const bundlePath = sandboxDir + '/' + this.bundlePath
let stream = fs.createStreamSync(bundlePath, 'w')
stream.writeSync(rawBuffer)
stream.closeSync()
this.hasBundle = true
```
--------------------------------
### Get Initial Bundle URL
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/api-description.md
Retrieves the initial JavaScript Bundle URL. Useful for applications that split bundles for performance.
```typescript
getInitialBundleUrl(): string | undefined
```
--------------------------------
### Add Synchronous Trace on JS Side
Source: https://github.com/auroramaster/ohos_react_native/blob/main/docs/en/debugging.md
Use Systrace.beginEvent and Systrace.endEvent to mark the start and end of a synchronous operation for performance tracing.
```JavaScript
import {Systrace} from 'react-native';
...