当前位置:主页 > 移动开发 > Android代码 >

Android实现页面短信验证功能

时间:2021-11-19 13:21:16 | 栏目:Android代码 | 点击:

本文实例为大家分享了Android实现页面短信验证功能的具体代码,供大家参考,具体内容如下

目标效果:

上一篇博文介绍的是使用SDK中自带的验证页面,需要进行多次跳转,并且项目需要添加两个框架,多有不便,这个例子简化了短信验证的代码,但是不足的是功能不如原本那个完善。

1.新建项目,找到上一次下载的SDK文件中包含的SMSSDK项目,复制lib目录下的三个jar包,res目录下的raw文件夹和values目录下的两个xml文件到本项目。

2.activity_main.xml页面设置布局。

activity_main.xml页面:

<RelativeLayout 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"
  tools:context=".MainActivity" >
 
  <EditText
    android:id="@+id/etPhone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:hint="请输入手机号"
    android:layout_marginTop="45dp"
    android:ems="10" >
 
    <requestFocus />
  </EditText>
 
  <EditText
    android:id="@+id/etNumber"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/etPhone"
    android:hint="请输入验证码"
    android:layout_marginTop="26dp"
    android:ems="10" />
 
  <Button
    android:id="@+id/btGet"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/etNumber"
    android:layout_alignParentRight="true"
    android:text="获取验证码" />
 
  <Button
    android:id="@+id/btRegister"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="注册" />
  
</RelativeLayout>

3.MainActivity.java页面验证信息。

MainActivity.java页面:

package com.example.notetest;
 
import org.json.JSONObject;
 
import com.example.notetest.MyCountDownTime;
 
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.utils.SMSLog;
 
public class MainActivity extends Activity implements OnClickListener, Callback {
 
 private static String APPKEY= "13e9653a7ff00";
 
 // 填写从短信SDK应用后台注册得到的APPSECRET
 private static String APPSECRET ="a881cac45bce10a59ccf22203062e763";
 
 private EditText etPhone;
 
 private EditText etNumber;
 
 private Button btGet;
 
 private Button btRegister;
 
 private String phone;
 
 private MyCountDownTime myCountDownTime;// 用于验证码倒计时
 private Handler mHandler;//用于执行耗时操作
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 SMSSDK.initSDK(this, APPKEY, APPSECRET, false);
 btGet = (Button) findViewById(R.id.btGet);
 btRegister = (Button) findViewById(R.id.btRegister);
 etPhone = (EditText) findViewById(R.id.etPhone);
 etNumber = (EditText) findViewById(R.id.etNumber);
 
 btGet.setOnClickListener(this);
 btRegister.setOnClickListener(this);
 
 initSDK();
 }
 
 private void initSDK() {
 try {
  final Handler handler = new Handler(this);
  EventHandler eventHandler = new EventHandler() {
  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); // 注册短信回调
 } catch (Exception e) {
  e.printStackTrace();
 }
 }
 
 @Override
 public void onClick(View v) {
 switch (v.getId()) {
 case R.id.btGet:
  phone = etPhone.getText().toString().trim();
  if (!TextUtils.isEmpty(phone)) {
  SMSSDK.getVerificationCode("86", phone);// 获取短信
  getCode();
  } else {
  Toast.makeText(MainActivity.this, "电话号码不能为空",
   Toast.LENGTH_SHORT).show();
  }
  break;
 case R.id.btRegister:
  String number = etNumber.getText().toString().trim();
  if (!TextUtils.isEmpty(number)) {
  SMSSDK.submitVerificationCode("86", phone, number);// 验证短信
  } else {
  Toast.makeText(MainActivity.this, "验证码不能为空", Toast.LENGTH_SHORT)
   .show();
  return;
  }
  break;
 default:
  break;
 }
 }
 
 private void getCode() {
 mHandler = new Handler();
 mHandler.postDelayed(new Runnable() {
  @Override
  public void run() {
  startTimer();
  }
 }, 2000);
 }
 
 /**
 * 
 * @Description: TODO 发送成功后,开始倒计时
 * 
 */
 private void startTimer() {
 if (null == myCountDownTime) {
  myCountDownTime = new MyCountDownTime(60000, 1000, btGet, "重新发送");
 }
 myCountDownTime.start();
 }
 /**
 * 
 * @Description: TODO 一般发送失败时,需要重置Button状态
 */
 private void cancelTimer(){
 if(null != myCountDownTime){
  myCountDownTime.cancel();
  myCountDownTime.onFinish();
 }
 }
 
 protected void onDestroy() {
 // 销毁回调监听接口
 SMSSDK.unregisterAllEventHandler();
 super.onDestroy();
 }
 
 @Override
 public boolean handleMessage(Message msg) {
 int event = msg.arg1;
 int result = msg.arg2;
 Object data = msg.obj;
 if (result == SMSSDK.RESULT_COMPLETE) {
  // 回调完成
  if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
  // 提交验证码成功
  Toast.makeText(MainActivity.this, "验证成功", Toast.LENGTH_SHORT)
   .show();
  } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
  // 获取验证码成功
  Toast.makeText(MainActivity.this, "获取验证码成功", Toast.LENGTH_SHORT)
   .show();
  } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
  // 返回支持发送验证码的国家列表
  }
 } else {
  int status = 0;
  try {
  ((Throwable) data).printStackTrace();
  Throwable throwable = (Throwable) data;
 
  JSONObject object = new JSONObject(throwable.getMessage());
  String des = object.optString("detail");
  status = object.optInt("status");
  if (!TextUtils.isEmpty(des)) {
   Toast.makeText(MainActivity.this, des, Toast.LENGTH_SHORT)
    .show();
   return false;
  }
  } catch (Exception e) {
  SMSLog.getInstance().w(e);
  }
 }
 return false;
 }
}

