【问题标题】:Android save user sessionAndroid 保存用户会话
【发布时间】:2014-05-18 09:08:35
【问题描述】:

我是 android 新手,我正在尝试保存登录会话并在每次向服务器发送请求时发送它,我的 Web 服务是 PHP(Zend 框架 2)。

此代码用于识别用户:

$auth = Zend_Auth::getInstance();
$IdentityObj = $auth->getIdentity();

可以保存会话并像使用网络浏览器一样发送它,而无需对我的网络服务进行任何更改。

【问题讨论】:

  • 当然可以。我最近在 OpenCart 上工作(我不确定它使用的是哪个框架)。你可以得到会话。将其存储在共享首选项中,然后在您要发送请求时检索它。

标签: android session zend-framework login zend-auth


【解决方案1】:

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

要与SharedPreferences合作,请采取以下步骤:

  1. 通过向构造函数传递两个参数(字符串和整数)来初始化共享SharedPreferences 接口

    // 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. 使用 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
    
  3. 检索数据:

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

    // 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
    
  4. 最后,像注销一样清除/删除数据

    如果您想从共享首选项中删除,您可以调用 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/

另外,这是我使用的实现类:

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

最后,您必须在活动类的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);
}

希望对你有帮助。

【讨论】:

  • 比选择的答案更好
【解决方案2】:

是的,是的。您只需使用SharedPreferences 存储会话。

这个想法是,在您登录后,我猜您会返回某种会话 ID 或其他什么。你只需要存储它。然后,在后续执行中,您只需在执行任何请求之前获取该会话。

SharedPreferences preferences = 
    getSharedPreferences("com.blabla.yourapp", Context.MODE_PRIVATE);

//Save it
preferences.edit().putString("session", <yoursessiontoken>).commit();

//Fetch it
// The second parameter is the default value.
preferences.getString("session", ""); 

无论如何,您最好阅读文档以真正了解您在做什么。

【讨论】:

  • 但是当我清除应用程序缓存时呢?偏好也很明确。
  • 清除应用缓存不会清除首选项。
猜你喜欢
  • 2014-09-25
  • 1970-01-01
  • 2017-12-03
  • 2014-12-25
  • 1970-01-01
  • 2017-05-24
  • 2017-02-09
  • 2020-05-20
  • 2023-04-03
相关资源
最近更新 更多