【问题标题】:Android: download bunch of images from serverAndroid:从服务器下载一堆图像
【发布时间】:2016-01-21 07:09:05
【问题描述】:

我正在开发测验应用程序。所有问题都在服务器端。当用户选择测验服务器的类别时,返回包含问题、答案变体和图像 url 的 json 文件。例如,在一个类别中,我有 10 个问题,其中 4 个问题需要加载图像。我从 json 文件中检查其中哪些有图像 url,我需要将它们下载到缓存或磁盘内存(不知道哪种解决方案更好)
问题:如何加载一堆来自服务器的图像并显示进度条?以及当用户想参加测验时如何访问下载的图像? 我需要在开始回答问题之前下载图片,因为回答问题会有时间限制。

【问题讨论】:

    标签: android image picasso universal-image-loader aquery


    【解决方案1】:

    我认为你使用https://github.com/nostra13/Android-Universal-Image-Loader。该库使用磁盘缓存来存储图像,因此如果图像在磁盘上可用,则无需下载图像。

    要创建带有更新的进度条,您必须创建一个 AsyncTask:http://developer.android.com/reference/android/os/AsyncTask.html。

    文章的第一个例子是一个文件的下载。对于您的项目,请在下载的每个图像处调用 publishProgress()。

    编辑:

    private class DownloadImageTask extends AsyncTask<List<URL>, Integer, List<Bitmap>> {
        ImageLoader imageLoader = ImageLoader.getInstance(); // Instance android-universal-image-loader
        List<Bitmap> downloadedImage = new LinkedList<>();
    
        protected List<Bitmap> doInBackground(List<URL>... urls) {
            List<URL> yoururls = urls[0];
            for(URL url : yoururls){
                imageLoader.loadImage(url.toString(), new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        downloadedImage.add(loadedImage);
                        publishProgress(1);
                    }
                });
            }
            return downloadedImage;
        }
    
        protected void onProgressUpdate(Integer... progress) {
            //Update here your progress bar
        }
    
        protected void onPostExecute(List<Bitmap> result) {
            //Close your progress bar
            //Put your bitmap in your imageview
        }
    
        protected void onPreExecute(){
            //Create your progress bar
        }
    }
    

    执行:

    List<Bitmap> yourimages = new DownloadImageTask().execute(YOURLISTURL).get();
    

    【讨论】:

    • 你的意思是在 DownloadFilesTask 而不是 Downloader.downloadFile(urls[i]) 我将使用universal-image-loader?
    • 我在我的第一篇文章中添加了一个示例,它是一个异步任务,用于下载带有 URL 列表的图像。如果需要,您可以将其替换为字符串列表。该异步任务返回一个位图列表(您的图像),您可以在 onPostExecute() 或返回 get() 函数中管理此位图列表。
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-10
      • 2012-09-22
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 1970-01-01
      相关资源
      最近更新 更多