Koltin26.Takeout登录界面使用SMSSDK验证(12)

链接地址:https://www.mob.com/download

使用方法:

1.将下面的脚本添加到您的根模块build.gradle中

buildscript {
    repositories {
        jcenter()
    }
    
    dependencies {
        // 注册MobSDK
        classpath "com.mob.sdk:MobSDK:2018.0319.1724"
    }
}

2.在使用相应模块的build.gradle中,添加MobSDK插件和扩展,如:

apply plugin: 'com.mob.sdk'

MobSDK {
    appKey "替换为mob官方申请的appkey"
    appSecret "替换为mob官方申请的appkey对应的appSecret"
    SMSSDK {}
}

截图如下:

3.环境配置,代码中使用方法,监听每一次提交验证码操作:

        val eh = object : EventHandler() {
            override fun afterEvent(event: Int, result: Int, data: Any) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        //返回支持发送验证码的国家列表
                    }
                } else {
                    (data as Throwable).printStackTrace()
                }
            }
        }
        SMSSDK.registerEventHandler(eh) //注册短信回调

4.环境配置注销监听,避免内存泄露

// 使用完EventHandler需注销,否则可能出现内存泄漏
override fun onDestroy() {
    super.onDestroy()
    SMSSDK.unregisterEventHandler(eventHandler)
}

5.添加混淆设置,在proguard-rules.pro

-keep class com.mob.**{*;}
-keep class cn.smssdk.**{*;}
-dontwarn com.mob.**

代码中的实现:

UserFragment.kt用户信息的展示界面,会跳转到验证码登录的界面

package com.example.takeout.ui.fragment

import android.app.Fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.example.takeout.R
import com.example.takeout.ui.activity.LoginActivity
import org.jetbrains.anko.find

class UserFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val userview = View.inflate(activity, R.layout.fragment_user, null)
        val ivLogin = userview.find<ImageView>(R.id.login)
        ivLogin.setOnClickListener {
            val intent = Intent(activity, LoginActivity::class.java)
            activity.startActivity(intent)
        }
        return userview
    }
}

fragment_user.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#3090E6">

                <ImageView
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="15dp"
                    android:layout_marginTop="20dp"
                    android:layout_marginBottom="20dp"
                    android:src="@mipmap/user_center_default_avatar" />

                <FrameLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="20dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginBottom="20dp"
                    android:layout_weight="1.0">

                    <ImageView
                        android:id="@+id/login"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@mipmap/user_center_login" />

                    <LinearLayout
                        android:id="@+id/ll_userinfo"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:gravity="center"
                        android:orientation="vertical"
                        android:visibility="invisible">

                        <TextView
                            android:id="@+id/username"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"

                            android:text="username"

                            android:textColor="#FFF"
                            android:textSize="18sp" />

                        <LinearLayout

                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="10dp"
                            android:gravity="center_vertical"
                            android:orientation="horizontal">

                            <ImageView
                                android:layout_width="20dp"
                                android:layout_height="20dp"
                                android:src="@mipmap/user_center_mobile" />

                            <TextView
                                android:id="@+id/phone"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="13263203501"


                                android:textColor="#FFF"
                                android:textSize="16sp" />


                        </LinearLayout>

                    </LinearLayout>


                </FrameLayout>


            </LinearLayout>

            <ImageView
                android:id="@+id/iv_address_manager"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scaleType="fitXY"
                android:src="@mipmap/user_center_orther" />
        </LinearLayout>


    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#3090E6"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"

            android:gravity="center_vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="15dp"
                android:text="我的"
                android:textColor="#FFF"
                android:textSize="18sp" />

            <ImageView
                android:id="@+id/tv_user_setting"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_alignParentRight="true"

                android:layout_marginRight="15dp"
                android:src="@mipmap/user_center_setting" />

            <ImageView
                android:id="@+id/iv_user_notice"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_marginRight="40dp"
                android:layout_toLeftOf="@+id/tv_user_setting"
                android:src="@mipmap/user_center_notice" />


        </RelativeLayout>

    </LinearLayout>


</LinearLayout>

LoginActivity.kt登录界面的操作,首先包括监听验证码的操作动作,发送验证码和验证验证码,其中增加了验证码的倒计时操作功能

