'How do create background service for Android in Ionic?

Tell me how in Ionic (I use Angular and Capacitor) to create function that, after building project on Android, will work even when application is closed (including after restarting the mobile phone)? It is required to make periodic POST requests to server and receive data (with open and closed application). If data on server is refreshed, I would like to display LocalNotifications from this background service.



Solution 1:[1]

Marco's answer is not correct. (I don't have 50 reputation to comment on his answer.. seriously!) Anyway, background-mode does not allow you to run a background service when the app is closed. It will work when you app is in the background, but close it and it will stop. At least that is my experience. I am trying to find an answer to run a service even when the app is closed. Hence I ended up on this thread. Would love to be proven wrong!

Solution 2:[2]

Why don't we try native?

  1. Try creating service with reference to native android documentation.

  2. I have added a service in ionic and it is working properly.

  3. What you have to do is open your your-project/android folder in Android studio.

4.Refer https://developer.android.com/guide/components/services for more details.

[Android Studio shows a different folder structure that a user can understand]

  1. Create a Service (Right click on app folder, new-->Service in Android Studio) inside the folder where MainActivity is present.

  2. Give the same package name of MainActivity at top of the new file.

  3. Then put the service code and instructions by how to work.

It will definitely work. (To Check services in MIUI, OPPO, enable AutoStart in app settings inside settings)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 George DW
Solution 2 mani kandan