Android Studio使用Mob获取手机验证码

最近,在做毕设,对于我这个android小白来说,真的是很头大啊,好多东西都不会。。。

无奈,边学边做呗,都是自己作的啊!其中有一个模块是通过手机获取验证码进行登录,开始用的是Mob的后台获取验证码实现的,但是现在和服务端连接接口后,要改代码,但是觉得还是有必要记录一下,万一以后用得上呢!

先来看看最后的效果图,这是点击获取验证码之后的效果,初始效果见后面的布局文件哦:

              

1. mod官网下载相关包

  • 这里我们需要用到几个包,这里自己就先注册一个账号了,因为如果要使用这个功能的话,后面是会用到的账号中的信息的。

  • 点击这里添加应用,随意取一个名字就好:

  • 应用添加成功后,添加SDK产品SMSSDK:

  • 注意生成的AppKey和AppSecret哦,接下来我们会用到:

  • 接下来就去下载中心,下载我们需要的包:

  •  这里提醒一句哦,主要看自己下载的版本,这里分了IOS、android和其他的,我的手机是android,所以下的android的版本:

  •  点击Android版的,会有这么一个弹框:

当然,你可以选择在build.gradle中直接配置,这样就不用下载离线SDK了,我这里讲的是第二种,第一种的话,按着上图的步骤操作就好了。

2. 配置Android Studio的环境

解压上面下载的压缩包,找到这样的几个jar包:

把它们放在项目的libs文件夹下:

修改build.gradle,添加如下:

3. 配置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.READ_SMS" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  • 在application节点下添加name属性:
android:name="com.mob.MobApplication"
  • 在application里添加一个activity:
<activity

   android:name="com.mob.tools.MobUIShell"

   android:theme="@android:style/Theme.Translucent.NoTitleBar"

   android:configChanges="keyboardHidden|orientation|screenSize"

   android:windowSoftInputMode="stateHidden|adjustResize"/>
  • 最后再补上两个meta-data,其中Mob-AppKey和Mob-AppSecret就是我们之前申请到的,这里把你的替换上去就好了,我就不把我的贴出来了。
<meta-data android:name="Mob-AppKey" android:value="你的AppKey"/>
<meta-data android:name="Mob-AppSecret" android:value="你的AppSecret"/>
  • 当然,如果你不想在这里设置,也可以通过代码,代码设置就不需要继承上面说到的MobApplication,只要在使用SMSSDK之前,将AppKey和AppSecret传过去即可,例如:
// 通过代码注册你的AppKey和AppSecret
MobSDK.init(context,"你的AppKey","你的AppSecret");

最后,附上完整的AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manage_system">
    <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" />
    <application
        android:name="com.mob.MobApplication"
       android:allowBackup="true"
        android:icon="@mipmap/logo"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".LoginByPhoneActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.mob.tools.MobUIShell"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:windowSoftInputMode="stateHidden|adjustResize"/>
        <!-- 通过AndroidManifest配置AppKey和AppSecret,如果你选择通过代码配置,则不需要配置以下meta-data -->
        <meta-data android:name="Mob-AppKey" android:value="你的AppKey"/>
        <meta-data android:name="Mob-AppSecret" android:value="你的AppSecret"/>
    </application>

</manifest>

4. 页面布局ms_login_phone.xml

先看一张效果图:

