当前位置: 首页 > 工具软件 > takeout > 使用案例 >

Koltin27.Takeout登录SMSSDK验证后获取数据(13)

狄宜然
2023-12-01

HomeFragment.kt界面的逻辑

package com.example.takeout.ui.fragment

import android.app.Fragment
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.takeout.R
import com.example.takeout.model.beans.Seller
import com.example.takeout.dagger2.component.DaggerHomeFragmentComponent
import com.example.takeout.dagger2.module.HomeFragmentModule
import com.example.takeout.presenter.HomeFragmentPresenter
import com.example.takeout.ui.adapter.HomeRvAdapter
import kotlinx.android.synthetic.main.fragment_home.*
import org.jetbrains.anko.find
import org.jetbrains.anko.toast
import javax.inject.Inject

class HomeFragment : Fragment() {
    lateinit var homeRvAdapter: HomeRvAdapter//延迟初始化
    lateinit var rvHome: RecyclerView
    //dragger2注解使用prenster
    @Inject
    lateinit var homeFragmentPresenter:HomeFragmentPresenter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = View.inflate(activity, R.layout.fragment_home, null)
        rvHome = view.find<RecyclerView>(R.id.rv_home)
        //上下布局
        rvHome.layoutManager = LinearLayoutManager(activity)
        homeRvAdapter = HomeRvAdapter(activity)
        rvHome.adapter = homeRvAdapter
//        homeFragmentPresenster = HomeFragmentPresenster(this)
        //TODO:解耦View层和P层,通过dagger2(基于注解的依赖注入)生成HomeFragmentPresenter
        DaggerHomeFragmentComponent.builder().homeFragmentModule(HomeFragmentModule(this)).build().inject(this)

        distance = 120.dp2px()
        return view
    }

    fun Int.dp2px(): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            toFloat(), resources.displayMetrics
        ).toInt()

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initData()
    }

    val datas: ArrayList<Seller> = ArrayList<Seller>()
    var sum: Int = 0
    var distance: Int = 0
    var alpha = 55
    private fun initData() {
//        for (i in 0 until 100) {
//            datas.add("我是商家:" + i)
//        }
        homeFragmentPresenter.getHomeInfo()
//        homeRvAdapter.setData(datas)
    }

    //    所有的数据
    val allList: ArrayList<Seller> = ArrayList()
    fun onHomeSuccess(nearbySellers: List<Seller>, otherSellers: List<Seller>) {
        allList.clear()
        allList.addAll(nearbySellers)
        allList.addAll(otherSellers)
        homeRvAdapter.setData(allList)

        //有数据可以滚动才可以监听滚动事件,设置标题的透明效果
        rvHome.setOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (recyclerView != null) {
                    super.onScrollStateChanged(recyclerView, newState)
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                if (recyclerView != null) {
                    super.onScrolled(recyclerView, dx, dy)
                }
                sum += dy
                if (sum > distance) {
                    alpha = 255
                } else {
                    alpha = sum * 200 / distance
                    alpha += 55
                }
                Log.e("home", "alpha:$alpha")
                ll_title_container.setBackgroundColor(Color.argb(alpha, 0x31, 0x90, 0xe8))
            }
        })
    }

    fun onHomeFailed() {
        toast("onHomeFailed")
    }

}

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.example.takeout.presenter.LoginActivityPresenter
import com.heima.takeout.utils.SMSUtil
import com.mob.MobSDK
import kotlinx.android.synthetic.main.activity_login.*
import org.jetbrains.anko.toast

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", "提交验证码成功")
                    //登录外卖服务器
                    val phone = et_user_phone.text.toString().trim()
                    loginActivityPresenter.loginByPhone(phone)
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //获取验证码成功
                    Log.d("LoginActivity", "获取验证码成功")
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    //返回支持发送验证码的国家列表
                }
            } else {
                (data as Throwable).printStackTrace()
            }
        }
    }

    lateinit var loginActivityPresenter: LoginActivityPresenter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        loginActivityPresenter = LoginActivityPresenter(this)
        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)
    }

    fun onLoginSuccess() {
        finish()
        toast("登录成功")
    }

    fun onLoginFailed(){
        toast("登录失败")
    }
}

