我有这个代码,但进度条不会更新文件的上传字节/长度。
进度对话框正确显示,但进度保持在 0,然后它就消失了,文件已正确上传,但没有更新进度。
private class UploadFile extends AsyncTask<String, Integer, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
FTPClient client = null;
String filePath = params[0];
try {
// Get the FTP Connection from the Utility class
client = FTPUtility.connect(ipAddress, userName, password);
//if directory is not there, create it.
try {
client.changeDirectory(params[1]);
} catch(Exception e) {
client.createDirectory(params[1]);
client.changeDirectory(params[1]);
}
if (client != null) {
try {
// Define the File with complete path to be uploaded
File fileUpload = new File(filePath);
fileSize= fileUpload.length();
Log.d("FTPSync", "File Size: "+fileSize);
Log.d("FTPSync", "Uploading the " + filePath
+ " to Remote Machine");
// Upload the file
client.upload(fileUpload, new FTPDataTransferListener() {
@Override
public void started() {
// Transfer started
Log.d("FTP","TRANSFER-STATUS: File transfer started...");
}
@Override
public void transferred(int length) {
int progress = (length*100)/((int)fileSize);
publishProgress(progress);
Log.d("FTP","Progress: "+progress);
}
@Override
public void completed() {
Log.d("FTP","TRANSFER-STATUS: File transfer completed...");
}
@Override
public void aborted() {
// Transfer aborted
Log.d("FTP","TRANSFER-STATUS: File transfer aborted...");
}
@Override
public void failed() {
// Transfer failed
Log.d("FTP","TRANSFER-STATUS: File transfer failed...");
}
});
Log.d("FTPSync", "Successfully Uploaded the "
+ filePath + " File to Remote Machine");
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (client != null) {
try {
client.disconnect(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Boolean result) {
pDialog.dismiss();
Toast.makeText(context, "Operation Completed", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(context);
pDialog.setMessage(message);
pDialog.setIndeterminate(true);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
pDialog.setProgress(values[0]);
}
}
private static class FTPUtility {
public static FTPClient connect(String ipAddress, String userName,
String password) {
FTPClient client = new FTPClient();
Log.d("FTP","Connecting to " + ipAddress);
try {
client.setType(FTPClient.TYPE_BINARY);
client.connect(ipAddress);
client.login(userName, password);
return client;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
调试只显示一个关于 Progress:100 的条目
如何使进度条更新。
注意:我尝试过使用小文件和大文件,所以这两种文件大小似乎都是同一个问题。