我正在将文件从android上传到服务器,我正在上传整个进度百分比,从0到100%的所有文件。所有文件都是逐个上传的。已知的事情是
我有一个进度条来显示所有人的总体百分比。
上传代码为:
public abstract class UploadTask extends AsyncTask<String, Integer, String>
{
private Context mContext;
private Cursor mCursor;
private ProgressBar mProgressBar;
private int mItemCounter;
private int mFilesCount;
private int mUploaded;
private long mTotalSize;
public UploadTask(Context context, Cursor cursor, ProgressBar progressBar)
{
mContext = context;
mCursor = cursor;
mProgressBar = progressBar;
mFilesCount = cursor.getCount();
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressBar.setMax(mFilesCount);
}
@Override
protected String doInBackground(String... params)
{
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
while (mCursor.moveToNext())
{
String path = mCursor.getString(mCursor.getColumnIndex("_data"));
HttpPost httpPost = new HttpPost("http://...");
try
{
CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(new CustomMultiPartEntity.ProgressListener()
{
@Override
public void transferred(long num)
{
publishProgress((int) (((((float) mUploaded) + ((float) num / (float) mTotalSize)) / (float) mFilesCount)));
}
});
multipartContent.addPart("userfile", new FileBody(new File(path), Utility.removeExtention(title), type, "UTF-8"));
mTotalSize = multipartContent.getContentLength();
httpPost.setEntity(multipartContent);
HttpResponse response = httpClient.execute(httpPost, httpContext);
InputStream inputStream = response.getEntity().getContent();
StringBuilder total = new StringBuilder();
String line;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
try
{
while ((line = bufferedReader.readLine()) != null)
{
total.append(line);
}
inputStream.close();
bufferedReader.close();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.wtf("response", total.toString() + " File Size: " + (mTotalSize / (1024)) + "KB");
}
catch (Exception e)
{
e.printStackTrace();
}
mUploaded++;
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress)
{
super.onProgressUpdate(progress);
mProgressBar.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String s)
{
onCompleted(s == null);
}
protected abstract void onCompleted(boolean result);
}
答案 0 :(得分:1)
mProgressBar.setMax(mFilesCount);
。如果你这样做,那么你应该在publishProgress中使用mFilesDownloaded。否则从mTotalBytesOfAllFiles开始,并使用mTotalBytesUploaded更新。