Ionic Capacitor Local Notification

Recently I am working on an app, in which I need to use the local notification. So, this week I have learned about Notifications, 

Push Notifications and Local Notifications, Notification plugins.

I am using an ionic capacitor with Angular to develop the app, and the capacitor provides you several plugins. So, today let's talk about the implementation of Local Notification.

Below are the steps to implement the ionic capacitor local notifications:

[Note: The steps include creating, building, and executing the project. If you only want to know the LocalNotification implement start to read from step 6]

Steps to use Ionic Capacitor Local Notification:

1. Create a blank project

> ionic start ionicLocalNotification blank –type=angular –capacitor

2. Change to your project directory and build the project 

>cd .\ionicLocalNotification

> ionic build

3. You can use any one of the below commands to add the android platform to your application

> npx cap add android 

>ionic cap add android

4. To execute the project on android, use the below command. “--livereload”- this option detects changes in code and reload the application, if you are using LAN, a device or an emulator “--external” option is useful, otherwise the web view tries to access “localhost”.

> ionic capacitor run android --livereload –external

5. I have created two buttons in the template (“.html” file) of components to trigger the notifications.

home.page.html

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Ionic Local Notification
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-button (click)="scheduleBasic()" expand="block" fill="clear"> Schedule Basic</ion-button>
  <ion-button (click)="repeatNotification()" expand="block" fill="clear"> Schedule Repeat without color</ion-button>
  <ion-button (click)="scheduleAdvanced()" expand="block" fill="clear"> Schedule Advanced</ion-button>
  
</ion-content>

 

6. To use the LocalNotification, you must import the Plugins from “@capacitor/core”,

And assign it in a constant.

Home.page.ts

import { Component, OnInit } from '@angular/core';
import {LocalNotification, LocalNotificationActionPerformed, NotificationChannel, Plugins} from '@capacitor/core';
import {AlertController} from '@ionic/angular'; 

const {LocalNotifications}= Plugins;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit{

  constructor( private alertCtrl: AlertController) {}

 

 

[Note: Make sure to use async before ngOnInit() if you are using await function in there.]

 

For request permission you use requestPermission() on LocalNotifications

 async ngOnInit(){
    LocalNotifications.createChannel(channel);
    await LocalNotifications.requestPermission();
    // this.scheduleBasic();
    LocalNotifications.registerActionTypes({
      types:[
        {
          id: 'CHAT_MSG',   
          actions:[
            // {
            //   id:'view',
            //   title:'OpenChat'
            // },
            {
              id: 'remove',
              title: 'Dismiss',
              destructive: true
            },
            {         
              id: 'respond',
              title: 'Respond',
              input: true
            },
            {
              id:'fore',
              title:'foreground',
              foreground: true
            }
          ]
        }
      ]
    });

    LocalNotifications.addListener('localNotificationReceived',(notification: LocalNotification)=>{
      this.presentAlert(`Received: ${notification.id}`,`Custom Data: ${JSON.stringify(notification.extra)}`);
      console.log(notification.id);
    });

    LocalNotifications.addListener('localNotificationActionPerformed', (notification:LocalNotificationActionPerformed)=>{
      this.presentAlert(`Performed: ${notification.actionId}`, `Input value:${notification.inputValue}`);
    });
  }

 

Use the schedule() function to schedule your notifications.

  async scheduleBasic(){
    await LocalNotifications.schedule({
      notifications:[
        {
          title: 'Basic Reminder',
          body: 'A pop up in instant',
          id:1,
         // sound:null,
          extra:{
            data: 'Pass data to your handler'
          },
          iconColor: '#0000ff'
        }
      ]
    });
  }



I have used some of the options of schedule. You can always go to its definition to know more.

async scheduleAdvanced(){
    await LocalNotifications.schedule({
      notifications:[
        {
          title: ' Reminder with Action',
          body: ' Hey I have action types',
          id: 2,
          sound:null,
          extra:{
            data: 'Pass data to handler'
          },
          iconColor:'#0000ff',
          actionTypeId:'CHAT_MSG',
          schedule:{
            //  at: new Date(Date.now()+1000*3),
            // repeats:true,
            // every:'minute',
             count:5,
            // on: {
            //   minute: 5
            // }
          }
        }
      ]
    });
  }

  async presentAlert(header, message){
    const alert= await this.alertCtrl.create({
      header,
      message,
      buttons:['OK']
    });
    alert.present();
  }

 

Below is the output of my code: