Andorid - Open Activity only once

1

How do I make an Activity open only the first time the app is initialized?

    
asked by anonymous 05.05.2018 / 12:10

2 answers

2

First, conceptually the first time use of an application, if the control is offline, it is done directly by the application itself, ie you need to do this yourself.

You can do this in several ways. The simplest is to use Shared Preferences.

For example, before you can initialize the Activity you can check for a certain value. See:

//obter SharedPreferences
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
//chave de checagem
String isnew = prefs.getString("primeira_vez", null);
if (isnew != null) {
  String name = prefs.getString("name", "Não é a primeira vez");
  int idName = prefs.getInt("idName", 0); //0 is the default value.
} else {
  //... inicialize a atividade
  //... altera o valor de "primeira_vez" para "usado"
}
    
05.05.2018 / 12:44
0

You can create in Main , a flag in SharedPreferences , and check it every time the app starts. If the flag has false , it opens the desired activity and changes to true .

I did not find here a project I had done, but I found a HERE .

Example:

public class Splash extends Activity {

    SharedPreferences sharedpreferences;
    boolean splash;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        sharedpreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
        splash = sharedpreferences.getBoolean("Splash", false);
        if (splash == true) {
            Intent mainIntent = new Intent(Splash.this, MainActivity.class);
            startActivity(mainIntent);
        }
        else
        {
            setContentView(R.layout.splash);

            //animation
            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            Animation alpha = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.fade_in);

            imageView.startAnimation(alpha);

            alpha.setAnimationListener((new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    // TODO Start your activity here.
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putBoolean("Splash", true);
                    Intent mainIntent = new Intent(Splash.this, MainActivity.class);
                    Splash.this.startActivity(mainIntent);
                    Splash.this.finish();
                }
            }));
        }
    }
}
    
05.05.2018 / 12:41