Full Source Code: https://github.com/varunon9/DynamicWallpaper/tree/always_running_service
- Create a Foreground Service (MyService.java)
- Create a Manifest registered Broadcast Receiver (MyReceiver.java) which will start your Foreground Service
- In
onDestroy
lifecycle of MyService, send a broadcast intent to MyReceiver - Launch the MyService on app start from MainActivity (see step 8)
- With above 4 steps, MyService will always get re-started when killed as long as
onDestroy
of Service gets called onDestroy
method of Service is not always guaranteed to be called and hence it might not get started again- To overcome this step, register a unique periodic Background Job via WorkManager which will restart MyService if not already started
- Register this UniquePeriodicWork (this will run every ~16 minutes) from MainActivity and it will also be responsible for the first launch of MyService
I resolved the issue by using LineageOS, a non-fvuked Android ROM/OS. You can have you service for years without the OS killing it. You have to have a compatible device (there are a lot, I bought one specifically to test it).
This is for you Google, and all the manufacturers:
![torvaldsnvidia-640x424](https://private-user-images.githubusercontent.com/73592852/324211923-fd9a41f3-8a51-4d20-a3b4-87e631ede8a4.jpg?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MjAzMjM0NzUsIm5iZiI6MTcyMDMyMzE3NSwicGF0aCI6Ii83MzU5Mjg1Mi8zMjQyMTE5MjMtZmQ5YTQxZjMtOGE1MS00ZDIwLWEzYjQtODdlNjMxZWRlOGE0LmpwZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNDA3MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjQwNzA3VDAzMzI1NVomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWJiZTAzMWI0MWFiMjA3ODNkY2RmYWNhMWRmZTFjZTA0MmQ1ZGE4NjUzM2QxMTYzN2Y0MjNmNWJkOWU2NDcxYmUmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JmFjdG9yX2lkPTAma2V5X2lkPTAmcmVwb19pZD0wIn0.qT1uExNJFu57tgucr4fDHqm3jD5AYYiSN6DqBqcXevA)