Detailed Android login That's the point _android

Source: Internet
Author: User
Tags gettext http request xmlns

With the rapid development of the Internet, an application to protect the privacy of users, usually by setting the user name + Password authentication method to ensure the relative security of user privacy, I know the general Web site login verification, usually set a two-dimensional code, through the verification of two-dimensional code, to prevent malicious software through the mechanical program, the user password to crack, So how does an Android device implement this functionality? I believe many developers are dismissive of this, because this increases the user's use of complexity, many software is not the design, now we do not talk about it is not useful, today we focus on how to implement this feature on Android devices. This article for you to introduce the content includes: 1, the user repeatedly wrong password, increase verification code verification; 2. How Android communicates with the server via HTTP requests. All right, now let's start with the introduction of today's content, first of all, we will learn how to achieve the user multiple consecutive wrong password, increase the authentication code function.

Now that you are using two-dimensional code, how does Android generate a two-dimensional code? To provide you with a class that generates two-dimensional code:

Generate two-dimensional code class public class Bputil {/** * The character used to generate the two-dimensional code * * Private static final char[] CHARS = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ' , ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' j ', ' K ', ' m ', ' l ', ' n ', ' o ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' W ', ' x ', ' y ', ' z ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' M ', ' L ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' x '
 , ' Y ', ' Z '};
 private static Bputil Bputil;
  public static Bputil getinstance () {if (Bputil = null) Bputil = new Bputil ();
 return bputil; }//Width= "height="//base_padding_left= "5"//range_padding_left= "ten"//base_padding_top= "/RA Nge_padding_top= "Ten"//codelength= "4"//line_number= "3"//font_size= ""//default settings private static FINA
 l int default_code_length = 4;
 private static final int default_font_size = 20;
 private static final int default_line_number = 3;
 private static final int base_padding_left = 5, Range_padding_left = ten, Base_padding_top =, range_padding_top = 10; private static final int default_width =, default_height = 30; Settings decided by the layout XML//canvas width and height private int width = default_width, height = Default_heigh 
 T 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 ();
  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.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);//Save C.restore ();//return BP;
 Public String GetCode () {return bputil.createcode ();
  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 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 to underline, false to not paint.setstrikethrutext///(TRUE); True is strikethrough, false is not deleted} private void Randompadding () {padding_left + = Base_padding_left + random.nextint (range_padding
  _left);
 Padding_top = Base_padding_top + random.nextint (range_padding_top);

 }
}

The

has a two-dimensional code, below we start to design our function, here is a simple, we finally want to achieve the function: 1, user's normal input username + password login; 2, when the user has 3 consecutive wrong password, require the user must increase the verification code input verification. Here we start the functional design implementation, first of all our layout files:

<relativelayout 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 "Tools:context" = "${relativepackage}.${activityclass}" android:orientation= "vertical" > <linearlayout android:layout_width= " Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical "> <textview android:layout_ Width= "Wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "Center_horizontal" Android:text = "@string/yanzheng"/> <linearlayout android:orientation= "Horizontal" android:layout_width= "fill_parent" and roid:layout_height= "Wrap_content" > <textview android:layout_weight= "1" android:layout_width= "Wrap_conte" NT "android:layout_height=" Wrap_content "android:text=" @string/name "/> <edittext android:id=" @+id/nam E "android:layout_width=" Wrap_content "android:layout_weight= "6" android:layout_height= "Wrap_content" android:hint= "@string/name_new" true "/> </LinearLayout> <linearlayout android:orientation=" Horizontal "android:layout_width=" fill_p Arent "android:layout_height=" wrap_content "> <textview android:layout_weight=" 1 "android:layout_width = "Wrap_content" android:layout_height= "wrap_content" android:text= "@string/password"/> <edittext Oid:id= "@+id/pass" android:layout_weight= "6" "Android:layout_width=" Wrap_content "android:layout_height=" Wrap_c Ontent "android:hint=" @string/pass_new "android:singleline= true"/> </LinearLayout> <linearla Yout android:id= "@+id/layout_yanzhengma" android:visibility= "Gone" android:orientation= "Horizontal" android:layou T_width= "Fill_parent" android:layout_height= "wrap_content" > <textview android:layout_width= "wrap_content" "Android:layout_height= "Wrap_content" android:text= "@string/yanzhengma"/> <textview android:id= "@+id/rander" android:layou t_weight= "1" android:layout_width= "wrap_content" android:layout_height= "wrap_content"/> <EditText A Ndroid:id= "@+id/rander_input" android:layout_weight= "1" android:layout_width= "Wrap_content" Android:layout_hei ght= "Wrap_content" android:singleline= "true"/> </LinearLayout> <linearlayout Android:orientati on= "Horizontal" android:layout_width= "Fill_parent" android:layout_height= "wrap_content" > <Button Andro Id:id= "@+id/get" android:layout_weight= "1" "Android:layout_width=" Wrap_content "android:layout_height=" Wrap_conten T "android:text=" @string/get "/> <button android:id=" @+id/post "android:layout_weight=" 1 "android:l Ayout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "@string/post"/> </LinearLayou T> </linearlayouT> </RelativeLayout>
 

The content of the

focus is here, our main activity code, let's take a look at it:

public class Mainactivity extends activity {private TextView mytext = null;  Private EditText myname = null;//user name private EditText mypass = null;//password private edittext myrander = null;//Authentication Code Private Button Mygetbutton = null;//get Send http request private Button Mypostbutton = null;//post Way Send HTTP request private LinearLayout Myli NE = null;//Control two-dimensional code display private static int n = 0;//user error password count static string name = null;//User entered user name static string password  = null;//user entered password private string edit;//user input authentication code private string code;//authentication code @Override protected void OnCreate (Bundle
  Savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  MyText = (TextView) Findviewbyid (R.id.rander);
  MyName = (edittext) Findviewbyid (r.id.name);
  Mypass = (edittext) Findviewbyid (R.id.pass);
  Myrander = (edittext) Findviewbyid (r.id.rander_input);
  Mygetbutton = (Button) Findviewbyid (r.id.get);
  Mypostbutton = (Button) Findviewbyid (r.id.post); Myline = (linearlayout) FindviewbyId (R.ID.LAYOUT_YANZHENGMA);
  Mygetbutton.setonclicklistener (New Mygetbutton ());

 Mypostbutton.setonclicklistener (New Mypostbutton ());
   Class Mygetbutton implements onclicklistener{public void OnClick (View v) {name = Myname.gettext (). toString ();
   Password = Mypass.gettext (). toString ();
    if (n>=3) {//Three consecutive wrong password edit = Myrander.gettext (). toString ();
    Boolean boo = Captcha (code, edit); if (boo) {new Thread (new Runnable () {public void run () {final Boolean flag = Sendserver.getsave (name, p
       Assword); Runonuithread (New Runnable () {public void run () {if (flag) {Toast.maketext (mainactivity.this, "Logon succeeded",
          Toast.length_short). Show ();
         n=0;
          }else{Toast.maketext (mainactivity.this, "Login Failed", Toast.length_short). Show ();
          n++;
          if (n>=3) {myline.setvisibility (view.visible);
      }
         }
        }
       });
    }). Start (); }else{code = bputil.getinstance (). GetcoDe (). toLowerCase ()//Generate a new two-dimensional code mytext.settext (code);//show in front of the user}}else{new Thread (new Runnable () {Publ
      IC void Run () {final Boolean flag = sendserver.getsave (name, password); Runonuithread (New Runnable () {public void run () {if (flag) {Toast.maketext (mainactivity.this, "login
         Success ", Toast.length_short). Show ();
        n=0;
         }else{Toast.maketext (mainactivity.this, "Login Failed", Toast.length_short). Show ();
         n++;
          if (n>=3) {myline.setvisibility (1);
     Code = bputil.getinstance (). GetCode (). toLowerCase ();
         Mytext.settext (code);
     }
        }
       }
      });
   }). Start (); Class Mypostbutton implements onclicklistener{public void OnClick (View v) {name = Myname.gettext (). Tostri
   Ng ();
   Password = Mypass.gettext (). toString ();
     New Thread (New Runnable () {public void run () {final Boolean flag = sendserver.postsave (name, password); Runonuithread (NewRunnable () {@Override public void run () {if (flag) {Toast.maketext (mainactivity.this), "Logon succeeded",
        Toast.length_short). Show ();
       n=0;
        }else{Toast.maketext (mainactivity.this, "Login Failed", Toast.length_short). Show ();
        n++;
        if (n>=3) {myline.setvisibility (1);
    }
       }
      }
     });
  }). Start (); 
  @SuppressLint ("Showtoast") Private Boolean Captcha (string code, string edit) {Boolean flag = false;
  if (code.equals (edit)) {flag = true;
   }else {flag = false;
Toast.maketext (Mainactivity.this, "Validation code Error", 0). Show ();
  Imageview.setimagebitmap (bitmap);
 return flag;
  } protected void Onrestart () {Super.onrestart ();
 n=0;
  } protected void OnDestroy () {Super.ondestroy ();
 n=0;
 }
}

Here's a quick introduction to the code, because this is the next thing I want to share with you about Android sending get and post requests, where I've written two buttons, one that is validated by using a Get method, and one that is functionally consistent by using the Post method. Finally, please pay attention to: Red font part, the Red font part is we call the upper two-dimensional code generation class, generate two-dimensional code, and then display in the user interface. There is: Onrestart, OnDestroy are activity life cycle function, here will be N zero, convenient for our login experience again. All right, here we go. The first part is done, and here we begin to enter the lower part of our article.

About the Android server request, there are generally two ways: get, post two ways, then we begin to study together.

public class Sendserver {//get mode request public static Boolean Getsave (string name, String password) {Boolean flag = Fals
  E
  HttpURLConnection conn = null;
   try {//Prevent Chinese garbled String username = urlencoder.encode (name, "UTF-8");
   String userpassword = urlencoder.encode (password, "UTF-8"); URL url = new URL ("Http://10.20.90.3:8080/Register/ManageServlet?")
   + "Name=" +username+ "&password=" +userpassword);
   conn = (httpurlconnection) url.openconnection ();
   Conn.setrequestmethod ("get");
   Conn.setconnecttimeout (5000);
   Conn.setreadtimeout (5000);
   int responsecode = Conn.getresponsecode ();
    if (Responsecode =) {InputStream is = Conn.getinputstream ();
    String stu = Getstringfrominputstream (IS);
    if (stu.equals ("Login succeeded")) {flag = true;
  A catch (Malformedurlexception e) {e.printstacktrace ());
  catch (Exception e) {e.printstacktrace ();
 } finally{if (conn!= null) {conn.disconnect ();//Close Connection}} return flag; }//post Request PUblic Static Boolean Postsave (string name, String password) {Boolean flag = false;
  HttpURLConnection conn = null;
   try {URL url = new URL ("Http://10.20.90.3:8080/Register/ManageServlet?");
   conn = (httpurlconnection) url.openconnection ();
   Conn.setrequestmethod ("POST");
   Conn.setconnecttimeout (5000);
   Conn.setreadtimeout (5000);
   Post request parameter String data = "Name=" +name+ "&password=" +password;
   OutputStream out = Conn.getoutputstream ();
   Out.write (Data.getbytes ());
   Out.flush ();
Out.close ();
   Conn.setrequestproperty ("Content-length", 500),//content length set to 500; Request Header message format int respon = Conn.getresponsecode ();
    if (Respon =) {InputStream is = Conn.getinputstream ();
    String stu = Getstringfrominputstream (IS);
    if (stu.equals ("Login succeeded")) {flag = true;
  A catch (Exception e) {e.printstacktrace ());
   }finally{if (conn!= null) {conn.disconnect ();
 } return flag; }//Resolve request returned by service private static String GetstringfrominpuTstream (InputStream is) throws exception{bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
  byte[] buffer = new BYTE[1024*8];
  int len =-1;
  while (len = is.read (buffer))!=-1) {baos.write (buffer, 0, Len);
  } is.close ();

  String html = new string (Baos.tobytearray (), "GBK");//When receiving server-side data, prevent Chinese garbled characters from appearing.
  String html = baos.tostring ();
  Baos.close ();
 return HTML;
 }
}

Well, it's over, it's simple, everybody knows it. Novice learning, Master Exchange.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support 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.