公司动态
Expo 推送通知实战教程:15分钟让通知真正送达用户手机
Expo 推送通知实战教程15分钟让通知真正送达用户手机【免费下载链接】expoAn open-source framework for making universal native apps with React. Expo runs on Android, iOS, and the web.项目地址: https://gitcode.com/GitHub_Trending/ex/expo订单发货了、好友点赞了、活动开始了——这些主动找用户的时刻靠的都是推送通知。这篇 Expo 通知expo-notifications教程面向新手手把手带你从零跑通完整流程申请权限、拿到推送令牌、发出第一条推送、处理通知点击。全程不需要写一行原生代码15 分钟左右就能在真机上收到一条由你亲手发出去的通知。 先预览最终效果完成本教程后你的应用会具备三种能力启动时自动申请通知权限并生成一个绑定设备的ExpoPushToken推送令牌点一下按钮就能通过 Expo 推送服务向这台设备发送一条标题 正文 自定义数据的推送无论应用在前台、后台还是被用户划掉通知都能按预期呈现点击通知还能跳回指定页面。为什么 Expo 通知适合跨平台项目推送通知历来是 React Native 开发者最头疼的部分Android 要配 FirebaseiOS 要申请 APNs 证书两端的 API 还各说各话。Expo 通知模块把这套复杂度封装掉了核心价值有四点一套 API 双端通用请求权限、获取令牌、监听事件Android 和 iOS 调用完全一致令牌即发即用ExpoPushToken一个令牌同时打通 FCM 与 APNs后端不需要分别对接两家厂商配置插件自动改原生把expo-notifications写进app.json原生工程的通知相关设置由插件替你生成不用手改 Gradle 或 Podfile不锁死推送服务想直接对接 FCM / APNs 也完全可以expo-notifications的 API 与具体推送服务解耦。 快速上手四步发出第一条推送第 1 步安装依赖在项目根目录执行npx expo install expo-notifications expo-constantsexpo-notifications负责权限、令牌与通知的全部逻辑expo-constants用来从应用配置里读取projectId令牌需要绑定项目。第 2 步注册配置插件在app.json或app.config.js中加入{ expo: { plugins: [ expo-notifications ] } }插件会在 prebuild / 构建阶段自动写入 Android 与 iOS 的通知配置比如 Android 的通知图标、iOS 的 push 能力声明。第 3 步写入最小可用代码下面的示例覆盖了完整链路前台处理策略 → 权限 → 令牌 → 发送 → 监听。直接替换你的App.tsx即可运行import { useState, useEffect } from react; import { Text, View, Button, Platform } from react-native; import * as Notifications from expo-notifications; import Constants from expo-constants; // ① 声明前台收到通知时的呈现策略 Notifications.setNotificationHandler({ handleNotification: async () ({ shouldShowBanner: true, // 顶部横幅 shouldShowList: true, // 进入通知中心 shouldPlaySound: true, // 播放声音 shouldSetBadge: true, // 更新应用角标 }), }); // ② 请求权限并获取 ExpoPushToken async function registerForPushNotificationsAsync() { // Android 8.0 必须显式创建通知渠道否则通知可能被静默 if (Platform.OS android) { await Notifications.setNotificationChannelAsync(default, { name: default, importance: Notifications.AndroidImportance.MAX, }); } // 先看现有权限未授权才弹窗请求避免打扰用户 const { status: existing } await Notifications.getPermissionsAsync(); const { status } existing granted ? { status: granted as const } : await Notifications.requestPermissionsAsync(); if (status ! granted) return null; // 令牌绑定 projectId项目换账号、改名后令牌依然有效 const projectId Constants.expoConfig?.extra?.eas?.projectId ?? Constants.easConfig?.projectId; return (await Notifications.getExpoPushTokenAsync({ projectId })).data; } // ③ 通过 Expo 推送服务发送测试推送 async function sendPushNotification(token: string) { const payload { to: token, sound: default, title: Hello Expo!, body: 这是你的第一条 Expo 通知, data: { screen: detail, id: 123 }, // 自定义数据供深度链接使用 }; await fetch(https://exp.host/--/api/v2/push/send, { method: POST, headers: { Content-Type: application/json }, body: JSON.stringify(payload), }); } export default function App() { const [token, setToken] useState(); const [last, setLast] useStateNotifications.Notification(); useEffect(() { registerForPushNotificationsAsync().then(t setToken(t ?? )); // 前台监听JS 层第一时间感知通知到达 const received Notifications.addNotificationReceivedListener(setLast); // 点击监听用户点击通知后触发可在此做路由跳转 const tapped Notifications.addNotificationResponseReceivedListener(r console.log(通知被点击:, r.notification.request.content.data), ); return () { received.remove(); tapped.remove(); }; }, []); return ( View style{{ flex: 1, alignItems: center, justifyContent: center }} Text推送令牌: {token}/Text Text最近收到: {last?.request.content.body}/Text Button title发送测试通知 disabled{!token} onPress{() sendPushNotification(token)} / /View ); }第 4 步配置凭据构建并在真机测试推送需要平台凭据两端各做一次只需一次平台凭据操作要点AndroidFCMFirebase创建 Firebase 项目、生成google-services.json再通过eas credentials上传iOSAPNs需要 Apple Developer 账号首次eas build时按提示启用推送并生成 APNs 密钥随后构建并测试eas build # 生成包含通知配置的 development build npx expo start # 启动开发服务器安装后打开应用拿到屏幕上显示的令牌粘贴到 Expo 官网的推送测试工具中填写标题正文点击发送即可。⚠️ 推送必须用真机验证Android 模拟器需带 Google Play 服务iOS 模拟器需 Xcode 14 及以上。 机制拆解一条推送到底怎么送达三种应用状态三种行为同一条推送到达时的表现取决于应用当时处于什么状态应用状态推送的呈现方式前台完全由你的 JS 代码接管setNotificationHandler决定横幅/声音/角标addNotificationReceivedListener同步触发后台 / 已被划掉系统原生显示通知应用不参与渲染用户点击通知触发addNotificationResponseReceivedListener应用未运行时iOS 端建议尽早注册监听并在启动时用getLastNotificationResponse()补查点击动作最后一个细节很关键从通知点进来冷启动时监听器可能还没挂载完毕。所以除了注册监听最好在应用启动时调用一次getLastNotificationResponse()确保点击通知 → 跳转对应页面的深度链接 100% 生效。无感后台任务Headless 通知不是所有推送都需要弹给用户看。只带data字段、没有标题正文的推送称为Headless 通知——系统不展示任何 UI而是唤醒一段 JS 任务默默处理数据比如静默拉取内容、写入存储甚至再弹一条自定义的本地通知// 注册一个后台任务收到 headless 推送时静默执行 Notifications.registerTaskAsync(syncTask, { data: async ({ data }) { // 写本地存储、请求接口、或展示本地通知 console.log(后台收到数据:, data); }, }); 进阶玩法定时与重复的本地通知——不用服务器本地就能排期// 5 分钟后提醒一次 await Notifications.scheduleLocalNotificationAsync( { title: 休息一下, body: 该看看眼睛了 }, { seconds: 300 }, );Android 渠道精细管理——不同业务走不同渠道订单、社交、营销用户可以单独关闭某一类await Notifications.setNotificationChannelAsync(order, { name: 订单更新, importance: Notifications.AndroidImportance.HIGH, }); // 发送时在 payload 中指定 channelId: order自定义声音与图标——把音频文件放进assets目录在 payload 的sound字段引用文件名即可Android 图标与强调色可通过配置插件的 options 参数定制。直连 FCM / APNs——如果后端已经在用 Firebase 或自建 APNs 通道无需切换到 Expo 推送服务expo-notifications客户端能力照常使用详见 docs/pages/push-notifications/sending-notifications-custom.mdx。❓ 常见问题速查模拟器上收不到推送正常现象推送依赖系统级推送通道请换真机或符合条件的模拟器。令牌获取失败依次检查是否真机、projectId是否正确注入、权限弹窗是否被拒绝拒绝后需引导用户去系统设置开启。前台收到推送却不弹横幅检查setNotificationHandler是否返回了shouldShowBanner: true——前台行为完全由它决定。Android 8.0 通知静默大概率是通知渠道没建或渠道 importance 过低。Android 用户从系统设置强行停止后收不到这是 Android 系统限制无法通过代码绕过建议在新手引导中说明。更多问题可查阅docs/pages/push-notifications/faq.mdx 延伸阅读与相关资源资源说明docs/pages/push-notifications/overview.mdx推送服务总览docs/pages/push-notifications/what-you-need-to-know.mdx各类通知类型与三态行为详解docs/pages/push-notifications/fcm-credentials.mdxAndroid FCM V1 凭据配置docs/pages/push-notifications/receiving-notifications.mdx接收与响应通知packages/expo-notifications通知模块源码apps/notification-tester仓库内置的通知测试应用现在就动手克隆仓库把上面的示例代码贴进你自己的项目按四步走一遍——权限、令牌、构建、发送15 分钟后你的手机会收到第一条由你完全掌控的 Expo 推送通知git clone https://gitcode.com/GitHub_Trending/ex/expo推送是留存利器先把能收到跑通再逐步加上渠道分级、深度链接和静默同步。祝上线顺利【免费下载链接】expoAn open-source framework for making universal native apps with React. Expo runs on Android, iOS, and the web.项目地址: https://gitcode.com/GitHub_Trending/ex/expo创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考