下载文件时更新通知时如何防止UI滞后? [英] How to prevent UI lag when updating Notification while downloading file?

查看:85
本文介绍了下载文件时更新通知时如何防止UI滞后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently using AsyncTask to download a large file in the background within my app, currently the download progress is shown as a ProgressDialog which is updated via onProgressUpdate as below:

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]);


    }

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

This works fine, however I now want to use a notification in the notification bar so keep track of the download instead (as the file can be rather large and users would like to keep track from outside the app).

我尝试了以下代码,但是UI开始严重滞后,由于publishProgress被大量调用,我可以看到它,所以我该如何更改后台代码以仅每秒调用publishProgress

I have tried the below code however the UI starts to lag badly, I can see its due to the publishProgress getting called alot, so how could I go about changing the background code to call publishProgress only every second

@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);

    }

推荐答案

所以我该如何更改后台代码以仅每秒调用一次publishProgress

so how could I go about changing the background code to call publishProgress only every second

我之前对上传功能执行过此操作,该功能在Notification中显示了%,但完全相同.让您的AsyncTask跟踪下载的内容是percentDone,并且percentDone更改时会调用publishProgress.这样,您将只在%下载已更改时调用publishProgress,因此Notification需要更新.这样可以解决UI延迟问题.

I have done this before for an upload function that showed the % in a Notification, but same exact idea. Have your AsyncTask keep track of what percentDone the download is, and ONLY call publishProgress when percentDone changes. That way, you will only ever call publishProgress when the % downloaded changes, and the Notification therefore needs to update. This should resolve the UI lag.

我正在将其编写为建议的实现,听起来好像OP已经使它起作用了.但这也许会在将来对其他人有所帮助:

I was writing this up as my suggested implementation, sounds like the OP already got it working. But maybe this will help someone else in the future:

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

这篇关于下载文件时更新通知时如何防止UI滞后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