我一直在尝试用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**
})
}
排球请求方法类
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)
}
}
}
有什么解决方法吗?谢谢!
答案 0 :(得分:0)
您可以使用作为Volley对象的RequestFuture。它可以帮助您在Worker类中创建同步调用
@NonNull
@Override
public Result doWork() {
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, "https://jsonplaceholder.typicode.com/todos/1", null, future, future);
VolleySingleton.getmInstance(getApplicationContext()).addToRequestQueue(request);
try {
JSONObject response = future.get(60, TimeUnit.SECONDS); // this will block
Log.d(TAG, response.toString());
return Result.success();
} catch (InterruptedException e) {
e.printStackTrace();
// exception handling
return Result.failure();
} catch (ExecutionException e) {
e.printStackTrace();
return Result.failure();
// exception handling
} catch (TimeoutException e) {
e.printStackTrace();
return Result.failure();
}
}