Thursday, February 21, 2019

Check if app open the first time

Sometime we want to show a notification just one time when user first open app.
We will use SharedPreferences to do this.
Copy this lines to below setContentView.
final String MYPREFS = "mySave";
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
int number = mySharedPreferences.getInt("number", 1);
editor.putInt("number", 200);
editor.commit();
We use a variable name number to get saved value, we put the line int number = mySharedPreferences.getInt("number", 1); above the line editor.putInt("number", 200); so that in the first time app open, the value of number=1, next time number=200.
And we use if command to show text or do any thing you want.
if(number==1){
Toast.makeText(MainActivity.this, "This is the first open",
                               Toast.LENGTH_SHORT).show();

}

No comments:

Post a Comment