Project Context/Purpose: In a part of my Android project, the user can set their training time per repetition and rest, for example: "I want to run for 1 minute, rest for 30 seconds, and I want to do 3 repetitions of this." The app counts the 1 minute, triggers a sound alert indicating the rest time, and starts counting the 30 seconds.
However, this obviously only works if the app is open, and in this context, I need it to run in the background, as it is not possible to count the time difference from when the app is closed until it is opened again, since the user will not open the app during the run. I generated a Cordova export and added the "cordova-plugin-background-mode" plugin, configured it in the config, everything is set up, I even made this script to disable it as soon as the project opens, since I don't need it running in the background all the time, only at specific moments:
console.log("background-mode.js loaded");
document.addEventListener('deviceready', function () {
console.log("Cordova is ready");
cordova.plugins.backgroundMode.disableWebViewOptimizations();
cordova.plugins.backgroundMode.disableBatteryOptimizations();
cordova.plugins.backgroundMode.setDefaults({
title: 'App in Background',
text: 'Your app is running in the background',
icon: 'icon', // Icon name in the res/drawable folder
color: 'F14F4D', // Notification color
resume: true,
hidden: false,
bigText: false
});
cordova.plugins.backgroundMode.enable();
}, false);
And I created two functions to enable and disable it:
function enableBackgroundMode() {
console.log("Enabling background mode");
cordova.plugins.backgroundMode.enable();
}
function disableBackgroundMode() {
console.log("Disabling background mode");
cordova.plugins.backgroundMode.disable();
}
It is called when the user starts the run and disabled when they finish. I can see from the console log that it is running as it should, but whenever the phone locks the screen or the app goes into the background, the project pauses anyway. Is there any way to work around this?