2013-12-19 55 views
11

任何人都可以告诉我如何维护用户登录的会话。例如,当用户登录到应用程序时,他们必须登录,除非用户注销或卸载类似于android中的gmail的应用程序。如何在android中保持会话?

+2

读取前登录ID您是否尝试过使用[SharedPreferences(HTTP://开发商。 android.com/reference/android/cont ent/SharedPreferences.html)作为会话存储设施?不太确定安全/安全问题,但它可能是你需要的。 –

回答

26

让一个类你SharedPreferences

public class Session { 

    private SharedPreferences prefs; 

    public Session(Context cntx) { 
     // TODO Auto-generated constructor stub 
     prefs = PreferenceManager.getDefaultSharedPreferences(cntx); 
    } 

    public void setusename(String usename) { 
     prefs.edit().putString("usename", usename).commit(); 
    } 

    public String getusename() { 
     String usename = prefs.getString("usename",""); 
     return usename; 
    } 
} 

现在,当你想使用它,使用这样使得这个类后:使这个类的对象像

private Session session;//global variable 
session = new Session(cntx); //in oncreate 
//and now we set sharedpreference then use this like 

session.setusename("USERNAME"); 

现在,每当你想要获得用户名,则需要为会话对象完成相同的工作,并致电

​​

做同样的密码

+2

prefsCommit()的用途是什么? –

+3

考虑使用apply()来代替; commit()立即将其数据写入永久存储,而apply()将在后台处理它。 –

+0

我得到了prefsCommit(); –

2

您可以在SharedPreferences中使用布尔值。

在登录前加载它来检查是否需要登录。

登录后进行保存。

0

你可以通过几种不同的方式获得行为,我更喜欢在共享首选项中设置一个标志。当用户登录时检查应用程序何时启动,如果你得到的默认值是用户不是逻辑数据库,否则你应该有你的标志(我使用用户名)设置并避免登录部分。

2

我有一个简单的方法,而不是维护一个会话。

即只存储一个boolean变量与您的用户名和密码。默认设置值等于false。

第一次成功登录后,将其值设置为true。

然后只要检查它的Mainactivity值,如果它是真的,那么跳转到下一个活动,否则跳转到登录活动。

+0

你认为它的安全吗? –

+0

当然,是因为共享首选项始终存储在数据中。所以没有人可以从“设备”导入数据。你仍然不满意,那么你可以用加密的形式存储用户名和密码。 @ Swap-IOS-Android – Andrain

0

将用户数据保存在共享首选项中,直到用户注销。 一旦用户注销清除共享首选项中的数据。

+0

即使在没有注销的情况下关闭应用程序后,用户是否仍可以维护会话? – june

+0

是的。他将能够。只有当他按下注销按钮时才会清除sharedprefs。直到除非sharedprefs将内部保存到您的应用程序中。 – Yogamurthy

5

您可以通过客户经理做到这一点 - click here 代码样品 - //方法添加帐户.. 私人无效addAccount(用户名字符串,字符串密码){

AccountManager accnt_manager = AccountManager 
      .get(getApplicationContext()); 

    Account[] accounts = accnt_manager 
      .getAccountsByType(getString(R.string.account_type));//account name identifier. 

    if (accounts.length > 0) { 
     return; 
    } 
    final Account account = new Account(username, 
      getString(R.string.account_type)); 

    accnt_manager.addAccountExplicitly(account, password, null); 

    final Intent intent = new Intent(); 
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username); 
    intent.putExtra(AccountManager.KEY_PASSWORD, password); 
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, 
      getString(R.string.account_type)); 
    // intent.putExtra(AccountManager.KEY_AUTH_TOKEN_LABEL, 
    // PARAM_AUTHTOKEN_TYPE); 
    intent.putExtra(AccountManager.KEY_AUTHTOKEN, "token"); 
    this.setAccountAuthenticatorResult(intent.getExtras()); 
    this.setResult(RESULT_OK, intent); 
    this.finish(); 

} 

//方法回顾账户。 私人布尔va​​lidateAccount(){

AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { 

     @Override 
     public void run(AccountManagerFuture<Bundle> arg0) { 
      Log.e("calback", "msg"); 

      try { 
       Bundle b = arg0.getResult(); 
       if (b.getBoolean(AccountManager.KEY_ACCOUNT_MANAGER_RESPONSE)) { 
        //User account exists!!.. 
       }  

      } catch (OperationCanceledException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (AuthenticatorException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 
    }; 

    AccountManager accnt_manager = AccountManager 
      .get(getApplicationContext()); 

    Account[] accounts = accnt_manager 
      .getAccountsByType(getString(R.string.account_type)); 

    if (accounts.length <= 0) { 
     return false; 
    } else { 

     loginNameVal = accounts[0].name; 
     loginPswdVal = accnt_manager.getPassword(accounts[0]); 
     return true; 

    } 

} 
+1

这是处理会话的正确方法。谢谢! – Jalal

0

使用下面的代码。

SessionManager.java

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 = "Pref"; 

    // 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 
    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, LoginActivity.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, LoginActivity.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); 
    } 
} 

