Matias Nagore
Matias Nagore

Reputation: 97

SharedPreferences on first run are not saved when pressing Back Button

I have an Activity that only runs when the application is opened the first time. Every time I open the app again, this Activity won't run(and this is ok). The problem comes when I press the Back Button the first time I open my app. That Activity appears again and I don't want that to happen. How can I prevent this to happen?

This is my SharedPreferences code on my main activity's onCreate(the variable is created outside):

prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);

And this is the onResume method that let my app know if it's running for the first time:

`@Override
    protected void onResume() {
        super.onResume();
        if (prefs.getBoolean("firstrun", true)) {
            // Do first run stuff here then set 'firstrun' as false
            Intent myIntent = new Intent(MainActivity.this, StoryActivity.class);
            myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            MainActivity.this.startActivity(myIntent);
            prefs.edit().putBoolean("firstrun", false).commit();
        }
       }`

Upvotes: 0

Views: 746

Answers (2)

Submersed
Submersed

Reputation: 8870

Call finish() on your MainActivity before launching the Intent to direct to the next Activity. You can also declare noHistory=true in your AndroidManifest.xml to prevent the Activity from sticking around.

You can also use PackageManager.setComponentEnabledSetting(...) to completely change your "launcher" Activity once it's been viewed.

Upvotes: 1

Because your activity is finish after starActivity.Use this, check the working code: @Override protected void onResume() { super.onResume(); if (prefs.getBoolean("firstrun", true)) { prefs.edit().putBoolean("firstrun", false).commit(); // Do first run stuff here then set 'firstrun' as false Intent myIntent = new Intent(MainActivity.this, StoryActivity.class); myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(myIntent); } }

Upvotes: 0

Related Questions