You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native中NativeModules.NotificationModule执行后触发应用重载?

实现方案

1. 确保Native方法执行完成

首先需确认NativeModules.NotificationModule.triggerFullScreenNotification的异步状态,否则后续重载代码会提前执行,无法满足"运行完成后触发"的需求:

  • 如果原生方法已支持Promise,直接添加await等待执行完成:
await NativeModules.NotificationModule.triggerFullScreenNotification(
  remoteMessage.notification.title,
  remoteMessage.notification.body,
  'limestone'
);
  • 如果原生方法是回调形式,先封装为Promise:
const triggerNotification = (title, body, type) => {
  return new Promise((resolve, reject) => {
    NativeModules.NotificationModule.triggerFullScreenNotification(
      title,
      body,
      type,
      (success) => success ? resolve() : reject(new Error('Notification trigger failed'))
    );
  });
};

// 调用时添加await
await triggerNotification(
  remoteMessage.notification.title,
  remoteMessage.notification.body,
  'limestone'
);

2. 实现React Native应用重载

开发环境

直接使用RN内置的DevSettings:

import { DevSettings } from 'react-native';

// 在需要重载的位置调用
DevSettings.reload();

生产环境

DevSettings仅在开发环境生效,生产环境可选择以下两种方案:

方案1:使用第三方库

安装react-native-restart后直接调用:

import RNRestart from 'react-native-restart';

RNRestart.Restart();

方案2:原生层实现重载(Android)

无需依赖第三方库,在原生NotificationModule的方法执行完成后添加重载逻辑:

ReactInstanceManager manager = getReactInstanceManager();
if (manager != null) {
    manager.recreateReactContextInBackground();
}

完整代码示例(基于Promise支持的Native方法)

import { Platform, DevSettings } from 'react-native';
import { messaging } from '@react-native-firebase/messaging';
// 生产环境请导入RNRestart
// import RNRestart from 'react-native-restart';

messaging().setBackgroundMessageHandler(async remoteMessage => {
  if (Platform.OS === 'ios') {
    onMessageReceived(remoteMessage);
  }

  if (Platform.OS === 'android') {
    console.log("before modules");
    try {
      // 等待Native通知逻辑执行完成
      await NativeModules.NotificationModule.triggerFullScreenNotification(
        remoteMessage.notification.title,
        remoteMessage.notification.body,
        'limestone'
      );
      console.log('Android Message handled in the background');
      console.log(remoteMessage);
      
      // 触发应用重载
      if (__DEV__) {
        DevSettings.reload();
      } else {
        // RNRestart.Restart();
        // 若选择原生层重载,此处无需额外代码
      }
    } catch (error) {
      console.error('Notification trigger failed:', error);
    }
  }
});

内容的提问来源于stack exchange,提问作者Otonye Amietubodie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 17:17:17