4.新建MyCountDownTime.java页面,用于获取验证码后按钮的倒计时。

MyCountDownTime.java页面:

package com.example.notetest;
 
import org.json.JSONObject;
 
import com.example.notetest.MyCountDownTime;
 
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.utils.SMSLog;
 
public class MainActivity extends Activity implements OnClickListener, Callback {
 
 private static String APPKEY= "13e9653a7ff00";
 
 // 填写从短信SDK应用后台注册得到的APPSECRET
 private static String APPSECRET ="a881cac45bce10a59ccf22203062e763";
 
 private EditText etPhone;
 
 private EditText etNumber;
 
 private Button btGet;
 
 private Button btRegister;
 
 private String phone;
 
 private MyCountDownTime myCountDownTime;// 用于验证码倒计时
 private Handler mHandler;//用于执行耗时操作
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 SMSSDK.initSDK(this, APPKEY, APPSECRET, false);
 btGet = (Button) findViewById(R.id.btGet);
 btRegister = (Button) findViewById(R.id.btRegister);
 etPhone = (EditText) findViewById(R.id.etPhone);
 etNumber = (EditText) findViewById(R.id.etNumber);
 
 btGet.setOnClickListener(this);
 btRegister.setOnClickListener(this);
 
 initSDK();
 }
 
 private void initSDK() {
 try {
  final Handler handler = new Handler(this);
  EventHandler eventHandler = new EventHandler() {
  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); // 注册短信回调
 } catch (Exception e) {
  e.printStackTrace();
 }
 }
 
 @Override
 public void onClick(View v) {
 switch (v.getId()) {
 case R.id.btGet:
  phone = etPhone.getText().toString().trim();
  if (!TextUtils.isEmpty(phone)) {
  SMSSDK.getVerificationCode("86", phone);// 获取短信
  getCode();
  } else {
  Toast.makeText(MainActivity.this, "电话号码不能为空",
   Toast.LENGTH_SHORT).show();
  }
  break;
 case R.id.btRegister:
  String number = etNumber.getText().toString().trim();
  if (!TextUtils.isEmpty(number)) {
  SMSSDK.submitVerificationCode("86", phone, number);// 验证短信
  } else {
  Toast.makeText(MainActivity.this, "验证码不能为空", Toast.LENGTH_SHORT)
   .show();
  return;
  }
  break;
 default:
  break;
 }
 }
 
 private void getCode() {
 mHandler = new Handler();
 mHandler.postDelayed(new Runnable() {
  @Override
  public void run() {
  startTimer();
  }
 }, 2000);
 }
 
 /**
 * 
 * @Description: TODO 发送成功后,开始倒计时
 * 
 */
 private void startTimer() {
 if (null == myCountDownTime) {
  myCountDownTime = new MyCountDownTime(60000, 1000, btGet, "重新发送");
 }
 myCountDownTime.start();
 }
 /**
 * 
 * @Description: TODO 一般发送失败时,需要重置Button状态
 */
 private void cancelTimer(){
 if(null != myCountDownTime){
  myCountDownTime.cancel();
  myCountDownTime.onFinish();
 }
 }
 
 protected void onDestroy() {
 // 销毁回调监听接口
 SMSSDK.unregisterAllEventHandler();
 super.onDestroy();
 }
 
 @Override
 public boolean handleMessage(Message msg) {
 int event = msg.arg1;
 int result = msg.arg2;
 Object data = msg.obj;
 if (result == SMSSDK.RESULT_COMPLETE) {
  // 回调完成
  if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
  // 提交验证码成功
  Toast.makeText(MainActivity.this, "验证成功", Toast.LENGTH_SHORT)
   .show();
  } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
  // 获取验证码成功
  Toast.makeText(MainActivity.this, "获取验证码成功", Toast.LENGTH_SHORT)
   .show();
  } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
  // 返回支持发送验证码的国家列表
  }
 } else {
  int status = 0;
  try {
  ((Throwable) data).printStackTrace();
  Throwable throwable = (Throwable) data;
 
  JSONObject object = new JSONObject(throwable.getMessage());
  String des = object.optString("detail");
  status = object.optInt("status");
  if (!TextUtils.isEmpty(des)) {
   Toast.makeText(MainActivity.this, des, Toast.LENGTH_SHORT)
    .show();
   return false;
  }
  } catch (Exception e) {
  SMSLog.getInstance().w(e);
  }
 }
 return false;
 }
}

5.运行就可以显示目标效果了。

您可能感兴趣的文章:

相关文章