而且在MainActivity做如下所示。

public class MainActivity extends Activity { 

    // Email, password edittext 
    EditText txtUsername, txtPassword; 

    // login button 
    Button btnLogin; 

    // Alert Dialog Manager 
    AlertDialogManager alert = new AlertDialogManager(); 

    // Session Manager Class 
    SessionManager session; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 

     // Session Manager 
     session = new SessionManager(getApplicationContext());     

     // Email, Password input text 
     txtUsername = (EditText) findViewById(R.id.txtUsername); 
     txtPassword = (EditText) findViewById(R.id.txtPassword); 

     Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show(); 


     // Login button 
     btnLogin = (Button) findViewById(R.id.btnLogin); 


     // Login button click event 
     btnLogin.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // Get username, password from EditText 
       String username = txtUsername.getText().toString(); 
       String password = txtPassword.getText().toString(); 

       // Check if username, password is filled     
       if(username.trim().length() > 0 && password.trim().length() > 0){ 
        // For testing puspose username, password is checked with sample data 
        // username = test 
        // password = test 
        if(username.equals("test") && password.equals("test")){ 

         // Creating user login session 
         // For testing i am stroing name, email as follow 
         // Use user real data 
         session.createLoginSession("ABC", "[email protected]"); 

         // Staring MainActivity 
         Intent i = new Intent(getApplicationContext(), MainActivity.class); 
         startActivity(i); 
         finish(); 

        }else{ 
         // username/password doesn't match 
         alert.showAlertDialog(LoginActivity.this, "Login failed..", "Username/Password is incorrect", false); 
        }    
       }else{ 
        // user didn't entered username or password 
        // Show alert asking him to enter the details 
        alert.showAlertDialog(LoginActivity.this, "Login failed..", "Please enter username and password", false); 
       } 

      } 
     }); 
    }   
} 
1

使用SharedPreferences。 码的值保存到sharedpreferences:

SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE); 
SharedPreferences.Editor ed=sp.edit(); 
ed.putInt("value", your_value); 
ed.commit(); 

代码从sharedpreferences获得价值:

SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE); 
int value = sp.getInt("value", default_value); 

您可以使用此值检查登录和注销。

0
public class Session { 

    private SharedPreferences prefs; 

    public Session(Context cntx) { 
     // TODO Auto-generated constructor stub 
     prefs = PreferenceManager.getDefaultSharedPreferences(cntx); 
     editor = prefs.edit(); 
    } 

    public void setusename(String usename) { 
     editor.putString("usename", usename).commit(); 

    } 

    public String getusename() { 
     String usename = prefs.getString("usename",""); 
     return usename; 
    } 
} 
0

源代码

https://drive.google.com/open?id=0BzBKpZ4nzNzUcUZxeHo0UnJ5UHc

在android系统 enter image description here

**After Login save Email ID is SharedPreferences** 

    emaidId = et_Email.getText().toString().trim(); 

    SharedPreferences ss = getSharedPreferences("loginSession_key", 0); 
    Set<String> hs = ss.getStringSet("set", new HashSet<String>()); 
    hs.add(emaidId); 
    SharedPreferences.Editor edit = ss.edit(); 
    edit.clear(); 
    edit.putStringSet("set", hs); 
    edit.commit(); 

===================onCreate()==================== 
===================AutoCompleteTextView set Adapter=================== 

**Fetch PRevious Login Email id in email EditText** 

SharedPreferences sss = getSharedPreferences("loginSession_key", 0);   // todo loginSession_key key name ALWAYS SAME 
Log.i("chauster", "2.set = " + sss.getStringSet("set", new HashSet<String>())); 
Log.e("Session", "Value->" + sss.getStringSet("set", new HashSet<String())); 
ArrayList<String> al = new ArrayList<>(); 
al.addAll(sss.getStringSet("set", new HashSet<String>())); 
//Creating the instance of ArrayAdapter containing list of language names 
ArrayAdapter<String> adapter = new ArrayAdapter<String> 
       (this, android.R.layout.select_dialog_item, al); 
//Getting the instance of AutoCompleteTextView 
et_Email.setThreshold(1);//will start working from first character 
et_Email.setAdapter(adapter);//setting the adapter data into the