android - 自定义侦听器在 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 的新手,如果这是一个愚蠢的问题,我很抱歉。
解决方案
推荐阅读
- python - 将字符串附加到列表/字符串返回'None'或'AttributeError:'str'对象在python中没有属性'append''
- php - PHP:将带有单独行的数组作为值插入数据库
- c# - .NET Core 3.1 Windows 服务的 EventLog 源名称
- java - 按员工编号对字符串数组进行排序
- flask - Flask- Session (server-side cache) - CSRF attacks
- jenkins - 如何在 Jenlins Job DSL 中声明PromotedBuildParameterDefinition?
- google-chrome - Chrome:更改相机权限弹出窗口中按钮的顺序
- c# - blazor webassembly windows 身份验证 + .netcore 托管
- peoplesoft - 在验证电子邮件地址 peoplecode 时计算 @ 的出现次数
- python - 在单个熊猫数据框中连接具有相同列值的行