To achieve this with SharedPreferences
you might do something like this:
Insert the following in any Class you see more fit. Let's suppose you insert this in class Example
.
//Give your SharedPreferences file a name and save it to a static variable
public static final String PREFS_NAME = "MyPrefsFile";
Now, in the method that evaluates if the user successfully logs in, do the following. Notice the Example
class, you must change this to match your code.
//User has successfully logged in, save this information
// We need an Editor object to make preference changes.
SharedPreferences settings = getSharedPreferences(Example.PREFS_NAME, 0); // 0 - for private mode
SharedPreferences.Editor editor = settings.edit();
//Set "hasLoggedIn" to true
editor.putBoolean("hasLoggedIn", true);
// Commit the edits!
editor.commit();
Finally, when your application starts you can now evaluate if the user has already logged in or not. Still notice the Example
class that you must change.
SharedPreferences settings = getSharedPreferences(Example.PREFS_NAME, 0);
//Get "hasLoggedIn" value. If the value doesn't exist yet false is returned
boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);
if(hasLoggedIn)
{
//Go directly to main activity.
}
Hope this helps
EDIT: To prevent the user from using the back button to go back to the Login activity you have to finish()
the activity after starting a new one.
Following code taken from Forwarding.java | Android developers
// Here we start the next activity, and then call finish()
// so that our own will stop running and be removed from the
// history stack
Intent intent = new Intent();
intent.setClass(Example.this, ForwardTarget.class);
startActivity(intent);
Example.this.finish();
So, what you have to do in your code is to call the finish()
function on the Login activity, after calling startActivity()
.
See also: Removing an activity from the history stack
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…