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

如何使用React Native实现每日定时推送本地通知

双端每日7点定时本地通知实现方案

以下是基于zo0r/react-native-push-notification库的适配iOS、安卓双端的实现步骤:

前置准备

先确保库已完成原生侧集成,iOS侧执行过pod install,安卓侧已完成自动link配置。

基础初始化配置

1. 权限与全局配置

import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from '@react-native-community/push-notification-ios';

PushNotification.configure({
  onRegister: (token) => {
    console.log('通知注册token:', token);
  },
  onNotification: (notification) => {
    // iOS端必填,处理完通知后回调
    notification.finish(PushNotificationIOS.FetchResult.NoData);
  },
  permissions: {
    alert: true,
    badge: true,
    sound: true,
  },
  popInitialNotification: true,
  requestPermissions: true,
});

2. 安卓端通知渠道创建(必做)

安卓8.0及以上系统要求所有通知必须绑定渠道,需提前创建:

PushNotification.createChannel(
  {
    channelId: "daily_reminder_channel",
    channelName: "每日提醒",
    channelDescription: "每日7点定时提醒通知渠道",
    soundName: "default",
    importance: 4,
    vibrate: true,
  },
  (created) => console.log('通知渠道创建状态:', created)
);

定时通知核心逻辑

const setDaily7AMNotification = () => {
  // 先取消同ID的旧通知,避免重复创建
  PushNotification.cancelLocalNotifications({ id: 'daily_7am_notify' });

  // 计算触发时间
  const triggerDate = new Date();
  triggerDate.setHours(7, 0, 0, 0); // 设为今日7点整

  // 若当前时间已过今日7点,自动顺延到次日7点
  if (triggerDate < new Date()) {
    triggerDate.setDate(triggerDate.getDate() + 1);
  }

  PushNotification.localNotificationSchedule({
    id: 'daily_7am_notify',
    channelId: 'daily_reminder_channel', // 安卓需与上面的渠道ID完全一致
    title: '每日提醒',
    message: '你设置的7点提醒已触发',
    date: triggerDate,
    repeatType: 'day', // 按天重复,双端通用配置
    allowWhileIdle: true, // 安卓低电耗模式下也可触发
    sound: 'default',
    playSound: true,
    priority: 'high',
    importance: 'high',
  });
};

// 调用时机:应用初始化完成后调用一次即可
setDaily7AMNotification();

分端额外配置

  • Android端:
    在android/app/src/main/AndroidManifest.xml中添加以下权限:

    <!-- 安卓13+通知权限 -->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <!-- 精确闹钟权限,保障定时触发 -->
    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
    <!-- 设备重启后自动恢复定时通知 -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    

    注:国产安卓系统需引导用户开启应用的自启动、后台活动权限,避免进程被系统查杀后通知无法触发

  • iOS端:
    打开Xcode项目,在Signing & Capabilities标签下添加两个配置:

    1. 开启Push Notifications能力
    2. 开启Background Modes,勾选Remote notifications选项
      注:iOS端通知必须获得用户授权才能弹出,若用户拒绝权限则无法触发

测试建议

可先将triggerDate的小时参数改为当前时间+1分钟,验证通知可正常触发后,再改回7点的正式配置。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:09:03