如何在android中的异步类中显示FTP下载的进度条?
我已经尝试了很多东西,但没有得到进度条。这是我的代码, 我从其他 Activity 调用这个类,将那个 Activity 的上下文传递给这个类。
package com.scft;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import java.io.File;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.StrictMode;
import android.util.Log;
import android.widget.PopupWindow;
import android.widget.Toast;
public class ftpdownload_class {
static final String FTP_HOST= "**************";
/********* FTP USERNAME ***********/
static final String FTP_USER = "*********";
/********* FTP PASSWORD ***********/
static final String FTP_PASS ="*******";
File fileDownload=null;
long startTime_ftpDownload=0;
long endTime_ftpDownload=0;
long downloaded_file=0;
long startTime_ftpUpload=0;
long endTime_ftpUpload=0;
FTPClient client=null;
public static File m_fileName;
private PopupWindow pwindo;
String totaltime_ftpUpload,filesize_ftpUpload,ratevalue_ftpUpload,totaltime_ftpDownload,filesize_ftpDownload,ratevalue_ftp_download;
Context mContext=null;
public ftpdownload_class( Context c)
{
mContext=c;
}
public void ftp_downloadStart() {
FTPClient ftp = new FTPClient();
try {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ftp.connect(FTP_HOST,158);//158 is the port number
//System.out.println(ftp.connect(host)[0]);
ftp.login(FTP_USER, FTP_PASS);
fileDownload = new File("/sdcard/test.mp3");
fileDownload.createNewFile();
startTime_ftpDownload = System.currentTimeMillis();
ftp.download("test.mp3", fileDownload,
new FTPDataTransferListener() {
// lenghtOfFile = conection.getContentLength();
public void transferred(int arg0) {
// download_btn.setVisibility(View.GONE);
//Log.v("log_tag", "This is for transfer");
// Toast.makeText(getBaseContext(), " transferred ..."+arg0 , Toast.LENGTH_SHORT).show();
}
public void started() {
// TODO Auto-generated method stub
// Toast.makeText(getBaseContext(), " Download Started ...", Toast.LENGTH_SHORT).show();
//Log.v("log_tag", "This is for started");
}
public void failed() {
// download_btn.setVisibility(View.VISIBLE);
Toast.makeText(mContext, " failed ...", Toast.LENGTH_SHORT).show();
System.out.println(" failed ..." );
}
public void completed() {
// download_btn.setVisibility(View.VISIBLE);
endTime_ftpDownload = System.currentTimeMillis(); //maybe
Toast.makeText(mContext, " Download completed ...", Toast.LENGTH_SHORT).show();
getspeedfor_ftp_download();
//Log.v("log_tag", "This is for completed");
}
public void aborted() {
// download_btn.setVisibility(View.VISIBLE);
Toast.makeText(mContext," transfer aborted,please try again...", Toast.LENGTH_SHORT).show();
//Log.v("log_tag", "This is for aborted");
}
});
} catch (Exception e) {
e.printStackTrace();
try {
ftp.disconnect(true);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
long downloaded_file_ftp=0;
public void getspeedfor_ftp_download()
{
downloaded_file_ftp = fileDownload.length();
//Log.d("DownloadManager", "download ended: " + ((endTime - startTime) / 1000) + " secs");
String abc = (((endTime_ftpDownload - startTime_ftpDownload) / 1000) + " secs");
totaltime_ftpDownload = abc;
double size = (downloaded_file_ftp/1024);
if(size<1000)
filesize_ftpDownload=String.valueOf(size).concat("Kb");
else
filesize_ftpDownload=String.valueOf(size/1024).concat("Mb");
double rate = (((downloaded_file_ftp / 1024) / ((endTime_ftpDownload - startTime_ftpDownload) / 1000)) * 8);
rate = Math.round( rate * 100.0 ) / 100.0;
if(rate > 1000)
ratevalue_ftp_download = String.valueOf(rate / 1024).concat(" Mbps");
else
ratevalue_ftp_download = String.valueOf(rate).concat(" Kbps");
Log.d("DownloadManager", "download speed: "+ratevalue_ftp_download);
alertStatus_ftp_download();
}
public void alertStatus_ftp_download()
{
AlertDialog.Builder alertDialogBuilderfor_ftp_download = new AlertDialog.Builder(mContext);
// set title
alertDialogBuilderfor_ftp_download.setTitle("Ftp Download Speed Status");
// set dialog message
alertDialogBuilderfor_ftp_download
.setMessage("Download Speed : "+ratevalue_ftp_download+", "+"\n Total File Size :"+filesize_ftpDownload+"\nTotal time taken : "+totaltime_ftpDownload)
//.setMessage("Download Speed "+ratevalue_ftp_download)
.setCancelable(false)
.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
dialog.cancel();
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialogftp_download = alertDialogBuilderfor_ftp_download.create();
// show it
alertDialogftp_download.show();
}
}
最佳答案
经过数小时的搜索,我终于构建了一个这样的解决方案。 创建一个像这样的 uploader 类 UploadToFtp.java
public class UploadToFtp {
public FTPClient mFTPClient = null;
String host;
String username;
String password;
CopyStreamAdapter streamListener;
ProgressDialog pDialog;
boolean status = false;
public boolean ftpUpload1(String srcFilePath, String desFileName,
String desDirectory, String host, String username, String password,
final ProgressDialog pDialog) {
this.pDialog = pDialog;
this.host = host;
this.username = username;
this.password = password;
int port = 21;
mFTPClient = new FTPClient();
try {
mFTPClient.connect(host, port); // connecting to the host
mFTPClient.login(username, password); // Authenticate using username
// and password
mFTPClient.changeWorkingDirectory(desDirectory); // change directory
System.out.println("Dest Directory-->" + desDirectory); // to that
// directory
// where image
// will be
// uploaded
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn = null;
final File file = new File(srcFilePath);
System.out.println("on going file-->" + srcFilePath);
buffIn = new BufferedInputStream(new FileInputStream(file), 8192);
mFTPClient.enterLocalPassiveMode();
streamListener = new CopyStreamAdapter() {
@Override
public void bytesTransferred(long totalBytesTransferred,
int bytesTransferred, long streamSize) {
// this method will be called everytime some
// bytes are transferred
// System.out.println("Stream size" + file.length());
// System.out.println("byte transfeedd "
// + totalBytesTransferred);
int percent = (int) (totalBytesTransferred * 100 / file
.length());
pDialog.setProgress(percent);
if (totalBytesTransferred == file.length()) {
System.out.println("100% transfered");
removeCopyStreamListener(streamListener);
}
}
};
mFTPClient.setCopyStreamListener(streamListener);
status = mFTPClient.storeFile(desFileName, buffIn);
System.out.println("Status Value-->" + status);
buffIn.close();
mFTPClient.logout();
mFTPClient.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
}
现在在实际获取或创建文件的类中创建一个 Asynctask,如下所示
class UploadTask extends AsyncTask<Void, Integer, Void> {
ProgressDialog pDialog;
Boolean uploadStat;
UploadToFtp utp = new UploadToFtp();
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(UploadActivity.this);
pDialog.setMessage("Uploading...");
pDialog.setCancelable(false);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
System.out.println("source url -> " + sourceUrl);
System.out.println("filename -> " + filename);
System.out.println("desDirectory -> " + desDirectory);
uploadStat = new UploadToFtp().ftpUpload1(sourceUrl, filename,
desDirectory, app.getHostname(), app.getUsername(),
app.getPassword(), pDialog);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (uploadStat) {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
reviewImageView.setImageBitmap(null);
mCurrentPhotoPath = "";
photo = null;
uploadMessage.setVisibility(View.VISIBLE);
UploadSuccess.setVisibility(View.VISIBLE);
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
UploadActivity.this);
// Setting Dialog Message
alertDialog.setTitle("Error Uploading File");
alertDialog
.setMessage("Connection lost during upload, please try again!");
alertDialog.setCancelable(false);
// Setting Icon to Dialog
// Setting OK Button
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
alertDialog.show();
}
}
});
return null;
}
@Override
protected void onPostExecute(Void result) {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
System.out.println("Result-->" + result);
super.onPostExecute(result);
}
}
现在只需在按钮单击或任何其他您想要的事件上调用此 Asynctask
new UploadTask().execute();
关于android - 如何在 Android 的异步类中显示 FTP 下载的进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21923833/