繁体   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