Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

License

NotificationsYou must be signed in to change notification settings

Resgrid/capacitor-push-notifications

Repository files navigation

The Push Notifications API provides access to native push notifications.

Install

npm install @capacitor/push-notificationsnpx cap sync

iOS

On iOS you must enable the Push Notifications capability. SeeSetting Capabilities for instructions on how to enable the capability.

After enabling the Push Notifications capability, add the following to your app'sAppDelegate.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

The Push Notification API usesFirebase Cloud Messaging SDK for handling notifications. SeeSet up a Firebase Cloud Messaging client app on Android and follow the instructions for creating a Firebase project and registering your application. There is no need to add the Firebase SDK to your app or edit your app manifest - the Push Notifications provides that for you. All that is required is your Firebase project'sgoogle-services.json file added to the module (app-level) directory of your app.

Android 13 requires a permission check in order to receive push notifications. You are required to callcheckPermissions() andrequestPermissions() accordingly, when targeting SDK 33.

Variables

This plugin will use the following project variables (defined in your app'svariables.gradle file):

  • firebaseMessagingVersion version ofcom.google.firebase:firebase-messaging (default:23.3.1)

Push Notifications icon

On Android, the Push Notifications icon with the appropriate name should be added to theAndroidManifest.xml file:

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

If no icon is specified Android will use the application icon, but push icon should be white pixels on a transparent backdrop. As the application icon is not usually like that, it will show a white square or circle. So it's recommended to provide the separate icon for Push Notifications.

Android Studio has an icon generator you can use to create your Push Notifications icon.

Push Notification channel

From Android 8.0 (API level 26) and higher, notification channels are supported and recommended. The SDK will derive thechannelId for incoming push notifications in the following order:

  1. Firstly it will check if the incoming notification has achannelId set.When sending a push notification from either the FCM dashboard, or through their API, it's possible to specify achannelId.
  2. Then it will check for a possible given value in theAndroidManifest.xml.If you prefer to create and use your own default channel, setdefault_notification_channel_id to the ID of your notification channel object as shown; FCM will use this value whenever incoming messages do not explicitly set a notification channel.
<meta-dataandroid:name="com.google.firebase.messaging.default_notification_channel_id"android:value="@string/default_notification_channel_id" />
  1. Lastly it will use the fallbackchannelId that the Firebase SDK provides for us.FCM provides a default notification channel with basic settings out of the box. This channel will be created by the Firebase SDK upon receiving the first push message.

WarningWhen using option 1 or 2, you are still required to create a notification channel in code with an ID that matches the one used the chosen option. You can usecreateChannel(...) for this. If you don't do this, the SDK will fallback to option 3.

Push notifications appearance in foreground

You can configure the way the push notifications are displayed when the app is in foreground.

PropTypeDescriptionSince
presentationOptionsPresentationOption[]This is an array of strings you can combine. Possible values in the array are: -badge: badge count on the app icon is updated (default value) -sound: the device will ring/vibrate when the push notification is received -alert: the push notification is displayed in a native dialog An empty array can be provided if none of the options are desired. badge is only available for iOS.1.0.0

Examples

Incapacitor.config.json:

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

Incapacitor.config.ts:

/// <reference types="@resgrid/push-notifications" />import{CapacitorConfig}from'@capacitor/cli';constconfig:CapacitorConfig={plugins:{PushNotifications:{presentationOptions:["badge","sound","alert"],},},};exportdefaultconfig;

Silent Push Notifications / Data-only Notifications

iOS

This plugin does not support iOS Silent Push (Remote Notifications). We recommend using native code solutions for handling these types of notifications, seePushing Background Updates to Your App.

Android

This plugin does support data-only notifications, but will NOT callpushNotificationReceived if the app has been killed. To handle this scenario, you will need to create a service that extendsFirebaseMessagingService, seeHandling FCM Messages.

Common Issues

On Android, there are various system and app states that can affect the delivery of push notifications:

  • If the device has enteredDoze mode, your application may have restricted capabilities. To increase the chance of your notification being received, consider usingFCM high priority messages.
  • There are differences in behavior between development and production. Try testing your app outside of being launched by Android Studio. Read morehere.

Example

import{PushNotifications}from'@capacitor/push-notifications';constaddListeners=async()=>{awaitPushNotifications.addListener('registration',token=>{console.info('Registration token: ',token.value);});awaitPushNotifications.addListener('registrationError',err=>{console.error('Registration error: ',err.error);});awaitPushNotifications.addListener('pushNotificationReceived',notification=>{console.log('Push notification received: ',notification);});awaitPushNotifications.addListener('pushNotificationActionPerformed',notification=>{console.log('Push notification action performed',notification.actionId,notification.inputValue);});}constregisterNotifications=async()=>{letpermStatus=awaitPushNotifications.checkPermissions();if(permStatus.receive==='prompt'){permStatus=awaitPushNotifications.requestPermissions();}if(permStatus.receive!=='granted'){thrownewError('User denied permissions!');}awaitPushNotifications.register();}constgetDeliveredNotifications=async()=>{constnotificationList=awaitPushNotifications.getDeliveredNotifications();console.log('delivered notifications',notificationList);}

API

register()

register()=>Promise<void>

Register the app to receive push notifications.

This method will trigger the'registration' event with the push token or'registrationError' if there was a problem. It does not prompt the user fornotification permissions, userequestPermissions() first.

Since: 1.0.0


unregister()

unregister()=>Promise<void>

Unregister the app from push notifications.

This will delete a firebase token on Android, and unregister APNS on iOS.

Since: 5.0.0


getDeliveredNotifications()

getDeliveredNotifications()=>Promise<DeliveredNotifications>

Get a list of notifications that are visible on the notifications screen.

Returns:Promise<DeliveredNotifications>

Since: 1.0.0


removeDeliveredNotifications(...)

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

Remove the specified notifications from the notifications screen.

ParamType
deliveredDeliveredNotifications

Since: 1.0.0


removeAllDeliveredNotifications()

removeAllDeliveredNotifications()=>Promise<void>

Remove all the notifications from the notifications screen.

Since: 1.0.0


createChannel(...)

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

Create a notification channel.

Only available on Android O or newer (SDK 26+).

ParamType
channelChannel

Since: 1.0.0


deleteChannel(...)

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

Delete a notification channel.

Only available on Android O or newer (SDK 26+).

ParamType
args{ id: string; }

Since: 1.0.0


listChannels()

listChannels()=>Promise<ListChannelsResult>

List the available notification channels.

Only available on Android O or newer (SDK 26+).

Returns:Promise<ListChannelsResult>

Since: 1.0.0


checkPermissions()

checkPermissions()=>Promise<PermissionStatus>

Check permission to receive push notifications.

On Android 12 and below the status is always granted because you can alwaysreceive push notifications. If you need to check if the user allowsto display notifications, use local-notifications plugin.

Returns:Promise<PermissionStatus>

Since: 1.0.0


requestPermissions()

requestPermissions()=>Promise<PermissionStatus>

Request permission to receive push notifications.

On Android 12 and below it doesn't prompt for permission because you can alwaysreceive push notifications.

On iOS, the first time you use the function, it will prompt the userfor push notification permission and return granted or denied basedon the user selection. On following calls it will get the current status ofthe permission without prompting again.

Returns:Promise<PermissionStatus>

Since: 1.0.0


addListener('registration', ...)

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

Called when the push notification registration finishes without problems.

Provides the push notification token.

ParamType
eventName'registration'
listenerFunc(token:Token) => void

Returns:Promise<PluginListenerHandle>

Since: 1.0.0


addListener('registrationError', ...)

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

Called when the push notification registration finished with problems.

Provides an error with the registration problem.

ParamType
eventName'registrationError'
listenerFunc(error:RegistrationError) => void

Returns:Promise<PluginListenerHandle>

Since: 1.0.0


addListener('pushNotificationReceived', ...)

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

Called when the device receives a push notification.

ParamType
eventName'pushNotificationReceived'
listenerFunc(notification:PushNotificationSchema) => void

Returns:Promise<PluginListenerHandle>

Since: 1.0.0


addListener('pushNotificationActionPerformed', ...)

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

Called when an action is performed on a push notification.

ParamType
eventName'pushNotificationActionPerformed'
listenerFunc(notification:ActionPerformed) => void

Returns:Promise<PluginListenerHandle>

Since: 1.0.0


removeAllListeners()

removeAllListeners()=>Promise<void>

Remove all native listeners for this plugin.

Since: 1.0.0


Interfaces

DeliveredNotifications

PropTypeDescriptionSince
notificationsPushNotificationSchema[]List of notifications that are visible on the notifications screen.1.0.0

PushNotificationSchema

PropTypeDescriptionSince
titlestringThe notification title.1.0.0
subtitlestringThe notification subtitle.1.0.0
bodystringThe main text payload for the notification.1.0.0
idstringThe notification identifier.1.0.0
tagstringThe notification tag. Only available on Android (from push notifications).4.0.0
badgenumberThe number to display for the app icon badge.1.0.0
notificationanyIt's not being returned.1.0.0
dataanyAny additional data that was included in the push notification payload.1.0.0
click_actionstringThe action to be performed on the user opening the notification. Only available on Android.1.0.0
linkstringDeep link from the notification. Only available on Android.1.0.0
groupstringSet the group identifier for notification grouping. Only available on Android. Works likethreadIdentifier on iOS.1.0.0
groupSummarybooleanDesignate this notification as the summary for an associatedgroup. Only available on Android.1.0.0

Channel

PropTypeDescriptionDefaultSince
idstringThe channel identifier.1.0.0
namestringThe human-friendly name of this channel (presented to the user).1.0.0
descriptionstringThe description of this channel (presented to the user).1.0.0
soundstringThe sound that should be played for notifications posted to this channel. Notification channels with an importance of at least3 should have a sound. The file name of a sound file should be specified relative to the android appres/raw directory.1.0.0
importanceImportanceThe level of interruption for notifications posted to this channel.31.0.0
visibilityVisibilityThe visibility of notifications posted to this channel. This setting is for whether notifications posted to this channel appear on the lockscreen or not, and if so, whether they appear in a redacted form.1.0.0
lightsbooleanWhether notifications posted to this channel should display notification lights, on devices that support it.1.0.0
lightColorstringThe light color for notifications posted to this channel. Only supported if lights are enabled on this channel and the device supports it. Supported color formats are#RRGGBB and#RRGGBBAA.1.0.0
vibrationbooleanWhether notifications posted to this channel should vibrate.1.0.0

ListChannelsResult

PropTypeDescriptionSince
channelsChannel[]List of all the Channels created by your app.1.0.0

PermissionStatus

PropTypeDescriptionSince
receivePermissionStatePermission state of receiving notifications.1.0.0

PluginListenerHandle

PropType
remove() => Promise<void>

Token

PropTypeDescriptionSince
valuestringOn iOS it contains the APNS token. On Android it contains the FCM token.1.0.0

RegistrationError

PropTypeDescriptionSince
errorstringError message describing the registration failure.4.0.0

ActionPerformed

PropTypeDescriptionSince
actionIdstringThe action performed on the notification.1.0.0
inputValuestringText entered on the notification action. Only available on iOS.1.0.0
notificationPushNotificationSchemaThe notification in which the action was performed.1.0.0

Type Aliases

Importance

The importance level. For more details, see theAndroid Developer Docs

1 | 2 | 3 | 4 | 5

Visibility

The notification visibility. For more details, see theAndroid Developer Docs

-1 | 0 | 1

PermissionState

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

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp