使用通用图片加载器时,图片未被本地缓存 - 导致图片加载速度缓慢。

9

问题描述:

我正在创建一个带缩略图的可滚动文章列表,其中缩略图是通过我的SQLite数据库填充的。总体而言,它“工作”得很好,只是速度有点慢:

图片加载非常缓慢... 我以为使用 “Universal Image Loader”会在设备上缓存图像,并且这样会使它们似乎只是在视图中滚动,如果您已经查看过它们(或者至少接近于此)。但是-当您向上/向下拖动时,没有任何图像,然后3-5秒钟后,图像开始弹出(就像它们正在重新下载一样)

我正在动态更改缩略图框的可见性,但那完美无缺-它们似乎不会改变-它们只是滚动进入或退出视图,没有闪烁或任何东西。 (但是几秒钟后,图像才会出现)。

我通过移除滚动时的php脚本进行了测试...当我滚回到先前的位置时,图像不会显示-让我认为它每次都从我的PHP脚本加载。

但是根据文档“UsingFreqLimitedMemoryCache(当缓存大小超过限制时,删除最不常用的位图)-默认使用”

详细信息:

在我的ArticleEntryAdapter.js中,我有:

@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {

    // We need to get the best view (re-used if possible) and then
    // retrieve its corresponding ViewHolder, which optimizes lookup efficiency
    final View view = getWorkingView(convertView);
    final ViewHolder viewHolder = getViewHolder(view);
    final Article article = getItem(position);

    // Set the title
    viewHolder.titleView.setText(article.title);

    //Set the subtitle (subhead) or description
    if(article.subtitle != null)
    {
        viewHolder.subTitleView.setText(article.subtitle);
    }
    else if(article.description != null)
    {
        viewHolder.subTitleView.setText(article.description);
    }

    ImageLoader imageLoader = ImageLoader.getInstance();

    imageLoader.displayImage("", viewHolder.thumbView); //clears previous one
    if(article.filepath != null && article.filepath.length() != 0) {
        imageLoader.displayImage(
            "http://img.sltdb.com/processes/resize.php?image=" + article.filepath + "&size=100&quality=70",
            viewHolder.thumbView
            );
        viewHolder.thumbView.setVisibility(View.VISIBLE);
    } else {
        viewHolder.thumbView.setVisibility(View.GONE);
    }

    return view;
}

就图像不正确而言——虽然不经常发生,但有时在滚动时,我会看到两张相同的图像,当我查看文章时,它们根本没有关联(即没有机会实际拥有相同的图像)。因此,我将其向上或向下滚动,再次查看时,这张不正确的图像就变成了正确的图像。
提示:我是Java / Android的新手--您可能已经注意到了。
更多代码请参阅评论请求:
private View getWorkingView(final View convertView) {
    // The workingView is basically just the convertView re-used if possible
    // or inflated new if not possible
    View workingView = null;

    if(null == convertView) {
        final Context context = getContext();
        final LayoutInflater inflater = (LayoutInflater)context.getSystemService
          (Context.LAYOUT_INFLATER_SERVICE);

        workingView = inflater.inflate(articleItemLayoutResource, null);
    } else {
        workingView = convertView;
    }

    return workingView;
}

更新: 我的清单文件包含:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

但是我找到的缓存文件夹是完全空的:
mnt
  -sdcard
    -Android
      -data
        -com.mysite.news
          -cache
            -uil-images

getWorkingView(convertView);是什么? - Sherif elKhatib
@Sherif elKhatib - 已添加 - Dave
4个回答

19

我在列表视图中遇到了类似的图片问题。可能这个答案可以解决您错误的图片问题。

我刚刚下载了使用UniversalImageLoader的样例项目,它展示了你所描述的相同行为。

从查看源代码的角度来看,有一些注意事项。

public static final int DEFAULT_THREAD_POOL_SIZE = 3;
public static final int DEFAULT_THREAD_PRIORITY = Thread.NORM_PRIORITY - 1;
public static final int DEFAULT_MEMORY_CACHE_SIZE = 2 * 1024 * 1024; // bytes

这段话指出在任何时候都会有三个线程下载,最大可下载2MB的图像。你下载的图片有多大?另外,你是否将其缓存到磁盘上?如果是的话,那么速度会比较慢。

要配置ImageLoader中的一些基本选项,您需要传递给displayImage函数。

 DisplayImageOptions options = new DisplayImageOptions.Builder()
     .showStubImage(R.drawable.stub_image)
     .cacheInMemory()
     .cacheOnDisc()
     .build();

我还希望你尝试这些选项:

ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(this)
    .enableLogging()
    .memoryCacheSize(41943040)
    .discCacheSize(104857600)
    .threadPoolSize(10)
    .build();

imageLoader = ImageLoader.getInstance();
imageLoader.init(imageLoaderConfiguration);

经过我的测试,图片已经存在于磁盘中,但是加载速度仍然很慢。

经过大量测试,我发现主要问题是UniversalImageLoader加载速度太慢了。具体来说,ImageLoader和LoadAndDisplayImageTask正在阻塞进程。我(非常快地)将LoadAndDisplayImageTask重写为AsyncTask后性能立即提高了。您可以在GitHub上下载代码的分支版本。

Universal Image Loader with AsyncTasks


ImageLoaderConfiguration 还允许您指定最大图像大小。我没有尝试过这个选项,但它可能会有所帮助。 - Cameron Lowell Palmer
AsyncTask是Android API提供的一种在后台线程上执行某些操作并在主线程上返回结果的方法。它们往往非常快。UniversalImageLoader默认有3个线程进行下载工作,还有一个线程在主线程上更新图像视图。所以,是的,无论是UIL还是我重新使用AsyncTask类进行的重构都是“异步”的,但我认为它们的方法在性能方面还有很大的改进空间。 - Cameron Lowell Palmer
建议的设置并没有明显改变任何东西。我很乐意尝试您修改后的版本,但它仍然没有解决主要问题——它没有在本地缓存。 - Dave
好的。用我的版本试试看。如果可以,我可以进一步清理代码并进行一些错误修复。 - Cameron Lowell Palmer
3
我认为你在构建ImageLoaderConfiguration时忘记调用.defaultDisplayImageOptions(displayImageOptions)了。如果你不这样做,那些DisplayImageOptions选项将完全不起作用。我遇到了相同的缓慢问题,但在应用DisplayImageOptions后问题消失了。 - pimguilherme
显示剩余13条评论

3
一个备选方案是来自点火开源项目的“RemoteImageView”。

http://kaeppler.github.com/ignition-docs/ignition-core/apidocs/com/github/ignition/core/widgets/RemoteImageView.html

有效地说,RemoteImageView 扩展了 ImageView 并在幕后为您完成所有的获取/缓存工作。
虽然它不一定能解决您列出的问题,但作为替代方案值得探究。
编辑:如果您仍需要远程图像解决方案,我强烈推荐 Picasso。我已经在我的应用程序中用 Picasso 替换了 RemoteImageView: http://square.github.io/picasso/

有没有相关的教程或指导网站? - Dave
在ignition项目中的示例Activity在这里有一个非常简单明了的用法:https://github.com/kaeppler/ignition/blob/master/ignition-core/ignition-core-samples/src/com/github/ignition/samples/core/RemoteImageViewActivity.java - theelfismike

1

我怀疑 resize.php 很慢,特别是当它需要调整大页面并且收到多个请求时。而且,图像加载器中的缓存机制似乎没有实现。

首先,我会在图像加载之后再处理剩下的内容:字幕、描述和其他所有内容。因为如果图像加载时间太长,如果描述和其他所有内容一起出现,就会产生更即时的效果。通常你的语句顺序是正确的。

@CameronLowellPallmer 的答案解决了切换图像和缓存的问题。


resize.php文件被缓存,当您在浏览器中点击URL时会立即加载(因为它们是微小的文件)。我不确定您所说的“图像加载后的其余部分……”是什么意思(请记住我是新手 :))。 - Dave
我将图片相关的内容移到了标题之前...等等的内容没有改变。 - Dave
(更重要的是,图片应该被缓存在设备上 - 如果每次都在访问我的PHP脚本,那么这本身就是一个问题!) - Dave
我已经在我的回答中作了澄清。如果您可以控制PHP,则可以验证Android上的缓存行为以及调整大小是否从其缓存中提供服务。 - Joop Eggen
当我删除我的 PHP 代码(在滚动了一段时间后),图片就不再加载,这可能是因为它要么没有本地缓存,要么没有使用本地缓存。 - Dave

0

