cordova-plugin-background-mode
cordova-plugin-background-mode copied to clipboard
Background mode not working on Android 8.0.0. Working on earlier versions
Test Environment:
- Android 8.0.0
- Phone: Galaxy S9+
- Samsung experience version 9.0
- Background Mode Version: cordova-plugin-background-mode 0.7.2 "BackgroundMode"
- Cordova Android Version: 6.4.0
- npm install output:
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
- Battery optimization disabled.
Symptoms:
- Phone sleeps, fails several minutes after working in background
- Notification is not showing up for backgroundmode
- Logging the output of isEnabled(), I get an empty result (at least console.log doesn't show anything).
I'm happy to do any debugging or additional information that might help.
same here Dont works in android 8
after 5 minutes of running the app in the background in android the app stops
after 5 minutes of running the app in the background in android the app stops
That's what I'm seeing as well. I'm also noticing that the notification isn't showing up as described in the plugin. I've tried a few of the forks that fix the notification issue for 8.0... they fix the notification issue, but I was still seeing what you are seeing.
Same problem with me too. It works for few mins after going to background and then stops until I go back to foreground. And I guess this issue is coming with Samsung devices more often. Working slightly better on Nexus and other devices.
what I found in my testing was that after disabling webview optimizations, the code worked correctly:
this.backgroundMode.on('activate', () => this.backgroundMode.disableWebviewOptimizations());
what I found in my testing was that after disabling webview optimizations, the code worked correctly:
this.backgroundMode.on('activate', () => this.backgroundMode.disableWebviewOptimizations());
What device and OS are you working with? I'm testing on a Galaxy S9+, 8.0. I'll give this a try tonight.
Nexus 6p, android 8.1.0
not working after +- 5 minutes Android 8.0
Same here I tried several times by Disabling Web View Optimisation.Its working better in Nexus but have a problem with Samsung. I guess Its because Samsung has custom OS which is customised Android OS.
what I found in my testing was that after disabling webview optimizations, the code worked correctly:
this.backgroundMode.on('activate', () => this.backgroundMode.disableWebviewOptimizations());
I tried this with my Samsung s9+, still fails to stay running. I send a ping every 30 seconds to the phone. At just under 4 minutes, the phone fails to reply to the ping. The ping timeout is set to about 40 seconds, so that means the phone app is stalling about 3 min 30 sec.
@katzer Does anyone managing this plugin anymore? This issue is really critical :(
Same problem with 8.0
Moto G, Sansung, Azuz etc., to andrond 7 Works well. LG stop more frequently. It only closes if you stress the system too much and call the camera, for example. It is still possible to circumvent predicting the user, and optimizing the maximum memory and CPU resource during persistent use, because it counts more in the decision of the system to encessr or not the application.
Moto X 8.0 With promises reported. In fact the service apparently is not really started, because neither the notification in my case works.
I came across this solution mixing power management, partial wake-locks, and background mode: https://forum.ionicframework.com/t/i-found-a-solution-for-some-regular-background-activity/27012
Seems to do the trick for the samsung s9...
@mpfurnari Do this trick works on all android?
@mpfurnari Do this trick works on all android?
Not being completely familiar with the underlying design of this backgroundmode plugin, I'm not certain that I'd call the wake-lock solution a trick. But, to answer your question, yes this works on Android. Specifically, I've tested this on a Samsung S9+ running Android 8.0. I'm only using this for Android. The backgroundmode plugin seems to work as-is for iOS.
i need keep open a websocket connection on background
i need keep open a websocket connection on background
That's exactly what's I'm doing...
I came across this solution mixing power management, partial wake-locks, and background mode: https://forum.ionicframework.com/t/i-found-a-solution-for-some-regular-background-activity/27012
Seems to do the trick for the samsung s9...
I've been running for hours with this solution... tested through phone calls, idle times, on a charger and off a charger. It seems to work. I'll be shipping with this solution. As I mentioned in my last comment, I'm setting up a WebSocket and need this to keep the other end informed that I'm still alive...
The mpfurnari solution has momentarily answered, even if it is not yet the ideal form, as I'm afraid the nescessity of it keeps the screen on and the application in the foreground :/ . The truth is that there is only one really correct and stable way to do this: with java through service. I'm trying to integrate a real service into android (outside the webview environment) natively developed in java via plugin. However all behavior and methods must be done directly in the plugin, in java. It is not possible in this case to create a universal method because there is no java / javascript interaction for this case. What seems to be a possible solution (still in testing) is to have the application call the service and receive data from it and vice versa. If the application is paused or closed, the service will continue. If the application reopens, it collects the updated data gutted by the service.
I'm working together with a java developer for this. If you succeed, step here.
Hugs!
The mpfurnari solution has momentarily answered, even if it is not yet the ideal form, as I'm afraid the nescessity of it keeps the screen on and the application in the foreground :/ . The truth is that there is only one really correct and stable way to do this: with java through service. I'm trying to integrate a real service into android (outside the webview environment) natively developed in java via plugin. However all behavior and methods must be done directly in the plugin, in java. It is not possible in this case to create a universal method because there is no java / javascript interaction for this case. What seems to be a possible solution (still in testing) is to have the application call the service and receive data from it and vice versa. If the application is paused or closed, the service will continue. If the application reopens, it collects the updated data gutted by the service.
I'm working together with a java developer for this. If you succeed, step here.
Hugs!
Agreed this solution is not ideal in that it requires 2 plugins to make it work. However, you might want to try the solution before making comments. This does not keep the screen on... it stays off as it should. It also does not keep the application in the "foreground"; In fact, the application doesn't come to the top unless called upon. The cost of this (in my solution and measured in battery consumption) appears to be close to the solution without the partial wake-lock. That said, I welcome a solution which provides an equivalent service layer that can easily be customized for a cordova app. Until then, I'm good with the partial wake-lock and the backgroundmode solution.
In my case, even with the two plugins, activating the window.powerManagement.dim mode, but putting the app in the background and stressing the system, the android paused the application (moto g5). If the app stays in the foreground, keeping the "dim" state on, it really does not stop. But I did not find a relation of the "dim" state with a supposed response of the system in killing or not the application when in the background. If the system needs resources, it will kill! Even because, from what I noticed, when you put the application in the background, this state is paused, only resuming if it is to the foreground again. But I pray that my ignorance is wrong.
I launched the solution for beta testers and I will monitor whether the report of problems with "normal" use decreases. I'm very fond of it, believe me!
I've been trying to get around this for over a year. As much as Cordova's own documentation does not recommend this and imposes this limitation, we try to stubbornly. I have combined all kinds of plugin and behavior. But I am more and more convinced that there really is nothing that can be done other than trying to develop a service through Plugin and with the methods directly in Java. Google Maps itself, for example, google native app, by not using a service, if put in background mode and stressing Android with the use of links and camera, it is dead, only maintain the state of form really stable in " acquire "(foreground and with the screen attached). Why would mine be any different?
Unfortunately, because of the limitations of the platform and the way it works, I do not see today how this so-called background services plugin can be developed and integrated with the webview JS, where it installs and submits to the javascript methods as a plugin any . It would be a kind of plugin itself, where your service is really built within the JAVA environment.
Maybe in a future version of Cordova? Do not know!
I am guided by this content: https://www.red-folder.com/blog/phonegap-android-background-service
Agreed, if the app is kept in the foreground with this solution, it doesn't behave as desired when the phone is locked etc. My workaround for this will be to force the app into the background. It works for my application, but maybe not for everyone.
I haven't tried stressing the system, but I could see this causing issues with even just basic performance. Again, for my application, I'm not so concerned about excessive stress scenario. (My typical use case is with the phone otherwise idled.)
I'm very open to move the necessary functions to a service layer. Specifically, I'm trying to run an MQTT connection (over websockets for now, but not required.) Ultimately, though, my service layer needs to interrupt the user with notifications and vibrations.... I imagine my needs are not so different than many others developing system solutions that are not just basic phone apps.
I'd be very interested in what you uncover!
For now, though, this will have to do....
Is this about using API 26 as target sdk in android code or running any targeted sdk code on android 8.0 or above devices?
Is this about using API 26 as target sdk in android code or running any targeted sdk code on android 8.0 or above devices?
As far as I know, the issue is specific to Android 8.0 running on Samsung. @luisvt reported a similar problem but different solution (above) running on a Nexus 6p 8.1.
Following up on the undesired lock-screen behavior, I've added the following to my initialization:
this.onPauseSubscription = this.platform.pause.subscribe(() => { this.backgroundmode.moveToBackground(); });
and added this to my cleanup:
this.onPauseSubscription.unsubscribe();
@mpfurnari , thanks so much for posting your fix. I have just implemented it in our test env and it appears to be working! This if the first time we've been able to get our app to last past 5 min since this error started happening with Android devices. I am going to test overnight and let you all know how it goes. I'm encouraged so far.
@aminholmes Hey Amin, Glad to hear that it's working for you! Matt
I was running on android P on oneplus 6. I have enabled the notification and it is being displayed on android 6.0 devices but not on P.
Hey Everyone,
I think this fork is working better. https://github.com/tushe/cordova-plugin-background-mode
Finally I was able to make it work for longer time.
I was running on android P on oneplus 6. I have enabled the notification and it is being displayed on android 6.0 devices but not on P.
I believe the tushe fork provided by @iverveinc corrects the notification issue. Still, with this fork, I was unable to run for long on a Samsung S9+ Android 8.0 with only the backgroundmode plugin. Failing that on tushe's fork, I tried the wake-lock solution with katzer's version of backgroundmode and I was able to run.
If someone can confirm that they are getting tushe's fork to work on a Samsung S9, I'll dig deeper...
@mpfurnari Hey, Would like to hear more about wake-lock solution in bit detail. I read above thread but not sure how to implement it. Can you help me with it.
@mpfurnari Noticing similar behaviour with Android 8.* on OnePlus 5T, Huawei and Sony models. I have implemented the wake-lock workaround, but still seeing the same type of behaviour (5 mins of background work). Going to spend some time today ensuring I have implemented the fix correctly, will update if I get anywhere.
@mpfurnari Hey, Would like to hear more about wake-lock solution in bit detail. I read above thread but not sure how to implement it. Can you help me with it.
I implemented this as an ionic provider. I've attempted to clean up my code for general use below, but I haven't verified this version. My version is very similar...
` import { Injectable } from '@angular/core'; import { BackgroundMode } from '@ionic-native/background-mode'; import { Platform } from 'ionic-angular'; import { PowerManagement } from '@ionic-native/power-management';
@Injectable() export class backgroundProvider {
static backgroundMode;
static isAndroid;
static powerManagement;
static platform;
static onPauseSubscription;
constructor(public _backgroundMode: BackgroundMode,
public _platform: Platform,
public _powerManagement: PowerManagement) {
backgroundProvider.backgroundMode = _backgroundMode;
backgroundProvider.platform = _platform
backgroundProvider.isAndroid = (backgroundProvider.platform.is('android'));
backgroundProvider.powerManagement = _powerManagement;
backgroundProvider.onPauseSubscription = undefined;
}
static paused() {
// push us to the background in this case so that we're not driving the screen...
backgroundProvider.backgroundMode.moveToBackground();
}
static enableBackground(forceBackgroundOnPause) {
console.log("Enabling Background Mode");
// https://forum.ionicframework.com/t/i-found-a-solution-for-some-regular-background-activity/27012
backgroundProvider.backgroundMode.setDefaults({
title: "My App Name",
text: "Working for you in the background",
icon: 'res://bgicon.png',
hidden: true
});
if (backgroundProvider.isAndroid) {
backgroundProvider.backgroundMode.enable();
if (forceBackgroundOnPause) {
backgroundProvider.onPauseSubscription = this.backgroundMode.platform.pause.subscribe(() => {
console.log('paused')
backgroundProvider.paused(); // when we pause, some apps are better left in the background so as to not keep the screen lit..
});
} else {
backgroundProvider.onPauseSubscription = undefined;
}
backgroundProvider.powerManagement.dim(function () {
console.log('enablebackground: Wakelock acquired');
backgroundProvider.powerManagement.setReleaseOnPause(false, function () {
console.log('enablebackground: setReleaseOnPause success');
}, function () {
console.log('enablebackground: setReleaseOnPause Failed to set');
});
}, function () {
console.log('enablebackground: Failed to acquire wakelock');
});
} else {
backgroundProvider.backgroundMode.enable();
}
}
static disableBackground() {
console.log("Disabling Background Mode");
if (backgroundProvider.isAndroid) {
if (backgroundProvider.onPauseSubscription != undefined) {
this.backgroundMode.onPauseSubscription.unsubscribe();
}
this.backgroundMode.bgmode.disable();
this.backgroundMode.powerManagement.release(function () {
console.log('disableBackground: Wakelock released');
}, function () {
console.log('disableBackground: Failed to release wakelock');
});
} else {
backgroundProvider.backgroundMode.disable();
}
}
} `
@mpfurnari I was wondering what problems you were having regarding when the phone is locked, which prompted you to force the application to the background, as I have not seen any problems with a Samsung Galaxy s8. I am also using a websocket that must stay open.
@gerard-d-kelly Did it work for you at the end? Try with setting the cordova.plugins.backgroundMode.disableWebViewOptimizations(); in the onactivate clause.
@mpfurnari I was wondering what problems you were having regarding when the phone is locked, which prompted you to force the application to the background, as I have not seen any problems with a Samsung Galaxy s8. I am also using a websocket that must stay open.
@Danthemanwenttojapan The phone screen would stay on, and the app would be in focus even though the screen was "locked". Forcing the app to the background eliminated this problem.
@Danthemanwenttojapan I spent 3-4 days trying different solutions including the disableWebViewOptimizations() and still couldn't get it working correctly. Android 8 seems to be very aggressive towards background processes even when writing natively. I have moved on to writing a native app that will run the "always on" background tasks I need and use my angular 6 as a front end embedded in a webview using cordova. Like I said, Android 8 is very agressive and I think this is the best solution in my case. Moving forward using another cross-platform angular to mobile framework might be better, one which allows easier access to native APIs and doesn't use webviews.
@mpfurnari That's interesting, I'm not getting the same phenomena with with a Cordova implementation (Not ionic), with Android 8, galaxy s8. I used all the solutions including backgroundMode.disableWebViewOptimizations();
@gerard-d-kelly It's working for me with all the solutions here together on a Android 8 with galaxy s8 (I must maintain a websocket). The plugin (I didn't look too carefully at the code), creates a foreground (or background) service, which should work. I don't have access to all the phones you mentioned, so was wondering if some Android implementation pauses foreground services. Try disabling doze mode for your app (Under battery management), and let me know what happened (If that is ok). I don't think this should be necessary for a foreground service.
i need keep open a websocket connection on background
Is this work-around to keep the App alive in background?
@gerard-d-kelly It's working for me with all the solutions here together on a Android 8 with galaxy s8 (I must maintain a websocket). The plugin (I didn't look too carefully at the code), creates a foreground (or background) service, which should work. I don't have access to all the phones you mentioned, so was wondering if some Android implementation pauses foreground services. Try disabling doze mode for your app (Under battery management), and let me know what happened (If that is ok). I don't think this should be necessary for a foreground service.
I have done this still App got close.
Did anyone tried this solution https://github.com/Red-Folder/bgs-core/wiki/Build-your-own-Background-Service
In silent mode the plugin will not display a notification - which is not the default. Be aware that Android recommends adding a notification otherwise the OS may pause the app.
cordova.plugins.backgroundMode.setDefaults({ silent: true });
decided to develop the service in native code as I have come to the conclusion the plugins for such type of requirement will not work. The App will close period, background service is something need, s to be out proc and not in-proc, the plugins here I guess works as in-proc and when the App closes the service will close bhoom over :( more here
Is there any solution for this? For what functions on Android 8+
I have the same issue with background mode. The app stops after 5 minutes if not power plug in. But it works well when I plug power cable in my android phone.
How to make phone always think that power cable is plugged even though it is not?
Try below, solved the crashing issue for me on Android 8+ https://github.com/katzer/cordova-plugin-background-mode/issues/393#issuecomment-449635095
Tested working on 8.0 on device, while 8.1 & 9.0 on emulator.
Hey Everyone,
I think this fork is working better. https://github.com/tushe/cordova-plugin-background-mode
Finally I was able to make it work for longer time.
Work on [email protected] thx...
@devi255 It doesn't work for me. still stop in 5 minutes.
thx
@n1705771 are you sure that you are using the latest git version of the plugin?
Working for Oreo & Pie.
Little tips for OnePlus users, you have to "lock" the app (the padlock in top right on app switcher)
Use this to keep app running when phone goes into (Android 6+) doze/standby mode.
https://github.com/thomas550i/cordova-plugin-doze-Optimize/
@ziyaddin Thanks. Do you mean latest "katzer" version or "tushe" version? I installed katzer version is: @ionic-native/background-mode": "^4.20.0"
Working for Oreo & Pie.
Little tips for OnePlus users, you have to "lock" the app (the padlock in top right on app switcher)
Locking the app isn't a good solution for most users...
Hey Everyone, I think this fork is working better. https://github.com/tushe/cordova-plugin-background-mode Finally I was able to make it work for longer time.
Work on [email protected] thx...
What version of Android did you test with? I ran a test with tushe's merged in changes and still had issues with the communications stopping after a few minutes. The app still runs in the background, but comms are stopped. I had to go back to using the wakelock to keep comms up. I guess I should update the original issue with this bit of information...
@mpfurnari Hey, Would like to hear more about wake-lock solution in bit detail. I read above thread but not sure how to implement it. Can you help me with it.
I implemented this as an ionic provider. I've attempted to clean up my code for general use below, but I haven't verified this version. My version is very similar...
` import { Injectable } from '@angular/core'; import { BackgroundMode } from '@ionic-native/background-mode'; import { Platform } from 'ionic-angular'; import { PowerManagement } from '@ionic-native/power-management';
@Injectable() export class backgroundProvider {
static backgroundMode; static isAndroid; static powerManagement; static platform; static onPauseSubscription; constructor(public _backgroundMode: BackgroundMode, public _platform: Platform, public _powerManagement: PowerManagement) { backgroundProvider.backgroundMode = _backgroundMode; backgroundProvider.platform = _platform backgroundProvider.isAndroid = (backgroundProvider.platform.is('android')); backgroundProvider.powerManagement = _powerManagement; backgroundProvider.onPauseSubscription = undefined; } static paused() { // push us to the background in this case so that we're not driving the screen... backgroundProvider.backgroundMode.moveToBackground(); } static enableBackground(forceBackgroundOnPause) { console.log("Enabling Background Mode"); // https://forum.ionicframework.com/t/i-found-a-solution-for-some-regular-background-activity/27012 backgroundProvider.backgroundMode.setDefaults({ title: "My App Name", text: "Working for you in the background", icon: 'res://bgicon.png', hidden: true }); if (backgroundProvider.isAndroid) { backgroundProvider.backgroundMode.enable(); if (forceBackgroundOnPause) { backgroundProvider.onPauseSubscription = this.backgroundMode.platform.pause.subscribe(() => { console.log('paused') backgroundProvider.paused(); // when we pause, some apps are better left in the background so as to not keep the screen lit.. }); } else { backgroundProvider.onPauseSubscription = undefined; } backgroundProvider.powerManagement.dim(function () { console.log('enablebackground: Wakelock acquired'); backgroundProvider.powerManagement.setReleaseOnPause(false, function () { console.log('enablebackground: setReleaseOnPause success'); }, function () { console.log('enablebackground: setReleaseOnPause Failed to set'); }); }, function () { console.log('enablebackground: Failed to acquire wakelock'); }); } else { backgroundProvider.backgroundMode.enable(); } } static disableBackground() { console.log("Disabling Background Mode"); if (backgroundProvider.isAndroid) { if (backgroundProvider.onPauseSubscription != undefined) { this.backgroundMode.onPauseSubscription.unsubscribe(); } this.backgroundMode.bgmode.disable(); this.backgroundMode.powerManagement.release(function () { console.log('disableBackground: Wakelock released'); }, function () { console.log('disableBackground: Failed to release wakelock'); }); } else { backgroundProvider.backgroundMode.disable(); } }
} `
I'm still on this solution...
@mpfurnari Does wakelock help background mode works longer time in your case? I added power management's wakelock in my app too, but it doesn't help.
@ziyaddin Thanks. Do you mean latest "katzer" version or "tushe" version?
@n1705771 I mean latest "katzer" version.
I installed katzer version is: @ionic-native/background-mode": "^4.20.0"
You have installed the ionic wrapper for cordova plugin. You need to install the latest "katzer" version of cordova plugin itself by this command:
ionic cordova plugin add https://github.com/katzer/cordova-plugin-background-mode.git
@mpfurnari Does wakelock help background mode works longer time in your case? I added power management's wakelock in my app too, but it doesn't help.
I've found I have to use the wakelock (in addition to using this plugin) to keep background communications going. I had tried a no-doze solution to get around issues caused by Android's doze feature (which seems to be the root of the communications stoppage), but those are a pain to manage from a user's perspective. From what I've tried, there's no easy way to turn off doze (ie disable battery optimization) without giving the user some complicated and device-specific instructions. The wakelock solution is far from elegant, but it works for my app without additional burden on my users. I'm not an authority on all this... I'm just a developer trying to keep my app working for my customers... Can you be more specific about what problems are you seeing?
@mpfurnari Thanks, I did the same thing in my ionic app, but it doesn't work well. My code is:
if (this.platform.is('android')){
this.backgroundMode.enable();
this.powerManagement.dim().then((value)=>{
console.log('enablebackground: Wakelock acquired');
this.powerManagement.setReleaseOnPause(false).then(()=>{
console.log('enablebackground: setReleaseOnPause success');
}).catch(()=>{
console.log('enablebackground: setReleaseOnPause Failed to set');
});
}).catch(()=>{
console.log('enablebackground: Failed to acquire wakelock');
});
this.backgroundMode.on("activate").subscribe(()=>{
this.backgroundMode.disableWebViewOptimizations();
console.log("background activate !!!!");
});
this.backgroundMode.on("deactivate").subscribe(()=>{
console.log("background deactivate xxxx ");
});
} else {
this.backgroundMode.enable();
}
It only works if device is plugged in power cable. I don't know why this happens...
It only works if device is plugged in power cable. I don't know why this happens...
It's working for me based on my comments on battery with no stoppage on Android 8.0 and 9.0. I went back and looked... Based on some searches I wound up with this repo for power management: https://github.com/boltex/cordova-plugin-powermanagement.git
Possible fix for some of you: https://github.com/katzer/cordova-plugin-background-mode/pull/435
@boedy I have changed the plugin.xml according to your commits, but it doesn't work for me. Is there any other code I need to modified?
No that should be it. To check if you did everything right, the configuration changes should also be added to the AndroidManifest in your android platform folder.
My PR Basically should solve the issue that the notification will not show in Android 9. If that was not the issue you were having then my PR probably wont fix it.
@boedy Thanks. Is there a plugin.xml file also in platforms/android?
I used kazer & tush fork, with and without powerManager and the best result that i got, is like @n1705771 said, it works only when the device is plugged in power cable. android 8
I used kazer & tush fork, with and without powerManager and the best result that i got, is like @n1705771 said, it works only when the device is plugged in power cable. android 8
I found I had to use this power management plugin: at.gofg.sportscomputer.powermanagement.
@mpfurnari Yes with it , and still not works,
"dependencies": {
"@angular/common": "^7.2.11",
"@angular/core": "^7.2.11",
"@angular/forms": "^7.2.11",
"@angular/http": "^7.2.11",
"@angular/platform-browser": "^7.2.11",
"@angular/platform-browser-dynamic": "^7.2.11",
"@angular/router": "^7.2.11",
"@ionic-native/background-mode": "^5.3.0",
"@ionic-native/core": "^5.3.0",
"@ionic-native/native-audio": "^5.3.0",
"@ionic-native/native-storage": "^5.3.0",
"@ionic-native/power-management": "^5.3.0",
"@ionic-native/splash-screen": "^5.3.0",
"@ionic-native/status-bar": "^5.3.0",
"@ionic/angular": "^4.1.2",
"cordova-android": "^7.1.4",
"cordova-plugin-background-mode": "^0.7.2",
"cordova-plugin-device": "^2.0.2",
"cordova-plugin-ionic-keyboard": "^2.1.3",
"cordova-plugin-ionic-webview": "^4.0.1",
"cordova-plugin-nativeaudio": "git+https://github.com/TheMoroccan09/cordova-plugin-nativeaudio.git",
"cordova-plugin-nativestorage": "^2.3.2",
"cordova-plugin-powermanagement-orig": "git+https://github.com/boltex/cordova-plugin-powermanagement.git",
"cordova-plugin-splashscreen": "^5.0.2",
"cordova-plugin-statusbar": "^2.4.2",
"cordova-plugin-whitelist": "^1.3.3",
"core-js": "^2.5.4",
"ng-circle-progress": "^1.4.0",
"rxjs": "~6.3.3",
"zone.js": "~0.8.29",
"at.gofg.sportscomputer.powermanagement": "https://github.com/boltex/cordova-plugin-powermanagement.git"
}
it works for you ?!!
import { PowerManagement } from '@ionic-native/power-management';
Thanks a Lot @mpfurnari for your explanations :-)
It is working to received messages one to one ...
this.socket.on('message'+id ...
I thought it was not working receiving from zone
If in the server I am doing
socket.join('zone' + zones[zo].id);
...
io.to('zone' + zonesAr[i]).emit('alert', ...
In the app
this.socket.on('alert',
and if I went back to the app connects again with the socket and show the notifications that I had not received before ....
But the problem was that I lunch the notification inside the modal and was receiving the colour and sound name from an api to set in the notification. And in background seems to slow the internet to get all this info ... When I set a notification with a default colour and sound (not getting from the api) it is working
I did:
cordova plugin add https://github.com/boltex/cordova-plugin-powermanagement.git
npm install @ionic-native/power-management --save
I needed to do this import because I am using Angular 6+
import { PowerManagement } from '@ionic-native/power-management/ngx';
And have also forget to add to app.module
providers: [
...
PowerManagement,
BackgroundMode,
...
@TheMoroccan09 Did you found a solution ?
@Entrecampos not yet
@TheMoroccan09 It is working now in my Xiaomi 7.1.1 and not working in my cliente Galaxy S10+ 9 You can check the solutions for your mobile clicking in the corresponding icon here https://dontkillmyapp.com
Working on emulator Galaxy 9 with https://github.com/irceline/aq-mobile-be/issues/94#issuecomment-464293865
and in the client :-)
@Entrecampos Thanks. for my Huawei Mate 10, I installed the latest plugin and added function:
this.backgroundMode.disableBatteryOptimizations();
After turning off the power save mode in battery setting, it starts to work as expected!
@Entrecampos I am curious if there is a way can automatically set the power save mode off when once the application is opened? or is it possible make the app working as expected in power save mode too?
@n1705771 In my Android 7.1, if I go to installed apps I can change settings of battery mode.
I installed this https://github.com/lkonzen-garupa/cordova-plugin-background-mode and the app ask user permission to use battery in background. https://github.com/katzer/cordova-plugin-background-mode/issues/430#issuecomment-484074971
My code is:
public enable_background_mode() {
const options = {
title: 'My Tittle', text: 'tt',
hidden: false, silent: true
};
this.plataform.ready().then(() => {
console.log('plataform ready');
cordova.plugins.backgroundMode.setDefaults(options);
cordova.plugins.backgroundMode.enable();
cordova.plugins.backgroundMode.on('enable', () => {
console.log('background mode activated !!!');
cordova.plugins.backgroundMode.disableWebViewOptimizations();
cordova.plugins.backgroundMode.disableBatteryOptimizations();
if (this.plataform.is('android')) { this.dimPM(); }
});
});
}
I really write
cordova.plugins.backgroundMode
, I am not using the ionic wrapper.
(So it's not necessary to do npm install --save @ionic-native/background-mode)
Because Ionic doesn't support yet this last plugin update.
To avoid type errors before declaring the class I do,
...
import { PowerManagement } from '@ionic-native/power-management/ngx';
declare var cordova: Cordova;
@Injectable({
providedIn: 'root'
})
And to work more than 4 minutes disconnected from battery source
public dimPM() {
if (this.powerManagement) {
console.log('powerManagement');
this.powerManagement.release().then(() => {
this.powerManagement.dim().then((v) => {
console.log('enablebackground: Wakelock acquired');
this.powerManagement.setReleaseOnPause(false).then(() => {
console.log('enablebackground: setReleaseOnPause success');
}).catch(() => {
console.log('enablebackground: setReleaseOnPause Failed to set');
});
}).catch((err) => {
console.log('enablebackground: Failed to acquire wakelock:', err);
});
});
}
}
@Entrecampos and @mpfurnari, thanks guys for your investigation and sharing your solution.
Just wondering:
Is the disableBatteryOptimizations() and REQUEST_IGNORE_BATTERY_OPTIMIZATION permissions sufficient to solve the problem?
Or BackgroundMode still needs to be used with the PowerManagement code to make a viable solution?
Hi @Entrecampos,
What I meant was whether you have tried to run test without PowerManagement code. ie: Just using disableBatteryOptimizations and REQUEST_IGNORE_BATTERY_OPTIMIZATION permissions.
Oh damn. I was hoping for solution with the need for another plugin.
Thanks @Entrecampos
Totally agree!!!! I really would love to see something better ! Fortunately google store accept it! https://play.google.com/store/apps/details?id=nl.gotop.nms
I have the same problem with audio streaming
I've seen this: https://altbeacon.github.io/android-beacon-library/foreground-service.html
so Android versions 8+ restrict services from running in the background to only 10 minutes after an app leaves the foreground.
... so the alternative is to use a foreground service: A foreground service is differs from regular Android background services in that it shows a persistent notification showing your app icon and configurable text.
... I'm looking for a Cordova Plugin that manage the foreground service if Android 8+ or background service if Android < 8.
Great @Entrecampos. Let us know your results, and what device you tested it on.
I tested it with Samsung S9+ (on Android 9), and it did not seem to work without the PowerManagement plugin. Not sure whether is it is a bug, the code cordova.plugins.backgroundMode.disableBatteryOptimizations();
does not actually disable battery optimisation on the S9+.
If your result is successful, it would be worthwhile for me to test again and if anyone else can also test on S9+ to verify my results.
Great @Entrecampos. Let us know your results, and what device you tested it on.
I tested it with Samsung S9+ (on Android 9), and it did not seem to work without the PowerManagement plugin. Not sure whether is it is a bug, the code
cordova.plugins.backgroundMode.disableBatteryOptimizations();
does not actually disable battery optimisation on the S9+.If your result is successful, it would be worthwhile for me to test again and if anyone else can also test on S9+ to verify my results.
I have android 7.1.1 Mi Max 2. My Client has Samsung Galaxy S10+.
With him the problem was that was crashing the app as soon as he went to background. But this https://github.com/lkonzen-garupa/cordova-plugin-background-mode solve it ...
Yes you a right @8bhsolutions ... If I comment
// if (this.plataform.is('android')) { this.dimPM(); }
:-( It is not working with 7.1.1 if the phone is not connected to charger or to laptop. After a while disconnects form the socket.
Seems to be broken on S9+ again. My app seems to run on average 6-8 hours, on a few occasions I have seen the log of over 20 hours. But it will always get killed.
Even with the PowerManagement plugin, and manually disabled battery optimisation, and calling disableBatteryOptimizations + disableWebViewOptimizations.
I've added more code and plugins to my app, so it has gotten a lot more complex. @Entrecampos @mpfurnari and anyone else experiencing same issue?
Seems to be broken on S9+ again. My app seems to run on average 6-8 hours, on a few occasions I have seen the log of over 20 hours. But it will always get killed.
Even with the PowerManagement plugin, and manually disabled battery optimisation, and calling disableBatteryOptimizations + disableWebViewOptimizations.
I've added more code and plugins to my app, so it has gotten a lot more complex. @Entrecampos @mpfurnari and anyone else experiencing same issue?
Did you activated "sticky" mode (ongoing) on localnotification plugin ?
@JuneTwooo Can you elaborate? The notification from the background mode plugin is shown. The user can't swipe it away. When the app dies, the notification is also gone.
@JuneTwooo Can you elaborate? The notification from the background mode plugin is shown. The user can't swipe it away. When the app dies, the notification is also gone.
Since Android 8, you have to use a persistent foreground notification. You can set it with https://github.com/katzer/cordova-plugin-local-notifications (with sticky: true) like that :
cordova.plugins.notification.local.schedule(
{
title: 'my app',
text: 'my text',
icon: 'file://icon.png',
smallIcon: 'res://icon.png',
sticky: true,
foreground: true
});
My app run till few week with that
Thanks @JuneTwooo That's interesting info.
I don't use the local notification plugin. I'll give it a go to see if it can keep my app alive.
@JuneTwooo . Can you clarify you setup to have you app run in the background?
Do you have background mode plugin notification showing ie: silent: false? Do you have PowerManagement plugin as well? And do you show another notification from local notification plugin?
@JuneTwooo . Can you clarify you setup to have you app run in the background?
Do you have background mode plugin notification showing ie: silent: false? Do you have PowerManagement plugin as well? And do you show another notification from local notification plugin?
I only use background mode plugin (with silent:false) and local notification plugin (sticky: true)
Thanks. Would that result in showing 2 notifications?
Thanks. Would that result in showing 2 notifications?
Yes, but maybe you can set silence:true on background mode plugin, i have not tested that.
Another thing, i have spent a lot of time before i know of the foreground service too keep app runing in background, i use a forked plugin for background mode : https://bitbucket.org/TheBosZ/cordova-plugin-run-in-background/src
Thanks for the clarification. I'll try with the forked plugin instead.
@JuneTwooo Unfortunately, that didn't work for me. My app is still getting killed on the Samsung S9+
The pattern seems to be that the app is killed 7 hours after last interaction. I have also created a new starter app, and added TheBosZ for + local notification. It follows the same pattern.
Maybe it is a new update on Samsung S9+? Can I ask what is the Android version and device you are able to run for weeks?
@JuneTwooo Unfortunately, that didn't work for me. My app is still getting killed on the Samsung S9+
The pattern seems to be that the app is killed 7 hours after last interaction. I have also created a new starter app, and added TheBosZ for + local notification. It follows the same pattern.
Maybe it is a new update on Samsung S9+? Can I ask what is the Android version and device you are able to run for weeks?
My app use websocket to stay connected from a server, i use 4 devices : 1 galaxy A5 2017 (oreo), OnePlus 5 (pie), a box tv android (x96 mini, nougat) and tablet galaxy tab S2 (oreo)
hmm. I have a firebase connection in background as well. I assume that is a websocket as well.
Maybe it's just a Samsung S9 thing. S6 on Android 7 has no problems with old code. Have been running for 4 days.
I can't get my app running after 7-9 mins with background geolocation updating via firebase on Android 8+ any one have an idea why is it so? if it is in screen locked my app.component.ts backgroundService() {
this.platform.ready().then(() => {
cordova.plugins.backgroundMode.enable();
cordova.plugins.backgroundMode.setDefaults({ silent: true });
cordova.plugins.backgroundMode.overrideBackButton();
this.powerManagement.acquire()
.then(res => {
console.log('Wakelock aquire')
})
.catch(res => console.log('Error Wakelock acquired'));
this.powerManagement.setReleaseOnPause(false).then(
res => console.log('setReleaseOnPause successfully'),
() => {
console.log('Failed to set');
}
);
this.platform.pause.subscribe(() => { cordova.plugins.backgroundMode.moveToBackground(); });
// 2) Now the app runs ins background but stays awake
cordova.plugins.backgroundMode.on('activate', () => {
cordova.plugins.backgroundMode.disableWebViewOptimizations();
cordova.plugins.backgroundMode.disableBatteryOptimizations();
//setInterval(() => {
var dt = new Date();
if (this.platform.is('android')) { this.dimPM(); }
if (dt.getHours() >= 9 && dt.getHours() < 24) {
if (localStorage.getItem("IsLoggedIn") == "true") {
this.LocationtrackerService.startBackgroundGeolocation()
}
}
else {
this.LocationtrackerService.stopTracking();
}
});
// 3) App is back to foreground
cordova.plugins.backgroundMode.on('deactivate', () => {
if (localStorage.getItem("IsLoggedIn") == "true") {
this.LocationtrackerService.stopTracking();
}
}
dimPM() { if (this.powerManagement) { console.log('powerManagement'); this.powerManagement.release().then(() => { this.powerManagement.dim().then((v) => { console.log('enablebackground: Wakelock acquired'); this.powerManagement.setReleaseOnPause(false).then(() => { console.log('enablebackground: setReleaseOnPause success'); }).catch(() => { console.log('enablebackground: setReleaseOnPause Failed to set'); }); }).catch((err) => { console.log('enablebackground: Failed to acquire wakelock:', err); }); }); } }
my provider tracker.ts startBackgroundGeolocation() {
this.backgroundGeolocation.configure({
desiredAccuracy: 10,
stationaryRadius: 5,
distanceFilter: 0,
// timeout: 20000,
startForeground: true,
locationProvider: 1,
interval: (120 * 1000), //2mins in millis
fastestInterval: (60 * 1000), // 1min in millis
//fastestInterval: 5000,
//activitiesInterval: 10000,
//saveBatteryOnBackground:false,
//enableHighAccuracy: true,
//debug: false, enable this hear sounds for background-geolocation life-cycle.
//stopOnTerminate: false // enable this to clear background location settings when the app terminates
})
var i = 0;
this.backgroundGeolocation.on('location', (location) => {
if (localStorage.getItem("IsLoggedIn") == "true") {
console.log('Background Watch');
this.zone.run(() => {
this.sendGPS(location);
});
i++
}
else {
console.log('Please Log in')
}
}, (err) => {
window.alert(err);
})
this.backgroundGeolocation.start();
let options = {
frequency: 3000,
enableHighAccuracy: true
};
setInterval(() => {
this.watch = this.geolocation.watchPosition();
this.subscription = this.watch.subscribe((data) => {
console.log('Foreground Watch');
this.sendGPS(data.coords);
});
}, 100000);
}
stopTracking() { this.backgroundGeolocation.stop(); let subscription = this.geolocation.watchPosition().subscribe( (position) => { }, ); subscription.unsubscribe(); }
sendGPS(location) {
//using firebase to push the data }
Try silent: false You can't have silent foreground services.
Try silent: false You can't have silent foreground services.
ok i will try n give it a go do u have any working solution of this?
i will be glad if u can help me out of this tried all the solution no luck app wont run more than 7-9 mins T
THanks