首页 > 解决方案 > 自定义侦听器在 Android Kotlin 中不起作用

问题描述

我正在尝试将接口实现为从服务中触发的侦听器。侦听器设置器工作正常,但是当我尝试使用回调onStatusChanged()时它不起作用。请让我知道我们是否可以在服务中使用侦听器。

定制服务.kt

class CustomService : Service(){

    object Status{
         var serviceRunning:Boolean = false
    }

    interface StatusListener{
        fun onStatusChanged(status:Boolean) = Unit
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val returnVal = super.onStartCommand(intent, flags, startId)
        Status.serviceRunning = true
        val testRequest = StringRequest(
            Request.Method.GET,             
            "api.chandanmahto.com",
            Response.Listener {
                Toast.makeText(
                    this,
                    "Service has been started! You can now close the app",
                    Toast.LENGTH_LONG
                ).show() // this toast is shown
                statusListener?.onStatusChanged(true)
            },
            Response.ErrorListener {
                Toast.makeText(
                    this,
                    "Server cannot be reached!!!", Toast.LENGTH_LONG
                ).show()
                statusListener?.onStatusChanged(false)
                stopSelf()
            }
        )
        queue.add(testRequest)
        return returnVal
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    fun setStatusListener(listener: StatusListener){
        // this runs without problem
        statusListener = listener
    }
}

仪表板活动.kt

class DashboardActivity : AppCompatActivity() {

    private lateinit var serviceLog: TextView
    private lateinit var service: Intent
    private val adrsService: ADRSService = ADRSService()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dashboard)
        serviceLog = findViewById(R.id.service_logs)
        service = Intent(this, ADRSService::class.java)
        serviceSwitch.setOnClickListener {
            serviceLog.text = getString(R.string.dashboard_service_working)
            if (serviceSwitch.isChecked) {
                startService(service)
            } else {
                stopService(service)
                serviceLog.text = getString(R.string.dashboard_service_stopped)
                Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show()
            }
        }
        adrsService.setStatusListener(object : ADRSService.StatusListener {
            override fun onStatusChanged(status: Boolean) {
                Log.d("LISTENER", "Listener Fired")    // this doesn't get logged.
                serviceLog.text =
                    if (status) getString(R.string.dashboard_service_started) else getString(R.string.dashboard_service_stopped)
            }
        })
    }
}

PS 我是 Kotlin 的新手,如果这是一个愚蠢的问题,我很抱歉。

标签: androidkotlin

解决方案


推荐阅读