feat: sync whenever app goes to background on mobile

This commit is contained in:
Johannes Millan 2025-04-10 19:40:04 +02:00
parent e3d9a14a5d
commit df67f4a78b
4 changed files with 23 additions and 1 deletions

View file

@ -11,7 +11,7 @@ apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-app')
implementation project(':capacitor-filesystem')
implementation project(':capawesome-capacitor-background-task')
}

View file

@ -7,3 +7,6 @@ project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/
include ':capacitor-filesystem'
project(':capacitor-filesystem').projectDir = new File('../node_modules/@capacitor/filesystem/android')
include ':capawesome-capacitor-background-task'
project(':capawesome-capacitor-background-task').projectDir = new File('../node_modules/@capawesome/capacitor-background-task/android')

View file

@ -130,6 +130,7 @@
"@capacitor/cli": "^7.2.0",
"@capacitor/core": "^7.2.0",
"@capacitor/filesystem": "^7.0.1",
"@capawesome/capacitor-background-task": "^7.0.1",
"@csstools/stylelint-formatter-github": "^1.0.0",
"@electron/notarize": "^2.5.0",
"@fontsource/roboto": "^4.5.8",

View file

@ -53,6 +53,8 @@ import { AppComponent } from './app/app.component';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { ShortTime2Pipe } from './app/ui/pipes/short-time2.pipe';
import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
import { BackgroundTask } from '@capawesome/capacitor-background-task';
import { promiseTimeout } from './app/util/promise-timeout';
if (environment.production || environment.stage) {
enableProdMode();
@ -207,4 +209,20 @@ if (IS_ANDROID_WEB_VIEW) {
window.history.back();
}
});
CapacitorApp.addListener('appStateChange', async ({ isActive }) => {
if (isActive) {
return;
}
// The app state has been changed to inactive.
// Start the background task by calling `beforeExit`.
const taskId = await BackgroundTask.beforeExit(async () => {
// Run your code...
// Finish the background task as soon as everything is done.
console.log('Time window for completing sync started');
await promiseTimeout(20000);
console.log('Time window for completing sync ended. Closing app!');
BackgroundTask.finish({ taskId });
});
});
}