安卓开发集成SMS短信验证码模块,mob平台

前一段时间公司有需求搞一个登录的短信验证模块,上网看了下,大都不靠谱,都是几年前的SDK,对最新的SDK不兼容,于是自己搞了一个。可以适配MOB平台最新版的SDK。

废话不多说,直接上教程。

一、上Mob官网下载最新版的SMSSDK

http://www.mob.com/downloadDetail/SMS/android/



二、把下载好的文件解压缩,把SMSSDK文件夹导入到eclipse中


三、在你自己的项目中添加依赖

四、在AndroidManifest文件中添加以下代码

1.权限:

<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.READ_SMS" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

2.Activity

 <activity
            android:name="com.mob.tools.MobUIShell"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:windowSoftInputMode="stateHidden|adjustResize" />


        <!-- 通过AndroidManifest配置AppKey和AppSecret,如果你选择通过代码配置,则不需要配置以下meta-data -->
        <meta-data
            android:name="Mob-AppKey"
            android:value="你申请到的key" />
        <meta-data
            android:name="Mob-AppSecret"
            android:value="你申请到的secret" />

注意:最后一定要在application标签下加上这句代码:android:name="com.mob.MobApplication"

五、MainActivity、布局



package com.example.smsdemo;


import java.util.ArrayList;


import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
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.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;


//请注意:测试短信条数限制发送数量:20条/天,APP开发完成后请到mob.com后台提交审核,获得不限制条数的免费短信权限。
public class MainActivity extends Activity implements Callback, OnClickListener {


private boolean gettingFriends, ready;
private EditText et_phone, et_code;
private Button bt_send, bt_login;
private ImageView iv_phone, iv_code;
private MyCountDownTimer myCountDownTimer;


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gettingFriends = false;
if (Build.VERSION.SDK_INT >= 23) {
int readPhone = checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
int receiveSms = checkSelfPermission(Manifest.permission.RECEIVE_SMS);
int readSms = checkSelfPermission(Manifest.permission.READ_SMS);
int readContacts = checkSelfPermission(Manifest.permission.READ_CONTACTS);
int readSdcard = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);


int requestCode = 0;
ArrayList<String> permissions = new ArrayList<String>();
if (readPhone != PackageManager.PERMISSION_GRANTED) {
requestCode |= 1 << 0;
permissions.add(Manifest.permission.READ_PHONE_STATE);
}
if (receiveSms != PackageManager.PERMISSION_GRANTED) {
requestCode |= 1 << 1;
permissions.add(Manifest.permission.RECEIVE_SMS);
}
if (readSms != PackageManager.PERMISSION_GRANTED) {
requestCode |= 1 << 2;
permissions.add(Manifest.permission.READ_SMS);
}
if (readContacts != PackageManager.PERMISSION_GRANTED) {
requestCode |= 1 << 3;
permissions.add(Manifest.permission.READ_CONTACTS);
}
if (readSdcard != PackageManager.PERMISSION_GRANTED) {
requestCode |= 1 << 4;
permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (requestCode > 0) {
String[] permission = new String[permissions.size()];
this.requestPermissions(permissions.toArray(permission), requestCode);
return;
}
}
inits();
myCountDownTimer = new MyCountDownTimer(60000, 1000);
registerSDK();
initfocusclick();
}


private void initfocusclick() {
et_phone.setOnFocusChangeListener(new OnFocusChangeListener() {


@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
iv_phone.setBackgroundResource(R.drawable.phone_click);
et_phone.setTextColor(Color.rgb(54, 195, 222));
} else {
iv_phone.setBackgroundResource(R.drawable.phone);
et_phone.setTextColor(Color.rgb(218, 218, 218));
}
}
});
et_code.setOnFocusChangeListener(new OnFocusChangeListener() {


@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
iv_code.setBackgroundResource(R.drawable.code_click);
et_code.setTextColor(Color.rgb(54, 195, 222));
} else {
iv_code.setBackgroundResource(R.drawable.code);
et_code.setTextColor(Color.rgb(218, 218, 218));
}
}
});
}


private void inits() {
et_phone = (EditText) findViewById(R.id.et_phone);
et_code = (EditText) findViewById(R.id.et_code);
bt_send = (Button) findViewById(R.id.bt_send);
bt_login = (Button) findViewById(R.id.bt_login);
iv_phone = (ImageView) findViewById(R.id.iv_phone);
iv_code = (ImageView) findViewById(R.id.iv_code);


bt_send.setOnClickListener(this);
bt_login.setOnClickListener(this);


}


private class MyCountDownTimer extends CountDownTimer {


public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}


// 计时过程
@Override
public void onTick(long l) {
// 防止计时过程中重复点击
bt_send.setClickable(false);
bt_send.setText(l / 1000 + "s");
}


