Android call free SMS verification code sdk development

We often need to use the SMS verification code when registering an app, enter a mobile phone number, click to get the verification code, the mobile phone can receive a text message, and the verification code in the text message can be successfully verified and then some operations can be performed. write picture description here
Of course, there are many SMS service providers. We choose Mob, a free sdk platform. If you have any questions, you can also consult technical support. The service is pretty good. But because it is free, there are still some restrictions. If it is used as a test, a mobile phone number can only receive less than 10 verification codes at most, and it will not be sent after 10 times. At this time, you need to change a mobile phone. number to receive the verification code.

Official website address: http://www.mob.com/#/ The platform also provides some other services, which can be tapped if necessary. write picture description here
Of course, you still need to register an account, then apply for an app, get the app key and app secret, which are needed in your project, such as the SecurityCodeSDK in the picture,
write picture description here
and then download the sdk. The picture below is the Android sdk download page. You can see that we can choose different sdk according to the IDE. What I downloaded is the sdk of Android studio. After the write picture description here
download is complete, unzip it, and you can get the following four jar packages, and a txt file, txt file is the way to add sdk to the project. write picture description here
First copy these four jar packages to the libs folder of the project, and then add the following red part to the gradle file (packaged by * * * *)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            ***minifyEnabled false***
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

**repositories {
    flatDir{
        dirs 'libs'
    }
}**

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.0'
    **compile name:'SMSSDK-2.1.2',ext:'aar'
    compile name:'SMSSDKGUI-2.1.2',ext:'aar'**
    testCompile 'junit:junit:4.12'
}

Then add the following activity to the AndroidManifest.xml file:

    <activity  
                android:name="com.mob.tools.MobUIShell"  
                android:configChanges="keyboardHidden|orientation|screenSize"  
                android:theme="@android:style/Theme.Translucent.NoTitleBar"  
                android:windowSoftInputMode="stateHidden|adjustResize"/>  

