How to save and update a state in a foreground service?

Viewed 27

I'm trying to make an app on wearOS 3.0 to monitor user exercises. I start from the base project you can find here : https://github.com/android/health-samples/tree/main/health-services/ExerciseSample

In this example, the method bindViewsToService() in ExerciseFragment listens to changes that come from the service.

I added other values in my viewModel and I want them to be saved when the application goes to background for whatever reason. As I use Android Compose, I used variables to keep the ui state and also to know which exercises I give to the user. If the app goes to background and the user comes back to my app, I need it to continue his/her current exercise and not restart everything.

My guess is that I need to save my state currently stored in my viewModel into the ExerciseService to be able to restore it when user comes back. I don't know how I can save it to the service when there is a change and then restore it if the app goes background.

First, is it what I should do? Otherwise, how should I save my state? Do you have ressources on this?

If my explanations aren't clear enough, feel free to ask any clarification!

1 Answers

I maybe found a solution. Not a clean one but it works. I create a data class which is parcelable and in which I put all variables I need to save when I go to background.

In the ExerciseService, I create a MutableStateFlow of this class. Then, every time the ExerciseFragment starts, I affect the mutableStateFlow of ExerciseService to one of my viewModel variable which is a MutableStateFlow of my data class. Then each time I update a variable belonging to the data class, I emit a value for this flow.

In the ExerciseService, I collect this flow and store my data class to a local variable in ExerciseService and called startForeground(NOTIFICATION_ID, buildNotification()). In buildNotification, I have a different argument for the pending Intent in which I put my parcelable data class.

I get it in ExerciseFragment in onCreateView with arguments?.getParcelable<DataClass>("state")?.let so if we have something we update the state.

It seems to work and I maybe have to adjust the values I store.

Do you have a better solution?

Related