React Native 鸿蒙 PC 系统通知实战:两套 ContentType 枚举打崩编译,运行时授权与三态返回怎么接
React Native 鸿蒙 PC 系统通知实战:两套 ContentType 枚举打崩编译,运行时授权与三态返回怎么接
用户说"发布一张图片后,要有一个真正的系统推送弹出来"。这句话的重点在"真正"两个字——应用内的 toast 再漂亮,也只是一个
View,关掉页面就没了,不会出现在通知栏,更不会在应用退到后台时提醒用户。要做到真推送,就必须走鸿蒙的notificationManager,把一条通知发布到系统通知中心。这篇文章用一个跑在鸿蒙 PC 上的 RNOH 工程,把"原生 TurboModule → 运行时授权 → 发布系统通知 → JS 侧接结果"这条链完整走一遍,重点讲清三个真实的坎:编译期两套ContentType枚举互不兼容导致的10505001报错、运行时通知授权怎么申请和降级、以及跨桥返回怎么设计成三态才不会把失败当成功。这是又一次"功能看着简单,落地全是细节"的实战复盘。
仓库与版本地址:
- RNOH 主仓:https://atomgit.com/CPF-RN/ohos_react_native
- React Native 仓库:https://github.com/facebook/react-native
0. 环境与实测设备
这一轮新增了一个原生模块:ArkTS 侧实现通知能力,C++ 侧做转发包装,JS 侧在发布图片后调用。通知走系统 notificationManager,没有新增第三方依赖。
| 项 | 版本 / 型号 |
|---|---|
| 操作系统 | HarmonyOS PC(aarch64,API 26) |
| DevEco Studio | 鸿蒙电脑版 |
| React Native | 0.84.1 |
@react-native-oh/react-native-harmony | 0.84.4 |
| React | 19.2.3 |
| JS 引擎 | Hermes(预编译在 HAR 里) |
| Node | v24(package.json 声明 >= 22.11.0) |
| ohpm / hvigor | hmos-clt_1.0.0 自带 |
| 目标架构 | arm64-v8a |
| 工程路径 | /storage/Users/currentUser/Documents/DevEcoStudioProjects/hello-rnoh-pc |
| 实测设备 | 鸿蒙 PC 本机,DevEco「此电脑」运行 |
| 通知能力 | @ohos.notificationManager(系统原生) |
| 产物 | entry-default-signed.hap,约 43MB |
1. “弹个提示还不行吗”——toast 和系统通知不是一回事
接到需求时,我第一反应是复用已有的 toast:发布图片成功后弹一条"发布成功",不就完了?
但仔细看用户的话——“跟系统真正的消息推送”“提示出来”——他要的不是页面里一闪而过的提示,而是出现在系统通知栏、应用退到后台也能看到的推送。这两者完全不是一回事:
- toast 是应用自己画的一个
View或Modal。它活在应用进程里,页面关掉就没了,应用退到后台根本看不到,也不会留在通知中心。 - 系统通知 是应用把一条消息交给系统,由系统的通知中心展示和管理。它在通知栏里常驻,可以下拉查看,应用没运行也能看到。

所以要发真通知,JS 侧的 showToast 帮不上忙,必须让原生去调系统的通知 API。而这个工程是 RNOH——JS 跑在 Hermes 里,要调原生能力,得走 TurboModule。
2. 效果展示
发布一张图片后,系统通知栏弹出一条通知:标题"图片发布成功",正文"《xxx》已发布到图库"。即使把应用切到后台,这条通知仍然在通知中心里。编辑图片时则发"图片已更新"。
首次发布会先弹一个系统授权框,问用户是否允许本应用发通知。允许之后通知正常发出;拒绝之后不反复打扰,只在应用内用 toast 提示"通知未授权,请在系统设置里开启"。


3. 原理:鸿蒙通知的授权、内容、发布三步
3.1 一个 TurboModule 要跨三层
JS 想调一次系统通知,代码要穿过三层:
- JS 层:
TurboModuleRegistry.get('NotificationModule')拿到模块对象,调publish(title, text)。 - C++ 层:
ArkTSTurboModule包装,把publish这个方法调用转发给 ArkTS。 - ArkTS 层:真正的实现,调
notificationManager.publish()发通知。

