Search code examples
javascriptcordovabackgroundionic-frameworkbackground-mode

Cordova plugin background mode : onactivate is not working the first time (android)


I'm trying to use the background mode plugin in my ionic application but i'm encountering an issue.

I would like to do the same thing that what is shown in the readme of the github project with backgroundmode.onactivate. It would work perfectly fine if it was not working only from the second time I go to background.

If anyone has any idea about that issue, I'd be glad to hear about it :)

Sample from my code :

 $ionicPlatform.ready(function() {

document.addEventListener('deviceready', function () {
 // Android customization
 cordova.plugins.backgroundMode.setDefaults({ text:'Doing heavy tasks.'});
 // Enable background mode
 cordova.plugins.backgroundMode.enable();

 if(cordova.plugins.backgroundMode.isEnabled()){
     console.log('Hi, I am enabled. Signed : backgroundMode.');
   }

 // Called when background mode has been activated
 cordova.plugins.backgroundMode.onactivate = function () {
     setTimeout(function () {
         // Modify the currently displayed notification
         cordova.plugins.backgroundMode.configure({
             text:'Running in background for more than 5s now.'
         });
         console.log('Running in background for more than 5s now.');
     }, 5000);
 }
}, false);

Note : I do get the line Hi, I am enabled. Signed : backgroundMode. when my application is launched.


Solution

  • I changed the way of doing things to get round the problem. I did not manage to understand that bug though :(

    document.addEventListener("pause",onPause,false);
    
    function onPause() {
      $timeout(function() {
        console.log("Running in background for more than 5s now ...");
      }, 5000);
    
    };