进度条在下载pdf时不更新

时间:2014-12-22 11:08:11

标签: android pdf download

我正在从我的网络服务器上下载pdf文件&显示进度条中的更新进度。但我的进度条没有更新。虽然文件是在背景中下载的,但进度条仍然像图片一样。

enter image description here   这是我的代码。

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DownloadsPDFTest extends Activity {

 ProgressDialog mProgressDialog;
 String mPdf_links = "http://nationalappsbangladesh.com/Files/02122014104948amar_bangla_boi2.pdf";
 String mlist;
 String img_path;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_download_pdf);


  ((Button) findViewById(R.id.button_start_download))
    .setOnClickListener(new OnClickListener() {

     @Override
     public void onClick(View v) {

      startDownloadingOrOpen();

     }
    });

 }

 private void startDownloadingOrOpen() {
  // set the file name from url
  String filenameLink = mPdf_links.substring(
    mPdf_links.lastIndexOf('/') + 1, mPdf_links.length());
  System.out.println("FileName:" + filenameLink);

  File downloadfile = new File("/sdcard/CONSTRUCTION/" + filenameLink);

  if (!downloadfile.exists()) {

   Log.e("DownloadsPDFTest", "First Part Working");

   mProgressDialog = new ProgressDialog(DownloadsPDFTest.this);
   mProgressDialog.setMessage("Downloading..");
   mProgressDialog.setIndeterminate(false);
   mProgressDialog.setProgress(0);
   mProgressDialog.incrementProgressBy(1);
   mProgressDialog.setMax(100);
   mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

   // execute this when the downloader must be fired
   DownloadFile downloadFile = new DownloadFile();
   System.out.println(mPdf_links);
   downloadFile.execute(mPdf_links);

  } else {

   Log.e("DownloadsPDFTest", "Second Part Working");

   File file = new File(Environment.getExternalStorageDirectory()
     .getAbsolutePath() + "/CONSTRUCTION/" + filenameLink);
   Intent intent = new Intent(Intent.ACTION_VIEW);
   intent.setDataAndType(Uri.fromFile(file), "application/pdf");
   intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
   startActivity(intent);

  }
 }

 private class DownloadFile extends AsyncTask<String, Integer, String> {
  @Override
  protected String doInBackground(String... sUrl) {
   try {
    URL url = new URL(sUrl[0]);
     URLConnection c
    connection.connect();
    // this will be useful so that you can show a typical 0-100%
    // progress bar
    int fileLength = connection.getContentLength();
    System.out.println("File length:" + fileLength);
    System.out.println("TEST here in Downloadfile");
    // download the file
    File wallpaperDirectory = new File("/sdcard/CONSTRUCTION/");
    // have the object build the directory structure, if needed.
    wallpaperDirectory.mkdirs();
    // create a File object for the output file

    String filename = sUrl[0].substring(
      sUrl[0].lastIndexOf('/') + 1, sUrl[0].length());
    System.out.println("FileName:" + filename);
    InputStream input = new BufferedInputStream(url.openStream());
    OutputStream output = new FileOutputStream(
      "/sdcard/CONSTRUCTION/" + filename);

    byte data[] = new byte[2048];
    long total = 0;
    int count;
    while ((count = input.read(data)) != -1) {
     total += count;
     System.out.println("Total downloaded" + total + " count:"
       + count);
     // publishing the progress....
     publishProgress((int) (total * 100 / fileLength));
     output.write(data, 0, count);
    }

    output.flush();
    output.close();
    input.close();

    mProgressDialog.dismiss();

    File file = new File(Environment.getExternalStorageDirectory()
      .getAbsolutePath() + "/CONSTRUCTION/" + filename);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file), "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    startActivity(intent);

   } catch (Exception e) {
   }
   return null;
  }

  @Override
  protected void onPreExecute() {
   super.onPreExecute();
   mProgressDialog.show();
  }

  @Override
  protected void onProgressUpdate(Integer... progress) {
   super.onProgressUpdate(progress);
   mProgressDialog.setProgress(progress[0]);
  }
 }
}

xml在这里。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<Button
    android:id="@+id/button_start_download"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="Click to Download PDF/ Open it" />

<TextView
    android:id="@+id/textView_test_data"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button_start_download"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="21dp"
    android:text="Download Pdf Sample" />

更新:

我的上述代码适用于其他网址,例如:&gt;&gt;

http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg

我的问题:我的下载链接中有任何问题吗?或者我必须编写额外的代码来处理这么大的文件/ pdf文件?

我的服务器下载链接类似于http://nationalappsbangladesh.com/Files/02122014104948amar_bangla_boi2.pdf

任何想法?

1 个答案:

答案 0 :(得分:0)

使用此代码:

private void startDownload() {
    String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
    new DownloadFileAsync().execute(url);
}
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Downloading file..");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        return mProgressDialog;
    default:
        return null;
    }
   }

class DownloadFileAsync extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
    super.onPreExecute();
    showDialog(DIALOG_DOWNLOAD_PROGRESS);
}

@Override
protected String doInBackground(String... aurl) {
    int count;

try {

URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();

int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");

byte data[] = new byte[1024];

long total = 0;

    while ((count = input.read(data)) != -1) {
        total += count;
        publishProgress(""+(int)((total*100)/lenghtOfFile));
        output.write(data, 0, count);
    }

    output.flush();
    output.close();
    input.close();
} catch (Exception e) {}
return null;

}
protected void onProgressUpdate(String... progress) {
     Log.d("ANDRO_ASYNC",progress[0]);
     mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
    dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}