基于 react-native-system-setting 的 OpenHarmony 适配版,读取/跳转系统设置(音量、亮度、WiFi、蓝牙)
| 文件 | 最后提交记录 | 最后更新时间 |
|---|---|---|
| 1 天前 | ||
| 1 天前 | ||
| 10 个月前 | ||
| 9 个月前 | ||
| 1 天前 | ||
| 6 年前 | ||
| 1 天前 | ||
| 10 个月前 | ||
| 8 年前 | ||
| 1 天前 | ||
| 8 年前 | ||
| 10 个月前 | ||
| 1 天前 | ||
| 1 天前 | ||
| 9 个月前 | ||
| 5 个月前 | ||
| 9 年前 | ||
| 10 个月前 | ||
| 1 天前 | ||
| 1 天前 | ||
| 10 个月前 |
文档模板: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.9.0 (开发中) | Gitcode Releases | 0.84.* / 0.82.* | 是 | API12+ | 1.7.6 | master |
| @react-native-ohos/react-native-system-setting | ~ 1.8.0 | Gitcode Releases | 0.77.* | 否 | API12+ | 1.7.6 | br_rnoh0.77 |
| @react-native-ohos/react-native-system-setting | ~ 1.7.7 | Gitcode Releases | 0.72.* | 是 | API12+ | 1.7.6 | br_rnoh0.72 |
| @react-native-oh-tpl/react-native-system-setting | <= 1.7.6-0.0.1@deprecated | Github Releases(deprecated) | 0.72.* | 否 | API12+ | 1.7.6 | sig |
简介
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.9.0 | 是 | 0.82.* / 0.84.* |
使用AutoLink的工程需要根据该文档配置,Autolink框架指导文档:https://gitcode.com/CPF-RN/ohos_react_native/blob/master/docs/zh-cn/Autolinking.md
如您使用的版本支持 Autolink,并且工程已接入 Autolink,可跳过ManualLink配置。
ManualLink: 此步骤为手动配置原生依赖项的指导
首先需要使用 DevEco Studio 打开项目里的 HarmonyOS 工程 harmony。
1. Overrides RN SDK
为了让工程依赖同一个版本的 RN SDK,需要在工程根目录的 oh-package.json5 添加 overrides 字段,指向工程需要使用的 RN SDK 版本。替换的版本既可以是一个具体的版本号,也可以是一个模糊版本,还可以是本地存在的 HAR 包或源码目录。
关于该字段的作用请阅读官方说明
{
"overrides": {
"@rnoh/react-native-openharmony": "~0.82.30" // 0.82 工程;0.84 工程改为对应 0.84.x 版本
// "@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)
];
}
运行
点击右上角的 sync 按钮
或者在终端执行:
cd entry
ohpm install
然后编译、运行即可。
约束与限制
兼容性
要使用此库,需要使用正确的 React-Native 和 RNOH 版本。另外,还需要使用配套的 DevEco Studio 和手机 ROM。
本文档内容基于以下版本验证通过:
- RNOH: 0.82.7; SDK: HarmonyOS 6.0.1 Release SDK; IDE: DevEco Studio 6.0.1 Release; ROM: 6.0.0.328 SP26;
- RNOH: 0.84.2; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.2.636; ROM: 6.0.0.125;
权限要求
由于此库涉及蓝牙、亮度等系统控制功能,使用对应接口时需要配置对应的权限,权限需配置在 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"列表示该属性在原三方库上支持的平台。
"OpenHarmony Support"列为 yes 表示 OpenHarmony平台支持 该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。
详情请见react-native-system-setting
| 名称 | 类型 | 参数类型 | 默认值 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|---|
| getVolume | (type?: VolumeType) => Promise<number> | VolumeType | 'music' | Promise<number> | No | iOS/Android | yes | 获取系统音量。 |
| setVolume | (value: number, config?: VolumeConfig) => void | value: number, config?: VolumeConfig | { type: 'music', playSound: false, showUI: false } | / | No | iOS/Android | no | 按指定值设置系统音量,范围为 0 到 1。0 表示静音,1 表示最大音量。 |
| addVolumeListener | (callback: (volumeData: VolumeData) => void) => EmitterSubscription | callback: (volumeData: VolumeData) => void | / | EmitterSubscription | No | iOS/Android | yes | 监听音量变化,并返回监听器。 |
| removeVolumeListener | (listener?: EmitterSubscription) => void | listener?: EmitterSubscription | / | / | No | iOS/Android | yes | 在不再需要时移除监听器。 |
| getBrightness | () => Promise<number> | / | / | Promise<number> | No | iOS/Android | no | 获取系统亮度。 |
| setBrightness | (val: number) => Promise<boolean> | number | / | Promise<boolean> | No | iOS/Android | no | 按指定值设置系统亮度,范围为 0 到 1。0 为最暗,1 为最亮。 |
| setBrightnessForce | (val: number) => Promise<boolean> | number | / | Promise<boolean> | No | Android | no | 在 Android 中,如果屏幕模式为自动,SystemSetting.setBrightness() 将不会生效。可调用此方法先将屏幕模式改为手动。 |
| setAppBrightness | (val: number) => Promise<true> | number | / | Promise<true> | No | Android | yes | 对于 Android 和 Harmony,setBrightness() 或 setBrightnessForce() 会修改系统亮度,而该方法只修改应用亮度,且无需权限。 |
| getAppBrightness | () => Promise<number> | / | / | Promise<number> | No | Android | yes | 获取应用亮度;如果尚未调用 setAppBrightness(val),则返回系统亮度。(iOS 始终返回系统亮度) |
| getScreenMode | () => Promise<number> | / | / | Promise<number> | No | Android | no | (仅 Android 支持,iOS 和 Harmony 返回 -1)获取屏幕模式:0 为手动,1 为自动。 |
| setScreenMode | (val: number) => Promise<boolean> | number | / | Promise<boolean> | No | Android | no | (仅 Android 支持,iOS 和 Harmony 无法修改)设置屏幕模式:0 为手动,1 为自动。 |
| grantWriteSettingPermission | () => void | / | / | / | No | iOS/Android | no | 打开应用设置页面。当你需要某些权限时更友好。通常可在 setScreenMode()、setBrightness() 或 setBrightnessForce() 返回 false 时调用。 |
| saveBrightness | () => Promise<void> | / | / | Promise<void> | No | iOS/Android | yes | 保存当前亮度和屏幕模式。 |
| restoreBrightness | () => number | / | / | number | No | iOS/Android | yes | 将亮度和屏幕模式恢复到 saveBrightness() 保存时的状态。iOS 仅恢复亮度,Android 恢复两者,Harmony 恢复应用亮度。 |
| isWifiEnabled | () => Promise<boolean> | / | / | Promise<boolean> | No | iOS/Android | yes | 获取 WiFi 状态,若 WiFi 开启则返回 true。 |
| switchWifi | (onComplete?: CompleteFunc) => void | onComplete?: () => void | / | / | No | iOS/Android | yes | 打开 WiFi 设置页面,你可以自行修改。返回应用后会调用 complete。 |
| switchWifiSilence | (onComplete?: CompleteFunc) => void | onComplete?: () => void | / | / | No | Android | no | 若当前 WiFi 关闭则打开,若当前 WiFi 开启则关闭。完成后会调用 complete。 |
| addWifiListener | (callback: (wifiEnabled: boolean) => void) => Promise<EmitterSubscription | null> | callback: (wifiEnabled: boolean) => void | / | Promise<EmitterSubscription | null> | No | Android | no | 监听 WiFi 状态变化,并返回监听器。(仅 Android) |
| isLocationEnabled | () => Promise<boolean> | / | / | Promise<boolean> | No | iOS/Android | yes | 获取定位状态,若定位开启则返回 true。 |
| switchLocation | (onComplete?: CompleteFunc) => void | onComplete?: () => void | / | / | No | iOS/Android | yes | 打开系统定位设置页面,你可以自行修改。返回应用后会调用 complete。 |
| addLocationListener | (callback: (locationEnabled: boolean) => void) => Promise<EmitterSubscription | null> | callback: (locationEnabled: boolean) => void | / | Promise<EmitterSubscription | null> | No | Android | no | 监听定位状态变化,并返回监听器。(仅 Android) |
| getLocationMode | () => Promise<number> | / | / | Promise<number> | No | Android | no | 获取当前定位模式代码:0 - 'off',1 - 'gps',2 - 'network',3 - 'gps & network'。(仅 Android) |
| addLocationModeListener | (callback: (locationMode: number) => void) => Promise<EmitterSubscription | null> | callback: (locationMode: number) => void | / | Promise<EmitterSubscription | null> | No | Android | no | 监听定位模式变化,并返回监听器。(仅 Android) |
| isBluetoothEnabled | () => Promise<boolean> | / | / | Promise<boolean> | No | iOS/Android | yes | 获取蓝牙状态,若蓝牙开启则返回 true。 |
| switchBluetooth | (onComplete?: CompleteFunc) => void | onComplete?: () => void | / | / | No | iOS/Android | yes | 打开系统蓝牙设置页面,你可以自行修改。返回应用后会调用 complete。 |
| switchBluetoothSilence | (onComplete?: CompleteFunc) => void | onComplete?: () => void | / | / | No | Android | yes | 若当前蓝牙关闭则打开,若当前蓝牙开启则关闭。完成后会调用 complete。在 Android 中,该过程以编程方式完成。 |
| addBluetoothListener | (callback: (bluetoothEnabled: boolean) => void) => Promise<EmitterSubscription> | callback: (bluetoothEnabled: boolean) => void | / | Promise<EmitterSubscription> | No | iOS/Android | yes | 监听蓝牙状态变化,并返回监听器。 |
| isAirplaneEnabled | () => Promise<boolean> | / | / | Promise<boolean> | No | iOS/Android | no | 获取飞行模式状态,若飞行模式开启则返回 true。 |
| switchAirplane | (onComplete?: CompleteFunc) => void | onComplete?: () => void | / | / | No | iOS/Android | yes | 打开系统设置页面,你可以自行修改。 |
| addAirplaneListener | (callback: (airplaneModeEnabled: boolean) => void) => Promise<EmitterSubscription | null> | callback: (airplaneModeEnabled: boolean) => void | / | Promise<EmitterSubscription | null> | No | Android | no | 监听飞行模式状态变化,并返回监听器。(仅 Android) |
| setAppStore | (isAppStore: boolean) => void | isAppStore: boolean | / | / | No | iOS | no | true 表示你将把应用提交到 App Store,false 表示应用不会上传到 App Store,你可以自由使用任意 API。 |
| removeListener | (listener?: EmitterSubscription) => void | listener?: EmitterSubscription | / | / | No | iOS/Android | yes | 你可以使用该方法移除由 add*Listener(callback) 返回的监听器。 |
| openAppSystemSettings | () => Promise<void> | / | / | Promise<void> | 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 # 示例工程(RN 0.84,上游 demo + 鸿蒙 demo)
├── README.md # 中文文档
├── README_en.md # 英文文档
贡献代码
使用过程中发现任何问题都可以提交 Issue,当然,也非常欢迎提交 PR 。
开源协议
本项目基于 The Mit License (MIT) ,请自由地享受和参与开源。