저는 안드로이드에 새로운입니다 로그인 세션을 저장하려고하고 서버에 요청을 보낼 때마다 내 웹 서비스가 PHP (젠드 프레임 워크 2)입니다.안드로이드는 사용자 세션을 저장합니다
이 코드는 사용자를 식별하기 :
$auth = Zend_Auth::getInstance();
$IdentityObj = $auth->getIdentity();
이 세션을 저장하고 내 웹 서비스에 변경을하지 않고 웹 브라우저를 사용처럼 보낼 수도 있습니다.
저는 안드로이드에 새로운입니다 로그인 세션을 저장하려고하고 서버에 요청을 보낼 때마다 내 웹 서비스가 PHP (젠드 프레임 워크 2)입니다.안드로이드는 사용자 세션을 저장합니다
이 코드는 사용자를 식별하기 :
$auth = Zend_Auth::getInstance();
$IdentityObj = $auth->getIdentity();
이 세션을 저장하고 내 웹 서비스에 변경을하지 않고 웹 브라우저를 사용처럼 보낼 수도 있습니다.
예, 그렇습니다. 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", "");
실제로 어떤 작업을하는지 문서를 읽는 것이 좋습니다.
하지만 애플리케이션 캐시 (Cache of application)는 어떨까요? 환경 설정도 명확합니다. –
앱 캐시를 지우지도 환경 설정이 지워지지 않습니다. – Santi
SharedPreferences
을 사용하면 Android에서 키, 값 쌍 데이터를 저장하고 검색하고 전체 애플리케이션에서 세션을 유지할 수 있습니다.
// Sharedpref file name
private static final String PREF_NAME = "PreName";
// Shared pref mode
int PRIVATE_MODE = 0;
// 초기화하기를 생성자에 두 개의 인수를 전달하여 공유 SharedPreferences
인터페이스의
초기화 (문자열과 정수) :
는 다음과 같은 조치를 취할SharedPreferences
작업하려면 SharedPreferences SharedPreferences pref = getApplicationContext(). getSharedPreferences ("MyPref", 0); // 0 - 전용 모드 편집기 인터페이스 및 된 SharedPreferences 값을 수정하기 위해 그 방법을 사용나중에 검색을 위해
//Initialising the Editor
Editor editor = pref.edit();
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString 데이터를 저장하는 ("KEY_NAME" "문자열 값") ; // 문자열 저장 editor.putInt ("key_name", "int value"); // 정수 저장 editor.putFloat ("key_name", "float value"); // float 저장 editor.putLong ("key_name", "long value"); // 길게 저장
editor.commit(); // 커밋 변경
데이터 검색
데이터() (문자열) 메소드에는 getString를 호출하여 저장된 환경 설정에서 검색 할 수 있습니다 . 이 메서드는 Editor가 아닌 Shared Preferences에서 호출해야합니다.
당신이 특정 값을 삭제 제거 호출 할 수있는 공유 환경 설정에서 ("KEY_NAME")를 삭제하려면 로그 아웃의 경우처럼 마지막
// 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. 지우기/데이터 삭제.당신은 모든 데이터를 삭제하려면, 전화 분명()
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
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);
}
}
마지막으로, 당신은 전체
// Session Manager Class
SessionManager session;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Session Manager
session = new SessionManager(getApplicationContext());
session.createLoginSession("Username", intentValue);
}
전반에 걸쳐 사용되는 세션에 대한 createLoginSession을 활동 클래스의에서 onCreate 방법이 SessionManager에 클래스의 인스턴스를 생성 한 다음 전화를해야합니다 나는 그것이 도움이되기를 바랍니다.
선택한 답변보다 좋습니다. – Guido
물론 가능합니다. 나는 최근에 OpenCart (어떤 프레임 워크를 사용하고 있는지 잘 모르겠다.)에서 일했다. 세션을 얻을 수 있습니다. 공유 환경 설정에 저장 한 다음 요청을 보낼 때 검색하십시오. – Hesam