在developer.android.com上缓存Bitmap错误

时间:2013-01-04 06:33:19

标签: java android

我刚刚在developer.android.com

上阅读了来自网址缓存位图的教程

参考代码

    private LruCache<String, Bitmap> mMemoryCache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // Get memory class of this device, exceeding this amount will throw an
        // OutOfMemory exception.
        final int memClass = ((ActivityManager) context.getSystemService(
                Context.ACTIVITY_SERVICE)).getMemoryClass();

        // Use 1/8th of the available memory for this memory cache.
        final int cacheSize = 1024 * 1024 * memClass / 8;

        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in bytes rather than number of items.
                return bitmap.getByteCount();
            }
        };
        ...
    }

    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    public Bitmap getBitmapFromMemCache(String key) {
        return mMemoryCache.get(key);
    }

public void loadBitmap(int resId, ImageView imageView) {
    final String imageKey = String.valueOf(resId);

    final Bitmap bitmap = getBitmapFromMemCache(imageKey);
    if (bitmap != null) {
        mImageView.setImageBitmap(bitmap);
    } else {
        mImageView.setImageResource(R.drawable.image_placeholder);
        BitmapWorkerTask task = new BitmapWorkerTask(mImageView);
        task.execute(resId);
    }
}
活动缓存中的

是beign initialize,有两种方法

  1. addBitmapToMemoryCache(String key, Bitmap bitmap)

  2. getBitmapFromMemCache(String key)

  3. 这是BitmapWorkerTask类

    class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
        ...
        // Decode image in background.
        @Override
        protected Bitmap doInBackground(Integer... params) {
            final Bitmap bitmap = decodeSampledBitmapFromResource(
                    getResources(), params[0], 100, 100));
            addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
            return bitmap;
        }
        ...
    }
    

    现在我的问题是在 BitmapWorkerTask 类中如何调用方法 addBitmapToMemoryCache(String.valueOf(params [0]),bitmap); 被调用,并且有任何引用在Activty中定义的方法或可能在其他类

    中的方法

2 个答案:

答案 0 :(得分:2)

BitmapWorkerTask可能是活动中的内部类,因此可以访问已定义的方法。

答案 1 :(得分:0)

对于仍无法获取示例代码的人,

为了使代码正常工作,您应该将BitmapWorkerTask类作为内部类,然后更改其两个静态函数

public  static int calculateInSampleSize()
public  static Bitmap decodeSampledBitmapFromResource()

到正常(非静态)方法