Android Studio Mob快速集成短信验证(图文教程)

转载请标明出处:http://blog.csdn.net/donkor_/article/details/53389505

前言

现在APP应用都是需要通过手机获取短信验证码来注册应用或是实现其它功能 。而利用短信验证码来注册会员,大大降低了非法注册,很大程度上提高了用户账户的安全性,同时避免一些黑名单用户的骚扰。目前市面上已经有了很多提供短信验证的服务商,有收费的,也有免费的。而我们作为个人开发者或者公司为了节约成本,就需要用到下面介绍的一个免费的短信验证平台—Mob.com
Mob平台的优点,这里我们就不再多说,直接开始看教程如何使用。

1.注册开发者
http://reg.mob.com/
只有注册了用户,才可以创建应用,使用第Mob平台提供的短信验证工具。(已有账号这步可以省略)

2.登录官网首页
点击右侧头像栏那里,选择进入后台

这里写图片描述

3.选择SecurityCodeSDK

立即使用并创建名为MobSmsDemo的Android应用
这里写图片描述

这里写图片描述

4.进入SecurityCodeSDK后台
获取创建应用成功后的APP Key和 APP Secret

这里写图片描述

5.回到首页下载 SMS For Android短信验证码SDK

这里写图片描述

这里写图片描述

6.下载完成后得到的是一个压缩包,解压缩,打开SMSSDK这个文件夹

这里写图片描述

7.HowToUse.txt文档是Mob平台提供给我们需要注意的两个地方点,这里简要看过一遍

这里写图片描述

8.在这里我们不需要用GUI库,所以把除了SMSSDKGUI-2.1.2.aar其他三个文件拷贝到项目中,放在Module所在的Libs里面,在build.gradle中进行配置添加依赖

这里写图片描述

9.在AndroidManifest.xml配置相应的权限,然后在“application”下添加如下activity

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

10.使用上面获取到的APP Key和 APP Secret,初始化SDK

//initSDK方法是短信SDK的入口,需要传递您从MOB应用管理后台中注册的SMSSDK的应用AppKey和AppSecrete,如果填写错误,后续的操作都将不能进行
SMSSDK.initSDK(MainActivity.this, "196e511258800", "ba98d7e9aa85eaa323cb4dc60435fd16");

11.registerEventHandler是用来往SMSSDK中注册一个事件接收器。

EventHandler eventHandler = new EventHandler() {
    @Override
    public void afterEvent(int event, int result, Object data) {
        Message msg = new Message();
        msg.arg1 = event;
        msg.arg2 = result;
        msg.obj = data;
        handler.sendMessage(msg);
    }
};
SMSSDK.registerEventHandler(eventHandler);

12.由于EventHandler开启了线程,不能直接在afterEvent中更新UI,所以还需要在MainActivity当中定义一个Handler来接受EventHandler发送过来的消息。

Handler handler = new Handler() {
public void handleMessage(Message msg) {
    if (msg.what == -1) {
        //修改控件文本进行倒计时  i 以60秒倒计时为例
        btnSendMsg.setText( i+" s");
    } else if (msg.what == -2) {
        //修改控件文本,进行重新发送验证码
        btnSendMsg.setText("重新发送");
        btnSendMsg.setClickable(true);
        i = 60;
    } else {
        int event = msg.arg1;
        int result = msg.arg2;
        Object data = msg.obj;

        // 短信注册成功后,返回MainActivity,然后提示
        if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
        // 提交验证码成功,调用注册接口,之后直接登录
        //当号码来自短信注册页面时调用登录注册接口
        //当号码来自绑定页面时调用绑定手机号码接口


        } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
        Toast.makeText(getApplicationContext(), "验证码已经发送",
                Toast.LENGTH_SHORT).show();
            } else {
                ((Throwable) data).printStackTrace();
            }
        } else if (result == SMSSDK.RESULT_ERROR) {
            try {
                Throwable throwable = (Throwable) data;
                throwable.printStackTrace();
                JSONObject object = new JSONObject(throwable.getMessage());
                String des = object.optString("detail");//错误描述
                int status = object.optInt("status");//错误代码
                if (status > 0 && !TextUtils.isEmpty(des)) {
                    Toast.makeText(MainActivity.this, des, Toast.LENGTH_SHORT).show();
                    return;
                }
            } catch (Exception e) {
                //do something
            }
        }
    }
   }
};

13.在布局上定义两个按钮控件进行发送短信和验证短信验证码并监听点击事件。

@Override
public void onClick(View v) {
    String phoneNum=etPhoneNumber.getText().toString().trim();
    switch (v.getId()) {
        case R.id.btnSendMsg:
            if (TextUtils.isEmpty(phoneNum)) {
                Toast.makeText(getApplicationContext(),"手机号码不能为空",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            SMSSDK.getVerificationCode("86", phoneNum);
            btnSendMsg.setClickable(false);
            //开始倒计时
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (; i > 0; i--) {
                        handler.sendEmptyMessage(-1);
                        if (i <= 0) {
                            break;
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    //倒计时结束执行
                    handler.sendEmptyMessage(-2);
                }
            }).start();
            break;
        case R.id.btnSubmitCode:
             String code = etCode.getText().toString().trim();
            if (TextUtils.isEmpty(phoneNum)) {
                Toast.makeText(getApplicationContext(),"手机号码不能为空",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(code)) {
                Toast.makeText(getApplicationContext(),"验证码不能为空",
                    Toast.LENGTH_SHORT).show();
                    return;
            }
            SMSSDK.submitVerificationCode("86", phoneNum, code);
            break;
        default:
            break;
    }
}

14.在完成短信验证之后,需要销毁回调监听接口。

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

15.最后看下布局UI和效果图。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginTop="60dp"
        android:orientation="horizontal">


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="手机号:"
            android:textColor="#222222"
            android:textSize="16sp" />

        <EditText
            android:id="@+id/etPhoneNumber"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:background="@null"
            android:drawablePadding="10dp"
            android:hint="请输入手机号"
            android:inputType="phone"
            android:lines="0"
            android:maxLength="11"
            android:paddingBottom="10dp"
            android:paddingLeft="20dp"
            android:paddingTop="10dp"
            android:textColor="@android:color/black"
            android:textColorHint="#cccccc"
            android:textSize="16sp" />

    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:background="@android:color/darker_gray" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="验证码:"
            android:textColor="#222222"
            android:textSize="16sp" />

        <EditText
            android:id="@+id/etCode"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@null"
            android:hint="请输入验证码"
            android:inputType="phone"
            android:lines="0"
            android:maxLength="6"
            android:paddingBottom="10dp"
            android:paddingLeft="20dp"
            android:paddingTop="10dp"
            android:textColor="@android:color/black"
            android:textColorHint="#cccccc"
            android:textSize="16sp" />

        <Button
            android:id="@+id/btnSendMsg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:background="@android:color/darker_gray"
            android:text="获取验证码"
            android:textColor="#0000ff"
            android:textSize="15sp" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:background="@android:color/darker_gray" />

    <Button
        android:id="@+id/btnSubmitCode"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/darker_gray"
        android:gravity="center"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginTop="30dp"
        android:text="验证"
        android:textColor="#0000ff"
        android:textSize="15sp" />
</LinearLayout>


2017-01-16更新:
通过汉语拼音排列,添加城市与城市代码

无城市、城市代码Demo_CSDN下载地址 : http://download.csdn.net/detail/donkor_/9697039
包含城市、城市代码Demo_CSDN下载地址 : http://download.csdn.net/detail/donkor_/9738986


About me
Email :donkor@yeah.net
Android开发交流QQ群 : 537891203
Android开发交流群

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值