2014-09-22 4 views
0

У меня есть приложение, которое загружает и открывает pdf-файл из списка прослушивания списка.Android - Скачайте и откройте Pdf

Файл загружается и сохраняется на моем телефоне, но имеет размер файла 0 байт, поэтому он не может быть открыт. Я использовал код учебника от http://www.coderzheaven.com/2013/03/06/download-pdf-file-open-android-installed-pdf-reader/ Вот мой код. Любая помощь будет оценена.

public class OpenPdfActivity extends Activity { 

    TextView tv_loading; 
    String dest_file_path = "pdf-test.pdf"; 
    int downloadedSize = 0, totalsize; 
    String download_file_url = "http://www.education.gov.yk.ca/pdf/pdf-test.pdf"; 
    float per = 0; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     tv_loading = new TextView(this); 
     setContentView(tv_loading); 
     tv_loading.setGravity(Gravity.CENTER); 
     tv_loading.setTypeface(null, Typeface.BOLD); 
     downloadAndOpenPDF(); 
    } 

    void downloadAndOpenPDF() { 
     new Thread(new Runnable() { 
      public void run() { 
       Uri path = Uri.fromFile(downloadFile(download_file_url)); 
       try { 
        Intent intent = new Intent(Intent.ACTION_VIEW); 
        intent.setDataAndType(path, "application/pdf"); 
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        startActivity(intent); 
        finish(); 
       } catch (ActivityNotFoundException e) { 
        tv_loading 
          .setError("PDF Reader application is not installed in your device"); 
       } 
      } 
     }).start(); 

    } 

    File downloadFile(String dwnload_file_path) { 
     File file = null; 
     try { 

      URL url = new URL(dwnload_file_path); 
      HttpURLConnection urlConnection = (HttpURLConnection) url 
        .openConnection(); 

      urlConnection.setRequestMethod("GET"); 
      urlConnection.setDoOutput(true); 

      // connect 
      urlConnection.connect(); 

      // set the path where we want to save the file 
      File SDCardRoot = Environment.getExternalStorageDirectory(); 
      // create a new file, to save the downloaded file 
      file = new File(SDCardRoot, dest_file_path); 

      FileOutputStream fileOutput = new FileOutputStream(file); 

      // Stream used for reading the data from the internet 
      InputStream inputStream = urlConnection.getInputStream(); 

      // this is the total size of the file which we are 
      // downloading 
      totalsize = urlConnection.getContentLength(); 
      setText("Starting PDF download..."); 

      // create a buffer... 
      byte[] buffer = new byte[1024 * 1024]; 
      int bufferLength = 0; 

      while ((bufferLength = inputStream.read(buffer)) > 0) { 
       fileOutput.write(buffer, 0, bufferLength); 
       downloadedSize += bufferLength; 
       per = ((float) downloadedSize/totalsize) * 100; 
       setText("Total PDF File size : " 
         + (totalsize/1024) 
         + " KB\n\nDownloading PDF " + (int) per 
         + "% complete"); 
      } 
      // close the output stream when complete // 
      fileOutput.close(); 
      setText("Download Complete. Open PDF Application installed in the device."); 

     } catch (final MalformedURLException e) { 
      setTextError("Some error occured. Press back and try again.", 
        Color.RED); 
     } catch (final IOException e) { 
      setTextError("Some error occured. Press back and try again.", 
        Color.RED); 
     } catch (final Exception e) { 
      setTextError(
        "Failed to download image. Please check your internet connection.", 
        Color.RED); 
     } 
     return file; 
    } 

    void setTextError(final String message, final int color) { 
     runOnUiThread(new Runnable() { 
      public void run() { 
       tv_loading.setTextColor(color); 
       tv_loading.setText(message); 
      } 
     }); 

    } 

    void setText(final String txt) { 
     runOnUiThread(new Runnable() { 
      public void run() { 
       tv_loading.setText(txt); 
      } 
     }); 

    } 

} 
+0

ли на самом деле существуют PDF? Один в вашем примере возвращает 404 – daentech

+0

Нет, эта ссылка не поддерживает мой файл в формате pdf. Я редактирую pdf-ссылку для тестирования. – user3267471

ответ

1

Пару вещей:

Может быть, добавить тайм-аут?

Попробуйте НЕ проверять длину содержимого на данный момент.

Использование BufferedOutputStream

Что-то вроде этого:

FileOutputStream fos = new FileOutputStream(file); 
BufferedOutputStream out = new BufferedOutputStream(fos); 

try { 
HttpURLConnection urlConnection = (HttpURLConnection) url 
        .openConnection(); 
urlConnection.setRequestMethod("GET"); 
urlConnection.setReadTimeout(15000); 
urlConnection.connect(); 

try { 
     InputStream in = urlConnection.getInputStream(); 
     byte[] buffer = new byte[1024 * 1024]; 
     int len = 0; 

     while ((len = in.read(buffer)) > 0) 
     { 
     out.write(buffer, 0, len); 
     } 
     out.flush(); 
    } finally { 
     fos.getFD(). sync(); 
     out.close(); 
    } 





} catch (IOException eio) { 
Log.e("Download Tag", "Exception in download", eio); 
} 
+0

Вы гениальная благодарность – user3267471

0

(В том числе LogCat может помочь иметь лучшее представление о том, что происходит)

Одним из возможных проблема заключается в следующем:

fileOutput.close(); 

не убедитесь, что все байты записываются диск. Если вы попытаетесь прочитать файл сразу после закрытия потока, возможно, файл еще не написан полностью (особенно потому, что ваш буфер большой).

Решение запросить синхронизацию после закрытия():

fileOutput.close(); 
fileOutput.getFD().sync(); 

here подобный вопрос

+0

Все еще получает размер 0. Похоже, что файл не полностью загружается. – user3267471

Смежные вопросы