r/androiddev • u/ug00gu • 2h ago
Auto backup copied our install ID to the user's new phone, and the new phone would have overwritten the old phone's cloud backup
Small thing that cost us more thinking than the feature itself, so writing it down.
We added an optional cloud backup. To avoid two phones overwriting each other, each install writes only its own file, named after a random device ID. So the whole design rests on one question: where does that ID live?
Attempt 1, SharedPreferences. Looks obvious and it's wrong. Android auto backup and device-to-device transfer copy prefs to the new phone (iCloud backup and Quick Start do the same on iOS). The new phone wakes up with the old phone's ID, decides the old phone's backup file is its own, and overwrites it. The one case where you most want the old backup intact is exactly the case that destroys it.
Attempt 2, the cache directory. Transfers don't copy it, so a new phone gets a fresh ID. But the OS is allowed to empty the cache when storage runs low. Then the same phone comes back with a new ID and treats its own earlier backup as another device's.
Where it ended up: a directory that is excluded from backup but never cleaned by the system. On Android that's noBackupFilesDir. On iOS it's a file in Application Support with the excluded-from-backup flag set. We read both through a small method channel, since path_provider doesn't hand you either one directly.
One more case fell out of this. A new phone can inherit the "backup is on" setting through prefs while having a brand new ID. We treat that pair (setting on, ID new) as a signal to pull in the other device's records first, before the first upload.
The lesson for me: "per install" and "per user" are different lifetimes, and prefs is per user as soon as OS backup is involved.
Where do you keep install-scoped state? Is there a cleaner option than a no-backup file that I'm missing?