Android, how to determine if a reboot occurred?

前端 未结 4 1695
慢半拍i
慢半拍i 2021-01-14 09:33

How would I programmatically determine when an android device has rebooted (whether on its own, or user initiated) ?

4条回答
  •  伪装坚强ぢ
    2021-01-14 10:02

    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.
    }
    

提交回复
热议问题