Android, how to determine if a reboot occurred?
How would I programmatically determine when an android device has r开发者_如何学Cebooted (whether on its own, or user initiated) ?
Set up a BroadcastReceiver and register it in your manifest to respond to the android.intent.action.BOOT_COMPLETED system even. When the phone starts up the code in your broadcastreceiver's onReceive method will run. Make sure it either spawns a separate thread or takes less than 10 seconds, the OS will destroy your broadcastreceiver thread after 10 seconds.
This snippet starts an Application automatically after the android-os booted up.
in AndroidManifest.xml (application-part):
// You must hold the RECEIVE_BOOT_COMPLETED permission in order to receive this broadcast.
<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
[..]
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
[..]
In Java Class
public class BootUpReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
Use a BroadcastReceiver and listen to the broadcast Intent ACTION_BOOT_COMPLETED.
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, MODE_PRIVATE)
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.
}
精彩评论