跳至主要內容
版本:v8

@capacitor/push-notifications

推播通知 API 提供存取原生推播通知的功能。

安裝

npm install @capacitor/push-notifications
npx cap sync

iOS

在 iOS 上,您必須啟用「推播通知」功能。請參閱設定功能,以瞭解如何啟用此功能。

啟用「推播通知」功能後,將以下內容新增至您應用程式的 AppDelegate.swift

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
}

Android

推播通知 API 使用 Firebase Cloud Messaging SDK 來處理通知。請參閱 在 Android 上設定 Firebase Cloud Messaging 用戶端應用程式,並按照指示建立 Firebase 專案並註冊您的應用程式。無需將 Firebase SDK 新增至您的應用程式或編輯您的應用程式資訊清單 — 推播通知會為您提供這些功能。您只需要將 Firebase 專案的 google-services.json 檔案新增至您應用程式的模組 (應用程式層級) 目錄中。

Android 13 需要權限檢查才能接收推播通知。當目標為 SDK 33 時,您必須呼叫 checkPermissions()requestPermissions()

變數

此外掛程式會使用下列專案變數 (定義於您應用程式的 variables.gradle 檔案中)

  • firebaseMessagingVersion com.google.firebase:firebase-messaging 的版本 (預設值:23.3.1)

推播通知圖示

在 Android 上,應將具有適當名稱的推播通知圖示新增至 AndroidManifest.xml 檔案

<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/push_icon_name" />

如果未指定圖示,Android 會使用應用程式圖示,但推播圖示應為透明背景上的白色像素。由於應用程式圖示通常不是這樣,因此會顯示白色正方形或圓形。因此,建議為推播通知提供個別的圖示。

Android Studio 有一個圖示產生器,您可以使用它來建立推播通知圖示。

推播通知頻道

從 Android 8.0 (API 層級 26) 及更高版本開始,支援並建議使用通知頻道。SDK 將以下列順序導出傳入推播通知的 channelId

  1. 首先,它會檢查傳入通知是否已設定 channelId從 FCM 儀表板或透過其 API 發送推播通知時,可以指定 channelId
  2. 然後,它會檢查 AndroidManifest.xml 中是否有可能給定的值。如果您偏好建立並使用自己的預設頻道,請將 default_notification_channel_id 設定為您的通知頻道物件的 ID,如下所示;當傳入訊息未明確設定通知頻道時,FCM 會使用此值。
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
  1. 最後,它會使用 Firebase SDK 為我們提供的回退 channelIdFCM 提供一個開箱即用的預設通知頻道,其中包含基本設定。Firebase SDK 會在收到第一則推播訊息後建立此頻道。

警告 當使用選項 1 或 2 時,您仍然需要在程式碼中建立通知頻道,其 ID 與所選選項中使用的 ID 相符。您可以使用 createChannel(...) 來執行此操作。如果您不這樣做,SDK 會回退至選項 3。

前景中的推播通知外觀

您可以設定應用程式在前台時顯示推播通知的方式。

屬性類型描述自從
presentationOptionsPresentationOption[]這是一個您可以組合的字串陣列。陣列中的可能值為: - badge:應用程式圖示上的徽章計數已更新 (預設值) - sound:收到推播通知時,裝置會響鈴/震動 - alert:推播通知會顯示在原生對話框中。如果不需要任何選項,則可以提供一個空陣列。徽章僅適用於 iOS。1.0.0

範例

capacitor.config.json

{
"plugins": {
"PushNotifications": {
"presentationOptions": ["badge", "sound", "alert"]
}
}
}

capacitor.config.ts

/// <reference types="@capacitor/push-notifications" />

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
plugins: {
PushNotifications: {
presentationOptions: ["badge", "sound", "alert"],
},
},
};

export default config;

靜音推播通知/僅限資料的通知

iOS

此插件不支援 iOS 靜音推播 (遠端通知)。我們建議使用原生程式碼解決方案來處理這些類型的通知,請參閱將背景更新推送到您的應用程式

Android

此插件支援僅限資料的通知,但如果應用程式已終止,則不會呼叫 pushNotificationReceived。若要處理這種情況,您需要建立一個延伸 FirebaseMessagingService 的服務,請參閱處理 FCM 訊息

常見問題

在 Android 上,有各種系統和應用程式狀態可能會影響推播通知的傳遞

  • 如果裝置已進入Doze 模式,您的應用程式可能會有受限的功能。若要增加收到通知的可能性,請考慮使用FCM 高優先順序訊息
  • 開發和生產之間的行為有所不同。嘗試在 Android Studio 啟動之外測試您的應用程式。請在此處閱讀更多資訊 here

