简体   繁体   中英

Showing toast only at a third time, when we open the app on Android

I'm trying to create simple toast which will show only at the third time, when we open the app. Tried to google that question, but nothing found. Help me please.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Context context = getApplicationContext();
    CharSequence text = "Hello toast!";
    int duration = Toast.LENGTH_SHORT;

    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
}

}

So you need a counter the increments on starting the app and also gets checked if it reached the number 3. For this question I assume that MainActivity will be the first Activity that will be shown on startup and it is the only activity. Otherwise you must do some adjustments, when it is possible to navigate to another Activity and back.

private final String PREF_COUNTER_KEY = "PREF_COUNTER_KEY";

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   
   // load counter 
   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);  
   int startupCounter = prefs.getInt(PREF_COUNTER_KEY, 0);  
   startupCounter++;

   if(startupCounter > 2){
      Toast toast = Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT).show();
   }  
 
   // save incrementation
   SharedPreferences.Editor prefsEditor = prefs.edit();
   prefsEditor.putInt(PREF_COUNTER_KEY, counter);
   prefsEditor.apply();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM