I have been playing around with Android app development, particularly on how to retain UI values after configuration changes and minimizing the app to launch a different one.
To retain values after configuration changes, I use ViewModels.
And to retain values after minimizing the app, the following is supposed to do the trick:
1 2 3 4 5 6 7 8 9 |
override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt(KEY, number) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { binding.textView.text = savedInstanceState.getInt(KEY) } |
But in the phone where I test most of my apps, it doesn’t! Minimizing my app to play a YouTube video, open a mobile game, and watch a few TikTok videos for about 15 minutes, causes my app’s UI data to reset.
I installed the same app to another phone, a Samsung phone under the A Series. The user played a mobile game for several hours, and came back to my app to find all the previous UI values still intact!
I remember that when I was still working with the Squadzip team (still grateful to Roman for suggesting that I try to practice “mindfulness” — it works wonders for a hectic lifestyle!), that Huawei phones gave us the same kind of issue. Apparently, Huawei phones are quite aggressive at killing apps in the background to preserve battery life.
Options that I considered to prevent Huawei phone from killing my Android app in the background:
- Save UI data to SharedPreferences, on top of using Bundle to save and restore instance state (hesitatant to do this because I don’t really need to save UI data)
- Simply advise the user not to leave the app if they want their data to be retained (BAAAD IDEA!)
- Find some sort of “whitelist” in Huawei settings to exempt my app from being aggressively killed
The method I chose to prevent Huawei phone from killing my Android app:
For the current app I’m working on, I chose to change a setting in the Huawei phone because it’s the easiest. It shouldn’t be so hard to explain to app users either.
Instructions:
- Go to Settings
- Look for “Battery” and click on it
- Look for “App launch” and click on it
- Type the name of your app in the Search field.
- Turn off the “Manage automatically” setting
- Click OK on the prompt. (I chose to leave auto-launch, secondary launch, and run in background to keep my app alive.)
- The description below your app’s name should now be “Manage manually” instead of “Manage automatically.”