Android登录时密码保护功能
发布时间 - 2026-01-10 22:40:50 点击率:次在很多的Android项目中都需要用户登录、注册。这样的话在开发中做好保护用户密码的工作就显得尤为重要。这里我把自己的密码保护方法记录下来。

这是我建了一个保存密码的文件,以便于检查自己保存密码或者上传到服务器的时候密码是否已经被保护了。这就是当我输入用户名和密码之后点击记住密码之后
保存在SD卡上的文件,打开之后可以明显的看到密码已经被保护了。
下面是我的布局文件以及主程序的代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E6E6E6"
android:orientation="vertical">
<ImageView
android:id="@+id/iv_head"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:src="@drawable/ic_launcher"/>
<LinearLayout
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/iv_head"
android:layout_margin="10dp"
android:background="#FFFFFF"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/rl_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="账号"/>
<EditText
android:id="@+id/et_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_toRightOf="@+id/tv_name"
android:background="@null"/>
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#E6E6E6"/>
<RelativeLayout
android:id="@+id/rl_userpsd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:id="@+id/tv_psw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="密码"/>
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_toRightOf="@+id/tv_psw"
android:inputType="textPassword"
android:background="@null"/>
</RelativeLayout>
</LinearLayout>
<Button
android:id="@+id/login"
android:onClick="login"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="@+id/layout"
android:layout_centerHorizontal="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:background="#3C8DC4"
android:text="登录"
android:textColor="#FFFFFF"/>
<Button
android:id="@+id/signUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="注册"
android:background="#E6E6E6"
android:textColor="#000000"
android:layout_marginTop="21dp"
android:layout_centerHorizontal="true"
android:layout_marginRight="10dp"
android:layout_below="@+id/login"
android:layout_alignParentRight="true"/>
<CheckBox
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/signUp"
android:layout_alignBottom="@+id/signUp"
android:layout_alignLeft="@+id/login"
android:layout_marginLeft="14dp"
android:text="记住密码" />
</RelativeLayout>
package com.itcast.test03;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private EditText et_username;
private EditText et_userPsd;
private Button login;
private Button signUp;
private CheckBox save;
private String user,pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText)findViewById(R.id.et_number);
et_userPsd = (EditText)findViewById(R.id.et_password);
login=(Button)findViewById(R.id.login);
signUp=(Button)findViewById(R.id.signUp);
save = (CheckBox)findViewById(R.id.save);
save.setOnClickListener(new CheckBox.OnClickListener(){
public void onClick(View v) {
SharedPreferences pre = getSharedPreferences("loginvalue",
MODE_WORLD_WRITEABLE);
pass = MD5( et_userPsd.getText().toString());
user = et_username.getText().toString();
if (!pass.equals("") && !user.equals("")) {
pre.edit().putString("username",
et_username.getText().toString())
.putString("password", encryptmd5(pass)).commit();
Toast.makeText(getApplicationContext(),"保存成功!",
Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(),"密码不能为空!",
Toast.LENGTH_LONG).show();
}
}
});
login.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sp = getSharedPreferences("loginvalue",MODE_WORLD_READABLE);
String loginuser = sp.getString("username",null);
String loginpass = sp.getString("password",null);
user = et_username.getText().toString();
pass = et_userPsd.getText().toString();
String passmd5 = MD5(pass);
String encryptmd5 = encryptmd5(passmd5);
System.out.println("username="+ loginuser
+ "-------------password="+ loginpass);
System.out.println("user=="+ user
+ "-------------encryptmd5=="+ encryptmd5);
if (!user.equals("") && !pass.equals("")) {
if (user.equals(loginuser) && encryptmd5.equals(loginpass)) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, StudentMainActivity.class);
MainActivity.this.startActivity(intent);
finish();
} else{
Toast.makeText(getApplicationContext(),"密码是错误的!",
Toast.LENGTH_LONG).show();
}
} else{
Toast.makeText(getApplicationContext(),"密码不能为空!",
Toast.LENGTH_LONG).show();
}
}
});
initWidget();//
}
private void initWidget()
{
login.setOnClickListener(this);
signUp.setOnClickListener(this);
et_username.setOnFocusChangeListener(new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
String username=et_username.getText().toString().trim();
if(username.length()<4){
Toast.makeText(MainActivity.this, "用户名不能小于4个字符", Toast.LENGTH_SHORT);
}
}
}
});
et_userPsd.setOnFocusChangeListener(new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
String password=et_userPsd.getText().toString().trim();
if(password.length()<4){
Toast.makeText(MainActivity.this, "密码不能小于4个字符", Toast.LENGTH_SHORT);
}
}
}
});
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.login:
if(checkEdit())
{
login();
}
break;
case R.id.signUp:
Intent intent2=new Intent(MainActivity.this,SignUp.class);
startActivity(intent2);
break;
}
}
private boolean checkEdit(){
if(et_username.getText().toString().trim().equals("")){
Toast.makeText(MainActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,StudentMainActivity.class);
startActivity(intent);
}else if(et_userPsd.getText().toString().trim().equals("")){
Toast.makeText(MainActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
}else{
return true;
}
return false;
}
private void login(){
//这个网址需要改动
String httpUrl="http://192.168.1.102:8080/web-test/login.jsp";
HttpPost httpRequest=new HttpPost(httpUrl);
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username",et_username.getText().toString().trim()));
params.add(new BasicNameValuePair("password",et_userPsd.getText().toString().trim()));
HttpEntity httpentity = null;
try {
httpentity = new UrlEncodedFormEntity(params,"utf8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpRequest.setEntity(httpentity);
HttpClient httpclient=new DefaultHttpClient();
HttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpRequest);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(httpResponse.getStatusLine().getStatusCode()==200)
{
String strResult = null;
try {
strResult = EntityUtils.toString(httpResponse.getEntity());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(MainActivity.this, strResult, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,StudentMainActivity.class);
startActivity(intent);
}
else
{
Toast.makeText(MainActivity.this, "登录失败!", Toast.LENGTH_SHORT).show();
}
}
public static String MD5(String str){
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
char[] charArray = str.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++) {
byteArray[i] = (byte)charArray[i];
}
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int)md5Bytes[i])&0xff;
if(val<16){
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
public static String encryptmd5(String str){
char[] a = str.toCharArray();
for (int i = 0; i < a.length; i++) {
a[i] = (char)(a[i]^'1');
}
String s = new String(a);
return s;
}
}
添加权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INTERNET" />
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
# Android登录密码保护
# Android密码保护
# Android登录密码
# Android 开发仿简书登录框可删除内容或显示密码框的内容
# Android设计登录界面、找回密码、注册功能
# 在Nginx用htpasswd对网站进行密码保护的设置方法
# 页面使用密码保护代码
# 设置密码保护的SqlServer数据库备份文件与恢复文件的方法
# Android开发之登录验证实例教程
# Android集成新浪微博第三方登录的方法
# Android开发之注册登录方法示例
# Android实现登录功能demo示例
# Android调用第三方QQ登录代码分享
# 为空
# 自己的
# 这就是
# 主程序
# 当我
# 我把
# 这是我
# 输入用户名
# 中都
# 用户登录
# 大家多多
# 这样的话
# 卡上
# 就显得
# import
# java
# package
# itcast
# io
# UnsupportedEncodingException
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
千库网官网入口推荐 千库网设计创意平台入口
如何在腾讯云服务器快速搭建个人网站?
北京的网站制作公司有哪些,哪个视频网站最好?
学生网站制作软件,一个12岁的学生写小说,应该去什么样的网站?
Laravel怎么使用Collection集合方法_Laravel数组操作高级函数pluck与map【手册】
Laravel项目如何进行性能优化_Laravel应用性能分析与优化技巧大全
如何在Windows 2008云服务器安全搭建网站?
打造顶配客厅影院,这份100寸电视推荐名单请查收
如何在建站之星网店版论坛获取技术支持?
如何用5美元大硬盘VPS安全高效搭建个人网站?
Laravel模型关联查询教程_Laravel Eloquent一对多关联写法
如何在阿里云部署织梦网站?
微信小程序 闭包写法详细介绍
Android实现代码画虚线边框背景效果
怎么制作一个起泡网,水泡粪全漏粪育肥舍冬季氨气超过25ppm,可以有哪些措施降低舍内氨气水平?
Laravel怎么配置.env环境变量_Laravel生产环境敏感数据保护与读取【方法】
Laravel如何使用Gate和Policy进行权限控制_Laravel权限判定与策略规则配置
如何为不同团队 ID 动态生成多个“认领值班”按钮
iOS发送验证码倒计时应用
如何确保西部建站助手FTP传输的安全性?
js实现获取鼠标当前的位置
Laravel怎么上传文件_Laravel图片上传及存储配置
制作网站软件推荐手机版,如何制作属于自己的手机网站app应用?
焦点电影公司作品,电影焦点结局是什么?
Laravel用户密码怎么加密_Laravel Hash门面使用教程
香港服务器建站指南:外贸独立站搭建与跨境电商配置流程
如何自己制作一个网站链接,如何制作一个企业网站,建设网站的基本步骤有哪些?
深圳防火门网站制作公司,深圳中天明防火门怎么编码?
什么是javascript作用域_全局和局部作用域有什么区别?
PHP怎么接收前端传的文件路径_处理文件路径参数接收方法【汇总】
Laravel API路由如何设计_Laravel构建RESTful API的路由最佳实践
使用C语言编写圣诞表白程序
Laravel怎么配置自定义表前缀_Laravel数据库迁移与Eloquent表名映射【步骤】
网站制作大概要多少钱一个,做一个平台网站大概多少钱?
Laravel怎么写单元测试_PHPUnit在Laravel项目中的基础测试入门
如何在Ubuntu系统下快速搭建WordPress个人网站?
怎么制作网站设计模板图片,有电商商品详情页面的免费模板素材网站推荐吗?
Windows10如何删除恢复分区_Win10 Diskpart命令强制删除分区
Laravel如何使用缓存系统提升性能_Laravel缓存驱动和应用优化方案
如何快速搭建安全的FTP站点?
如何用PHP快速搭建CMS系统?
潮流网站制作头像软件下载,适合母子的网名有哪些?
如何在万网自助建站中设置域名及备案?
Laravel如何创建自定义Artisan命令?(代码示例)
矢量图网站制作软件,用千图网的一张矢量图做公司app首页,该网站并未说明版权等问题,这样做算不算侵权?应该如何解决?
Laravel如何创建自定义中间件?(Middleware代码示例)
Laravel如何实现模型的全局作用域?(Global Scope示例)
米侠浏览器网页背景异常怎么办 米侠显示修复
如何快速生成ASP一键建站模板并优化安全性?
Python正则表达式进阶教程_复杂匹配与分组替换解析