这个类对我很有用:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class ImageDownloader {

    Map<String,Bitmap> imageCache;

    public ImageDownloader(){
        imageCache = new HashMap<String, Bitmap>();

    }

    //download function
    public void download(String url, ImageView imageView) {
         if (cancelPotentialDownload(url, imageView)&&url!=null) {

             //Caching code right here
             String filename = String.valueOf(url.hashCode());
             File f = new File(getCacheDirectory(imageView.getContext()), filename);

              // Is the bitmap in our memory cache?
             Bitmap bitmap = null;

              bitmap = (Bitmap)imageCache.get(f.getPath());
                BitmapFactory.Options bfOptions=new BitmapFactory.Options();
                bfOptions.inDither=false;                     //Disable Dithering mode
                bfOptions.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
                bfOptions.inInputShareable=true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
                bfOptions.inTempStorage=new byte[32 * 1024]; 
                FileInputStream fs=null;

              if(bitmap == null){

                  //bitmap = BitmapFactory.decodeFile(f.getPath(),options);
                  try {
                      fs = new FileInputStream(f);
                        if(fs!=null) bitmap=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
                    } catch (IOException e) {
                        //TODO do something intelligent
                        e.printStackTrace();
                    } finally{ 
                        if(fs!=null) {
                            try {
                                fs.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }

                  if(bitmap != null){
                      imageCache.put(f.getPath(), bitmap);
                  }

              }
              //No? download it
              if(bitmap == null){
                  BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
                  DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
                  imageView.setImageDrawable(downloadedDrawable);
                  task.execute(url);
              }else{
                  //Yes? set the image
                  imageView.setImageBitmap(bitmap);
              }
         }
    }

    //cancel a download (internal only)
    private static boolean cancelPotentialDownload(String url, ImageView imageView) {
        BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);

        if (bitmapDownloaderTask != null) {
            String bitmapUrl = bitmapDownloaderTask.url;
            if ((bitmapUrl == null) || (!bitmapUrl.equals(url))) {
                bitmapDownloaderTask.cancel(true);
            } else {
                // The same URL is already being downloaded.
                return false;
            }
        }
        return true;
    }

    //gets an existing download if one exists for the imageview
    private static BitmapDownloaderTask getBitmapDownloaderTask(ImageView imageView) {
        if (imageView != null) {
            Drawable drawable = imageView.getDrawable();
            if (drawable instanceof DownloadedDrawable) {
                DownloadedDrawable downloadedDrawable = (DownloadedDrawable)drawable;
                return downloadedDrawable.getBitmapDownloaderTask();
            }
        }
        return null;
    }

    //our caching functions
    // Find the dir to save cached images
    public static File getCacheDirectory(Context context){
        String sdState = android.os.Environment.getExternalStorageState();
        File cacheDir;

        if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
            File sdDir = android.os.Environment.getExternalStorageDirectory();  

            //TODO : Change your diretcory here
            cacheDir = new File(sdDir,"data/tac/images");
        }
        else
            cacheDir = context.getCacheDir();

        if(!cacheDir.exists())
            cacheDir.mkdirs();
            return cacheDir;
    }

    private void writeFile(Bitmap bmp, File f) {
          FileOutputStream out = null;

          try {
            out = new FileOutputStream(f);
            bmp.compress(Bitmap.CompressFormat.PNG, 80, out);
          } catch (Exception e) {
            e.printStackTrace();
          }
          finally { 
            try { if (out != null ) out.close(); }
            catch(Exception ex) {} 
          }
    }
    ///////////////////////

    //download asynctask
    public class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
        private String url;
        private final WeakReference<ImageView> imageViewReference;

        public BitmapDownloaderTask(ImageView imageView) {
            imageViewReference = new WeakReference<ImageView>(imageView);
        }

        @Override
        // Actual download method, run in the task thread
        protected Bitmap doInBackground(String... params) {
             // params comes from the execute() call: params[0] is the url.
             url = (String)params[0];
             return downloadBitmap(params[0]);
        }

        @Override
        // Once the image is downloaded, associates it to the imageView
        protected void onPostExecute(Bitmap bitmap) {
            if (isCancelled()) {
                bitmap = null;
            }

            if (imageViewReference != null) {
                ImageView imageView = imageViewReference.get();
                BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
                // Change bitmap only if this process is still associated with it
                if (this == bitmapDownloaderTask) {
                    imageView.setImageBitmap(bitmap);

                    //cache the image


                    String filename = String.valueOf(url.hashCode());
                    File f = new File(getCacheDirectory(imageView.getContext()), filename);

                    imageCache.put(f.getPath(), bitmap);

                    writeFile(bitmap, f);
                }
            }
        }


    }

    static class DownloadedDrawable extends ColorDrawable {
        private final WeakReference<BitmapDownloaderTask> bitmapDownloaderTaskReference;

        public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) {
            super(Color.BLACK);
            bitmapDownloaderTaskReference =
                new WeakReference<BitmapDownloaderTask>(bitmapDownloaderTask);
        }

        public BitmapDownloaderTask getBitmapDownloaderTask() {
            return bitmapDownloaderTaskReference.get();
        }
    }

    //the actual download code
    static Bitmap downloadBitmap(String url) {
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpClient client = new DefaultHttpClient(params);
        final HttpGet getRequest = new HttpGet(url);

        try {
            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) { 
                Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); 
                return null;
            }

            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = null;
                try {
                    inputStream = entity.getContent(); 
                    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                } finally {
                    if (inputStream != null) {
                        inputStream.close();  
                    }
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {
            // Could provide a more explicit error message for IOException or IllegalStateException
            getRequest.abort();
            Log.w("ImageDownloader", "Error while retrieving bitmap from " + url + e.toString());
        } finally {
            if (client != null) {
                //client.close();
            }
        }
        return null;
    }
}

使用示例:

downloader = new ImageDownloader();
ImageView image_profile =(ImageView) row.findViewById(R.id.image_profile);
downloader.download(url, image_profile);

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