The layout file is very simple, just two textiews and two buttons, paste the main code below:

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {  

        private static final String TAG = "SmsYanzheng";  
        EditText mEditTextPhoneNumber;  
        EditText mEditTextCode;  
        Button mButtonGetCode;  
        Button mButtonLogin;  

        EventHandler eventHandler;  
        String strPhoneNumber;  

        @Override  
        protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_main);  

            mEditTextPhoneNumber = (EditText) findViewById(R.id.phone_number);  
            mEditTextCode = (EditText) findViewById(R.id.verification_code);  
            mButtonGetCode = (Button) findViewById(R.id.button_send_verification_code);  
            mButtonLogin = (Button) findViewById(R.id.button_login);  

            mButtonGetCode.setOnClickListener(this);  
            mButtonLogin.setOnClickListener(this);  

            SMSSDK.initSDK(this, "app key", "app secret"); //使用你申请的key 和 secret  

            eventHandler = new EventHandler() {  

                /** 
                 * 在操作之后被触发 
                 * 
                 * @param event  参数1 
                 * @param result 参数2 SMSSDK.RESULT_COMPLETE表示操作成功,为SMSSDK.RESULT_ERROR表示操作失败 
                 * @param data   事件操作的结果 
                 */  

                @Override  
                public void afterEvent(int event, int result, Object data) {  
                    Message message = myHandler.obtainMessage(0x00);  
                    message.arg1 = event;  
                    message.arg2 = result;  
                    message.obj = data;  
                    myHandler.sendMessage(message);  
                }  
            };  

            SMSSDK.registerEventHandler(eventHandler);  
        }  

        @Override  
        protected void onDestroy() {  
            super.onDestroy();  
            SMSSDK.unregisterEventHandler(eventHandler);  
        }  

        @Override  
        public void onClick(View view) {  
            if (view.getId() == R.id.button_login) {  
                String strCode = mEditTextCode.getText().toString();  
                if (null != strCode && strCode.length() == 4) {  
                    Log.d(TAG, mEditTextCode.getText().toString());  
                    SMSSDK.submitVerificationCode("86", strPhoneNumber, mEditTextCode.getText().toString());  
                } else {  
                    Toast.makeText(this, "密码长度不正确", Toast.LENGTH_SHORT).show();  
                }  
            } else if (view.getId() == R.id.button_send_verification_code) {  
                strPhoneNumber = mEditTextPhoneNumber.getText().toString();  
                if (null == strPhoneNumber || "".equals(strPhoneNumber) || strPhoneNumber.length() != 11) {  
                    Toast.makeText(this, "电话号码输入有误", Toast.LENGTH_SHORT).show();  
                    return;  
                }  
                SMSSDK.getVerificationCode("86", strPhoneNumber);  
                mButtonGetCode.setClickable(false);  
                //开启线程去更新button的text  
                new Thread() {  
                    @Override  
                    public void run() {  
                        int totalTime = 60;  
                        for (int i = 0; i < totalTime; i++) {  
                            Message message = myHandler.obtainMessage(0x01);  
                            message.arg1 = totalTime - i;  
                            myHandler.sendMessage(message);  
                            try {  
                                sleep(1000);  
                            } catch (InterruptedException e) {  
                                e.printStackTrace();  
                            }  
                        }  
                        myHandler.sendEmptyMessage(0x02);  
                    }  
                }.start();  
            }  
        }  

        Handler myHandler = new Handler() {  
            @Override  
            public void handleMessage(Message msg) {  
                switch (msg.what) {  
                    case 0x00:  
                        int event = msg.arg1;  
                        int result = msg.arg2;  
                        Object data = msg.obj;  
                        Log.e(TAG, "result : " + result + ", event: " + event + ", data : " + data);  
                        if (result == SMSSDK.RESULT_COMPLETE) { //回调  当返回的结果是complete  
                            if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) { //获取验证码  
                                Toast.makeText(MainActivity.this, "发送验证码成功", Toast.LENGTH_SHORT).show();  
                                Log.d(TAG, "get verification code successful.");  
                            } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) { //提交验证码  
                                Log.d(TAG, "submit code successful");  
                                Toast.makeText(MainActivity.this, "提交验证码成功", Toast.LENGTH_SHORT).show();  
                                Intent intent = new Intent(MainActivity.this, SecondActivity.class);  
                                startActivity(intent);  
                            } else {  
                                Log.d(TAG, data.toString());  
                            }  
                        } else { //进行操作出错,通过下面的信息区分析错误原因  
                            try {  
                                Throwable throwable = (Throwable) data;  
                                throwable.printStackTrace();  
                                JSONObject object = new JSONObject(throwable.getMessage());  
                                String des = object.optString("detail");//错误描述  
                                int status = object.optInt("status");//错误代码  
                                //错误代码:  http://wiki.mob.com/android-api-%E9%94%99%E8%AF%AF%E7%A0%81%E5%8F%82%E8%80%83/  
                                Log.e(TAG, "status: " + status + ", detail: " + des);  
                                if (status > 0 && !TextUtils.isEmpty(des)) {  
                                    Toast.makeText(MainActivity.this, des, Toast.LENGTH_SHORT).show();  
                                    return;  
                                }  
                            } catch (Exception e) {  
                                e.printStackTrace();  
                            }  
                        }  
                        break;  
                    case 0x01:  
                        mButtonGetCode.setText("重新发送(" + msg.arg1 + ")");  
                        break;  
                    case 0x02:  
                        mButtonGetCode.setText("获取验证码");  
                        mButtonGetCode.setClickable(true);  
                        break;  
                }  
            }  
        };  
    }  

Of course, you also need to declare permissions in the AndroidManifest file:

    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>  
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>  
    <uses-permission android:name="android.permission.READ_SMS"/>  
    <uses-permission android:name="android.permission.READ_CONTACTS"/>  
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  


    <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.GET_TASKS"/>  

Details code csdn
https://blog.csdn.net/u010153076/article/details/53305224

———-Second ———————————————-See – The methods to integrate the documentation need to pay attention to are as follows
1.
Configure gradle 1. Add the following script to your root module build. In gradle:

