Caching SVG Images Using Android and Memory

I am using Android SVG ( http://code.google.com/p/svg-android/ ). I use the same svg file in several actions of my application. Is it good to create a cache for storing and retrieving images?

I am using SparseArray to store a PictureDrawable (generated from SVG) as follows:

SVG svg = SVGParser.getSVGFromResource(resources, resourceId);
PictureDrawable pictureDrawable = svg.createPictureDrawable();
cache.put(resourceId, pictureDrawable);

Should I pay attention to memory usage when managing PictureDrawable objects? I confirm that the maximum items in the cache will be less than 50.

+5
source share
1 answer

, . svg . CPU, .

, . (, 2) svg, .

10 Context.getCacheDir(), .

, , , Cache, , .. .

, Serializable, :

public class ObjectCacheFile<T> {
    private final File mFile;

    public ObjectCacheFile(Context context, String name) {
        mFile = new File(context.getCacheDir(), name);
    }

    public File getFile() {
        return mFile;
    }

    public void put(T o) {

        try {

            if (!mFile.exists()) {
                mFile.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(mFile);

            ObjectOutputStream objOut = new ObjectOutputStream(fos);

            try {
                objOut.writeObject(o);
            } finally {
                objOut.close();
            }
        } catch (IOException e) {
            Log.e(App.getLogTag(this), "error saving cache file", e);
        }
    }

    @SuppressWarnings("unchecked")
    public T get() {

        if (!mFile.exists()) {
            return null;
        }

        try {
            ObjectInputStream objIn = new ObjectInputStream(new FileInputStream(mFile));
            try {
                return (T) objIn.readObject();
            } finally {
                objIn.close();
            }
        } catch (IOException e) {
            Log.e(App.getLogTag(this), "error reading cache file", e);
        } catch (ClassNotFoundException e1) {
            Log.e(App.getLogTag(this), "cache file corrupted, deleting", e1);
            mFile.delete();
        }

        return null;
    }

}
+4

All Articles