【发布时间】:2020-06-25 14:01:18
【问题描述】:
我刚刚创建了一个应用程序,其中我的函数 getdata() 每秒调用一次以从服务器获取新数据,并且 updateui() 函数将更新 UI 中的视图我在我的应用程序中不使用任何异步任务或协程我想这样做请告诉我该怎么做。
这是我的代码...
private fun getdata(){
try {
val api = RetroClient.getApiService()
call = api.myJSON
call!!.enqueue(object : Callback<ProductResponse> {
override fun onResponse(
call: Call<ProductResponse>,
response: Response<ProductResponse>
) {
if (response.isSuccessful) {
productList = response.body()!!.data
for (list in productList) {
if (list.BB.equals("AAA")) {
aProductList.add(list)
}
}
if (recyclerView.adapter != null) {
eAdapter!!.updatedata(aProductList)
}
updateui()
}
}
override fun onFailure(call: Call<ProductResponse>, t: Throwable) {
println("error")
}
})
} catch (ex: Exception) {
} catch (ex: OutOfMemoryError) {
}
Handler().postDelayed({
getdata()
}, 1000)
}
private fun updateui() {
try {
//some code to handel ui
} catch (e: NumberFormatException) {
} catch (e: ArithmeticException) {
} catch (e: NullPointerException) {
} catch (e: Exception) {
}
}
【问题讨论】:
-
你可以试试
TimerTask -
WorkManager是正确的方法。