Good way to cache data during Android application lifecycle?

后端 未结 3 526
忘了有多久
忘了有多久 2020-12-14 03:16

keeping my question short, I have created an application with 3 activities, where A - list of categories, B - list of items, C - single item. Data displayed in B and C is pa

相关标签:
3条回答
  • 2020-12-14 03:39

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

    0 讨论(0)
  • 2020-12-14 03:45

    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.

    0 讨论(0)
  • 2020-12-14 03:53

    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

    0 讨论(0)
提交回复
热议问题