Android登录时密码保护功能

在很多的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" />

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Android实现登录功能demo示例

    本文实例讲述了Android实现登录功能的方法.分享给大家供大家参考,具体如下: 安卓,在小编实习之前的那段岁月里面,小编都没有玩儿过,如果说玩儿过,那就是安卓手机了,咳咳,敲登录的时候有种特别久违的熟悉,这种熟悉的感觉就和当时敲机房收费系统一样,那叫一个艰难啊,不过小编相信,在小编的IT成长之路上,正是因为有了这些艰难险阻陪伴着小编一起成长,才让小编更加勇敢坚强,勇敢的面对一个又一个bug,坚强的敲完一行行代码,经过了几天的研究登录一条线的功能已经实现,现在小编就来简单的总结一下,还请小伙伴们

  • Android开发之登录验证实例教程

    本文所述实例源自一个项目开发中的登录验证功能,具体的要求就是,在Android端输入用户名和密码,在服务器端验证MySQL数据库中是否有此用户,实现之前当然首要的是,如何使Android端的数据发送到服务器端,具体的实现方法如下: 服务器端:ManageServlet.java代码如下: public class ManageServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServle

  • 设置密码保护的SqlServer数据库备份文件与恢复文件的方法

    设置密码保护SqlServer数据库备份文件! 备份SqlServer数据库 Backup Database [数据库] To disk='c:\mysql'+ replace(replace(replace(replace(CONVERT(varchar, getdate(), 121),'-',''),' ',''),':',''),'.','') +'.bak' With Password = '123',init; 恢复SqlServer数据库 Restore Database [数据库

  • Android调用第三方QQ登录代码分享

    本文为大家分享了调用QQ登录的相关代码,希望对大家有帮助,减少项目开发的时间,具体内容如下 1.去QQ开放平台注册帐号(http://open.qq.com/),为应用申请QQ的APP_ID , 并下载相关的jar包,放到工程的lib目录下. 2.在Manifest.xml里注册QQ相关的Activity,代码如下 <activity android:name="com.tencent.connect.common.AssistActivity" android:screenOr

  • Android集成新浪微博第三方登录的方法

    本文实例讲述了Android集成新浪微博第三方登录的方法.分享给大家供大家参考.具体实现方法如下: 1.下载微博的sdk ,导入微博的jar包两个 android-support-v4.jar和weibosdkcore.jar两个包 2.把新浪微博中的demo_src中SDK中的com,导入到项目中 3.用demo中的constants,主要是参数设置,将里面的参数改成自己的参数. 4.编写代码,主要步骤如下: 复制代码 代码如下: // 初始化微博对象 mWeiboAuth = new Wei

  • Android开发之注册登录方法示例

    本文所述,继续上一篇关于Android端向服务器端发送数据的方法进一步完善注册登录的方法,由于版本问题出现一点瑕疵,今天经过调试已经解决,在这里给大家介绍一下. 在Android4.0以后版本的对于网络权限要求变得严格,致使上一篇所述的案例无法将数据发送到服务器端,当你一点击发送数据,Android控制台就会报错,错误当然是很让人头疼,基本上都是关于http的错误,所以可以肯定是Android虚拟机向服务器发送数据时出现了错误,经过一番检查与测试后才知道,4.0之后的版本,主线程中不允许调用网络

  • Android 开发仿简书登录框可删除内容或显示密码框的内容

    简书App 是我很喜欢的一款软件.今天就模仿了一下他的登录框.先上图: 好了下面上代码,自定义ImgEditText 继承与EditText.重写一些方法. package lyf.myimgedittextdemo; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.text.Editable; impor

  • Android设计登录界面、找回密码、注册功能

    本文实例为大家分享了Android 登录.找回密码.注册功能的实现代码,供大家参考,具体内容如下 1.数据库的设计 我在数据库中添加了两张表,一张表用来存储用户信息,诸如用户名,密码,手机号等,可任意添加.另一张表用来存储上一个登录用户的账户信息,我是为了方便才另外创建了一张表去存储,而且这张表我设计了它只能存储一条信息,每次的存储都是对上一条记录的覆盖.事实上,我尝试过在存储用户信息的那张表内添加一个标识,用来标记上一次登录的是哪一个帐号,但是这样做的话,每次改变标识都需要遍历整张表,十分的麻

  • 页面使用密码保护代码

    代码如下所示: <html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>密码保护相应页面</title></head><body><SCRIPT LANGUAGE="JavaScript">function password() {

  • 在Nginx用htpasswd对网站进行密码保护的设置方法

    最后的效果就类似(不同浏览器的界面有所不同): 如果认证失败,就会报HTTP错误:401 Authorization Required. 要实现这样的功能,就需要更改服务器的配置,并设定好用于登录的用户名和密码. 首先我们需要更改网站的Nginx的server配置,Ubuntu服务器的话这个配置文件通常位于/etc/nginx/sites-enabled/,比如我这里就使用默认的配置文件/etc/nginx/sites-enabled/default来做一个例子: 复制代码 代码如下: serv

随机推荐