package com.example.takeout.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.os.SystemClock
import android.text.TextUtils
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import cn.smssdk.EventHandler
import cn.smssdk.SMSSDK
import com.example.takeout.R
import com.heima.takeout.utils.SMSUtil
import com.mob.MobSDK
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : AppCompatActivity() {

    //监听每一次提交验证码操作
    val eh = object : EventHandler() {
        override fun afterEvent(event: Int, result: Int, data: Any) {
            if (result == SMSSDK.RESULT_COMPLETE) {
                //回调完成
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //提交验证码成功
                    Log.d("LoginActivity", "提交验证码成功")
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //获取验证码成功
                    Log.d("LoginActivity", "获取验证码成功")
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    //返回支持发送验证码的国家列表
                }
            } else {
                (data as Throwable).printStackTrace()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        initListener()
        MobSDK.submitPolicyGrantResult(true, null);

        //注册短信回调
        SMSSDK.registerEventHandler(eh)

    }

    private fun initListener() {
        iv_user_back.setOnClickListener { finish() }
        //获取验证码
        tv_user_code.setOnClickListener {

            val phone = et_user_phone.text.toString().trim()
            //验证手机号码
            if (SMSUtil.judgePhoneNums(this, phone)) {
                // 请求验证码,其中country表示国家代码,如“86”;phone表示手机号码,如“13800138000”
                SMSSDK.getVerificationCode("86", phone)
                //开启倒计时
                tv_user_code.isEnabled = false
                Thread(CutDownTask()).start()

            }
        }
        iv_login.setOnClickListener {
            //提交验证码
            val phone = et_user_phone.text.toString().trim()
            val code = et_user_code.text.toString().trim()
            if (SMSUtil.judgePhoneNums(this, phone) && !TextUtils.isEmpty(code)) {
                // 提交验证码,其中的code表示验证码,如“1357”
                SMSSDK.submitVerificationCode("86", phone, code)
            }
            //登录外卖服务器
//            loginActivityPresenter.loginByPhone(phone)
        }
    }

    companion object {
        val TIME_MINUS = -1 //剩余时间的消息
        val TIME_IS_OUT = 0 //60s超时
    }
    //创建一个handler来刷新UI
    val handler = @SuppressLint("HandlerLeak")
    object : Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when(msg!!.what){
                TIME_MINUS -> tv_user_code.text = "剩余时间(${time})秒"
                TIME_IS_OUT -> {
                    tv_user_code.isEnabled = true
                    tv_user_code.text = "点击重发"
                    time = 60
                }
            }

        }
    }

    //倒计时的实现60s
    var time = 60
    inner class CutDownTask: Runnable {
        override fun run() {
            //倒计时循环
            while (time>0){
                //刷新剩余时间,当前子线程,使用handler
                handler.sendEmptyMessage(TIME_MINUS)
                SystemClock.sleep(999)
                time --
            }
            handler.sendEmptyMessage(TIME_IS_OUT)
        }
    }

    // 使用完EventHandler需注销,否则可能出现内存泄漏
    override fun onDestroy() {
        super.onDestroy()
        SMSSDK.unregisterEventHandler(eh)
    }
}

SMSUtil.kt验证码的合理性校验

package com.heima.takeout.utils

import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Build
import android.text.TextUtils
import android.widget.Toast
import java.util.*

object SMSUtil {
    /**
     * 判断手机号码是否合理
     * y
     */
    fun judgePhoneNums(activity: Activity, phoneNums: String): Boolean {
        if (isMatchLength(phoneNums, 11) && isMobileNO(phoneNums)) {
            return true
        }
        Toast.makeText(activity, "手机号码输入有误!", Toast.LENGTH_SHORT).show()
        return false
    }

    /**
     * 验证手机格式
     */
    fun isMobileNO(mobileNums: String): Boolean {
        /*
         * 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
		 * 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通)
		 * 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9
		 */
        val telRegex = "[1][358]\\d{9}"// "[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
        if (TextUtils.isEmpty(mobileNums))
            return false
        else
            return mobileNums.matches(telRegex.toRegex())
    }


    /**
     * 判断一个字符串的位数

     * @param str
     * *
     * @param length
     * *
     * @return
     */
    fun isMatchLength(str: String, length: Int): Boolean {
        if (str.isEmpty()) {
            return false
        } else {
            return if (str.length == length) true else false
        }
    }

    /**
     * 权限校验
     * @param activity
     */
    fun checkPermission(activity: Activity) {
        if (Build.VERSION.SDK_INT >= 23) {
            val readPhone = activity.checkSelfPermission(Manifest.permission.READ_PHONE_STATE)
            val receiveSms = activity.checkSelfPermission(Manifest.permission.RECEIVE_SMS)
            val readSms = activity.checkSelfPermission(Manifest.permission.READ_SMS)
            val readContacts = activity.checkSelfPermission(Manifest.permission.READ_CONTACTS)
            val readSdcard = activity.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)

            var requestCode = 0
            val permissions = ArrayList<String>()
            if (readPhone != PackageManager.PERMISSION_GRANTED) {
                requestCode = requestCode or (1 shl 0)
                permissions.add(Manifest.permission.READ_PHONE_STATE)
            }
            if (receiveSms != PackageManager.PERMISSION_GRANTED) {
                requestCode = requestCode or (1 shl 1)
                permissions.add(Manifest.permission.RECEIVE_SMS)
            }
            if (readSms != PackageManager.PERMISSION_GRANTED) {
                requestCode = requestCode or (1 shl 2)
                permissions.add(Manifest.permission.READ_SMS)
            }
            if (readContacts != PackageManager.PERMISSION_GRANTED) {
                requestCode = requestCode or (1 shl 3)
                permissions.add(Manifest.permission.READ_CONTACTS)
            }
            if (readSdcard != PackageManager.PERMISSION_GRANTED) {
                requestCode = requestCode or (1 shl 4)
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
            if (requestCode > 0) {
                val permission = arrayOfNulls<String>(permissions.size)
                activity.requestPermissions(permissions.toTypedArray(), requestCode)
                return
            }
        }
    }
}

项目下的build.gradle

app下的build.gradle

效果如下:

监听代码打印如下:

2020-10-24 01:14:25.360 12945-16896/com.example.takeout D/LoginActivity: 获取验证码成功
2020-10-24 01:16:34.256 12945-17277/com.example.takeout D/LoginActivity: 获取验证码成功
2020-10-24 01:17:14.665 12945-17318/com.example.takeout D/LoginActivity: 提交验证码成功

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值