2011-06-15 94 views
4

我有一個應用程序,可能跟蹤單個玩家在應用程序使用過程中的大量數據,而且我的應用程序一次最多可以允許5個玩家,這意味着大量數據可能會相乘times 5.替代使用onRetainNonConfigurationInstance

當Activity被銷燬時,我將所有的數據寫入到我的SQLite數據庫,並且工作正常。

問題發生在方向更改期間。我使用onRetainNonConfigurationInstance是因爲我認爲我至少可以依靠它來改變方向,但是我發現Android中的其他事情可能會消除我的數據。用戶報告的一些例子:

- While the app was running, the user took a phone call. After returning to the app, the data was gone. 
- While the app was running, another user downloaded an update to a different app from the Market, and found the data gone after returning to the app. 
- While the app was running, another user started a different app (a music player), and returned to find the data gone. 

我知道,使用onRetainNonConfigurationInstance的是問題,因爲我的應用程序最初寫每一個人數據字段爲每個玩家束,並同時應用程序是實現這種方式,沒有問題在數月中遇到。

一旦我發現onRetainNonConfigurationInstance,並用它來執行,我開始接受投訴。

我的實現很簡單。我實現如下:

@Override 
public Object onRetainNonConfigurationInstance() 
{ 
    return mPlayers; //array of player objects 
} 

然後在的onCreate,我這樣做:

mPlayers = (PlayerData [])getLastNonConfigurationInstance(); 

因爲似乎有一些潛在的問題,什麼是保存整個屏幕的大量用戶數據的最佳替代品旋轉?

感謝您的幫助!

回答

4

使用Bundle:onRetainNonConfigurationInstance的問題在於它與應用程序進程的生命週期相關聯,即使進程完全終止,Bundle也可以保存和恢復。

如果您打算讓人們關閉並且做可能導致進程死亡的內存密集型事情,那麼請使用Bundle。

+0

謝謝Femi。讓我再補充一點這個問題。我認爲Bundle是更好的選擇,但是推進的最佳方式是什麼?例如,假設我有100個我想保留的字符串。可以將100個不同長度的獨立字符串填充到Bundle中嗎?或者我應該實現某種Bundle擴展?或者在這些情況下有什麼可以更好的工作? – Michael 2011-06-16 02:24:09

+0

Bundle將採用包括字符串在內的大多數基元的數組和ArrayLists。我過去做過的一件事情是,當我感到懶惰時,基本上只是用我想要的零散件構建一個JSON對象,然後將其序列化到Bundle中。在另一端反序列化它,你很好走。 – Femi 2011-06-16 02:36:33

+0

好的,謝謝費米,我會試試看。 – Michael 2011-06-16 03:30:13