基于 react-native-system-setting 的 OpenHarmony 适配版,读取/跳转系统设置(音量、亮度、WiFi、蓝牙)
文档模板:v0.4.2
react-native-system-setting
本项目基于 react-native-system-setting 开发。
该第三方库的仓库已迁移至 Gitcode,且支持直接从 npm 下载,新的包名为:@react-native-ohos/react-native-system-setting(JS 别名 react-native-system-setting),版本所属关系如下:
| 三方库名称 | 三方库版本(npm地址) | 发布信息 | 支持RN版本 | Autolink | 编译API版本 | 社区基线版本 | 源码地址 |
|---|---|---|---|---|---|---|---|
| @react-native-ohos/react-native-system-setting | ~ 1.8.0 | Gitcode Releases | 0.77.* | 否 | API12+ | 1.7.6 | br_rnoh0.77 |
简介
react-native-system-setting 提供音量、亮度、WiFi、定位、蓝牙、飞行模式等系统设置的读取与控制能力。
本库为其提供 React Native 鸿蒙(HarmonyOS)适配,基于 TurboModule 实现,支持音量/亮度获取与设置、各系统开关状态查询、跳转设置页、状态监听等接口。
下载安装
进入到工程目录并输入以下命令:
npm
npm install @react-native-ohos/react-native-system-setting
yarn
yarn add @react-native-ohos/react-native-system-setting
Link
| 是否支持autolink | RN框架版本 | |
|---|---|---|
| ~ 1.8.0 | 否 | 0.77.* |
使用AutoLink的工程需要根据该文档配置,Autolink框架指导文档:https://gitcode.com/CPF-RN/ohos_react_native/blob/master/docs/zh-cn/Autolinking.md
如您使用的版本支持 Autolink,并且工程已接入 Autolink,可跳过ManualLink配置。
首先需要使用 DevEco Studio 打开项目里的 HarmonyOS 工程 harmony。
1. Overrides RN SDK
为了让工程依赖同一个版本的 RN SDK,需要在工程根目录的 oh-package.json5 添加 overrides 字段,指向工程需要使用的 RN SDK 版本。替换的版本既可以是一个具体的版本号,也可以是一个模糊版本,还可以是本地存在的 HAR 包或源码目录。
关于该字段的作用请阅读官方说明
{
"overrides": {
"@rnoh/react-native-openharmony": "^0.77.73"
// "@rnoh/react-native-openharmony" : "./react_native_openharmony.har" // 指向本地 har 包的路径
// "@rnoh/react-native-openharmony" : "./react_native_openharmony" // 指向源码路径
}
}
2. 引入原生端代码
目前有两种方法:
- 通过 har 包引入(在 IDE 完善相关功能后该方法会被遗弃,目前首选此方法);
- 直接链接源码。
方法一:通过 har 包引入(推荐)
har 包位于三方库安装路径的 `harmony` 文件夹下。
打开 entry/oh-package.json5,添加以下依赖
"dependencies": {
"@rnoh/react-native-openharmony": "file:../react_native_openharmony",
"@react-native-ohos/react-native-system-setting": "file:../../node_modules/@react-native-ohos/react-native-system-setting/harmony/react_native_system_setting.har"
}
点击右上角的 sync 按钮
或者在终端执行:
cd entry
ohpm install
方法二:直接链接源码
如需使用直接链接源码,请参考[直接链接源码说明](https://gitcode.com/CPF-RN/usage-docs/blob/master/zh-cn/link-source-code.md)
3. 配置 CMakeLists 和引入 RNSystemSettingPackage
若工程已接入 RNOH AutoLink,且本库的
harmony.autolinking配置生效,则 CMake 与PackageProvider注册可由 AutoLink 自动生成,可跳过本节手动配置。
打开 entry/src/main/cpp/CMakeLists.txt,添加:
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-system-setting/src/main/cpp" ./system_setting)
# 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_system_setting)
# RNOH_END: manual_package_linking_2
打开 entry/src/main/cpp/PackageProvider.cpp,添加:
#include "RNOH/PackageProvider.h"
+ #include "RNSystemSettingPackage.h"
using namespace rnoh;
std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
return {
+ std::make_shared<RNSystemSettingPackage>(ctx)
};
}
4. 在 ArkTs 侧引入 RNSystemSettingPackage
打开 entry/src/main/ets/RNPackagesFactory.ts,或者 entry/src/main/ets/rn/RNPackagesFactory.ts,添加:
...
+ import { RNSystemSettingPackage } from '@react-native-ohos/react-native-system-setting/ts';
export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
return [
+ new RNSystemSettingPackage(ctx)
];
}
5. 运行
点击右上角的 sync 按钮
或者在终端执行:
cd entry
ohpm install
然后编译、运行即可。
约束与限制
兼容性
要使用此库,需要使用正确的 React-Native 和 RNOH 版本。另外,还需要使用配套的 DevEco Studio 和手机 ROM。
本文档内容基于以下版本验证通过:
- RNOH: 0.77.18; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;
权限要求
由于此库涉及蓝牙、亮度等系统控制功能,使用对应接口时需要配置对应的权限,权限需配置在 entry/src/main/module.json5 中。其中部分权限需弹窗向用户申请授权。具体权限配置见文档:程序访问控制。
此库部分功能与接口需要 normal 权限:ohos.permission.ACCESS_BLUETOOTH、ohos.permission.GET_WIFI_INFO。
此库部分功能与接口需要 full sdk 与 system_basic 权限:ohos.permission.MANAGE_SECURE_SETTINGS、ohos.permission.MANAGE_WIFI_CONNECTION 等,full sdk获取地址,system_basic权限获取方式。
编译运行API要求
当前三方库所有版本均已实现版本隔离,支持在 `API12+` 工程编译,及 `API12+` ROM运行。
使用示例
下面的代码展示了这个库的基本使用场景:
使用时 import 的库名不变,JS 侧通过 `react-native-system-setting` 导入。
import React, { useEffect, useState } from 'react';
import { ScrollView, Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import SystemSetting, { EmitterSubscription } from 'react-native-system-setting';
export default function SystemSettingDemo() {
const [bluetoothEnabled, setBluetoothEnabled] = useState<boolean>();
useEffect(() => {
// 初始获取蓝牙状态
SystemSetting.isBluetoothEnabled().then(setBluetoothEnabled);
}, []);
let bluetoothEvent: EmitterSubscription;
return (
<ScrollView>
<View style={styles.module}>
<Text style={styles.moduleName}>Bluetooth(蓝牙模块)</Text>
<Text style={styles.moduleContent}>
蓝牙状态: {bluetoothEnabled === undefined ? '未获取' : bluetoothEnabled ? '开启' : '关闭'}
</Text>
<TouchableOpacity
onPress={() => SystemSetting.isBluetoothEnabled().then(setBluetoothEnabled)}
style={styles.moduleButton}>
<Text style={styles.buttonText}>获取蓝牙状态</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => SystemSetting.switchBluetooth(() => console.log('跳转完成'))}
style={styles.moduleButton}>
<Text style={styles.buttonText}>切换蓝牙状态(跳转设置)</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={async () => {
bluetoothEvent = await SystemSetting.addBluetoothListener(setBluetoothEnabled);
}}
style={styles.moduleButton}>
<Text style={styles.buttonText}>开启蓝牙状态监听器</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => SystemSetting.removeListener(bluetoothEvent)}
style={styles.moduleButton}>
<Text style={styles.buttonText}>关闭蓝牙状态监听器</Text>
</TouchableOpacity>
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
module: { margin: 15 },
moduleName: { fontSize: 25, fontWeight: '700', marginBottom: 4 },
moduleContent: { fontSize: 16, fontWeight: '500', marginBottom: 4 },
moduleButton: { marginBottom: 4, backgroundColor: 'deepskyblue', height: 34, borderRadius: 10 },
buttonText: { fontSize: 18, fontWeight: '400', color: 'white', textAlign: 'center', lineHeight: 32 },
});
使用说明
音量
// 获取系统音量(0~1),type 可选: 'music' | 'system' | 'call' | 'ring' | 'alarm' | 'notification'
const vol = await SystemSetting.getVolume('music');
// 设置音量
SystemSetting.setVolume(0.5, { type: 'music', playSound: false, showUI: false });
// 监听音量变化(返回监听器)
const listener = SystemSetting.addVolumeListener((data) => {
console.log(data.value); // iOS/Harmony 返回 value
});
SystemSetting.removeVolumeListener(listener); // 移除音量监听
亮度
const brightness = await SystemSetting.getBrightness(); // 获取系统亮度
await SystemSetting.setBrightness(0.8); // 设置系统亮度
await SystemSetting.setAppBrightness(0.5); // 仅设置应用亮度(无需权限)
const appBrightness = await SystemSetting.getAppBrightness(); // 获取应用亮度
SystemSetting.saveBrightness(); // 保存当前亮度
const saved = SystemSetting.restoreBrightness(); // 恢复保存的亮度(Harmony 恢复应用亮度)
WiFi / 定位 / 蓝牙 / 飞行模式
await SystemSetting.isWifiEnabled(); // 查询 WiFi 状态
SystemSetting.switchWifi(() => {}); // 跳转 WiFi 设置页
await SystemSetting.isLocationEnabled(); // 查询定位状态
SystemSetting.switchLocation(() => {}); // 跳转定位设置页
await SystemSetting.isBluetoothEnabled(); // 查询蓝牙状态
SystemSetting.switchBluetoothSilence(() => {}); // 静默切换蓝牙开关
await SystemSetting.isAirplaneEnabled(); // 查询飞行模式状态
SystemSetting.switchAirplane(() => {}); // 跳转系统设置页
监听器
const l1 = await SystemSetting.addBluetoothListener((enabled) => {});
const l2 = await SystemSetting.addWifiListener((enabled) => {});
const l3 = await SystemSetting.addLocationListener((enabled) => {});
const l4 = await SystemSetting.addAirplaneListener((enabled) => {});
SystemSetting.removeListener(l1); // 统一移除
其他
await SystemSetting.openAppSystemSettings(); // 打开应用的系统设置页
接口说明
"Platform"列表示该属性在原三方库上支持的平台。
"HarmonyOS Support"列为 yes 表示 HarmonyOS 平台支持该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。
详情请见react-native-system-setting
| Name | Description | Type | Required | Platform | HarmonyOS Support |
|---|---|---|---|---|---|
| getVolume | 获取系统音量。 | (type:string) => Promise | No | iOS/Android | yes |
| setVolume | 按指定值设置系统音量,范围为 0 到 1。0 表示静音,1 表示最大音量。 | (val:float, config:object) => void | No | iOS/Android | no |
| addVolumeListener | 监听音量变化,并返回监听器。 | callback | No | iOS/Android | yes |
| removeVolumeListener | 在不再需要时移除监听器。 | listener | No | iOS/Android | yes |
| getBrightness | 获取系统亮度。 | () => Promise | No | iOS/Android | no |
| setBrightness | 按指定值设置系统亮度,范围为 0 到 1。0 为最暗,1 为最亮。 | (val:float) => Promise | No | iOS/Android | no |
| setBrightnessForce | 在 Android 中,如果屏幕模式为自动,SystemSetting.setBrightness() 将不会生效。可调用此方法先将屏幕模式改为手动。 |
(val:float) => Promise | No | Android | no |
| setAppBrightness | 对于 Android 和 Harmony,setBrightness() 或 setBrightnessForce() 会修改系统亮度,而该方法只修改应用亮度,且无需权限。 |
(val:float) => boolean | No | Android | yes |
| getAppBrightness | 获取应用亮度;如果尚未调用 setAppBrightness(val),则返回系统亮度。(iOS 始终返回系统亮度) |
() => Promise | No | Android | yes |
| getScreenMode | (仅 Android 支持,iOS 和 Harmony 返回 -1)获取屏幕模式:0 为手动,1 为自动。 | () => Promise | No | Android | no |
| setScreenMode | (仅 Android 支持,iOS 和 Harmony 无法修改)设置屏幕模式:0 为手动,1 为自动。 | (mode:int) => Promise | No | Android | no |
| grantWriteSettingPermission | 打开应用设置页面。当你需要某些权限时更友好。通常可在 setScreenMode()、setBrightness() 或 setBrightnessForce() 返回 false 时调用。 |
callback | No | iOS/Android | no |
| saveBrightness | 保存当前亮度和屏幕模式。 | callback | No | iOS/Android | yes |
| restoreBrightness | 将亮度和屏幕模式恢复到 saveBrightness() 保存时的状态。iOS 仅恢复亮度,Android 恢复两者,Harmony 恢复应用亮度。 |
() => Promise | No | iOS/Android | yes |
| isWifiEnabled | 获取 WiFi 状态,若 WiFi 开启则返回 true。 | () => Promise | No | iOS/Android | yes |
| switchWifi | 打开 WiFi 设置页面,你可以自行修改。返回应用后会调用 complete。 |
(complete) => void | No | iOS/Android | yes |
| switchWifiSilence | 若当前 WiFi 关闭则打开,若当前 WiFi 开启则关闭。完成后会调用 complete。 |
(complete) => void | No | Android | no |
| addWifiListener | 监听 WiFi 状态变化,并返回监听器。(仅 Android) | (callback) => Promise | No | Android | no |
| isLocationEnabled | 获取定位状态,若定位开启则返回 true。 | () => Promise | No | iOS/Android | yes |
| switchLocation | 打开系统定位设置页面,你可以自行修改。返回应用后会调用 complete。 |
(complete) => void | No | iOS/Android | yes |
| addLocationListener | 监听定位状态变化,并返回监听器。(仅 Android) | (callback) => Promise | No | Android | no |
| getLocationMode | 获取当前定位模式代码:0 - 'off',1 - 'gps',2 - 'network',3 - 'gps & network'。(仅 Android) |
() => Promise | No | Android | no |
| addLocationModeListener | 监听定位模式变化,并返回监听器。(仅 Android) | (callback) => Promise | No | Android | no |
| isBluetoothEnabled | 获取蓝牙状态,若蓝牙开启则返回 true。 | () => Promise | No | iOS/Android | yes |
| switchBluetooth | 打开系统蓝牙设置页面,你可以自行修改。返回应用后会调用 complete。 |
(complete) => void | No | iOS/Android | yes |
| switchBluetoothSilence | 若当前蓝牙关闭则打开,若当前蓝牙开启则关闭。完成后会调用 complete。在 Android 中,该过程以编程方式完成。 |
(complete) => void | No | Android | yes |
| addBluetoothListener | 监听蓝牙状态变化,并返回监听器。 | (callback) => Promise | No | iOS/Android | yes |
| isAirplaneEnabled | 获取飞行模式状态,若飞行模式开启则返回 true。 | () => Promise | No | iOS/Android | no |
| switchAirplane | 打开系统设置页面,你可以自行修改。 | (complete) => void | No | iOS/Android | yes |
| addAirplaneListener | 监听飞行模式状态变化,并返回监听器。(仅 Android) | (callback) => Promise | No | Android | no |
| setAppStore | true 表示你将把应用提交到 App Store,false 表示应用不会上传到 App Store,你可以自由使用任意 API。 |
(isAppStore:bool) => void | No | iOS | no |
| removeListener | 你可以使用该方法移除由 add*Listener(callback) 返回的监听器。 |
(listener) => void | No | iOS/Android | yes |
| openAppSystemSettings | 打开应用的系统设置页面。 | callback | No | iOS/Android | yes |
遗留问题
其他
由于仅支持 Android/iOS 特有功能,HarmonyOS 暂无法实现的接口:issue#11
目录结构
/rntpc_react-native-system-setting # 项目根目录
├── harmony # 鸿蒙适配代码
│ └─ react_native_system_setting.har # har 包
│ └─ react_native_system_setting # 鸿蒙适配核心代码
│ └─ Index.ets # 鸿蒙适配代码入口
│ └─ ts.ets # ArkTS 侧类型导出入口
│ └─ src/main
│ └─ ets
│ └─ RNSystemSettingPackage.ets # 鸿蒙侧 Package(TurboModule 注册枢纽)
│ └─ RNSystemSettingTurboModule.ts # TurboModule 实现
│ └─ Logger.ts # 日志
│ └─ generated/ # codegen 生成的 ArkTS 代码
│ └─ cpp
│ └─ CMakeLists.txt # C++ 侧构建配置(目标 rnoh_system_setting)
│ └─ RNSystemSettingPackage.h # C++ Package
│ └─ ReactNativeSystemSetting.cpp/.h # TurboModule C++ 实现
├── src # RN 侧 Spec
│ └─ ReactRNSystemSetting.ts # TurboModule Spec 定义(codegen 输入)
├── SystemSetting.js / SystemSetting.d.ts # JS 入口与类型定义
├── example # 示例工程
├── README.md # 中文文档
├── README_en.md # 英文文档
贡献代码
使用过程中发现任何问题都可以提交 Issue,当然,也非常欢迎提交 PR 。
开源协议
本项目基于 The MIT License (MIT) ,请自由地享受和参与开源。