这个三层结构和工程里已有的定位模块是一样的。但这次我不打算把篇幅花在"怎么注册 TurboModule"上——那部分原理是通用的。这次要讲的是通知这件事特有的三个细节。
3.2 第一步:运行时授权
鸿蒙的通知不是想发就能发,得先拿到授权。相关 API 有三个:
notificationManager.isNotificationEnabledSync(): boolean; // 同步查授权状态
notificationManager.isNotificationEnabled(): Promise<boolean>; // 异步查
notificationManager.requestEnableNotification(context): Promise<void>; // 弹授权框
我选同步版 isNotificationEnabledSync() 做快速判断,逻辑是:已经授权就直接发;没授权就调 requestEnableNotification(this.ctx.uiAbilityContext) 弹一次系统授权框,弹完再查一次。两次都拿不到授权,就返回 NO_PERMISSION。
这里有个必须克制的地方:不能因为授权失败就反复弹框。系统对 requestEnableNotification 的弹窗次数有约束,用户拒绝一次后再弹只会惹人烦。所以我的实现里失败就返回,把决定权交给用户——想开通知自己去系统设置里开。
3.3 第二步:内容结构,以及两套枚举的坑
一条通知用 NotificationRequest 描述,核心是 content 字段:
const request: notificationManager.NotificationRequest = {
id: Date.now() % 1000000,
content: {
notificationContentType:
notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: title,
text: text,
additionalText: '鸿蒙 PC 图库',
},
},
};
notificationContentType 指定内容布局类型(普通文本、长文本、图片等),normal 提供普通文本通知的标题和正文,必须和类型配套。
这里藏着这次最坑的一个编译错误。 SDK 的 NotificationContent 接口里其实有两个类型字段:
export interface NotificationContent {
contentType?: notification.ContentType; // 旧字段,从 API 11 弃用
notificationContentType?: notificationManager.ContentType; // 新字段
normal?: NotificationBasicContent;
...
}
注意这两个字段的类型不是一个东西:
contentType的类型是@ohos.notification.ContentType(旧模块的枚举)notificationContentType的类型是notificationManager.ContentType(新模块的枚举)
我一开始想当然地写了 contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT——字段名用了旧的,值用了新的。结果编译直接报 10505001:
Type '...notificationManager.default.ContentType' is not assignable to
type '...notification.default.ContentType'.
Property 'NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW' is missing in type
'...notification.default.ContentType'.
报错信息说得很清楚:新枚举比旧枚举多了 NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW 这个成员,所以新枚举不能赋给旧枚举类型的字段。这是两套 API 演进留下的坑——旧字段为了兼容保留了旧枚举类型,新字段才接新枚举。
解法:字段名和值的模块必须配套。要用 notificationManager.ContentType,就得用 notificationContentType 字段:
// 错:旧字段 + 新枚举
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT
// 对:新字段 + 新枚举
notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT
3.4 第三步:三态返回,别把失败当成功
原生方法返回给 JS 的结果,我没有只用一个布尔值,而是设计成三态结构:
export interface NotifyResult {
success: boolean;
code: 'OK' | 'NO_PERMISSION' | 'FAILED';
message: string;
}
为什么要三态?因为通知发布有三种截然不同的结局,用户需要知道是哪种:
| code | 含义 | JS 侧反馈 |
|---|---|---|
OK | 通知已发到系统通知栏 | toast「系统通知已发送」 |
NO_PERMISSION | 用户没授权通知 | toast「通知未授权,请在系统设置里开启」 |
FAILED | 授权了但发布过程异常 | toast「系统通知发送失败」 |
如果只返回一个 boolean,JS 侧看到 false 根本不知道是用户拒绝授权(需要引导去设置)还是发布异常(可能需要重试),给用户的提示只能是一句模糊的"发送失败"。三态返回把"失败的原因"也带过桥,才能给出准确的反馈。
4. 工程怎么搭
这次新增的文件分两组。
ArkTS 侧(harmony/entry/src/main/ets/notification/):
NotificationTurboModule.ts 通知实现:授权检查 + 发布
NotificationPackage.ets 注册到 RNOH
C++ 侧(harmony/entry/src/main/cpp/):
NotificationTurboModule.h/.cpp ArkTSTurboModule 包装
NotificationPackage.h TurboModuleFactoryDelegate
然后在三个注册点接线:PackageProvider.cpp、PackageProvider.ets、CMakeLists.txt。注意没有碰 autolinking.cmake 和 RNOHPackagesFactory——那两个文件会在 hvigor 的 preBuild 阶段被重新生成覆盖,手改了也会丢。

