Android随机生成验证码,Android利用随机数绘制不规则的验证码,加强用户登录或者注册的安全性。
具体思路如下:
在一块固定宽高的画布上,画上固定个数的随机数字和字母,再画上固定条数的干扰线, 随机数和干扰线的颜色随机生成,随机数的样式随机生成。

界面效果如下:

1.生成随机数的代码,Code.java

public class Code {    //随机数数组    private static final char[]CHARS={'2', '3', '4', '5', '6', '7', '8', '9',            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm',            'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',            'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };    private static Code bmpCode;    //验证码默认随机数的个数    private static final int DEFAULT_CODE_LENGTH=4;    //默认字体的大小    private static final int DEFAULT_FONT_SIZE=25;    //默认线条的个数    private static final int DEFAULT_LINE_NUMBER=5;    //padding值    private static final int BASE_PADDING_LEFT=10,RANGE_PADDING_LEFT=15,BASE_PADDING_TOP=15,RANGE_PADDING_TOP=20;    //验证码的默认宽高    private static final int DEFAULT_WITH=100,DEFAULT_HEIGHT=40;    //画布的宽高    private int with=DEFAULT_WITH,height=DEFAULT_HEIGHT;    //random word space and pading_top    private int base_padding_left=BASE_PADDING_LEFT,range_padding_left=RANGE_PADDING_LEFT,base_padding_top=BASE_PADDING_TOP            ,range_padding_top=RANGE_PADDING_TOP;    //字符、线条、的个数,字体的大小    private int codeLength=DEFAULT_CODE_LENGTH,line_number=DEFAULT_LINE_NUMBER,font_size=DEFAULT_FONT_SIZE;    //变量    private String code;    private int padding_left,padding_top;    private Random random=new Random();    public static Code getInstance(){        if (bmpCode==null){            bmpCode=new Code();        }        return bmpCode;    }    //验证码图片    public Bitmap createBitmap(){        padding_left=0;        Bitmap bp=Bitmap.createBitmap(with,height, Bitmap.Config.ARGB_8888);        Canvas c=new Canvas(bp);        code=createCode();//        c.drawColor(Color.GRAY);//设置画布的颜色        Paint paint=new Paint();        paint.setAntiAlias(true);//去除锯齿        paint.setTextSize(font_size);        //画验证码        for (int i = 0; i < code.length(); i++) {            randomTextStyle(paint);            randomPadding();            c.drawText(code.charAt(i)+"",padding_left,padding_top,paint);        }        //画线条        for (int i = 0; i < line_number; i++) {            drawLine(c,paint);        }        c.save(Canvas.ALL_SAVE_FLAG);//保存        c.restore();        return bp;    }    public String getCode(){        return code;    }    //画干扰线    private void drawLine(Canvas canvas, Paint paint) {        int color=randomColor();        int startX=random.nextInt(with);        int startY=random.nextInt(height);        int stopX=random.nextInt(with);        int stopY=random.nextInt(height);        paint.setStrokeWidth(1);        paint.setColor(color);        canvas.drawLine(startX,startY,stopX,stopY,paint);    }    //生成随机颜色    private int randomColor() {        return randomColor(1);    }    private int randomColor(int rate) {        int red=random.nextInt(256)/rate;        int green=random.nextInt(256)/rate;        int blue=random.nextInt(256)/rate;        return Color.rgb(red,green,blue);    }    //随机生成padding值    private void randomPadding() {        padding_left+=base_padding_left+random.nextInt(range_padding_left);        padding_top=base_padding_top+random.nextInt(range_padding_top);    }    //随机生成文字样式,颜色,粗细,倾斜度    private void randomTextStyle(Paint paint) {        int color=randomColor();        paint.setColor(color);        paint.setFakeBoldText(random.nextBoolean()); //true为粗体,false为非粗体        float skewX=random.nextInt(11)/10;        skewX=random.nextBoolean()?skewX:-skewX;        paint.setTextSkewX(skewX);//float类型参数,负数表示右斜,整数左斜    }    //生成验证码    private String createCode() {        StringBuilder buffer=new StringBuilder();        for (int i = 0; i < codeLength; i++) {            buffer.append(CHARS[random.nextInt(CHARS.length)]);        }        return buffer.toString();    }}
2.布局文件,activity_register.xml:

<?xml version="1.0" encoding="utf-8"?>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:orientation="vertical"    tools:context="com.example.dell.RegisterActivity">            android:layout_width="match_parent"        android:layout_height="64dp"        android:text="MTM系统账号绑定"        android:textColor="#262626"        android:textSize="18sp"        android:gravity="center"/>            android:layout_width="match_parent"        android:layout_height="30dp"        android:background="#cdcdcd"        android:text="首次登录时请填写MTM账户信息"        android:textSize="11sp"        android:textColor="#737373"        android:gravity="center">                android:layout_width="match_parent"        android:layout_height="44dp"        android:orientation="horizontal"        android:gravity="center_vertical"        android:paddingLeft="12dp">                    android:layout_width="0dp"            android:layout_weight="1"            android:layout_height="wrap_content"            android:text="MTM账号"            android:textSize="15sp"            android:textColor="#000"/>                    android:id="@+id/et_login_account"            android:layout_width="0dp"            android:layout_weight="2"            android:layout_height="wrap_content"            android:hint="请输入MTM账号"            android:background="@null"            android:textSize="12sp"            android:textColorHint="#b3b3b3"/>                android:layout_width="match_parent"        android:layout_height="1dp"        android:background="#cdcdcd"        android:layout_marginLeft="12dp"        android:layout_marginRight="12dp"/>            android:layout_width="match_parent"        android:layout_height="44dp"        android:orientation="horizontal"        android:gravity="center_vertical"        android:paddingLeft="12dp">                    android:layout_width="0dp"            android:layout_weight="1"            android:layout_height="wrap_content"            android:text="MTM密码"            android:textSize="15sp"            android:textColor="#000"/>                    android:id="@+id/et_login_password_ok"            android:layout_width="0dp"            android:layout_weight="2"            android:layout_height="wrap_content"            android:hint="请再次输入MTM密码"            android:background="@null"            android:textSize="12sp"            android:textColorHint="#b3b3b3"/>                android:layout_width="match_parent"        android:layout_height="30dp"        android:background="#cdcdcd"        android:paddingLeft="12dp"        android:text="验证码获取"        android:gravity="center_vertical">                android:layout_width="match_parent"        android:layout_height="44dp"        android:gravity="center_vertical"        android:paddingLeft="12dp">                    android:id="@+id/tv_yanzheng_companyReg"            android:layout_width="wrap_content"            android:layout_height="match_parent"            android:text="验证码"            android:gravity="center_vertical"            android:textSize="15sp"            android:textColor="#000"/>                    android:id="@+id/et_code_companyRe"            android:layout_width="wrap_content"            android:layout_height="match_parent"            android:layout_weight="1"            android:layout_toRightOf="@id/tv_yanzheng_companyReg"            android:hint="请输入验证码"            android:textColorHint="#666"            android:textSize="12sp"            android:gravity="center_vertical"            android:layout_marginLeft="24dp"            android:background="@null"/>                    android:id="@+id/iv_code"            android:layout_width="100dp"            android:layout_height="32dp"            android:layout_alignParentRight="true"            android:layout_marginRight="12dp"            android:background="@drawable/btn_yanzhengmabg"/>                android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="#cdcdcd">                    android:layout_width="match_parent"            android:layout_height="44dp"            android:orientation="horizontal"            android:layout_alignParentBottom="true">                            android:id="@+id/btn_cancel"                android:layout_width="0dp"                android:layout_height="match_parent"                android:layout_weight="1"                android:gravity="center"                android:text="取消"                android:textSize="16sp"                android:textColor="#262626"                android:background="#fff"/>                            android:id="@+id/btn_ok"                android:layout_width="0dp"                android:layout_height="match_parent"                android:layout_weight="1"                android:gravity="center"                android:text="确定"                android:textSize="16sp"                android:textColor="#fff"                android:background="#ff4c4c"/>            
3.在主界面生成验证码,并校验验证码的正确和错误,RegisterActivity.java:

public class RegisterActivity extends Activity implements View.OnClickListener {    private Button btn_cancel;//取消    private EditText et_login_account;//账号    private EditText et_login_password_ok;//密码    private EditText et_code;//验证码    private Button btn_ok;//确定    private ImageView iv_code;    private String realCode;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_register);        initView();    }    private void initView() {        btn_cancel = (Button) findViewById(R.id.btn_cancel);        btn_cancel.setOnClickListener(this);        btn_ok = (Button) findViewById(R.id.btn_ok);        btn_ok.setOnClickListener(this);        et_login_account = (EditText) findViewById(R.id.et_login_account);        et_login_password_ok = (EditText) findViewById(R.id.et_login_password_ok);        et_code = (EditText) findViewById(R.id.et_code_companyRe);        iv_code = (ImageView) findViewById(R.id.iv_code);        iv_code.setOnClickListener(this);        //将验证码用图片的形式显示出来        iv_code.setImageBitmap(Code.getInstance().createBitmap());        realCode = Code.getInstance().getCode().toLowerCase();    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.iv_code://验证码                iv_code.setImageBitmap(Code.getInstance().createBitmap());                realCode = Code.getInstance().getCode().toLowerCase();                break;            case R.id.btn_cancel://取消                RegisterActivity.this.finish();                break;            case R.id.btn_ok://确定                String etCode=et_code.getText().toString().toLowerCase();                if (etCode.equals(realCode)){                    Intent intent=new Intent(RegisterActivity.this,WelcomeActivity.class);                    startActivity(intent);                }else {                    Toast.makeText(RegisterActivity.this,"验证码错误",Toast.LENGTH_SHORT).show();                }                break;        }    }}
到此验证码功能已完成!

更多相关文章

  1. android圆角ImageView的几种实现方式
  2. 2014-11-6Android学习------Android(安卓)仿真翻页效果实现-----
  3. android 绘图--简单手写绘图后保存为图片(demo)
  4. Android(安卓)Widget开发系列(二)
  5. 【Android】第三方QQ账号登录的实现
  6. 个人帐号密码信息管理(PAPIM)软件构想
  7. Android(安卓)-- handler消息传送机制
  8. IOS 5编程 -2 -准备工作。
  9. Android(安卓)自定义模拟时钟控件

随机推荐

  1. Android(安卓)4.0源码编译错误
  2. Android(安卓)监控网络状态
  3. Android(安卓)读写文件整理
  4. How to build Android(安卓)Windows SDK
  5. Android(安卓)沉浸式全屏(StatusBar,Navig
  6. Android(安卓)XUtils的cookie
  7. android 传感器
  8. android editText 输入字数限制
  9. Android获取基站坐标代码
  10. Android(安卓)ArrayAdapter的使用