範例

import { PushNotifications } from '@capacitor/push-notifications';

const addListeners = async () => {
await PushNotifications.addListener('registration', token => {
console.info('Registration token: ', token.value);
});

await PushNotifications.addListener('registrationError', err => {
console.error('Registration error: ', err.error);
});

await PushNotifications.addListener('pushNotificationReceived', notification => {
console.log('Push notification received: ', notification);
});

await PushNotifications.addListener('pushNotificationActionPerformed', notification => {
console.log('Push notification action performed', notification.actionId, notification.inputValue);
});
}

const registerNotifications = async () => {
let permStatus = await PushNotifications.checkPermissions();

if (permStatus.receive === 'prompt') {
permStatus = await PushNotifications.requestPermissions();
}

if (permStatus.receive !== 'granted') {
throw new Error('User denied permissions!');
}

await PushNotifications.register();
}

const getDeliveredNotifications = async () => {
const notificationList = await PushNotifications.getDeliveredNotifications();
console.log('delivered notifications', notificationList);
}

API

register()

register() => Promise<void>

註冊應用程式以接收推播通知。

如果發生問題,此方法將觸發包含推播權杖的 'registration' 事件或 'registrationError'。它不會提示使用者要求通知權限,請先使用 requestPermissions()

自從 1.0.0


unregister()

unregister() => Promise<void>

取消註冊應用程式的推播通知。

這將刪除 Android 上的 Firebase 權杖,並取消註冊 iOS 上的 APNS。

自從 5.0.0


getDeliveredNotifications()

getDeliveredNotifications() => Promise<DeliveredNotifications>

取得通知畫面中可見的通知列表。

回傳值: Promise<DeliveredNotifications>

自從 1.0.0


removeDeliveredNotifications(...)

removeDeliveredNotifications(delivered: DeliveredNotifications) => Promise<void>

從通知畫面移除指定的通知。

參數類型
deliveredDeliveredNotifications

自從 1.0.0


removeAllDeliveredNotifications()

removeAllDeliveredNotifications() => Promise<void>

從通知畫面移除所有通知。

自從 1.0.0


createChannel(...)

createChannel(channel: Channel) => Promise<void>

建立一個通知頻道。

僅在 Android O 或更新版本 (SDK 26+) 上可用。

參數類型
channelChannel

自從 1.0.0


deleteChannel(...)

deleteChannel(args: { id: string; }) => Promise<void>

刪除一個通知頻道。

僅在 Android O 或更新版本 (SDK 26+) 上可用。

參數類型
args{ id: string; }

自從 1.0.0


listChannels()

listChannels() => Promise<ListChannelsResult>

列出可用的通知頻道。

僅在 Android O 或更新版本 (SDK 26+) 上可用。

回傳值: Promise<ListChannelsResult>

自從 1.0.0


checkPermissions()

checkPermissions() => Promise<PermissionStatus>

檢查接收推播通知的權限。

在 Android 12 及更早版本上,狀態始終為已授予,因為您可以始終接收推播通知。如果您需要檢查使用者是否允許顯示通知,請使用 local-notifications 外掛程式。

回傳值: Promise<PermissionStatus>

自從 1.0.0


requestPermissions()

requestPermissions() => Promise<PermissionStatus>

請求接收推播通知的權限。

在 Android 12 及更早版本上,它不會提示權限,因為您可以始終接收推播通知。

在 iOS 上,第一次使用該功能時,它會提示使用者是否允許推播通知權限,並根據使用者的選擇回傳已授予或已拒絕。後續呼叫將取得權限的目前狀態,而不會再次提示。

回傳值: Promise<PermissionStatus>

自從 1.0.0


addListener('registration', ...)

addListener(eventName: 'registration', listenerFunc: (token: Token) => void) => Promise<PluginListenerHandle>

當推播通知註冊順利完成時呼叫。

提供推播通知權杖。

參數類型
eventName'registration'
listenerFunc(token: Token) => void

回傳值: Promise<PluginListenerHandle>

自從 1.0.0


addListener('registrationError', ...)

addListener(eventName: 'registrationError', listenerFunc: (error: RegistrationError) => void) => Promise<PluginListenerHandle>

當推播通知註冊完成但發生問題時呼叫。

提供一個包含註冊問題的錯誤。

