2012-11-19 59 views
-2

我使用這個類來下載文件:如何使用AsyncTask下載文件?

public class DownloadService extends Service { 
    String downloadUrl; 
    LocalBroadcastManager mLocalBroadcastManager; 
    ProgressBar progressBar; 
    File sdCard = Environment.getExternalStorageDirectory(); 
    File dir = new File (sdCard.getAbsolutePath() + "/org.test.download/"); 
    double fileSize = 0; 
    DownloadAsyncTask dat; 
    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 

    public DownloadService(String url,Context c, ProgressBar pBar){ 
     downloadUrl = url; 
     mLocalBroadcastManager = LocalBroadcastManager.getInstance(c); 
     progressBar = pBar; 
     dat = new DownloadAsyncTask(); 
     dat.execute(new String[]{downloadUrl}); 

    } 

    private boolean checkDirs(){ 
     if(!dir.exists()){ 
      return dir.mkdirs(); 
     } 
     return true; 
    } 
    public void cancel(){ 
     dat.cancel(true); 
    } 
    public class DownloadAsyncTask extends AsyncTask<String, Integer, String>{ 

     @Override 
     protected String doInBackground(String... params) { 
       String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/")+1); 
       if(!checkDirs()){ 
        return "Making directories failed!"; 
       } 
       try { 
        URL url = new URL(downloadUrl); 
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
        urlConnection.setRequestMethod("GET"); 
        urlConnection.setDoOutput(true); 
        urlConnection.connect(); 
        fileSize = urlConnection.getContentLength(); 
        FileOutputStream fos = new FileOutputStream(new File(dir,fileName)); 
        InputStream inputStream = urlConnection.getInputStream(); 
        byte[] buffer = new byte[500]; 
        int bufferLength = 0; 
        int percentage = 0; 
        double downloadedSize = 0; 
        while ((bufferLength = inputStream.read(buffer)) > 0) 
        { 
         if(isCancelled()){ 
          break; 
         } 
         fos.write(buffer, 0, bufferLength); 
         downloadedSize += bufferLength; 
         percentage = (int) ((downloadedSize/fileSize) * 100); 
         publishProgress(percentage); 
        } 
        fos.close(); 
        urlConnection.disconnect(); 
       } catch (Exception e) { 
        Log.e("Download Failed",e.getMessage()); 
       } 
       if(isCancelled()){ 
        return "Download cancelled!"; 
       } 
      return "Download complete"; 
     } 
     @Override 
     protected void onProgressUpdate(Integer... values){ 
      super.onProgressUpdate(values[0]); 
      if(progressBar != null){ 
       progressBar.setProgress(values[0]); 
      }else{ 
       Log.w("status", "ProgressBar is null, please supply one!"); 
      } 
     } 

     @Override 
     protected void onPreExecute(){ 
      mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_STARTED")); 
     } 

     @Override 
     protected void onPostExecute(String str){ 
      mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_FINISHED")); 
     } 

     @Override 
     protected void onCancelled(){ 
      mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_CANCELLED")); 
     } 

    } 

} 

我用這個,因爲之前API 9顯然DownloadManager不會工作,我瞄準API 7

我有ListView,它解析XML文件並顯示可以下載的軟件包。

如何修改此類以接受包含URL的字符串數組並逐個下載它們?

或者有沒有什麼好的方法來下載文件列表?

+1

你的答案可能會留在這兒: http://stackoverflow.com/questions/7660963/downloading-multiple-files-one-by-one-using-asynctask – PhatHV

+0

P/S:我不是一個downvoter。 – PhatHV

回答

2

查看使用IntentService。 IntentService中的線程在後臺運行,這意味着您不必處理所有線程處理的混亂情況。

IntentService一旦完成就終止它的線程,所以你必須堅持數據。

要與您的活動溝通,請使用廣播接收器。

+0

你能提供我示例代碼嗎? – Nevercom