Android Development--easy implementation of local verification code (prevent brute force login)

Source: Internet
Author: User

0. Preface

Verification code everywhere, someone asked me, you know what is under the Da Vinci Code, yes, the answer is the Da Vinci verification Code.

Verification Code One of the most important role is to prevent malicious violence to log in, to prevent uninterrupted login attempts, some people say that the terminal can actually be on the server to log on the interval detection, if the interval is too short to show the attitude of rejection. However, the local code function is more real, can reduce the pressure on the server side. This article will use a custom View to implement a simple local verification code with the following effect. It's a review of your custom View knowledge.



1. Layout structure

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:myattribute= "http// Schemas.android.com/apk/res-auto "android:layout_width=" match_parent "android:layout_height=" Match_parent "> & Lt;com.calvin.verification_code. MyView android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_center        Inparent= "true" android:padding= "10DP" myattribute:text= "0 0 0 0" myattribute:textcolor= "#000" Myattribute:textsize= "40SP" android:id= "@+id/myview"/> <edittext android:layout_width= "Wrap_cont Ent "android:layout_height=" wrap_content "android:inputtype=" number "android:hint=" after refresh enter "Android        oid:layout_below= "@+id/myview" android:layout_centerhorizontal= "true" android:layout_margintop= "20DP"        Android:id= "@+id/edittext"/> <button android:text= "confirm" android:layout_width= "wrap_content" Android:layout_height= "Wrap_content" android:layout_alignbottom= "@+id/edittext" android:layout_alignparentend= "Tru E "android:layout_marginend=" 10DP "android:id=" @+id/button "/></relativelayout>

in the custom control MyView The use of custom properties in the interview, occasionally will be asked, in fact, it is not difficult. This uses three custom attributes, text content, color, and font size. Namespaces don't forget to add.

custom attribute declarations only need to be Values the directory declares a XML files can be. The name of the file is not important, it is important that this name attribute, because we will Find this custom attribute declaration information in the custom control class through R.styleable.myview.

<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "MyView" >        <attr name= "Text" format= "string"/>        <attr name= "textcolor" format= "color"/> <attr name=        " Textsize "format=" Dimension "/>    </declare-styleable></resources>


2. custom View class

Take a look at the constructor of this class:

Public MyView (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle);        TypedArray a = Context.obtainstyledattributes (Attrs, R.styleable.myview);            for (int i = 0; i < A.getindexcount (); i++) {int attr = A.getindex (i);                    Switch (attr) {Case r.styleable.myview_text:mtext = a.getstring (attr);                Break Case R.styleable.myview_textcolor://Two parameter is the default color Mtextcolor = A.getcolor (attr, Color.bla                    CK);                Break Case r.styleable.myview_textsize://default font size is 16sp,typevalue convert sp to px mtextsize = A.get                                    Dimensionpixelsize (attr, (int) typedvalue.applydimension (typedvalue.complex_unit_sp,                    Getresources () getdisplaymetrics ());            Break        }} a.recycle (); Mpaint = new Paint ();        Mpaint.settextsize (mtextsize);        Mbound = new Rect ();        Get the width and height of the drawn text mpaint.gettextbounds (mText, 0, Mtext.length (), mbound);                This.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {                Generates a random four-digit number and sends a custom broadcast MText = Randomtext ();            Postinvalidate ();    }        }); }

The core code is to parse the custom attribute, initialize a brush, and set the parsed font size to the brush, design the click Time, make it randomly generate four digit verification code after clicking, and use postinvalidate () refresh the interface. Finally, use mbound to record the width and height of this four-digit text.

2. customizing Other details in the View class

@Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {int width = 0;        int height = 0;        int specmode = Measurespec.getmode (Widthmeasurespec);        int specsize = measurespec.getsize (Widthmeasurespec); Switch (specmode) {Case MeasureSpec.EXACTLY:width = getpaddingleft () + getpaddingright () + SPE                CSize;            Break                Case MeasureSpec.AT_MOST:width = getpaddingleft () + getpaddingright () + mbound.width ();        Break    }//Same logic handles high setmeasureddimension (width, height);}        @Override protected void OnDraw (canvas canvas) {mpaint.setcolor (color.yellow);        Canvas.drawrect (0, 0, getmeasuredwidth (), Getmeasuredheight (), mpaint);        Mpaint.setcolor (Mtextcolor);        Canvas.drawtext (MText, getwidth ()/2-mbound.width ()/2, GetHeight ()/2 + mbound.height ()/2, mpaint);        Random random = new random (); for (int i = 0;I <= 3;            i++) {int temp = Random.nextint (colors.length);            Mpaint.setcolor (Colors[temp]);            Mpaint.setstrokewidth (3);        Canvas.drawline (Randomstartwidth (), Randomstartheight (), Randomendwidth (), Randomendheight (), mPaint); }    }

In fact, the main or Measure and the Draw of the process.

in the onmeasure () The most important logic in the method is to handle Measurespec.at_most This is the case, when the front mbound.width () it worked. There is the case that padding is handled manually regardless of the measurement mode .

OnDraw () method, a yellow rectangle is first drawn as the custom View background, then draws four digits according to the text content and color of the custom attribute, and draws four noise lines, the color is random, and the starting and ending positions are randomly generated.

3. Correct verification code for real-time change of maintenance

in order to verify the correctness of the verification code entered by the user, the mainactivity to maintain a variable in the user click on the custom View The value of this variable can be changed in real time when the verification code is refreshed. Here, using a custom broadcast implementation, a random four-bit number is generated, sending a custom broadcast.

Intent Intent = new Intent () intent.setaction ("Com.seu_calvin.update"); Intent.putextra ("Data", sb.tostring ()); GetContext (). Sendbroadcast (Intent);

then in mainactivity register a broadcast receiver to obtain the verification code information at this time, after the user clicks the OK button to get EditText to compare the values in the. This logic is still relatively simple.

The author level is limited, if the question or the mistake please many message exchanges. Reprint Please specify source: http://blog.csdn.net/seu_calvin/article/details/70156547.

Android Development--easy implementation of local verification code (prevent brute force login)

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.