Cordova-plugin-local-notifications: The notifications will not trigger when app is closed(killed) and will be triggered after opening the app

Created on 20 Apr 2020  路  10Comments  路  Source: katzer/cordova-plugin-local-notifications

I'm implementing a basic app for reminding a person to take her pills. I need to have something like an alarm clock. I need to show notifications to her with positive sentences. I need your help to achieve this. I hope you help and I appreciate it in advance.

Your Environment

  • Plugin version:
  • Platform: 0.9.0-beta.3
  • OS version: Android 9
  • Device manufacturer / model: Smasung S8
  • Cordova version (cordova -v): 9.0.0 ([email protected])
  • Cordova platform version (cordova platform ls): android 8.1.0
  • Plugin config : [if you mean config.xml, I didn't change anything in it. It is too long to append here]
  • Ionic Version (if using Ionic)

Expected Behavior

Based on my understanding that maybe is false #750, when a notification is scheduled for the future, it should be displayed even when the app is closed or killed.

Actual Behavior

the notifications are triggered when the app is open or is in the background, but when I close the app (I do this by clear all in the history) the notifications will not trigger and when I open the app again all of the scheduled ones triggered at once.

Steps to Reproduce

I just have a function for scheduling a notification. after that I close my app and wait. but nothing happen. If I don't close the app or if I put in background(by going to home), the notification will be shown.

scheduleDelayed () {
      console.log('scheduleDelayed called : ', Date())
      cordova.plugins.notification.local.schedule(
        [
          {
            id: this.countId,
            title: 'Scheduled with delay',
            text: `${this.countId} -- ${Date()}`,
            icon: 'res://balloons',
            smallIcon: 'res://balloons',
            trigger: { at: new Date(Date.now() + 10000) },
            silent: false,
            wakeup: true,
            foreground: true,
            priority: 1
          }
        ],
        event => {
          console.log('schedule callback')
          console.log('this.countId', this.countId)
          const notificationId = this.countId
          cordova.plugins.notification.local.isScheduled(
            notificationId,
            result => {
              console.log(`${notificationId} schedule result is : ${result}`)
            }
          )
          cordova.plugins.notification.local.hasPermission(function (granted) {
            console.log(`hasPermission : ${granted}`)
          })
          this.countId++
          console.log('scheduled')
        }
      )
    }

Context

I am trying to have an app to reminding a person with some sentences.

Debug logs

_Include iOS / Android logs_

  • Android: $ adb logcat ( I am not familiar with that and I don't know how should I get it, I am using vscode and my mobile phone)

JFYI:
I followed all the issues like #1836,#1682,#1483,#899 and I was not successful.
@katzer ,@julianlecalvez, @ferryjagers and others, you are all experts I hope you could help me. I am really in the critical situation and I don't have time to learn android and I can't :|

Most helpful comment

It's weird because your code seems ok.
Two points you can try, just to see if it works with the app closed :
. Use random or unique IDs because reusing the same IDs can be a problem if you never cancel it.
. Try with an hardcoded date, or with a delay more important (2 or 3 minutes). Sometimes, my notifications arrives 1 minute late.
. I would also try without any variables in the notification text (just in case)

If I still doesn't work, maybe you can take a look at the battery optimization system which delay notifications in certain case. There's 2 modes : App Standby and Doze.
Both are explained shortly and clearly in the article, but the interesting part is the command lines to force the device entering and leaving each modes : https://developer.android.com/training/monitoring-device-state/doze-standby

Hope it'll help

Julian

All 10 comments

Hi !

Did you try to check the permission before scheduling the notification ?

cordova.plugins.notification.local.hasPermission(function (granted) {
    console.log(`hasPermission : ${granted}`)
    if (granted) {
        cordova.plugins.notification.local.schedule(/* ... */)
    }
})

Hi !

Did you try to check the permission before scheduling the notification ?

cordova.plugins.notification.local.hasPermission(function (granted) {
    console.log(`hasPermission : ${granted}`)
    if (granted) {
        cordova.plugins.notification.local.schedule(/* ... */)
    }
})

Hi Julian. I changed my code based on your proposal and attached the results.

scheduleDelayed () {
      console.log('scheduleDelayed called : ', Date())

      // check permision before
      cordova.plugins.notification.local.hasPermission(function (granted) {
        console.log(`before : hasPermission : ${granted}`)
        if (granted) {
          cordova.plugins.notification.local.schedule(
            [
              {
                id: 2222,
                title: 'Scheduled with delay',
                text: `${this.countId} -- ${Date()}`,
                icon: 'res://balloons',
                smallIcon: 'res://balloons',
                trigger: { at: new Date(Date.now() + 10000) },
                silent: false,
                wakeup: true,
                foreground: true,
                priority: 1
              }
            ],
            event => {
              console.log('schedule callback')
              console.log('id', 2222)

              cordova.plugins.notification.local.isScheduled(
                2222,
                result => {
                  console.log(
                    `2222 schedule result is : ${result}`
                  )
                }
              )
              cordova.plugins.notification.local.hasPermission(function (
                granted
              ) {
                console.log(`after: hasPermission : ${granted}`)
              })
              this.countId++
              console.log('scheduled')
            }
          )
        }
      })
    }

result [copied from chrome DevTools console] :

scheduleDelayed called :  Mon Apr 20 2020 16:35:37 GMT+0200 (Central European Summer Time)
before : hasPermission : true
schedule callback
id 2222
scheduled
after: hasPermission : true
2222 schedule result is : true

still when I close the app, notification will not triggered but when I open the app again it will come up.

It's weird because your code seems ok.
Two points you can try, just to see if it works with the app closed :
. Use random or unique IDs because reusing the same IDs can be a problem if you never cancel it.
. Try with an hardcoded date, or with a delay more important (2 or 3 minutes). Sometimes, my notifications arrives 1 minute late.
. I would also try without any variables in the notification text (just in case)

If I still doesn't work, maybe you can take a look at the battery optimization system which delay notifications in certain case. There's 2 modes : App Standby and Doze.
Both are explained shortly and clearly in the article, but the interesting part is the command lines to force the device entering and leaving each modes : https://developer.android.com/training/monitoring-device-state/doze-standby

Hope it'll help

Julian

Hi Julian,
you are definitely an expert. The problem is for the battery optimization. I manually change the mode of my app and I got the notifications.
I can not go further due to lack of knowledge but it would be great and helpful if you could guide me how can I add my app to whitelist easily and without knowing the android stuff.
Can I do it by adding something to the manifest file?
again appreciate your support.

Hi @aefn !
Everything is explained in the article I shared in my previous post.
You can easily find a complementary cordova library to manage the battery optimization system.
Cheers

Just to confirm I can use this particular plugin for local notifications even when the app is killed correct? I've been recommended to use https://github.com/vasani-arpit/cordova-plugin-local-notifications however, I was wondering if I could just use this plugin instead for my attached use case.

Just to confirm I can use this particular plugin for local notifications even when the app is killed correct? I've been recommended to use https://github.com/vasani-arpit/cordova-plugin-local-notifications however, I was wondering if I could just use this plugin instead for my attached use case.

It should work, but if you encounter any problem like me, you need to handle it by disabling the battery optimization. The solution is proposed by @julianlecalvez. Check the previous comments.

Where in our project would we put it because wouldn鈥檛 you want this to run as a background process even when the app is closed? @aefn

Hi all
I have the same problem: I can schedule a lot of tasks to be triggered during the day, and als long as my app is in the foreground the local notifications are triggered. When the app is in the background nothing happens, and when I open the app the notifications come in.

For the moment I am working on Android. I have not tested it on iOS yet.

This is my environment:
Ionic:

Ionic CLI : 6.11.9 (C:\Users\hovin\AppData\Roaming\npm\node_modules\@ionic\cli)
Ionic Framework : ionic-angular 3.9.8
@ionic/app-scripts : 3.2.4

Cordova:

Cordova CLI : 10.0.0
Cordova Platforms : android 8.1.0, ios 5.1.1
Cordova Plugins : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 5.0.0, (and 23 other plugins)

Utility:

cordova-res : not installed
native-run : 0.2.8

System:

NodeJS : v10.18.0 (C:\Program Files\nodejs\node.exe)
npm : 6.10.1
OS : Windows 10

and these are my plugins:
cordova-plugin-advanced-http 2.1.1 "Advanced HTTP plugin"
cordova-plugin-background-mode 0.7.3 "BackgroundMode"
cordova-plugin-badge 0.8.8 "Badge"
cordova-plugin-camera 4.0.3 "Camera"
cordova-plugin-camera-preview 0.9.0 "cordova-plugin-camera-preview"
cordova-plugin-crop 0.3.1 "CropPlugin"
cordova-plugin-device 2.0.2 "Device"
cordova-plugin-file 6.0.1 "File"
cordova-plugin-file-transfer 1.7.1 "File Transfer"
cordova-plugin-filepath 1.5.5 "cordova-plugin-filepath"
cordova-plugin-inappbrowser 4.0.0 "InAppBrowser"
cordova-plugin-ionic-keyboard 2.1.3 "cordova-plugin-ionic-keyboard"
cordova-plugin-ionic-webview 5.0.0 "cordova-plugin-ionic-webview"
cordova-plugin-local-notification 0.9.0-beta.2 "LocalNotification"
cordova-plugin-market 1.2.0 "Market"
cordova-plugin-network-information 2.0.2 "Network Information"
cordova-plugin-screen-orientation 3.0.1 "Screen Orientation"
cordova-plugin-splashscreen 5.0.2 "Splashscreen"
cordova-plugin-statusbar 2.4.2 "StatusBar"
cordova-plugin-telerik-imagepicker 2.3.2 "ImagePicker"
cordova-plugin-tts 0.2.3 "TTS"
cordova-plugin-whitelist 1.3.3 "Whitelist"
cordova-plugin-wkwebview-engine 1.2.1 "Cordova WKWebView Engine"
cordova-sqlite-storage 3.2.1 "Cordova sqlite storage plugin - cordova-sqlite-storage plugin version"
es6-promise-plugin 4.2.2 "Promise"
phonegap-plugin-barcodescanner 8.1.0 "BarcodeScanner"

I am using the ionic-native plugin for local notifications because "cordova.plugins.notification.local." is not recognized.

The code I am using is:
updateNotifications(timeline) {
timeline.forEach( element =>{
let taskid = +element.taskid;
var taskdateArr = element.taskdate.split('-');
let time = new Date(+taskdateArr[0], +taskdateArr[1] - 1, +taskdateArr[2], +element.tasktime,0, 0, 0);
let time2 = new Date(time.getTime() - 15*60000)
console.info(time + " " + time2);
this.localNotifications.schedule(
{
id: taskid,
text: element.instruction,
title: element.tasktime + " " + this.hour + ": " + element.title,
trigger: { at:time2 },
}
);
});
}
The function receives an object with all messages for with notifications need to be scheduled, and every notification is triggered 15 minutes before tasktime.

In app.component.ts there is initial activity performed at platform.ready.
Ideally I want to solve this at platform.pause, but everything I put in there has a negative effect on the battery.

I have tried the Background Mode plugin, without result,

How can I have the scheduled notifications be triggered when the app is in the background?

Thanks for your input!

Was this page helpful?
0 / 5 - 0 ratings