How is it possible to make an Activity appear only once to the user?

Asked

Viewed 1,006 times

3

My plan is the following: In my project I have 2 Activitys; these two activitys are only welcome to the user, so I would need it to appear only the first time the user starts the application.

I started studying Shared Preferences, but the materials I find around are just about how to Login/Password for the user. I couldn’t find any demonstration of how to accomplish my problem. Can I use Shared Preferences? In what way?

  • 1

    I don’t know if it’s duplicate, but you have three questions related to SharedPreferences who have already been answered: http://answall.com/questions/33677/comorsalvar-lista-de-objetos-em-android/33698#33698, http://answall.com/questions/25167/salvar-string-sharedpreference and http://answall.com/questions/34571/howto store and inform%C3%A7%C3%B5es-when-leaving-an-app-and-retrieve-no-pr%C3%B3next-use/34572#34572. Your question is how to make this logic at the beginning of the app or how to use SharedPreferences?

  • Actually it’s how to use Sharedpreferences at the beginning of my application. I don’t exactly have the "logic" of how to use for my goal. All the materials I found only teach you how to use Sharedpreferences for login systems, but no how to use in an Activity.

1 answer

2


It is no different from login systems as you found or as suggested. Assuming you have one Boasvindasactivity and a Mainactivity (the latter set as main in its file manifest), has something like this in the Mainactivity:

SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences(NOME_PREFS, Context.MODE_PRIVATE);

if (!sharedPrefs.getBoolean("primeiroAcesso", false)) {
    Intent intent = new Intent(this, BoasVindasActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    startActivity(intent);
    finish();

    return;
}

That is, if you entered the main and does not have the primeiroAcesso saved in user preferences, go to the welcome screen. Otherwise, in your Boasvindasactivity you save this option at some point to open the main:

SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("primeiroAcesso", true);
editor.commit();

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();

The same check at the beginning you can also do on Boasvindasactivity, to avoid opening this screen if you are already saved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.