ANDROID_ID after reinstall: a per-install id
I keyed a coin ledger by a random id, then by ANDROID_ID. A backup broke the first and a reinstall broke the second. What I use now, and how I checked it.
Contents
ASMR Logo Craft Block keeps its coins in a ledger with one entry per device, and the entries
are merged through the player's cloud save. That design stands on one assumption: an entry's
key is never reused by an install whose storage started over. I picked the key twice and got
it wrong both times, in opposite directions. The first id was carried over by a backup. The
second, ANDROID_ID, stays the same after a reinstall — and a reinstall is exactly when the
key has to change.
The short answer, if that is what you came for: a random UUID, written once to the app's no-backup folder on Android and to a file excluded from backup on iOS. The rest of this post is the two wrong answers, because each one looked right when I chose it.
Why the key matters
A balance cannot be merged. Two phones that both start at 100 coins, where one earns 50 and the other spends 30, give you 150 and 70, and no rule picks the right answer (120) out of those two numbers. So the wallet does not store a balance at all. Each device counts what it ever earned and spent, the counts only grow, and the balance is the sum over every entry:
ledger: {
<device A>: { coinsEarned: 500, coinsSpent: 400 },
<device B>: { coinsEarned: 60, coinsSpent: 0 },
}
Two copies of that merge by taking the larger value of each count, entry by entry. Since a count only ever grows on its own device, the larger value is always the newer one, and nothing is lost or counted twice.
Unless two installs write to the same entry. Then "the larger value" is just whichever install counted further, and the other install's history is gone. Every bug below is a version of that.
Wrong answer one: a random id in app storage
The first version made a random UUID the first time the wallet was created and saved it inside the wallet, in Capacitor's Preferences. New install, new id. That held until a bug-hunting pass with Claude Code asked what Android Auto Backup does to it.
The manifest had android:allowBackup="true" and no backup rules. Android's Auto Backup page
says shared preferences are included by default, and Capacitor's Preferences plugin writes to
shared preferences. So a player who sets up a new phone from a backup gets the old phone's
wallet, old id included. If both phones are still in use on one account, they write the same
ledger entry, and the merge throws one phone's history away.
The repro simulated two devices restored to the same id. It failed the way the arithmetic says it should:
× keeps what both devices earned → expected 125 to be 150
× keeps what both devices spent (nothing spent comes back) → expected 480 to be 420
✓ control: two devices with their own ids keep both
Lost earnings on one side, spent coins coming back on the other. I did not run an actual backup restore onto a second phone; the test stands in for it, and the inclusion of shared preferences comes from Android's documentation, not from a device.
Wrong answer two: ANDROID_ID
The fix looked obvious: use an id the platform owns, so no backup can carry it.
@capacitor/device has Device.getId(), which returns ANDROID_ID on Android and
identifierForVendor on iOS. Neither is part of the app's data, so neither is restored onto a
new phone. I switched the wallet to it and the backup repro went green.
The next round found what that did to a reinstall. Android's reference for ANDROID_ID says
that on Android 8.0 and higher the value is "unique to each combination of app-signing key,
user, and device", and that it "may change if a factory reset is performed on the device or if
an APK signing key changes." Those are the only two events listed. An uninstall is not one of
them, and neither is "Clear data". Same phone, same signing key: same id, every install.
So a reinstalled game started its ledger entry at zero under a key the cloud save already held with higher counts. Whatever the player earned before the first successful sync was then merged away, because the cloud's count was larger:
cloud: ledger[A] = { coinsEarned: 500, ... }
phone: ledger[A] = { coinsEarned: 10, ... } // fresh install, login gift claimed
merge: max(10, 500) = 500 // the 10 coins are gone
The repro covered four ways in, and the old random id as a control:
× the login gift claimed before the first sync is paid → expected 940 to be 950
× a level reward earned before the first sync is kept → expected 940 to be 965
× days of play while the silent sign-in failed: all of it vanishes → expected 940 to be 1440
× Auto Backup restores an older wallet onto the same phone → expected 940 to be 965
✓ control: random id per install (pre-round-2) keeps the reward
✓ a coin pack bought before the first sync is kept
The third line is the bad one. If the silent sign-in fails at launch, the first sync can be days away, and every coin earned in between disappears the moment it lands. Store purchases were safe only because each one already has its own ledger entry, keyed by its transaction id.
iOS has the same hole, smaller. Apple documents that identifierForVendor changes only when
the user deletes all of that vendor's apps from the device. If another app from the same
developer is still installed, a reinstall keeps the old value.
One thing I did not do is read ANDROID_ID on a device before and after a reinstall. The
behaviour is the documented one, and the repro proved what the documented behaviour does to
the ledger, using a fake that returned the same id twice. That was enough to act on. I mention
it so nobody reads this as a device measurement.
What the key actually has to do
Written down as requirements, which is what I should have done before picking either id:
| Event | Key must | Random id in Preferences | ANDROID_ID |
|---|---|---|---|
| Relaunch, app update | stay the same | yes | yes |
| Uninstall and reinstall | change | yes, unless a backup restores it | no |
| Clear data | change | yes | no |
| Backup restored onto a new phone | change | no | yes |
Each candidate fails one of those rows. The question that decides it is not "which id names this device" but "when does this install's storage start over", because that is exactly when the key has to be new.
The id that works
A random UUID, created by the app on first use, stored where uninstall and Clear data delete
it and where no backup reaches. On Android that place is Context.getNoBackupFilesDir().
Its reference says files there "will be excluded from automatic backup to remote storage",
and being inside the app's data directory, they go with an uninstall or a Clear data.
Capacitor has no plugin for this, so it became a small native plugin of its own. This is a simplified version of the Android side, not the shipped code:
@CapacitorPlugin(name = "InstallId")
class InstallIdPlugin : Plugin() {
@PluginMethod
fun get(call: PluginCall) {
val file = File(context.noBackupFilesDir, "install-id")
synchronized(this) {
val existing = file.takeIf { it.exists() }?.readText()?.trim()
val id = if (!existing.isNullOrEmpty()) existing else {
val fresh = UUID.randomUUID().toString()
// Write aside, then rename, so a crash never leaves half an id.
val tmp = File(file.parentFile, "install-id.tmp")
tmp.writeText(fresh)
if (!tmp.renameTo(file)) return call.reject("could not write the install id")
fresh
}
call.resolve(JSObject().put("id", id))
}
}
}
On iOS the file goes in Application Support with isExcludedFromBackup set on it. Two details
in that version. An atomic write replaces the file, so the flag is set after the write;
set before, it would sit on the file that just got replaced. And the file cannot be read
before the first unlock after a restart, so a read error is never answered with a new id
written over the old one: the JavaScript side returns an empty string and the wallet keeps
what it had.
Checking it on a device
The unit tests use a fake id, so they cannot tell you whether the native code works. The check that can is short: install, read the file, then do each of the events from the table.
export ANDROID_SERIAL=emulator-5556
PKG=com.example.game
readid() { adb shell run-as $PKG cat no_backup/install-id; }
adb install app.apk; launch; readid # install 1
adb shell am force-stop $PKG; launch; readid # relaunch
adb uninstall $PKG; adb install app.apk; readid # reinstall
adb shell pm clear $PKG; launch; readid # clear data
(launch is an am start plus a wait.) The result on an API 36 emulator, on a build with R8
on, with the values replaced:
install 1: 11111111-1111-4111-8111-111111111111
relaunch: 11111111-1111-4111-8111-111111111111
reinstall: 22222222-2222-4222-8222-222222222222
clear data: 33333333-3333-4333-8333-333333333333
INSTALL-ID OK
Two things went wrong on the way, both mine. The first script put the serial in a variable,
D="-s emulator-5556", and called adb $D shell .... zsh does not split an unquoted variable
into words, so every call failed with adb: -s requires an argument and the check printed
INSTALL-ID PROBLEM with every id empty. ANDROID_SERIAL avoids the problem entirely. The
second run got empty ids for a different reason: on a first launch the game waits for the
consent form before it loads the wallet, so nothing had asked for an id yet. Once Consent was
tapped, the file appeared.
On the iOS simulator the same sequence gave the same id across a relaunch and a new one after a
reinstall, and xattr on the file showed
com.apple.metadata:com_apple_backup_excludeItem: com.apple.MobileBackup, which is the
exclusion actually being on the file rather than just in the code.
Moving existing players over
Every player already had a wallet keyed by one of the old ids, so the switch has to happen once without changing anyone's balance. When the wallet loads and the install id differs from the one stored in it, the wallet takes the new id and starts a new entry. The old entry stays in the ledger, frozen: nothing writes to it again, but it still counts toward the sum, so the balance is the same before and after. A test covers that case: an existing random id switches once and keeps the balance.
The same rule handles a restore onto a new phone. The restored wallet carries the old phone's id, the new phone's install id is different, and the wallet moves to a fresh entry instead of writing into the old phone's.
What I did not test
- A real Auto Backup restore onto a second physical phone, and an iCloud restore on iOS. Both rest on unit tests that give two installs the same id.
ANDROID_IDread off a device across a reinstall. I relied on Android's reference for that.- Anything older than Android 8.0, where
ANDROID_IDfollows different rules.
The full round this came out of, along with the other regressions my own fixes caused, is in the bug-hunt write-up.
Takeaway
Before choosing a unique device id, write down the events after which it must change. For any
key that a merge relies on, that list is "whenever this install's storage starts over", and
neither a stored random id nor ANDROID_ID meets it on its own. A random id in the no-backup
folder does, and checking it takes a handful of adb commands.