メインコンテンツまでスキップ
バージョン: v8

@capacitor/local-notifications

ローカル通知APIは、デバイスの通知をローカルにスケジューリングする方法を提供します(サーバーがプッシュ通知を送信しない場合)。

Install

npm install @capacitor/local-notifications
npx cap sync

Android

Android 13では、通知を送信するためにパーミッションチェックが必要です。checkPermissions()requestPermissions()を適切に呼び出す必要があります。

Android 12以前では、プロンプトは表示されず、許可されたものとして返されます。

Android 12以降、以下のパーミッションをAndroidManifest.xmlに追加しない限り、スケジュールされた通知は正確になりません:

<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />

パーミッションが存在していても、ユーザーはアプリ設定から正確な通知を無効にできることに注意してください。checkExactNotificationSetting()を使用して設定の値を確認してください。ユーザーがこの設定を無効にすると、アプリは再起動し、正確なアラームでスケジュールされた通知は削除されます。アプリケーションが正確なアラームに依存している場合は、フォールバックまたは代替動作を提供するために、アプリ起動時(例:App.appStateChange)にこの設定を確認してください。

Android 14では、USE_EXACT_ALARMという新しいパーミッションがあります。このパーミッションを使用すると、ユーザーにパーミッションを要求せずに正確なアラームを使用できます。これは、正確なアラームの使用がアプリの機能の中心である場合にのみ使用してください。このパーミッションの使用の影響についてはこちらを参照してください。

Android 15以降、ユーザーはプライベートスペースにアプリをインストールできます。ユーザーはいつでもプライベートスペースをロックでき、ユーザーがロックを解除するまでプッシュ通知は表示されません。

アプリがプライベートスペースにインストールされているかどうかを検出することはできません。そのため、アプリが重要な通知を表示する場合は、プライベートスペースにアプリをインストールしないようユーザーに通知してください。

プライベートスペースに関連するアプリの動作変更の詳細については、Androidドキュメントを参照してください。

設定

Androidでは、ローカル通知は以下のオプションで設定できます:

プロパティ説明Since
smallIconstring通知のデフォルトのステータスバーアイコンを設定します。アイコンはアプリのres/drawableフォルダに配置する必要があります。このオプションの値は、拡張子なしのファイル名であるdrawableリソースIDです。Androidのみで使用可能です。1.0.0
iconColorstring通知のステータスバーアイコンのデフォルトの色を設定します。Androidのみで使用可能です。1.0.0
soundstring通知のデフォルトの通知音を設定します。Android 8以降ではデフォルトのチャンネルサウンドを設定し、アプリがアンインストールされない限り変更できません。オーディオファイルが見つからない場合、Android 7.xではデフォルトのシステムサウンドが再生され、Android 8以降では音が鳴りません。Androidのみで使用可能です。1.0.0

設定例

capacitor.config.jsonでの設定:

{
"plugins": {
"LocalNotifications": {
"smallIcon": "ic_stat_icon_config_sample",
"iconColor": "#488AFF",
"sound": "beep.wav"
}
}
}

capacitor.config.tsでの設定:

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

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

const config: CapacitorConfig = {
plugins: {
LocalNotifications: {
smallIcon: "ic_stat_icon_config_sample",
iconColor: "#488AFF",
sound: "beep.wav",
},
},
};

export default config;

Doze

デバイスがDozeモードに入った場合、アプリケーションの機能が制限される可能性があります。Doze中でも通知を発火させる必要がある場合は、allowWhileIdle: trueを使用して通知をスケジュールしてください。これらの通知はアプリごとに9分に1回しか発火できないため、allowWhileIdleは慎重に使用してください。

API

schedule(...)

schedule(options: ScheduleOptions) => Promise<ScheduleResult>

Schedule one or more local notifications.

ParamType
options
ScheduleOptions

Returns:

Promise<ScheduleResult>

Since: 1.0.0


getPending()

getPending() => Promise<PendingResult>

Get a list of pending notifications.

Returns:

Promise<PendingResult>

Since: 1.0.0


registerActionTypes(...)

registerActionTypes(options: RegisterActionTypesOptions) => Promise<void>

Register actions to take when notifications are displayed.

Only available for iOS and Android.

ParamType
options
RegisterActionTypesOptions

Since: 1.0.0


cancel(...)

cancel(options: CancelOptions) => Promise<void>

Cancel pending notifications.

ParamType
options
CancelOptions

Since: 1.0.0


areEnabled()

areEnabled() => Promise<EnabledResult>

