开相关发中总会遇到短信验证这些操作,这周没有来得及写新的东西,借此分享一篇以前学习短信验证的笔记,本文使用的是 Mob 提供的 SMSSDK .

下载 SMSSDK

官网下载地址:SMSSDK

集成 SMSSDK

将 MobCommons.jar、MobTools.jar、SMSSDK-2.0.1.aar、SMSSDKGUI-2.0.1.aar 放到了app 的 libs 目录下,如果不需要带界面的 SMSSDK 可以不添加 SMSSDKGUI-2.0.1.aar,具体文件请参考最新的 SMSSDK。

配置 build.gradle 文件

打开 app 下面的 build.gradle 文件进行如下配置:

配置AndroidManifest.xml

在 AndroidManifest.xml 文件中配置权限和Application.

配置权限
<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.READ_SMS" /><uses-permission android:name="android.permission.GET_TASKS" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
配置 application
<activity    android:name="com.mob.tools.MobUIShell"    android:theme="@android:style/Theme.Translucent.NoTitleBar"    android:configChanges="keyboardHidden|orientation|screenSize"    android:windowSoftInputMode="stateHidden|adjustResize"/>

启动 SDK

public class MyApplication extends Application {    @Override    public void onCreate() {        super.onCreate();        SMSSDK.initSDK(this, "您的appkey", "您的appsecret");    }}

参考代码

实现一个简单的案例,获取验证码,并进行验证。

布局文件
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.manu.sharesdksms.MainActivity">    <LinearLayout        android:id="@+id/ll_user"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:paddingLeft="16dp"        android:paddingRight="16dp">        <TextView            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:gravity="center"            android:hint="手机号:" />        <EditText            android:id="@+id/et_number"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="4"/>        <TextView            android:id="@+id/tv_getCheckCode"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="2"            android:gravity="center"            android:text="获取验证码"            android:clickable="true"/>    </LinearLayout>    <LinearLayout        android:id="@+id/ll_pass"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/ll_user"        android:paddingLeft="16dp"        android:paddingRight="16dp">        <TextView            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:gravity="center"            android:text="验证码:"/>        <EditText            android:id="@+id/et_checkCode"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="4"/>        <TextView            android:id="@+id/tv_sendCheckCode"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="2"            android:gravity="center"            android:text="验证"            android:clickable="true"/>    </LinearLayout></RelativeLayout>
MainActivity
/** * ShareSDk 验证码测试 */public class MainActivity extends AppCompatActivity implements View.OnClickListener{    private EditText et_number;    private EditText et_checkCode;    private TextView tv_getCheckCode;    private TextView tv_sendCheckCode;    private String phoneNumber;    private String checkCode;    private ProgressDialog dialog;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        et_number = (EditText) findViewById(R.id.et_number);        et_checkCode = (EditText) findViewById(R.id.et_checkCode);        tv_getCheckCode = (TextView) findViewById(R.id.tv_getCheckCode);        tv_sendCheckCode = (TextView) findViewById(R.id.tv_sendCheckCode);        checkCode = et_checkCode.getText().toString().trim();        tv_getCheckCode.setOnClickListener(this);        tv_sendCheckCode.setOnClickListener(this);        //注册短信回调        SMSSDK.registerEventHandler(ev);    }    /**     * 短信验证的回调监听     */    private EventHandler ev = new EventHandler() {        @Override        public void afterEvent(int event, int result, Object data) {            if (result == SMSSDK.RESULT_COMPLETE) { //回调完成                //提交验证码成功,如果验证成功会在data里返回数据。data数据类型为HashMap<number,code>                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {                    Log.e("TAG", "提交验证码成功" + data.toString());                    HashMap<String, Object> mData = (HashMap<String, Object>) data;                    String country = (String) mData.get("country");//返回的国家编号                    String phone = (String) mData.get("phone");//返回用户注册的手机号                    Log.e("TAG", country + "====" + phone);                    if (phone.equals(phoneNumber)) {                        runOnUiThread(new Runnable() {//更改ui的操作要放在主线程,实际可以发送hander                            @Override                            public void run() {                                showDailog("恭喜你!通过验证");                                dialog.dismiss();                            }                        });                    } else {                        runOnUiThread(new Runnable() {                            @Override                            public void run() {                                showDailog("验证失败");                                dialog.dismiss();                            }                        });                    }                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {//获取验证码成功                    Log.e("TAG", "获取验证码成功");                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {//返回支持发送验证码的国家列表                }            } else {                ((Throwable) data).printStackTrace();            }        }    };    private void showDailog(String text) {        new AlertDialog.Builder(this)                .setTitle(text)                .setPositiveButton("确定", null)                .show();    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.tv_getCheckCode:                toast("getCode");                getCheckCode();                break;            case R.id.tv_sendCheckCode:                toast("sendCode");                sendCheckCode();                break;        }    }    /**     * 获取验证码     */    public void getCheckCode() {        phoneNumber = et_number.getText().toString().trim();        //发送短信,传入国家号和电话号码        if (TextUtils.isEmpty(phoneNumber)) {            toast("号码不能为空!");        } else {            SMSSDK.getVerificationCode("+86", phoneNumber);            toast("发送成功!");        }    }    /**     * 向服务器提交验证码,在监听回调中监听是否验证     */    private void sendCheckCode() {        checkCode = et_checkCode.getText().toString();        if (!TextUtils.isEmpty(checkCode)) {            dialog = ProgressDialog.show(this, null, "正在验证...", false, true);            //提交短信验证码            SMSSDK.submitVerificationCode("+86", phoneNumber, checkCode);//国家号,手机号码,验证码            Toast.makeText(this, "提交了注册信息:" + phoneNumber, Toast.LENGTH_SHORT).show();        } else {            Toast.makeText(this, "验证码不能为空", Toast.LENGTH_SHORT).show();        }    }    /**     * Toast     * @param info     */    public void toast(String info){        Toast.makeText(MainActivity.this, info, Toast.LENGTH_SHORT).show();    }    @Override    protected void onDestroy() {        SMSSDK.unregisterEventHandler(ev);        super.onDestroy();    }}

测试效果

稍等一下,gif动画时间有点长,为了接收到短信哦!

可以选择关注微信公众号:jzman-blog 获取最新更新,一起交流学习!