保存登陆用户名和密码

在一些软件中登陆时保存用户名和密码是常见的功能,它实现起来也特别简单,其原理就是在点击登陆按钮时判断是否勾选保存密码选项,如果勾选,则在内存中保存一份包含用户名和密码的文件文件,在下次再打开登陆界面时会获取文件中的信息。

登陆界面:

在onclick中判断如果勾选了记住密码:

			if (cb_remeber_password.isChecked()) {
				boolean result = LoginService.saveInfo(this, username, password);
				if(result) {
					Toast.makeText(this, "保存密码成功", 0).show();
				}
saveInfo的方法:

	public static boolean saveInfo(Context context, String username,
			String password) {
		//getFileDir : /data/data/包名/files
		//getCacheDir : /data/data/包名/cache
		File file = new File(context.getFilesDir(), "info.txt");
	
		try {
			FileOutputStream fos = new FileOutputStream(file);
			fos.write((username + "#" + password).getBytes());
			fos.flush();
			fos.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

在这里的getFileDir获取的是手机内存的文件下路径,getCacheDir获取的是应用缓存路径,放在这个路径下的文件会在手机清理缓存是被清理,而且有大小限制,所以一般不建议放在getCacheDir路径下。

这样就保存了一份包含有用户名和密码信息的文件了,下次登录时就可以直接获取这里面的信息而不用重新输入了

		HashMap<String, String> info = LoginService.getInfo(this);
		if(info != null) {
			et_username.setText(info.get("username"));
			et_password.setText(info.get("password"));
		}
获取登录信息getInfo方法:

	public static HashMap<String, String> getInfo(Context context) {
		File file = new File(context.getFilesDir(), "info.txt");
		try {
			FileInputStream fis = new FileInputStream(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			String[] result = br.readLine().split("#");
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("username", result[0]);
			map.put("password", result[1]);
			br.close();
			return map;

		} catch (Exception e) {
			Toast.makeText(context, "无法读取用户信息", 0).show();

		}
		return null;
	}

这样就实现了登录信息的获取

再次登录时的状态:






  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值