Android中使用AsyncTask做下载进度条


AsyncTask是个不错的东西,可以使用它来做下载进度条。代码讲解如下:

  1. package com.example.downloadfile;   
  2.   
  3. import java.io.File;   
  4. import java.io.FileOutputStream;   
  5. import java.io.InputStream;   
  6. import java.net.HttpURLConnection;   
  7. import java.net.URL;   
  8.   
  9. import Android.app.Activity;   
  10. import android.app.Dialog;   
  11. import android.app.ProgressDialog;   
  12. import android.os.AsyncTask;   
  13. import android.os.Bundle;   
  14. import android.os.Environment;   
  15. import android.util.Log;   
  16. import android.widget.TextView;   
  17.   
  18. public class DownloadFile extends Activity {   
  19.        
  20.     public static final String LOG_TAG = "test";   
  21.        
  22.        private ProgressDialog mProgressDialog;   
  23.     public static final int DIALOG_DOWNLOAD_PROGRESS = 0;   
  24.        
  25.        
  26.     File rootDir = Environment.getExternalStorageDirectory();   
  27.        
  28.     //定义要下载的文件名   
  29.     public String fileName = "test.jpg";   
  30.     public String fileURL = "https://lh4.googleusercontent.com/-HiJOyupc-tQ/TgnDx1_HDzI/AAAAAAAAAWo/DEeOtnRimak/s800/DSC04158.JPG";   
  31.        
  32.     @Override  
  33.     public void onCreate(Bundle savedInstanceState)    
  34.     {   
  35.         super.onCreate(savedInstanceState);   
  36.           
  37.         setContentView(R.layout.main);   
  38.         TextView tv = new TextView(this);   
  39.         tv.setText("Android Download File With Progress Bar");   
  40.        
  41.        //检查下载目录是否存在    
  42.         checkAndCreateDirectory("/mydownloads");   
  43.            
  44.         //执行asynctask   
  45.         new DownloadFileAsync().execute(fileURL);   
  46.     }   
  47.      
  48.        
  49.     class DownloadFileAsync extends AsyncTask<String, String, String> {   
  50.            
  51.         @Override  
  52.         protected void onPreExecute() {   
  53.             super.onPreExecute();   
  54.             showDialog(DIALOG_DOWNLOAD_PROGRESS);   
  55.         }   
  56.   
  57.            
  58.         @Override  
  59.         protected String doInBackground(String... aurl) {   
  60.   
  61.             try {   
  62.                 //连接地址   
  63.                 URL u = new URL(fileURL);   
  64.                 HttpURLConnection c = (HttpURLConnection) u.openConnection();   
  65.                 c.setRequestMethod("GET");   
  66.                 c.setDoOutput(true);   
  67.                 c.connect();   
  68.                    
  69.                 //计算文件长度   
  70.                 int lenghtOfFile = c.getContentLength();   
  71.                    
  72.                    
  73.                 FileOutputStream f = new FileOutputStream(new File(rootDir + "/my_downloads/", fileName));   
  74.              
  75.                 InputStream in = c.getInputStream();   
  76.   
  77.                //下载的代码   
  78.                 byte[] buffer = new byte[1024];   
  79.                 int len1 = 0;   
  80.                 long total = 0;   
  81.                    
  82.                 while ((len1 = in.read(buffer)) > 0) {   
  83.                     total += len1; //total = total + len1   
  84.                     publishProgress("" + (int)((total*100)/lenghtOfFile));   
  85.                     f.write(buffer, 0, len1);   
  86.                 }   
  87.                 f.close();   
  88.                    
  89.             } catch (Exception e) {   
  90.                 Log.d(LOG_TAG, e.getMessage());   
  91.             }   
  92.                
  93.             return null;   
  94.         }   
  95.            
  96.         protected void onProgressUpdate(String... progress) {   
  97.              Log.d(LOG_TAG,progress[0]);   
  98.              mProgressDialog.setProgress(Integer.parseInt(progress[0]));   
  99.         }   
  100.   
  101.         @Override  
  102.         protected void onPostExecute(String unused) {   
  103.             //dismiss the dialog after the file was downloaded   
  104.             dismissDialog(DIALOG_DOWNLOAD_PROGRESS);   
  105.         }   
  106.     }   
  107.        
  108.        
  109.     public void checkAndCreateDirectory(String dirName){   
  110.         File new_dir = new File( rootDir + dirName );   
  111.         if( !new_dir.exists() ){   
  112.             new_dir.mkdirs();   
  113.         }   
  114.     }   
  115.        
  116.         @Override  
  117.     protected Dialog onCreateDialog(int id) {   
  118.         switch (id) {   
  119.             case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0   
  120.                 mProgressDialog = new ProgressDialog(this);   
  121.                 mProgressDialog.setMessage("Downloading file...");   
  122.                 mProgressDialog.setIndeterminate(false);   
  123.                 mProgressDialog.setMax(100);   
  124.                 mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);   
  125.                 mProgressDialog.setCancelable(true);   
  126.                 mProgressDialog.show();   
  127.                 return mProgressDialog;   
  128.             default:   
  129.                 return null;   
  130.         }   
  131.     }   
  132. }  
  • 1
  • 2
  • 下一页

相关内容