使用mob第三方平台提供的免费短信验证码服务SMSSDK。
在Mob官网中注册登录并创建应用,获取相应的App key和App Secret。
在线安装,免下载SDK(官网介绍)
- 在根目录下的build.gradle文件中添加内容
- 在app目录下的build.gradle文件中添加MobSDK插件和扩展
apply plugin: 'com.mob.sdk'MobSDK {appKey "App key"appSecret "App Secret"SMSSDK {}
}
实例
使用方法 参考MobTech文档说明
以下只可用于中国内陆,未设置区号选择,即只可用于:+86 手机号
//需要先判断输入的手机号是否已被注册(后台接口实现)
public class RegisterActivity extends BaseActivity implements View.OnClickListener {private static final String TAG = "RegisterActivity";int time = Constants.MESSAGE_COUNTDOWNTIME; //短信验证码发送倒计时private String phone;private EditText mEt_verificationCode, mEt_phone;private Button mBtn_getCode, mBtn_registerNext;private TextView mTv_sendMessage;EventHandler mEventHandler;private ImageView mIv_back;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_register);initView(); //初始化viewinitTextChanged(); //注册手机号EditText输入监听initEventHandler(); //注册监听回调事件}/*** 初始化view*/private void initView() {
// 后退mIv_back = findViewById(R.id.iv_back);mIv_back.setOnClickListener(this);
// 手机号、验证码输入框mEt_phone = findViewById(R.id.et_phone);mEt_verificationCode = findViewById(R.id.et_verificationCode);
// 获取验证码按钮mBtn_getCode = findViewById(R.id.btn_getCode);mBtn_getCode.setOnClickListener(this);mBtn_getCode.setEnabled(false); //未输入手机号,按钮不可点击
// 验证码提示信息mTv_sendMessage = findViewById(R.id.tv_sendMessage);mTv_sendMessage.setVisibility(View.INVISIBLE);
// 下一步按钮mBtn_registerNext = findViewById(R.id.btn_registerNext);mBtn_registerNext.setOnClickListener(this);}/*** 手机号输入监听*/private void initTextChanged() {mEt_phone.addTextChangedListener(new TextWatcher() {@Overridepublic void beforeTextChanged(CharSequence s, int start, int count, int after) {}@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {}@Overridepublic void afterTextChanged(Editable s) {Log.d(TAG, "afterTextChanged: mEt_phone.getText().toString().length()==" + mEt_phone.getText().toString().length());if (mEt_phone.getText().toString().length() == 11) {mBtn_getCode.setEnabled(true);} else {mBtn_getCode.setEnabled(false);}}});}public void onClick(View v) {switch (v.getId()) {
// “后退”点击事件case R.id.iv_back:onBackPressed(); //后退操作break;
// "获取验证码"点击事件case R.id.btn_getCode:phone = mEt_phone.getText().toString();Log.d(TAG, "onClick: 获取验证码,phone==\" + phone");boolean result = UserUtils.validatePhone(this, phone); //验证手机号if (!result) return;//判断网络状态mTv_sendMessage.setVisibility(View.INVISIBLE);SMSSDK.getVerificationCode("86", phone); //请求发送验证码的服务Log.d(TAG, "onClick: 获取验证码,phone==\" + phone");break;
// "注册"按钮点击事件case R.id.btn_registerNext:Log.d(TAG, "onClick: -注册--");mTv_sendMessage.setVisibility(View.INVISIBLE);phone = mEt_phone.getText().toString();Log.d(TAG, "onClick: phone==" + phone);boolean validate = UserUtils.validatePhone(this, phone); //验证手机号if (validate) {SMSSDK.submitVerificationCode("86", phone, mEt_verificationCode.getText().toString()); //提交验证码}break;default:break;}}private void initEventHandler() {mEventHandler = new EventHandler() {@Overridepublic void afterEvent(int event, int result, Object data) {// TODO 此处不可直接处理UI线程,处理后续操作需传到主线程中操作Message msg = new Message();msg.arg1 = event;msg.arg2 = result;msg.obj = data;mHandler.sendMessage(msg);}};SMSSDK.registerEventHandler(mEventHandler); //注册一个事件回调监听}Handler mHandler = new Handler() {public void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);int event = msg.arg1;int result = msg.arg2;Object data = msg.obj;Log.e("event", "event==" + event + "result==" + result);if (result == SMSSDK.RESULT_COMPLETE) {//回调完成Log.d(TAG, "handleMessage: --回调完成--");if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交验证码成功Log.d(TAG, "handleMessage: 提交验证码成功");Toast.makeText(getApplicationContext(), "验证成功", Toast.LENGTH_LONG).show();startActivity(new Intent(RegisterActivity.this, SetPasswordActivity.class)); //跳转到设置登录密码界面} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {//获取验证码成功Log.d(TAG, "handleMessage: 获取验证码成功,验证码已发送");Toast.makeText(getApplicationContext(), "验证码已发送,请注意查收", Toast.LENGTH_SHORT).show();messageCountDown(); //倒计时} else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {//返回支持发送验证码的国家列表Log.d(TAG, "handleMessage: 获取国家列表成功");} else {Log.d(TAG, "handleMessage: 捕捉");}} else {int status = 0;try {Throwable throwable = (Throwable) data;throwable.printStackTrace();JSONObject object = new JSONObject(throwable.getMessage());status = object.optInt("status");//错误代码Log.d(TAG, "handleMessage: -回调失败--");Log.d(TAG, "handleMessage: data==" + data + " status==" + status);} catch (Exception e) {//do somethingSMSLog.getInstance().w(e);}if (status == 468) {Log.d(TAG, "handleMessage: 验证码输入错误,请重新输入");mTv_sendMessage.setText("验证码输入错误,请重新输入");mTv_sendMessage.setVisibility(View.VISIBLE);} else if (status == 466) {Log.d(TAG, "handleMessage: 验证码为空");mTv_sendMessage.setText("验证码为空");mTv_sendMessage.setVisibility(View.VISIBLE);} else if (status == 462) {mTv_sendMessage.setText("当前操作过于频繁");mTv_sendMessage.setVisibility(View.VISIBLE);} else if (status == 467) {mTv_sendMessage.setText("验证失败3次,验证码失效,请重新请求");mTv_sendMessage.setVisibility(View.VISIBLE);} else if (status == 477) {mTv_sendMessage.setText("当前手机号发送短信的数量超过限额");mTv_sendMessage.setVisibility(View.VISIBLE);} else {Log.d(TAG, "handleMessage: 错误" + status);}}}};/*** 发送短信验证码60s倒计时* millisInFuture 倒计时总时长* countDownInterval 间隔时间*/private void messageCountDown() {mBtn_getCode.setEnabled(false); //“获取验证码”按钮不可点击CountDownTimer countDownTimer = new CountDownTimer(time * 1000, 1000) {@Overridepublic void onTick(long millisUntilFinished) {Log.d(TAG, "onTick: time==" + time);mBtn_getCode.setText(time-- + "秒后再次获取");}@Overridepublic void onFinish() {mTv_sendMessage.setVisibility(View.INVISIBLE);mBtn_getCode.setText("获取验证码");mBtn_getCode.setEnabled(true);}};countDownTimer.start();}/*** 注销监听,避免内存泄露*/protected void onDestroy() {super.onDestroy();SMSSDK.unregisterEventHandler(mEventHandler);}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".Activities.RegisterActivity"><ImageViewandroid:layout_width="106dp"android:layout_height="76dp"android:layout_marginLeft="@dimen/marginSize"android:layout_marginTop="25dp"android:src="@mipmap/logo" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="28dp"android:layout_marginBottom="30dp"android:text="注册账号"android:textColor="@android:color/black"android:textSize="@dimen/navBarTitleSize" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="@dimen/marginSize"android:orientation="horizontal"><ImageViewandroid:layout_width="@dimen/inputIconSize"android:layout_height="@dimen/inputIconSize"android:layout_gravity="center"android:layout_marginLeft="@dimen/marginSize"android:layout_marginRight="@dimen/marginSize"android:src="@mipmap/phone" /><EditTextandroid:id="@+id/et_phone"android:layout_width="0dp"android:layout_height="@dimen/inputViewHeight"android:layout_weight="1"android:background="@drawable/shape_radius"android:hint="请输入手机号"android:inputType="number"android:maxLength="11"android:paddingLeft="@dimen/marginSize" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="@dimen/marginSize"android:orientation="horizontal"><ImageViewandroid:layout_width="@dimen/inputIconSize"android:layout_height="@dimen/inputIconSize"android:layout_gravity="center"android:layout_marginLeft="@dimen/marginSize"android:layout_marginRight="@dimen/marginSize"android:src="@mipmap/password" /><EditTextandroid:id="@+id/et_verificationCode"android:layout_width="0dp"android:layout_height="@dimen/inputViewHeight"android:layout_weight="1"android:background="@drawable/shape_radius"android:hint="请输入验证码"android:inputType="number"android:maxLength="6"android:paddingLeft="@dimen/marginSize" /><Buttonandroid:id="@+id/btn_getCode"android:layout_width="wrap_content"android:layout_height="match_parent"android:layout_marginRight="@dimen/marginSize"android:clickable="false"android:inputType="number"android:text="获取验证码" /></LinearLayout><TextViewandroid:id="@+id/tv_sendMessage"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="54dp"android:layout_marginTop="@dimen/paddingIconSize"android:text="验证码为空"android:textColor="@android:color/holo_red_dark"android:visibility="invisible" /><Buttonandroid:id="@+id/btn_register"style="@style/commitBtn"android:layout_marginTop="@dimen/marginSize"android:text="注 册" /></LinearLayout>
效果图: