Caching Svg Images On Android And Memory Usage
Solution 1:
Yes, its a very good Idea, Only on first run, App will generate images for that particular device screen size from svg, and store them in cache, and use these all the time after that. Saves a lot of CPU, faster UI loading.
However, I'd recommend to save cache files with names containing version of your App. If you release an update (say version 2) with some different svg images, then new files with different names will be used instead of old files.
Its normally Ok to use up to 10Mb in Context.getCacheDir()
, system will clean this folder when low on storage.
Also, as a good measure, every time you initialize Cache
class, you could do a little clean up, i.e. delete some old version or not requires items.
Here's a class I mostly use to just save and get a Serializable object, from App cache directory:
publicclassObjectCacheFile<T> {
privatefinal File mFile;
publicObjectCacheFile(Context context, String name) {
mFile = newFile(context.getCacheDir(), name);
}
public File getFile() {
return mFile;
}
publicvoidput(T o) {
try {
if (!mFile.exists()) {
mFile.createNewFile();
}
FileOutputStreamfos=newFileOutputStream(mFile);
ObjectOutputStreamobjOut=newObjectOutputStream(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()) {
returnnull;
}
try {
ObjectInputStreamobjIn=newObjectInputStream(newFileInputStream(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();
}
returnnull;
}
}
Post a Comment for "Caching Svg Images On Android And Memory Usage"