【问题标题】:How do i use non static method in kotlin?如何在 kotlin 中使用非静态方法?
【发布时间】:2018-10-18 10:05:09
【问题描述】:

我有一个类扩展BroadcastReceiver。因此,当消息到达时,将调用该方法。现在在那个方法中,我正在调用另一个类的方法来设置EditText 中的文本。但是由于我使用的是 kotlin,所以我需要在伴随对象中使用静态方法。那么如何在该方法或其他地方为我的EditText 调用setText

我的BroadcastReceiver班级:

class SMS : BroadcastReceiver() {

    val OTP_REGEX = "[0-9]{1,6}"

    override fun onReceive(context: Context, intent: Intent) {
        Log.e("onReceive", "==->$intent")

        val bundle = intent.extras
        try {
            if (bundle != null) {
                Log.e("onReceive", "==->$bundle")
                val pdusObj = bundle.get("pdus") as Array<Any>
                for (i in pdusObj.indices) {
                    val currentMessage = SmsMessage.createFromPdu(pdusObj[i] as ByteArray)
                    val phoneNumber = currentMessage.displayOriginatingAddress
                    val senderNum = phoneNumber
                    val message = currentMessage.displayMessageBody

                    Log.e("getMessage", "===->$message")

                    try {
                        VerifyOTPActivity.ReceievdMsg(message);
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

} 

我需要在编辑文本中设置该消息的类。

class VerifyOTPActivity : AppCompatActivity()  {

    companion object {

        @JvmStatic
        fun ReceievdMsg(message: String) {
            var otp = ""
            val OTP_NUMBERS = "[0-9]{1,6}"
            val pattern = Pattern.compile(OTP_NUMBERS)
            val matcher = pattern.matcher(message)

            while (matcher.find()) {
                otp = matcher.group()
            }

            try {
               // edt.setText(otp) // Edit text
            } catch (e: Exception) {

            }
        }

    }

    var mobileNo: String = ""

    var preference: AppPreference? = null
    lateinit var adminAPI: AdminAPI
    lateinit var customDialog: CustomDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_verify_otp)

        preference = Utils.getAppPreference(applicationContext)
        adminAPI = ServiceGenerator.getAPIClass()
        customDialog = CustomDialog(this)
        customDialog.setCancelable(false)

        val intent: Intent = intent

        mobileNo = intent.getStringExtra("mobileNo")

        workonIds()
        setupToolBar()
    }

    private fun setupToolBar() {
        txt_toolbar_title.gravity = Gravity.CENTER
    }

    private fun workonIds() {
        txt_mobile_no.setText(mobileNo)

        txt_mobile_no.setOnClickListener{
            onBackPressed()
        }

        layout_next.setOnClickListener {
            val getOTP = edt_otp.text.toString().trim()
            val getMobileNo = txt_mobile_no.text.toString().trim()

            if (getOTP.isEmpty()) {
                C.showToast(applicationContext, resources.getString(R.string.emptyotp))
            } else if (getOTP.length < 6) {
                C.showToast(applicationContext, resources.getString(R.string.validotp))
            } else {
                verifyOTP(getMobileNo , getOTP)
            }
        }
    }

    private fun verifyOTP(mobileNo: String, otp: String) {
        customDialog.show()
        val sendOTP : Call<AppModel> = adminAPI.VerifyOTP(mobileNo , otp)
        sendOTP.enqueue(object : Callback<AppModel> {
            override fun onFailure(call: Call<AppModel>?, t: Throwable?) {
                customDialog.dismiss()
                C.errorToast(applicationContext , t)
            }

            override fun onResponse(call: Call<AppModel>?, response: Response<AppModel>?) {
                customDialog.dismiss()
                val appModel : AppModel = response!!.body()!!
                if (appModel != null) {
                    if (appModel.isStatus) {
                        val intent = Intent(applicationContext, UserRegistrationActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                        preference!!.verify = true
                        preference!!.mobileNumber = mobileNo
                        intent.putExtra("mobileNo", mobileNo)
                        startActivity(intent)
                    } else {
                        C.showToast(applicationContext , appModel.message)
                    }
                } else {
                    C.defaultError(applicationContext)
                }
            }
        })
    }

}

如何在我的EditText 中设置该消息?

【问题讨论】:

    标签: java android kotlin static-methods


    【解决方案1】:

    您可以在VerifyOTPActivity 中创建内部类并使用BroadcastReceiver 对其进行扩展。在您的onReceive() 内部,您将可以访问您的VerifyOTPActivity 实例,并且可以调用findViewById() 来让您的TextView 实例在那里写入您的文本。 当然,您应该在VerifyOTPActivityunregisterReceiver() 内部onCreate() 内部调用registerReceiver() onDestroy()@

    换句话说,只需将您的 SMS braodcast 接收器设置为 VerifyOTPActivity 内部并将其注册绑定到活动生命周期

    【讨论】:

    • 实际上我已经用不同的类在java中开发了整个过程。但我无法在 kotlin 中实现这一点。不用担心,这次我将使用内部类概念。谢谢顺便说一句@Mykhailo Yuzheka
    • 在activity销毁的时候取消注册不会泄露
    • 它会因为一个内部类,如果不是静态的(如果你想能够访问你的实例就是这种情况),保持对它的“父”的引用。由于这个“父母”保留了对 Context 的引用......你会度过一段糟糕的时光
    【解决方案2】:

    您可以设置一个单例的事件总线。这样,您可以从您的 BroadcastReceiver 将事件发送到总线,从您的 Activity/Fragment/Whatever 您可以订阅这些事件并做出相应的反应

    您可以查看一些库,例如 EventBusOtto,尽管我强烈推荐 RxJava。它有点复杂但更强大

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      相关资源
      最近更新 更多