我正在尝试从 FTP 服务器下载电影。可以成功下载,但是看不到下载进度。你能告诉我为什么 publishProgress() 不能正常工作吗?
以下是我的代码
public void doClick(View v){
boolean x = decodedLink.startsWith("ftp://");
boolean y = decodedLink.startsWith("http://");
if(x ==true && y==false)
{
//ftp
myurl = null;
try {
myurl = new URL("ftp://newrising:newrising2014cap!@newrising.win5.siteonlinetest.com/dummy/giant.mp4");
} catch (MalformedURLException e) {
e.printStackTrace();
}
pd = new ProgressDialog(this);
pd.setTitle("EOrder");
pd.setMessage("Downloading file. Please wait...");
pd.setIndeterminate(false);
pd.setMax(100);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(true);
new FTPDownload().execute(myurl);
}
else if(x ==false && y==true)
{
//http
}
else
{
//invalid message
}
}
class FTPDownload extends AsyncTask<URL , Integer , Void>{
boolean running = true;
int count ;
Date today = Calendar.getInstance().getTime();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String reportDate = formatter.format(today);
String file = reportDate + "_" + "giant.mp4";
@Override
protected Void doInBackground(URL... params) {
// TODO Auto-generated method stub
Log.d("******", "Background thread starting......");
try
{
URL url = new URL("ftp://newrising:newrising2014cap!@newrising.win5.siteonlinetest.com/dummy/giant.mp4");
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
Log.d("lenghtOfFile","values: "+lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator + file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total/lenghtOfFile)*100));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch(Exception e)
{
System.out.println("Error: could not connect to host " + decodedLink);
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
Log.d("progress","values: "+progress[0]);
pd.setProgress(progress[0]);
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pd.dismiss();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd.show();
}
@Override
protected void onCancelled() {
running = false;
}