哈哈,把学校图标遮住了,大家换成自定义的图像即可,布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<!--登录界面,用LinearLayout-->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
  
    <!--标题栏-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <!--显示头像,记得加入id iv_head -->
        <ImageView
            android:id="@+id/iv_logo"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="15dp"
            android:background="@drawable/logo_icon" />

        <TextView
            android:id="@+id/bs_header"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_gravity="bottom"
            android:padding="10dp"
            android:text="毕业论文管理系统"
            android:textColor="#b4594c"
            android:textSize="14sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="35dp"
        android:layout_marginRight="35dp"
        android:orientation="vertical">
        <!--输入框-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_marginTop="50dp">

            <ImageView
                android:id="@+id/img_phone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="8dp"
                android:src="@drawable/phone_icon" />

            <EditText
                android:id="@+id/edit_phone"
                android:layout_width="fill_parent"
                android:layout_height="48dp"
                android:layout_gravity="center_horizontal"
                android:layout_toRightOf="@+id/img_phone"
                android:gravity="center_vertical"
                android:hint="请输入手机号"
                android:paddingLeft="8dp"
                android:singleLine="true"
                android:phoneNumber="true"
                android:textColor="#000000"
                android:textColorHint="#a3a3a3"
                android:textSize="14sp" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="45dp"
            android:layout_marginTop="10dp"
            android:paddingLeft="8dp"
            android:gravity="center_horizontal"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/edit_cord"
                android:layout_width="34dp"
                android:layout_height="match_parent"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:background="@drawable/edit_bg_border"
                android:hint="请输入验证码"
                android:padding="8dp"
                android:textSize="14sp" />
            <!--layout_weight="1" layout_width="0dp"实现均分效果-->
            <Button
                android:id="@+id/btn_checkCode"
                android:layout_width="160dp"
                android:layout_height="match_parent"
                android:layout_gravity="center_horizontal"
                android:layout_marginLeft="8dp"
                android:background="@drawable/login_button_selector"
                android:text="获取验证码"
                android:textColor="@android:color/white"
                android:textSize="18sp" />
        </LinearLayout>

        <!--按钮-->

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="15dp">

            <Button
                android:id="@+id/btn_byphone_login"
                android:layout_width="match_parent"
                android:layout_height="55dp"
                android:layout_gravity="center_horizontal"
                android:layout_marginLeft="8dp"
                android:background="@drawable/login_button_selector"
                android:text="登 陆"
                android:textColor="@android:color/white"
                android:textSize="18sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="15dp">

            <TextView
                android:id="@+id/login_by_phone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginLeft="8dp"
                android:text="账号登录"
                android:textColor="#4876FF" />

            <TextView
                android:id="@+id/help"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:text="帮助"
                android:textColor="#4876FF" />

        </LinearLayout>
    </LinearLayout>

    <!--layout_weight="1" layout_width="0dp"实现均分效果-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/bs_info"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_gravity="bottom"
            android:padding="8dp"
            android:text="XX大学  版权所有"
            android:textColor="#a7a7a7"
            android:textSize="10sp" />
    </LinearLayout>
</LinearLayout>

5. LoginByPhoneActivity,这里面就是一个业务逻辑的处理,注释已经很详细了,这里就不再多说了,直接上代码吧。

