r/androiddev • u/soaboz • Jul 31 '21
Discussion This is why your subclassed Application isn't always instantiated
A little over a year ago, I ran into a weird problem and I didn't understand what was happening. I had a service that was casting the application object from Service.getApplication() to my subclassed Application class (let's call it MyApp). However, I was seeing a crash caused by a ClassCastException because the object from Service.getApplication() could not be cast to MyApp. The user impact was low, but the volume was incredible (thousands of crashes per user). What was weird was that this crash was not appearing in Crashlytics, metrics showed nothing weird, and an investigation in the code showed that MyApp was setup properly in the manifest. However, Google Play Console was showing that this was a problem, and user reviews were mentioning constant crashing. So I did a quick sanity check, and obviously MyApp had to initialize before the app got to any of the services I had... So what was happening?
This one tag in the Android manifest:
<application
android:allowBackup=true
/>How was that tag causing this crash? The following image comes from the Android AutoBackup documentation (https://developer.android.com/guide/topics/data/autobackup#ImplementingBackupAgent)

So when Android enters this "Restricted" mode, basically the app is not running anything, which is understandable, as you don't want to modify data stored on the device while the app data is being backed up. So I did some testing and discovered something interesting: BroadcastReceivers and Services can still be started while this backup is in progress. Shit.
So that's pretty bad... anything that would normally start your app from external sources (Alarms, Jobs, FCM, etc) would still trigger while in this "Restricted" mode. That explains one, maybe two crashes per user, by why thousands of crashes per user?
Well, after more testing, some deep digging in the AOSP, beers to help numb the despair, and possibly some crying under my desk, I discovered that when an app crashes while in this "Restricted" mode, the next app start, regardless of how it is started (user initiated, intent, etc), restarted back in this "Restricted" mode. Any ContentProviders or library initialization in MyApp did not run. The app started up in a broken state. Naturally, the app crashed because of this. Now, because the app was still in the "Restricted" mode when it crashed, that meant the next app start was going to be in this "Restricted" mode again, and thus, we had a vicious cycle of crashes.
How was this fixed?
<application
android:allowBackup=false
/>I just disabled the backup, and like magic, the crashes went away.
I hope that my story helps any other poor soul who is dealing with this maddening issue. If you happen to be dealing with it, know that I have file a bug ticket with Google over a year ago: https://issuetracker.google.com/issues/160946170
Edit:
TL;DR - The android:allowBackup=true tag can lead to a broken app state that can cause constant app crashes. If you are seeing ClassCastException crashes because of you casting the result of getApplication() to your subclass application, you probably should disable allowBackup.
Edit #2:
I made a re-telling of how I went about debugging this issue in this article, since a few were curious how I went from crash to allowBackup: https://medium.com/@pablobaxter/what-happened-to-my-subclass-android-application-924c91bafcac?source=friends_link&sk=5c57ceba870af9c604270f371a328c6a
3
u/alexblokh Aug 05 '21
Thanks man, now I can have piece https://stackoverflow.com/questions/46771288/cannot-cast-application-to-customapplication
1
u/soaboz Aug 05 '21
I've been where you were... I'm glad this provided insight and I'm hoping it also provided you with a fix. Please let me know if it did.
2
u/fuzzyachooobject Jul 31 '21
Like everyone else I loved your write up and you have helped your fellow devs in a great way.
I am actually looking to dive deep into AOSP, what would be your guidance for me?
You mentioned that it happened when broadcast receiver or service ran during backup. How were u even able to trigger the backup and also started the service at the same time
Again, Massive respect for ur find!
4
u/soaboz Jul 31 '21
Basically, I created an app with a broadcast receiver that was exposed to an external custom event and crashed the app each time it ran. Then I ran the app, killed the process, and used ADB to trigger the backup followed by a run of the broadcast reciever.
Info on testing backup: https://developer.android.com/guide/topics/data/testingbackup
Info on running receivers via ADB: https://developer.android.com/studio/command-line/adb#am
As for the backup investigation, it all started in ActivityThread.java, where I followed the code for the variable
restrictedBackupMode. This lead me to ActivityManagerService.java, which lead me even further to areas I don't even recall any more. But basically, theActivityManagerServicedidn't clear some flag when the app crashes in restricted mode, so when it begins the app process again, it still has it set as if it was restricted. It's been a while so I don't recall all the details.2
u/grolschie Jul 31 '21
Noob question here. If broadcast receivers can be started from an external source, couldn't you just do some checks in your broadcast receivers and exit them if the app is running in restricted mode or if your Activity isn't running?
3
u/soaboz Jul 31 '21
Not a noob question. From what I can tell, there's no way to check if we are in restricted mode. Even if there was one, we (as app developers) would have to put in checks in all recievers/services, but there are many 3rd party libraries that have their own recievers/services too. Also, what if an intent comes in with required data? It's now lost as well, unless you risk doing some IO work to store the data and retrieve it next app start, which then increases the risk of this crashing issue. Remember, if the app crashes once in restricted mode, it's basically FUBAR until the device restarts.
1
u/grolschie Jul 31 '21
Thanks. Besides disabling backup, I guess all one can do is check that one's own Activity/app is running properly in the externally launched broadest receivers, etc, and then decide what to do with that information. That should stop the crash, right?
2
u/soaboz Jul 31 '21
Supposedly, you can use the Key/Value backup as another option, but I haven't tried it to see if this issue still persists with that.
https://developer.android.com/guide/topics/data/keyvaluebackup
From the docs (https://developer.android.com/guide/topics/data/autobackup#ImplementingBackupAgent)
If you can't avoid those patterns, then consider implementing Key/Value backup or disabling backup entirely.
1
u/simon2k6 Jul 31 '21 edited Jul 31 '21
I was thinking a similar thing, but I think ultimately it depends on your app. It means you could miss some data in a broadcast?
If that was important, I wonder if the scenario could be checked for, and a "lite" capture process puts the broadcast in a queue. Queue data could be processed when the Application is available?
I think there are other options, but it would be interesting to know of an alternative place to synchronise in process (if it's not the Application instance)
Edit: I don't think BroadcastReceiver has a built in redelivery mechanism, so you could use WorkManager to capture a task + data to do later (assuming the WorkManager implementation does not require Application context.) It has a retry mechanism built-in
6
u/VasiliyZukanov Jul 31 '21
I wonder how this "feature" isn't widely known (the fact that BroadcastReceivers and Services can still be started while backing up)? Very few projects use this backup feature maybe?
TBH, I never even cared to read about it. Just set it to false always. Anyone found this feature useful in some way?
7
Jul 31 '21 edited Jul 31 '21
Well, it's very useful if you want backup of your app settings/data being made automatically by the system (if the user enabled backups in Android settings) to whatever backend on the device (usually Google's cloud but Samsung also has its own) and have it restored on subsequent installs (if the user enabled restore in Android settings). You just have to be extremely cautious in the implementation of the Backup agent, as you are in restricted mode. Especially beware of any class that get loaded and their static initializers that may make wrong assumptions in that mode. I've never seen these crashes mentioned by OP with my Backup Agent restore part mainly filtering out some restored Shared Preferences to remove prefs that should not be restored.
6
u/soaboz Jul 31 '21
The point of the BackUpAgent not running ContentProviders or subclassed Application is so that none of your code runs... just so happens that receivers and services can still be triggered. That is the bug.
2
Jul 31 '21
I've never seen it happening, though I'm not saying it isn't. I still does not understand how it can happen though as the running time of the Backup Agent for its backup or restore operation is very small. If the problem is that the app process is lingering afterwards, maybe killing it with
Process.killProcess(Process.myPid())after the backup/restore would be a workaround ?2
u/soaboz Jul 31 '21
It wasn't widespread. The number of users affected were low in my case. That might work, but if an FCM notification comes through as this is running, and before the code to kill the process, we get back to the same broken state. What I've seen is that this broken state doesn't restart the backup agent. It just runs normally, sans providers and custom application.
2
u/VasiliyZukanov Jul 31 '21
Thanks for the explanation. As I understand it, you say that it allows to restore settings if a user re-installs the app after uninstall.
In your specific case, do you think the app would malfunction in any way if you remove this backup mechanism from it, or it's just a "nice to have" courtesy for returning users?
4
Jul 31 '21 edited Jul 31 '21
It's nice to have not only for returning users, but for users that change devices or install the app on many devices, the latter being not so infrequent for my app.
1
7
u/juliocbcotta Jul 31 '21
Looking at the related issues I see something that might be related to some crashes that I have... Like... Using the Application.onCreate method to initialise singletons... Without running the method, my singletons are not initialised and I get crashes...
5
u/Izacus Developer Jul 31 '21
Anyone found this feature useful in some way?
I'm sure the users did before you messed up their backups by turning them off.
6
u/VasiliyZukanov Jul 31 '21
I usually assume that if anything needs to be backed up, then the best way to go about that is to use your own backend. Worked well so far. So, why do you say "messed up with their backups"? What are the implication for users if I turn this off?
6
u/grivos Jul 31 '21
The implication is that the preferences won't be backed up and restored automatically. Usually apps sync the user data and not the app preferences (such as "always use dark mode).
3
u/VasiliyZukanov Jul 31 '21
But this "restore" is only relevant if the user uninstalls the app and then re-installs it? Or there are other relevant flows as well?
If this is just for re-installs, then I'll probably keep setting this option to false in all situtations...
4
u/grivos Jul 31 '21
Right, it's only relevant for re-installations.
I agree with you. This backup mechanism is not worth its drawbacks.
31
u/jaytothefunk Developer Jul 31 '21
Thank you for sharing. Never used that feature but good to know about these edge cases. Happy coding.
7
48
u/itpgsi2 Jul 31 '21
Very obscure fact, thanks for sharing. I think this should be a Lint rule: if allowBackup is enabled, don't cast Application class within Service or BroadcastReceiver without checking.
1
u/houseband23 Jul 31 '21
Jeez, I'm curious what lead you to look at the backup tag... Mind sharing your debugging tricks?
5
u/soaboz Jul 31 '21
For this bug, lots of crying, beer, and sheer dumb luck.
Being serious and thinking back, I started looking into how a service could start before the Application was initialized. That was the only thing that made close to any sense. After a few weeks of poking around the docs and AOSP, I finally saw the note in the AutoBackup docs.
From there, I started doing a deeper investigation on how this could happen. Given that only the provider and application were mentioned, I became curious if services and receivers would also be prevented from running. After setting up the test, I saw that they weren't. So I did even more testing, and finally found the reproduction steps for this crash.
But yes, there was beer, tears, and luck involved.
1
u/soaboz Aug 09 '21
Made an article about this. Feel free to read: https://medium.com/@pablobaxter/what-happened-to-my-subclass-android-application-924c91bafcac?source=friends_link&sk=5c57ceba870af9c604270f371a328c6a
3
2
u/puppiadog Jul 31 '21
I had a similar bug when I upgraded to the newest Billing Library. No matter what I did, I would get an error thrown when trying to launch the purchase dialog. I ended up creating a brand new project and implemented the Billing Library in it which allowed me to narrow down to a single attribute in the application node of the Android manifest (tools:node=replace). Removing that fixed it.
1
1
u/lnkprk114 Jul 31 '21
Awesome write up! Also, ridiculous bug. I wish Android wasn't so full of these types of foot guns.
1
u/lunatikul36 Aug 01 '21
Same happened to me. Lots of crashes appearing as random. Last year I pot allownackupnflag to false and half of the crashes disappear. I can confirm the crashes are not appearing on crashlytics.
8
u/Dimezis Jul 31 '21 edited Jul 31 '21
Oh man, apparently I had many crashes because of this too, and I had some wildest theories on why it could happen. Thanks for sharing, I finally can fix it now!
Edit: However, the docs say the main activity is not instantiated, which for me doesn't seem to be the case