The realization method of acquiring and reading short message verification code by Android _android

Source: Internet
Author: User
Tags gettext numeric value stub throwable

Today, verification code is very common on Android clients. Register the application account information directly through the mobile account and the authentication code. Many applications are registered in this way. A brief introduction.

Android to get SMS verification code is relatively simple, through the mob official website provided by the SHARESDK, call the internal method, you can get to the text of the verification code. Provide the mob's official website address. http://www.mob.com/#/ After registering the relevant information on the official website, download the relevant jar package and the. So file to obtain the SMS authentication code (the version before 2.0 needs to download the jar package and the. so file, and now version 2.2 does not need to download the. So file anymore, by loading Smssdk.jar, Mobcommons.jar,mobtools.jar packages can be used directly. I don't explain how to sign up.

The final registration style is like this. Let's look at the concrete implementation.

1. How to obtain the SMS authentication code.

First, the SDK needs to be initialized, and the first thing a third party has to do is initialize the SDK. It is generally done in the OnCreate () function.

@Override
 protected void onCreate (Bundle savedinstancestate) {
 super.oncreate (savedinstancestate);
 Setcontentview (r.layout.activity_main);
 Init ();
 SMSSDK.INITSDK (This, Appkey, Appsecret);
 EventHandler eh = new EventHandler () {

  @Override public
  void afterevent (int event, int result, Object data) {
  msg = new Message ();
  Msg.arg1 = event;
  MSG.ARG2 = result;
  msg.obj = data;
  Handler.sendmessage (msg);
  }

 ;
 Smssdk.registereventhandler (EH);
 }

This is an operation that must be done, otherwise the subsequent things will not be completed. INITSDK (context context,string appkey,string Appsecret), initialization needs to pass the context object, As well as the key and secret we applied for. And here defines a eventhandler, used for verification when the message to the main thread of the handler, let the main thread to do some related operations to inform the user verify the situation in the end.

Ii. invoking the Smssdk.getverificationcode (string,string) method

After initializing the SDK, we can get our captcha by using the Getverificationcode () method.

/**
 * @param the area code of the string phone number such as
 * @param string specific phone number
/Smssdk.getverificationcode ("86", Phoneed.gettext (). toString ());

When we call the method, we need to pass the area code of our cell phone number and the specific cell phone number. Since China is 86 in the beginning. So the area code passed is 86, and in addition to its own phone number can be called through the network method to obtain the relevant authentication code.

Iii. Verify that the verification code we have entered is consistent with the verification code sent over.

When the verification code is sent over, the client generally needs to input, but here needs a validation process to determine the current user input and the authentication code sent to the same.

Smssdk.submitverificationcode (""), Phone, Codeed.gettext (). toString ());
validation is done by calling the Submitverificationcode () method. You need to pass the area code, phone number, and the numeric value of the verification code we entered. The process of verification is done by SHARESDK. Therefore, there is no need to perform too many complex operations. When we pass the same number as the value sent, the validation succeeds, or the validation fails.

This can be done on our client software through this authentication method to complete the registration function. When the validation is successful, you can enter the new interface, and if the validation fails, you need to confirm the input verification code. This will enable verification code validation for the application.

In general, we just need to look through the text message, then the relevant verification code can be submitted, but there are some other applications more user-friendly, when the verification code information sent to the inside of the phone directly to obtain the relevant verification code, and then directly add in the need to verify the place, so very convenient, It also prevents users from entering errors. Then this involves reading the relevant content of the text message.

Iv. Adding related permissions

 <uses-permission android:name= "Android.permission.READ_CONTACTS"/>
 <uses-permission android:name= " Android.permission.READ_PHONE_STATE "/>
 <uses-permission android:name=" android.permission.WRITE_ External_storage "/>
 <uses-permission android:name=" Android.permission.ACCESS_NETWORK_STATE "/>"
 <uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/>
 <uses-permission android: Name= "Android.permission.INTERNET"/>
 <uses-permission android:name= "Android.permission.RECEIVE_SMS"/ >
 <uses-permission android:name= "Android.permission.GET_TASKS"/>
 <uses-permission android: Name= "Android.permission.ACCESS_FINE_LOCATION"/>

So how to get the relevant content of SMS?

2. How to get the relevant content of the SMS just received.

In general, the validation of SMS is sent directly to the user in the form of a new text message, then the application will need to have the relevant listening event if it thinks of reading the short content just received. I do this by using Contentobserver. By using this class, you can capture a specific URI to make the database change. And then to do some related processing.

So we can do this, by inheriting the Contentobserver class, rewriting the internal onchange method, setting the specific URI so that our class can listen for changes in the SMS data so our application knows when the text message arrives. So, after the text arrives, We get the message content, and then read the contents of the Verification code information on it.

 private class Smsobserver extends Contentobserver {public smsobserver (Handler handle
   R) {super (handler);
   The TODO auto-generated constructor stub}/** *uri.parse ("Content://sms/inbox") represents a listener's Uri for the received SMS. */@Override public void OnChange (Boolean selfchange) {//TODO auto-generated method stub StringBuilder sb = NE
   W StringBuilder ();
      Cursor Cursor = Getcontentresolver (). Query (Uri.parse ("Content://sms/inbox"), NULL, NULL, NULL, NULL);
   Do not use a while loop here. We just need to get the SMS data that is currently sent.
   Cursor.movetonext (); Sb.append ("body=" + cursor.getstring (Cursor.getcolumnindex ("body"));
   Gets the entity data for the SMS content. Pattern pattern = Pattern.compile ("[^0-9]");
   The regular expression.
   Matcher Matcher = Pattern.matcher (sb.tostring ());
   Codetext = Matcher.replaceall (""); Codeed.settext (Codetext);
   Changes the contents of the control that entered the validation code. Cursor.close ();
   Closes the cursor pointer.
  Super.onchange (Selfchange); }
 }  

The way to implement the class, such as, by rewriting the OnChange method for subsequent operations, where the cursor can be the current SMS database to find the data, where the cursor pointer do not use the while loop, because the verification code this message is used with the hair, We also just need to get the relevant content in the current message of the CAPTCHA, and if cursor uses a while loop, it will read everything in the message. That's not what we want.

When we get to the specific content of the text, we can use regular expressions to match the number of SMS content, and then we can get the code data. The general idea is such a situation. At the same time we need to add relevant user rights.

 <uses-permission android:name= "Android.permission.RECEIVE_SMS"/>
 <uses-permission android:name= " Android.permission.READ_SMS "/>

After completing the above steps, we need to get the Contentresolver instance and register the Contentobserver.

Getcontentresolver (). Registercontentobserver (Uri.parse ("Content://sms"), True, new Smsobserver (New Handler ());
Registration We need to pass the relevant URI, the second parameter determines the way to match the URI, if set to True, then indicates an inaccurate match, then it means that if the URI is a class, it will be matched to, if set to false, Then we can only match the URI we pass in, the so-called exact match. The last object needs to pass an instance of a subclass, and it needs to pass the handler object. So we can update the UI in this way.

When we do not need to use the contentobserver, we only need to log off the registration is OK.

In contrast, verification code information is generally less content, if the content is more complex, and then there are other additional digital information, then we use regular expressions when the need for relevant optimization.

Last previous source code:

Package com.example.sms;
Import Java.util.regex.Matcher;

Import Java.util.regex.Pattern;

Import Org.json.JSONObject;
Import Cn.smssdk.EventHandler;
Import Cn.smssdk.SMSSDK;
Import Cn.smssdk.utils.SMSLog;
Import android.app.Activity;
Import Android.database.ContentObserver;
Import Android.database.Cursor;
Import Android.net.Uri;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.text.TextUtils;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.EditText;

Import Android.widget.Toast;
 public class Mainactivity extends activity implements Onclicklistener {private Button getcode;

 Private Button Identity;
 Private EditText phoneed;
 Private EditText codeed;
 Private String Appkey = "110EE66F30B40";
 Private String Appsecret = "85ec67aed1b89e3ec73f37b8b89f5142";

 public String phone;

 Private String Codetext; Private Handler Handler = new Handler () {@Override PubLIC void Handlemessage (Message msg) {//TODO auto-generated Method Stub super.handlemessage (msg);
   int event = MSG.ARG1;
   int result = MSG.ARG2;
   Object data = Msg.obj; if (result = = Smssdk. Result_complete) {if (event = = Smssdk. Event_submit_verification_code) {Toast.maketext (Getapplicationcontext (), "Commit authentication code succeeded", Toast.length_short). Show (
    ); else if (event = = Smssdk. Event_get_verification_code) {//Verified Toast.maketext (Getapplicationcontext (), "Verify code has been sent", Toast.length_sh
    ORT). Show ();
    } else {int status = 0;
     try {(throwable) data). Printstacktrace ();

     Throwable throwable = (throwable) data;
     Jsonobject object = new Jsonobject (Throwable.getmessage ());
     String des = object.optstring ("detail");
     Status = Object.optint ("status"); if (!
      Textutils.isempty (des)) {Toast.maketext (Mainactivity.this, DES, Toast.length_short). Show ();
     Return The catch (Exception e) {SMSlog.getinstance (). W (e);

 }
   }
  }

 };
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  Init ();
  SMSSDK.INITSDK (This, Appkey, Appsecret); EventHandler eh = new EventHandler () {@Override public void afterevent (int event, int result, Object data) {M
    Essage msg = new Message ();
    Msg.arg1 = event;
    MSG.ARG2 = result;
    Msg.obj = data;
   Handler.sendmessage (msg);
  }

  };
 Smssdk.registereventhandler (EH);
  private void Init () {GetCode = (Button) Findviewbyid (R.id.getcode);
  Identity = (Button) Findviewbyid (r.id.indentity);
  Phoneed = (edittext) Findviewbyid (r.id.phoneed);
  Codeed = (edittext) Findviewbyid (R.id.code);
  Getcode.setonclicklistener (this);
 Identity.setonclicklistener (this);
   Private class Smsobserver extends Contentobserver {public smsobserver (Handler Handler) {super (Handler);
 TODO auto-generated Constructor stub @Override public void OnChange (Boolean selfchange) {//TODO auto-generated method stub StringBuilder SB = N
   EW StringBuilder ();
   Cursor Cursor = Getcontentresolver (). Query (Uri.parse ("Content://sms/inbox"), NULL, NULL, NULL, NULL);
   Cursor.movetonext ();

   Sb.append ("body=" + cursor.getstring (Cursor.getcolumnindex ("body"));
   System.out.println (Sb.tostring ());
   Pattern pattern = Pattern.compile ("[^0-9]");
   Matcher Matcher = Pattern.matcher (sb.tostring ());
   Codetext = Matcher.replaceall ("");
   Codeed.settext (Codetext);
   Cursor.close ();
  Super.onchange (Selfchange); @Override public void OnClick (View v) {//TODO auto-generated Method Stub switch (V.getid ()) {case R.ID.G
   Etcode://Get the verification code process. if (! Textutils.isempty (Phoneed.gettext (). toString ())) {Getcontentresolver (). Registercontentobserver (Uri.parse ("cont
    Ent://sms "), True, new Smsobserver (New Handler ())); Smssdk.getverificationcode (""), Phoneed.gettext (). tostring ());

   Phone = Phoneed.gettext (). toString ();
   else {toast.maketext (mainactivity.this, "phone number cannot be empty", Toast.length_long). Show ();
  } break;
   Case R.id.indentity:smssdk.submitverificationcode (""), Phone, Codeed.gettext (). toString ());
  Break
  } protected void OnDestroy () {Smssdk.unregisteralleventhandler ();
 Getcontentresolver (). Unregistercontentobserver (new Smsobserver (handler));
};

 }

This will be able to complete a simple through the use of SMS Verification code to achieve validation, in the general project, we can according to the specific requirements of the relevant improvement, In short same ideas are basically the same. Of course, in determining whether there are text messages can also use Broadcasereceiver to achieve, but I read some of the relevant resources on the Internet, I have tried, Not realized. It's not as easy as contentobserver.

SOURCE Download:android Access and read SMS verification code

The above is the Android acquisition and read SMS authentication Code implementation method, I hope to learn about Android software programming help.

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.