How to Handle Process Death on Android

Mithat Sinan Sarı
Hipo
Published in
3 min readJan 22, 2022

--

Have you ever thought about what happens after we die? No one knows. But there is something we know: When an app dies, we lose state.

Unfortunately mobile devices don’t have unlimited battery or unlimited memory. That’s why when system needs more memory, it kills processes to make some room. So we should make sure that our apps are not effected by this process death. Although it is very important in terms of user experience, the solution is quite easy.

Let’s see an example; We have an application where we fetch user details when Get User button is clicked. This is the initial state of the application.

When we click on Get User button, we fetch user details from an API and update the UI.

We have a simple ViewModel that keeps the UI state;

And this is our UI state class, just a simple data class.

Since we keep the UI state reference in ViewModel, application will not lose state when we rotate the device or send the application to the background.

BUT if system kills the app when the application is on the background, user will see the initial/empty state when the app is reopened.

To simulate process death in Android Studio;
Go to Logcat -> Terminate Application

Or you can enable “Don’t keep activities” option in Developer Settings of the device.

So how do we prevent state loss in this situation? How do we save the state and how do we handle it? We use SavedStateHandle:

As soon as we update the UI state, we save it to the SavedStateHandle and when app is relaunched, we check if we have saved state or not. It is that simple!

There are some key points that we need to consider while applying this solution;

  • Data we save in SavedStateHandle must be Parcelable so that we can write it to the bundle.
  • The amount of data should be kept small because the system process needs to hold on to the provided data for as long as the user can ever navigate back to that activity. Android recommends that we should keep saved state to less than 50k of data.

You can check the sample application in the repo below:

--

--