Java 使用FTPClient下载时更新ProgressBar
我正在使用Apache的FTPClient将文件上传到我的服务器(如果有必要的话,可以从图库上传图片) 我有一个小问题,但我仍然想解决它 问题是,在上传实际完成之前,该条已填充并达到100%,导致小文件的对话框在额外的2-3秒钟内显示100%(在重数MB的文件上可能会显示更多)。 我猜这是因为从Java 使用FTPClient下载时更新ProgressBar,java,android,progress-bar,apache-commons,apache-commons-net,Java,Android,Progress Bar,Apache Commons,Apache Commons Net,我正在使用Apache的FTPClient将文件上传到我的服务器(如果有必要的话,可以从图库上传图片) 我有一个小问题,但我仍然想解决它 问题是,在上传实际完成之前,该条已填充并达到100%,导致小文件的对话框在额外的2-3秒钟内显示100%(在重数MB的文件上可能会显示更多)。 我猜这是因为从long到int的转换,但这只是一个猜测 代码如下: @Override protected void onPreExecute() { super.onPreExecut
long
到int
的转换,但这只是一个猜测
代码如下:
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(UploadActivity.this);
dialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
uploadImage.cancel(true);
}
});
dialog.setMessage("Uploading...\nPlease Wait.");
dialog.setIndeterminate(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setCancelable(false);
dialog.setMax((int)(file.length()/1024));
dialog.setProgressNumberFormat ("%1dKB/%2dKB");
dialog.show();
}
@Override
protected String doInBackground(Void... params) {
CopyStreamAdapter streamListener = new CopyStreamAdapter() {
@Override // THIS PART IS RESPONSIBLE FOR UPDATING THE PROGRESS
public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
int percent = (int) (totalBytesTransferred * 100 / file.length());
publishProgress(percent);
}
};
String name = null;
ftp.setCopyStreamListener(streamListener);
FileInputStream fis = null;
try {
String extension = "";
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
if (i > p) {
extension = fileName.substring(i + 1);
}
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyy-hhmmss-SSS");
name = String.format("File-%s.%s", sdf.format(new Date()), extension);
ftp.connect(FTP_SERVER);
ftp.enterLocalPassiveMode();
ftp.login(ftpUser, ftpPassword);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
fis = new FileInputStream(file);
if (!ftp.storeFile(name, fis)) {
showToast("Failed uploading");
return null;
}
ftp.logout();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return name;
}
@Override
protected void onProgressUpdate(Integer... values) {
dialog.setProgress(values[0]);
}
谢谢