Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

android - How to display login screen only one time?

I am creating a project where I have a login screen, which is used for user to login into the
Application. This login screen should only be visible the first time, so the user can fill it and log in, but when user opens the application at the second time the application must show main.activity. How to use Shared preference.

I don't understand how to do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...