我面临一个我不知道如何解决的问题。
GetDataTask 工作正常。但是当我上传文件时,请求已发送,但只有在文件上传完成后才会响应!GetDataTask 和 UploadTask 使用 AsyncTask 异步运行。
知道为什么它不起作用以及为什么在文件上传时响应没有返回。
有没有另一种方法来实现这一点?
问题是,它应该并行运行,但不幸的是它们正在同步运行。
我在下面发布了我的实际来源。
提前致谢。
获取数据任务:
private class GetDataTask extends AsyncTask<String, Void, String>{
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... params) {
return NetConnection.getRecordData(mUserId, mUserPassword);
}
@Override
protected void onPostExecute(String result) {
parseJson(result);
}
}
上传任务:
private class HttpMultipartPost extends AsyncTask<String, Integer, String>
{
TextProgressBar pb;
long totalSize;
String filePath;
@Override
protected void onPreExecute()
{
pb = (TextProgressBar) findViewById(R.id.idPBUploadProgress);
pb.setMax(100);
}
@Override
protected String doInBackground(String... arg)
{
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost( Utils.UPLOAD_URL );
try
{
CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(new ProgressListener()
{
@Override
public void transferred(long num)
{
publishProgress((int) ((num / (float) totalSize) * 100));
//Log.v(TAG, "Progress =" + num);
}
});
// We use FileBody to transfer an file
filePath = arg[0];
multipartContent.addPart("upfile", new FileBody(new File( filePath )));
totalSize = multipartContent.getContentLength();
Log.e(TAG, "Upload file size = " + totalSize/1048576 + "MB") ;
// Send it
httpPost.setEntity(multipartContent);
HttpResponse response = httpClient.execute(httpPost, httpContext);
String serverResponse = EntityUtils.toString(response.getEntity());
return serverResponse;
}
catch (Exception e)
{
System.out.println(e);
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress)
{
pb.setProgress((int) (progress[0]));
pb.setText(progress[0] + "%");
}
@Override
protected void onPostExecute(String result)
{
Log.e(TAG, "Response =" + result);
parseResult( result, filePath );
}
}