Check if notifications are enabled or not.

Returns:

Promise<EnabledResult>

Since: 1.0.0


getDeliveredNotifications()

getDeliveredNotifications() => Promise<DeliveredNotifications>

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

Returns:

Promise<DeliveredNotifications>

Since: 4.0.0


removeDeliveredNotifications(...)

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

Remove the specified notifications from the notifications screen.

ParamType
delivered
DeliveredNotifications

Since: 4.0.0


removeAllDeliveredNotifications()

removeAllDeliveredNotifications() => Promise<void>

Remove all the notifications from the notifications screen.

Since: 4.0.0


createChannel(...)

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

Create a notification channel.

Only available for Android.

ParamType
channel
Channel

Since: 1.0.0


deleteChannel(...)

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

Delete a notification channel.

Only available for Android.

ParamType
args{ id: string; }

Since: 1.0.0


listChannels()

listChannels() => Promise<ListChannelsResult>

Get a list of notification channels.

Only available for Android.

Returns:

Promise<ListChannelsResult>

Since: 1.0.0


checkPermissions()

checkPermissions() => Promise<PermissionStatus>

Check permission to display local notifications.

Returns:

Promise<PermissionStatus>

Since: 1.0.0


requestPermissions()

requestPermissions() => Promise<PermissionStatus>

Request permission to display local notifications.

Returns:

Promise<PermissionStatus>

Since: 1.0.0


changeExactNotificationSetting()

changeExactNotificationSetting() => Promise<SettingsPermissionStatus>

Direct user to the application settings screen to configure exact alarms.

In the event that a user changes the settings from granted to denied, the application will restart and any notification scheduled with an exact alarm will be deleted.

On Android < 12, the user will NOT be directed to the application settings screen, instead this function will return granted.

Only available on Android.

Returns:

Promise<SettingsPermissionStatus>

Since: 6.0.0


checkExactNotificationSetting()

checkExactNotificationSetting() => Promise<SettingsPermissionStatus>

Check application setting for using exact alarms.

Only available on Android.

Returns:

Promise<SettingsPermissionStatus>

Since: 6.0.0


addListener('localNotificationReceived', ...)

addListener(eventName: 'localNotificationReceived', listenerFunc: (notification: LocalNotificationSchema) => void) => Promise<PluginListenerHandle>

Listen for when notifications are displayed.

ParamType
eventName'localNotificationReceived'
listenerFunc
(notification: LocalNotificationSchema) => void

Returns:

Promise<PluginListenerHandle>

Since: 1.0.0


addListener('localNotificationActionPerformed', ...)

addListener(eventName: 'localNotificationActionPerformed', listenerFunc: (notificationAction: ActionPerformed) => void) => Promise<PluginListenerHandle>

Listen for when an action is performed on a notification.

ParamType
eventName'localNotificationActionPerformed'
listenerFunc
(notificationAction: ActionPerformed) => void

Returns:

Promise<PluginListenerHandle>

Since: 1.0.0


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all listeners for this plugin.

Since: 1.0.0


Interfaces

ScheduleResult

PropTypeDescriptionSince
notificationsLocalNotificationDescriptor[]The list of scheduled notifications.1.0.0

LocalNotificationDescriptor

The object that describes a local notification.

PropTypeDescriptionSince
idnumberThe notification identifier.1.0.0

ScheduleOptions

PropTypeDescriptionSince
notificationsLocalNotificationSchema[]The list of notifications to schedule.1.0.0

LocalNotificationSchema

