用户登录的时候,需要将用户名、用户ID等等一些信息保存到APP的文件里面,下次进入APP的时候,先读文件,如果用户已经登录过,则跳过登录界面;
首先,将保存文件的方法写到基类里面,
//保存用户信息
public void saveData(Context context,int userid , int cityid , int shopid , int typeid , String token ,
String username){
SharedPreferences sp = context.getSharedPreferences("config", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("userid", userid);
editor.putInt("cityid",cityid);
editor.putInt("shopid",shopid);
editor.putInt("typeid",typeid);
editor.putString("token",token);
editor.putString("username",username);
editor.commit();
}
//判断是不是第一次登陆
public void savefrist(Context context , String isFirstIn){
SharedPreferences sp = context.getSharedPreferences("config", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("isFirstIn", isFirstIn);
editor.commit();
}
在登录界面,进行登录操作的时候,如果操作成功,则保存这些信息,在操作成功之后,加上:
baseactivity.saveData(Login.this,userid , cityid , shopid , typeid, token , username );
baseactivity.savefrist(Login.this,isFirstIn);
在登录的activity的oncreat里面,读取文件,如果文件为空,则直接加载登录界面,如果文件不为空,且能读取到第一次登陆时保存的那个数值,则直接跳转到主界面。
private void isnettestfirst() {
boolean isnet = BaseActivity.isNetworkAvailable(Login.this);
if (isnet == false) {
setContentView(R.layout.activity_login);
login_instance = this;
findid();
click();
Toast.makeText(Login.this, "请检查你的网络连接", Toast.LENGTH_SHORT).show();
} else {
myisFirstIn = baseactivity.loadfrist(Login.this);
myusername = baseactivity.loadusername(Login.this);
if ("isFirstIn".equals(myisFirstIn)){
startActivity(new Intent(Login.this,MainActivity.class));
finish();
}else {
setContentView(R.layout.activity_login);
login_instance = this;
findid();
click();
main_login_et_user.setText(myusername);
}
}
}
//读取文件里面的内容
public String loadusername(Context context){
SharedPreferences sp = context.getSharedPreferences("config", MODE_PRIVATE);
String username = sp.getString("username", "");
return username;
}
//调用读取文件
BaseActivity baseActivity1 = new BaseActivity();
username= baseActivity1.loadusername(this);
//清除文件里面的内容
public void clear(Context context) {
SharedPreferences sp = context.getSharedPreferences("config", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove("isFirstIn");
editor.remove("userid");
editor.remove("cityid");
editor.remove("shopid");
editor.remove("typeid");
editor.remove("token");
editor.commit();
}