Ionic 5 Show Local Notifications in Ionic Application using Native Plugin

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.

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 notifications
  • clearAll() : Promise<any>; Clears all notifications
  • cancel(notificationId: any) : Promise<any>;
  • cancelAll() : Promise<any>; Cancels all notifications
  • isPresent(notificationId: number) : Promise<boolean>; Checks presence of a notification
  • isScheduled(notificationId: number) : Promise<boolean>; Checks is a notification is scheduled
  • isTriggered(notificationId: number) : Promise<boolean>; Checks if a notification is triggered
  • hasType(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 ids
  • getScheduledIds() : Promise<number[]>; Get the ids of scheduled notifications
  • getTriggeredIds() : Promise<number[]>; Get the ids of triggered notifications
  • get(notificationId: any) : Promise<ILocalNotification>; Get a notification object
  • getAll() : Promise<ILocalNotification[]>; Get all notification objects
  • getScheduled(notificationId: any) : Promise<ILocalNotification>; Get a scheduled notification object
  • getTriggered(notificationId: any) : Promise<ILocalNotification>; Get a triggered notification object
  • addActions(groupId: any, actions: ILocalNotificationAction[]) : Promise<any>; Adds a group of actions
  • removeActions(groupId: any) : Promise<any>; Removes a group of actions
  • hasActions(groupId: any) : Promise<boolean>; Checks if a group of actions is defined
  • getDefaults() : 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 objects
  • getAllTriggered() : Promise<ILocalNotification[]>; Get all triggered notification objects
  • on(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 future
  • title? : string; First row of the notification
  • text? : string | string[]; Second row of the notification
  • badge? : 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 displayed
  • data? : any; Arbitrary data, objects will be encoded to JSON string
  • icon? : string; ANDROID ONLY Uri of the icon that is shown in the ticker and notification
  • smallIcon? : string; ANDROID ONLY. Uri of the resource (only res ://) to use in the notification layouts. Different classes of devices may return different sizes
  • color? : 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 notification
  • launch? : boolean; Specifies whether the a click on the notification causes the app to launch in the foreground
  • wakeup? : 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 actions
  • trigger? : ILocalNotificationTrigger; When to trigger the notification
  • attachments? : 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!

Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Douglas

Hi ! thanks for your tutorial!!! Can you help me? How can I disable the notification with a button like toggle button ?