In this Ionic 5/4 article, we’ll learn how to show local notifications or push messages in Ionic Angular application. These Notifications can be sent from triggers within the app using Cordova and Native plugins with number of configurations available.
Some of the applications may have some operations running on the device without any need for network connections. In that case, we may want to show some type on notifications like reminders, alerts of some notifications other then push messages. Such type of notifications which are pushed by the locally installed app in the device is local notifications.Â
In Ionic applications it’s possible to show local notifications with a variety of flexible options like ID, custom sound, text, title, LED color customizations, etc.
Here we will create a new Ionic Application with a blank template to demonstrate the different types of local notifications with example.
[lwptoc]
Let’s get started!
Supported Platforms
- Android
- iOS
- Windows
Update Ionic CLI
First, make sure you have the latest version on Ionic CLI installed on your system. Run following CLI command to update Ionic CLI to the latest version
$ npm install -g @ionic/cli
Create an Ionic Application
To demonstrate Ionic local notifications we will create a new Ionic application. If you already have a running application just use that. Run following CLI command to create a new Ionic application with a blank template.
# Create app
$ ionic start ionic-local-notification-app blank --type=angular
# Change directory
$ cd ionic-local-notification-app
# Open code in Visual Studio Code
$ code .
Install Cordova and Native Local Notification Plugin
After creating and moving to the app folder in CLI we will install Cordova and Ionic native plugin for Local Notifications to work in the application.
Run following CLI commands to install the native plugin.
$ ionic cordova plugin add cordova-plugin-local-notification
$ npm install @ionic-native/local-notifications
Import Local Notification Plugin in App Module
To use local notification we need to import local notification then add in providers array. Open the app.module.ts file, then make the following changes.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { LocalNotifications } from '@ionic-native/local-notifications/ngx';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,
LocalNotifications,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
Use Local Notification in Home Component
To create a Local notification we first need to import it in component then call schedule method with options.
Add the following buttons in the home.page.html file.
<ion-button (click)="single_notification()">
Single Notification
</ion-button>
<ion-button (click)="multi_notification()">
Multi Notifcations
</ion-button>
<ion-button (click)="delayed_notification()">
Delayed Notification
</ion-button>
then add three types of example methods with different options in home.page.ts file
import { Component } from '@angular/core';
import { LocalNotifications } from '@ionic-native/local-notifications/ngx';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(private localNotifications: LocalNotifications) { }
single_notification() {
// Schedule a single notification
this.localNotifications.schedule({
id: 1,
text: 'Single ILocalNotification',
sound: 'file://sound.mp3',
data: { secret: 'key_data' }
});
}
multi_notification() {
// Schedule multiple notifications
this.localNotifications.schedule([{
id: 1,
text: 'Multi ILocalNotification 1',
sound: 'file://sound.mp3',
data: { secret: 'key_data' }
}, {
id: 2,
title: 'Local ILocalNotification Example',
text: 'Multi ILocalNotification 2',
icon: 'http://example.com/icon.png'
}]);
}
delayed_notification() {
// Schedule delayed notification
this.localNotifications.schedule({
text: 'Delayed ILocalNotification',
trigger: { at: new Date(new Date().getTime() + 3600) },
led: 'FF0000',
sound: null
});
}
}
If next notification is having the same id,
it will replace the previous. The schedule()
method is called with configuration option properties to trigger a local notification.
Methods Available in LocalNotification Class
hasPermission()
: Promise<boolean>; Informs if the app has the permission to show notifications.requestPermission()
: Promise<boolean>; Request permission to show notifications if not already granted.schedule(options?: ILocalNotification | ILocalNotification[])
: void; Schedules a single or multiple notifications.update(options?: ILocalNotification)
: void; Updates a previously scheduled notification. Must include the id in the options parameter.clear(notificationId: any)
: Promise<any>; Clears single or multiple notificationsclearAll()
: Promise<any>; Clears all notificationscancel(notificationId: any)
: Promise<any>;cancelAll()
: Promise<any>; Cancels all notificationsisPresent(notificationId: number)
: Promise<boolean>; Checks presence of a notificationisScheduled(notificationId: number)
: Promise<boolean>; Checks is a notification is scheduledisTriggered(notificationId: number)
: Promise<boolean>; Checks if a notification is triggeredhasType(id: number, type: string)
: Promise<boolean>; Check if a notification has a given type.getType(id: number)
: Promise<boolean>; Get the type (triggered, scheduled) for the notification.getIds()
: Promise<number[]>; Get all the notification idsgetScheduledIds()
: Promise<number[]>; Get the ids of scheduled notificationsgetTriggeredIds()
: Promise<number[]>; Get the ids of triggered notificationsget(notificationId: any)
: Promise<ILocalNotification>; Get a notification objectgetAll()
: Promise<ILocalNotification[]>; Get all notification objectsgetScheduled(notificationId: any)
: Promise<ILocalNotification>; Get a scheduled notification objectgetTriggered(notificationId: any)
: Promise<ILocalNotification>; Get a triggered notification objectaddActions(groupId: any, actions: ILocalNotificationAction[])
: Promise<any>; Adds a group of actionsremoveActions(groupId: any)
: Promise<any>; Removes a group of actionshasActions(groupId: any)
: Promise<boolean>; Checks if a group of actions is definedgetDefaults()
: Promise<any>; Gets the (platform specific) default settings.setDefaults(defaults: any)
: Promise<any>; Overwrites the (platform specific) default settings.getAllScheduled()
: Promise<ILocalNotification[]>; Get all scheduled notification objectsgetAllTriggered()
: Promise<ILocalNotification[]>; Get all triggered notification objectson(eventName: string)
: Observable<any>; Sets a callback for a specific event. Available events: schedule, trigger, click, update, clear, clearall, cancel, cancelall.fireEvent(eventName: string, args: any)
: void; Not an official interface, however its possible to manually fire events.fireQueuedEvents()
: Promise<any>; Fire queued events once the device is ready and all listeners are registered.
Options Available for Local Notifications
id
? : number; A unique identifier required to clear, cancel, update or retrieve the local notification in the futuretitle
? : string; First row of the notificationtext
? : string | string[]; Second row of the notificationbadge
? : number; The number currently set as the badge of the app icon in Springboard (iOS) or at the right-hand side of the local notification (Android)sound
? : string; Uri of the file containing the sound to play when an alert is displayeddata
? : any; Arbitrary data, objects will be encoded to JSON stringicon
? : string; ANDROID ONLY Uri of the icon that is shown in the ticker and notificationsmallIcon
? : string; ANDROID ONLY. Uri of the resource (only res ://) to use in the notification layouts. Different classes of devices may return different sizescolor
? : string; ANDROID ONLY RGB value for the background color of the smallIcon.vibrate
? : boolean; ANDROID ONLY Use the default notification vibrate.led
? : ANDROID ONLY. Define the blinking of the LED on the device.priority
? : number; Notification priority.silent
? : boolean; Is a silent notificationlaunch
? : boolean; Specifies whether the a click on the notification causes the app to launch in the foregroundwakeup
? : boolean; ANDROID ONLY. Wakeup the device. (default is true)timeoutAfter
? : number | false; ANDROID ONLY. Specifies a duration in milliseconds after which this notification should be canceled, if it is not already canceled.actions
? : string | ILocalNotificationAction[]; Actions id or actionstrigger
? : ILocalNotificationTrigger; When to trigger the notificationattachments
? : string[]; A list of image attachments
So by using a Local Notification native plugin, we can easily show customized notification from an application itself on the device. you can check more options and examples here
Conclusion
We discussed how to easily implement the local notification in the Ionic application scheduled from the application itself which can be triggered from outside to inside the application using Cordova and native plugins.
Hope you enjoyed this tutorial, thanks for reading!
Leave a Reply