How would I programmatically determine when an android device has rebooted (whether on its own, or user initiated) ?
If you happen to want to know if the device has been rebooted in-app, then you can use this code.
fun hasDeviceBeenRebooted(app: Application): Boolean {
val REBOOT_PREFS = "reboot prefs"
val REBOOT_KEY = "reboot key"
val sharedPrefs = app.getSharedPreferences(REBOOT_PREFS,
val expectedTimeSinceReboot = sharedPrefs.getLong(REBOOT_KEY, 0)
val actualTimeSinceReboot = System.currentTimeMillis() - SystemClock.elapsedRealtime() // Timestamp of rebooted time
sharedPrefs.edit().putLong(REBOOT_KEY, actualTimeSinceReboot).apply()
return actualTimeSinceReboot !in expectedTimeSinceReboot.minus(2000)..expectedTimeSinceReboot.plus(2000) // 2 Second error range.
}