Reputation: 11
I've created an Ionic App with Capacitor that's supposed to send the GPS coordinates to an API every minute. That works generally, but when it comes to working when the screen is locked it gets troublesome.
Now, I've included cordova-background-mode, as well as ForegroundService. Yet, it still stops after 5 minutes. I've also used
this.backgroundMode.disableWebViewOptimizations();
this.backgroundMode.disableBatteryOptimizations();
but to no avail.
I even manually deactivated Battery Optimisation in the settings.
What am I overlooking?
Upvotes: 1
Views: 1751
Reputation: 59
If anyone needs a solution, this works with android 10 + Capacitor + native backgrounde mode:
if (this.platform.is('android')) {
this.platform.ready().then(() => {
this.backgroundMode.enable();
this.backgroundMode.setEnabled(true);
this.backgroundMode.on('activate').subscribe(() => {
this.backgroundMode.disableWebViewOptimizations();
this.backgroundMode.disableBatteryOptimizations();
});
this.backgroundMode.disableBatteryOptimizations();
});
const timer = 3 * 60 * 1000; // three minutes
setInterval(() => {
this.backgroundMode.wakeUp();
}, timer);
}
Also add in manifest:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_SERVICE"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
Upvotes: 1