【问题标题】:Get time (& network speed) to download a file in AsyncTask - Android获取时间(和网络速度)以在 AsyncTask 中下载文件 - Android
【发布时间】:2013-09-04 07:20:24
【问题描述】:

我是 Android 新手。

谁能说,如何在 Android UI 中显示,在下载进度状态下,文件(比如xyz.mp4)正在下载的速度以及完成下载xyz.mp4 文件的剩余时间。

我正在使用AsyncTask 进行下载任务,我想显示速度和时间以及“进度百分比”。我在DialogFragment 中使用ProgressDialog

解决方案

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

【问题讨论】:

    标签: android performance time download


    【解决方案1】:

    你检查过TrafficStats 类吗?里面有很多信息。

    这是Example of TrafficStats

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

    这是一个测量边缘或 3g 下载速度的小应用程序的源代码 Detecting Network Speed and Type on 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;
    

    【讨论】:

    • 但我有一个疑问。假设我正在从一个浏览器应用下载一个文件,同时从我自己的另一个应用abc下载一个xyz.mp4,那么我的应用只需要下载@的速度信息987654328@ 仅限应用程序。那么上面给出的代码在这里可以工作吗??? Tnx 4 Rply
    • 如何传递参数downloadTimebytesIn ??什么意思??
    • 在这种情况下它不起作用,因为这个类在你的应用程序中而不是在浏览器中。和下载时间和字节,你必须从你的文件中计算出来。
    • 不,这不仅仅与您的 abc 有关。但速度的计算取决于原生应用程序。
    • 只需访问 Detecting Network Speed and Type on Android (Edge,3G),正如我在我的链接中提到的,你得到了你想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2011-04-24
    • 2019-08-26
    • 2015-09-16
    相关资源
    最近更新 更多