PropTypeDescriptionSince
titlestringThe title of the notification.1.0.0
bodystringThe body of the notification, shown below the title.1.0.0
largeBodystringSets a multiline text block for display in a big text notification style.1.0.0
summaryTextstringUsed to set the summary text detail in inbox and big text notification styles. Only available for Android.1.0.0
idnumberThe notification identifier. On Android it's a 32-bit int. So the value should be between -2147483648 and 2147483647 inclusive.1.0.0
schedule
Schedule
Schedule this notification for a later time.1.0.0
soundstringName of the audio file to play when this notification is displayed. Include the file extension with the filename. On iOS, the file should be in the app bundle. On Android, the file should be in res/raw folder. Recommended format is .wav because is supported by both iOS and Android. Only available for iOS and Android 7.x. For Android 8+ use channelId of a channel configured with the desired sound. If the sound file is not found, (i.e. empty string or wrong name) the default system notification sound will be used. If not provided, it will produce the default sound on Android and no sound on iOS.1.0.0
smallIconstringSet a custom status bar icon. If set, this overrides the smallIcon option from Capacitor configuration. Icons should be placed in your app's res/drawable folder. The value for this option should be the drawable resource ID, which is the filename without an extension. Only available for Android.1.0.0
largeIconstringSet a large icon for notifications. Icons should be placed in your app's res/drawable folder. The value for this option should be the drawable resource ID, which is the filename without an extension. Only available for Android.1.0.0
iconColorstringSet the color of the notification icon. Only available for Android.1.0.0
attachmentsAttachment[]Set attachments for this notification.1.0.0
actionTypeIdstringAssociate an action type with this notification.1.0.0
extraanySet extra data to store within this notification.1.0.0
threadIdentifierstringUsed to group multiple notifications. Sets threadIdentifier on the UNMutableNotificationContent. Only available for iOS.1.0.0
summaryArgumentstringThe string this notification adds to the category's summary format string. Sets summaryArgument on the UNMutableNotificationContent. Only available for iOS.1.0.0
groupstringUsed to group multiple notifications. Calls setGroup() on NotificationCompat.Builder with the provided value. Only available for Android.1.0.0
groupSummarybooleanIf true, this notification becomes the summary for a group of notifications. Calls setGroupSummary() on NotificationCompat.Builder with the provided value. Only available for Android when using group.1.0.0
channelIdstringSpecifies the channel the notification should be delivered on. If channel with the given name does not exist then the notification will not fire. If not provided, it will use the default channel. Calls setChannelId() on NotificationCompat.Builder with the provided value. Only available for Android 8+.1.0.0
ongoingbooleanIf true, the notification can't be swiped away. Calls setOngoing() on NotificationCompat.Builder with the provided value. Only available for Android.1.0.0
autoCancelbooleanIf true, the notification is canceled when the user clicks on it. Calls setAutoCancel() on NotificationCompat.Builder with the provided value. Only available for Android.1.0.0
inboxListstring[]Sets a list of strings for display in an inbox style notification. Up to 5 strings are allowed. Only available for Android.1.0.0
silentbooleanIf true, notification will not appear while app is in the foreground. Only available for iOS.5.0.0

Schedule

Represents a schedule for a notification.

Use either at, on, or every to schedule notifications.

PropTypeDescriptionSince
at
Date
Schedule a notification at a specific date and time.1.0.0
repeatsbooleanRepeat delivery of this notification at the date and time specified by at. Only available for iOS and Android.1.0.0
allowWhileIdlebooleanAllow this notification to fire while in Doze Note that these notifications can only fire once per 9 minutes, per app.1.0.0
on
ScheduleOn
Schedule a notification on particular interval(s). This is similar to scheduling cron jobs. Only available for iOS and Android.1.0.0
every
ScheduleEvery
Schedule a notification on a particular interval.1.0.0
countnumberLimit the number times a notification is delivered by the interval specified by every.1.0.0

Date

Enables basic storage and retrieval of dates and times.

