Environment
Provide version numbers for the following components (information can be retrieved by running tns info in your project folder or by inspecting the package.json of the project):
Describe the bug
I am using an Android foreground service to keep the app running while in background with location tracking. On application exit event the service is stopped, notification successfully removed from status bar. The problem is that the app is still running - JS code is still executing. This does not happen if the service is stopped manually, e.g. by pushing a button, only then closing the app.
To Reproduce
I have attached a sample project.
Expected behavior
The app should be completely stopped by closing it.
Sample project
Sample project demonstrating the issue (location tracking not included). After closing the app by swiping it out, you can still see the output in console. If the "Stop foreground service" button is tapped before closing, it works as expected.
ns-test-android.zip
Hi @jnorkus,
Thank you for the provided sample project. I tested it several times on my side, however, I was not able to recreate the issue. Here are the steps, that I've followed:
tns run androidRegarding the case, try to reset the device/simulator, clear up the project(delete node_modules, platforms, hooks folders and package-lock.json file) and rebuild it via tns run android. If the issue persists, please provide more info about the steps, which you are following while building the app and some more info about the device or simulator, that you are using
Hi @tsonevn,
This is very odd. I can reproduce the issue on multiple devices (both emulator and a real one) and multiple apps (I created the sample app to isolate the issue).
I can still reproduce. I'm attaching a screen recording.
foreground-service-issue.mp4.zip
Hi @jnorkus,
I rechecked the project and was able to recreate the issue. Further investigation shows that the problem seems to be related to the project and the service, that is defined in it.
The Android documentation states that:
A started service must manage its own lifecycle. That is, the system doesn鈥檛 stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. The service must stop itself by calling stopSelf(), or another component can stop it by calling stopService().
Regarding that, for appropriate stopping the service when the app is closed, you need to add android:stopWithTask to true inside the AndroidManifest.xml file. For example:
<service
android:name="org.nativescript.nstestandroid.ForegroundService"
android:enabled="true"
android:stopWithTask="true"
android:exported="false" />
For more info check out this StackOverflow thread.
Thanks @tsonevn you're a rock star! Adding android:stopWithTask="true" solved the issue.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.