// 计时完毕的方法
@Override
public void onFinish() {
// 重新给Button设置文字
bt_send.setText("重新获取");
// 设置可点击
bt_send.setClickable(true);
}
}


public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
registerSDK();
}


private void registerSDK() {
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);
ready = true;
}


protected void onDestroy() {
if (ready) {
// 销毁回调监听接口
SMSSDK.unregisterAllEventHandler();
}
super.onDestroy();
}


@Override
protected void onPause() {
super.onPause();
}


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) {
// right
Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

}
} else {
((Throwable) data).printStackTrace();
Toast.makeText(MainActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
}


return false;
}


// 提交用户信息
/*
* private void registerUser(String country, String phone) { Random rnd =
* new Random(); int id = Math.abs(rnd.nextInt()); String uid =
* String.valueOf(id); String nickName = "SmsSDK_User_" + uid; String avatar
* = AVATARS[id % 12]; SMSSDK.submitUserInfo(uid, nickName, avatar, country,
* phone); }
*/


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_send:
if (incorrect()) {
String number = et_phone.getText().toString().trim();
SMSSDK.getVerificationCode("86", number);
myCountDownTimer.start();
Toast.makeText(this, "验证码已发送", Toast.LENGTH_SHORT).show();
}
break;
case R.id.bt_login:
if (incorrect()) {
if (TextUtils.isEmpty(et_code.getText())) {
Toast.makeText(MainActivity.this, "验证码不能为空!", 0).show();
}else {
String vNumber = et_phone.getText().toString().trim();
String vCode = et_code.getText().toString().trim();
SMSSDK.submitVerificationCode("86", vNumber, vCode);
//Toast.makeText(this, "请等待验证", Toast.LENGTH_SHORT).show();
}
}
break;
}
}


private boolean incorrect() {
boolean isTel = true; // 标记位:true-是手机号码;false-不是手机号码
/* 判断输入的用户名是否是电话号码 */
if (et_phone.getText().toString().length() == 11) {
for (int i = 0; i < et_phone.getText().toString().length(); i++) {
char c = et_phone.getText().toString().charAt(i);
if (!Character.isDigit(c)) {
isTel = false;
break; // 只要有一位不符合要求退出循环
}
}
} else {
isTel = false;
}


if (TextUtils.isEmpty(et_phone.getText())) {
Toast.makeText(MainActivity.this, "手机号不能为空!", 0).show();
} else if (!isTel) {
Toast.makeText(MainActivity.this, "请输入正确的手机号码!", 0).show();
}
return isTel;
}
}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >


        <TextView
            android:id="@+id/tv_head_color"
            android:layout_width="match_parent"
            android:layout_height="55dp"
            android:background="#16cbc5" />


        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/tv_head_color"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="14dp"
            android:text="登录"
            android:textColor="#fff"
            android:textSize="20sp" />
    </RelativeLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="20dp"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:gravity="center"
        android:orientation="horizontal" >


        <ImageView
            android:id="@+id/iv_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:background="@drawable/phone" />


        <EditText
            android:id="@+id/et_phone"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:background="@null"
            android:hint="请输入您的手机号"
            android:inputType="number"
            android:maxLength="11"
            android:textColorHint="#C3C3C3"
            android:textSize="17sp" />


        <Button
            android:id="@+id/bt_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            android:text="获取验证码"
            android:textColor="#16cbc5"
            android:textSize="15sp" />
    </LinearLayout>


    <View
        android:layout_width="320dp"
        android:layout_height="1dp"
        android:layout_gravity="center_horizontal"
        android:background="#C3C3C3" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="10dp"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:gravity="center"
        android:orientation="horizontal" >


        <ImageView
            android:id="@+id/iv_code"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:background="@drawable/code" />


        <EditText
            android:id="@+id/et_code"
            android:layout_width="288dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="10dp"
            android:background="@null"
            android:hint="请输入您收到的验证码"
            android:inputType="number"
            android:maxLength="6"
            android:textColorHint="#C3C3C3"
            android:textSize="17sp" />
    </LinearLayout>


    <View
        android:layout_width="320dp"
        android:layout_height="1dp"
        android:layout_gravity="center_horizontal"
        android:background="#C3C3C3" />


    <Button
        android:id="@+id/bt_login"
        android:layout_width="320dp"
        android:layout_height="45dp"
        android:layout_gravity="center"
        android:layout_marginTop="50dp"
        android:background="@drawable/shape_corner_login"
        android:text="登  录"
        android:textColor="#fff"
        android:textSize="17sp" />




</LinearLayout>

代码里已经做了登录的大量逻辑,如果有登录需求的小伙伴可以直接拿去用,那么到这里就完成了,在输入框输入你自己的号码,就可以收到验证码了。同时可以验证验证码的正确性,以及提交用户信息到服务器。




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值