用户注册或者找回密码时一般会用到短信验证功能,这里我们使用第三方的短信平台进行验证实例。
我们用到第三方短信验证平台是Mob,地址为:http://mob.com/
一、注册用户、获取SDK
大家可以自行注册,得到APPKEY和APPSECRET,然后下载SDK,包的导入方式如截图:
二、主要代码
SMSSendForRegisterActivity.java:(获取验证码页)
- package com.qiandaobao.activity;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.view.Window;
- import android.widget.Button;
- import android.widget.Toast;
- import cn.smssdk.EventHandler;
- import cn.smssdk.SMSSDK;
- import com.qiandaobao.broadcast.SMSBroadcastReceiver;
- import com.qiandaobao.broadcast.SMSBroadcastReceiver.MessageListener;
- import com.qiandaobao.view.DeletableEditText;
- import com.qiaodaobao.activity.R;
- public class SMSSendForRegisterActivity extends Activity implements
- OnClickListener {
- // 填写从短信SDK应用后台注册得到的APPKEY
- private static String APPKEY = "9aef0d828910";
- // 填写从短信SDK应用后台注册得到的APPSECRET
- private static String APPSECRET = "11b6db0240c87e2839a2995e05fcd7c5";
- private DeletableEditText mPhoneDeletableEditText, mCodeDeletableEditText;
- private Button mGetCodeButton, mNextButton;
- private String mPhoneString, mCodeString;
- private SMSBroadcastReceiver mSMSBroadcastReceiver;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- setContentView(R.layout.activity_sendsms);
- initViews();
- SMSSDK.initSDK(this, APPKEY, APPSECRET);
- EventHandler eh = 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(eh);
- }
- private void initViews() {
- mPhoneDeletableEditText = (DeletableEditText) findViewById(R.id.et_phone_sendsms);
- mCodeDeletableEditText = (DeletableEditText) findViewById(R.id.et_code_sendsms);
- mGetCodeButton = (Button) findViewById(R.id.btn_getcode_sendsms);
- mNextButton = (Button) findViewById(R.id.btn_next_sendsms);
- mGetCodeButton.setOnClickListener(this);
- mNextButton.setOnClickListener(this);
- mSMSBroadcastReceiver = new SMSBroadcastReceiver();
- mSMSBroadcastReceiver
- .setOnReceivedMessageListener(new MessageListener() {
- public void OnReceived(String message) {
- mCodeDeletableEditText
- .setText(getDynamicPassword(message));// 截取6位验证码
- mCodeDeletableEditText.setSelection(getDynamicPassword(
- message).length());
- }
- });
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.btn_getcode_sendsms:
- if (!TextUtils
- .isEmpty(mPhoneDeletableEditText.getText().toString())) {
- SMSSDK.getVerificationCode("86", mPhoneDeletableEditText
- .getText().toString());
- mPhoneString = mPhoneDeletableEditText.getText().toString();
- } else {
- Toast.makeText(this, "电话不能为空", 1).show();
- }
- break;
- case R.id.btn_next_sendsms:
- if (!TextUtils.isEmpty(mCodeDeletableEditText.getText().toString())) {
- SMSSDK.submitVerificationCode("86", mPhoneString,
- mCodeDeletableEditText.getText().toString());
- } else {
- Toast.makeText(this, "验证码不能为空", 1).show();
- }
- break;
- default:
- break;
- }
- }
- Handler handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- int event = msg.arg1;
- int result = msg.arg2;
- Object data = msg.obj;
- Log.e("event", "event=" + event);
- if (result == SMSSDK.RESULT_COMPLETE) {
- // 短信注册成功后,返回MainActivity,然后提示新好友
- if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
- Toast.makeText(getApplicationContext(), "提交验证码成功",
- Toast.LENGTH_SHORT).show();
- Intent intent = new Intent(SMSSendForRegisterActivity.this,
- RegisterActivity.class);
- startActivity(intent);
- } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
- Toast.makeText(getApplicationContext(), "验证码已经发送",
- Toast.LENGTH_SHORT).show();
- }
- } else {
- ((Throwable) data).printStackTrace();
- Toast.makeText(SMSSendForRegisterActivity.this, "验证码错误",
- Toast.LENGTH_SHORT).show();
- }
- }
- };
- @Override
- protected void onDestroy() {
- super.onDestroy();
- SMSSDK.unregisterAllEventHandler();
- }
- /**
- * 从字符串中截取连续4位数字组合 ([0-9]{" + 4+ "})截取六位数字 进行前后断言不能出现数字 用于从短信中获取动态密码
- *
- * @param str
- * 短信内容
- * @return 截取得到的4位动态密码
- */
- public String getDynamicPassword(String str) {
- // 6是验证码的位数一般为六位
- Pattern continuousNumberPattern = Pattern.compile("(?<![0-9])([0-9]{"
- + 4 + "})(?![0-9])");
- Matcher m = continuousNumberPattern.matcher(str);
- String dynamicPassword = "";
- while (m.find()) {
- System.out.print(m.group());
- dynamicPassword = m.group();
- }
- return dynamicPassword;
- }
- }
上面代码中所用到的SMSBroadcastRecevier代码在 《Android实战简易教程-第三十六枪(监听短信-实现短信验证码自动填入)》 中可以找到。
三、布局文件
main.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="@color/white" >
- <RelativeLayout
- android:id="@+id/head_relat"
- android:layout_width="match_parent"
- android:layout_height="44dp"
- android:background="@color/green" >
- <ImageButton
- android:id="@+id/back_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_centerVertical="true"
- android:layout_marginLeft="5dp"
- android:background="@drawable/back" />
- <TextView
- style="@style/title"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:layout_centerVertical="true"
- android:layout_marginLeft="5dp"
- android:layout_toRightOf="@id/back_btn"
- android:ellipsize="end"
- android:gravity="center"
- android:singleLine="true"
- android:text="手机验证" />
- <ImageView
- android:layout_width="fill_parent"
- android:layout_height="0.5dp"
- android:layout_alignParentBottom="true"
- android:background="#dddddd" />
- </RelativeLayout>
- <com.qiandaobao.view.DeletableEditText
- android:id="@+id/et_phone_sendsms"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_below="@+id/head_relat"
- android:layout_margin="15dp"
- android:layout_marginTop="35dp"
- android:drawableLeft="@drawable/password_iv"
- android:drawableRight="@drawable/user_delete"
- android:gravity="center_vertical"
- android:hint="请输入手机号" />
- <com.qiandaobao.view.DeletableEditText
- android:id="@+id/et_code_sendsms"
- android:layout_width="200dp"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/et_phone_sendsms"
- android:layout_margin="15dp"
- android:layout_marginTop="35dp"
- android:drawableLeft="@drawable/password_iv"
- android:drawableRight="@drawable/user_delete"
- android:gravity="center_vertical"
- android:hint="验证码" />
- <Button
- android:id="@+id/btn_getcode_sendsms"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:layout_below="@+id/et_phone_sendsms"
- android:layout_marginTop="15dp"
- android:layout_toRightOf="@+id/et_code_sendsms"
- android:background="@color/white"
- android:paddingBottom="5dp"
- android:text="获取验证码"
- android:textColor="@color/green"
- android:textSize="12sp" />
- <Button
- android:id="@+id/btn_next_sendsms"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_below="@id/btn_getcode_sendsms"
- android:layout_centerHorizontal="true"
- android:layout_margin="15dp"
- android:background="@drawable/login_btn_bg"
- android:text="下一步"
- android:textSize="14sp" />
- </RelativeLayout>
四、权限添加和配置文件
打开您项目的“AndroidManifest.xml”,在其中添加如下的权限:
- <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.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">
五、运行实例
这时点击获取验证码,短信来了之后就会自动输入到验证码EditText中。
短信验证码还可以用到找回密码的功能中,大家可以自行设置Intent的跳转就可以了。