I have an activity that i only want to run when the application is ran for the first time.
And never again. It is a facebook login activity. I only want to launch it once when the app is initially opened for the first time.
How do i go about doing this?
It is important to check that the first activity which opens when the app is launched is MainActivity. java (The activity which we want to appear only once). For this, open the AndroidManifest. xml file and ensure that we have the intent-filter tag inside the activity tag that should appear just once.
Activities will very often need to support the CATEGORY_DEFAULT so that they can be found by Context. startActivity(). So, CATEGORY_DEFAULT can appear number of times. Android does not grab whichever one appears first in the manifest but it starts with activity having CATEGORY_LAUNCHER.
Post the following code within your onCreate statement
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE) .getBoolean("isFirstRun", true); if (isFirstRun) { //show start activity startActivity(new Intent(MainActivity.this, FirstLaunch.class)); Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG) .show(); } getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit() .putBoolean("isFirstRun", false).commit();
Replace FirstLaunch.class with the class that you would like to launch
What I've generally done is add a check for a specific shared preference in the Main Activity
: if that shared preference is missing then launch the single-run Activity, otherwise continue with the main activity . When you launch the single run Activity create the shared preference so it gets skipped next time.
EDIT : In my onResume
for the default Activity I do this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false); if(!previouslyStarted) { SharedPreferences.Editor edit = prefs.edit(); edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE); edit.commit(); showHelp(); }
Basically I load the default shared preferences and look for the previously_started
boolean preference. If it hasn't been set I set it and then launch the help file. I use this to automatically show the help the first time the app is installed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With