Reference version

This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

Expo 通知 iconExpo 通知

一个提供 API 用于获取推送通知令牌,以及展示、安排、接收和响应通知的库。

Android
iOS
Recommended version:
~58.0.1

expo-notifications 提供了用于获取推送通知令牌,以及呈现、安排、接收和响应通知的 API。

通知指南

别错过我们的指南,了解如何设置、发送和处理推送通知。

功能

  • 为特定日期或从现在起的一段时间安排一次性通知
  • 按某个时间间隔重复安排通知(或在 iOS 上匹配日历日期)
  • 获取和设置应用角标图标的数字
  • 获取原生设备推送令牌,以便使用 FCM(Android)和 APNs(iOS)发送推送通知
  • 获取 Expo 推送令牌,以便通过 Expo Push Service 发送推送通知
  • 监听前台和后台收到的通知
  • 监听与通知的交互
  • 在应用处于前台时处理通知
  • 从通知中心/通知栏中主动清除通知
  • 创建、更新和删除 Android 通知渠道
  • 在 Android 上为通知设置自定义图标和颜色

安装

Terminal
- npx expo install expo-notifications
- yarn expo install expo-notifications
- pnpm expo install expo-notifications
- bun expo install expo-notifications

If you are installing this in an existing React Native app, make sure to install expo in your project.


然后继续阅读配置,设置配置插件并获取推送通知所需的凭据。

已知问题
Android

在 Android 开发构建中从推送通知启动应用时,启动屏幕在约 70% 的情况下可能无法正确显示。图标和淡入动画可能无法按预期显示。

  • 图标可能缺失
  • 淡入动画可能无法播放
  • 可能只有背景颜色短暂闪烁

此问题只影响调试构建,在发布构建中不会出现。若要规避此问题,请在发布模式下测试通知启动(npx expo run:android --variant release),以确保行为准确。

用法

查看下面的示例 Snack,了解通知的实际效果。推送通知可在实体设备、装有 Google Play 服务的 Android 模拟器,以及运行 Xcode 14 或更高版本的 iOS 模拟器上使用(macOS 13+、iOS 16+)。

推送通知
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 () => ({ shouldPlaySound: false, shouldSetBadge: false, shouldShowBanner: true, shouldShowList: true, }), }); export default function App() { const [expoPushToken, setExpoPushToken] = useState(''); const [channels, setChannels] = useState<Notifications.NotificationChannel[]>([]); const [notification, setNotification] = useState<Notifications.Notification | undefined>( undefined ); useEffect(() => { registerForPushNotificationsAsync().then(token => token && setExpoPushToken(token)); if (Platform.OS === 'android') { Notifications.getNotificationChannelsAsync().then(value => setChannels(value ?? [])); } const notificationListener = Notifications.addNotificationReceivedListener(notification => { setNotification(notification); }); const responseListener = Notifications.addNotificationResponseReceivedListener(response => { console.log(response); }); return () => { notificationListener.remove(); responseListener.remove(); }; }, []); return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'space-around', }}> <Text>Your expo push token: {expoPushToken}</Text> <Text>{`Channels: ${JSON.stringify( channels.map(c => c.id), null, 2 )}`}</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 schedule a notification" onPress={async () => { await schedulePushNotification(); }} /> </View> ); } async function schedulePushNotification() { await Notifications.scheduleNotificationAsync({ content: { title: "You've got mail! 📬", body: 'Here is the notification body', data: { data: 'goes here', test: { test1: 'more data' } }, }, trigger: { type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL, seconds: 2, }, }); } async function registerForPushNotificationsAsync() { let token; if (Platform.OS === 'android') { await Notifications.setNotificationChannelAsync('myNotificationChannel', { name: 'A channel is needed for the permissions prompt to appear', importance: Notifications.AndroidImportance.MAX, vibrationPattern: [0, 250, 250, 250], lightColor: '#FF231F7C', }); } const { status: existingStatus } = await Notifications.getPermissionsAsync(); let finalStatus = existingStatus; if (existingStatus !== 'granted') { const { status } = await Notifications.requestPermissionsAsync(); finalStatus = status; } if (finalStatus !== 'granted') { alert('Failed to get push token for push notification!'); return; } // Learn more about projectId: // https://docs.expo.dev/push-notifications/push-notifications-setup/#configure-projectid // EAS projectId is used here. try { const projectId = Constants?.expoConfig?.extra?.eas?.projectId ?? Constants?.easConfig?.projectId; if (!projectId) { throw new Error('Project ID not found'); } token = ( await Notifications.getExpoPushTokenAsync({ projectId, }) ).data; console.log(token); } catch (e) { token = `${e}`; } return token; }

向用户呈现本地(应用内)通知

import * as Notifications from 'expo-notifications'; Notifications.scheduleNotificationAsync({ content: { title: 'Look at that notification', body: "I'm so proud of myself!", }, trigger: null, });

使用导航处理推送通知

如果你希望在收到推送通知时深度链接到应用中的特定屏幕,可以配置 Expo 的任一导航系统来实现。

你可以使用 Expo Router 的内置深度链接来处理推送通知中的传入 URL。只需配置根布局,以监听传入通知和初始通知事件。

app/_layout.tsx
import { useEffect } from 'react'; import * as Notifications from 'expo-notifications'; import { Slot, router } from 'expo-router'; function useNotificationObserver() { useEffect(() => { function redirect(notification: Notifications.Notification) { const url = notification.request.content.data?.url; if (typeof url === 'string') { router.push(url); Notifications.clearLastNotificationResponse(); } } const response = Notifications.getLastNotificationResponse(); if (response?.notification) { redirect(response.notification); } const subscription = Notifications.addNotificationResponseReceivedListener(response => { redirect(response.notification); }); return () => { subscription.remove(); }; }, []); } export default function Layout() { useNotificationObserver(); return <Slot />; }

配置

凭据

请按照设置指南操作。

App 配置

若要配置 expo-notifications,请在应用配置文件(app.json 或 app.config.js)中使用内置的配置插件,用于 EAS Build 或 npx expo run:[android|ios]。该插件允许你配置以下无法在运行时设置、且需要构建新的应用二进制文件才能生效的属性:

Configurable properties

NameDefaultDescription
icon-
Only for: 
Android

用于推送通知图标的本地图片路径。使用 96x96 的全白色透明 PNG 图片。

largeIcon-
Only for: 
Android

用于通知大图标的本地图片路径。图片会缩放至 64x64 dp,并显示在通知文本旁边。若通知自带图片,则会使用该图片。

color#ffffff
Only for: 
Android

推送通知图片显示在通知栏时的着色颜色。

defaultChannel-
Only for: 
Android

FCMv1 通知的默认渠道。

sounds-

本地声音文件路径数组(推荐使用 .wav 文件),可用作自定义通知声音。专注模式不允许播放声音或开启静音模式时,不会播放声音。

enableBackgroundRemoteNotificationsfalse
Only for: 
iOS

是否启用后台远程通知,详情请参阅 Apple 文档。这会更新 Info.plist 中的 UIBackgroundModes 键,将 remote-notification 加入其中。

以下是在应用配置文件中使用配置插件的示例:

app.json
{ "expo": { "plugins": [ [ "expo-notifications", { "icon": "./local/assets/notification_icon.png", "largeIcon": "./local/assets/notification_large_icon.png", "color": "#ffffff", "defaultChannel": "default", "sounds": [ "./local/assets/notification_sound.wav", "./local/assets/notification_sound_other.wav" ], "enableBackgroundRemoteNotifications": false } ] ] } }
Are you using this library in an existing React Native app?

了解如何在 expo-notifications 仓库的安装说明中配置原生项目。

权限

Android

  • 在 Android 上,此模块需要订阅设备启动事件的权限,用于在设备重新启动时设置已安排的通知。 该库会自动将 RECEIVE_BOOT_COMPLETED 权限添加到 AndroidManifest.xml。

  • 从 Android 12(API 级别 31)开始,若要安排在精确时间触发的通知,需要在 AndroidManifest.xml 中添加 <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>。 详细信息请参阅精确闹钟权限。 delivery: 'alarmClock' 触发选项也需要精确闹钟权限。在 Android 13(API 级别 33)及更高版本上,闹钟、计时器和日历应用 可以改为声明 <uses-permission android:name="android.permission.USE_EXACT_ALARM"/>。系统会直接授予此权限,无需用户确认。 Google Play 的精确闹钟政策将 USE_EXACT_ALARM 限制在这些应用类别中。

  • 在 Android 13 上,应用用户必须通过操作系统自动触发的权限提示,选择是否接收通知。 至少创建一个通知渠道后,才会显示此提示。获取推送令牌前,必须先调用 setNotificationChannelAsync,再调用 getDevicePushTokenAsync 或 getExpoPushTokenAsync。关于 Android 13 新通知权限行为的更多信息,请参阅 官方文档。

Android permissionDescription

RECEIVE_BOOT_COMPLETED

Allows an application to receive the Intent.ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting.

SCHEDULE_EXACT_ALARM

Allows applications to use exact alarm APIs.

USE_EXACT_ALARM

Allows apps to use exact alarms just like with SCHEDULE_EXACT_ALARM but without needing to request this permission from the user.

iOS

无需提供用法说明,参阅与通知相关的权限。

解读 iOS 权限响应

在 iOS 上,发送通知的权限比 Android 上更加细分。因此,你应该依据 NotificationPermissionsStatus 的 ios.status 字段,而不是根级别的 status 字段。

此值将是以下之一,可通过 Notifications.IosAuthorizationStatus 访问:

  • NOT_DETERMINED:用户尚未决定是否允许应用安排通知
  • DENIED:应用未获准安排或接收通知
  • AUTHORIZED:应用已获准安排或接收通知
  • PROVISIONAL:应用已获准发布非打扰式用户通知
  • EPHEMERAL:应用已获准在有限时间内安排或接收通知

通知事件监听器

通知事件包括收到通知、用户与通知进行的交互(例如点按通知,或通过通知类别与之交互),以及通知可能被丢弃的少数情况。

多个监听器的说明请参阅推送通知行为一节。

无头(后台)通知

请参阅你需要了解的内容指南中关于无头后台通知的定义。

若要在应用处于后台或未运行时处理通知,需要执行以下操作:

然后发送满足以下条件的推送通知:

后台通知配置 
iOS

若要在 iOS 上使用无头(后台)推送通知,应用的 Info.plist 文件中的 UIBackgroundModes 数组必须包含 remote-notification 值。

如果你正在使用 CNG,请将配置插件的 enableBackgroundRemoteNotifications 属性设为 true,prebuild 会自动应用正确的配置。

在 iOS 上手动配置 UIBackgroundModes

如果你没有使用 Continuous Native Generation(CNG),或者使用的是原生 iOS 项目,则需要将以下内容添加到 Expo.plist 文件中:

ios/project-name/Supporting/Expo.plist
<key>UIBackgroundModes</key> <array> <string>remote-notification</string> </array>

附加信息

设置自定义通知声音

若要向应用添加自定义推送通知声音,请将 expo-notifications 插件添加到 app.json 文件中,然后在 sounds 键下提供可用作自定义通知声音的本地声音文件路径数组。这些路径相对于项目目录。

app.json
{ "expo": { "plugins": [ [ "expo-notifications", { "sounds": ["local/path/to/mySoundFile.wav"] } ] ] } }

构建应用后,这些文件即可用于 NotificationContentInput 和 NotificationChannelInput。 只需提供基础文件名。以下是使用上述配置的示例:

await Notifications.setNotificationChannelAsync('new_emails', { name: 'E-mail notifications', importance: Notifications.AndroidImportance.HIGH, sound: 'mySoundFile.wav', // Provide ONLY the base filename }); await Notifications.scheduleNotificationAsync({ content: { title: "You've got mail! 📬", sound: 'mySoundFile.wav', // Provide ONLY the base filename }, trigger: { type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL, seconds: 2, channelId: 'new_emails', }, });

如果愿意,也可以手动将通知文件添加到 Android 和 iOS 项目中:

在 Android 上手动添加通知声音

在 Android 8.0 及更高版本上,为通知播放自定义声音,仅设置 NotificationContentInput 的 sound 属性是不够的。 你还需要为 NotificationChannel 配置相应的 sound,并在发送/安排通知时使用该渠道。

要使下面的示例正常工作,请将 email_sound.wav 文件放在 android/app/src/main/res/raw/ 中。

// Prepare the notification channel await Notifications.setNotificationChannelAsync('new_emails', { name: 'E-mail notifications', importance: Notifications.AndroidImportance.HIGH, sound: 'email_sound.wav', // <- for Android 8.0+, see channelId property below }); // Eg. schedule the notification await Notifications.scheduleNotificationAsync({ content: { title: "You've got mail! 📬", body: 'Open the notification to read them all', sound: 'email_sound.wav', // <- for Android below 8.0 }, trigger: { type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL, seconds: 2, channelId: 'new_emails', // <- for Android 8.0+, see definition above }, });
在 iOS 上手动添加通知声音

在 iOS 上,只需将声音文件放入 Xcode 项目中(见下方截图), 然后在 NotificationContentInput 中指定声音文件,如下所示:

await Notifications.scheduleNotificationAsync({ content: { title: "You've got mail! 📬", body: 'Open the notification to read them all', sound: 'notification.wav', }, trigger: { // ... }, });

推送通知负载规范

请参阅消息请求格式。

管理交互式通知的通知类别

通知类别允许你创建交互式推送通知,使用户可以通过按钮或文本回复直接响应收到的通知。类别定义了用户可以执行的一组操作,然后通过在通知的 NotificationContent 中指定 categoryIdentifier,将这些操作应用于通知。

在 iOS 上,通知类别还可以让你进一步自定义通知。对于每个类别,你可以设置用户可以执行的交互操作,并配置诸如当用户为你的应用停用通知预览时显示的占位文本等内容。

特定平台指南

处理通知渠道 
Android 8+

从 Android 8.0(API level 26)开始,所有通知都必须分配到一个渠道。对于每个渠道, 你可以设置应用于该渠道中所有通知的视觉和听觉行为。 然后,用户可以更改这些设置,并决定你的应用中的哪些通知渠道应当具有侵扰性或完全可见, 正如 Android developer docs 所述。

如果你未指定通知渠道,expo-notifications 将为你创建一个名为 Miscellaneous 的备用渠道。 我们建议你始终确保为应用设置合适且名称清晰的渠道,并始终将通知发送到这些渠道。

自定义通知图标和颜色 
Android

你可以通过将 expo-notifications config plugin 与 Expo Prebuild 搭配使用,在项目中配置通知的 icon 和 color 键。这些是构建时设置,因此你需要使用 eas build -p android 或 npx expo run:android 重新编译原生 Android 应用,才能看到更改。

对于通知图标,请确保遵循 Google's design guidelines (图标必须为全白色且背景透明),否则它可能无法按预期显示。

你还可以直接在 NotificationContentInput 的 color 属性下为每条通知设置自定义通知颜色。

API

import * as Notifications from 'expo-notifications';

获取推送通知的令牌

addPushTokenListener(listener)

Android
iOS
ParameterTypeDescription
listenerPushTokenListener

A function accepting a push token as an argument, it will be called whenever the push token changes.


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.

Returns:
EventSubscription

An 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 ); }

getDevicePushTokenAsync()

Android
iOS

Returns a native FCM, APNs token or a PushSubscription data that can be used with another push notification service.

getExpoPushTokenAsync(options)

Android
iOS
ParameterTypeDescription
options(optional)ExpoPushTokenOptions

Object allowing you to pass in push notification configuration.

Default:{}

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.

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, }), }); }

