簡體   English   中英

使用 onRetainNonConfigurationInstance 的替代方法

[英]Alternatives to using onRetainNonConfigurationInstance

我有一個應用程序可能會在單個玩家使用應用程序期間跟蹤大量數據,而我的應用程序一次最多允許 5 個玩家,這意味着大量數據可能會乘以 5。

當 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();

由於似乎存在一些潛在問題,那么在屏幕旋轉中保留大量用戶數據的最佳選擇是什么?

感謝您的幫助!

使用 Bundle: onRetainNonConfigurationInstance的問題在於它與應用進程的生命周期綁定,而 Bundle 即使進程被完全殺死也可以保存和恢復。

如果您要讓人們離開並執行可能導致進程被殺死的內存密集型事情,那么 go 與 Bundle。

使用 setRetainInstance(true) 創建一個 Fragment,將需要保留的字段寫入其中並添加到 Activity。

private PlayerData[] mPlayerDataArr;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

public void setPlayerDataArr(PlayerData[] playerDataArr){
    this.mPlayerDataArr = playerDataArr;
}

public PlayerData[] getPlayerDataArr() {
    return mPlayerDataArr;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM