原文著做權地址:http://www.jb51.net/article/84946.htm前端
demo地址:http://git.oschina.net/lizhanqi/MobSMSDemojava
一.前言android
如今的app基本上都須要用到短信功能,註冊時或者有消息通知時須要給用戶發送一條短信,可是對於我的開發者來講,去買第三方的短信服務實在是有點奢侈,很好的是mob爲咱們提供了免費的短信驗證碼服務功能,我不是打廣告,的確以爲這項服務很不錯。那麼下面就簡單講一下如何在本身的工程裏集成mob的短信功能,其實整個流程並不複雜,只是我的以爲mob的官方文檔有點小亂,官方Demo也有點小複雜,同時有一些細節地方容易被忽視,也會致使一些問題。
PS:太喜歡mob的logo了。 git
二.實現過程正則表達式
本篇只涉及Android,若是是IOS系統,還望本身斟酌,但願本篇文章也能給您提供幫助,同時IDE是Android Studio。api
1.key申請app
申請地址:http://www.mob.com,在產品中心選擇短信驗證碼SDK,而後完成相應的註冊和申請工做;
進入本身的後臺中心,就能夠看見本身的App Key和App Secret: ide
總體趨勢欄給咱們展現了一些短信服務使用狀況。未上線登記時,咱們能夠無償使用20條/天,若是需求量比較大,咱們能夠在本身的工程裏集成了mob短信,而後上線登記,應該能夠得到更多的免費短信條數,暫何嘗試。函數
2.下載SDK佈局
在SDK下載欄目選擇SMS for Android,而後選擇相應IDE對應的SDK便可(本篇IDE是as)
下載後大概是這樣:
3.集成過程
申請到了key和secret後就是集成到本身的工程中了。mob主要提供兩種接口方式:1)使用官方自帶的UI;2)使用無GUI接口。
3.1.配置SDK
這已是使用第三方接口的老規矩了。官網文檔我就不貼了,着實看着不舒服,在這裏只貼本身的。
首先是在工程的libs下添加jar包和.aar文件。
而後在build.gradle中添加依賴項
在AndroidManifest中添加相應權限和註冊相應的activity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<!-- mob短信 須要的權限 -->
<
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.GET_TASKS"
/>
<
uses-permission
android:name
=
"android.permission.ACCESS_FINE_LOCATION"
/>
<!--在application中註冊activity -->
<!-- Mob短信(若是使用無GUI的,這個activity應該能夠不須要了,本身沒試過,就先在這注冊着吧) -->
<
activity
android:name
=
"com.mob.tools.MobUIShell"
android:configChanges
=
"keyboardHidden|orientation|screenSize"
android:theme
=
"@android:style/Theme.Translucent.NoTitleBar"
android:windowSoftInputMode
=
"stateHidden|adjustResize"
>
</
activity
>
|
3.2.調用接口發送短信
前面提到了,mob短息提供有GUI和無GUI的兩種方式,不管哪一種方式,都須要對SMSSDK先初始化,再調用接口。
初始化:SMSSDK.initSDK(LoginActivity.this, "App Key", "App Secret");
1)有GUI,即便用mob提供的界面
方法以下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
registerText.setOnClickListener(
new
View.OnClickListener() {
@Override
public
void
onClick(View v) {
//首先初始化SMSSDK
SMSSDK.initSDK(LoginActivity.
this
,
"App Key"
,
"App Secret"
);
RegisterPage registerPage =
new
RegisterPage();
//回調函數
registerPage.setRegisterCallback(
new
EventHandler()
{
public
void
afterEvent(
int
event,
int
result, Object data)
{
// 解析結果
if
(result == SMSSDK.RESULT_COMPLETE)
{
//提交驗證碼成功
if
(event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE)
{
}
//提交驗證碼成功,此時已經驗證成功了
else
if
(event == SMSSDK.EVENT_GET_VERIFICATION_CODE)
{
}
}
}
});
registerPage.show(LoginActivity.
this
);
}
});
|
2)無GUI
這種狀況通常是使用本身的activity界面,而後集成短信功能,好比一個簡單的註冊。
邏輯
package com.qg.lizhanqi.mobsms;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
public class SignUpActivity extends AppCompatActivity implements View.OnClickListener {
private TimerTask tt;
private Timer tm;
private EditText et_phonenum;
private Button btn_check;
private EditText et_checkecode;
private Button btn_sure;
private int TIME = 60;//倒計時60s這裏應該多設置些由於mob後臺須要60s,咱們前端會有差別的建議設置90,100或者120
public String country="86";//這是中國區號,若是須要其餘國家列表,可使用getSupportedCountries();得到國家區號
private String phone;
private static final int CODE_REPEAT = 1; //從新發送
Handler hd = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == CODE_REPEAT) {
btn_check.setEnabled(true);
btn_sure.setEnabled(true);
tm.cancel();//取消任務
tt.cancel();//取消任務
TIME = 60;//時間重置
btn_check.setText("從新發送驗證碼");
}else {
btn_check.setText(TIME + "從新發送驗證碼");
}
}
};
//回調
EventHandler eh=new EventHandler(){
@Override
public void afterEvent(int event, int result, Object data) {
if (result == SMSSDK.RESULT_COMPLETE) {
if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
toast("驗證成功");
}else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){ //獲取驗證碼成功
toast("獲取驗證碼成功");
}else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){//若是你調用了獲取國家區號類表會在這裏回調
//返回支持發送驗證碼的國家列表
}
}else{//錯誤等在這裏(包括驗證失敗)
//錯誤碼請參照http://wiki.mob.com/android-api-錯誤碼參考/這裏我就再也不繼續寫了
((Throwable)data).printStackTrace();
String str = data.toString();
toast(str);
}
}
};
//吐司的一個小方法
private void toast(final String str) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(SignUpActivity.this, str, Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
//配置app你的 SMSSDK.initSDK(this, "您的appkey", "您的appsecret");
SMSSDK.initSDK(this, "185afd2d1b380", "fa6c235598dc50b9b7881680b84109a8");
SMSSDK.registerEventHandler(eh); //註冊短信回調(記得銷燬,避免泄露內存)
initView();
}
private void initView() {
et_phonenum = (EditText) findViewById(R.id.et_phonenum);
btn_check = (Button) findViewById(R.id.btn_check);
et_checkecode = (EditText) findViewById(R.id.et_checkecode);
btn_sure = (Button) findViewById(R.id.btn_sure);
btn_check.setOnClickListener(this);
btn_sure.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_check:
phone = et_phonenum.getText().toString().trim().replaceAll("/s","");
if (!TextUtils.isEmpty(phone)) {
//定義須要匹配的正則表達式的規則
String REGEX_MOBILE_SIMPLE = "[1][358]\\d{9}";
//把正則表達式的規則編譯成模板
Pattern pattern = Pattern.compile(REGEX_MOBILE_SIMPLE);
//把須要匹配的字符給模板匹配,得到匹配器
Matcher matcher = pattern.matcher(phone);
// 經過匹配器查找是否有該字符,不可重複調用重複調用matcher.find()
if (matcher.find()) {//匹配手機號是否存在
alterWarning();
} else {
toast("手機號格式錯誤");
}
} else {
toast("請先輸入手機號");
}
break;
case R.id.btn_sure:
//得到用戶輸入的驗證碼
String code = et_checkecode.getText().toString().replaceAll("/s","");
if (!TextUtils.isEmpty(code)) {//判斷驗證碼是否爲空
//驗證
SMSSDK.submitVerificationCode( country, phone, code);
}else{//若是用戶輸入的內容爲空,提醒用戶
toast("請輸入驗證碼後再提交");
}
break;
}
}
//彈窗確認下發
private void alterWarning() {
// 2. 經過sdk發送短信驗證
AlertDialog.Builder builder = new AlertDialog.Builder(this); //先獲得構造器
builder.setTitle("提示"); //設置標題
builder.setMessage("咱們將要發送到" + phone + "驗證"); //設置內容
builder.setIcon(R.mipmap.ic_launcher);//設置圖標,圖片id便可
builder.setPositiveButton("肯定", new DialogInterface.OnClickListener() {
//設置肯定按鈕
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //關閉dialog
// 2. 經過sdk發送短信驗證(請求獲取短信驗證碼,在監聽(eh)中返回)
SMSSDK.getVerificationCode(country, phone);
//作倒計時操做
Toast.makeText(SignUpActivity.this, "已發送" + which, Toast.LENGTH_SHORT).show();
btn_check.setEnabled(false);
btn_sure.setEnabled(true);
tm = new Timer();
tt = new TimerTask() {
@Override
public void run() {
hd.sendEmptyMessage(TIME--);
}
};
tm.schedule(tt,0,1000);
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //設置取消按鈕
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Toast.makeText(SignUpActivity.this, "已取消" + which, Toast.LENGTH_SHORT).show();
}
});
//參數都設置完成了,建立並顯示出來
builder.create().show();
}
//銷燬短信註冊
@Override
protected void onDestroy() {
super.onDestroy();
// 註銷回調接口registerEventHandler必須和unregisterEventHandler配套使用,不然可能形成內存泄漏。
SMSSDK.unregisterEventHandler(eh);
}
}
----------------------------------華麗的 分割線---------------------------------------------------------------------
佈局文件<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="50dp" android:gravity="center" tools:context="com.qg.lizhanqi.mobsms.SignUpActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <EditText android:inputType="phone" android:id="@+id/et_phonenum" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="手機號碼" /> <Button android:id="@+id/btn_check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="發送驗證碼" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <EditText android:id="@+id/et_checkecode" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="驗證碼" /> <Button android:enabled="false" android:id="@+id/btn_sure" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="驗證" /> </LinearLayout></LinearLayout>