Android code by SharedPreferences to checks if the user is opening the app for the first time




The code is based  on SharedPreferences, if the user is opening the app for the first time the "firstTime" value is true, if not the value be false.

the code:

//declarer the var before the class name  
private Boolean firstTime = null;
..
..
if (firstTime == null) {
    SharedPreferences mPreferences = this.getSharedPreferences("first_time", Context.MODE_PRIVATE);
    firstTime = mPreferences.getBoolean("firstTime", true);
    if (firstTime) {
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putBoolean("firstTime", false);
        editor.commit();
    }
}
 
 
if (firstTime){
//the code you need to execute in the first opening the app
} 


you can use this code in a new class and add it like a fonction with return of firstTime like this:

private Boolean firstTime = null;
/**
* Checks if the user is opening the app for the first time. 
* Note that this method should be placed inside an activity and it can be called multiple times.
* @return boolean
*/
private boolean isFirstTime() {
if (firstTime == null) {
SharedPreferences mPreferences = this.getSharedPreferences("first_time", Context.MODE_PRIVATE);
firstTime = mPreferences.getBoolean("firstTime", true);
if (firstTime) { 
    SharedPreferences.Editor editor = mPreferences.edit();
    editor.putBoolean("firstTime", false);
    editor.commit();
}
}
return firstTime;
}


And don't forget to add:
import android.content.Context;
import android.content.SharedPreferences;


source: link
 
 

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel