Full Source Code: https://github.com/varunon9/DynamicWallpaper/tree/always_running_service
Steps-
- 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
Hey, thanks for your detailed explanation. While I'm working on my endless map, I found out that doze mode is ruining the flow of foreground service that provides me the device's location. I considering to use this method but my problem that the
onDestroy()
execution is not guarantee. Or that I'm missing something. Can you introduce me to something new?