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?
10 Answers
The following is an example of using SharedPreferences
to achieve a 'first run' check.
public class MyActivity extends Activity {
SharedPreferences prefs = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Perhaps set content view here
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
}
@Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firstrun", false).commit();
}
}
}
When the code runs prefs.getBoolean(...)
if there isn't a boolean
saved in SharedPreferences
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 line prefs.edit().putBoolean("firstrun", false).commit();
will have been executed and therefore prefs.getBoolean("firstrun", true)
will actually return false as it overrides the default true provided as the second parameter.
-
7@Squonk Can you please tell me the benefit of putting the code separately in both onCreate() and onResume()? – Ken Ratanachai S. Jun 27 '16 at 00:01
-
1Out of curiosity, why is the part where we use `putBoolean` in `onResume()`? Why cant this be in the `onCreate()` function? – James Heald Apr 23 '17 at 15:16
-
Despite I prefer [Suragch's answer](https://stackoverflow.com/a/30274315/370798), this works nice. Anyway, a minor remark is that the value of `firstrun`, when existent, will always be `false`. Despite this value doesn't really matter, it is more common and conventional to expect `false` as the default value of a boolean. If I used this approach I would use an `appHasRunBefore` preference in the following way `if (prefs.getBoolean("appHasRunBefore", false)){ /* This is not the first run */} else { /* Do first run stuff */ prefs.edit().putBoolean("appHasRunBefore", true).commit(); }` – Sam Jul 27 '17 at 18:48
-
2Hi what if the user clears the app data ? The shared preference data will be cleared right ? – ANUJ GUPTA Mar 07 '18 at 07:08
-
12This will not work if app has set android:allowBackup="true" (which is by default set to true) and sharedpreference is restored on install after uninstall while backup is enabled on device. So also make sure to set android:allowBackup="false" in AndroidManifest.xml. – Ashwin Nov 16 '18 at 03:24
-
Use `apply()` here instead of `commit()` because `commit()` will result into warning. eg. `prefs.edit().putBoolean("firstrun", false).apply();` – Vaibhav Oct 04 '19 at 04:15
-
1@KenRatanachaiS. My guess would be like this: app crashed when it's still at the "onCreate" stage, if you put all the codes inside onCreate, and if the crash happens, the next time when you run the app, it will not be its "firstrun", since the shared prefs code have already been executed inside onCreate. So put it separately inside the onResume method can make sure that the app is ready and everything shown on the screen, which makes it the "first run" to our perspective – marticztn May 30 '21 at 06:34
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.
import com.yourpackage.BuildConfig;
...
private void checkFirstRun() {
final String PREFS_NAME = "MyPrefsFile";
final String PREF_VERSION_CODE_KEY = "version_code";
final int DOESNT_EXIST = -1;
// Get current version code
int currentVersionCode = BuildConfig.VERSION_CODE;
// Get saved version code
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
int savedVersionCode = prefs.getInt(PREF_VERSION_CODE_KEY, DOESNT_EXIST);
// Check for first run or upgrade
if (currentVersionCode == savedVersionCode) {
// This is just a normal run
return;
} else if (savedVersionCode == DOESNT_EXIST) {
// TODO This is a new install (or the user cleared the shared preferences)
} else if (currentVersionCode > savedVersionCode) {
// TODO This is an upgrade
}
// Update the shared preferences with the current version code
prefs.edit().putInt(PREF_VERSION_CODE_KEY, currentVersionCode).apply();
}
You would probably call this method from onCreate
in your main activity so that it is checked every time your app starts.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkFirstRun();
}
private void checkFirstRun() {
// ...
}
}
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:
- How can you get the Manifest Version number from the App's (Layout) XML variables?
- User versionName value of AndroidManifest.xml in code
If you are having trouble getting the version code, see the following Q&A:

- 484,302
- 314
- 1,365
- 1,393
-
1+1 for considering the upgrade, but also for providing a more elegant solution than having a preference whose value doesn't really matter (since `firstrun`, if existent, would always be `false`). Also I personally think that expecting `true` as default value for a preference (when not present) is not so intuitive, and should be avoided when possible. – Sam Jul 27 '17 at 17:08
-
if u check the default value of share Preference Boolean as FALSE and you check if it value is False make it TRUE it will be remain true if u upgrade the app until u uninstall the app or clear cache – Nouman Shah Feb 17 '18 at 19:20
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;
import android.content.Context;
public class Util {
// ===========================================================
//
// ===========================================================
private static final String INSTALLATION = "INSTALLATION";
public synchronized static boolean isFirstLaunch(Context context) {
String sID = null;
boolean launchFlag = false;
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists()) {
launchFlag = true;
writeInstallationFile(installation);
}
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return launchFlag;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");// read only mode
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
> Usage (in class extending android.app.Activity)
Util.isFirstLaunch(this);

- 21,688
- 25
- 143
- 191
I'm not sure it's good way to check it. What about case when user uses button "clear data" from settings? SharedPreferences will be cleared and you catch "first run" again. And it's a problem. I guess it's better idea to use InstallReferrerReceiver.

- 1,391
- 18
- 18
-
You have rightly pointed out issue arising out of "clear data" which no one has addressed. How can your solution work when app is side-loaded? – v.j Feb 14 '18 at 01:49
There is no way to know that through the Android API. You have to store some flag by yourself and make it persist either in a SharedPreferenceEditor
or using a database.
If you want to base some licence related stuff on this flag, I suggest you use an obfuscated preference editor provided by the LVL library. It's simple and clean.
Regards, Stephane
The following is an example of using SharedPreferences to achieve a 'forWhat' check.
preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferencesEditor = preferences.edit();
public static boolean isFirstRun(String forWhat) {
if (preferences.getBoolean(forWhat, true)) {
preferencesEditor.putBoolean(forWhat, false).commit();
return true;
} else {
return false;
}
}

- 5,593
- 38
- 51
Just check for some preference with default value indicating that it's a first run. So if you get default value, do your initialization and set this preference to different value to indicate that the app is initialized already.

- 24,429
- 7
- 52
- 49
-
Hmm ok....I am new to android so I think I first have to study preferences...thanks anyways – Waneya Iqbal Aug 27 '11 at 21:57
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.

- 1
- 1

- 21
- 3
-
What if the user uninstalls and reinstalls? What about when the user upgrades? – Suragch May 16 '15 at 08:49
This might help you
public class FirstActivity extends Activity {
SharedPreferences sharedPreferences = null;
Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sharedPreferences = getSharedPreferences("com.myAppName", MODE_PRIVATE);
}
@Override
protected void onResume() {
super.onResume();
if (sharedPreferences.getBoolean("firstRun", true)) {
//You can perform anything over here. This will call only first time
editor = sharedPreferences.edit();
editor.putBoolean("firstRun", false)
editor.commit();
}
}
}

- 2,047
- 21
- 39
-
1Google says " Your app can listen to the system broadcast Intent.ACTION_PACKAGE_FIRST_LAUNCH to identify the app's first execution. " Here https://developer.android.com/google/play/installreferrer/library . But I struggle to do that as there seems to be no broadcasted intent - except when installed from Google Play - – Dan Alboteanu Jun 03 '19 at 14:09
SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// second argument is the default to use if the preference can't be found
Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);
if (!welcomeScreenShown) {
// here you can launch another activity if you like
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference
}
}

- 4,249
- 7
- 53
- 89

- 21
- 3