[英]What is the best practice to keep a phone app logged in? Is the token approach safe?
使用共享首选项将数据保存在手机中,并在要注销时清除保存的数据。
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();
上面的代码用于将数据保存在唯一键中。
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");
}
好吧,您必须将用户存储在设备中,并在每次打开应用程序时检查是否仍然存在! 这是一个例子。
如果通过Web请求api登录,现在在Web请求的OnSuccessResponse
内,则OnSuccessResponse
User模型类的新对象,然后使用SharedPreference保存它! 我为此使用了一个非常棒的SharedPreference库,称为Hawk 。
// 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.