This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
Expo 通知
一个提供 API,用于获取推送通知令牌,以及展示、安排、接收和响应通知的库。
原文内容已经是简体中文,无需翻译。
在 iOS 上,通知类别还允许你进一步自定义通知。对于每个类别,你可以设置用户可执行的交互操作,并配置一些选项,例如当用户为你的应用关闭通知预览时显示的占位文本。
平台特定指南
处理通知渠道 Android 8+
从 Android 8.0(API 级别 26)开始,所有通知都必须分配到一个渠道。对于每个渠道, 你可以设置应用于该渠道中所有通知的视觉和听觉行为。 然后,用户可以更改这些设置,并决定来自你的应用的哪些通知渠道应当具有干扰性或完全可见, 正如 Android 开发者文档 所述。
如果你没有指定通知渠道,expo-notifications 会为你创建一个回退渠道,名为 Miscellaneous。
我们建议你始终确保为应用设置带有说明性名称的合适渠道,并始终将通知发送到这些渠道。
对于不支持此功能的平台(Android 8.0(26)以下版本和 iOS),调用这些方法不会产生任何作用。
自定义通知图标和颜色 Android
你可以通过使用 Expo Prebuild 与 expo-notifications 配置插件 来为项目中的通知配置 icon 和 color 键。这些都是构建时设置,因此你需要使用 eas build -p android 或 npx expo run:android 重新编译原生 Android 应用才能看到更改。
对于通知图标,请确保你遵循 Google 的设计指南 (图标必须是全白色且背景透明),否则它可能不会按预期显示。
你也可以直接在 NotificationContentInput 的 color 属性下,针对每条通知设置自定义通知颜色。
API
import * as Notifications from 'expo-notifications';
获取推送通知的令牌
In rare situations, a push token may be changed by the push notification service while the app is running. When a token is rolled, the old one becomes invalid and sending notifications to it will fail. A push token listener will let you handle this situation gracefully by registering the new token with your backend right away.
EventSubscriptionAn EventSubscription object represents the subscription of the provided listener.
Example
import React from 'react'; import * as Notifications from 'expo-notifications'; import { registerDevicePushTokenAsync } from '../api'; export default function App() { React.useEffect(() => { const subscription = Notifications.addPushTokenListener(registerDevicePushTokenAsync); return () => subscription.remove(); }, []); return ( // Your app content ); }
Returns a native FCM, APNs token or a PushSubscription data
that can be used with another push notification service.
Promise<DevicePushToken>Returns an Expo token that can be used to send a push notification to the device using Expo's push notifications service.
This method makes requests to the Expo's servers. It can get rejected in cases where the request itself fails
(for example, due to the device being offline, experiencing a network timeout, or other HTTPS request failures).
To provide offline support to your users, you should try/catch this method and implement retry logic to attempt
to get the push token later, once the device is back online.
For Expo's backend to be able to send notifications to your app, you will need to provide it with push notification keys. For more information, see credentials in the push notifications setup.
Promise<ExpoPushToken>Returns a Promise that resolves to an object representing acquired push token.
Example
import * as Notifications from 'expo-notifications'; export async function registerForPushNotificationsAsync(userId: string) { const expoPushToken = await Notifications.getExpoPushTokenAsync({ projectId: 'your-project-id', }); await fetch('https://example.com/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ userId, expoPushToken, }), }); }
监听通知事件
Listeners registered by this method will be called whenever a notification is received while the app is running.
EventSubscriptionAn EventSubscription object represents the subscription of the provided listener.
Example
import React from 'react'; import * as Notifications from 'expo-notifications'; export default function App() { React.useEffect(() => { const subscription = Notifications.addNotificationReceivedListener(notification => { console.log(notification); }); return () => subscription.remove(); }, []); return ( // Your app content ); }
Listeners registered by this method will be called whenever a user interacts with a notification (for example, taps on it).
EventSubscriptionAn EventSubscription object represents the subscription of the provided listener.
Example
import React from 'react'; import { Linking } from 'react-native'; import * as Notifications from 'expo-notifications'; export default function Container() { React.useEffect(() => { const subscription = Notifications.addNotificationResponseReceivedListener(response => { const url = response.notification.request.content.data.url; Linking.openURL(url); }); return () => subscription.remove(); }, []); return ( // Your app content ); }
Listeners registered by this method will be called whenever some notifications have been dropped by the server.
Applicable only to Firebase Cloud Messaging which we use as a notifications service on Android. It corresponds to onDeletedMessages() callback.
More information can be found in Firebase docs.
EventSubscriptionAn EventSubscription object represents the subscription of the provided listener.
A React hook which returns the notification response that was received most recently (a notification response designates an interaction with a notification, such as tapping on it).
To clear the last notification response, use clearLastNotificationResponseAsync().
If you don't want to use a hook, you can use
Notifications.getLastNotificationResponseAsync()instead.
MaybeNotificationResponseThe hook may return one of these three types/values:
undefined- until we're sure of what to return,null- if no notification response has been received yet,- a
NotificationResponseobject - if a notification response was received.
Example
Responding to a notification tap by opening a URL that could be put into the notification's data
(opening the URL is your responsibility and is not a part of the expo-notifications API):
import * as Notifications from 'expo-notifications'; import { Linking } from 'react-native'; export default function App() { const lastNotificationResponse = Notifications.useLastNotificationResponse(); React.useEffect(() => { if ( lastNotificationResponse && lastNotificationResponse.notification.request.content.data.url && lastNotificationResponse.actionIdentifier === Notifications.DEFAULT_ACTION_IDENTIFIER ) { Linking.openURL(lastNotificationResponse.notification.request.content.data.url); } }, [lastNotificationResponse]); return ( // Your app content ); }
当应用运行时展示收到的通知
When a notification is received while the app is running, using this function you can set a callback that will decide whether the notification should be shown to the user or not.
When a notification is received, handleNotification is called with the incoming notification as an argument.
The function should respond with a behavior object within 3 seconds, otherwise, the notification will be discarded.
If the notification is handled successfully, handleSuccess is called with the identifier of the notification,
otherwise (or on timeout) handleError will be called.
The default behavior when the handler is not set or does not respond in time is not to show the notification.
voidExample
import * as Notifications from 'expo-notifications'; Notifications.setNotificationHandler({ handleNotification: async () => ({ shouldShowBanner: true, shouldShowList: true, shouldPlaySound: false, shouldSetBadge: false, }), });
响应收到的通知时运行 JavaScript
Call registerTaskAsync to set a callback (task) that runs when a notification is received while the app is in foreground, background, or terminated.
Only on Android, the task also runs in response to a notification action tap when the app is backgrounded or terminated.
When the app is terminated, only a Headless Background Notification triggers the task execution.
However, the OS may decide not to deliver the notification to your app in some cases (e.g. when the device is in Doze mode on Android, or when you send too many notifications - Apple recommends to not "send more than two or three per hour").
Under the hood, this function is run using expo-task-manager. You must define the task first, with TaskManager.defineTask and register it with registerTaskAsync.
Make sure you define and register the task in the module scope of a JS module which is required early by your app (e.g. in the index.ts file) - see this example.
expo-task-manager loads your app's JS bundle in the background and executes the task, as well as any side effects which may happen as a consequence of requiring any JS modules.
The callback function you define with TaskManager.defineTask receives an object with the following fields:
data: The remote payload delivered by either FCM (Android) or APNs (iOS). SeeNotificationTaskPayloadfor details.executionInfo: JSON object of additional info related to the task, including thetaskName.error: This field should always be undefined with a push-notification task.
From the callback function, you may return a BackgroundNotificationResult value to indicate the result of a background fetch operation on iOS.
Be advised that console.log statements may not be appropriate for debugging background tasks, as the output may not be visible depending on the platform and app state.
Promise<null>Example
import * as TaskManager from 'expo-task-manager'; import * as Notifications from 'expo-notifications'; const BACKGROUND_NOTIFICATION_TASK = 'BACKGROUND-NOTIFICATION-TASK'; TaskManager.defineTask<Notifications.NotificationTaskPayload>(BACKGROUND_NOTIFICATION_TASK, ({ data, executionInfo, error }) => { console.log('Received a notification task payload!'); const isNotificationResponse = 'actionIdentifier' in data; if (isNotificationResponse) { // Do something with the notification response from user } else { // Do something with the data from notification that was received } return BackgroundNotificationResult.NoData }); Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
获取与通知相关权限的信息
Calling this function checks current permissions settings related to notifications. It lets you verify whether the app is currently allowed to display alerts, play sounds, etc. There is no user-facing effect of calling this.
Promise<NotificationPermissionsStatus>It returns a Promise resolving to an object represents permission settings (NotificationPermissionsStatus).
On iOS, make sure you properly interpret the permissions response.
Example
import * as Notifications from 'expo-notifications'; export async function allowsNotificationsAsync() { const settings = await Notifications.getPermissionsAsync(); return ( settings.granted || settings.ios?.status === Notifications.IosAuthorizationStatus.PROVISIONAL ); }
Prompts the user for notification permissions according to request. Request defaults to asking the user to allow displaying alerts, setting badge count and playing sounds.
Promise<NotificationPermissionsStatus>It returns a Promise resolving to an object represents permission settings (NotificationPermissionsStatus).
On iOS, make sure you properly interpret the permissions response.
Example
import * as Notifications from 'expo-notifications'; export function requestPermissionsAsync() { return Notifications.requestPermissionsAsync({ ios: { allowAlert: true, allowBadge: true, allowSound: true, }, }); }
管理应用角标图标
Fetches the number currently set as the badge of the app icon on device's home screen. A 0 value means that the badge is not displayed.
Note: Not all Android launchers support application badges. If the launcher does not support icon badges, the method will always resolve to
0.
Promise<number>Returns a Promise resolving to a number that represents the current badge of the app icon.
Sets the badge of the app's icon to the specified number. Setting it to 0 clears the badge. On iOS, this method requires that you have requested
the user's permission for allowBadge via requestPermissionsAsync,
otherwise it will automatically return false.
Note: Not all Android launchers support application badges. If the launcher does not support icon badges, the method will resolve to
false.
Promise<boolean>It returns a Promise resolving to a boolean representing whether the setting of the badge succeeded.
安排通知
Cancels all scheduled notifications.
Promise<void>A Promise that resolves once all the scheduled notifications are successfully canceled, or if there are no scheduled notifications.
Cancels a single scheduled notification. The scheduled notification of given ID will not trigger.
Promise<void>A Promise resolves once the scheduled notification is successfully canceled or if there is no scheduled notification for a given identifier.
Example
import * as Notifications from 'expo-notifications'; async function scheduleAndCancel() { const identifier = await Notifications.scheduleNotificationAsync({ content: { title: 'Hey!', }, trigger: { seconds: 60, repeats: true }, }); await Notifications.cancelScheduledNotificationAsync(identifier); }
Fetches information about all scheduled notifications.
Promise<NotificationRequest[]>Returns a Promise resolving to an array of objects conforming to the Notification interface.
Allows you to check what will be the next trigger date for given notification trigger input.
Promise<number | null>If the return value is null, the notification won't be triggered. Otherwise, the return value is the Unix timestamp in milliseconds
at which the notification will be triggered.
Example
import * as Notifications from 'expo-notifications'; async function logNextTriggerDate() { try { const nextTriggerDate = await Notifications.getNextTriggerDateAsync({ hour: 9, minute: 0, }); console.log(nextTriggerDate === null ? 'No next trigger date' : new Date(nextTriggerDate)); } catch (e) { console.warn(`Couldn't have calculated next trigger date: ${e}`); } }
Schedules a notification to be triggered in the future.
Note: This does not mean that the notification will be presented when it is triggered. For the notification to be presented you have to set a notification handler with
setNotificationHandlerthat will return an appropriate notification behavior. For more information see the example below.
Promise<string>Returns a Promise resolving to a string which is a notification identifier you can later use to cancel the notification or to identify an incoming notification.
Example
Schedule the notification that will trigger once, in one minute from now
import * as Notifications from 'expo-notifications'; Notifications.scheduleNotificationAsync({ content: { title: "Time's up!", body: 'Change sides!', }, trigger: { type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL, seconds: 60, }, });
Schedule the notification that will trigger repeatedly, every 20 minutes
import * as Notifications from 'expo-notifications'; Notifications.scheduleNotificationAsync({ content: { title: 'Remember to drink water!', }, trigger: { type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL, seconds: 60 * 20, repeats: true, }, });
Schedule the notification that will trigger once, at the beginning of next hour
import * as Notifications from 'expo-notifications'; const date = new Date(Date.now() + 60 * 60 * 1000); date.setMinutes(0); date.setSeconds(0); Notifications.scheduleNotificationAsync({ content: { title: 'Happy new hour!', }, trigger: { type: Notifications.SchedulableTriggerInputTypes.DATE, date }, });
关闭通知
Removes all application's notifications displayed in the notification tray (Notification Center).
Promise<void>A Promise which resolves once the request to dismiss the notifications is successfully dispatched to the notifications manager.
Removes notification displayed in the notification tray (Notification Center).
Promise<void>A Promise which resolves once the request to dismiss the notification is successfully dispatched to the notifications manager.
Fetches information about all notifications present in the notification tray (Notification Center).
This method is not supported on Android below 6.0 (API level 23) – on these devices it will resolve to an empty array.
Promise<Notification[]>A Promise which resolves with a list of notifications (Notification) currently present in the notification tray (Notification Center).
管理通知渠道(Android 特定)
Removes the notification channel.
Promise<void>A Promise which resolving once the channel is removed (or if there was no channel for given identifier).
Removes the notification channel group and all notification channels that belong to it.
Promise<void>A Promise which resolves once the channel group is removed (or if there was no channel group for given identifier).
Fetches information about a single notification channel.
Promise<NotificationChannel | null>A Promise which resolves to the channel object (of type NotificationChannel) or to null
if there was no channel found for this identifier. On platforms that do not support notification channels, it will always resolve to null.
Fetches information about a single notification channel group.
Promise<NotificationChannelGroup | null>A Promise which resolves to the channel group object (of type NotificationChannelGroup)
or to null if there was no channel group found for this identifier. On platforms that do not support notification channels,
it will always resolve to null.
Fetches information about all known notification channel groups.
Promise<NotificationChannelGroup[]>A Promise which resoles to an array of channel groups. On platforms that do not support notification channel groups, it will always resolve to an empty array.
Fetches information about all known notification channels.
Promise<NotificationChannel[]>A Promise which resolves to an array of channels. On platforms that do not support notification channels, it will always resolve to an empty array.
Assigns the channel configuration to a channel of a specified name (creating it if need be). This method lets you assign given notification channel to a notification channel group.
Note: After a channel has been created, you can modify only its name and description. This limitation is imposed by the Android OS.
Note: For some settings to be applied on all Android versions, it may be necessary to duplicate the configuration across both a single notification and its respective notification channel.
For example, for a notification to play a custom sound on Android versions below 8.0,
the custom notification sound has to be set on the notification (through the NotificationContentInput),
and for the custom sound to play on Android versions above 8.0, the relevant notification channel must have the custom sound configured
(through the NotificationChannelInput). For more information,
see Set custom notification sounds on Android.
Promise<NotificationChannel | null>A Promise which resolving to the object (of type NotificationChannel) describing the modified channel
or to null if the platform does not support notification channels.
Assigns the channel group configuration to a channel group of a specified name (creating it if need be).
Promise<NotificationChannelGroup | null>A Promise resolving to the object (of type NotificationChannelGroup)
describing the modified channel group or to null if the platform does not support notification channels.
管理通知类别(交互式通知)
Deletes the category associated with the provided identifier.
Promise<boolean>A Promise which resolves to true if the category was successfully deleted, or false if it was not.
An example of when this method would return false is if you try to delete a category that doesn't exist.
Fetches information about all known notification categories.
Promise<NotificationCategory[]>A Promise which resolves to an array of NotificationCategorys. On platforms that do not support notification channels,
it will always resolve to an empty array.
Sets the new notification category.
Promise<NotificationCategory>A Promise which resolves to the category you just have created.
Constants
Methods
Clears the notification response that was received most recently. May be used when an app selects a route based on the notification response, and it is undesirable to continue selecting the route after the response has already been handled.
If a component is using the useLastNotificationResponse hook,
this call will also clear the value returned by the hook.
voidDeprecated: Use
clearLastNotificationResponseinstead.
Clears the notification response that was received most recently. May be used when an app selects a route based on the notification response, and it is undesirable to continue selecting the route after the response has already been handled.
If a component is using the useLastNotificationResponse hook,
this call will also clear the value returned by the hook.
Promise<void>A promise that resolves if the native call was successful.
Gets the notification response that was received most recently (a notification response designates an interaction with a notification, such as tapping on it).
null- if no notification response has been received yet- a
NotificationResponseobject - if a notification response was received
NotificationResponse | nullDeprecated: Use
getLastNotificationResponseinstead.
Gets the notification response received most recently (a notification response designates an interaction with a notification, such as tapping on it).
null- if no notification response has been received yet- a
NotificationResponseobject - if a notification response was received
Promise<NotificationResponse | null>Subscribes the device to a push notification topic. This allows the device to receive notifications sent to that topic.
Promise<null>a Promise which resolves to null once the device is subscribed to the topic.
Promise<void>Unsubscribes the device from a push notification topic. The device will no longer receive notifications sent to that topic.
Promise<null>a Promise which resolves to null once the device is unsubscribed from the topic.
Interfaces
Extends: Region
A region used to detect the presence of iBeacon devices. Based on Core Location CLBeaconRegion class.
Extends: Region
A circular geographic region, specified as a center point and radius. Based on Core Location CLCircularRegion class.
A trigger related to a daily notification.
The same functionality will be achieved on iOS with a
CalendarNotificationTrigger.
A subscription object that allows to conveniently remove an event listener from the emitter.
Object which contains the Expo push token in the data field. Use the value from data to send notifications via Expo Notifications service.
A Firebase RemoteMessage that caused the notification to be delivered to the app.
Available configuration for permission request on iOS platform.
See Apple documentation for UNAuthorizationOptions to learn more.
A trigger related to a monthly notification.
The same functionality will be achieved on iOS with a
CalendarNotificationTrigger.
An object which represents a single notification that has been triggered by some request (NotificationRequest) at some point in time.
An object which represents behavior that should be applied to the incoming notification. On Android, this influences whether the notification is shown, a sound is played, and priority. On iOS, this maps directly to UNNotificationPresentationOptions.
On Android, setting
shouldPlaySound: falsewill result in the drop-down notification alert not showing, no matter what the priority is. This setting will also override any channel-specific sounds you may have configured.
Defines a group of notification actions and their behavior. Categories allow you to create custom action buttons that appear with notifications, enabling users to respond to notifications.
Categories must be registered with setNotificationCategoryAsync
before they can be used. When scheduling a notification, reference the category by its identifier in the
NotificationContentInput.categoryIdentifier field.
An object which represents a notification channel group to be set.
An interface representing the permissions request scope configuration. Each option corresponds to a different native platform authorization option.
Extends: PermissionResponse
An object obtained by permissions get and request functions.
An object represents a request to present a notification. It has content — how it's being represented, and a trigger — what triggers the notification.
Many notifications (Notification) may be triggered with the same request (for example, a repeating notification).
An object which represents a notification request you can pass into scheduleNotificationAsync.
An object which represents user's interaction with the notification.
Note: If the user taps on a notification,
actionIdentifierwill be equal toNotifications.DEFAULT_ACTION_IDENTIFIER.
A trigger related to an elapsed time interval. May be repeating (see repeats field).
Represents a notification trigger that is unknown to expo-notifications and that it didn't know how to serialize for JS.
A trigger related to a weekly notification.
The same functionality will be achieved on iOS with a
CalendarNotificationTrigger.
A trigger related to a yearly notification.
The same functionality will be achieved on iOS with a
CalendarNotificationTrigger.
Types
Type: Partial<AudioAttributes>
This trigger input will cause the notification to be delivered once or many times
(controlled by the value of repeats)
when the date components match the specified values.
Corresponds to native
UNCalendarNotificationTrigger.
A trigger that will cause the notification to be delivered immediately.
This trigger input will cause the notification to be delivered once per day
when the hour and minute date components match the specified values.
This trigger input will cause the notification to be delivered once
on the specified value of the date property. The value of repeats will be ignored
for this trigger type.
Literal type: union
In simple terms, an object of type: Platform.OS and data: any. The data type depends on the environment - on a native device it will be a string,
which you can then use to send notifications via Firebase Cloud Messaging (Android) or APNs (iOS).
Acceptable values are: ExplicitlySupportedDevicePushToken | ImplicitlySupportedDevicePushToken
Type: NativeDevicePushToken
Literal type: string
The notification’s importance and required delivery timing. Possible values:
- 'passive' - the system adds the notification to the notification list without lighting up the screen or playing a sound
- 'active' - the system presents the notification immediately, lights up the screen, and can play a sound
- 'timeSensitive' - The system presents the notification immediately, lights up the screen, can play a sound, and breaks through system notification controls
- 'critical - the system presents the notification immediately, lights up the screen, and bypasses the mute switch to play a sound
Acceptable values are: 'passive' | 'active' | 'timeSensitive' | 'critical'
This trigger input will cause the notification to be delivered once per month
when the day, hour, and minute date components match the specified values.
Note: All properties are specified in JavaScript
Dateobject's ranges (i.e. January is represented as 0).
Literal type: union
Acceptable values are: IosNotificationPermissionsRequest | object
Type: RequiredBy<Omit<NotificationChannel, 'id' | 'audioAttributes' | 'sound'> & {
audioAttributes: AudioAttributesInput,
sound: string | null
}, 'name' | 'importance'>
An object which represents a notification channel to be set.
An object representing notification's content when reading a notification (on the "output", when it is presented by the system). For the input type, see NotificationContentInput.
Type: NotificationContentIos | NotificationContentAndroid extended by:
See Android developer documentation for more information on specific fields.
An object which represents notification content that you pass in as a part of NotificationRequestInput.
Literal type: union
Acceptable values are: NotificationTimeoutError | Error
Payload for the background notification handler task. See Run JavaScript in response to incoming notifications.
Type: NotificationResponse or object shaped as below:
Literal type: union
A union type containing different triggers which may cause the notification to be delivered to the application.
Acceptable values are: PushNotificationTrigger | LocationNotificationTrigger | NotificationTriggerInput | UnknownNotificationTrigger
Literal type: union
A type which represents possible triggers with which you can schedule notifications.
A null trigger means that the notification should be scheduled for delivery immediately.
Acceptable values are: null | ChannelAwareTriggerInput | SchedulableNotificationTriggerInput
Literal type: union
Permission expiration time. Currently, all permissions are granted permanently.
Acceptable values are: 'never' | number
A function accepting a device push token (DevicePushToken) as an argument.
Note: You should not call
getDevicePushTokenAsyncinside this function, as it triggers the listener and may lead to an infinite loop.
void
Literal type: union
Input for time-based, schedulable triggers.
For these triggers you can check the next trigger date with getNextTriggerDateAsync.
If you pass in a number (Unix timestamp) or Date, it will be processed as a
trigger input of type SchedulableTriggerInputTypes.DATE. Otherwise, the input must be
an object, with a type value set to one of the allowed values in SchedulableTriggerInputTypes.
If the input is an object, date components passed in will be validated, and
an error is thrown if they are outside their allowed range (for example, the minute and
second components must be between 0 and 59 inclusive).
Acceptable values are: CalendarTriggerInput | TimeIntervalTriggerInput | DailyTriggerInput | WeeklyTriggerInput | MonthlyTriggerInput | YearlyTriggerInput | DateTriggerInput
This trigger input will cause the notification to be delivered once or many times
(depends on the repeats field) after seconds time elapse.
On iOS, when
repeatsistrue, the time interval must be 60 seconds or greater. Otherwise, the notification won't be triggered.
This trigger input will cause the notification to be delivered once every week
when the weekday, hour, and minute date components match the specified values.
Note: Weekdays are specified with a number from
1through7, with1indicating Sunday.
This trigger input will cause the notification to be delivered once every year
when the day, month, hour, and minute date components match the specified values.
Note: All properties are specified in JavaScript
Dateobject's ranges (i.e. January is represented as 0).
Enums
AndroidImportance.UNSPECIFIED = 1Use DEFAULT instead. This value is present for compatibility reasons.
An enum corresponding to values appropriate for Android's Notification#priority field.
Constants that indicate the result of a background fetch operation.
Corresponds to UIBackgroundFetchResult.
Schedulable trigger inputs (that are not a plain date value or time value) must have the "type" property set to one of these values.