Android:从服务器下载文件,并使用AsyncTask在通知栏中显示下载进度

问题描述:

我正在使用示例使用 AsycTask $ c $从服务器下载文件c>并在通知栏中显示downlaod进度。我只是修改了 doInBackground 方法,以便下载我的文件:

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?

以下是从评论中挑选。


你可以在publishProgress和
检查之前放一个睡眠(1000)方法。只是一个猜测

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.