安卓验证码的生成与验证
1.生成验证码
package com.medees.dazhima_android;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import java.util.Random;
/**
*
* Created by root on 14-7-10.
*
* 绘制注册界面验证码
*
*/
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', 'l', '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;
public static Code getInstance(){
if (bmpCode==null){
bmpCode=new Code();
}
return bmpCode;
}
private static final int DEFAULT_CODE_LENGTH = 4;
private static final int DEFAULT_FONT_SIZE = 25;
private static final int DEFAULT_LINE_NUMBER = 2;
private static final int BASE_PADDING_LEFT = 5, RANGE_PADDING_LEFT = 15, BASE_PADDING_TOP = 15, RANGE_PADDING_TOP = 20;
private static final int DEFAULT_WIDTH = 60, DEFAULT_HEIGHT = 40;
private int width=DEFAULT_WIDTH,height=DEFAULT_HEIGHT;
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;
//number of chars, lines; font size
private int codeLength = DEFAULT_CODE_LENGTH, line_number = DEFAULT_LINE_NUMBER, font_size = DEFAULT_FONT_SIZE;
//variables
private String code;
private int padding_left, padding_top;
private Random random = new Random();
//验证码图片
public Bitmap createBitmap() {
padding_left = 0;
Bitmap bp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bp);
code = createCode();
c.drawColor(Color.WHITE);
Paint paint = new Paint();
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 String createCode() {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < codeLength; i++) {
buffer.append(CHARS[random.nextInt(CHARS.length)]);
}
return buffer.toString();
}
private void drawLine(Canvas canvas, Paint paint) {
int color = randomColor();
int startX = random.nextInt(width);
int startY = random.nextInt(height);
int stopX = random.nextInt(width);
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);
}
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类型参数,负数表示右斜,整数左斜
// paint.setUnderlineText(true); //true为下划线,false为非下划线
// paint.setStrikeThruText(true); //true为删除线,false为非删除线
}
private void randomPadding() {
padding_left += base_padding_left + random.nextInt(range_padding_left);
padding_top = base_padding_top + random.nextInt(range_padding_top);
}
}
2.验证过程:
package com.medees.dazhima_android.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.medees.dazhima_android.Code;
import com.medees.dazhima_android.MainActivity;
import com.medees.dazhima_android.R;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* Created by root on 14-7-10.
*
* 用户注册界面
*
*/
public class RegisterActivity extends ActionBarActivity {
EditText editText_register_email;
EditText editText_register_name;
EditText editText_register_password;
EditText editText_register_password_agin;
EditText editText_register_code;
ImageView imageView_register_yanzhengma;
ImageView imageView_register_yanzhengma_refresh;
Button button_register;
String register_email;
String register_name;
String register_password;
String register_password_agin;
String register_code;
Code code;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
init();
imageView_register_yanzhengma.setOnClickListener( new Yanzhengma_Image_OnClickLister());
imageView_register_yanzhengma_refresh.setOnClickListener(new Yanzhengma_Image_OnClickLister());
button_register.setOnClickListener(new Register_OnClickLister());
ActionBar actionBar=getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.register_actionbar,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.home:{
finish();
Intent intent=new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
}return true;
case R.id.register:
new Register_OnClickLister();
}
return false;
}
private boolean CheckPassWordLength() {
if (register_password.length()<6)
return false;
else
return true;
}
private void InsertRegisterInfo(String register_email, String register_name, String register_password) {
}
private boolean CheckCode() {
if(register_code.equalsIgnoreCase(code.getInstance().getCode()))
return true;
else
return false;
}
private boolean CheckPassWordIsEqual() {
if(register_password.equals(register_password_agin))
return true;
else
return false;
}
private boolean CheckInputIsEmpty() {
if (TextUtils.isEmpty(register_email)||
TextUtils.isEmpty(register_name)||
TextUtils.isEmpty(register_password)||
TextUtils.isEmpty(register_password_agin)||
TextUtils.isEmpty(register_code))
return true;
return false;
}
public static boolean CheckIsEmail(String strEmail) {
String strPattern = "^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strEmail);
return m.matches();
}
private void getRegisterInfo() {
register_email=editText_register_email.getText().toString();
register_name=editText_register_name.getText().toString();
register_password=editText_register_password.getText().toString();
register_password_agin=editText_register_password_agin.getText().toString();
register_code=editText_register_code.getText().toString();
}
private void init() {
editText_register_email=(EditText)findViewById(R.id.registerActivity_email);
editText_register_name=(EditText)findViewById(R.id.registerActivity_name);
editText_register_password=(EditText)findViewById(R.id.registerActivity_password);
editText_register_password_agin=(EditText)findViewById(R.id.registerActivity_rePassword);
editText_register_code=(EditText)findViewById(R.id.register_yanzhengma_code);
imageView_register_yanzhengma=(ImageView)findViewById(R.id.register_yanzhengma_image);
imageView_register_yanzhengma_refresh=(ImageView)findViewById(R.id.register_yanzhengma_refresh);
button_register=(Button)findViewById(R.id.register_button);
imageView_register_yanzhengma.setImageBitmap(code.getInstance().createBitmap());
System.out.println("验证码:" + code.getInstance().getCode());
}
private class Yanzhengma_Image_OnClickLister implements View.OnClickListener {
@Override
public void onClick(View v) {
imageView_register_yanzhengma.setImageBitmap(code.getInstance().createBitmap());
System.out.println("验证码:"+code.getInstance().getCode());
}
}
private class Register_OnClickLister implements View.OnClickListener {
@Override
public void onClick(View v) {
getRegisterInfo();
if(CheckInputIsEmpty()){
Toast.makeText(RegisterActivity.this,"不能为空!",Toast.LENGTH_SHORT).show();
}
else {
if (CheckIsEmail(register_email)) {
if (CheckPassWordLength()) {
if (CheckPassWordIsEqual()) {
if (CheckCode()) {
Toast.makeText(RegisterActivity.this, "注册成功!", Toast.LENGTH_SHORT).show();
InsertRegisterInfo(register_email, register_name, register_password);
} else
Toast.makeText(RegisterActivity.this, "验证码输入错误,请您重新输入!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(RegisterActivity.this, "两次输入的密码不相同,请您重新输入!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(RegisterActivity.this, "密码必须大于6个字符!", Toast.LENGTH_SHORT).show();
}
}
else
Toast.makeText(RegisterActivity.this, "请输入正确的邮箱!", Toast.LENGTH_SHORT).show();
}
}
}
}