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

9

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

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

除了我无法下拉通知栏之外,一切都很正常。为什么?


谢谢,我会看一下。你在不同的设备上或模拟器上测试过吗?在我看来,这似乎是一个非常奇怪的问题。 - pogo2065
在不同设备上测试,问题始终相同。 - b.i
相关问题(也未得到解答):https://dev59.com/9mXWa4cB1Zd3GeqPN4qX?rq=1 - pogo2065
当我使用sleep(1000)时,这并不意味着下载速度会变慢,对吗? - b.i
@iPaulPro:NotificatiocHelper来自于这个链接:https://eliasbland.wordpress.com/2011/03/11/an-example-of-how-to-run-a-background-task-and-report-progress-in-the-status-bar-using-asynctask-on-android/ - b.i
显示剩余7条评论
2个回答

4
以下内容来自评论。
“在publishProgress和check之前加入sleep(1000)方法,试一试吧。”这只是一个猜测。
“是的,它能够工作,但下载速度变慢了。”
希望您理解问题所在。由于您频繁更新通知栏,您将无法下拉通知栏。通过增加数据块的大小或每4kb或更多kb更新进度条而不是1kb,您可以避免这个问题。
以上方法不会减缓数据下载速度。

完全同意。通知进度没有太大的用处。我可能会使用16kb缓冲区。 - njzk2

2

我正在做这个:protected void onProgressUpdate(Integer... progress) { //此方法在UI线程上运行,它接收来自后台线程的进度更新,并将它们发布到状态栏 mNotificationHelper.progressUpdate(progress[0]); } ....但问题是我无法拉下或上通知栏。 - b.i

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接