有时应用程序被销毁,我可能在单例中有一些临时值。 Android恢复我的活动,但不恢复我的单身人士。因此,我的解决方案是将单例保存在所有活动中,并在重新创建活动并且不再存在单例时恢复它。
这似乎不是一个好的解决方案,因为我经常拯救单身人士。应用程序没有和它在被销毁之前调用的功能,所以我也不能使用它。
在Android中安装一个可以保存到应用程序终端的单例是一个好习惯吗?
修改的
我的解决方案如下:
public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
Global.restore(savedInstanceState);
super.onCreate(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
Global.save(outState);
}
}
而且:
public class Global implements Parcelable {
public static final String KEY_BUNDLE = "GLOBAL";
private static Global INSTANCE = null;
public static synchronized Global get()
{
if (INSTANCE == null)
INSTANCE = new Global();
return INSTANCE;
}
public static synchronized void save(Bundle outState)
{
// save the singleton... not very effective, is happening on every's activity destroy
if (INSTANCE != null)
outState.putParcelable(KEY_BUNDLE, INSTANCE);
}
public static synchronized void restore(Bundle savedInstanceState)
{
// ONLY read it if it does not already exists
if (INSTANCE != null)
return;
if (savedInstanceState != null && savedInstanceState.containsKey(KEY_BUNDLE))
INSTANCE = savedInstanceState.getParcelable(KEY_BUNDLE);
}
// Data and Parcelable code...
// ......
}
答案 0 :(得分:0)
使用SharedPreferences保存数据。
http://developer.android.com/reference/android/content/SharedPreferences.html