【问题标题】:ListView lags when loading from application cache从应用程序缓存加载时 ListView 滞后
【发布时间】:2012-10-02 09:27:57
【问题描述】:

我写了一小段代码,从互联网上下载图像并将它们缓存到缓存目录中。 它在辅助线程中运行。

{

    String hash = md5(urlString);
    File f = new File(m_cacheDir, hash);

    if (f.exists())
    {
        Drawable d = Drawable.createFromPath(f.getAbsolutePath());
        return d;
    }

    try {
        InputStream is = download(urlString);
        Drawable drawable = Drawable.createFromStream(is, "src");

        if (drawable != null)
        {
            FileOutputStream out = new FileOutputStream(f);
            Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
            bitmap.compress(CompressFormat.JPEG, 90, out);
        }

        return drawable;
    } catch (Throwable e) { }

    return null;
}

我使用此代码在 ListView 项目中加载图片,它工作正常。如果我删除第一个 if(我从磁盘加载图像)它运行顺利(并且每次都下载图片!)。如果我保留它,当您滚动列表视图时,您会在从磁盘加载图片时感觉有些滞后,为什么?

【问题讨论】:

    标签: android multithreading listview drawable


    【解决方案1】:

    为了回答“为什么”这个问题,我在我的 logcat 中遇到了很多 gc() 消息。 Android 在从磁盘解码文件之前分配内存,这可能会导致垃圾收集,这对所有线程的性能来说都是痛苦的。当您对 jpeg 进行编码时,可能也会发生同样的情况。

    对于解码部分,如果您有一个让 Android 就地解码图像,您可以尝试重用现有位图。请看下面的sn-p:

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = inSampleSize;
    options.inJustDecodeBounds = false;
    options.inMutable = true;
    if (oldBitmap != null) {
        options.inBitmap = oldBitmap;
    }
    return BitmapFactory.decodeFile(f.getAbsolutePath(), options);
    

    【讨论】:

      【解决方案2】:

      http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/

      在后台执行。(使用 AsyncTask 加载图像。)

      【讨论】:

      • 但是当你创建你的适配器对象时你不需要下载所有的图像,第一次下载碎片之后的可见视图图像。
      猜你喜欢
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      相关资源
      最近更新 更多