我已经坚持了一段时间。我有一个将图像上传到 Web 服务器的异步任务。工作正常。
我为此设置了一个进度条对话框。我的问题是如何准确更新进度条。我尝试的一切都会导致它一步从 0 到 100。不管是 5 秒还是 2 分钟。栏挂在 0 上,然后在上传完成后达到 100。
这是我的 doInBackground 代码。任何帮助表示赞赏。
编辑:我更新了下面的代码以包含整个 AsynchTask
private class UploadImageTask extends AsyncTask<String,Integer,String> {
private Context context;
private String msg = "";
private boolean running = true;
public UploadImageTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage("Uploading photo, please wait.");
dialog.setMax(100);
dialog.setCancelable(true);
}
@Override
protected void onPreExecute() {
dialog.show();
dialog.setOnDismissListener(mOnDismissListener);
}
@Override
protected void onPostExecute(String msg){
try {
// prevents crash in rare case where activity finishes before dialog
if (dialog.isShowing()) {
dialog.dismiss();
}
} catch (Exception e) {
}
}
@Override
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
@Override
protected String doInBackground(String... urls) {
if(running) {
// new file upload
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = savedImagePath;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
String urlString = "https://mysite.com/upload.php";
float currentRating = ratingbar.getRating();
File file = new File(savedImagePath);
int sentBytes = 0;
long fileSize = file.length();
try {
// ------------------ CLIENT REQUEST
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ exsistingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName));
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
// Update progress dialog
sentBytes += bufferSize;
publishProgress((int)(sentBytes * 100 / fileSize));
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
fileInputStream.close();
}catch (MalformedURLException e) {
}catch (IOException e) {
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
// try to read input stream
// InputStream content = inStream.getContent();
BufferedInputStream bis = new BufferedInputStream(inStream);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
long total = 0;
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
/* Convert the Bytes read to a String. */
String mytext = new String(baf.toByteArray());
final String newtext = mytext.trim();
inStream.close();
} catch (Exception e) {
}
}
return msg;
}
}