安卓:从服务器下载文件,并显示使用的AsyncTask在通知栏的下载进度进度、服务器、文件、通知

2023-09-06 13:29:59 作者:回忆说、让我忘了你

我用这example使用 AsycTask 从服务器下载文件,并显示在通知栏立即下载进度。我只是修改了 doInBackground 的方法,以downoad我的文件:

I am using this example to download a file from a server using AsycTask and to show the downlaod progress in a notification bar. I just modified the doInBackground method in order to downoad my file:

@Override
    protected Void doInBackground(String... Urls) {
        //This is where we would do the actual download stuff
        //for now I'm just going to loop for 10 seconds
        // publishing progress every second
        try {   
            URL url = new URL(Urls[0]);
            URLConnection connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a typical 0-100%
            // progress bar
            int fileLength = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream( _context.getFilesDir() + "/file_name.apk");

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count ;
                // publishing the progress....
                publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();      
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


protected void onPreExecute() {
        // Create the notification in the statusbar
        mNotificationHelper.createNotification();
    }


protected void onPostExecute(Void result) {
        // The task is complete, tell the status bar about it
        mNotificationHelper.completed();
    }

protected void onProgressUpdate(Integer... progress) {
        // This method runs on the UI thread, it receives progress updates
        // from the background thread and publishes them to the status bar
        mNotificationHelper.progressUpdate(progress[0]);
    }

一切都会好的,只是我不能拉下通知栏。为什么呢?

Everything is going ok except that I cannot pull down the notification bar. Why?

推荐答案

以下是从评论中取出。

可以请你把一个睡眠(1000)法publishProgress前   检查。只是一个猜测

can you please put an sleep(1000) method before publishProgress and check. just a guess

-

是的,它的工作原理,但下载放缓

yes, it works, but the download is slowing

希望大家理解这个问题。既然要更新的通知栏非常频繁,你不能能够把它拉下来。通过增加数据块大小,或通过更新进度条上每4个或更多KB,而不是1KB,就可以避免这个问题。

Hope you understood the problem. Since you are updating the Notification bar very frequently, you cant be able to pull it down. By increasing the chunk size of data or by updating the progress bar on every 4 or more kb instead of 1kb, you can avoid this problem.

以上不会减慢数据下载。

Above will not slow down the data download.