我应该将对象保存为宗地还是单独存储变量?

时间:2012-02-25 16:06:39

标签: java android bundle parcelable

我希望存储一个简单类的几个实例,作为在活动未清晰时保存我的应用程序状态的一部分。

public class Player
{
   int score1;
   int score2;
   int total;
}

我被告知分手是要走的路。使用以下方法单独保存变量有什么优势呢?

savedInstanceState.putInt(player.getScore1);

编辑: 我可能会存储每个类中最多50个实例,并最终将它们中的变量数增加到12个。

序列化让人想到,但我转过身去,我被告知这是一种缓慢低效的存储方法,甚至知识库文档建议避免使用它。

3 个答案:

答案 0 :(得分:0)

我的第一个建议是使用SharedPreference而不是savedInstanceState。 savedInstanceState拥有自己的pro和con。 如果app通过Back或home按钮之类的用户交互关闭,则不会调用savedInstanceState。仅当应用程序受到android o.s.的干扰时才会调用它。本身就像你正在使用应用程序和调用发生和应用程序进入后台。 在共享偏好中,您可以控制自己以自己想要的方式编写自己的逻辑。

答案 1 :(得分:0)

每当一个活动被系统或使用杀死时,总是会调用onPause()方法。 您可以使用SharedPreferences存储您的值,因此可以在再次创建活动时检索它。

根据您的代码,您可以进行以下更改:

public class Player extends Activity {

  private SharedPreferences mPrefs;
  int score1;
  int score2;
  int total;
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     SharedPreferences mPrefs = getSharedPreferences();
     score1 = mPrefs.getInt(String key1, int defaultValue);
     score2 = mPrefs.getInt(String key2, int defaultValue);
     total = mPrefs.getInt(String key3, int defaultValue);
 }

  protected void onPause() {
     super.onPause();

     SharedPreferences.Editor ed = mPrefs.edit();
     ed.putInt(key1, score1);
     ed.putInt(key2, score2);
     ed.putInt(key3, total);
     ed.commit();
 }
}

String key是首选项的名称。

int defaultValue是未存储任何内容时返回的默认值。通常在首次创建活动时返回

答案 2 :(得分:0)

我使用以下方法存储我的玩家实例。

public Object onRetainNonConfigurationInstance() 
{
  if (table != null) // Check that the object exists
      return(table);
  return super.onRetainNonConfigurationInstance();
}

存储的表实例包含一个包含所有播放器实例的数组。重新加载我的应用程序时,使用以下代码在onCreate方法中加载表对象:

if (getLastNonConfigurationInstance() != null)
    {
      table = (Table)getLastNonConfigurationInstance();
    }

*此方法已弃用,但我的测试版手机没有任何问题。

*这仅适用于您的应用已被手机操作系统关闭而非手动关闭的情况。许多用户将按下后退按钮,不知道它关闭应用程序,而家庭最小化。下面的文章有许多方法可以避免这种情况。

http://www.androiduipatterns.com/2011/03/back-button-behavior.html