Search code examples
androidsessionpasswordstoken

How should I maintain session in android and what should I store(hashed passwords or something else) to maintain logged in state


I am working on an android application which requires login. I am yet to create the back end for the same and requires some suggestions on how to maintain the logged in state in the android app. I know we create sessions when it comes to web pages. I wanted to know how and what should I store in my android app so that my server knows that the subsequent requests after the login are coming from an authenticated device. Do we require some tokens or how does in work?


Solution

  • you can create a shared preference class to store your small data like user info and you can create a login session like this :-

    your preference class :-

    public class AppPrefrences {
    
        private static SharedPreferences mPrefs;
        private static SharedPreferences.Editor mPrefsEditor;
    
        public static boolean isUserLoggedOut(Context ctx) {
            mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
            return mPrefs.getBoolean("id_logged_in", true);
        }
    
        public static void setUserLoggedOut(Context ctx, Boolean value) {
            mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
            mPrefsEditor = mPrefs.edit();
            mPrefsEditor.putBoolean("id_logged_in", value);
            mPrefsEditor.commit();
        }
    }
    

    and when you logged in your app you can set the session of your logged in session like this where your login method seccess:-

    AppPreference.setUserLoggedOut(CompleteProfileActivity.this, false);
    

    and second time when you open the app you can set a check condition on your splash screen like this:-

    if (isUserLoggedOut(StartActivity.this)) {
                        startActivity(new Intent(StartActivity.this, LoginActivity.class));
                        finish();
                    } else {
                        startActivity(new Intent(StartActivity.this, MainActivity.class));
                        finish();
                    }