Rohith Rohith - 1 year ago 424
Android Question

How to keep android applications always be logged in state?

Right now I am trying to create one Android application, assume it is going to be some "X" concept okay. So I am creating one login screen. What I want to do is at once if I logged in that application on my mobile, it should always be logged in whenever I try to access that application.

For example our Facebook, g-mail and yahoo etc.. in our mobile phones

What to do for that?

Answer Source

Use Shared Preference for that . When user logged into your application store login status into sharedPreference and clear sharedPreference when user click on logged Out.

Check every time when user enter into application if user status from shared Preference is true then no need to login otherwise move to login page.

To achieve that first create one class, in that class you need to write all the function regarding get and set value in the sharedpreference . Please look at this below Code.

public class SaveSharedPreference 
    static final String PREF_USER_NAME= "username";

    static SharedPreferences getSharedPreferences(Context ctx) {
        return PreferenceManager.getDefaultSharedPreferences(ctx);

    public static void setUserName(Context ctx, String userName) 
        Editor editor = getSharedPreferences(ctx).edit();
        editor.putString(PREF_USER_NAME, userName);

    public static String getUserName(Context ctx)
        return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");

Now in your main activity (Activity, that user will be redirected when logged in) first check

if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
     // call Login Activity
     // Stay at the current activity.

In Login activity if user login successful then set UserName using setUserName() function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download