5. 把代码讲透
5.1 ArkTS 侧:授权与发布
核心实现就一个 publish 方法,前面套一层授权检查:
export class NotificationTurboModule extends UITurboModule {
public static readonly NAME = 'NotificationModule';
async publish(title: string, text: string): Promise<NotifyResult> {
const enabled = await this.ensureEnabled();
if (!enabled) {
return {
success: false,
code: 'NO_PERMISSION',
message: '通知未授权,请在系统设置里开启本应用通知',
};
}
try {
const request: notificationManager.NotificationRequest = {
id: Date.now() % 1000000,
content: {
notificationContentType:
notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: title,
text: text,
additionalText: '鸿蒙 PC 图库',
},
},
};
await notificationManager.publish(request);
return {success: true, code: 'OK', message: '通知已发布'};
} catch (e) {
return {
success: false,
code: 'FAILED',
message: `发布失败:${JSON.stringify(e)}`,
};
}
}
}
ensureEnabled() 把授权逻辑收成一个私有方法,先同步查状态,没授权就弹一次授权框再查。发布过程整体 try/catch 兜住,任何异常都转成 FAILED 返回,不让原生异常直接冒到 JS 侧变成红屏。
通知 id 用 Date.now() % 1000000:每次发布生成不同的 id,系统上会显示成多条通知而不是互相覆盖。对"图片发布成功"这种场景,多次发布留多条记录是合理的。
5.2 C++ 侧:参数个数必须对上
C++ 包装层要做的事就是把 JS 的 publish(a, b) 转发给 ArkTS:
static jsi::Value hostFunction_NotificationTurboModule_publish(
jsi::Runtime &rt,
react::TurboModule &turboModule,
const jsi::Value *args,
size_t count) {
return static_cast<ArkTSTurboModule &>(turboModule).call(
rt, "publish", args, count);
}
NotificationTurboModule::NotificationTurboModule(
const ArkTSTurboModule::Context ctx,
const std::string name)
: ArkTSTurboModule(ctx, name) {
methodMap_["publish"] =
MethodMetadata{2, hostFunction_NotificationTurboModule_publish};
}
MethodMetadata 的第一个参数是方法期望的参数个数,这里必须写 2,因为 ArkTS 侧的 publish(title, text) 收两个参数。写错了参数个数,JS 调用时传参和 ArkTS 接收就会对不上——要么参数被截断,要么调用直接失败。
5.3 双侧注册:ArkTS 和 C++ 都要登记
TurboModule 要在两个地方登记,少一个 JS 侧就拿不到模块:
ArkTS 侧(NotificationPackage.ets):
export class NotificationPackage extends RNOHPackage {
override getUITurboModuleFactoryByNameMap() {
return new Map()
.set(NotificationTurboModule.NAME, ctx => new NotificationTurboModule(ctx));
}
}
C++ 侧(NotificationPackage.h):
class NotificationFactoryDelegate : public TurboModuleFactoryDelegate {
public:
SharedTurboModule createTurboModule(Context ctx, const std::string &name) const override {
if (name == "NotificationModule") {
return std::make_shared<NotificationTurboModule>(ctx, name);
}
return nullptr;
}
};
两处的模块名字符串必须完全一致,都是 NotificationModule。JS 侧 TurboModuleRegistry.get('NotificationModule') 也是这个名字——三处对齐,缺一处就找不到模块。
然后在 PackageProvider.cpp 和 PackageProvider.ets 里各 push_back / new 一个 NotificationPackage,在 CMakeLists.txt 的 add_library 里加上 NotificationTurboModule.cpp。
5.4 JS 侧:延迟获取与作用域隔离
JS 侧有两层封装,各解决一个问题。
第一层:延迟获取模块。
let cachedNotificationModule: NotificationSpec | null | undefined;
const getNotificationModule = (): NotificationSpec | null => {
if (cachedNotificationModule !== undefined) {
return cachedNotificationModule;
}
try {
cachedNotificationModule =
TurboModuleRegistry.get<NotificationSpec>('NotificationModule') ?? null;
} catch (e) {
cachedNotificationModule = null;
}
return cachedNotificationModule;
};
不能在模块顶层直接 get:bundle 加载时 ArkTS 侧的 Package 还没注册完,顶层 get 会抛错把 App 打崩。改成首次调用时再取,取不到返回 null,用 try/catch 兜底。
第二层:作用域隔离。
顶层定义了一个 notifySystem:
const notifySystem = async (title: string, text: string): Promise<NotifyResult | null> => {
const module = getNotificationModule();
if (!module) return null;
try {
return await module.publish(title, text);
} catch (e) {
return {success: false, code: 'FAILED', message: String(e)};
}
};
注意它只返回结果,不 toast。原因是一个很容易踩的作用域坑:showToast 是组件内部用 useState 定义的,模块顶层的函数根本引用不到它。如果在顶层 notifySystem 里直接写 showToast(...),编译期就会报"找不到标识符"。
所以拆成两层:顶层 notifySystem 只负责调原生、返回结果;组件内的 publishSystemNotice 拿到结果再转成 toast:
const publishSystemNotice = async (title: string, text: string) => {
const result = await notifySystem(title, text);
if (result === null) {
showToast('系统通知模块不可用');
} else if (result.success) {
showToast('系统通知已发送');
} else if (result.code === 'NO_PERMISSION') {
showToast('通知未授权,请在系统设置里开启');
} else {
showToast('系统通知发送失败');
}
};
这样顶层函数和组件 state 彻底解耦,职责也清楚:一个管调用,一个管反馈。
5.5 触发点:发布图片之后
最后在 submitImage 的成功分支调用。新增图片发"图片发布成功",编辑图片发"图片已更新":
if (editingImageId) {
setImages(/* 更新原记录 */);
publishSystemNotice('图片已更新', `《${payload.title}》的修改已保存`);
} else {
setImages(/* 插入新记录 */);
publishSystemNotice('图片发布成功', `《${payload.title}》已发布到图库`);
}
resetImageForm();
这里是 fire-and-forget:调用 publishSystemNotice 后不 await,通知是异步发出去的,不阻塞图片发布主流程。通知发成功发失败,都不影响图片已经存进列表这个事实。
6. 我踩过的坑(每一条都有真实报错)
坑 1:两套 ContentType 枚举打崩编译
这是本轮最硬的坑。写了 contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,hvigor 直接报:
10505001 ArkTS Compiler Error
Type '...notificationManager.default.ContentType' is not assignable to
type '...notification.default.ContentType'.
Property 'NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW' is missing in type
'...notification.default.ContentType'.
At File: .../NotificationTurboModule.ts:66:11
根因是 contentType 字段期望的是旧模块 @ohos.notification.ContentType,我给的是新模块 notificationManager.ContentType,新旧枚举成员不一致。
解法:用新字段 notificationContentType,它才接新枚举。字段名和值的模块必须配套。
坑 2:顶层 get 打崩启动
如果把 TurboModuleRegistry.get('NotificationModule') 写在模块顶层,bundle 加载时 Package 还没注册,会抛 “Couldn’t find Turbo Module” 把 App 打崩。根因是 JS bundle 的加载时机早于原生 Package 的注册完成时机,两者之间存在一个时间差。
解法:延迟获取 + try/catch + 缓存三态(undefined/null/模块),首次调用时再取。
坑 3:模块顶层函数引用不到 showToast
在顶层 notifySystem 里直接写 showToast(...),编译报找不到标识符。showToast 是组件内用 useState 定义的,模块顶层函数不在这个作用域里。
解法:拆两层。顶层只调原生返回结果,组件内包装结果转 toast。
坑 4:MethodMetadata 参数个数写错
C++ 的 MethodMetadata{2, ...} 第一个参数是参数个数。一开始对"参数个数到底要不要算 this"有疑虑,写错过。 ArkTS 侧 publish(title, text) 收两个参数,C++ 就必须写 2。
解法:按 ArkTS 方法的形参数量写,不多不少。
坑 5:授权被拒后反复弹框
最早的实现里,授权失败会再次调 requestEnableNotification,用户拒绝一次后接着弹,体验很差。系统对这个弹窗也有次数约束。
解法:失败就返回 NO_PERMISSION,不重试。想重新开启让用户去系统设置,把决定权交还用户。
坑 6:改了 autolink 文件,构建时被覆盖
手动在 autolinking.cmake 和 RNOHPackagesFactory 里加过注册,结果 hvigor preBuild 阶段把这些文件重新生成,改动全丢,出现"构建成功但模块找不到"的假象。
解法:只改不会被覆盖的 PackageProvider.cpp/.ets 和 CMakeLists.txt,碰都别碰 autolink 生成的文件。
坑 7:JS 改完直接打 HAP,结果没生效
有一轮改完 JS 就打 HAP,装上发现通知没触发。原因是 JS 改动必须先经 Metro 打包进 bundle.harmony.js,HAP 里跑的是打包产物。
解法:JS 改动后先跑打包命令,确认新关键词进包,再打 HAP。
坑 8:验证符号进包,别只看构建成功
构建成功只说明代码编过了,不代表模块真的接上了。我用两层验证:C++ so 里查 NotificationModule 字符串,ArkTS 字节码 modules.abc 里查 NotificationPackage、NotificationTurboModule。两边都有,才算真接线。
7. 从代码到 HAP
原生 + JS 都改了,完整流程是:
# 1. 重新打 Metro bundle(JS 改动必须经过这一步)
cd /storage/Users/currentUser/Documents/DevEcoStudioProjects/hello-rnoh-pc
env -u CODEBUDDY_SAFE_DELETE_BULK_STATE_DIR -u CODEBUDDY_TOOL_CALL_ID npm run dev
# 2. 确认通知代码进了 bundle
grep -oE "NotificationModule|notifySystem|publishSystemNotice|图片发布成功" \
harmony/entry/src/main/resources/rawfile/bundle.harmony.js | sort -u
# 3. 构建 HAP(C++/ArkTS 改动会一起编进去)
cd harmony
env -u CODEBUDDY_SAFE_DELETE_BULK_STATE_DIR -u CODEBUDDY_TOOL_CALL_ID \
DEVECO_SDK_HOME=/data/service/hnp/hmos-clt.org/hmos-clt_1.0.0/sdk \
/data/service/hnp/hmos-clt.org/hmos-clt_1.0.0/node/bin/node \
/data/service/hnp/hmos-clt.org/hmos-clt_1.0.0/hvigor/bin/hvigorw.js \
assembleHap --mode module -p product=default -p module=entry@default --no-daemon
# 4. 确认符号真的进了产物
strings entry/build/default/intermediates/libs/default/arm64-v8a/librnoh_app.so \
| grep -i NotificationModule
strings entry/build/default/intermediates/loader_out/default/ets/modules.abc \
| grep -i Notification
第 4 步是我后来加的习惯——构建成功不等于接线成功,符号级验证才能排除"假成功"。
总结
这次接系统通知,表面上是加一个 TurboModule,实际上被三个细节卡了很久,而这三个细节恰好代表了三类不同的问题。
第一类是编译期的类型坑。两套 ContentType 枚举并存,旧字段接旧枚举、新字段接新枚举,赋值时字段名和值的模块必须配套。报错 10505001 看着像类型系统小题大做,其实是两套 API 演进留下的真实差异——新枚举多了成员,不能往旧枚举的字段里塞。这类问题没有捷径,只能回到 SDK 声明文件,把 NotificationContent 的字段定义逐行看清楚,确认每个字段的确切类型。
第二类是运行时的授权设计。通知不是想发就能发,授权状态要主动查、主动申请,还要克制——用户拒绝后不能反复弹框。我把授权检查收成一个私有方法,把失败明确区分成 NO_PERMISSION 和 FAILED,本质上是承认"有些失败是用户的主动选择,不是技术故障",系统要尊重这个选择,应用也要给出对应的引导。
第三类是跨层的边界处理。JS 顶层函数引用不到组件内的 showToast,这是作用域边界;TurboModule 顶层 get 会打崩启动,这是时机边界;MethodMetadata 参数个数要和 ArkTS 方法对齐,这是接口边界。三处边界如果都当"细节"略过,代码能写出来的,但跑起来处处是坑。我的处理原则是:把不确定性挡在边界上——拿不到模块返回 null 而不是抛错,原生异常转成结构化结果而不是红屏,顶层函数只做纯调用不碰组件状态。
把这三件事放一起看,会有一个更深的感受:所谓"接一个原生能力",真正工作量不在接线本身,而在处理两套系统之间的错位。 JS 和 ArkTS 是两套类型系统、两套生命周期、两套错误模型,TurboModule 是它们之间的桥,但桥不会自动抹平差异。枚举不兼容是类型系统的错位,顶层 get 崩溃是生命周期的错位,作用域问题是编程模型的错位。好的接入代码,就是把这些错位一处一处识别出来、在边界上显式处理掉。
更多推荐


所有评论(0)