com.wj.android.wjframe.bitmap.BitmapMemoryCache.java Source code

Java tutorial

Introduction

Here is the source code for com.wj.android.wjframe.bitmap.BitmapMemoryCache.java

Source

/*
 * Copyright (c) 2014,KJFrameForAndroid Open Source Project,.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wj.android.wjframe.bitmap;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.wj.android.wjframe.utils.SystemTool;

/**
 * lruBitmap
 * <b></b> 2014-7-11
 *
 * @version 1.0
 */
public final class BitmapMemoryCache implements ImageDisplayer.ImageCache {

    private LruCache<String, Bitmap> cache;
    private int maxSize = 0;

    public BitmapMemoryCache() {
        int maxMemory = (int) (Runtime.getRuntime().maxMemory());
        init(maxMemory / 8);
    }

    /**
     * @param maxSize ???kb
     */
    public BitmapMemoryCache(int maxSize) {
        init(maxSize);
    }

    /**
     * @param maxSize ???kb
     */
    @SuppressLint("NewApi")
    private void init(int maxSize) {
        this.maxSize = maxSize;
        cache = new LruCache<String, Bitmap>(maxSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                super.sizeOf(key, value);
                if (SystemTool.getSDKVersion() >= 12) {
                    return value.getByteCount();
                } else {
                    return value.getRowBytes() * value.getHeight();
                }
            }
        };
    }

    @Override
    public void remove(String key) {
        cache.remove(key);
    }

    @Override
    public void clean() {
        init(maxSize);
    }

    /**
     * @param url ?
     * @return
     */
    @Override
    public Bitmap getBitmap(String url) {
        return cache.get(url);
    }

    /**
     * @param url    ?
     * @param bitmap ?bitmap
     */
    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        if (this.getBitmap(url) == null) {
            cache.put(url, bitmap);
        }
    }
}