0

我在像“ http://sample.com/test ”这样的 url 中有一个问题,它有大量的 xml 数据,我无法在 mainUI 中显示进度条。

请做有需要的。

4

2 回答 2

1

AsyncTask中,后台任务将 xml 保存在本地内存中

                    int count;
                    try {
                        URL url = new URL("http://sample.com/test");
                        URLConnection conection = url.openConnection();
                        conection.connect();
                        // getting file length
                        int lenghtOfFile = conection.getContentLength();
                        // input stream to read file - with 8k buffer
                        InputStream input = new BufferedInputStream(url.openStream(), 8192);
                        // Output stream to write file
                        OutputStream output = new FileOutputStream("/data/data/com.pc.demo/temp.xml");
                        byte data[] = new byte[1024];
                        long total = 0;
                        while ((count = input.read(data)) != -1) {
                            total += count;
                            int progress = (int)((total*100)/lenghtOfFile) ;
                            System.out.println("update---"+progress);
                            publishProgress(progress);
                            output.write(data, 0, count);
                        }

                        // flushing output
                        output.flush();
                        // closing streams
                        output.close();
                        input.close();

                    } catch (Exception e) {
                        Log.e("Error: ", e.getMessage());
                    }

后执行

     File yourFile = new File("/data/data/com.pc.demo/temp.xml");
     InputStream input =  new BufferedInputStream(new FileInputStream(yourFile), 8086);

onProgressUpdate

    setProgressPercent(progress[0])
于 2013-04-25T05:26:50.573 回答
0

您可以覆盖 AsyncTask 的 onProgressUpdate() 函数,并使用 doInBackgroud() 中的 publishProgress(Progress... values) 将您的保存状态推送到进度然后更新它,这是我的简单代码,希望可以帮助您.

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]); //change this with your progress bar
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }

}

于 2013-04-25T05:42:49.267 回答