enappd loader




Implement Local Notifications in Ionic 4 Apps 

In this post you are going to learn how to implement local notifications in Ionic 4 apps. We will see a variety of notification types that can be generated using Local Notifications .We will use a simple Cordova plugin for this purpose, and test the functionality on Android app.

Complete code of this blog post can be found at this github repo — ionic-4-local-notifications

What is Local Notification ? 

We have all heard of notifications, and push notifications mostly. These are the notifications app servers send to apps for regular reminders. For example, a chat app server sends notification to user to update of a latest message. These notifications are received in closed app, minimized app or open app. 



`Push notifications ….. necessary evil

Push notifications cause burden on Server, as well as, cost you money if you are using a service like OneSignal etc. Hence, for each action or reminder, you might not want the server to send push notifications to all users. Especially if you have millions of users. 

This is where Local Notifications come in handy. These look and feel exactly like push notifications, but are not sent from server. Instead, they are generated locally on your device. E.g. If you want an app to remind you of your tasks at a certain time of the day, it makes sense that the app does so using the in-built clock or timer in the device. The app then sends you Local Notification, which looks same as a push. 

You don’t feel the difference between Local and Push notification, and the server saves a lot of overhead.

In this post, we will learn how to implement Local notifications features in Ionic 4 apps. First, let’s see what Ionic 4 is all about. 

What is Ionic 4?

You probably already know about Ionic, but I’m putting it here just for the sake of beginners. Ionic is a complete open-source SDK for hybrid mobile app development created by Max Lynch, Ben Sperry and Adam Bradley of Drifty Co. in 2013. Ionic provides tools and services for developing hybrid mobile apps using Web technologies like CSS, HTML5, and Sass. Apps can be built with these Web technologies and then distributed through native app stores to be installed on devices by leveraging Cordova.

So, in other words — If you create Native apps in Android, you code in Java. If you create Native apps in iOS, you code in Obj-C or Swift. Both of these are powerful but complex languages. With Cordova (and Ionic) you can write a single piece of code for your app that can run on both iOS and Android (and windows!), that too with the simplicity of HTML, CSS, and JS.

Structure of the post

I will go ahead in step-by-step fashion so you can follow easily

  1. Create a basic Ionic 4 app
  2. Install Local Notification plugin and make imports
  3. Implement your first Local Notification
  4. Build your app on Android and test
  5. Implement various types of Local Notifications 

Let’s start with creating a simple Ionic 4 app

Step 1 — Create a basic Ionic 4 app

I have covered this topic in detail in this blog.

In short, the steps you need to take here are

  • Make sure you have node installed in the system (V10.15.3 at the time of this blog post)
  • Install ionic cli using npm (my Ionic version is 4.1.0 currently)
  • Create an Ionic app using ionic start

You can create a sidemenu starter for the sake of this tutorial. On running ionic start ionic-4-local-notifications sidemenu , node modules will be installed. Once the installation is done, run your app on browser using

$ ionic serve

The app will launch on browser. You can go to Inspect → Device Mode to see the code in a mobile layout. You can create a basic layout for triggering Local Notifications. All the real action will happen when we build the app for Android.



Basic layout for generating Local Notifications

Next we’ll add the Local Notifications plugin to our app.

Step 2 — Install Local Notification plugin and make imports

To implement Local Notifications you need to add cordova-plugin-local-notifications plugin to the app. Add the plugin using

$ ionic cordova plugin add cordova-plugin-local-notificationnpm 
$ install @ionic-native/local-notifications

This will install the plugin in your app. Next you should import the plugin in app.module.ts and in the pages you want to use it. 

import { LocalNotifications} from '@ionic-native/local-notifications/ngx'

Also, don’t forget to include LocalNotifications in @ngModule providers list.

@NgModule({
....,
providers: [
...,
LocalNotifications,
...],
})

That’s it ! You are ready to implement Local notifications in your Ionic 4 app.

Step 3 — Implement your first Local Notification

Local Notification implementation is very easy once you import the plugin correctly. Go ahead and create a function to schedule your first local notification like this


Super easy, right ? This will create a local notification and it will appear in your device’s status bar as an icon. You can check the full notification in your device’s notification tray.



Let’s dive deeper into the details of the notification object, and learn what all options are available

  • id — ID of the notifications
  • title — Title of the notification, shown in larger font. If no title is provided, app’s name is shown as title
  • text — Message of the notification. Shown in smaller font. It can be of multiple lines as well. Can be an array of messages as well. We’ll see that in later section
  • sound — location of sound file to be played with notification
  • data — additional data you can send along with notification in JSON format
  • icon —location or URL of icon shown with the notification
  • silent — (boolean) whether notification should be silent or not
  • trigger — custom trigger time of notification, can be given in various formats. We’ll see this in later section
  • attachments — Attached images to be sent with notification
  • progressBar — progress-bar options for Local notifications
  • group — define the group name to group similar notifications together
  • summary — summary of grouped notifications
  • smallIcon — Small icon shown for group notifications or custom notifications
  • sticky — whether the notification should be sticky or dismissible
  • autoClear — If yes, make the notification automatically dismissed when the user touches it (Android only)
  • lockscreen — If set to true the notification will be shown in its entirety on all lock-screens. If set to false it will not be revealed on a secure lock-screen. (Android only)
  • channel — Specifies the channel the notification should be delivered on (Android only)
  • foreground — If the notification should show up on app’s foreground
  • timeoutAfter — Specifies a duration in milliseconds after which this notification should be canceled, if it is not already canceled (Android only)
  • launch — Specifies whether a click on the notification causes the app to open in foreground
  • priority — Integers between -2 and 2, whereas -2 is minimum and 2 is maximum priority
  • led — to set LED options of the device. You can set color , on and off properties
  • vibrate — (boolean) — Whether notification should vibrate the device
  • color — RGB value for the background color of the smallIcon (Android only)
  • badge — 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). Default: 0 (which means don’t show a number)

… and few more options. That’s a lot !!! 

This is a really powerful and detailed plugin. You can make very good use of the plugin to supplement push notifications, and make your app interactive.

Step 4 — Build your app on Android and test

If you have carried out the above steps correctly, Android build should be a breeze.

Run the following command to create Android platform

$ ionic cordova platform add android

Once platform is added, run the app on device (Make sure you have a device attached to the system).

$ ionic cordova run android

Once your app is up and running on the device, you can start testing all the functions. The GIF shown above is taken from a real Android device 😎

Step 5 — Implement various types of Local Notifications

The GIF in previous section might not have impressed you a lot. So let’s have a look at the variety of notifications and actions you can perform with this plugin

Local notification in foreground

Just add foreground:true in notification trigger call, and your notification will show up in the foreground, just like Whatsapp ! 



Foreground Local Notification

Get Data from Notification Click

As we saw earlier, the data field of notification contains certain data in JSON format. We can extract this data using notification events . For our purpose, we will use click event. 

I will subscribe to the click event before scheduling the notification. Then on clicking the notification, the event will be triggered and we will get data in console. I will also show the data in an alert, just for demo. After the alert, we will unsubscribe from the listener. The complete code for this will be


The sequence will look like this



Local notification with event triggered on click

Multiple Notification at once

Just send multiple local notifications in an array inside the schedule 



Multiple Local notification at once

Delayed Local Notifications

You can also delay a notification or send it at a particular time. This way, you can even schedule notifications daily, weekly etc. 

E.g. For demo purpose, we’ll trigger a notification after 5000 ms of button click, but it will be taken as a date object. Just add the following option in notification options

trigger: { at: new Date(new Date().getTime() + 5000) },


Notification shows up after 5 second

Local Notification with Progress Bar

You can also display a local notification with a progress bar. This is useful in cases like when you are performing a long background task.

Just add following to notification options object (will show a 20% progress)

progressBar: { value: 20 }


Local notification with progress bar

Local Notification with multi-line message

You can make the notification message multi-line by adding new line characters. E.g.

text: '4:15 - 5:15 PM\nBig Conference Room'


Local Notification with Multi-line message

Local Notification with Image and Action buttons

To add a large image, you can add this to the notification options (yes, kitten photo 😛

attachments: ['http://placekitten.com/g/300/200']

For action buttons, you can add this to the options

actions: [
{ id: 'yes', title: 'Yes' },
{ id: 'no', title: 'No' }
]

An action generally has the following structure — 

id?: string;
title?: string;
foreground?: boolean;
launch?: boolean;
ui?: string;
needsAuth?: boolean;
icon?: string;
choices?: string[];
editable?: boolean;
submitTitle?: string;
type?: ILocalNotificationActionType;

This will create a notification with YES and NO buttons



Local Notification with Action buttons and Image

Local Notifications with Input

You can also generate local notification accepting input text in notification tray itself. This comes in handy in chat applications. This is all you need to add to the notification options

actions: [{
id: 'reply',
type: ILocalNotificationActionType.INPUT,
title: 'Reply'
}]

To use ILocalNotificationActionType , you will have to import it first in the page using

import { ILocalNotificationActionType } from '@ionic-native/local-notifications/ngx';

The result will look like this



Local notification with Input text

Local Notifications with Grouping

At times, you receive many notifications from the same app. E.g. your email app, or chat app. You would like to group these together so as to not take a lot of space in notification tray. You can do this easily with local notifications using the following option

this.localNotifications.schedule([
{ id: 0, title: 'Design team meeting' },
{ id: 1, summary: 'me@gmail.com', group: 'email', groupSummary: true },
{ id: 2, title: 'Please take all my money', group: 'email' },
{ id: 3, title: 'A question regarding this plugin', group: 'email'},
{ id: 4, title: 'Wellcome back home', group: 'email' }
]);

The group:'email' creates a group with similar notifications which have group:email . Here’s how it looks



Local notification with grouped notifications

You see the four emails grouped together, with one as a header. Other notification is shown as separate notification.

Conclusion

In this post, we learnt how to use Local Notification in Ionic 4 apps to generate a lot of different types of notifications. These include action buttons, input text, images, multiple notifications, grouping etc. With local notifications, you can save a lot on server push notifications. Plus it gives you the ability to schedule regular notifications as well.

Complete code of this blog post can be found at this github repo — ionic-4-local-notifications

Next Steps

Now that you have learned the implementation of Local Notifications in Ionic 4, you can also try

If you need a base to start your next Ionic 4 app, you can make your next awesome app using Ionic 4 Full App





Title
Subtitle
Kicker