Issue
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?
Solution
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;
}
Answered By - JensV
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.