监听通知事件

addNotificationReceivedListener(listener)

Android
iOS
ParameterTypeDescription
listener(event: Notification) => void

A function accepting a notification (Notification) as an argument.


Listeners registered by this method will be called whenever a notification is received while the app is running.

Returns:
EventSubscription

An 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 ); }

addNotificationResponseReceivedListener(listener)

Android
iOS
ParameterTypeDescription
listener(event: NotificationResponse) => void

A function accepting notification response (NotificationResponse) as an argument.


Listeners registered by this method will be called whenever a user interacts with a notification (for example, taps on it).

Returns:
EventSubscription

An 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 ); }

addNotificationsDroppedListener(listener)

Android
iOS
ParameterTypeDescription
listener() => void

A callback function.


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.

Returns:
EventSubscription

An EventSubscription object represents the subscription of the provided listener.

useLastNotificationResponse()

Android
iOS

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().

Returns:
MaybeNotificationResponse

The 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 NotificationResponse object - 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 ); }

应用运行时显示传入的通知

setNotificationHandler(handler)

Android
iOS
ParameterTypeDescription
handlerNotificationHandler | null

A single parameter which should be either null or a NotificationHandler object. Passing null removes the handler, so expo-notifications no longer decides whether an incoming notification shows. On Android the notification is then not shown while the app is in the foreground. On iOS the decision goes to the UNUserNotificationCenterDelegate that another library may set, and the notification is not shown if there is none.


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 presented. If the notification is handled successfully, handleSuccess is called with the identifier of the notification, otherwise (or on timeout) handleError will be called.

Until the app sets a handler, and when the handler it sets does not respond in time, the notification is shown with a banner, in the notification list, with a sound, and with the badge from the notification.

Returns:
void

Example

import * as Notifications from 'expo-notifications'; Notifications.setNotificationHandler({ handleNotification: async () => ({ shouldShowBanner: true, shouldShowList: true, shouldPlaySound: false, shouldSetBadge: false, }), });

响应传入的通知运行 JavaScript

registerTaskAsync(taskName)

Android
iOS
ParameterTypeDescription
taskNamestring

The string you passed to TaskManager.defineTask as the taskName parameter.


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). See NotificationTaskPayload for details.
  • executionInfo: JSON object of additional info related to the task, including the taskName.
  • 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.

Returns:
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);

unregisterTaskAsync(taskName)

Android
iOS
ParameterTypeDescription
taskNamestring

The string you passed to registerTaskAsync as the taskName parameter.


Used to unregister tasks registered with registerTaskAsync method.

Returns:
Promise<null>

获取与通知相关的权限信息

getPermissionsAsync()

Android
iOS

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.

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 ); }

requestPermissionsAsync(permissions)

Android
iOS
ParameterTypeDescription
permissions(optional)NotificationPermissionsRequest

An object representing configuration for the request scope.


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.

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, }, }); }

管理应用徽章图标

getBadgeCountAsync()

Android
iOS

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.

Returns:
Promise<number>

Returns a Promise resolving to a number that represents the current badge of the app icon.

setBadgeCountAsync(badgeCount, options)

Android
iOS
ParameterTypeDescription
badgeCountnumber

The count which should appear on the badge. A value of 0 will clear the badge.

options(optional)SetBadgeCountOptions

An object of options configuring behavior applied.


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.

Returns:
Promise<boolean>

It returns a Promise resolving to a boolean representing whether the setting of the badge succeeded.

安排通知

cancelAllScheduledNotificationsAsync()

Android
iOS

Cancels all scheduled notifications.

Returns:
Promise<void>

A Promise that resolves once all the scheduled notifications are successfully canceled, or if there are no scheduled notifications.

cancelScheduledNotificationAsync(identifier)

Android
iOS
ParameterTypeDescription
identifierstring

The notification identifier with which scheduleNotificationAsync method resolved when the notification has been scheduled.


Cancels a single scheduled notification. The scheduled notification of given ID will not trigger.

Returns:
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); }

getAllScheduledNotificationsAsync()

Android
iOS

Fetches information about all scheduled notifications.

Returns a Promise resolving to an array of objects conforming to the Notification interface.

getNextTriggerDateAsync(trigger)

Android
iOS
ParameterTypeDescription
triggerSchedulableNotificationTriggerInput

The schedulable notification trigger you would like to check next trigger date for (of type SchedulableNotificationTriggerInput).


Allows you to check what will be the next trigger date for given notification trigger input.

