Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code once after each boot on Android

Tags:

android

I need some initialization code to run exactly once, as soon as possible after each reboot, and then never again while the device is running.

  • Storing a SharedPreference that indicates the code has run isn't suitable because it survives reboot.
  • Relying on ACTION_SHUTDOWN to clear a SharedPreference value is not good enough because there are times when this wouldn't be sent (e.g. battery removed).
  • Using a static field to indicate the code has run isn't suitable because it would be reset if my app is killed.
  • Using some initialization code in my Application class isn't suitable because this would run again if my app is killed.
  • Receiving ACTION_BOOT_COMPLETED is almost good enough, but this can be preceded by other broadcasts my app responds to (such as ACTION_TIME_CHANGED) and can be fired after I have already launched my app from the launcher. I need this one-time setup code to run before then.
  • I can't rely on System.currentTimeMillis to calculate the boot time because clock changes would change the apparent boot time.

One option would be to get the last boot time of the device and see if this has changed (System.elapsedTime() is not good enough). I have tried executing commands like who -b and last reboot but permission is denied for both.

Another option is to store a setting/preference somewhere it will get reset ONLY if the device is rebooted, but not if my app is killed.

Is there another option, or a way to implement one of the above?

like image 660
Dave Morrissey Avatar asked Nov 16 '15 16:11

Dave Morrissey


People also ask

How do you call a method only once on Android?

You can do this, by using shared preferences . Store a value in shared preferences: SharedPreferences prefs = getPreferences(MODE_PRIVATE); SharedPreferences.

How do I run APK on startup?

To give this method a try, open Settings and go to the Application Manager. It should be in "Installed Apps" or "Applications," depending on your device. Select an app from the list of downloaded apps and turn the Autostart option on or off.

Can I run code in Android?

Sorry, is it possible to code on an Android phone? Alright, so yes, you can see the answer is what Yes, you can do programming in phone, you just need to install some app, which lets you do so you can also try the online compiler from Google Play Store as it supersedes the C++.


1 Answers

So You want to run you code at the System startup before any other app execution starts right?

If yes than here's the idea, Create a receiver for the ACTION_BOOT_COMPLETED and give the priority to 999 which is the highest so this will fire always at first when device gets starts.

like image 140
Hardik Chauhan Avatar answered Sep 21 '22 20:09

Hardik Chauhan