Good way to cache data during Android application lifecycle?

青春壹個敷衍的年華 提交于 2019-11-28 19:33:47
digitarald

A simple and fast way to cache information or to keep track of the application state, is to extend the Application as described in this blog post.

This blog post forgets to add that you have to set your CustomApplication class in the manifest, like:

<application [...] android:name="CustomApplication">

In my projects I stick to the singleton style via getInstance.

More resources: this answer, Global Variables in Android Apps and this blog post.

If you want to build some sort of cache on memory, consider using a Map with SoftReferences. SoftReferences are sort of references that tend to keep your data around for a while, but does not prevent it from being garbage collected.

Memory on a cell phone is scarce, so keeping everything in memory may not be practical. In that case you may want to save your caches on the device's secondary storage.

Check out MapMaker from Google's Collections, which allows you to conveniently build a 2-level cache. Consider doing this:

/** Function that attempts to load data from a slower medium */
Function<String, String> loadFunction = new Function<String, String>() {
    @Override
    public String apply(String key) {
        // maybe check out from a slower cache, say hard disk
        // if not available, retrieve from the internet
        return result;
    }
};

/** Thread-safe memory cache. If multiple threads are querying
*   data for one SAME key, only one of them will do further work.
*   The other threads will wait. */
Map<String, String> memCache = new MapMaker()
                                .concurrentLevel(4)
                                .softValues()
                                .makeComputingMap(loadFunction);

About cache on device's secondary storage, check out Context.getCacheDir(). If you're sloppy like me, just leave everything there and hope that the system will clean things for you when it needs more space :P

You can make use of data storage as explained in Android Reference here http://developer.android.com/guide/topics/data/data-storage.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!