2011-12-24 99 views
0

我想使用AsyncTask下載多個文件。 我通過通知欄中的進度條開始每次下載一個AsyncTask,但是我面臨很多問題。使用AsyncTask下載多個文件?

  1. 如果我下載4個或5個文件在一個或多個文件 中斷,沒有任何理由的同時。

  2. 如果我下載4張或5張圖片,一張或多張圖片損壞。

這是我使用的代碼。

private class DownloadFile extends AsyncTask<String, Integer, Long> 
      { 
       int nID = 0; 
       int nDownloadCounter = 0; 
       public DownloadFile(String sFileName, int nNotificationID) { 
        this.nID = nNotificationID; 
        this.NotificationName = sFileName; 
        this.nDownloadCounter = 0; 
       } 

       protected void onPreExecute(){ 
        this.sDownloadPath = sFilePathWithSubDir; 
        notification = new Notification(R.drawable.app_icon, "Download File", System.currentTimeMillis()); 
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification); 

        Intent notificationIntent = new Intent(); 
        File file = new File(this.sDownloadPath + this.NotificationName); 
        sMediaDataType = GSUtilities.sGetFileMIMEType(this.NotificationName); 

        notificationIntent.setAction(android.content.Intent.ACTION_VIEW); 
        notificationIntent.setDataAndType(Uri.fromFile(file), sMediaDataType); 

        PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0); 

        contentView.setTextViewText(R.id.status_percent, "0%"); 
        contentView.setTextViewText(R.id.status_fileName, this.NotificationName); 
        contentView.setProgressBar(R.id.status_progress, 100, 0, false); 

        notification.contentView = contentView; 
        notification.contentIntent = contentIntent; 
        mNotificationManager.notify(nID, notification);    
       } 

       protected Long doInBackground(String... urls) {  
        long retData = 0; 

        OutputStream fosXSPDatabse = null; 
        InputStream inServerResponse = null; 
        URLConnection oURLConnection = null; 
        URL oURL = null; 

        try 
        { 
         oURL = new URL(oFileManager.sExpiryLink); 
         oURLConnection = oURL.openConnection(); 

         if (!(oURLConnection instanceof HttpURLConnection)) 
          throw new IOException("Not an HTTP connection"); 

         oURLConnection.connect();    
         inServerResponse = new BufferedInputStream(oURL.openStream()); 
         if (inServerResponse != null) 
         { 
          File fDirectory = new File(oFileManager.sAppFlesDirectory); 
          if (!fDirectory.exists()) 
          { 
           if (!fDirectory.mkdir()) 
           {} 
          } 

          fosXSPDatabse = new FileOutputStream(oFileManager.sAppFlesDirectory + "/" + oFileInfo.getFileName()); 
          byte data[] = new byte[BUFFER_SIZE]; 

          int nCount = 0; 
          long lTotalDownloaded = 0; 
          int nTotalSize = oURLConnection.getContentLength(); 
          while ((nCount = inServerResponse.read(data)) != -1) 
          { 
           Log.d(String.valueOf(nID) + " - DoInBackground", String.valueOf(dNotificationbarProgress)); 
           nDownloadCounter ++; 
           lTotalDownloaded += nCount; 
           dNotificationbarProgress = lTotalDownloaded * 100.0/nTotalSize; 
           if (this.nDownloadCounter == 20 || dNotificationbarProgress == 100) { 
            publishProgress(Integer.parseInt(new DecimalFormat("#.##").format(dNotificationbarProgress).split("\\.")[0])); 
            nDownloadCounter = 0; 
           } 
           fosXSPDatabse.write(data, 0, nCount); 
          } 
          inServerResponse.close(); 
          fosXSPDatabse.flush(); 
          fosXSPDatabse.close(); 
         } 
        } 
        catch (MalformedURLException e) 
        {} 
        catch (IOException e) 
        {} 
        catch (Exception e) 
        {} 
        finally 
        { 
         try 
         { 
          inServerResponse.close(); 
          fosXSPDatabse.flush(); 
          fosXSPDatabse.close(); 

         } 
         catch (IOException e) 
         {} 
        } 

        return retData; 
       } 

       protected void onProgressUpdate(Integer... progress) { 
        try 
        { 
         Log.d(String.valueOf(nID),"onProgressUpdate"); 
         notification.contentView.setProgressBar(R.id.status_progress, 100, progress[0], false); 
         notification.contentView.setTextViewText(R.id.status_fileName, this.NotificationName); 
         notification.contentView.setTextViewText(R.id.status_percent, String.valueOf(progress[0]) + "%"); 

         Intent notificationIntent = new Intent(); 
         File file = new File(this.sDownloadPath + this.NotificationName); 
         sMediaDataType = GSUtilities.sGetFileMIMEType(this.NotificationName); 

         notificationIntent.setAction(android.content.Intent.ACTION_VIEW); 
         notificationIntent.setDataAndType(Uri.fromFile(file), sMediaDataType); 

         PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0); 
         notification.contentIntent = contentIntent; 
         mNotificationManager.notify(this.nID, notification);  
        } 
        catch(Exception e) 
        {} 
       } 

       protected void onPostExecute(Long result) { 
        notification.contentView.setTextViewText(R.id.status_fileName, "Successfully installed " + this.NotificationName); 
        notification.contentView.setTextViewText(R.id.status_percent, "100%"); 
        mNotificationManager.notify(this.nID, notification); 
       } 
      } 

回答

0

處理下載多個文件的最佳方法是使用服務。

0

首先,這是不是一個好主意悄悄忽略例外。你應該至少將它們記錄到logcat。它認爲這是問題。

其次,您正在多次關閉流。

你從哪裏調用AsyncTask?

如果它來自活動並且用戶離開它,那麼操作系統想要釋放內存時可能會終止該操作。

如果它來自服務,也可能會終止,但至少會在稍後重新啓動。如果服務是從一個不同的進程(如同步適配器)啓動的,則還應將PreExecute和PublishProgress和PostExecute代碼以應用程序循環處理程序作爲消息發佈到UI線程。

另外,嘗試將併發下載數限制爲最大3。否則,可能會發生OutOfMemory。你可以用BlockingQueue來做到這一點。如果併發不重要,請考慮使用IntentService而不是AsyncTask。

+0

第一:我不刪除異常它只是爲了減少上面的代碼。 第二:我從onclick ListView事件調用AsynkTask。 – Basbous 2011-12-25 01:43:16