Android实战简易教程<三十九>(第三方短信验证平台Mob和验证码自动填入功能结合实例)

用户注册或者找回密码时一般会用到短信验证功能,这里我们使用第三方的短信平台进行验证实例。

我们用到第三方短信验证平台是Mob,地址为:http://mob.com/

一、注册用户、获取SDK

大家可以自行注册,得到APPKEY和APPSECRET,然后下载SDK,包的导入方式如截图:



二、主要代码

SMSSendForRegisterActivity.java:(获取验证码页)

[java]  view plain copy
  1. package com.qiandaobao.activity;  
  2.   
  3. import java.util.regex.Matcher;  
  4. import java.util.regex.Pattern;  
  5.   
  6. import android.app.Activity;  
  7. import android.content.Intent;  
  8. import android.os.Bundle;  
  9. import android.os.Handler;  
  10. import android.os.Message;  
  11. import android.text.TextUtils;  
  12. import android.util.Log;  
  13. import android.view.View;  
  14. import android.view.View.OnClickListener;  
  15. import android.view.Window;  
  16. import android.widget.Button;  
  17. import android.widget.Toast;  
  18. import cn.smssdk.EventHandler;  
  19. import cn.smssdk.SMSSDK;  
  20.   
  21. import com.qiandaobao.broadcast.SMSBroadcastReceiver;  
  22. import com.qiandaobao.broadcast.SMSBroadcastReceiver.MessageListener;  
  23. import com.qiandaobao.view.DeletableEditText;  
  24. import com.qiaodaobao.activity.R;  
  25.   
  26. public class SMSSendForRegisterActivity extends Activity implements  
  27.         OnClickListener {  
  28.     // 填写从短信SDK应用后台注册得到的APPKEY  
  29.     private static String APPKEY = "9aef0d828910";  
  30.   
  31.     // 填写从短信SDK应用后台注册得到的APPSECRET  
  32.     private static String APPSECRET = "11b6db0240c87e2839a2995e05fcd7c5";  
  33.   
  34.     private DeletableEditText mPhoneDeletableEditText, mCodeDeletableEditText;  
  35.     private Button mGetCodeButton, mNextButton;  
  36.     private String mPhoneString, mCodeString;  
  37.     private SMSBroadcastReceiver mSMSBroadcastReceiver;  
  38.   
  39.     @Override  
  40.     protected void onCreate(Bundle savedInstanceState) {  
  41.         super.onCreate(savedInstanceState);  
  42.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  43.         setContentView(R.layout.activity_sendsms);  
  44.         initViews();  
  45.         SMSSDK.initSDK(this, APPKEY, APPSECRET);  
  46.         EventHandler eh = new EventHandler() {  
  47.   
  48.             @Override  
  49.             public void afterEvent(int event, int result, Object data) {  
  50.   
  51.                 Message msg = new Message();  
  52.                 msg.arg1 = event;  
  53.                 msg.arg2 = result;  
  54.                 msg.obj = data;  
  55.                 handler.sendMessage(msg);  
  56.             }  
  57.   
  58.         };  
  59.         SMSSDK.registerEventHandler(eh);  
  60.   
  61.     }  
  62.   
  63.     private void initViews() {  
  64.         mPhoneDeletableEditText = (DeletableEditText) findViewById(R.id.et_phone_sendsms);  
  65.         mCodeDeletableEditText = (DeletableEditText) findViewById(R.id.et_code_sendsms);  
  66.         mGetCodeButton = (Button) findViewById(R.id.btn_getcode_sendsms);  
  67.         mNextButton = (Button) findViewById(R.id.btn_next_sendsms);  
  68.         mGetCodeButton.setOnClickListener(this);  
  69.         mNextButton.setOnClickListener(this);  
  70.         mSMSBroadcastReceiver = new SMSBroadcastReceiver();  
  71.         mSMSBroadcastReceiver  
  72.                 .setOnReceivedMessageListener(new MessageListener() {  
  73.                     public void OnReceived(String message) {  
  74.   
  75.                         mCodeDeletableEditText  
  76.                                 .setText(getDynamicPassword(message));// 截取6位验证码  
  77.                         mCodeDeletableEditText.setSelection(getDynamicPassword(  
  78.                                 message).length());  
  79.                     }  
  80.                 });  
  81.   
  82.     }  
  83.   
  84.     @Override  
  85.     public void onClick(View v) {  
  86.         switch (v.getId()) {  
  87.         case R.id.btn_getcode_sendsms:  
  88.             if (!TextUtils  
  89.                     .isEmpty(mPhoneDeletableEditText.getText().toString())) {  
  90.                 SMSSDK.getVerificationCode("86", mPhoneDeletableEditText  
  91.                         .getText().toString());  
  92.                 mPhoneString = mPhoneDeletableEditText.getText().toString();  
  93.             } else {  
  94.                 Toast.makeText(this"电话不能为空"1).show();  
  95.             }  
  96.   
  97.             break;  
  98.   
  99.         case R.id.btn_next_sendsms:  
  100.             if (!TextUtils.isEmpty(mCodeDeletableEditText.getText().toString())) {  
  101.                 SMSSDK.submitVerificationCode("86", mPhoneString,  
  102.                         mCodeDeletableEditText.getText().toString());  
  103.             } else {  
  104.                 Toast.makeText(this"验证码不能为空"1).show();  
  105.             }  
  106.   
  107.             break;  
  108.   
  109.         default:  
  110.             break;  
  111.         }  
  112.   
  113.     }  
  114.   
  115.     Handler handler = new Handler() {  
  116.   
  117.         @Override  
  118.         public void handleMessage(Message msg) {  
  119.             super.handleMessage(msg);  
  120.             int event = msg.arg1;  
  121.             int result = msg.arg2;  
  122.             Object data = msg.obj;  
  123.             Log.e("event""event=" + event);  
  124.             if (result == SMSSDK.RESULT_COMPLETE) {  
  125.                 // 短信注册成功后,返回MainActivity,然后提示新好友  
  126.                 if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功  
  127.                     Toast.makeText(getApplicationContext(), "提交验证码成功",  
  128.                             Toast.LENGTH_SHORT).show();  
  129.                     Intent intent = new Intent(SMSSendForRegisterActivity.this,  
  130.                             RegisterActivity.class);  
  131.                     startActivity(intent);  
  132.                 } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {  
  133.                     Toast.makeText(getApplicationContext(), "验证码已经发送",  
  134.                             Toast.LENGTH_SHORT).show();  
  135.                 }  
  136.             } else {  
  137.                 ((Throwable) data).printStackTrace();  
  138.                 Toast.makeText(SMSSendForRegisterActivity.this"验证码错误",  
  139.                         Toast.LENGTH_SHORT).show();  
  140.   
  141.             }  
  142.   
  143.         }  
  144.   
  145.     };  
  146.   
  147.     @Override  
  148.     protected void onDestroy() {  
  149.         super.onDestroy();  
  150.         SMSSDK.unregisterAllEventHandler();  
  151.     }  
  152.   
  153.     /** 
  154.      * 从字符串中截取连续4位数字组合 ([0-9]{" + 4+ "})截取六位数字 进行前后断言不能出现数字 用于从短信中获取动态密码 
  155.      *  
  156.      * @param str 
  157.      *            短信内容 
  158.      * @return 截取得到的4位动态密码 
  159.      */  
  160.     public String getDynamicPassword(String str) {  
  161.         // 6是验证码的位数一般为六位  
  162.         Pattern continuousNumberPattern = Pattern.compile("(?<![0-9])([0-9]{"  
  163.                 + 4 + "})(?![0-9])");  
  164.         Matcher m = continuousNumberPattern.matcher(str);  
  165.         String dynamicPassword = "";  
  166.         while (m.find()) {  
  167.             System.out.print(m.group());  
  168.             dynamicPassword = m.group();  
  169.         }  
  170.   
  171.         return dynamicPassword;  
  172.     }  
  173.   
  174. }  

