I am currently developing an android app. I need to do something when the app is launched for the first time, i.e. the code only runs on the first time the program is launch
for kotlin
fun checkFirstRun() {
var prefs_name = "MyPrefsFile"
var pref_version_code_key = "version_code"
var doesnt_exist: Int = -1;
// Get current version code
var currentVersionCode = BuildConfig.VERSION_CODE
// Get saved version code
var prefs: SharedPreferences = getSharedPreferences(prefs_name, MODE_PRIVATE)
var savedVersionCode: Int = 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();
}
Hi guys I am doing something like this. And its works for me
create a Boolean field in shared preference.Default value is true {isFirstTime:true} after first time set it to false. Nothing can be simple and relaiable than this in android system.
I solved to determine whether the application is your first time or not , depending on whether it is an update.
private int appGetFirstTimeRun() {
//Check if App Start First Time
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
int appLastBuildVersion = appPreferences.getInt("app_first_time", 0);
//Log.d("appPreferences", "app_first_time = " + appLastBuildVersion);
if (appLastBuildVersion == appCurrentBuildVersion ) {
return 1; //ya has iniciado la appp alguna vez
} else {
appPreferences.edit().putInt("app_first_time",
appCurrentBuildVersion).apply();
if (appLastBuildVersion == 0) {
return 0; //es la primera vez
} else {
return 2; //es una versión nueva
}
}
}
Compute results:
My version for kotlin looks like the following:
PreferenceManager.getDefaultSharedPreferences(this).apply {
// Check if we need to display our OnboardingSupportFragment
if (!getBoolean("wasAppStartedPreviously", false)) {
// The user hasn't seen the OnboardingSupportFragment yet, so show it
startActivity(Intent(this@SplashScreenActivity, AppIntroActivity::class.java))
} else {
startActivity(Intent(this@SplashScreenActivity, MainActivity::class.java))
}
}