【问题标题】:How to prevent UI lag when updating Notification while downloading file?下载文件时更新通知时如何防止 UI 滞后?
【发布时间】:2013-06-25 02:24:45
【问题描述】:

我目前正在使用AsyncTask在我的应用程序的后台下载一个大文件,目前下载进度显示为ProgressDialog,通过onProgressUpdate更新如下:

protected String doInBackground(String... sUrl) {
        try {
            String destName = sUrl[1];
            file_Delete(destName); // Just to make sure!

            URL url = new URL(sUrl[0]);
            URLConnection connection = url.openConnection();
            connection.connect();
            int fileLength = connection.getContentLength();

            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(destName);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e(TAG, NAME + ": Error downloading file! " + e.getMessage());
            return e.getMessage();
        }

        return null;
    }

@Override protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        DownloadImage.mProgressDialog.setProgress(progress[0]);


    }

这很好用,但是我现在想在通知栏中使用通知,以便跟踪下载(因为文件可能相当大,用户希望从应用程序外部跟踪)。

我已经尝试了下面的代码,但是 UI 开始严重滞后,我可以看到它是因为 publishProgress 被调用了很多,所以我怎么能改变后台代码以每秒调用 publishProgress

@Override protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        DownloadImage.mProgressDialog.setProgress(progress[0]);

        DownloadImage.myNotification = new NotificationCompat.Builder(c)
        .setContentTitle("Downloading SlapOS")
        .setContentText("Download is " + progress[0] + "% done")
        .setTicker("Downloading...")
        .setOngoing(true)
        .setWhen(System.currentTimeMillis())
        .setProgress(100, progress[0], false)
        .setSmallIcon(R.drawable.icon)
        .build();

        DownloadImage.notificationManager.notify(1, DownloadImage.myNotification);

    }

【问题讨论】:

  • 你目前在哪个版本的android上运行这个?
  • Min SDK 版本为 8,但我在运行 4.2.1 的设备和运行 2.3.4 的设备上进行了测试,结果相同(UI 滞后,直到 systemUI 崩溃并重新启动)

标签: java android android-asynctask


【解决方案1】:

那么我怎么能改变后台代码以每秒调用一次publishProgress

我之前已经为一个在Notification 中显示% 的上传函数做过这个,但同样的想法。让您的AsyncTask 跟踪下载的percentDone 是什么,并且percentDone 更改时调用publishProgress。这样,您只会在下载百分比更改时调用publishProgress,因此Notification 需要更新。这应该可以解决 UI 滞后问题。

我正在写这个作为我建议的实现,听起来 OP 已经让它工作了。但也许这会在未来对其他人有所帮助:

    byte data[] = new byte[1024];
    long total = 0;
    int count, latestPercentDone;
    int percentDone = -1;
    while ((count = input.read(data)) != -1) {
        total += count;
        latestPercentDone = (int) Math.round(total / fileLength * 100.0);
        if (percentDone != latestPercentDone) {
            percentDone = latestPercentDone;
            publishProgress(percentDone);
        }
        output.write(data, 0, count);
    }

【讨论】:

  • 我也修复了延迟!
  • 谢谢,我改变了 latestPercentDone = (int)(total*100 / fileLength);并且工作完美!!!
  • 很棒的逻辑。我面临的唯一问题是latestPercentDone = (int) Math.round(total / fileLength * 100.0);这总是给出latestPercentDone = 0。所以我把它改成了latestPercentDone = (int) ((total * 100) / fileLength);
  • @AnujDeo 你得到 0 因为total 和/或fileLength 必须是double。如果totalfileLength 都是intlong,您将得到0,因为99/100=0 带有非浮点数。
【解决方案2】:

我真的很喜欢你的方法!我发现将代码更改为以下代码使我的进度条正确更新。我在使用 math.round() 时遇到了一些问题。

latestPercentDone = (int) ((dataBytesWritten / (float) totalSize) * 100);
    if (percentDone != latestPercentDone) {
    percentDone = latestPercentDone;
    publishProgress(percentDone);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多