2010-04-20 51 views
14

保持我的問題很短,我已經創建了一個應用程序有3項活動,其中A - 類別列表,B - 單個項目 - 項目,C的列表。 B和C中顯示的數據從在線XML解析。但是,如果我通過A - > B1 - > C,然後返回到A然後返回到B1,我希望將其數據緩存到某處,這樣我就不必再次請求XML。在Android應用程序生命週期中緩存數據的好方法?

我是新來的Android和Java編程,我GOOGLE了很多,仍然無法找到(或根本沒有一個想法在哪裏看)的方式做我想做的。

將存儲所有收到的主要活動中的數據(包含HashMap?ContentProviders?),然後傳遞給B和C(如果他們那是以前同樣的要求)是一個好主意?

回答

13

一個簡單,快捷的方式緩存信息或跟蹤應用程序的狀態,是在this blog post描述延長應用

本博客文章忘了補充一點,你必須設置你CustomApplication類在清單中,如:

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

在我的項目中,我首先通過getInstance堅持單身風格。

更多資源:this answerGlobal Variables in Android Appsthis blog post

+0

感謝您的第一個人談論清單,我認爲不添加它會導致拋出異常。 – 2011-11-30 23:02:48

-1

您可以使用數據存儲在Android的參考說明這裏http://developer.android.com/guide/topics/data/data-storage.html

+0

這是一個選項,但是我不得不擔心在數據結束時刷新數據應用程序一生 – sniurkst 2010-04-20 19:03:20

+5

即使在應用程序生命週期結束後仍保持數據緩存,是不是一個好主意? – the100rabh 2010-04-20 19:58:37

+0

強烈建議不要使用鏈接回答。 – 2018-01-17 10:37:57

2

如果您想在內存上構建某種緩存,請考慮使用帶有SoftReferences的Map。 SoftReferences是一些引用,可能會將數據保留一段時間,但不會阻止垃圾收集。在手機上

內存是稀缺的,所以在記憶藏在心裏可能是不切實際的。在這種情況下,您可能需要將緩存保存在設備的輔助存儲中。

Google's Collections退房地圖製作工具,它可以讓你方便地構建一個2級緩存。考慮這樣做:

/** 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); 

關於緩存設備的輔助存儲,請檢查出Context.getCacheDir()。如果你像我一樣馬虎,就把所有東西放在那裏,希望系統能夠在需要更多空間時爲你清理它們:P

+0

我認爲這是正確的方式,但有點老...有關應用程序2級+存儲緩存的任何新發現? – Motheus 2014-10-09 21:02:24

+0

由於[適用於SoftReference的官方Android API文檔](http://developer.android.com/reference/java/lang/ref/SoftReference.html)解釋說,使用SoftReference構建緩存並不是一個好主意。 – herman 2015-01-20 00:00:32