MethodSignatureDescription
toString() => stringReturns a string representation of a date. The format of the string depends on the locale.
toDateString() => stringReturns a date as a string value.
toTimeString() => stringReturns a time as a string value.
toLocaleString() => stringReturns a value as a string value appropriate to the host environment's current locale.
toLocaleDateString() => stringReturns a date as a string value appropriate to the host environment's current locale.
toLocaleTimeString() => stringReturns a time as a string value appropriate to the host environment's current locale.
valueOf() => numberReturns the stored time value in milliseconds since midnight, January 1, 1970 UTC.
getTime() => numberGets the time value in milliseconds.
getFullYear() => numberGets the year, using local time.
getUTCFullYear() => numberGets the year using Universal Coordinated Time (UTC).
getMonth() => numberGets the month, using local time.
getUTCMonth() => numberGets the month of a Date object using Universal Coordinated Time (UTC).
getDate() => numberGets the day-of-the-month, using local time.
getUTCDate() => numberGets the day-of-the-month, using Universal Coordinated Time (UTC).
getDay() => numberGets the day of the week, using local time.
getUTCDay() => numberGets the day of the week using Universal Coordinated Time (UTC).
getHours() => numberGets the hours in a date, using local time.
getUTCHours() => numberGets the hours value in a Date object using Universal Coordinated Time (UTC).
getMinutes() => numberGets the minutes of a Date object, using local time.
getUTCMinutes() => numberGets the minutes of a Date object using Universal Coordinated Time (UTC).
getSeconds() => numberGets the seconds of a Date object, using local time.
getUTCSeconds() => numberGets the seconds of a Date object using Universal Coordinated Time (UTC).
getMilliseconds() => numberGets the milliseconds of a Date, using local time.
getUTCMilliseconds() => numberGets the milliseconds of a Date object using Universal Coordinated Time (UTC).
getTimezoneOffset() => numberGets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC).
setTime(time: number) => numberSets the date and time value in the Date object.
setMilliseconds(ms: number) => numberSets the milliseconds value in the Date object using local time.
setUTCMilliseconds(ms: number) => numberSets the milliseconds value in the Date object using Universal Coordinated Time (UTC).
setSeconds(sec: number, ms?: number | undefined) => numberSets the seconds value in the Date object using local time.
setUTCSeconds(sec: number, ms?: number | undefined) => numberSets the seconds value in the Date object using Universal Coordinated Time (UTC).
setMinutes(min: number, sec?: number | undefined, ms?: number | undefined) => numberSets the minutes value in the Date object using local time.
setUTCMinutes(min: number, sec?: number | undefined, ms?: number | undefined) => numberSets the minutes value in the Date object using Universal Coordinated Time (UTC).
setHours(hours: number, min?: number | undefined, sec?: number | undefined, ms?: number | undefined) => numberSets the hour value in the Date object using local time.
setUTCHours(hours: number, min?: number | undefined, sec?: number | undefined, ms?: number | undefined) => numberSets the hours value in the Date object using Universal Coordinated Time (UTC).
setDate(date: number) => numberSets the numeric day-of-the-month value of the Date object using local time.
setUTCDate(date: number) => numberSets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).
setMonth(month: number, date?: number | undefined) => numberSets the month value in the Date object using local time.
setUTCMonth(month: number, date?: number | undefined) => numberSets the month value in the Date object using Universal Coordinated Time (UTC).
setFullYear(year: number, month?: number | undefined, date?: number | undefined) => numberSets the year of the Date object using local time.
setUTCFullYear(year: number, month?: number | undefined, date?: number | undefined) => numberSets the year value in the Date object using Universal Coordinated Time (UTC).
toUTCString() => stringReturns a date converted to a string using Universal Coordinated Time (UTC).
toISOString() => stringReturns a date as a string value in ISO format.
toJSON(key?: any) => stringUsed by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization.

ScheduleOn

PropType
yearnumber
monthnumber
daynumber
weekday
Weekday
hournumber
minutenumber
secondnumber

Attachment

Represents a notification attachment.

PropTypeDescriptionSince
idstringThe attachment identifier.1.0.0
urlstringThe URL to the attachment. Use the res scheme to reference web assets, e.g. res:///assets/img/icon.png. Also accepts file URLs.1.0.0
options
AttachmentOptions
Attachment options.1.0.0

AttachmentOptions

PropTypeDescriptionSince
iosUNNotificationAttachmentOptionsTypeHintKeystringSets the UNNotificationAttachmentOptionsTypeHintKey key in the hashable options of UNNotificationAttachment. Only available for iOS.1.0.0
iosUNNotificationAttachmentOptionsThumbnailHiddenKeystringSets the UNNotificationAttachmentOptionsThumbnailHiddenKey key in the hashable options of UNNotificationAttachment. Only available for iOS.1.0.0
iosUNNotificationAttachmentOptionsThumbnailClippingRectKeystringSets the UNNotificationAttachmentOptionsThumbnailClippingRectKey key in the hashable options of UNNotificationAttachment. Only available for iOS.1.0.0
iosUNNotificationAttachmentOptionsThumbnailTimeKeystringSets the UNNotificationAttachmentOptionsThumbnailTimeKey key in the hashable options of UNNotificationAttachment. Only available for iOS.1.0.0

PendingResult

PropTypeDescriptionSince
notificationsPendingLocalNotificationSchema[]The list of pending notifications.1.0.0

PendingLocalNotificationSchema

PropTypeDescriptionSince
titlestringThe title of the notification.1.0.0
bodystringThe body of the notification, shown below the title.1.0.0
idnumberThe notification identifier.1.0.0
schedule
Schedule
Schedule this notification for a later time.1.0.0
extraanySet extra data to store within this notification.1.0.0

RegisterActionTypesOptions

PropTypeDescriptionSince
typesActionType[]The list of action types to register.1.0.0

ActionType

A collection of actions.