package com.manage_system;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.manage_system.ui.personal.HelpActivity;
import com.manage_system.utils.TimeCountUtil;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class LoginByPhoneActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText edit_phone;
    private EditText edit_cord;
    private TextView login_by_phone,help;
    private Button btn_checkCode;
    private Button btn_byphone_login;
    private String phone_number;
    private String cord_number;
    EventHandler eventHandler;
    private boolean flag=true;
    private TimeCountUtil mTimeCountUtil;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ms_login_phone);
        getId();
        //这里的倒计时的时间 是 :用第二参数 / 第三个三参数 = 倒计时为60秒
        mTimeCountUtil = new TimeCountUtil(btn_checkCode, 60000, 1000);

        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);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eventHandler);
    }

    /**
     * 使用Handler来分发Message对象到主线程中,处理事件
     */
    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;
            if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                if(result == SMSSDK.RESULT_COMPLETE) {
                    boolean smart = (Boolean)data;
                    if(smart) {
                        Toast.makeText(getApplicationContext(),"该手机号已经注册过,请重新输入",
                                Toast.LENGTH_LONG).show();
                        edit_phone.requestFocus();
                        return;
                    }
                }
            }
            if(result==SMSSDK.RESULT_COMPLETE)
            {
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    Toast.makeText(getApplicationContext(), "验证码输入正确",
                            Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(LoginByPhoneActivity.this,MainActivity.class);
                    startActivity(intent);
                }
            }
            else
            {
                if(flag)
                {
                    btn_checkCode.setVisibility(View.VISIBLE);
                    Toast.makeText(getApplicationContext(),"验证码获取失败请重新获取", Toast.LENGTH_LONG).show();
                    edit_phone.requestFocus();
                }
                else
                {
                    Toast.makeText(getApplicationContext(),"验证码输入错误", Toast.LENGTH_LONG).show();
                }
            }
        }

    };

    /**
     * 获取id
     */
    private void getId()
    {
        edit_phone=(EditText) findViewById(R.id.edit_phone);
        edit_cord=(EditText)findViewById(R.id.edit_cord);
        btn_checkCode=(Button)findViewById(R.id.btn_checkCode);
        btn_byphone_login=(Button)findViewById(R.id.btn_byphone_login);
        login_by_phone=(TextView)findViewById(R.id.login_by_phone);
        help=(TextView)findViewById(R.id.help);
        btn_checkCode.setOnClickListener(this);
        btn_byphone_login.setOnClickListener(this);
        login_by_phone.setOnClickListener(this);
        help.setOnClickListener(this);
    }

    /**
     * 按钮点击事件
     */
    public void onClick(View v)
    {
        Intent intent;
        switch (v.getId())
        {
            case R.id.btn_checkCode:
                mTimeCountUtil.start();
                if(judPhone())//去掉左右空格获取字符串
                {
                    SMSSDK.getVerificationCode("86",phone_number);
                    edit_cord.requestFocus();
                }
                break;
            case R.id.btn_byphone_login:
                if(judCord())
                    SMSSDK.submitVerificationCode("86",phone_number,cord_number);
                flag=false;
                break;
            case R.id.login_by_phone:
                intent = new Intent(LoginByPhoneActivity.this,LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.help:
                intent = new Intent(LoginByPhoneActivity.this,HelpActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private boolean judPhone()
    {
        if(TextUtils.isEmpty(edit_phone.getText().toString().trim()))
        {
            Toast.makeText(LoginByPhoneActivity.this,"请输入您的电话号码",Toast.LENGTH_LONG).show();
            edit_phone.requestFocus();
            return false;
        }
        else if(edit_phone.getText().toString().trim().length()!=11)
        {
            Toast.makeText(LoginByPhoneActivity.this,"您的电话号码位数不正确",Toast.LENGTH_LONG).show();
            edit_phone.requestFocus();
            return false;
        }
        else
        {
            phone_number=edit_phone.getText().toString().trim();
            String num="[1][358]\\d{9}";
            if(phone_number.matches(num))
                return true;
            else
            {
                Toast.makeText(LoginByPhoneActivity.this,"请输入正确的手机号码",Toast.LENGTH_LONG).show();
                return false;
            }
        }
    }

    private boolean judCord()
    {
        judPhone();
        if(TextUtils.isEmpty(edit_cord.getText().toString().trim()))
        {
            Toast.makeText(LoginByPhoneActivity.this,"请输入您的验证码",Toast.LENGTH_LONG).show();
            edit_cord.requestFocus();
            return false;
        }
        else if(edit_cord.getText().toString().trim().length()!=4)
        {
            Toast.makeText(LoginByPhoneActivity.this,"您的验证码位数不正确",Toast.LENGTH_LONG).show();
            edit_cord.requestFocus();

            return false;
        }
        else
        {
            cord_number=edit_cord.getText().toString().trim();
            return true;
        }
    }

}

这里,有两个Activity的代码,没有放上来,大家根据需求换成自己的就好了,我是因为界面上的布局写了账号登录帮助,所以点击后会跳转到相应界面,这里根据项目需求进行增删就可以了。

6. 实现倒计时功能(TimeCountUtil)

package com.manage_system.utils;

import android.graphics.Color;
import android.os.CountDownTimer;
import android.widget.Button;

/**
 * Created by Violet-coco 
 * TimeCountUtil
 */
public class TimeCountUtil extends CountDownTimer {
    private Button mButton;

    public TimeCountUtil(Button button, long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        this.mButton = button;
    }

    @Override
    public void onTick(long millisUntilFinished) {
        // 按钮不可用
        mButton.setEnabled(false);
        mButton.setBackgroundColor(Color.parseColor("#dddddd"));
        String showText = millisUntilFinished / 1000 + "秒后可重新发送";
        mButton.setText(showText);
    }

    @Override
    public void onFinish() {
        // 按钮设置可用
        mButton.setEnabled(true);
        mButton.setText("重新获取验证码");
    }
}

好啦,大功告成,这下应该是问题不大了,感兴趣的小伙伴也可以试试哦!

最后,要感谢http://blog.csdn.net/qq_35812301/article/details/79150775,我这个小白也是参考完别人的教程,然后根据自己的项目需求总结的,若有什么不足,欢迎大家随时补充哦!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值