achabacha322
achabacha322

Reputation: 651

Schedule a function to run at a future time with Cordova on Android

I have an ionic app and I'd like to schedule a notification at a later time, and also calling some other function at a later time as well.

What I have now:

    var now = new Date();
    var _10SecondsFromNow = new Date(now.getTime() + (10 * 1000));
    $cordovaLocalNotification.schedule({
      id: 1,
      title: 'Title here',
      text: 'Text here',
      at: _10SecondsFromNow
    }, function(){
      console.log('callback') // never called
    })
    .then(function(){
      console.log('then'); // called right away
    });

The .then promise runs right away instead of when the notification occurs 10 seconds later. I also noticed in the docs that there is a callback you can pass to localNotification, however, it is never called.

I am open to any way to schedule a future task, I am not limited to localNotification from cordova.

Upvotes: 2

Views: 1554

Answers (1)

Dexter
Dexter

Reputation: 2472

You can do this by using localNotifications if you monitor either the trigger or click event, depending on what you want to achieve.

The trigger event will be fired once the notification is shown, which seems to be what you want and looks like this:

$rootScope.$on('$cordovaLocalNotification:trigger', function(event, notification, state) {
  // Your function here
})

Or you can use the click event, which is only fired once the user taps on the notification and opens your app, which looks like this:

$rootScope.$on('$cordovaLocalNotification:click', function(event, notification, state) {
  // Your function here
})

Both of these events are documented here, but the official Cordova plugin documentation may also be of use, you can find it here.

Upvotes: 3

Related Questions