如何在Expo中使用Firebase?及安卓iOS端推送通知实现方法
在Expo项目中使用Firebase & 实现推送通知指南
嘿,我来一步步帮你搞定这两个问题,都是Expo+Firebase开发里的高频需求~
一、Expo项目集成Firebase的基础步骤
1. 前置准备
先去Firebase控制台创建一个项目,然后分别添加Android和iOS应用(跟着控制台指引填包名/Bundle ID就行),之后下载对应的配置文件:Android的google-services.json和iOS的GoogleService-Info.plist。
2. 安装Firebase依赖
根据你需要用到的Firebase功能(比如认证、数据库、存储等),安装对应的Expo Firebase模块,核心的expo-firebase-core是必须的:
npx expo install expo-firebase-core expo-firebase-auth expo-firebase-firestore
(上面是举例,你可以根据需求增减模块,比如不需要认证就去掉expo-firebase-auth)
3. 配置Firebase到项目
这里分两种项目类型:
- Managed Workflow(未Eject的Expo项目):直接在
app.json或app.config.js的expo字段下添加firebase配置块,把Firebase控制台里的项目参数填进去:
{ "expo": { // ...其他配置 "firebase": { "apiKey": "你的API_KEY", "authDomain": "你的AUTH_DOMAIN", "projectId": "你的PROJECT_ID", "storageBucket": "你的STORAGE_BUCKET", "messagingSenderId": "你的SENDER_ID", "appId": "你的APP_ID" } } }
- Bare Workflow(已Eject的项目):把下载的
google-services.json和GoogleService-Info.plist放到项目根目录,然后在app.json里指定路径:
{ "expo": { "ios": { "googleServicesFile": "./GoogleService-Info.plist" }, "android": { "googleServicesFile": "./google-services.json" } } }
4. 初始化Firebase
在项目的入口文件(比如App.js)里初始化Firebase:
import { initializeApp } from 'expo-firebase-core'; const firebaseApp = initializeApp(); // 之后就可以使用其他Firebase模块了,比如认证 import { getAuth } from 'expo-firebase-auth'; const auth = getAuth(firebaseApp);
二、基于Firebase实现Expo推送通知(仅Android/iOS)
Expo的推送通知依赖expo-notifications和Firebase Cloud Messaging(FCM),步骤如下:
1. 安装推送相关依赖
npx expo install expo-notifications expo-firebase-messaging
2. 请求用户通知权限
在APP启动时请求用户授权,没有权限的话收不到推送:
import * as Notifications from 'expo-notifications'; import { useEffect } from 'react'; async function requestNotificationPermissions() { const { status } = await Notifications.requestPermissionsAsync({ ios: { allowAlert: true, allowBadge: true, allowSound: true, allowAnnouncements: true, }, android: { allowAlert: true, allowBadge: true, allowSound: true, allowVibrate: true, }, }); if (status !== 'granted') { alert('需要开启通知权限才能接收推送哦'); return false; } return true; } // 在组件挂载时调用 useEffect(() => { requestNotificationPermissions(); }, []);
3. 获取FCM设备令牌
这个令牌是Firebase用来定位设备的唯一标识,需要把它保存到你的后端或Firebase数据库,用来给指定设备发推送:
import { getToken } from 'expo-firebase-messaging'; async function getFCMToken() { const hasPermission = await requestNotificationPermissions(); if (!hasPermission) return; try { const token = await getToken(); if (token) { console.log('FCM令牌获取成功:', token); // 这里可以把token上传到你的后端/Firestore } } catch (error) { console.error('获取FCM令牌失败:', error); } } useEffect(() => { getFCMToken(); }, []);
4. 监听通知事件
处理APP在不同状态下的通知:
- 前台收到通知:当APP在前台运行时,默认不会弹出系统通知,需要自己监听并处理:
useEffect(() => { const notificationReceivedSubscription = Notifications.addNotificationReceivedListener(notification => { console.log('前台收到通知:', notification); // 这里可以自定义处理,比如弹出自定义弹窗、更新UI等 }); return () => notificationReceivedSubscription.remove(); }, []);
- 点击通知的处理:不管APP在前台、后台还是完全关闭,点击通知后的跳转逻辑都可以在这里处理:
useEffect(() => { const notificationResponseSubscription = Notifications.addNotificationResponseReceivedListener(response => { console.log('通知被点击:', response); // 比如跳转到指定页面:navigation.navigate('DetailScreen', { id: response.notification.request.content.data.id }); }); return () => notificationResponseSubscription.remove(); }, []);
5. 测试推送通知
打开Firebase控制台,进入Cloud Messaging模块:
- 点击「发送您的第一条消息」
- 填写通知标题和内容,点击「下一步」
- 选择「单个设备」,输入刚才获取的FCM令牌,点击「测试」
- 分别测试APP前台、后台、完全关闭三种状态,确认都能收到通知
6. 关键注意事项
- Android:需要在
app.json里添加通知权限配置:
"android": { // ...其他配置 "permissions": ["POST_NOTIFICATIONS"], "useNextNotificationsApi": true }
- iOS:需要在Apple开发者后台配置APNs推送证书,然后上传到Firebase控制台的iOS应用配置里,否则iOS设备收不到推送
- Bare Workflow:需要额外配置原生项目的推送相关设置,比如Android的
AndroidManifest.xml和iOS的AppDelegate.swift
内容的提问来源于stack exchange,提问作者Alo
相关产品推荐
相关产品推荐