buildscript {
    // 添加MobSDK的maven地址
    repositories {
        maven {
            url "http://mvn.mob.com/android"
        }
    }

    dependencies {
        // 注册MobSDK
        classpath 'com.mob.sdk:MobSDK:+'
    }
}

2. In the build.gradle using the SMSSDK module, add MobSDK plugins and extensions, (inner build.gradle) such as:

// 添加插件  (最上面-顶头)
apply plugin: 'com.mob.sdk'

// 在MobSDK的扩展中注册SMSSDK的相关信息  (“android{}中”)
MobSDK {
    appKey "d580ad56b4b5"
    appSecret "7fcae59a62342e7e2759e9e397c82bdd"

    SMSSDK {}
}

2. Add code
1. Initialize MobSDK

If you don't set the appliaction class name in AndroidManifest, MobSDK will set this to com.mob.MobApplication, but if you set it, please call it in your own Application class (instantiate an AndroidManifest inherit application and write oncreate method , don't forget to fill in android:name=”.AndroidManifest” in application in manifest file)

MobSDK.init(this);

2. Send the verification code and get the verification result

There are two ways to complete the sending and verification of the verification code SMS: calling the visual interface and using the interfaceless interface

2-1. Complete the operation with a visual interface

public void sendCode(Context context) {
    RegisterPage page = new RegisterPage();
    page.setRegisterCallback(new EventHandler() {
        public void afterEvent(int event, int result, Object data) {
            if (result == SMSSDK.RESULT_COMPLETE) {
                // 处理成功的结果
                HashMap<String,Object> phoneMap = (HashMap<String, Object>) data;
                String country = (String) phoneMap.get("country"); // 国家代码,如“86”
                String phone = (String) phoneMap.get("phone"); // 手机号码,如“13800138000”
                // TODO 利用国家代码和手机号码进行后续的操作
            } else{
                // TODO 处理错误的结果
            }
        }
    });
    page.show(context);
}

2-2. Complete the operation with no interface interface

// 请求验证码,其中country表示国家代码,如“86”;phone表示手机号码,如“13800138000”
public void sendCode(String country, String phone) {
    // 注册一个事件回调,用于处理发送验证码操作的结果
    SMSSDK.registerEventHandler(new EventHandler() {
        public void afterEvent(int event, int result, Object data) {
            if (result == SMSSDK.RESULT_COMPLETE) {
               // TODO 处理成功得到验证码的结果
               // 请注意,此时只是完成了发送验证码的请求,验证码短信还需要几秒钟之后才送达
            } else{
                // TODO 处理错误的结果
            }

        }
    });
    // 触发操作
    SMSSDK.getVerificationCode(country, phone);
}

// 提交验证码,其中的code表示验证码,如“1357”
public void submitCode(String country, String phone, String code) {
    // 注册一个事件回调,用于处理提交验证码操作的结果
    SMSSDK.registerEventHandler(new EventHandler() {
        public void afterEvent(int event, int result, Object data) {
            if (result == SMSSDK.RESULT_COMPLETE) {
                // TODO 处理验证成功的结果
            } else{
                // TODO 处理错误的结果
            }

        }
    });
    // 触发操作
    SMSSDK.submitVerificationCode(country, phone, code);
}

    protected void onDestroy() {
        super.onDestroy();
        //用完回调要注销掉,否则可能会出现内存泄露
        SMSSDK.unregisterAllEventHandler();
    };

3. Obfuscation settings
SMSSDK has already been obfuscated. Confusion again will lead to unexpected errors. Please add the following configuration to your obfuscation script to skip the obfuscation of SMSSDK:

-keep class com.mob.**{*;}
-keep class cn.smssdk.**{*;}
-dontwarn com.mob.**

Add permission

    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>  
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>  
    <uses-permission android:name="android.permission.READ_SMS"/>  
    <uses-permission android:name="android.permission.READ_CONTACTS"/>  
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  


    <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.GET_TASKS"/>  

If an error is reported, you need to add it to the application in the manifest file

tools:replace="android:name"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325686154&siteId=291194637