你要做的是創建一個AsyncTask
,可以爲你處理這個問題,覆蓋onProgressUpdate方法。
這是我在另一個應用程序中使用HttpURLConnection
測試過的東西的精簡版本。可能會有一些小的冗餘,我認爲HttpURLConnection
可能通常會被人忽視,但這應該起作用。只需通過調用new FileUploadTask().execute()
將此類用於您正在使用的任何活動類(在此示例中,我將其稱爲TheActivity
)。當然你可能需要調整這個以適應你的應用程序的需求。
private class FileUploadTask extends AsyncTask<Object, Integer, Void> {
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(TheActivity.this);
dialog.setMessage("Uploading...");
dialog.setIndeterminate(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.show();
}
@Override
protected Void doInBackground(Object... arg0) {
try {
File file = new File("file path");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fileInputStream.read(bytes);
fileInputStream.close();
URL url = new URL("some path");
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
OutputStream outputStream = connection.getOutputStream();
int bufferLength = 1024;
for (int i = 0; i < bytes.length; i += bufferLength) {
int progress = (int)((i/(float) bytes.length) * 100);
publishProgress(progress);
if (bytes.length - i >= bufferLength) {
outputStream.write(bytes, i, bufferLength);
} else {
outputStream.write(bytes, i, bytes.length - i);
}
}
publishProgress(100);
outputStream.close();
outputStream.flush();
InputStream inputStream = connection.getInputStream();
// read the response
inputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(Void result) {
try {
dialog.dismiss();
} catch(Exception e) {
}
}
}
這篇文章可能是你正在尋找:[Java FileUpload with progress](http://stackoverflow.com/questions/254719/file-upload-with-java-with-progress-bar)。 –