Making an activity appear only once, when the app is started

后端 未结 2 2023
暗喜
暗喜 2020-12-10 17:48

I have the following class, SplashActivity.java:

public class SplashScreen extends Activity{

    @Override
    protected void onCreate(Bund         


        
相关标签:
2条回答
  • 2020-12-10 17:51
     SharedPreferences pref = getSharedPreferences("ActivityPREF",    Context.MODE_PRIVATE);
         if(pref.getBoolean("activity_executed", false)){
    
    } else { 
       Intent intent = new Intent(this, TutorialOne.class);
        startActivity(intent);
        finish();
        Editor ed = pref.edit();
        ed.putBoolean("activity_executed", true);
        ed.commit();
    } 
    

    I think it should be like this.

    0 讨论(0)
  • 2020-12-10 18:17

    Add this code to your onCreate method

        SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
        if(pref.getBoolean("activity_executed", false)){
            Intent intent = new Intent(this, TutorialOne.class);
            startActivity(intent);
            finish();
        } else {
            Editor ed = pref.edit();
            ed.putBoolean("activity_executed", true);
            ed.commit();
        }
    

    SharedPreferences will be keep every time you execute the app unless you clean the data from Settings on your Android. The first time is going to get the value from a boolean (activity_executed) saved on such preferences (ActivityPREF).

    If it does not find any value it will return false, so we have to edit the preference and set the value to true. The next execution will launch the activity TutorialOne.

    finish() erases the current activity from the stack history, so no come back is possible using button back from TutorialOne.

    About your manifest, you can set this actitiy with

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter> 
    

    Every time the app is executed will launch this activity, but due to the true setted on the "activity_executed" is going to start a new activity with startActivity.

    0 讨论(0)
提交回复
热议问题