Before talking about the knowledge point of SMS verification code in Android, let's first understand the aggregate data. Introduction to Aggregate Data Aggregate Data is a leading basic data API provider in China, specializing in Internet data services. It provides free safe, stable and efficient data in various fields, including weather query, air quality, map coordinates, financial funds, e-commerce price comparison, violation query, etc. Developers can try Aggregate Data API for free to quickly develop mobile apps, eliminating data collection, maintenance and other links, greatly reducing development cycles and costs. Therefore, we can use the set of things provided by Aggregate Data to add the SMS verification code function. First we need to do the preparation work. Using aggregated data is mainly divided into the following steps: Step 1: Register aggregate data Go to Juhe Data official website (https://www.juhe.cn/) to register an account. After completing the registration, go to "Personal Center" -> "My Data" and click on the application data as shown below: Step 2: Apply for Appkey After applying, you will get an Appkey, which is very important. Step 3: Download the SDK Download address: https://www.juhe.cn/juhesdk Step 4: Create a project and configure the environment 1. Create a project and copy the "armeabi file" and "smscaptcha_v_1_4.jar" under libs in the SDK we downloaded to the libs directory of our project 2. Add development key, required permissions and other information in AndroidManifest (1) Add the development key to the application - <meta-data
- android: name = "JUHE_KEY"
- android:value= "developer key" />
(2) Add required permissions - <uses-permission android: name = "android.permission.ACCESS_NETWORK_STATE" />
- <uses-permission android: name = "android.permission.INTERNET" />
- <uses-permission android: name = "android.permission.ACCESS_WIFI_STATE" />
- <uses-permission android: name = "android.permission.ACCESS_COARSE_LOCATION " />
- <uses-permission android: name = "android.permission.READ_FINE_LOCATION" />
- <uses-permission android: name = "android.permission.READ_PHONE_STATE" />
- <uses-permission android: name = "android.permission.READ_CONTACTS" />
(3) Initialize the Context global variable referenced by the SDK when the application is created At this step we have two methods ***Configure in Activity - public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // Initialize context information before using SDK components and pass it into ApplicationContext
- //Note that this method should be implemented before the setContentView method
- /**
- * Initialization method
- * @param context
- * @needFriends Whether the friend function is needed
- */
- CommonFun.initialize(getApplicationContext(), true );
- setContentView(R.layout.activity_main);
- }
- }
The following note is the advice given to us by the Aggregate Data document. It recommends that we put this initialization work in the Application, because the program will first run the method in the Application when it runs. Note: Before using each SDK component, you need to call CommonFun.initialize(getApplicationContext(),true);, so we recommend that this method be placed in the initialization method of the Application. So we follow the method it suggests instead of using the first method. In this way, we need to create an Applicaiton class MyApplication as follows - package com.example.android.sms;
-
- import com.thinkland.sdk.util.CommonFun;
-
- import android.app.Application;
-
- public class MyApplication extends Application {
-
- @Override
- public void onCreate() {
- super.onCreate();
- CommonFun.initialize(getApplicationContext(), false );
- }
- }
After declaring the Application, don't forget to configure it in the manifest file Okay, the environment has been configured. Let's verify whether we can receive text messages. The code of MainActivity is as follows - package com.example.android.sms;
-
- import com.thinkland.sdk.sms.SMSCaptcha;
- import com.thinkland.sdk.util.BaseData;
- import com.thinkland.sdk.util.CommonFun;
-
- import android.os.Bundle;
- import android.app.Activity;
- import android.util.Log;
- import android.view.Menu ;
- import android.widget.Toast;
-
- public class MainActivity extends Activity {
-
- protected static final String TAG = "MainActivity" ;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- setContentView(R.layout.activity_main);
- // Initialize the SMSCaptcha object. In this object, there is a method to send us a text message verification code.
- SMSCaptcha smsCaptcha=SMSCaptcha.getInstance();
- //Call the method to send SMS verification code, in which there is a callback
-
- /**
- phone mobile phone number
- callBack returns the result callback method.
- */
- smsCaptcha.sendCaptcha( "Enter your phone number here" ,new BaseData.ResultCallBack() {
-
- @Override
- public void onResult( int code, String reason, String result) {
-
- /*
- code: Return code:
- Server: 0 success; 1 error;
- Local: -2 Local network exception; -3 Server network exception; -4 Parsing error; -5 Initialization exception
- Reason: Return information success or error reason.
- result: Return result, in JSON format. It will be empty if there is an error or no return value.*/
-
- if(code==0){
- Log.i(TAG, "code=" +code);
- Log.i(TAG, "reason=" +reason);
- Log.i(TAG, "result=" +result);
- }
- }
- });
- }
- }
The returned results are as follows: Step 5: Implementation of complete functions and interface UI First, let's take a look at the interface. We enter the mobile phone number and the destination of the text message in this interface, and a dialog box will pop up after clicking Next. After clicking OK, the sendCaptcha method provided by the aggregated data will be called. - /*Click OK and call the sendCaptcha method to submit the mobile phone number to the server
- code(return code):
- Server: 0 success, 1 error;
- Local: -2 local network exception, -3 server network exception, -4 parsing error, -5 initialization exception.
- reason (return information): reason for success or error.
- result (return result): JSON format, empty if there is an error or no return value.
- */
- smsCaptcha.sendCaptcha(phone,new ResultCallBack() {
-
- @Override
- public void onResult( int code, String reason, String result) {
- closeDialog();
- if(code==0){
- afterCapterRequested();
- }
- }
-
- );
When the returned code==0, it means that the SMS verification code is sent successfully. We need to jump to the interface. The code is as follows - //When code=0 is successful, jump to the Activity for entering the verification code
- private void afterCapterRequested() {
- String phone=etPhoneNumber.getText().toString().trim().replaceAll( "\\ss*" ,
- "" );
- String code=tvCountryNumber.getText().toString().trim();
- String fomatedPhone=code+ " " +splitPhoneNum(phone);
-
- Toast.makeText(this, "Success" ,Toast.LENGTH_SHORT).show();
- Intent intent=new Intent();
- intent.setClass(RegistActivity.this,CaptchaActivity.class);
- // Pass the mobile phone number and the formatted mobile phone number
- intent.putExtra( "formatedPhone" ,fomatedPhone);
- intent.putExtra( "phone" ,phone);
- startActivity(intent);
- }
-
- //How to format a mobile phone number. The formatted form is: +86 131 4118 2951
- private String splitPhoneNum(String phone) {
-
- StringBuilder builder=new StringBuilder(phone);
- builder.reverse();
- for ( int i=4,len=builder.length();i<len;i+=5){
- builder. insert (i, ' ' );
- }
- builder.reverse();
- return builder.toString();
- }
The layout of the jump interface is as follows In this interface, we need to enter the SMS verification code. After entering the SMS verification code, when you click Next, the submitCaptcha method of the aggregated data will be called to compare the data. - smsCaptcha.commitCaptcha(phoneNumbber,verfiyCode,new ResultCallBack() {
- /*
- code: Return code:
- Server: 0 success; 1 error;
- Local: -2 Local network exception; -3 Server network exception; -4 Parsing error; -5 Initialization exception
- Reason: Return information success or error reason.
- result: Return result, in JSON format. It will be empty if there is an error or no return value.*/
- @Override
- public void onResult( int code,String reason,String result) {
- if(code==0){
- Log.i(TAG,code+ "" );
- Log.i(TAG,reason);
- Log.i(TAG,result);
- Toast.makeText(CaptchaActivity.this, "The verification code you entered is correct" , Toast.LENGTH_SHORT).show();
- CaptchaActivity.this.finish();
- } else {
- Toast.makeText(CaptchaActivity.this, "The verification code you entered is incorrect" , Toast.LENGTH_SHORT).show();
- }
- }
- });
We can see that the parameters required by this method are ① mobile phone number ② mobile phone verification code. After we call this method, the server that aggregates the data will determine whether this verification code is the verification code just sent to this mobile phone number. After verification, it will return the result to me. We can perform corresponding operations based on the returned result. In the above interface, we found a countdown function. I will talk about the idea here. Of course, there are many countdown methods. In this demo, the countdown is placed in a textView of tvCountDown. First, - //The content of R.string.receiveMessgeCountDown is: <Data>It takes about <font color=#209526>%s</font> seconds to receive a text message</Data>
- //This sentence is to use time to replace the % in html
- String unReceive=getResources().getString(R.string. receiveMessageCountDown, time );
- //Set the string formatted with HTML to the countdown text box
- tvCountDown.setText(Html.fromHtml(unReceive));
In this way, we can fill tvCountDown with HTML formatted text. The next step is the countdown method. - private final int RETRY_INTERVAL =60;
- private int time =RETRY_INTERVAL;
- //Countdown method
- private void countDown() {
- new Thread( new Runnable() {
-
- @Override
- public void run() {
- while( time
- // Subtract one from the time to replace the % in <Data> It takes about <font color=#209526>%s</font> seconds to receive a text message</Data>
- String countDownTime=CaptchaActivity.this .getResources().getString(R.string.receiveMessageCountDown, time );
- //Update tvCountDown on the main thread
- upDateTvCountDown(countDownTime);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- String countDownTime=CaptchaActivity.this .getResources().getString(R.string.unreceiveMessage, time );
- upDateTvCountDown(countDownTime);
- time = RETRY_INTERVAL;
- }
- }).start();
- }
- //Update tvCountDown on the main thread
- private void upDateTvCountDown(final String countDownTime) {
- runOnUiThread( new Runnable() {
- @Override
- public void run() {
- tvCountDown.setText(Html. fromHtml(countDownTime));
- tvCountDown.setEnabled( false );
- }
- });
- }
Summary: In fact, there are two main methods for using the SMS verification code function of aggregated data. One is the sendCaptcha method to obtain the verification code, and the other is the commitCaptcha method to submit the verification code for verification. On this basis, we can change the interface according to needs. The above is an introduction to the main logic of the SMS verification code. |