【发布时间】:2019-03-11 09:51:06
【问题描述】:
我一直在尝试使用 Workmanager 实现 android volley 以进行后台数据上传。实现上完全没有问题,但是通过 Result.success 来注册并捕获并返回响应结果真的很难。
override fun doWork(): Result {
var volley = VolleySingleTon.getInstance(mContext)
.syncLocationData(mContext, location, success = Function { collection ->
ERROR HERE************
**Need to return the return Result.success()**
**but i can't return the above**
}, failure = Function { collection ->
ERROR HERE************
**Need to return the return Result.failure()**
**but i can't return the above**
})
}
Volley请求方法类
fun syncLocationData(
context: Context,
location: List<VehicleLocation>, success: Function<RestCollection, Any>, failure: Function<RestCollection, Any>
) {
var jsonObject: JSONObject? = null
val jsonString = RestUtil.getGson().toJson(location)
try {
jsonObject = JSONObject(jsonString)
} catch (e: JSONException) {
e.printStackTrace()
}
addToRequestQueue(
JsonObjectRequest(
Request.Method.POST,
AppConstants.WEB_SERVER.toString + AppConstants.SYNC_LOC_DATA.toString, jsonObject,
SuccessHandler(context, null, success),
ErrorHandler(context, null, failure)
)
)
}
用于从响应中收集结果的处理程序
class SuccessHandler(
val context: Context,
private val progressBar: ProgressBar?,
private val successCallBack: Function<RestCollection, Any>
) : Response.Listener<JSONObject> {
override fun onResponse(json: JSONObject?) {
if (json != null) {
progressBar?.visibility = View.GONE
val response: ApplicationResponse =
RestUtil.getGson().fromJson(json.toString(), ApplicationResponse::class.java)
successCallBack.apply(response.collection)
}
}
}
有什么解决方法吗?谢谢!!
【问题讨论】:
-
我有同样的问题,任何人都使用 volley 和 workmanager
-
可以查看这篇文章medium.com/@oyinloyeayodeji/…
标签: android android-volley android-workmanager