參數類型
eventName'registrationError'
listenerFunc(error: RegistrationError) => void

回傳值: Promise<PluginListenerHandle>

自從 1.0.0


addListener('pushNotificationReceived', ...)

addListener(eventName: 'pushNotificationReceived', listenerFunc: (notification: PushNotificationSchema) => void) => Promise<PluginListenerHandle>

當裝置收到推播通知時呼叫。

參數類型
eventName'pushNotificationReceived'
listenerFunc(notification: PushNotificationSchema) => void

回傳值: Promise<PluginListenerHandle>

自從 1.0.0


addListener('pushNotificationActionPerformed', ...)

addListener(eventName: 'pushNotificationActionPerformed', listenerFunc: (notification: ActionPerformed) => void) => Promise<PluginListenerHandle>

當對推播通知執行操作時呼叫。

參數類型
eventName'pushNotificationActionPerformed'
listenerFunc(notification: ActionPerformed) => void

回傳值: Promise<PluginListenerHandle>

自從 1.0.0


removeAllListeners()

removeAllListeners() => Promise<void>

移除此外掛程式的所有原生監聽器。

自從 1.0.0


介面

DeliveredNotifications

屬性類型描述自從
notificationsPushNotificationSchema[]通知畫面中可見的通知列表。1.0.0

PushNotificationSchema

屬性類型描述自從
titlestring通知標題。1.0.0
subtitlestring通知副標題。1.0.0
bodystring通知的主要文字內容。1.0.0
idstring通知識別碼。1.0.0
tagstring通知標籤。僅在 Android 上可用 (來自推播通知)。4.0.0
badgenumber應用程式圖示徽章上顯示的數字。1.0.0
notificationany不會回傳。1.0.0
dataany推播通知酬載中包含的任何其他資料。1.0.0
click_actionstring使用者開啟通知時要執行的操作。僅在 Android 上可用。1.0.0
linkstring來自通知的深層連結。僅在 Android 上可用。1.0.0
groupstring設定通知群組的群組識別碼。僅在 Android 上可用。在 iOS 上運作方式類似 threadIdentifier1.0.0
groupSummaryboolean將此通知指定為關聯的 group 的摘要。僅在 Android 上可用。1.0.0

Channel

屬性類型描述預設值自從
idstring頻道識別碼。1.0.0
namestring此頻道的人性化名稱 (呈現給使用者)。1.0.0
descriptionstring此頻道的說明 (呈現給使用者)。1.0.0
soundstring針對張貼到此頻道的通知應播放的聲音。重要性至少為 3 的通知頻道應具有聲音。應指定相對於 android 應用程式 res/raw 目錄的聲音檔檔名。1.0.0
importanceImportance針對張貼到此頻道的通知的中斷層級。31.0.0
visibilityVisibility張貼到此頻道的通知的可見性。此設定用於決定張貼到此頻道的通知是否顯示在鎖定畫面上,如果顯示,是否以經過編輯的形式顯示。1.0.0
lightsboolean張貼到此頻道的通知是否應在支援的裝置上顯示通知燈。1.0.0
lightColorstring張貼到此頻道的通知的燈光顏色。僅在此頻道上啟用燈光且裝置支援時才支援。支援的顏色格式為 #RRGGBB#RRGGBBAA1.0.0
vibrationboolean張貼到此頻道的通知是否應震動。1.0.0

ListChannelsResult

屬性類型描述自從
channelsChannel[]您的應用程式建立的所有頻道列表。1.0.0

PermissionStatus

屬性類型描述自從
receivePermissionState接收通知的權限狀態。1.0.0

PluginListenerHandle

屬性類型
remove() => Promise<void>

Token

屬性類型描述自從
valuestring在 iOS 上,它包含 APNS 權杖。在 Android 上,它包含 FCM 權杖。1.0.0

RegistrationError

屬性類型描述自從
errorstring描述註冊失敗的錯誤訊息。4.0.0

ActionPerformed

屬性類型描述自從
actionIdstring在通知上執行的操作。1.0.0
inputValuestring在通知操作中輸入的文字。僅在 iOS 上可用。1.0.0
notificationPushNotificationSchema執行操作的通知。1.0.0

類型別名

Importance

重要性層級。如需詳細資訊,請參閱 Android 開發人員文件

1 | 2 | 3 | 4 | 5

Visibility

通知可見性。如需詳細資訊,請參閱 Android 開發人員文件

-1 | 0 | 1

PermissionState

'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'