PropTypeDescriptionSince
idstringThe ID of the action type. Referenced in notifications by the actionTypeId key.1.0.0
actionsAction[]The list of actions associated with this action type.1.0.0
iosHiddenPreviewsBodyPlaceholderstringSets hiddenPreviewsBodyPlaceholder of the UNNotificationCategory. Only available for iOS.1.0.0
iosCustomDismissActionbooleanSets customDismissAction in the options of the UNNotificationCategory. Only available for iOS.1.0.0
iosAllowInCarPlaybooleanSets allowInCarPlay in the options of the UNNotificationCategory. Only available for iOS.1.0.0
iosHiddenPreviewsShowTitlebooleanSets hiddenPreviewsShowTitle in the options of the UNNotificationCategory. Only available for iOS.1.0.0
iosHiddenPreviewsShowSubtitlebooleanSets hiddenPreviewsShowSubtitle in the options of the UNNotificationCategory. Only available for iOS.1.0.0

Action

An action that can be taken when a notification is displayed.

PropTypeDescriptionSince
idstringThe action identifier. Referenced in the 'actionPerformed' event as actionId.1.0.0
titlestringThe title text to display for this action.1.0.0
requiresAuthenticationbooleanSets authenticationRequired in the options of the UNNotificationAction. Only available for iOS.1.0.0
foregroundbooleanSets foreground in the options of the UNNotificationAction. Only available for iOS.1.0.0
destructivebooleanSets destructive in the options of the UNNotificationAction. Only available for iOS.1.0.0
inputbooleanUse a UNTextInputNotificationAction instead of a UNNotificationAction. Only available for iOS.1.0.0
inputButtonTitlestringSets textInputButtonTitle on the UNTextInputNotificationAction. Only available for iOS when input is true.1.0.0
inputPlaceholderstringSets textInputPlaceholder on the UNTextInputNotificationAction. Only available for iOS when input is true.1.0.0

CancelOptions

PropTypeDescriptionSince
notificationsLocalNotificationDescriptor[]The list of notifications to cancel.1.0.0

EnabledResult

PropTypeDescriptionSince
valuebooleanWhether or not the device has local notifications enabled.1.0.0

DeliveredNotifications

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

DeliveredNotificationSchema

PropTypeDescriptionSince
idnumberThe notification identifier.4.0.0
tagstringThe notification tag. Only available on Android.4.0.0
titlestringThe title of the notification.4.0.0
bodystringThe body of the notification, shown below the title.4.0.0
groupstringThe configured group of the notification. Only available for Android.4.0.0
groupSummarybooleanIf this notification is the summary for a group of notifications. Only available for Android.4.0.0
dataanyAny additional data that was included in the notification payload. Only available for Android.4.0.0
extraanyExtra data to store within this notification. Only available for iOS.4.0.0
attachmentsAttachment[]The attachments for this notification. Only available for iOS.1.0.0
actionTypeIdstringAction type ssociated with this notification. Only available for iOS.4.0.0
schedule
Schedule
Schedule used to fire this notification. Only available for iOS.4.0.0
soundstringSound that was used when the notification was displayed. Only available for iOS.4.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 least 3 should have a sound. The file name of a sound file should be specified relative to the android app res/raw directory. If the sound is not provided, or the sound file is not found no sound will be used.1.0.0
importance
Importance
The level of interruption for notifications posted to this channel.
3
1.0.0
visibility
Visibility
The 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[]The list of notification channels.1.0.0

PermissionStatus

PropTypeDescriptionSince
display
PermissionState
Permission state of displaying notifications.1.0.0

SettingsPermissionStatus

PropTypeDescriptionSince
exact_alarm
PermissionState
Permission state of using exact alarms.6.0.0

PluginListenerHandle

PropType
remove() => Promise<void>

ActionPerformed

PropTypeDescriptionSince
actionIdstringThe identifier of the performed action.1.0.0
inputValuestringThe value entered by the user on the notification. Only available on iOS for notifications with input set to true.1.0.0
notification
LocalNotificationSchema
The original notification schema.1.0.0

Type Aliases

ScheduleEvery

'year' | 'month' | 'two-weeks' | 'week' | 'day' | 'hour' | 'minute' | 'second'

Importance

The importance level. For more details, see the Android Developer Docs

1 | 2 | 3 | 4 | 5

Visibility

The notification visibility. For more details, see the Android Developer Docs

-1 | 0 | 1

PermissionState

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

Enums

Weekday

MembersValue
Sunday1
Monday2
Tuesday3
Wednesday4
Thursday5
Friday6
Saturday7