当我尝试下载.zip文件。我没有得到完整的文件,文件大小为3.93 MB,但我只得到38KB.Don't得到完整的.zip文件 这里是我的代码AsyncTask下载zip文件android
活动课
private Button btnStart; // Progress Dialog Object private ProgressDialog prgDialog; // Progress Dialog type (0 - for Horizontal progress bar) public static final int progress_bar_type = 0; // Music resource URL private static String file_url = "http://www.mediafire.com/download/tvd070dounxk472/al_Quran_ul_Hakeem.zip"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnStart = (Button) findViewById(R.id.btnProgressBar); btnStart.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { btnStart.setEnabled(false); File file = new File(Environment.getExternalStorageDirectory().getPath()+"/al_Quran_ul_Hakeem.zip"); // Check if the Music file already exists if (file.exists()) { Toast.makeText(getApplicationContext(), "File already exist under SD card", Toast.LENGTH_LONG).show();
}
否则{
new DownloadMusicfromInternet().execute(file_url); }
} }); }
的AsyncTask类
类DownloadMusicfromInternet扩展的AsyncTask {
@Override protected void onPreExecute() { super.onPreExecute(); // Shows Progress Bar Dialog and then call doInBackground method showDialog(progress_bar_type); } @Override protected String doInBackground(String... f_url) { int count; try { URL url = new URL(f_url[0]); URLConnection conection = url.openConnection(); conection.connect(); int lenghtOfFile = conection.getContentLength(); // input stream to read file - with 8k buffer InputStream input = new BufferedInputStream(url.openStream(),100*1024); // Output stream to write file in SD card OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/al_Quran_ul_Hakeem.zip"); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; // Publish the progress which triggers onProgressUpdate method publishProgress("" + (int) ((total * 100)/lenghtOfFile)); // Write data to file output.write(data, 0, count); } // Flush output output.flush(); // Close streams output.close(); input.close(); } catch (Exception e) { Log.e("Error: ", e.getMessage()); } return null; } // While Downloading Music File protected void onProgressUpdate(String... progress) { // Set progress percentage prgDialog.setProgress(Integer.parseInt(progress[0])); } // Once Music File is downloaded @Override protected void onPostExecute(String file_url) { dismissDialog(progress_bar_type); Toast.makeText(getApplicationContext(), "Download complete", Toast.LENGTH_LONG).show(); } }
你从'得到什么价值conection.getContentLength()'? –
我正在获取文件的长度来更新进度条 – user3582794
这似乎没问题,也许链接是问题。顺便说一下,不要忘记关闭finally块上的流,目前的做法是不好的做法。 –