How to keep android applications always be logged

2019-01-10 05:53发布

问题:

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?

回答1:

Use Shared Preference for auto login functionality. When users log in to your application, store the login status into sharedPreference and clear sharedPreference when users log out.

Check every time when the user enters into the application if user status from shared Preference is true then no need to log in again otherwise direct to the login page.

To achieve this first create a class, in this class you need to write all the function regarding the 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);
        editor.commit();
    }

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

Now in the main activity (The "Activity" where users will be redirected when logged in) first check

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

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



回答2:

You may add the following for logout operation in your SaveSharedPreference.java :

public static void clearUserName(Context ctx) 
{
    Editor editor = getSharedPreferences(ctx).edit();
    editor.clear(); //clear all stored data
    editor.commit();
}


回答3:

Always and whenever ... so this seems like an automated login approach. The application starts, the user doesn't have to login again once he has provided his authorization information. There are several ways to achieve this. The Facebook API e.g. provides mechanism for login without the use of a form element. So you would basically have to construct a view in which the user can provide his authorization information once, store them in SharedPreferences and login automatically the next time. Even if there is no such API - based login and you have to use a login - form provided, you sometimes could simulate the POST - request for logging in. This depends on the actual server - side implementation of that form. But remember: This is an security issue. So never store authorization credentials in clear text format. Don't rely on crypting it by a defined key in your application as this key maybe detected by reverse engineering your APK. Instead use many collective informations about the device and a key the user has to enter or is randomly generated and stored by the app.



回答4:

Using SharedPreferences is a way to save and retrieve key-value pair data in Android and also to keep the session throughout the entire application.

To work with SharedPreferences you need to take the following steps:

  1. Initialization of the share SharedPreferences interface by passing two arguments to the constructor (String and integer)

    // Sharedpref file name
    private static final String PREF_NAME = "PreName";
    // Shared pref mode
    int PRIVATE_MODE = 0;
    

    //Initialising the SharedPreferences SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode

  2. Using Editor interface and its methods to modify the SharedPreferences values and for storing data for future retrieval

    //Initialising the Editor
      Editor editor = pref.edit();
      editor.putBoolean("key_name", true); // Storing boolean - true/false
    

    editor.putString("key_name", "string value"); // Storing string editor.putInt("key_name", "int value"); // Storing integer editor.putFloat("key_name", "float value"); // Storing float editor.putLong("key_name", "long value"); // Storing long

    editor.commit(); // commit changes

  3. Retrieving Data

Data can be retrieved from saved preferences by calling getString() (For string) method. Remember this method should be called on Shared Preferences and not on Editor.

  // returns stored preference value
    // If value is not present return second param value - In this case null
    pref.getString("key_name", null); // getting String
    pref.getInt("key_name", null); // getting Integer
    pref.getFloat("key_name", null); // getting Float
    pref.getLong("key_name", null); // getting Long
    pref.getBoolean("key_name", null); // getting boolean
  1. Finally, clearing / deleting data like in the case of logout

If you want to delete from shared preferences you can call remove(“key_name”) to delete that particular value. If you want to delete all the data, call clear()

editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email

editor.commit(); // commit changes

Following will clear all the data from shared preferences
editor.clear();
editor.commit(); // commit changes

Please follow the link below to download a simple and straightforward example: http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/

I hope I haven't gone against the rules and regulations of the platform for sharing this link.

//This is my SharedPreferences Class 
  import java.util.HashMap;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SessionManager {
    // Shared Preferences
    SharedPreferences pref;
    // Editor for Shared preferences
    Editor editor;
    // Context
    Context _context;
    // Shared pref mode
    int PRIVATE_MODE = 0;
    // Sharedpref file name
    private static final String PREF_NAME = "AndroidHivePref";
    // All Shared Preferences Keys
    private static final String IS_LOGIN = "IsLoggedIn";
    // User name (make variable public to access from outside)
    public static final String KEY_NAME = "name";
    // Email address (make variable public to access from outside)
    public static final String KEY_EMAIL = "email";

    // Constructor
    @SuppressLint("CommitPrefEdits")
    public SessionManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    /**
     * Create login session
     */
    public void createLoginSession(String name, String email) {
        // Storing login value as TRUE
        editor.putBoolean(IS_LOGIN, true);
        // Storing name in pref
        editor.putString(KEY_NAME, name);
        // Storing email in pref
        editor.putString(KEY_EMAIL, email);
        // commit changes
        editor.commit();
    }

    /**
     * Check login method wil check user login status If false it will redirect
     * user to login page Else won't do anything
     */
    public void checkLogin() {
        // Check login status
        if (!this.isLoggedIn()) {
            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, MainActivity.class);
            // Closing all the Activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity
            _context.startActivity(i);
        }

    }

    /**
     * Get stored session data
     */
    public HashMap<String, String> getUserDetails() {
        HashMap<String, String> user = new HashMap<String, String>();
        // user name
        user.put(KEY_NAME, pref.getString(KEY_NAME, null));

        // user email id
        user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

        // return user
        return user;
    }

    /**
     * Clear session details
     */
    public void logoutUser() {
        // Clearing all data from Shared Preferences
        editor.clear();
        editor.commit();

        // After logout redirect user to Loing Activity
        Intent i = new Intent(_context, MainActivity.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity
        _context.startActivity(i);
    }

    /**
     * Quick check for login
     **/
    // Get Login State
    public boolean isLoggedIn() {
        return pref.getBoolean(IS_LOGIN, false);
    }
}


Finally, you will have to create an instance of this SessionManager class in the  onCreate method of your activity class and then call the createLoginSession for the session that will be used throughout the entire session



// Session Manager Class
    SessionManager session;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // Session Manager
        session = new SessionManager(getApplicationContext());
session.createLoginSession("Username", intentValue);
}

I hope it helps.



回答5:

after login when you press back call moveTaskToBack(true);

from this your application will be in background state. hope help



回答6:

Xamarin.Android port of Chirag Raval's and LINTUism's answers:

public class SharedPreference
{   
    static ISharedPreferences get(Context ctx)
    {
        return PreferenceManager.GetDefaultSharedPreferences(ctx);
    }

    public static void SetUsername(Context ctx, string username)
    {
        var editor = get(ctx).Edit();
        editor.PutString("USERNAME", username);
        editor.Commit();
    }

    public static string GetUsername(Context ctx)
    {
        return get(ctx).GetString("USERNAME", "");
    }

    public static void Clear(Context ctx)
    {
        var editor = get(ctx).Edit();
        editor.Clear();
        editor.Commit();
    }
}


回答7:

Firstly after successful login, save username/email and password in SharedPreferences.

Whenever application will start, execute code which will retrieve the username and password from sharedPrefernces and then these two values can be passed as a parameter to a method which will authenticate the user.