This question already has an answer here:
I am new to android development and and I want to setup some of application's attributes based on Application first run after installation. Is there any way to find that the application is running for the first time and then to setup its first run attributes?
The accepted answer doesn't differentiate between a first run and subsequent upgrades. Just setting a boolean in shared preferences will only tell you if it is the first run after the app is first installed. Later if you want to upgrade your app and make some changes on the first run of that upgrade, you won't be able to use that boolean any more because shared preferences are saved across upgrades.
This method uses shared preferences to save the version code rather than a boolean.
You would probably call this method from
onCreate
in your main activity so that it is checked every time your app starts.If you needed to, you could adjust the code to do specific things depending on what version the user previously had installed.
Idea came from this answer. These also helpful:
If you are having trouble getting the version code, see the following Q&A:
The following is an example of using SharedPreferences to achieve a 'forWhat' check.
The following is an example of using
SharedPreferences
to achieve a 'first run' check.When the code runs
prefs.getBoolean(...)
if there isn't aboolean
saved inSharedPreferences
with the key "firstrun" then that indicates the app has never been run (because nothing has ever saved a boolean with that key or the user has cleared the app data in order to force a 'first run' scenario). If this isn't the first run then the lineprefs.edit().putBoolean("firstrun", false).commit();
will have been executed and thereforeprefs.getBoolean("firstrun", true)
will actually return false as it overrides the default true provided as the second parameter.There's no reliable way to detect first run, as the shared preferences way is not always safe, the user can delete the shared preferences data from the settings! a better way is to use the answers here Is there a unique Android device ID? to get the device's unique ID and store it somewhere in your server, so whenever the user launches the app you request the server and check if it's there in your database or it is new.