2013-05-14 22 views
0

我的android應用程序在下載文件時總是卡住,直到下載完成。但是,下載線程是從AyncTask繼承的,它位於後臺。任何人都可以看一看,看看有什麼不對,我如何修改代碼才能工作?Android:下載線程攔截應用程序

private class DownloadFileTask extends AsyncTask<String, Integer, String> { 

    File destFile; 

    private boolean openAfterDownload; 
    private Exception failure; 

    public DownloadFileTask(boolean openAfterDownload) { 
     this.openAfterDownload = openAfterDownload; 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute();   
     downloadDialog.setMessage(getString(R.string.downloading)); 
     downloadDialog.show(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 

     try { 

      String url = params[0]; 
      LOG.debug("Downloading: " + url); 

      String fileName = url.substring(url.lastIndexOf('/') + 1); 

      HttpParams httpParams = new BasicHttpParams(); 
      DefaultHttpClient client = new DefaultHttpClient(httpParams); 
      client.getCredentialsProvider().setCredentials(
        new AuthScope(null, -1), 
        new UsernamePasswordCredentials(user, password)); 
      HttpGet get = new HttpGet(url); 

      HttpResponse response = client.execute(get); 

      if (response.getStatusLine().getStatusCode() == 200) { 

       File destFolder = new File(config.getDownloadsFolder()); 
       if (!destFolder.exists()) { 
        destFolder.mkdirs(); 
       } 

       /** 
       * Make sure we always store downloaded files as .epub, 
       * so they show up in scans later on. 
       */ 
       if (! fileName.endsWith(".epub")) { 
        fileName = fileName + ".epub"; 
       } 

       destFile = new File(destFolder, URLDecoder.decode(fileName)); 

       if (destFile.exists()) { 
        destFile.delete(); 
       } 

       // lenghtOfFile is used for calculating download progress 
       long lenghtOfFile = response.getEntity().getContentLength(); 
       if(lenghtOfFile>=config.getAvailableSpace()) 
       { 
        this.failure = new Exception("not enough space"); 
        return null; 
       } 
       // this is where the file will be seen after the download 
       FileOutputStream f = new FileOutputStream(destFile); 

       try { 
        // file input is from the url 
        InputStream in = response.getEntity().getContent(); 

        // here's the download code 
        byte[] buffer = new byte[1024]; 
        int len1 = 0; 
        long total = 0; 

        while ((len1 = in.read(buffer)) > 0) { 

         // Make sure the user can cancel the download. 
         if (isCancelled()) { 
          return null; 
         } 

         total += len1; 
         publishProgress((int) ((total * 100)/lenghtOfFile)); 
         f.write(buffer, 0, len1); 
        } 
       } finally { 
        f.close(); 
       } 

      } else { 
       this.failure = new RuntimeException(response 
         .getStatusLine().getReasonPhrase()); 
       LOG.error("Download failed: " 
         + response.getStatusLine().getReasonPhrase()); 
      } 

     } catch (Exception e) { 
      Toast.makeText(getActivity(), e.getMessage() + "1", 
        Toast.LENGTH_LONG).show(); 
      LOG.error("Download failed.", e); 
      this.failure = e; 
     } 

     return null; 
    } 
+0

你如何開始任務?你有沒有機會創建新的DownloadFileTask,然後調用doInBackground()? – Axarydax

+0

我在主線程中啓動DownloadFileTask,之後應用程序無法運行,直到下載完成。 –

回答

0

儘管您運行的任務在AsyncTask,但你有這些代碼行:在你的onPreExecute()方法,基本上將任務是自我開始前啓動一個對話框

downloadDialog.setMessage(getString(R.string.downloading)); 
    downloadDialog.show(); 

更多我沒有在您的實施中看到onPostExecute()方法。所以你永遠不會在.dismiss()的對話框中。但即使你是應用程序,直到下載完成,這個對話框仍然會是「堆棧」(正常行爲)。

+0

謝謝埃米爾。所以你的意思是,如果我移動下面幾行代碼,並關閉onPostExecute方法中的對話框。我的應用程序不會再被卡住了? downloadDialog.setMessage(getString(R.string.downloading)); downloadDialog.show(); –

+0

如果刪除以下2行代碼,則不需要關閉對話框,因爲您永遠不會顯示它。這意味着AsyncTask將會在後臺運行,而用戶甚至不會注意到它。你可能會遇到這樣的問題,如果你使用這個AsyncTask傳遞你正在獲取的數據,那麼你仍然需要等到它完成它的執行。 –