java - 带有缓存的 Android 登录应用程序
问题描述
我正在尝试使用缓存开发应用程序。该应用程序将检查服务器中的登录凭据并允许用户。我希望用户只登录一次,如Facebook、G 邮件应用程序等。
截至目前,我第一次尝试使用共享首选项来存储登录凭据,当用户下次尝试打开应用程序时,我将使用存储的凭据登录。但我想像 G 邮件应用程序一样简化它,只有一次我需要登录,下次用户打开应用程序时,登录页面不应该显示给他,除非他注销。
在onCreate中,我正在检查我是否存储了凭据,如果有,那么我将使用该凭据登录,否则用户必须输入登录凭据并按下登录按钮。
sharedPref_login = MainActivity.this.getSharedPreferences("login_credentials",Context.MODE_PRIVATE);
username = sharedPref_login.getString("username", defaultValue);
password = sharedPref_login.getString("password", defaultValue);
roles = sharedPref_login.getString("roles", defaultValue);
if (!username.equals("")){
if (!isInternetOn()){
Toast.makeText(MainActivity.this, "Restart the application once the internet connection established", Toast.LENGTH_SHORT).show();
}
else {
Applogin(username, password, millisInString);
}
}
我想通过只登录一次来避免这种方法,除非他按下注销按钮。
解决方案
//Fetching id from shared preferences
SharedPreferences sharedPreferences;
sharedPreferences =getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);
username = sharedPreferences.getString(Constant.USERNAME_SHARED_PREF, "");
password = sharedPreferences.getString(Constant.PASSWORD_SHARED_PREF, "");
if(!username.equals("")){
Intent intent = new Intent(getApplicationContext(),LoginActivity.class)
startActivity(intent)
}else{
if (!isInternetOn()){
Toast.makeText(MainActivity.this, "Restart the application once the internet connection established", Toast.LENGTH_SHORT).show();
}
else {
Applogin(username, password, millisInString);
}
}