あなたはこれを処理できるAsyncTask
を作成し、onProgressUpdateメソッドをオーバーライドします。
ここでは、HttpURLConnection
を使用して別のアプリでテストしたものを削除しました。いくつかの小さな冗長性があるかもしれませんし、私はHttpURLConnection
が一般的に悩まされるかもしれないと思っていますが、これはうまくいくはずです。使用しているアクティビティクラス(この例ではTheActivity
)にこのクラスを使用するには、new FileUploadTask().execute()
を呼び出してください。もちろん、アプリのニーズに合わせて調整する必要があるかもしれません。
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)。 –