Android generated random verification code technology

Source: Internet
Author: User
Tags drawtext

in the development of Android client application, SMS Verification code or random verification code is often required to limit the user's operation or authentication. SMS verification code is to authenticate users, mainly through the HTTP protocol and other communication protocols, the random verification code is to restrict or prompt the user related operations. There are two main ways to verify random verification code: Request Server Authentication, local authentication . For example, when a user sends a login request to the server, we limit the user to pressing the request button randomly by random verification code (local authentication), as shown below:  Source Combat (1) Src/.../createcode.java Features: Use the random, Canvas, paint, and related methods to create a bitmap with 4 display styles and different characters in the location.
Package Com.example.randomcode;import Java.util.random;import Android.graphics.bitmap;import Android.graphics.bitmap.config;import Android.graphics.canvas;import Android.graphics.color;import android.graphics.paint;/** * Project name/version number: randomcode/v1.0 * Package Name: Com.example.randomcode * Class Description: (1) generate a set of random numbers; * (2) Set the random number style, and draw the Canvas.drawtext () on the bitmap () on the bitmap * (3) To draw the style change of the line of interference lines * created by: Jiangdongguo * Created: 2015-6-6 3:22:41 * Blog Address:/http blog.csdn.net/u012637501 */public class Createcode {private static final char[] CHARS = {' 1 ', ' 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 '}; Reserved random number library private static final int codelength = 4; Random number of private static final int linenumber = 8; Number of lines private static final int WIDTH =140, HEIGHT = 80; Bitmap long, wide private static final int FontSize = 40; Random number body size private static int base_padding_left; private static final int random_padding_left = Base_padding_top = Random_padding_top = 10;  private static random random = new random (); /********************************************************************************* * Method Name: CreateRandomBitmap * Function Description: Generate random Verification Code view * Data:2015-6-6[j] ******************************************************************************* **/public static Bitmap Createrandombitmap () {/** * (1) generates a set of random numbers * */String code = Createrandomtext ();//Generate 4 random numbers/* * * (2) Create bitmap Bitmap, canvas canvases, Initialize brush paint * */Bitmap Bitmap = Bitmap.createbitmap (WIDTH, HEIGHT, config.argb_8888);//Create Bitmap, and specify its long, wide canvas canvas = new canvas (bitmap); Create a canvas Canvas.drawcolor (color.white) that refers to a map; Sets the background of the canvas as white paint paint = new paint (); Define Brush Paint paint.settextsize (FontSize);  Set the brush font size/** * (3) generates four random numbers of different styles (color, position, shape) of the bitmap * */base_padding_left = 20; for (int i=0;i<code.length (); i++) {//Set a random number style int color = RaNdomcolor (); Paint.setcolor (color);   Set (brush) The color of the random number Paint.setfakeboldtext (false);//Set Brush to non-bold float skewx = Random.nextint (11)/10; Skewx = Random.nextboolean ()?   Skewx:(-skewx); Paint.settextskewx (SKEWX);//Set the font tilt direction (negative for right oblique, integer to left oblique)//Set a random number position//int padding_left = Base_padding_left +   Random.nextint (Random_padding_left);   int Padding_top =base_padding_top + random.nextint (random_padding_top);   Draw the random number Canvas.drawtext (Code.charat (i) + "", Base_padding_left, Padding_top, paint);  Base_padding_left + = Random_padding_left;  }/** * (4) Draw line **/for (int i=0;i<linenumber;i++) {mdrawline (canvas, paint);  } canvas.save (Canvas.all_save_flag);//Save Canvas.restore (); return bitmap;  }/********************************************************************************* * Method name: CreateRandomText * Function Description: * Data:2015-6-6[j] *********************************************************************************/private stat IC String Createrandomtext () {StringBuilder buffer =New StringBuilder ();  for (int i=0;i<codelength;i++) {buffer.append (Chars[random.nextint (chars.length));//chars subscript is limited to 0~codelength} return buffer.tostring (); Generate 4 Random Numbers}/******************************************************************************** * Method name: RandomColor * Function Description: Generate a random color * data:2015-6-6[j] ******************************************************************************** */private static int randomcolor () {int red = Random.nextint (256);//red: 0~256 between int green = Random.nextint (256);//green: 0 ~256 between int blue = Random.nextint (256); Blue: Return Color.rgb between 0~256 (red, green, blue);//return generate random color value}/***************************************************** * Method Name: Mdrawline * Function Description: Draw a line, parameters: current canvas, Current brush * Data:2015-6-6[j] ******************** /private static void Mdrawline (Canvas canvas,paint  Paint) {//a. Set the line color int color = Randomcolor ();  Paint.setcolor (color); B. Set theThe position of the random number (start and end, 0~width,0~height) int startX = Random.nextint (WIDTH);  int starty = Random.nextint (HEIGHT);  int stopx = Random.nextint (WIDTH);  int stopy = Random.nextint (HEIGHT); Canvas.drawline (StartX, Starty, stopx, stopy, paint); }}
Note: The key to creating a random character bitmap is to design each character's display position on the bitmap, and the characters will not appear on the bitmap if each character is displayed in the top, left, and right margins. Pay particular attention to the left and right margins of each character, with the following code:private static int base_padding_left;private static final int random_padding_left =base_padding_top = Random_padding_top = ten;base_padding_left = 20; The first character the left border distance of the bitmapfor (int i=0;i<code.length (); i++) {//Set this character to show the vertical position of the distance bitmapint padding_top =base_padding_top + random.nextint (random_padding_top); Canvas.drawtext (Code.charat (i) + "", Base_padding_left, Padding_top, paint);Base_padding_left + = Random_padding_left; Adjust the distance between the character and the previous character  } (2) Src/.../mainactivity.java function: Display the created bitmap in the ImageButton component of the interface layout
Package Com.example.randomcode;import Android.app.activity;import Android.os.bundle;import Android.view.View; Import Android.view.view.onclicklistener;import Android.widget.imagebutton;public class Mainactivity extends Activity {     @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate ( Savedinstancestate);        Setcontentview (r.layout.main);        Final ImageButton ImageButton = (ImageButton) Findviewbyid (r.id.myimage);        Imagebutton.setimagebitmap (Createcode.createrandombitmap ());        Imagebutton.setonclicklistener (New Onclicklistener () {public   void OnClick (View v) {             Imagebutton.setimagebitmap (Createcode.createrandombitmap ());}}  );}      }
(3) Res/layout/main.xml
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "Match_ Parent "    android:layout_height=" match_parent "    android:orientation=" vertical ">    <imagebutton        android:id= "@+id/myimage"        android:layout_width= "160DP"        android:layout_height= "80DP"        android: Layout_centerinparent= "true"/></linearlayou>
(4) Effect demonstration

Android generated random verification code technology

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.