Sunday, 24 March 2019

How to sync Toggle Button State with Foreground Service?

I have a Foreground Service which I start and stop with a Toggle Button in an Activity. To keep track if the Service is running or not I have used a variable which I store in SharedPreference.

Here is the flow

When user enable toggle button

startService()     start background work  
makeForeGround()              
bindService()      to get update

When user disable toggle button

unbindService()    to stop getting updates    
stopForeGround()          
stopService()      stop background work  

When user leaves the Activity

unbindService(); To stop getting the update. 
                 But the service is running for background work

When user reenters the Activity

if(Service is running)
Show toggle button state as enabled 
bindService() 

I have achieved all these.

Only problem I face is this.

Sometimes my Service gets killed by OS. In that case I have no way to update My SharedPreference variable. Hence no way to sync my Toggle button with Service.

How do I get notified that the service has got killed by OS. (Because onDestroy() is not getting called in this case)?
I have also gone through How to check if a service is running on Android? But sadly the solutions and methods provided are deprecated.

I got some workaround based on greeble31

Stll looking for a more general approach. Hence putting a bounty on it.



from How to sync Toggle Button State with Foreground Service?

No comments:

Post a Comment