Returns:
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}`); } }

scheduleNotificationAsync(request)

Android
iOS
ParameterTypeDescription
requestNotificationRequestInput

An object describing the notification to be triggered.


Schedules a notification to be triggered in the future.

Returns:
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 }, });

关闭通知

dismissAllNotificationsAsync()

Android
iOS

Removes all application's notifications displayed in the notification tray (Notification Center).

Returns:
Promise<void>

A Promise which resolves once the request to dismiss the notifications is successfully dispatched to the notifications manager.

dismissNotificationAsync(notificationIdentifier)

Android
iOS
ParameterTypeDescription
notificationIdentifierstring

The notification identifier, obtained either via setNotificationHandler method or in the listener added with addNotificationReceivedListener.


Removes notification displayed in the notification tray (Notification Center).

Returns:
Promise<void>

A Promise which resolves once the request to dismiss the notification is successfully dispatched to the notifications manager.

getPresentedNotificationsAsync()

Android
iOS

Fetches information about all notifications present in the notification tray (Notification Center).

A Promise which resolves with a list of notifications (Notification) currently present in the notification tray (Notification Center).

管理通知渠道(特定于 Android)

deleteNotificationChannelAsync(channelId)

Android
ParameterTypeDescription
channelIdstring

The channel identifier.


Removes the notification channel.

Returns:
Promise<void>

A Promise which resolves once the channel is removed (or if there was no channel for given identifier).

deleteNotificationChannelGroupAsync(groupId)

Android
ParameterTypeDescription
groupIdstring

The channel group identifier.


Removes the notification channel group and all notification channels that belong to it.

Returns:
Promise<void>

A Promise which resolves once the channel group is removed (or if there was no channel group for given identifier).

getNotificationChannelAsync(channelId)

Android
ParameterTypeDescription
channelIdstring

The channel's identifier.


Fetches information about a single notification channel.

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.

getNotificationChannelGroupAsync(groupId)

Android
ParameterTypeDescription
groupIdstring

The channel group's identifier.


Fetches information about a single notification channel group.

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.

getNotificationChannelGroupsAsync()

Android

Fetches information about all known notification channel groups.

A Promise which resolves to an array of channel groups. On platforms that do not support notification channel groups, it will always resolve to an empty array.

getNotificationChannelsAsync()

Android

Fetches information about all known notification channels.

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.

setNotificationChannelAsync(channelId, channel)

Android
ParameterTypeDescription
channelIdstring

The channel identifier.

channelNotificationChannelInput

Object representing the channel's configuration.


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.

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.

A Promise which resolves to the object (of type NotificationChannel) describing the modified channel or to null if the platform does not support notification channels.

setNotificationChannelGroupAsync(groupId, group)

Android
ParameterTypeDescription
groupIdstring

The channel group's identifier.

groupNotificationChannelGroupInput

Object representing the channel group configuration.


Assigns the channel group configuration to a channel group of a specified name (creating it if need be).

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.

管理通知类别(交互式通知)

deleteNotificationCategoryAsync(identifier)

Android
iOS
ParameterTypeDescription
identifierstring

Identifier initially provided to setNotificationCategoryAsync when creating the category.


Deletes the category associated with the provided identifier.

Returns:
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.

getNotificationCategoriesAsync()

Android
iOS

Fetches information about all known notification categories.

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.

setNotificationCategoryAsync(identifier, actions, options)

Android
iOS
ParameterTypeDescription
identifierstring

A string to associate as the ID of this category. You will pass this string in as the categoryIdentifier in your NotificationContent to associate a notification with this category.

actionsNotificationAction[]

An array of NotificationAction, which describe the actions associated with this category.

options(optional)NotificationCategoryOptions

An optional object of additional configuration options for your category.


Sets the new notification category.

A Promise which resolves to the category you just have created.

Constants

Notifications.DEFAULT_ACTION_IDENTIFIER

Android
iOS

Type: 'expo.modules.notifications.actions.DEFAULT'

Methods

Notifications.clearLastNotificationResponse()

Android
iOS

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.

Returns:
void

Notifications.clearLastNotificationResponseAsync()

Android
iOS

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.

Returns:
Promise<void>

A promise that resolves if the native call was successful.

Notifications.getLastNotificationResponse()

Android
iOS

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 NotificationResponse object - if a notification response was received
Returns:
NotificationResponse | null

Notifications.getLastNotificationResponseAsync()

Android
iOS

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 NotificationResponse object - if a notification response was received

Notifications.subscribeToTopicAsync(topic)

Android
ParameterTypeDescription
topicstring

The topic name to subscribe to.


Subscribes the device to a push notification topic. This allows the device to receive notifications sent to that topic.

Returns:
Promise<null>

a Promise which resolves to null once the device is subscribed to the topic.

Notifications.unregisterForNotificationsAsync()

Android
iOS
Returns:
Promise<void>

Notifications.unsubscribeFromTopicAsync(topic)

Android
ParameterTypeDescription
topicstring

The topic name to unsubscribe from.


Unsubscribes the device from a push notification topic. The device will no longer receive notifications sent to that topic.

Returns:
Promise<null>

a Promise which resolves to null once the device is unsubscribed from the topic.

Interfaces

AudioAttributes

Android
PropertyTypeDescription
contentTypeAndroidAudioContentType
-
flags{ enforceAudibility: boolean, requestHardwareAudioVideoSynchronization: boolean }
-
usageAndroidAudioUsage
-

BeaconRegion

iOS

Extends: Region

A region used to detect the presence of iBeacon devices. Based on Core Location CLBeaconRegion class.

PropertyTypeDescription
beaconIdentityConstraint(optional){ major: number | null, minor: number | null, uuid: string }

The beacon identity constraint that defines the beacon region.

majornumber | null

The major value from the beacon identity constraint that defines the beacon region.

minornumber | null

The minor value from the beacon identity constraint that defines the beacon region.

notifyEntryStateOnDisplayboolean

A Boolean value that indicates whether Core Location sends beacon notifications when the device’s display is on.

type'beacon'
-
uuid(optional)string

The UUID value from the beacon identity constraint that defines the beacon region.

CalendarNotificationTrigger

iOS

A trigger related to a UNCalendarNotificationTrigger.

PropertyTypeDescription
dateComponents{ calendar: string, day: number, era: number, hour: number, isLeapMonth: boolean, isRepeatedDay: boolean, minute: number, month: number, nanosecond: number, quarter: number, second: number, timeZone: string, weekday: number, weekdayOrdinal: number, weekOfMonth: number, weekOfYear: number, year: number, yearForWeekOfYear: number }
-
repeatsboolean
-
type'calendar'
-

CircularRegion

iOS

Extends: Region

A circular geographic region, specified as a center point and radius. Based on Core Location CLCircularRegion class.

PropertyTypeDescription
center{ latitude: number, longitude: number }

The center point of the geographic area.

radiusnumber

The radius (measured in meters) that defines the geographic area’s outer boundary.

type'circular'
-

DailyNotificationTrigger

Android

A trigger related to a daily notification.

PropertyTypeDescription
delivery(optional)NotificationDelivery
-
hournumber
-
minutenumber
-
type'daily'
-

EventSubscription

Android
iOS

A subscription object that allows to conveniently remove an event listener from the emitter.

EventSubscription Methods

remove()

Android
iOS

Removes an event listener for which the subscription has been created. After calling this function, the listener will no longer receive any events from the emitter.

Returns:
void

ExpoPushToken

Android
iOS

Object which contains the Expo push token in the data field. Use the value from data to send notifications via Expo Notifications service.

PropertyTypeDescription
datastring

The acquired push token.

type'expo'

Always set to "expo".

ExpoPushTokenOptions

Android
iOS
PropertyTypeDescription
applicationId(optional)string

The ID of the application to which the token should be attributed. Defaults to Application.applicationId exposed by expo-application.

baseUrl(optional)string

Endpoint URL override.

development(optional)boolean
Only for: 
iOS

On iOS, there are two push notification services: "sandbox" and "production". This defines whether the push token is supposed to be used with the sandbox platform notification service. Defaults to Application.getIosPushNotificationServiceEnvironmentAsync() exposed by expo-application or false. Most probably you won't need to customize that. You may want to customize that if you don't want to install expo-application and still use the sandbox APNs.

deviceId(optional)string
-
devicePushToken(optional)DevicePushToken

The device push token with which to register at the backend. Defaults to a token fetched with getDevicePushTokenAsync().

projectId(optional)string

The ID of the project to which the token should be attributed. Defaults to Constants.expoConfig.extra.eas.projectId exposed by expo-constants.

When using EAS Build, this value is automatically set. However, it is recommended to set it manually. Once you have EAS Build configured, you can find the value in app.json under extra.eas.projectId. You can copy and paste it into your code. If you are not using EAS Build, it will fallback to Constants.expoConfig?.extra?.eas?.projectId.

type(optional)string

Request body override.

url(optional)string

Request URL override.

FirebaseRemoteMessage

Android
iOS

A Firebase RemoteMessage that caused the notification to be delivered to the app.

PropertyTypeDescription
collapseKeystring | null
-
dataRecord<string, string>
-
fromstring | null
-
messageIdstring | null
-
messageTypestring | null
-
notificationFirebaseRemoteMessageNotification | null
-
originalPrioritynumber
-
prioritynumber
-
sentTimenumber
-
tostring | null
-
ttlnumber
-

FirebaseRemoteMessageNotification

Android
iOS
PropertyTypeDescription
bodystring | null
-
bodyLocalizationArgsstring[] | null
-
bodyLocalizationKeystring | null
-
channelIdstring | null
-
clickActionstring | null
-
colorstring | null
-
eventTimenumber | null
-
iconstring | null
-
imageUrlstring | null
-
lightSettingsnumber[] | null
-
linkstring | null
-
localOnlyboolean
-
notificationCountnumber | null
-
notificationPrioritynumber | null
-
soundstring | null
-
stickyboolean
-
tagstring | null
-
tickerstring | null
-
titlestring | null
-
titleLocalizationArgsstring[] | null
-
titleLocalizationKeystring | null
-
usesDefaultLightSettingsboolean
-
usesDefaultSoundboolean
-
usesDefaultVibrateSettingsboolean
-
vibrateTimingsnumber[] | null
-
visibilitynumber | null
-

IosNotificationPermissionsRequest

iOS

Available configuration for permission request on iOS platform. See Apple documentation for UNAuthorizationOptions to learn more.

PropertyTypeDescription
allowAlert(optional)boolean

The ability to display alerts.

allowBadge(optional)boolean

The ability to update the app’s badge.

allowCriticalAlerts(optional)boolean

The ability to play sounds for critical alerts.

allowDisplayInCarPlay(optional)boolean

The ability to display notifications in a CarPlay environment.

allowProvisional(optional)boolean

The ability to post noninterrupting notifications provisionally to the Notification Center.

allowSound(optional)boolean

The ability to play sounds.

provideAppNotificationSettings(optional)boolean

An option indicating the system should display a button for in-app notification settings.

LocationNotificationTrigger

iOS

A trigger related to a UNLocationNotificationTrigger.

PropertyTypeDescription
regionCircularRegion | BeaconRegion
-
repeatsboolean
-
type'location'
-

MonthlyNotificationTrigger

Android

A trigger related to a monthly notification.

PropertyTypeDescription
daynumber
-
delivery(optional)NotificationDelivery
-
hournumber
-
minutenumber
-
type'monthly'
-

NativeDevicePushToken

Android
iOS
PropertyTypeDescription
datastring
-
type'ios' | 'android'
-

Notification

Android
iOS

An object which represents a single notification that has been triggered by some request (NotificationRequest) at some point in time.

PropertyTypeDescription
datenumber
-
requestNotificationRequest
-

NotificationAction

Android
iOS
PropertyTypeDescription
buttonTitlestring

The title of the button triggering this action.

identifierstring

A unique string that identifies this action. If a user takes this action (for example, selects this button in the system's Notification UI), your app will receive this actionIdentifier via the NotificationResponseReceivedListener.

options(optional){ isAuthenticationRequired: boolean, isDestructive: boolean, opensAppToForeground: boolean }

Object representing the additional configuration options.

textInput(optional){ placeholder: string, submitButtonTitle: string }

Object which, if provided, will result in a button that prompts the user for a text response.

NotificationBehavior

Android
iOS

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.

PropertyTypeDescription
priority(optional)AndroidNotificationPriority
-
shouldPlaySoundboolean
-
shouldSetBadgeboolean
Only for: 
iOS

-
shouldShowAlert(optional)boolean
shouldShowBannerboolean
-
shouldShowListboolean
-

NotificationCategory

Android
iOS

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.

PropertyTypeDescription
actionsNotificationAction[]
-
identifierstring
-
options(optional)NotificationCategoryOptions
-

NotificationChannel

Android

An object which represents a notification channel.

PropertyTypeDescription
audioAttributesAudioAttributes
-
bypassDndboolean
-
descriptionstring | null
-
enableLightsboolean
-
enableVibrateboolean
-
groupId(optional)string | null
-
idstring
-
importanceAndroidImportance
-
lightColorstring
-
lockscreenVisibilityAndroidNotificationVisibility
-
namestring | null
-
showBadgeboolean
-
sound'default' | 'custom' | null
-
vibrationPatternnumber[] | null
-

NotificationChannelGroup

Android

An object which represents a notification channel group.

PropertyTypeDescription
channelsNotificationChannel[]
-
description(optional)string | null
-
idstring
-
isBlocked(optional)boolean
-
namestring | null
-

NotificationChannelGroupInput

Android

An object which represents a notification channel group to be set.

PropertyTypeDescription
description(optional)string | null
-
namestring | null
-

NotificationChannelGroupManager

Android
iOS

Extends: ProxyNativeModule

PropertyTypeDescription
deleteNotificationChannelGroupAsync(optional)(groupId: string) => Promise<void>
-
getNotificationChannelGroupAsync(optional)(groupId: string) => Promise<NotificationChannelGroup | null>
-
getNotificationChannelGroupsAsync(optional)() => Promise<NotificationChannelGroup[]>
-
setNotificationChannelGroupAsync(optional)(groupId: string, group: NotificationChannelGroupInput) => Promise<NotificationChannelGroup | null>
-

NotificationChannelManager

Android
iOS

Extends: ProxyNativeModule

PropertyTypeDescription
deleteNotificationChannelAsync(optional)(channelId: string) => Promise<void>
-
getNotificationChannelAsync(optional)(channelId: string) => Promise<NotificationChannel | null>
-
getNotificationChannelsAsync(optional)() => Promise<NotificationChannel[] | null>
-
setNotificationChannelAsync(optional)(channelId: string, channelConfiguration: NotificationChannelInput) => Promise<NotificationChannel | null>
-

NotificationHandler

Android
iOS
PropertyTypeDescription
handleError(optional)(notificationId: string, error: NotificationHandlingError) => void

A function called whenever calling handleNotification() for an incoming notification fails.

handleNotification(notification: Notification) => Promise<NotificationBehavior>

A function accepting an incoming notification returning a Promise resolving to a behavior (NotificationBehavior) applicable to the notification

handleSuccess(optional)(notificationId: string) => void

A function called whenever an incoming notification is handled successfully.

NotificationPermissionsRequest

Android
iOS

An interface representing the permissions request scope configuration. Each option corresponds to a different native platform authorization option.

PropertyTypeDescription
android(optional)object

On Android, all available permissions are granted by default, and if a user declines any permission, an app cannot prompt the user to change.

ios(optional)IosNotificationPermissionsRequest

Available configuration for permission request on iOS platform.

NotificationPermissionsStatus

Android
iOS

Extends: PermissionResponse

An object obtained by permissions get and request functions.

PropertyTypeDescription
android(optional){ importance: number, interruptionFilter: number }
-
ios(optional){ alertStyle: IosAlertStyle, allowsAlert: boolean | null, allowsAnnouncements: boolean | null, allowsBadge: boolean | null, allowsCriticalAlerts: boolean | null, allowsDisplayInCarPlay: boolean | null, allowsDisplayInNotificationCenter: boolean | null, allowsDisplayOnLockScreen: boolean | null, allowsPreviews: IosAllowsPreviews | null, allowsSound: boolean | null, providesAppNotificationSettings: boolean | null, status: IosAuthorizationStatus }
-

NotificationRequest

Android
iOS

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).

PropertyTypeDescription
contentNotificationContent
-
identifierstring
-
triggerNotificationTrigger
-

NotificationRequestInput

Android
iOS

An object which represents a notification request you can pass into scheduleNotificationAsync.

PropertyTypeDescription
contentNotificationContentInput
-
identifier(optional)string
-
triggerNotificationTriggerInput
-

NotificationResponse

Android
iOS

An object which represents user's interaction with the notification.

PropertyTypeDescription
actionIdentifierstring
-
notificationNotification
-
userText(optional)string
-

Region

iOS

The region used to determine when the system sends the notification.

PropertyTypeDescription
identifierstring

The identifier for the region object.

notifyOnEntryboolean

Indicates whether notifications are generated upon entry into the region.

notifyOnExitboolean

Indicates whether notifications are generated upon exit from the region.

typestring
-

TimeIntervalNotificationTrigger

Android
iOS

A trigger related to an elapsed time interval. May be repeating (see repeats field).

PropertyTypeDescription
repeatsboolean
-
secondsnumber
-
type'timeInterval'
-

UnknownNotificationTrigger

Android
iOS

Represents a notification trigger that is unknown to expo-notifications and that it didn't know how to serialize for JS.

PropertyTypeDescription
type'unknown'
-

WeeklyNotificationTrigger

Android

A trigger related to a weekly notification.

PropertyTypeDescription
delivery(optional)NotificationDelivery
-
hournumber
-
minutenumber
-
type'weekly'
-
weekdaynumber
-

YearlyNotificationTrigger

Android

A trigger related to a yearly notification.

PropertyTypeDescription
daynumber
-
delivery(optional)NotificationDelivery
-
hournumber
-
minutenumber
-
monthnumber
-
type'yearly'
-

Types

AudioAttributesInput

Android

Type: Partial<AudioAttributes>

CalendarTriggerInput

iOS

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.

PropertyTypeDescription
channelId(optional)string
-
day(optional)number
-
hour(optional)number
-
minute(optional)number
-
month(optional)number
-
repeats(optional)boolean
-
second(optional)number
-
seconds(optional)number
-
timezone(optional)string
-
typeSchedulableTriggerInputTypes.CALENDAR
-
weekday(optional)number
-
weekdayOrdinal(optional)number
-
weekOfMonth(optional)number
-
weekOfYear(optional)number
-
year(optional)number
-

ChannelAwareTriggerInput

Android
iOS

A trigger that will cause the notification to be delivered immediately.

PropertyTypeDescription
channelIdstring
-

DailyTriggerInput

Android
iOS

This trigger input will cause the notification to be delivered once per day when the hour and minute date components match the specified values.

PropertyTypeDescription
channelId(optional)string
-
delivery(optional)NotificationDelivery
Default:'bestEffort'
hournumber
-
minutenumber
-
typeSchedulableTriggerInputTypes.DAILY
-

DateTriggerInput

Android
iOS

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.

PropertyTypeDescription
channelId(optional)string
-
dateDate | number
-
delivery(optional)NotificationDelivery
Default:'bestEffort'
typeSchedulableTriggerInputTypes.DATE
-

DevicePushToken

Android
iOS

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

ExplicitlySupportedDevicePushToken

Android
iOS

Type: NativeDevicePushToken

ImplicitlySupportedDevicePushToken

Android
iOS
PropertyTypeDescription
dataany

The push token as a string for a native platform.

typeExclude<Platform.OS, ExplicitlySupportedDevicePushToken[type]>

Either android or ios.

InterruptionLevel

iOS

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'

MonthlyTriggerInput

Android
iOS

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.

PropertyTypeDescription
channelId(optional)string
-
daynumber
-
delivery(optional)NotificationDelivery
Default:'bestEffort'
hournumber
-
minutenumber
-
typeSchedulableTriggerInputTypes.MONTHLY
-

NativeNotificationPermissionsRequest

Android
iOS

Literal type: union

Acceptable values are: IosNotificationPermissionsRequest | object

NotificationCategoryOptions

iOS
PropertyTypeDescription
allowAnnouncement(optional)boolean
Default:false
allowInCarPlay(optional)boolean

Indicates whether to allow CarPlay to display notifications of this type. Apps must be approved for CarPlay to make use of this feature.

Default:false
categorySummaryFormat(optional)string

A format string for the summary description used when the system groups the category’s notifications.

customDismissAction(optional)boolean

Indicates whether to send actions for handling when the notification is dismissed (the user must explicitly dismiss the notification interface - ignoring a notification or flicking away a notification banner does not trigger this action).

Default:false
intentIdentifiers(optional)string[]

Array of Intent Class Identifiers. When a notification is delivered, the presence of an intent identifier lets the system know that the notification is potentially related to the handling of a request made through Siri.

Default:[]
previewPlaceholder(optional)string

Customizable placeholder for the notification preview text. This is shown if the user has disabled notification previews for the app. Defaults to the localized iOS system default placeholder (Notification).

showSubtitle(optional)boolean

Indicates whether to show the notification's subtitle, even if the user has disabled notification previews for the app.

Default:false
showTitle(optional)boolean

Indicates whether to show the notification's title, even if the user has disabled notification previews for the app.

Default:false

NotificationChannelInput

Android

Type: RequiredBy<Omit<NotificationChannel, 'id' | 'audioAttributes' | 'sound'> & { audioAttributes: AudioAttributesInput, sound: string | null }, 'name' | 'importance'>

An object which represents a notification channel to be set.

NotificationContent

Android
iOS

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:

PropertyTypeDescription
bodystring | null

Notification body - the main content of the notification.

categoryIdentifierstring | null

The identifier of the notification’s category.

data(optional)Record<string, unknown>

Data associated with the notification, not displayed

sound'default' | 'defaultCritical' | 'custom' | 'defaultRingtone' | null
-
subtitlestring | null

On Android: subText - the display depends on the device.

On iOS: subtitle - the bold text displayed between title and the rest of the content.

titlestring | null

Notification title - the bold text displayed above the rest of the content.

NotificationContentAndroid

Android

See Android developer documentation for more information on specific fields.

PropertyTypeDescription
badge(optional)number

Application badge number associated with the notification.

color(optional)string

Accent color (in #AARRGGBB or #RRGGBB format) to be applied by the standard Style templates when presenting this notification.

priority(optional)AndroidNotificationPriority

Relative priority for this notification. Priority is an indication of how much of the user's valuable attention should be consumed by this notification. Low-priority notifications may be hidden from the user in certain situations, while the user might be interrupted for a higher-priority notification. The system will make a determination about how to interpret this priority when presenting the notification.

vibrationPattern(optional)number[]

The pattern with which to vibrate.

NotificationContentAttachmentIos

iOS
PropertyTypeDescription
hideThumbnail(optional)boolean
-
identifierstring | null
-
thumbnailClipArea(optional){ height: number, width: number, x: number, y: number }
-
thumbnailTime(optional)number
-
typestring | null
-
typeHint(optional)string
-
urlstring | null
-

NotificationContentInput

Android
iOS

An object which represents notification content that you pass in as a part of NotificationRequestInput.

PropertyTypeDescription
attachments(optional)NotificationContentAttachmentIos[]
Only for: 
iOS

The visual and audio attachments to display alongside the notification’s main content.

autoDismiss(optional)boolean
Only for: 
Android

If set to false, the notification will not be automatically dismissed when clicked. The setting will be used when the value is not provided or is invalid is set to true, and the notification will be dismissed automatically anyway. Corresponds directly to Android's setAutoCancel behavior.

See Android developer documentation for more details.

badge(optional)number

Application badge number associated with the notification.

body(optional)string | null

The main content of the notification.

categoryIdentifier(optional)string
Only for: 
iOS

The identifier of the notification’s category.

color(optional)string
Only for: 
Android

Accent color (in #AARRGGBB or #RRGGBB format) to be applied by the standard Style templates when presenting this notification.

data(optional)Record<string, unknown>

Data associated with the notification, not displayed.

interruptionLevel(optional)InterruptionLevel
Only for: 
iOS

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
launchImageName(optional)string

The name of the image or storyboard to use when your app launches because of the notification.

priority(optional)string
Only for: 
Android

Relative priority for this notification. Priority is an indication of how much of the user's valuable attention should be consumed by this notification. Low-priority notifications may be hidden from the user in certain situations, while the user might be interrupted for a higher-priority notification. The system will make a determination about how to interpret this priority when presenting the notification.

sound(optional)boolean | 'default' | 'defaultCritical' | 'defaultRingtone' | string & undefined

The notification sound. Use false for a silent notification. On Android version 8 and later, control the sounds via notification channels. defaultCritical and defaultRingtone are applicable only on iOS, with defaultCritical requiring the critical alerts entitlement.

On iOS, you can also provide a custom sound filename including the extension. The file needs to be added to the expo-notifications config plugin sounds array in your app config.

sticky(optional)boolean
Only for: 
Android

If set to true, the notification cannot be dismissed by swipe. This setting defaults to false if not provided or is invalid. Corresponds directly to Android's isOngoing behavior. In Firebase terms this property of a notification is called sticky.

See Android developer documentation and Firebase documentation for more details.

subtitle(optional)string | null

On Android: subText - the display depends on the device.

On iOS: subtitle - the bold text displayed between title and the rest of the content.

threadIdentifier(optional)string
Only for: 
iOS

An identifier used to group related notifications together in the notification center.

title(optional)string | null

Notification title - the bold text displayed above the rest of the content.

vibrate(optional)number[]
Only for: 
Android

The pattern with which to vibrate.

NotificationContentIos

iOS

See Apple documentation for more information on specific fields.

PropertyTypeDescription
attachmentsNotificationContentAttachmentIos[]

The visual and audio attachments to display alongside the notification’s main content.

badgenumber | null

The number that your app’s icon displays.

interruptionLevel(optional)InterruptionLevel
-
launchImageNamestring | null

The name of the image or storyboard to use when your app launches because of the notification.

summaryArgument(optional)string | null

The text the system adds to the notification summary to provide additional context.

summaryArgumentCount(optional)number

The number the system adds to the notification summary when the notification represents multiple items.

targetContentIdentifier(optional)string

The value your app uses to determine which scene to display to handle the notification.

threadIdentifierstring | null

The identifier that groups related notifications.

NotificationDelivery

Android

Literal type: string

Controls which AlarmManager API schedules a wall-clock trigger on Android.

  • 'bestEffort': the default. Uses setExactAndAllowWhileIdle(), which delivers at the requested time on most devices. Some OEM Android builds defer these alarms by minutes to save battery. Without the exact alarm permission, the system may deliver the notification later than requested.
  • 'alarmClock': uses setAlarmClock(). The system delivers these alarms at the requested time and does not defer them for battery optimization. Use only for time-critical alarms, such as alarm clocks or medication reminders. The status bar shows an alarm icon until the notification is delivered. Requires the SCHEDULE_EXACT_ALARM or USE_EXACT_ALARM permission on Android 12 and higher. Without the permission, the notification is scheduled as 'bestEffort'.

Acceptable values are: 'bestEffort' | 'alarmClock'

NotificationHandlingError

Android
iOS

Literal type: union

Acceptable values are: NotificationTimeoutError | Error

NotificationTaskPayload

Android
iOS

Payload for the background notification handler task. See Run JavaScript in response to incoming notifications.

Type: NotificationResponse or object shaped as below:

PropertyTypeDescription
aps(optional)Record<string, unknown>
Only for: 
iOS

Detailed, raw object describing the remote notification. See Apple's payload key reference.

data{ dataString: string }

dataString carries the data payload of the notification as JSON string.

notificationRecord<string, unknown> | null

Object describing the remote notification. null for headless background notifications.

NotificationTrigger

Android
iOS

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

NotificationTriggerInput

Android
iOS

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

PermissionExpiration

Android
iOS

Literal type: union

Permission expiration time. Currently, all permissions are granted permanently.

Acceptable values are: 'never' | number

PermissionResponse

Android
iOS

An object obtained by permissions get and request functions.

PropertyTypeDescription
canAskAgainboolean

Indicates if user can be asked again for specific permission. If not, one should be directed to the Settings app in order to enable/disable the permission.

expiresPermissionExpiration

Determines time when the permission expires.

grantedboolean

A convenience boolean that indicates if the permission is granted.

statusPermissionStatus

Determines the status of the permission.

PushNotificationTrigger

Android
iOS
PropertyTypeDescription
payload(optional)Record<string, unknown>
Only for: 
iOS

-
remoteMessage(optional)FirebaseRemoteMessage
Only for: 
Android

-
type'push'
-

PushTokenListener(token)

Android
iOS

A function accepting a device push token (DevicePushToken) as an argument.

ParameterType
tokenDevicePushToken
Returns:

void

SchedulableNotificationTriggerInput

Android
iOS

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

Subscription

Android
iOS

Type: EventSubscription

TimeIntervalTriggerInput

Android
iOS

This trigger input will cause the notification to be delivered once or many times (depends on the repeats field) after seconds time elapse.

PropertyTypeDescription
channelId(optional)string
-
repeats(optional)boolean
-
secondsnumber
-
typeSchedulableTriggerInputTypes.TIME_INTERVAL
-

WeeklyTriggerInput

Android
iOS

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.

PropertyTypeDescription
channelId(optional)string
-
delivery(optional)NotificationDelivery
Default:'bestEffort'
hournumber
-
minutenumber
-
typeSchedulableTriggerInputTypes.WEEKLY
-
weekdaynumber
-

YearlyTriggerInput

Android
iOS

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.

PropertyTypeDescription
channelId(optional)string
-
daynumber
-
delivery(optional)NotificationDelivery
Default:'bestEffort'
hournumber
-
minutenumber
-
monthnumber
-
typeSchedulableTriggerInputTypes.YEARLY
-

Enums

AndroidAudioContentType

Android

UNKNOWN

AndroidAudioContentType.UNKNOWN = 0

SPEECH

AndroidAudioContentType.SPEECH = 1

MUSIC

AndroidAudioContentType.MUSIC = 2

MOVIE

AndroidAudioContentType.MOVIE = 3

SONIFICATION

AndroidAudioContentType.SONIFICATION = 4

AndroidAudioUsage

Android

UNKNOWN

AndroidAudioUsage.UNKNOWN = 0

MEDIA

AndroidAudioUsage.MEDIA = 1

VOICE_COMMUNICATION

AndroidAudioUsage.VOICE_COMMUNICATION = 2

VOICE_COMMUNICATION_SIGNALLING

AndroidAudioUsage.VOICE_COMMUNICATION_SIGNALLING = 3

ALARM

AndroidAudioUsage.ALARM = 4

NOTIFICATION

AndroidAudioUsage.NOTIFICATION = 5

NOTIFICATION_RINGTONE

AndroidAudioUsage.NOTIFICATION_RINGTONE = 6

NOTIFICATION_COMMUNICATION_REQUEST

AndroidAudioUsage.NOTIFICATION_COMMUNICATION_REQUEST = 7

NOTIFICATION_COMMUNICATION_INSTANT

AndroidAudioUsage.NOTIFICATION_COMMUNICATION_INSTANT = 8

NOTIFICATION_COMMUNICATION_DELAYED

AndroidAudioUsage.NOTIFICATION_COMMUNICATION_DELAYED = 9

NOTIFICATION_EVENT

AndroidAudioUsage.NOTIFICATION_EVENT = 10

ASSISTANCE_ACCESSIBILITY

AndroidAudioUsage.ASSISTANCE_ACCESSIBILITY = 11

ASSISTANCE_NAVIGATION_GUIDANCE

AndroidAudioUsage.ASSISTANCE_NAVIGATION_GUIDANCE = 12

ASSISTANCE_SONIFICATION

AndroidAudioUsage.ASSISTANCE_SONIFICATION = 13

GAME

AndroidAudioUsage.GAME = 14

AndroidImportance

Android

UNKNOWN

AndroidImportance.UNKNOWN = 0

UNSPECIFIED

AndroidImportance.UNSPECIFIED = 1

Use DEFAULT instead. This value is present for compatibility reasons.

NONE

AndroidImportance.NONE = 2

MIN

AndroidImportance.MIN = 3

LOW

AndroidImportance.LOW = 4

DEFAULT

AndroidImportance.DEFAULT = 5

HIGH

AndroidImportance.HIGH = 6

MAX

AndroidImportance.MAX = 7

AndroidNotificationPriority

Android

An enum corresponding to values appropriate for Android's Notification#priority field.

DEFAULT

AndroidNotificationPriority.DEFAULT = "default"

HIGH

AndroidNotificationPriority.HIGH = "high"

LOW

AndroidNotificationPriority.LOW = "low"

MAX

AndroidNotificationPriority.MAX = "max"

MIN

AndroidNotificationPriority.MIN = "min"

AndroidNotificationVisibility

Android

UNKNOWN

AndroidNotificationVisibility.UNKNOWN = 0

PUBLIC

AndroidNotificationVisibility.PUBLIC = 1

PRIVATE

AndroidNotificationVisibility.PRIVATE = 2

SECRET

AndroidNotificationVisibility.SECRET = 3

BackgroundNotificationTaskResult

iOS

Constants that indicate the result of a background fetch operation. Corresponds to UIBackgroundFetchResult.

NewData

BackgroundNotificationTaskResult.NewData = 0

NoData

BackgroundNotificationTaskResult.NoData = 1

Failed

BackgroundNotificationTaskResult.Failed = 2

IosAlertStyle

iOS

NONE

IosAlertStyle.NONE = 0
IosAlertStyle.BANNER = 1

ALERT

IosAlertStyle.ALERT = 2

IosAllowsPreviews

iOS

NEVER

IosAllowsPreviews.NEVER = 0

ALWAYS

IosAllowsPreviews.ALWAYS = 1

WHEN_AUTHENTICATED

IosAllowsPreviews.WHEN_AUTHENTICATED = 2

IosAuthorizationStatus

iOS

NOT_DETERMINED

IosAuthorizationStatus.NOT_DETERMINED = 0

DENIED

IosAuthorizationStatus.DENIED = 1

AUTHORIZED

IosAuthorizationStatus.AUTHORIZED = 2

PROVISIONAL

IosAuthorizationStatus.PROVISIONAL = 3

EPHEMERAL

IosAuthorizationStatus.EPHEMERAL = 4

PermissionStatus

Android
iOS

DENIED

PermissionStatus.DENIED = "denied"

User has denied the permission.

GRANTED

PermissionStatus.GRANTED = "granted"

User has granted the permission.

UNDETERMINED

PermissionStatus.UNDETERMINED = "undetermined"

User hasn't granted or denied the permission yet.

SchedulableTriggerInputTypes

Android
iOS

Schedulable trigger inputs (that are not a plain date value or time value) must have the "type" property set to one of these values.

CALENDAR

SchedulableTriggerInputTypes.CALENDAR = "calendar"

DAILY

SchedulableTriggerInputTypes.DAILY = "daily"

DATE

SchedulableTriggerInputTypes.DATE = "date"

MONTHLY

SchedulableTriggerInputTypes.MONTHLY = "monthly"

TIME_INTERVAL

SchedulableTriggerInputTypes.TIME_INTERVAL = "timeInterval"

WEEKLY

SchedulableTriggerInputTypes.WEEKLY = "weekly"

YEARLY

SchedulableTriggerInputTypes.YEARLY = "yearly"