现在我正在学习如何在Android中开发应用程序,我想让用户即使在应用程序关闭后仍然登录。我阅读here我可以使用android设备ID和发送令牌来保持用户登录。但是,如果以后我决定将我的应用程序扩展到iOS,Windows或其他操作系统,这种方法是否还在继续上班?使用令牌进行身份验证是否安全?如果是这样,那么令牌有多强(多少个字符)?
提前致谢
答案 0 :(得分:0)
使用共享偏好设置将数据保存在手机和手机中。要注销时清除已保存的数据。
private ProjectUtils utils;
pref = (this.getApplicationContext()).getSharedPreferences("login_credential",MODE_PRIVATE);
//SharedPreferences
editor = pref.edit();
editor.putBoolean("login_status",true);
editor.putString("user_id", String.valueOf(userId));
editor.putString("password", String.valueOf(passwd));
editor.putString("boy_id", String.valueOf(loginPojo.getBoyDetails().getBoyId()));
editor.putString("boy_name", loginPojo.getBoyDetails().getBoyName());
editor.putString("boy_age", loginPojo.getBoyDetails().getBoyAge());
editor.putString("boy_phone", String.valueOf(loginPojo.getBoyDetails().getBoyPhone()));
editor.putString("boy_dlno", loginPojo.getBoyDetails().getBoyDlno());
// editor.putString("boy_user_id", email);
editor.commit();
以上代码用于以Unique键保存数据。
if(pref.getBoolean("login_status", false))
{
Intent intent = new Intent(SplashScreen.this,MainActivity.class);
startActivity(intent);
Log.e("LOGIN","Yes");
}
else
{
Intent intent = new Intent(SplashScreen.this,LoginActivity.class);
startActivity(intent);
Log.e("LOGIN","No");
}
答案 1 :(得分:0)
好吧,你必须将用户存储在设备中并在每次应用程序打开时检查是否仍然存在!这是一个例子..
如果通过Web请求api完成登录,现在在Web请求的OnSuccessResponse
内部,我创建了User模型类的新对象,然后使用SharedPreference保存它!我为此使用了一个名为Hawk的非常棒的SharedPreference库。!
// code..
@Override
public void onResponse(JSONObject response) {
Gson gson = new Gson();
try {
UserModel user= gson.fromJson(response.getJSONObject("customer").toString(), UserModel.class);
Hawk.put("user", user); // here I save the user object
Toasty.success(context, "Login was a success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, MyHome.class);
context.startActivity(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
// code..
现在,当用户退出时,只需删除对象..!
Hawk.remove("user");
Intent i = new Intent(UserSettings.this, LoginActivity.class);
UserSettings.this.startActivity(i);
当应用程序再次打开时,请检查显示的第一个屏幕..对于我的情况,它是启动画面..!
UserModel user = Hawk.get("user");
Intent intent;
if (user != null) //if the user is null then the user was deleted from the logout process!
intent = new Intent(Splash.this, MyHome.class);
else
intent = new Intent(Splash.this, LoginActivity.class);
startActivity(intent);