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

一切正常,只是我无法拉下通知栏。为什么?

4

2 回答 2

4

以下是从评论中挑选出来的。

你能在 publishProgress 之前放一个 sleep(1000) 方法并检查。只是一个猜测

-

是的,它可以工作,但下载速度很慢

希望你明白这个问题。由于您非常频繁地更新通知栏,因此您无法将其拉下。通过增加数据的块大小或每 4 或更多 kb 而不是 1kb 更新进度条,您可以避免此问题。

以上不会减慢数据下载速度。

于 2012-07-16T17:46:53.677 回答
2

你应该重写onProgressUpdate方法来更新你的 UI。

于 2012-07-13T12:38:00.993 回答