2017-05-30 119 views
-2

我創建在用戶登錄和註銷,數據使用PHP Web服務來自MySQL服務器的應用程序,現在我想,當用戶註銷,我使用如何在Android登錄/註銷中管理會話?

intent.putExtra("SESSION_ID", sessionId); 
保持會話時,用戶登錄,並摧毀它

如何重置它註銷 這是否將作爲會議或我必須做別的事情

+0

http://www.androidhive.info/2012/ 08 /使用共享-喜好Android的會話管理-/ –

回答

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

註銷:

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

這裏是一個很好的教程約Android Login and Registration with PHP, MySQL and SQLite

希望這會有所幫助〜

0

使用sharedPreferences可以簡單得多。創建sharedPreference變量並在註銷時清除它。

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

後來,當會話註銷

editor.clear(); 
0

對於SET /登錄

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