2

我是安卓新手。

谁能说,如何在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)
    }
}
4

1 回答 1

1

你检查过TrafficStats类吗?里面有丰富的信息。

这是一个交通统计的例子

如果您正在寻找网络接口的最大下载/上传速度,那么wget已被移植到 Android,因此您可以使用这些答案中的任何一个

这是一个小应用程序的源代码,用于测量边缘或 3g 上的下载速度 在 Android(Edge,3G)上检测网络速度和类型

您也可以尝试以下代码

private SpeedInfo calculate(final long downloadTime, final long bytesIn) {
    SpeedInfo info=new SpeedInfo();
    //from mil to sec
    long bytespersecond   = (bytesIn / downloadTime) * 1000;
    double kilobits = bytespersecond * BYTE_TO_KILOBIT;
    double megabits = kilobits  * KILOBIT_TO_MEGABIT;
    info.downspeed = bytespersecond;
    info.kilobits = kilobits;
    info.megabits = megabits;

    return info;
}

private static class SpeedInfo { 
    public double kilobits = 0;
    public double megabits = 0;
    public double downspeed = 0;        
}


private static final int EXPECTED_SIZE_IN_BYTES = 1048576; //1MB 1024*1024

private static final double EDGE_THRESHOLD = 176.0;
private static final double BYTE_TO_KILOBIT = 0.0078125;
private static final double KILOBIT_TO_MEGABIT = 0.0009765625;
于 2013-09-04T07:39:47.680 回答