保存登陆username和password

在一些软件中登陆时保存username与password是常见的功能,它实现起来也特别简单,其原理就是在点击登陆button时推断是否勾选保存密码选项,假设勾选,则在内存中保存一份包括username与password的文件文件,在下次再打开登陆界面时会获取文件里的信息。

登陆界面:

在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路径下。

这样就保存了一份包括实username与password信息的文件了,下次登录时就能够直接获取这里面的信息而不用又一次输入了

		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;
	}

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

再次登录时的状态:






猜你喜欢

转载自www.cnblogs.com/ldxsuanfa/p/10554653.html
今日推荐