How to use Local Notifications with Ionic Framework

Written by on August 21, 2015

How to use Local Notifications with Ionic Framework

Once in a while you will need to inform application user that there’s an information they’re required to see, for example, an upcoming appointment. This is, of course, easy if said application is active and running but what if it’s running in the foreground? We can easily solve this problem with local notifications.

Note: If this tutorial was helpful, you need further clarification, something is not working or you have a request for another Ionic post? Furthermore, leave me a comment below if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com. Thanks and have a nice day!

Table of Contents

[spoiler title=” Click here if you want to see other tutorials, or articles about the Ionic framework (themes, templates, plugins, tutorials)”]

Tutorials

Other Resources (themes, templates, plugins, Cordova plugins, starter apps)

Cordova Plugin Tutorials


[/spoiler]

Preparation

Before we can start make sure you have these requirements; if you already have a configured Ionic Framework environment, skip this step completely:

  • Android Environment (or iOS if your working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova

No previous Ionic Framework experience, find more information here: Ionic Framework | Installation Guide.

1. Update Ionic & Cordova

The latest nodeJs version is a top priority, make sure you have it installed. You will not be able to download/update latest Ionic Framework without it.

When you check your nodeJS version, update Ionic, and Cordova, older versions may not work with this tutorial:

npm update -g cordova ionic

2. Create a New Project

ionic start IonicLocalNotificationDemo blank
cd IonicLocalNotificationDemo

Warning: Since some of you never worked with Ionic CLI. From this point and further, every time I tell you to execute something, do that inside a project folder.

This example will use Android platform so add it to this project:

ionic platform add android

For MacOS users, do it like this:

ionic platform add ios

3. Download ngCordova archive

ngCordova is a collection of 63+ AngularJS extensions on top of the Cordova API that make it easy to build, test, and deploy Cordova mobile apps with AngularJS. While we can make this work without ngCordova, it’s much more practical this way. This collection also holds many Ionic Framework compatible plugins.

Download ngCordova zip file, here’s site link:

Official Site
Docs
Download Link

Unzip this archive, find a file name called: ng-cordova.min.js, it should be available at this location: ng-cordova-master\dist\.

Open your newly created project directory and copy ng-cordova.min.js to this location: IonicLocalNotificationDemo\www\js.

Now include this location to index.html located at IonicLocalNotificationDemo\www; add it above cordova.js file, like this:

<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>

4. Install Cordova Local Notification Plugin

Add required plugins:

cordova plugin add https://github.com/katzer/cordova-plugin-local-notifications.git
cordova plugin add cordova-plugin-whitelist

Install Whitelist plugin only if you’re using Cordova 4.0 +. Without it you’ll receive “Application Error: There was a network error.” error.

GitHub - Local Notification

Development

At this point, you should have everything set up and ready, we can start working on our example.

Go to IonicLocalNotificationDemo project directory and find app.js, alter angular.module line and include ngCordova service, like this:

var app = angular.module('starter', ['ionic', 'ngCordova'])

Open index.html file, add a controller to ion-pane directive:

  <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Local Notification Example</h1>
      </ion-header-bar>
      <ion-content ng-controller="NotificationController">
      </ion-content>
   </ion-pane>

Initialize this controller in app.js file; don’t forget to inject $cordovaLocalNotification service. We will also need $ionicPlatform, like this:

app.controller('NotificationController', function($scope, $cordovaLocalNotification, $ionicPlatform) {

});

If you’re using Cordova 4+ you will need to check if there’s a Whitelist plugin installed with your project. If you have it, add this security meta tag to your index.html HEAD content:

<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">

Without it your application will throw an error during the app initialization, after that it will constantly throwing no security meta-tag found. While not a blocking point, constant console log warnings will make it hard to do any debugging.

We will use next function to trigger a notification, don’t forget to wrap it into Cordova deviceready event (or Ionic ready event depending on your project):

  $cordovaLocalNotification.schedule({
	id: 1,
	title: 'Warning',
	text: "You're so sexy!",
	data: {
	  customProperty: 'custom value'
	}
  }).then(function (result) {
	console.log('Notification 1 triggered');
  });

id is the most important part of this function. It’s a number that represents your local notification. Once you trigger it you can update it or cancel it through this number. In the next example, you’ll find all necessary examples.

Continue Reading

Categories

31 thoughts on “How to use Local Notifications with Ionic Framework”

  1. Great little tutorial for doing local notifications! As a newb, I got caught on:

    “Go to IonicLocalNotificationDemo project directory and find app.js, alter angular.module line and include ngCordova service, like this:”

    I only added the ngCordova to the modules list, and didn’t notice that you also defined the app there by adding “var app =” to the start.

    Thanks for the write up. Keep em coming! Helps a lot.

  2. Great tutorial as always.
    How would be a good way to redirect to a specific view after the user taps the notification, as in, I don’t want to reopen the previously shown screen, but rather open a specific one depending on the type of notification and information associated with it, like one would in native android by passing arguments to an intent and then starting it.
    Thanks.

  3. Also, this doesn’t seem to work on iOS, how do you add the permissions to run local notifications to this example?

  4. I followed the instructions and everything works fine except .onclick and ontrigger do not work. How exactly should this be used? Is it $cordovaLocalNotification.onclick( ) or $cordovaLocalNotification.on(‘click’,…)?

    Thanks

    • try
      $rootScope.$on(‘$cordovaLocalNotification:click’,function (event, notification, state) { });

    • Hi Khalil, If is similar to icon, You must to put your sound’s file in “[ionic project]platformsandroidresdrawable”.

      Only in this place I can change icon of notifications here.

        • You must to put your image’s file in a folder with exact this name “[ionic-project]platformsandroidresdrawable” without specifying resolution.

          It’ll be available for all resolutions.

          • Hi,
            Facing a similar issue here.I’v added the image file in the drawable folder of my project as u suggested.But even then I can not see the image in the notification as it is.All i find is a filled white circle or square(depending on the shape of the provided image).Please help.Thanks in advance.

    • Hi.. I found here… It’s simple: just pass other params when scheduling your notification. Example:

      id: 1,
      title: ‘My Title’,
      text: ‘My text’,
      badge: 1,
      icon: ‘res://coffee.png’,
      smallIcon: ‘res://social_usd.png’,
      color: ‘0000FF’

      • Hi,
        I have been trying to use a custom image on the cordova notification by placing the image on the res/drawable-hdpi/ folder, but when i compile it i see only a blank image. Let me know how to rectify this. Looking forward to hear from you.
        Regards
        Suresh

          • Hi,
            Thanks for the response. It doesn’t work. It still shows the same blank box.
            This is the routine
            $CordovaLocalNotification.add({
            id: “112”,
            title: “My Title”,
            text: “My text”,
            icon: “res://icon1. jpg”
            });

          • There’s one space in your imagem name above.

            I used this and works fine:

            $cordovaLocalNotification.schedule({
            id: 1,
            title: ‘My title’,
            text: ‘something to alert!’,
            badge: 1,
            icon: ‘res://coffee.png’,
            smallIcon: ‘res://checkmark.png’,
            color: ‘0000FF’,
            data: {
            customProperty: ‘custom value 1’
            }
            });

            Maybe you must to use a PNG image.

          • having problem with Lollipop and higher versions of android,wherein instead of the image it just displays a white box.In kitkat it works fine.Please help.

  5. Anyone has already successfully tried Local Notification in ionic 2 ?
    With button trigger too.

    need soft references here. Thank you

  6. Instead of assigning static value for the “at” attribute / key, how can we assign it user defined using ion-datetime-picker as its not assigning the user defined time

  7. this source copy & paste …
    not working my android device (android 4.4.2)
    What else do I need to know?

  8. Ive been trying to get local notifs to work. Im not getting any errors or anything, but no notifs either. Any ideas? Everything seems to be defined correctly and added to the controller.

  9. how can i pass the title and text of the notification in the index.html file and not in app.js

  10. I want image also..in notification..and i’m changing icon with ‘../img/logo.png’ but it is as it is..so please somebody help me

  11. How to add custom sound for local notification?
    I am using below code

    $cordovaLocalNotification.schedule({
    id: 1,
    title: ‘New Order’,
    at:1,
    text: “You have got a new order!”,
    data: {
    customProperty: ‘custom value’
    },
    sound: ‘file://audio/sound/notify-sound.wav’, or // sound: ‘file://audio/sound/notify-sound.mp3’,
    }).then(function (result) {
    navigator.vibrate([2000,500,2000,500,2000,500,2000,500,2000,500,2000]);
    console.log(‘Notification 1 triggered’);
    })

    With this code notifications are coming but sound is not working.

Leave a Reply