我正在尝试将多张图片上传到服务器并通过 Asynctask 将它们一张一张地发送。上传图像后,我将 url 保存到本地列表并将其发送以在 onPostExecute 中进行处理。但是,我遇到了问题,因为 onPostExecute 触发得太早并且 doInBackground 只返回一个空列表。
将 URI 传递给异步任务
new UploadImages().execute(arrayUri);
我的异步任务
private class UploadImages extends AsyncTask<Uri,Void,List<String>>{
@Override
protected List<String> doInBackground(Uri... params) {
final ArrayList<String> urlList = new ArrayList<>();
for(Uri uri : params) {
File file = new File(uri.getPath());
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
RequestBody folderName = RequestBody.create(MediaType.parse("text/plain"), folder);
ApiEndpointInterface apiEndpointInterface = RetrofitManager.getApiInterface();
Call<FileInfo> call4File = apiEndpointInterface.postFile(body, folderName);
call4File.enqueue(new ApiCallback<FileInfo>() {
@Override
protected void do4Failure(Throwable t) {
Log.d(TAG, t.toString());
snackbar = Snackbar.make(newIncidentLayout, R.string.sb_image_upload_error, Snackbar.LENGTH_SHORT);
snackbar.show();
}
@Override
protected void do4PositiveResponse(Response<FileInfo> response) {
FileInfo fileDetails = response.body();
urlList.add(fileDetails.getImage());
Log.d(TAG, "Uploaded Image");
}
@Override
protected void do4NegativeResponse(Response<FileInfo> response) {
String bodyMsg = "";
try {
bodyMsg = new String(response.errorBody().bytes());
} catch (IOException e) {
e.printStackTrace();
}
Log.d(TAG, bodyMsg);
snackbar = Snackbar.make(newIncidentLayout, R.string.sb_image_upload_error, Snackbar.LENGTH_SHORT);
snackbar.show();
}
});
}
return urlList;
}
@Override
protected void onPostExecute(List<String> urlList) {
super.onPostExecute(urlList);
//Post Incident
setProgressMessage("Posting incident...");
//other code here
}
}
我试过添加 thread.sleep,但结果总是不一样。有时我得到一个列表作为返回,有时什么也没有发生。
我不确定为什么会这样。我希望你可以帮助我。谢谢。
最佳答案
在 android 中,retrofit 调用默认在后台线程中进行。您不应该/不需要使用 AsyncTask
。
您可以在方法 onResponse
中为 onPostExecute
编写代码(或者在您的情况下为 do4PositiveResponse
和 do4NegativeResponse
) 你的改造回调。
关于android - Retrofit 中 AsyncTask 中的 onPostExecute 过早触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47028314/