我正在使用异步任务在服务器上上传图像,最后我想返回上传的文件 url 的值。我该怎么做我将异步任务称为
new Config.UploadFileToServer(loginUserInfoId, uploadedFileURL).execute();
我的异步任务函数是:
public static final class UploadFileToServer extends AsyncTask<Void, Integer, String> {
String loginUserInfoId = "";
String filePath = "";
long totalSize = 0;
public UploadFileToServer(String userInfoId, String url){
loginUserInfoId = userInfoId;
filePath = url;
}
@Override
protected void onPreExecute() {
// setting progress bar to zero
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// updating progress bar value
}
@Override
protected String doInBackground(Void... params) {
return uploadFile();
}
@SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.HOST_NAME + "/AndroidApp/AddMessageFile/"+loginUserInfoId);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("file", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
responseString = responseString.replace(""","");
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
尝试我的代码,如下所示。
public Result CallServer(String params)
{
try
{
MainAynscTask task = new MainAynscTask();
task.execute(params);
Result aResultM = task.get(); //Add this
}
catch(Exception ex)
{
ex.printStackTrace();
}
return aResultM;//Need to get back the result
}
你几乎已经明白了,你应该只做一步。如我所见,您正在doInBackground
方法返回结果(作为调用uploadFile
的结果)。现在,此值传递给在主线程上执行的 onPostExecute
方法。在其正文中,您应该通知正在等待结果的组件,该结果已到达。有很多方法可以做到这一点,但是如果您不想使用第三方库,最简单的方法应该是在AsyncTask
构造函数中注入侦听器并在onPostExecute
调用它。例如,可以声明以下接口:
public interface MyListener {
void onDataArrived(String data);
}
并在AsyncTask
构造函数中注入一个实现它的实例:
public UploadFileToServer(String userInfoId, String url, MyListener listener){
loginUserInfoId = userInfoId;
filePath = url;
mListener = listener;
}
现在,您可以简单地在onPostExecute
使用它:
@Override
protected void onPostExecute(String result) {
listener.onDataArrived(result);
super.onPostExecute(result); //actually `onPostExecute` in base class does nothing, so this line can be removed safely
}
如果您正在寻找更复杂的解决方案,可以从阅读本文开始。