I have a Broadcast Receiver which handles multiple events. I need it to do some special things for me at boot so I registered the android.intent.action.BOOT_COMPLETED
intent, which works fine. If the device is plugged in and is charging the android.intent.action.ACTION_POWER_CONNECTED
intent is fired before BOOT_COMPLETED
and does work before it's supposed to do stuff. (I'm using BOOT_COMPLETED
as a sort of initializer).
Is there a way to check if the BOOT_COMPLETED
event has been fired, so that I can run my initializing code in the event something gets fired too early?
When the BOOT_COMPLETED
is fired, you need to set a flag in your SharedPreferences as "true".
So, now if your ACTION_POWER_CONNECTED
gets fired before the BOOT_COMPLETED
then you need to check the value of the flag from the SharedPreferences.
If the value is still false, that means that the BOOT_COMPLETED broadcast has not fired yet and you should not perform your actions.
Note - Also remember to reset the flag in SharedPreferences every time.
I found another solution which is consistent. (I couldn't use another approach as I'm not the one who decides the approach sadly.)
Using the answer from this post: How to get Android system boot time I can save the last boot time in SharedPreferences (or some other storage). Once the boot time is different than the last I know that it's a fresh boot and can apply my initialisations etc.
This is the code I've ended up writing:
private boolean checkIfRebooted(Context context) {
SharedPreferences prefs = context.getSharedPreferences("package.name.class", Context.MODE_PRIVATE);
long savedUptime = prefs.getLong("timestamp", 0);
long currentUptime = System.currentTimeMillis() - SystemClock.elapsedRealtime();
// Giving it a threshold of 10ms since the calculation may be off by one sometimes.
if (Math.abs(currentUptime - savedUptime) < 10)
return false;
prefs.edit().putLong("timestamp", currentUptime).apply();
return true;
}
You could use the kernel boot id from /proc/sys/kernel/random/boot_id. When the code receives BOOT_COMPLETED, store the boot_id in the shared preference. After that it is simple. If the boot_id from /proc is equal to the shared preference, then BOOT_COMPLETED has been handled. Otherwise, not yet.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.