ResponseInfo1.kt网络Retrofit实现

package com.example.takeout.model.net


class ResponseInfo1 {
    //服务器开发者定义的数据结构
    var code: String = ""
    var data: String = ""
}

LoginActivityPresenter.kt网络请求

package com.example.takeout.presenter

import com.example.takeout.beans.User
import com.example.takeout.ui.activity.LoginActivity
import com.google.gson.Gson

//继承NetPresenter
class LoginActivityPresenter(val loginActivity: LoginActivity) : NetPresenter(){

    //使用手机号码登录的业务
    fun loginByPhone(phone:String) {
        val homeCall = takeoutService.loginByPhone()
        homeCall.enqueue(callback)
    }

    override fun parserJson(json: String) {
        val user = Gson().fromJson(json, User::class.java)

        if (user != null) {
            loginActivity.onLoginSuccess()
        } else{
            loginActivity.onLoginFailed()
        }
    }
}

NetPresenter.kt网络请求的基类

package com.example.takeout.presenter

import android.util.Log
import com.example.takeout.model.net.ResponseInfo1
import com.example.takeout.model.net.TakeoutService
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

abstract class NetPresenter {

    val takeoutService : TakeoutService
    init {
        val retrofit = Retrofit.Builder()
//            .baseUrl("https://mrobot.pcauto.com.cn/v2/cms/")
//            .baseUrl("https://baobab.kaiyanapp.com/")
            .baseUrl("http://127.0.0.1:8090/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        takeoutService = retrofit.create<TakeoutService>(TakeoutService::class.java!!)
    }

    abstract fun parserJson(json: String)

    val callback = object : Callback<ResponseInfo1> {
        override fun onResponse(call: Call<ResponseInfo1>?, response: Response<ResponseInfo1>?) {
            if (response == null) {
                Log.e("home", "服务器没有成功返回")
            } else {
                if (response.isSuccessful()) {
                    val responseInfo = response.body()
                    if (responseInfo.code.equals("0")) {
                        val json = responseInfo.data
                        Log.e("home", json.toString())
                        parserJson(json)
                    } else if (responseInfo.code.equals("-1")) {
                        //根据具体接口文档表示含义,比如定义-1为空数据
                        Log.e("home", "定义-1为空数据")
                    }
                } else {
                    Log.e("home", "服务器代码错误")
                }
            }
        }

        override fun onFailure(call: Call<ResponseInfo1>?, t: Throwable?) {
            //没有连上服务器
            Log.e("home", "没有连上服务器")
        }
    }
}

TakeoutService.kt服务端的配置

package com.example.takeout.model.net

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

interface TakeoutService {

//ex.    @GET("users/{user}/repos")
//ex.    fun listRepos(@Path("user") user: String): Call<List<Repo>>

    //http://127.0.0.1:8090/takeout?index=0
    @GET("takeout?index=0")
    fun getHomeInfo(): Call<ResponseInfo>

    //http://127.0.0.1:8090/takelogin?index=0
    @GET("takelogin?index=0")
    fun loginByPhone() : Call<ResponseInfo1>

}

User.kt登录成功后获取的用户信息bean

package com.example.takeout.beans

import java.io.Serializable


data class User(
    var name: String,
    var balance: String,
    var discount: String,
    var integral: String,
    var phone: String
) : Serializable {

//    var id: Long = 0
//    var pic: String? = null
//    var name: String? = null
//
//    var score: String? = null
//    var sale: String? = null
//    var ensure: String? = null
//
//    var invoice: String? = null
//    var sendPrice: String? = null
//    var deliveryFee: String? = null
//
//    var recentVisit: String? = null
//    var distance: String? = null
//    var time: String? = null
//
//    var icon: String? = null
//
//    var activityList: ArrayList<ActivityInfo>? = null

}

服务端的数据如下:

{
	"code": "0",
	"data": "{\"id\":101,\"name\":\"student\",\"balance\":0.0,\"dicouunt\":0,\"integral\":0,\"phone\":\"1230000000\"}"
}

 

 类似资料: