了解如何设置推送通知、获取开发和生产凭据以及测试发送推送通知。
要利用 Expo 的推送通知服务,你必须通过安装一组库、实现处理通知的函数以及设置 Android 和 iOS 凭据来配置你的应用。完成本指南中提到的步骤后,你将能够测试在设备上发送和接收通知。
¥To utilize Expo's push notification service, you must configure your app by installing a set of libraries, implementing functions to handle notifications, and setting up credentials for Android and iOS. Once you have completed the steps mentioned in this guide, you'll be able to test sending and receiving notifications on a device.
要让客户端准备好推送通知,需要执行以下操作:
¥To get the client-side ready for push notifications, the following things are required:
用户向其发送推送通知的权限。
¥The user's permission to send them push notifications.
用户的 ExpoPushToken
。
¥The user's ExpoPushToken
.
你可能需要对通知进行更细粒度的控制,因此可能需要直接与 FCM 和 APN 进行通信。Expo 平台不会限制你使用 Expo 的应用服务,并且 expo-notifications
API 与推送服务无关。了解如何 "使用 FCMv1 和 APN 发送通知"。
¥You may need finer-grained control over your notifications, so communicating directly with FCM and APNs may be necessary. The Expo platform does not lock you into using Expo's application services, and the expo-notifications
API is push-service agnostic. Learn how to "Send notifications with FCMv1 and APNs".
¥Prerequisites
本指南中描述的以下步骤使用 EAS 构建。但是,你可以通过构建 你的本地项目 来使用 expo-notifications
库,而无需 EAS Build。
¥The following steps described in this guide use EAS Build. However, you can use the expo-notifications
library without EAS Build by building your project locally.
1
¥Install libraries
运行以下命令安装 expo-notifications
、expo-device
和 expo-constants
库:
¥Run the following command to install the expo-notifications
, expo-device
and expo-constants
libraries:
-
npx expo install expo-notifications expo-device expo-constants
expo-notifications
库用于请求用户的许可并获取 ExpoPushToken
。Android 模拟器或 iOS 模拟器不支持它。
¥expo-notifications
library is used to request a user's permission and to fetch the ExpoPushToken
. It is not supported on an Android Emulator or an iOS Simulator.
expo-device
用于检查应用是否在物理设备上运行。
¥expo-device
is used to check whether the app is running on a physical device.
expo-constants
用于从应用配置中获取 projectId
值。
¥expo-constants
is used to get the projectId
value from the app config.
2
¥Add a minimal working example
下面的代码显示了如何在 React Native 应用中注册、发送和接收推送通知的工作示例。将其复制并粘贴到你的项目中:
¥The code below shows a working example of how to register for, send, and receive push notifications in a React Native app. Copy and paste it into your project:
import { useState, useEffect, useRef } from 'react';
import { Text, View, Button, Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});
async function sendPushNotification(expoPushToken: string) {
const message = {
to: expoPushToken,
sound: 'default',
title: 'Original Title',
body: 'And here is the body!',
data: { someData: 'goes here' },
};
await fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-encoding': 'gzip, deflate',
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
});
}
function handleRegistrationError(errorMessage: string) {
alert(errorMessage);
throw new Error(errorMessage);
}
async function registerForPushNotificationsAsync() {
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
if (Device.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
handleRegistrationError('Permission not granted to get push token for push notification!');
return;
}
const projectId =
Constants?.expoConfig?.extra?.eas?.projectId ?? Constants?.easConfig?.projectId;
if (!projectId) {
handleRegistrationError('Project ID not found');
}
try {
const pushTokenString = (
await Notifications.getExpoPushTokenAsync({
projectId,
})
).data;
console.log(pushTokenString);
return pushTokenString;
} catch (e: unknown) {
handleRegistrationError(`${e}`);
}
} else {
handleRegistrationError('Must use physical device for push notifications');
}
}
export default function App() {
const [expoPushToken, setExpoPushToken] = useState('');
const [notification, setNotification] = useState<Notifications.Notification | undefined>(
undefined
);
const notificationListener = useRef<Notifications.Subscription>();
const responseListener = useRef<Notifications.Subscription>();
useEffect(() => {
registerForPushNotificationsAsync()
.then(token => setExpoPushToken(token ?? ''))
.catch((error: any) => setExpoPushToken(`${error}`));
notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
setNotification(notification);
});
responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
console.log(response);
});
return () => {
notificationListener.current &&
Notifications.removeNotificationSubscription(notificationListener.current);
responseListener.current &&
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'space-around' }}>
<Text>Your Expo push token: {expoPushToken}</Text>
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
<Text>Title: {notification && notification.request.content.title} </Text>
<Text>Body: {notification && notification.request.content.body}</Text>
<Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
</View>
<Button
title="Press to Send Notification"
onPress={async () => {
await sendPushNotification(expoPushToken);
}}
/>
</View>
);
}
projectId
¥Configure projectId
使用前面的示例,当你注册推送通知时,你需要使用 projectId
。该属性用于将 Expo 推送令牌归因于特定项目。对于使用 EAS 的项目,projectId
属性表示该项目的通用唯一标识符 (UUID)。
¥Using the previous example, when you are registering for push notifications, you need to use projectId
. This property is used to attribute Expo push token to the specific project. For projects using EAS, the projectId
property represents the Universally Unique Identifier (UUID) of that project.
当你创建开发版本时,projectId
会自动设置。但是,我们建议在项目代码中手动设置它。为此,你可以使用 expo-constants
从应用配置中获取 projectId
值。
¥projectId
is automatically set when you create a development build. However, we recommend setting it manually in your project's code. To do so, you can use expo-constants
to get the projectId
value from the app config.
token = await Notifications.getExpoPushTokenAsync({
projectId: Constants.expoConfig.extra.eas.projectId,
});
将 Expo 推送令牌分配给项目 ID 的优点之一是,当项目在不同账户之间转移或现有账户被重命名时,它不会发生变化。
¥One advantage of attributing the Expo push token to your project's ID is that it doesn't change when a project is transferred between different accounts or the existing account gets renamed.
3
¥Get credentials for development builds
对于 Android 和 iOS,设置凭据有不同的要求。
¥For Android and iOS, there are different requirements to set up your credentials.
对于 Android,你需要配置 Firebase Cloud Messaging (FCM) V1 以获取凭据并设置你的 Expo 项目。
¥For Android, you need to configure Firebase Cloud Messaging (FCM) V1 to get credentials and set up your Expo project.
按照 添加 Android FCM V1 凭据 中的步骤设置你的凭据。
¥Follow the steps in Add Android FCM V1 credentials to set up your credentials.
需要付费的 Apple 开发者账户才能生成凭据。
对于 iOS,在首次运行 eas build
命令之前,请确保你有要测试的 注册你的 iOS 设备。
¥For iOS, make sure you have registered your iOS device on which you want to test before running the eas build
command for the first time.
如果你第一次创建开发版本,系统会要求你启用推送通知。当 EAS CLI 提示时,对以下问题回答“是”:
¥If you create a development build for the first time, you'll be asked to enable push notifications. Answer yes to the following questions when prompted by the EAS CLI:
为你的项目设置推送通知
¥Setup Push Notifications for your project
生成新的 Apple 推送通知服务密钥
¥Generating a new Apple Push Notifications service key
如果你不使用 EAS Build,请手动运行
eas credentials
。¥If you are not using EAS Build, run
eas credentials
manually.
4
¥Test using the push notifications tool
创建并安装开发版本后,你可以使用 Expo 的推送通知工具 快速向你的设备发送测试通知。
¥After creating and installing the development build, you can use Expo's push notifications tool to quickly send a test notification to your device.
启动你的项目的开发服务器:
¥Start the development server for your project:
-
npx expo start
在你的设备上打开开发版本。
¥Open the development build on your device.
生成 ExpoPushToken
后,在 Expo 推送通知工具中输入该值以及其他详细信息(例如消息标题和正文)。
¥After the ExpoPushToken
is generated, enter the value in the Expo push notifications tool with other details (for example, a message title and body).
单击发送通知按钮。
¥Click on the Send a Notification button.
从该工具发送通知后,你应该会在设备上看到该通知。以下是 Android 设备接收推送通知的示例。
¥After sending the notification from the tool, you should see the notification on your device. Below is an example of an Android device receiving a push notification.