上面代码中所用到的SMSBroadcastRecevier代码在 Android实战简易教程-第三十六枪(监听短信-实现短信验证码自动填入) 中可以找到。

三、布局文件

main.xml:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="@color/white" >  
  6.   
  7.     <RelativeLayout  
  8.         android:id="@+id/head_relat"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="44dp"  
  11.         android:background="@color/green" >  
  12.   
  13.         <ImageButton  
  14.             android:id="@+id/back_btn"  
  15.             android:layout_width="wrap_content"  
  16.             android:layout_height="wrap_content"  
  17.             android:layout_alignParentLeft="true"  
  18.             android:layout_centerVertical="true"  
  19.             android:layout_marginLeft="5dp"  
  20.             android:background="@drawable/back" />  
  21.   
  22.         <TextView  
  23.             style="@style/title"  
  24.             android:layout_width="wrap_content"  
  25.             android:layout_height="wrap_content"  
  26.             android:layout_centerInParent="true"  
  27.             android:layout_centerVertical="true"  
  28.             android:layout_marginLeft="5dp"  
  29.             android:layout_toRightOf="@id/back_btn"  
  30.             android:ellipsize="end"  
  31.             android:gravity="center"  
  32.             android:singleLine="true"  
  33.             android:text="手机验证" />  
  34.   
  35.         <ImageView  
  36.             android:layout_width="fill_parent"  
  37.             android:layout_height="0.5dp"  
  38.             android:layout_alignParentBottom="true"  
  39.             android:background="#dddddd" />  
  40.     </RelativeLayout>  
  41.   
  42.     <com.qiandaobao.view.DeletableEditText  
  43.         android:id="@+id/et_phone_sendsms"  
  44.         android:layout_width="match_parent"  
  45.         android:layout_height="wrap_content"  
  46.         android:layout_below="@+id/head_relat"  
  47.         android:layout_margin="15dp"  
  48.         android:layout_marginTop="35dp"  
  49.         android:drawableLeft="@drawable/password_iv"  
  50.         android:drawableRight="@drawable/user_delete"  
  51.         android:gravity="center_vertical"  
  52.         android:hint="请输入手机号" />  
  53.   
  54.     <com.qiandaobao.view.DeletableEditText  
  55.         android:id="@+id/et_code_sendsms"  
  56.         android:layout_width="200dp"  
  57.         android:layout_height="wrap_content"  
  58.         android:layout_alignParentLeft="true"  
  59.         android:layout_below="@+id/et_phone_sendsms"  
  60.         android:layout_margin="15dp"  
  61.         android:layout_marginTop="35dp"  
  62.         android:drawableLeft="@drawable/password_iv"  
  63.         android:drawableRight="@drawable/user_delete"  
  64.         android:gravity="center_vertical"  
  65.         android:hint="验证码" />  
  66.   
  67.     <Button  
  68.         android:id="@+id/btn_getcode_sendsms"  
  69.         android:layout_width="wrap_content"  
  70.         android:layout_height="wrap_content"  
  71.         android:layout_alignParentRight="true"  
  72.         android:layout_below="@+id/et_phone_sendsms"  
  73.         android:layout_marginTop="15dp"  
  74.         android:layout_toRightOf="@+id/et_code_sendsms"  
  75.         android:background="@color/white"  
  76.         android:paddingBottom="5dp"  
  77.         android:text="获取验证码"  
  78.         android:textColor="@color/green"  
  79.         android:textSize="12sp" />  
  80.   
  81.     <Button  
  82.         android:id="@+id/btn_next_sendsms"  
  83.         android:layout_width="match_parent"  
  84.         android:layout_height="wrap_content"  
  85.         android:layout_below="@id/btn_getcode_sendsms"  
  86.         android:layout_centerHorizontal="true"  
  87.         android:layout_margin="15dp"  
  88.         android:background="@drawable/login_btn_bg"  
  89.         android:text="下一步"  
  90.         android:textSize="14sp" />  
  91.   
  92. </RelativeLayout>  

四、权限添加和配置文件

打开您项目的“AndroidManifest.xml”,在其中添加如下的权限:

[html]  view plain copy
  1. <uses-permission android:name="android.permission.READ_CONTACTS" />  
  2. <uses-permission android:name="android.permission.READ_PHONE_STATE" />  
  3. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
  4. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  5. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
  6. <uses-permission android:name="android.permission.INTERNET" />  
  7. <uses-permission android:name="android.permission.RECEIVE_SMS" />  
  8. <uses-permission android:name="android.permission.GET_TASKS" />  
  9. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
然后打“application”下添加如下activity:

[html]  view plain copy
  1. <activity  
  2. android:name="com.mob.tools.MobUIShell"  
  3. android:theme="@android:style/Theme.Translucent.NoTitleBar"  
  4. android:configChanges="keyboardHidden|orientation|screenSize"  
  5. android:windowSoftInputMode="stateHidden|adjustResize">  

五、运行实例


这时点击获取验证码,短信来了之后就会自动输入到验证码EditText中。

短信验证码还可以用到找回密码的功能中,大家可以自行设置Intent的跳转就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值