如何在Android登录/注销中管理会话?

时间:2017-05-30 07:40:35

标签: php android session

我正在创建一个用户登录和注销的应用程序,数据来自使用php web服务的mysql服务器,现在我想在用户登录时维护会话并在用户注销时销毁它,我正在使用

intent.putExtra("SESSION_ID", sessionId);

如何在注销时重置它 这会作为会话工作还是我必须做其他事情

4 个答案:

答案 0 :(得分:1)

您可以使用共享首选项设置或重置会话

用于保存会话到登录的共享首选项

SharedPreferences.Editor editor = getSharedPreferences(YOUR_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("session", sessionId);editor.apply();

用于在注销时重置会话到共享首选项

SharedPreferences.Editor editor = getSharedPreferences(YOUR_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("session", "0");editor.apply();

用于从首选项中检索数据

SharedPreferences prefs = getSharedPreferences(YOUR_PREFS_NAME, MODE_PRIVATE); 
String sessionData= prefs.getString("session", null); //SessionId that you saved in preference

答案 1 :(得分:0)

使用SharedPreferences来管理您的session

以下是一个例子:

1。创建一个名为SessionManager的类,如下所示:

public class SessionManager {

    // LogCat tag
    private static String TAG = SessionManager.class.getSimpleName();

    Context context;

    // Shared Preferences
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "TEST";

    private static final String KEY_IS_LOGGED_IN = "IS_LOGGED_IN";


    public SessionManager(Context context) {
        this.context = context;
        sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = sharedPreferences.edit();
    }

    public void setLogin(boolean isLoggedIn) {

        editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);

        // commit changes
        editor.commit();

        Log.d(TAG, "User login session modified!");
    }

    public boolean isLoggedIn() {
        return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
    }
}

2。使用session方法更新setLogin()状态。

<强> LOGIN:

SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(true);

<强> LOGOUT:

SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(false);

这是一篇关于Android Login and Registration with PHP, MySQL and SQLite的好教程。

希望这会有所帮助〜

答案 2 :(得分:0)

使用sharedPreferences可以更轻松地完成。创建一个sharedPreference变量并在注销时清除它。

SharedPreferences settings = getSharedPreference("filename", 0);
SharedPreferences. Editor editor = settings.edit();
editor.putString("varName",value);

稍后会话退出时

editor.clear();

答案 3 :(得分:0)

用于设置/登录

SharedPreferences pref=getApplicationContext.getSharedPreferences("Your PREF_NAME",Private_Mode);
SharedPreferences.Editor editor=pref.edit();
editor.putString("SESSION_ID", sessionId);
editor.commit();

退出

SharedPreferences pref=getApplicationContext.getSharedPreferences("Your PREF_NAME",Private_Mode);
SharedPreferences.Editor editor=pref.edit();
pref.edit().remove(KEY_CUSTOMER_ID);
editor.clear();
editor.commit();
相关问题