PDA

View Full Version : مشکل در نمایش درصد پیشرفت هنگام دانلود فایلهایی غیر از عکس و آهنگ



mortex3000
یک شنبه 25 مرداد 1394, 12:18 عصر
سلام من یه file downloader نوشتم اما مشکلی که هست اینه که هنگام دانلود فایل هایی مثل txt یا apk دانلود انجام میشه اما پروگرس بار حرکتی نمیکنه ولی برای فایل های عکس یا آهنگ مشکلی نیست و همه چیز خوب پیش میره. فکر کنم مشکل از بدست آوردن حجم فایل باشه لطفا راهنماییم کنید


این هم کد:


public class FileDownloader {


public static void download(final String downloadPath, final String filepath, final OnProgressDownloadListener listener) {
Thread thread = new Thread(new Runnable() {


@Override
public void run() {
try {
URL url = new URL(downloadPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();


final int fileSize = connection.getContentLength();


File file = new File(filepath);
if (file.exists()) {
file.delete();
}


FileOutputStream outputStream = new FileOutputStream(filepath);


InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len = 0;
int downloadedSize = 0;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
downloadedSize += len;


final float downloadPercent = 100.0f * (float) downloadedSize / fileSize;
if (listener != null) {


final int finalDownloadedSize = downloadedSize;
G.HANDLER.post(new Runnable() {


@Override
public void run() {
listener.onProgressDownload((int) downloadPercent, finalDownloadedSize, fileSize);
}
});
}


}


outputStream.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});


thread.start();
}
}


OnProgressDownloadListener listener = new OnProgressDownloadListener() {


private String convertByteToMB(int byteLength) {
float sizeInKB = (float) byteLength / 1024;
float sizeInMB = (float) sizeInKB / 1024;
return String.format("%.1fMB", sizeInMB);
}




@Override
public void onProgressDownload(int percent, int downloadedSize, int fileSize) {
prgDownload.setProgress(percent);
txtDownload.setText(percent + "% " + convertByteToMB(downloadedSize) + "/" + convertByteToMB(fileSize));
if (percent >= 100) {
txtDownload.setText("Download Complete");
}
}
};
FileDownloader.download(filepath, G.DIR_APP + "/" + filename, listener);