【问题标题】:progress bar not update the while downloading pdf下载pdf时进度条不更新
【发布时间】:2014-12-22 11:08:11
【问题描述】:

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

这是我的代码。

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" />

更新:

我上面的代码在其他 URL 上运行良好:>>

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

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

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

有什么想法吗??

【问题讨论】:

  • progress[0] 有什么好处。你得到1-100之间的有效数字吗?你确定文件正在下载吗?对我来说它看起来不错,我只是不喜欢你设置mProgressDialog 的方式。我会在onPreExecute 这样做,但这是我的意见。

标签: android pdf download


【解决方案1】:

使用此代码:

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);
}
}

【讨论】:

  • 您的代码通过您的下载链接可以正常工作。但不适用于我的下载链接。所以问题还是一样的。意味着文件在后台下载,进度条未更新。 :( 任何问题,在我的下载服务器链接或服务器依赖项中??
  • 是的,那么您的服务器依赖存在问题。因为在我的情况下,进度条正在更新。
  • 不,更新:我发现 publishProgress(""+(int)((total*100)/lenghtOfFile)); 的值此方法仅采用整数值。但就我而言,它跨越了整数存储范围。它应该是双倍或长。那么接下来该怎么做呢?我正在尝试将 ""+(int)((total*100)/lenghtOfFile) 的长值转换为整数。
  • 你能告诉我你得到了多少价值吗?
  • 在一段时间之前与我完全一样的问题。如果你得到正值,那么进度条将被更新。在我的情况下服务器文件问题。我确定在你的情况下和我一样的问题。跨度>
猜你喜欢
  • 1970-01-01
  • 2012-03-01
  • 2015-11-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-16
  • 2020-12-18
  • 1970-01-01
  • 2020-11-05
相关资源
最近更新 更多