Android Random Generation Verification Code _android

Source: Internet
Author: User

Android randomly generates CAPTCHA code, Android uses random numbers to draw irregular verification code, which strengthens the security of user login or registration.
The specific ideas are as follows:
On a fixed-width canvas, draw a fixed number of random digits and letters, and then draw the disturbing line of the number of fixed bars
Random numbers and noise lines are randomly generated and random numbers are randomly generated.

The interface effect is as follows:

1, generate random number code, Code.java:

public class Code {//random number array 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; 
  public static Code getinstance () {if (Bmpcode = = null) Bmpcode = new Code (); 
 return bmpcode; 
 //default Settings//captcha default number of random numbers private static final int default_code_length = 4; 
 Default font size private static final int default_font_size = 25; 
 Number of default line bars private static final int default_line_number = 5; PADDING value private static final int base_padding_left = ten, Range_padding_left =, Base_padding_top =, Range_paddin 
 G_top = 20; 
 
 The default width of the verification code is high private static final int default_width = Default_height = 40; Settings decided by the layout XML//canvas width and height private int width = default_width, 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; 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 (); 
 
  Verify code Picture public Bitmap CreateBitmap () {padding_left = 0; 
  Bitmap BP = bitmap.createbitmap (width, height, config.argb_8888); 
 
  Canvas C = new Canvas (BP); 
 
  Code = Createcode (); 
  C.drawcolor (Color.White); 
  Paint Paint = new Paint (); 
  Paint.setantialias (TRUE); 
  Paint.settextsize (font_size); 
   Draw verification code for (int i = 0; i < code.length (); i++) {Randomtextstyle (paint); 
   Randompadding (); C. DrawText (Code.charat (i) + "", Padding_left, Padding_top, paint); 
  ///Draw line for (int i = 0; i < Line_number i++) {drawLine (c, paint); 
 C.save (Canvas.all_save_flag);//Save C.restore ();//return BP; 
 Public String GetCode () {return code; 
  //Generate Authenticode Private String Createcode () {StringBuilder buffer = new StringBuilder (); 
  for (int i = 0; i < codelength i++) {buffer.append (Chars[random.nextint (chars.length))); 
 return buffer.tostring (); 
  ///Draw interference line 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); 
 ///Generate random colors 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); 
  ///randomly generate text style, color, thickness, gradient private void Randomtextstyle (Paint Paint) {int color = Randomcolor (); 
  Paint.setcolor (color); Paint.setfakeboldtext (Random.nextboolean ()); 
  True is bold and false is not bold float skewx = Random.nextint (11)/10; Skewx = Random.nextboolean ()? 
  SKEWX:-skewx; Paint.settextskewx (SKEWX); Float type parameter, negative number indicates right oblique, integer left oblique//paint.setunderlinetext (true); True is an underscore, false is not an underscore//paint.setstrikethrutext (true); True is strikethrough, false is not strikethrough}//randomly generated padding value private void randompadding () {padding_left + = Base_padding_left + random. 
  Nextint (Range_padding_left); 
 Padding_top = Base_padding_top + random.nextint (range_padding_top); 
 } 
}

2, writing layout files, activity_main.xml:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" "Vertical" & 
 
 Gt <relativelayout android:layout_width= "match_parent" android:layout_height= "50DP" android:background= "@color/ma In_color_white "> <textview android:id=" @+id/tv_title "android:layout_width=" Wrap_content "Android:la" yout_height= "Wrap_content" android:layout_centerinparent= "true" android:text= "Retrieve password" android:textcolor= "@color Loan_butbackground "android:textsize=" 20sp "/> </RelativeLayout> <linearlayout Android:layout_wid 
  Th= "Match_parent" android:layout_height= "40DP" android:layout_margintop= "30DP" android:orientation= "vertical" android:layout_marginleft= "15DP" android:layout_marginright= "15DP" android:background= "@drawable/security_code_ BG "> <linearlaYout android:layout_width= "match_parent" android:layout_height= match_parent "android:gravity=" center_vertical "android:orientation=" Horizontal "> <textview android:layout_width=" wrap_content "android:layou t_height= "Wrap_content" android:layout_marginleft= "20DP" android:layout_marginright= "20DP" android:text= "China 
    +86 "android:textcolor=" #A2CD5A "android:textsize=" 16sp "/> <view android:layout_width=" 0.1DP " 
    android:layout_height= "Match_parent" android:background= "@color/loan_butbackground"/> <EditText Android:id= "@+id/et_forgetpass_phonenum" android:layout_width= "match_parent" android:layout_height= "Wrap_conte" NT "android:layout_marginleft=" 20DP "android:background=" "@null" android:digits= "0123456789" Android:hi Nt= "Please fill in your mobile number" Android:inputtype= "No." Android:maxlength= "one" android:textsize= "16sp"/> </linea Rlayout> </linearlayout> <linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:layout_marginleft= "15DP" android:layout_marginright= "15DP" android:layout_margintop= "20DP" Android:orie 
   ntation= "Horizontal" > <linearlayout android:layout_width= "wrap_content" android:layout_height= "40DP" android:background= "@drawable/security_code_bg" > <edittext android:id= "@+id/et_phonecodes" Andro Id:layout_width= "Match_parent" android:layout_height= "match_parent" android:layout_marginleft= "10DP" Androi 
 
  d:layout_marginright= "10DP" android:background= "@null" android:hint= "Please enter the right verification code"/> </LinearLayout> 
   <imageview android:id= "@+id/iv_showcode" android:layout_width= "100DP" android:layout_marginleft= "10DP" android:layout_height= "Match_parent"/> </LinearLayout> <button android:id= "@+id/but_forgetpas" S_tosetcodes "Android: layout_width= "match_parent" android:layout_height= "wrap_content" android:layout_margin= "20DP" Android:background = "@drawable/buttonshape" android:text= "Submit authentication Code" android:textcolor= "@color/main_color_white"/> </linearlayout 

 >

3, generating random numbers in the main interface, verifying Authenticode mainactivity.java:

public class Mainactivity extends activity implements Onclicklistener {public static final String TAG = mainactivity.c 
 Lass.getname (); 
 Private ImageView Iv_showcode; 
 Private EditText Et_phonecode; 
 Private EditText Et_phonenum; 
 
 The generated verification code private String Realcode; 
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
 
  Setcontentview (R.layout.activity_main); 
  Et_phonecode = (edittext) Findviewbyid (r.id.et_phonecodes); 
  Button But_tosetcode = (button) Findviewbyid (r.id.but_forgetpass_tosetcodes); 
  But_tosetcode.setonclicklistener (this); 
  Iv_showcode = (ImageView) Findviewbyid (R.id.iv_showcode); 
  Display the verification code in the form of a picture Iv_showcode.setimagebitmap (Code.getinstance (). CreateBitmap ()); 
  Realcode = Code.getinstance (). GetCode (). toLowerCase (); 
 Iv_showcode.setonclicklistener (this); @Override public void OnClick (View v) {switch (V.getid ()) {case R.id.iv_showcode:iv_showcode.setima Gebitmap (code.geTinstance (). CreateBitmap ()); 
    Realcode = Code.getinstance (). GetCode (). toLowerCase (); 
    LOG.V (TAG, "Realcode" +realcode); 
   Break 
    Case R.id.but_forgetpass_tosetcodes:string Phonecode = Et_phonecode.gettext (). toString (). toLowerCase (); 
    String msg = "Generated authentication code:" +realcode+ "The Authentication Code entered:" +phonecode; 
 
    Toast.maketext (Mainactivity.this,msg,toast.length_long). Show ();  
    if (Phonecode.equals (Realcode)) {Toast.maketext (mainactivity.this, Phonecode + "Verify code correct", Toast.length_short). Show (); 
    else {toast.maketext (mainactivity.this, Phonecode + "validation code error", Toast.length_short). Show (); 
  } break; 
 } 
 } 
}

At this point, the basic function has been realized, source download: Http://xiazai.jb51.net/201611/yuanma/AndroidSecurityCode (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.