Android Studio Mob快速集成短信驗證(圖文教程)

LayNcl 9年前發布 | 39K 次閱讀 Android開發 移動開發 Android Studio

前言:

現在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
        }
    }
}

} };</code></pre>

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="

    <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:text="13691942911"
        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></code></pre>

最后看下效果圖:

 

 

來自:http://www.jianshu.com/p/7832e3f5a213

 

 本文由用戶 LayNcl 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!