Я загружаю pdf-файл с моего веб-сервера & показывает прогресс обновления в строке прогресса. Но i progressbar не обновляется. Индикатор выполнения все еще похож на изображение, хотя файл загружается в backgroud.индикатор выполнения не обновляется при загрузке 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 is here.
<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" />
Update:
Мой выше код работает отлично для других URL, как: >>
http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg
Мой вопрос: ли их какие-либо проблемы в моей ссылке для скачивания? Или мне нужно написать дополнительный код для обработки такого большого файла/файла pdf?
My server download link is like http://nationalappsbangladesh.com/Files/02122014104948amar_bangla_boi2.pdf.
Любая идея ??
Что вы получите за 'прогресса [0]'. Получаете ли вы действительные цифры от 1 до 100? вы уверены, что файл загружен? Для меня это выглядит хорошо, мне не нравится, как вы настраиваете 'mProgressDialog'. Я бы сделал это в 'onPreExecute', но это мое мнение. – Mike