我是安卓新手。
谁能说,如何在Android UI中显示,在下载进度状态下,文件(比如xyz.mp4
)正在下载的速度以及完成下载xyz.mp4
文件的剩余时间。
我正在使用AsyncTask
下载任务,我想显示速度和时间以及“进度百分比”。我正在使用ProgressDialog
.DialogFragment
解决方案
class DownloadVideoFromUrl extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Do your pre executing codes (UI part)...
// The ProgressDialog initializations...
}
@Override
protected String doInBackground(String... params) {
if(params.length < 2) return "";
String videoUrlStr = params[0];
String fileName = params[1];
try {
URL url = new URL(videoUrlStr);
URLConnection conection = url.openConnection();
conection.connect();
// This will be useful so that you can show a 0-100% progress bar
int fileSizeInB = conection.getContentLength();
// Download the file
InputStream input = new BufferedInputStream(url.openStream(), 8 * 1024); // 8KB Buffer
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), fileName);
OutputStream output = new FileOutputStream(file);
int bufferSizeInB = 1024;
byte byteBuffer[] = new byte[bufferSizeInB];
int bytesRead;
long bytesInInterval = 0;
int timeLimit = 500; // ms.
long timeElapsed = 0; // ms.
long nlwSpeed = 0; String nlwSpeedStr = null;
long availableB = 0;
long remainingBytes = fileSizeInB;
long remainingTime = 0; String remainingTimeStr = null;
long startingTime = System.currentTimeMillis();
while ((bytesRead = input.read(byteBuffer)) != -1) { // wait to download bytes...
// bytesRead => bytes already Red
output.write(byteBuffer, 0, bytesRead);
availableB += bytesRead;
bytesInInterval += bytesRead;
remainingBytes -= bytesRead;
timeElapsed = System.currentTimeMillis() - startingTime;
if(timeElapsed >= timeLimit) {
nlwSpeed = bytesInInterval*1000 / timeElapsed; // In Bytes per sec
nlwSpeedStr = nlwSpeed + " Bytes/sec";
remainingTime = (long)Math.ceil( ((double)remainingBytes / nlwSpeed) ); // In sec
remainingTimeStr = remainingTime + " seconds remaining";
// Resetting for calculating nlwSpeed of next time interval
timeElapsed = 0;
bytesInInterval = 0;
startingTime = System.currentTimeMillis();
}
publishProgress(
"" + availableB, // == String.valueOf(availableB)
"" + fileSizeInB,
"" + bytesRead, // Not currently using. Just for debugging...
remainingTimeStr,
nlwSpeedStr);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
return "\n Download - Error: " + e;
}
return "";
}
protected void onProgressUpdate(String... progress) {
int availableB = Integer.parseInt(progress[0]);
int totalB = Integer.parseInt(progress[1]);
int percent = (availableB *100)/totalB; // here we get percentage of download...
String remainingTime = progress[3];
String nlwSpeed = progress[4];
if(remainingTime == null || nlwSpeed == null) return;
// Now show the details in UI:
// percent, remainingTime, nlwSpeed...
}
@Override
protected void onPostExecute(String result) {
// Code after download completes (UI part)
}
}