如何保持Android应用程序始终登录状态?

问题描述 投票:25回答:8

现在我正在尝试创建一个Android应用程序,假设它将是一些“X”概念没关系。所以我正在创建一个登录屏幕。如果我在移动设备上登录该应用程序,我想立即做的就是,每当我尝试访问该应用程序时,都应该始终登录。

例如我们的Facebook,g-mail和yahoo等..在我们的手机中

该怎么办?

android autologin
8个回答
60
投票

使用共享首选项进行自动登录功能。当用户登录到您的应用程序时,将登录状态存储到sharedPreference中,并在用户注销时清除sharedPreference。

如果用户进入应用程序,如果共享首选项中的用户状态为真,则无需再次登录,否则请直接登录到登录页面。

要实现这一点,首先要创建一个类,在这个类中,您需要编写有关共享首选项中的get和set值的所有函数。请看下面的代码。

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, "");
    }
}

现在在主要活动(“活动”中,用户将在登录时重定向)首先检查

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

在Login活动中,如果用户登录成功,则使用setUserName()函数设置UserName。


14
投票

您可以在SaveSharedPreference.java中为注销操作添加以下内容:

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

9
投票

始终和任何时候......所以这似乎是一种自动登录方式。应用程序启动后,用户在提供授权信息后无需再次登录。有几种方法可以实现这一目标。 Facebook API,例如提供登录机制而不使用表单元素。因此,您基本上必须构建一个视图,用户可以在其中提供一次授权信息,将它们存储在SharedPreferences中,并在下次自动登录。即使没有这样的基于API的登录,并且您必须使用提供的登录表单,您有时也可以模拟POST - 登录请求。这取决于该表单的实际服务器端实现。但请记住:这是一个安全问题。因此,永远不要以明文格式存储授权凭据。不要依赖于应用程序中定义的密钥来加密它,因为可以通过逆向工程APK来检测此密钥。而是使用关于设备的许多集体信息和用户必须输入的密钥或由应用程序随机生成和存储的密钥。


1
投票

使用SharedPreferences是一种在Android中保存和检索键值对数据的方法,也可以在整个应用程序中保持会话。

要使用SharedPreferences,您需要执行以下步骤:

  1. 通过将两个参数传递给构造函数来初始化共享SharedPreferences接口(String和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
  1. 使用Editor接口及其方法修改SharedPreferences值并存储数据以供将来检索
    //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
  1. 检索数据

可以通过调用getString()(For string)方法从保存的首选项中检索数据。请记住,此方法应在共享首选项上调用,而不是在编辑器上调用

        // 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. 最后,清除/删除数据,例如注销

如果要从共享首选项中删除,可以调用remove(“key_name”)来删除该特定值。如果要删除所有数据,请调用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

请点击以下链接下载一个简单明了的例子:http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/

我希望我没有违反平台的规则和条例来分享这个链接。

    //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
            checkLogin();
        }

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

最后,您必须在活动类的onCreate方法中创建此SessionManager类的实例,然后为将在整个会话中使用的会话调用createLoginSession

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

我希望它有所帮助。


0
投票

登录后按回拨moveTaskToBack(true);

从这个你的应用程序将处于后台状态。希望有所帮助


0
投票

Xamarin.Android港口的Chirag Raval和LINTUism的答案:

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();
    }
}

0
投票

只想发布另一个我认为对我来说最简单的解决方案:

SharedPreferences sharedpreferences;
int autoSave;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //"autoLogin" is a unique string to identify the instance of this shared preference
    sharedpreferences = getSharedPreferences("autoLogin", Context.MODE_PRIVATE);
    int j = sharedpreferences.getInt("key", 0);

    //Default is 0 so autologin is disabled
    if(j > 0){
        Intent activity = new Intent(getApplicationContext(), HomeActivity.class);
        startActivity(activity);
    }

}

    public void loginBtn(View view){
        //Once you click login, it will add 1 to shredPreference which will allow autologin in onCreate 
        autoSave = 1;
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putInt("key", autoSave);
        editor.apply();
}

现在让我们假设我在另一个活动中有一个退出按钮:

SharedPreferences sharedPreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    //Get that instance saved in the previous activity
    sharedPreferences = getSharedPreferences("autoLogin", Context.MODE_PRIVATE);
}


@Override
public void signOut(View view) {
    //Resetting value to 0 so autologin is disabled
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt("key", 0);
    editor.apply();

    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    startActivity(intent);

    }

-1
投票

首先成功登录后,在SharedPreferences中保存用户名/电子邮件和密码。

每当应用程序启动时,执行将从sharedPrefernces检索用户名和密码的代码,然后这两个值可作为参数传递给将对用户进行身份验证的方法。

© www.soinside.com 2019 - 2024. All rights reserved.