ngCordova + local notification plugin

Hi,

I’m playing with the $cordovaLocalNotification plugin wrapper and I’ve found that for these two methods, Android reports errors. I mean the isTriggered() and getTriggeredIds() functions. It seems that the original plugin hasn’t got these function published, is it true?

I’d like also ask someone experienced how to use the event callback events exposed by the $cordovaLocalNotification. I mean the onadd, ontrigger, onclick and oncancel. I’ve just added it to the scope and they are never fired, e.g.

$cordovaLocalNotification.onadd = function (id, state, json) {
  		console.log('rp: ' + 'onadd: ' + id);
	};
  $cordovaLocalNotification.onclick = function (id, state, json) {
  		console.log('rp: ' + 'onclick: ' + id);
	};

Could you please point me to a right direction?

One day a question, second day later the answer :wink: I should rather start a blog instead of litter here :wink:
One simple answer to my problems described above is: do not use ngCordova for local notifications. Use the plugin original examples. They work as described. ngCordova methods don’t. Simple as that. The whole magic about this plugin is:

  1. add plugin using CLI (instruction: https://github.com/katzer/cordova-plugin-local-notifications)

  2. in app_init.js or where you init your app add code that expose plugin events to the controllers. My way is:

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

.run(function($rootScope, $ionicPlatform, ...) {

  $ionicPlatform.ready(function() {
    if (window.cordova) {
      document.addEventListener("deviceready", function() {
        window.plugin.notification.local.onadd = app.onReminderAdd;
        window.plugin.notification.local.onclick = app.onReminderClick;
        window.plugin.notification.local.oncancel = app.onReminderCancel;
        window.plugin.notification.local.ontrigger = app.onReminderTrigger;
     }, false);
  }

app.onReminderAdd = function(id, state, json) {
  $timeout(function() {
    $rootScope.$broadcast('onReminderAdded', id, state, json);
  }, 100);
}
// other events this way as well... You can do this 
// without the timeout of course
}
  1. Add event handlers to your selected controller e.g.
$scope.$on('onReminderAdded', function(event, id, state, json) {
  console.log('notification ADDED, id: ' + id  + ' state:' + state + ' json:' + json );
});
  1. Now add functions that add notifications, cancel, etc, and you can handle the new traffic from notifications using the events above. For example simple code for adding an immediate notification:
$scope.addNotification = function(tit, msg) {
  window.plugin.notification.local.add({
      id: 'MYLN',
      title:   tit,
      message: msg,
      icon:      'ic_notification',
      smallIcon: 'ic_notification_small',
});

What’s worth mentioning, because it is not explained in the plugin documentation, is the icons handling procedure. The icons names in the above example points to the location: /platforms/android/res/drawable/ To make the plugin use the icons, the image files must be located in this path and named as defined in the parameters. In my case they are:

/platforms/android/res/drawable/ic_notification.png and
/platforms/android/res/drawable/ic_notification_small.png

By trail and error I’ve found that best sizes are 48x48 for the bigger and 24x24 for the smaller.

Happy notifying!

Rafaellop

1 Like

@rafaellop Hey rafael, looks great to me! If you have the time feel free to add your working solution to the ng-cordova demo files

Well, in fact, I haven’t used ngCordova because it simply doesn’t work the way it stays in the documentation. It’s been faster to just start over with the original plugin. My concept works completely without the ngCordova library so I think that ngCordova repository isn’t a good place for this tutorial.

2 Likes

Thanks for this - really useful tips in here, which helped me get notifications working properly in my Ionic app. I managed to use $cordovaLocalNotification for most of it, but it seemed that for the onclick event, I needed to revert back to window.plugin.notification.local.onclick.

I also managed to simplify the code in the initialisation stage. Basically had:

.run(function($ionicPlatform, $cordovaLocalNotification, $rootScope, DB) {

  $ionicPlatform.ready(function() {

    // Check for permissions to show local notifications - iOS 8 NEEDS permission to run!
    $cordovaLocalNotification.hasPermission().then(function(granted) {
      $cordovaLocalNotification.cancelAll();
      if (!granted) {
        $cordovaLocalNotification.promptForPermission();
      };
    });

    document.addEventListener("deviceReady", function() {
      // Event handling for Local Notifications
      window.plugin.notification.local.onclick = function(id, state, json) {
        $rootScope.$broadcast('onNotificationClick', id, state, json);
      };      
      // You can add more here for oncancel, ontrigger etc.
    });
  });
})

then in my controller where I wanted to handle the incoming notification response, I had the code:

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

	$scope.$on('onNotificationClick', function(event, id, state, json) {
            // Do whatever you need with the incoming notification here...
		$cordovaLocalNotification.cancel(id);
	});    
})

Seems to work a treat, but I never would have got there without your help, so thanks again!

1 Like

@CyberFerret, great I could help. However I’ve still got some issues with the local notification feature or maybe my understanding of this feature is wrong. Do you maybe know, or anyone else, why local notifications (Android’s) that are set for a future time in a distance of e.g. a month, don’t fire a notification in the notification area? I supposed the local notifications is a system service that works independently of the application and serving events like e.g. Windows scheduler. This is a big problem for me and I cannot find a solution. So do any of you have experience with that?

Has anybody got local notifications working in the simulator for ios?

To reply to my own question, yes it works in simulator.

1 Like

Thanks rafaellop,

I liked your approach with the $broadcast better than what I’ve implemented in the past with Push Notifications.

I was scratching my head with why ngCordova wasn’t working. I made some progress getting it to work with this post (http://devdactic.com/local-notifications-ionic/), but I liked you solution best.

Thanks again.

@ionicPlay, that’s nice :slight_smile: Thank you! Great article by the way.

@rafaellop : hey, i am using your solution but i am getting a problem
error : ’ Cannot read property ‘notification’ of undefined ’

here i am using this code please specify what i am doing wrong

in app.js

$ionicPlatform.ready(function () {

    if (window.cordova) {
    document.addEventListener("deviceready", function() {
    window.plugin.notification.local.onadd = app.onReminderAdd;
    window.plugin.notification.local.onclick = app.onReminderClick;
    window.plugin.notification.local.oncancel = app.onReminderCancel;
    window.plugin.notification.local.ontrigger = app.onReminderTrigger;
 }

app.onReminderAdd = function(id, state, json) {
$timeout(function() {
$rootScope.$broadcast(‘onReminderAdded’, id, state, json);
}, 100);
}

In controller.js

 $scope.addNotification = function(tit, msg) {
  window.plugin.notification.local.add({
  id: 'MYLN',
  title:   tit,
  message: msg

});
};

$scope.$on(‘onReminderAdded’, function(event, id, state, json) {
console.log(‘notification ADDED, id: ’ + id + ’ state:’ + state + ’ json:’ + json );
});

@nitishrajput01 The local notification plugin has undergone some backwards-breaking API changes recently and I don’t think ngCordova has been updated yet.

To be honest, it’s pretty simple to just use the notification plugin directly, without ngCordova:

$ionicPlatform.ready(function () {
  if (window.cordova && window.cordova.plugins.notification) {
    // Set default options.
    cordova.plugins.notification.local.setDefaults({
      autoCancel: false,
      badge: 1
    });

    // Ask for permission to display notifications.
    cordova.plugins.notification.local.registerPermission();

    // Listen for click event.
    cordova.plugins.notification.local.on('click', function (notification, state) {
      // Do something awesome! :smile: 
    }

    // Listen for trigger event.
    cordova.plugins.notification.local.on('trigger', function (notification, state) {
      // Do something awesome! :smile: 
    }

    // etc ...

    // To add a notification.
    cordova.plugins.notification.local.schedule({
      // options.
    });
  }
}
1 Like

Hello i have try like you but i don’t have any notification
Can someone have any issue?

Are you using Crosswalk?

Inject $cordovaLocalNotification in your controller and give permission in your app.js if your you are building on ios

and
try this

try{

var now = new Date().getTime();
var _10SecondsFromNow = new Date(now + 10 * 1000);

  $cordovaLocalNotification.schedule({
    id: 1,
    title: 'Title here',
    text: 'Text here',
    at: _10SecondsFromNow
  }).then(function (result) {
    // ...
  });
};

} catch{console.log(err);

}

1 Like

Is this plugin still working and compatible with android and iOS?

I can confirm that the local notification cordova plugin does work on ios 7/8 devices, using it on a project at the moment. I am not, however, using ngCordova.

There’s also a more active fork going of the local notification plugin that has better ios9 support too here: https://github.com/NorthMcCormick/cordova-plugin-local-notifications

I managed to get this working :wink: thank you for the reply.

Could any one tell how to set specific time in local notification.? :unamused: