欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

两种保存状态的方法getSharedPreferences和onSaveInstanceState

程序员文章站 2022-04-20 09:03:18
...
虽然这些东西很简单有时候还真的让你搞混
@Override 
protected void onPause() {
super.onPause();

SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("lastActivity", getClass().getName());
editor.commit();
}

public class Dispatcher extends Activity { 

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Class<?> activityClass;

try {
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
activityClass = Class.forName(
prefs.getString("lastActivity", Activity1.class.getName()));
} catch(ClassNotFoundException ex) {
activityClass = Activity1.class;
}

startActivity(new Intent(this, activityClass));
}
}

上面的方法通常保存一个activity以便下次发动
2.
@Override 
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}

这个上次已经记过了用来旋转保存状态最好

对onSaveInstanceState的解释:
为了获取activity被杀死前的状态,你应该为activity实现onSaveInstanceState() 方法。Android在activity有可能被销毁之前(即onPause() 调用之前)会调用此方法。它会将一个以名称-值对方式记录了activity动态状态的Bundle 对象传递给该方法。当activity再次启动时,这个Bundle会传递给onCreate()方法和随着onStart()方法调用的onRestoreInstanceState(),所以它们两个都可以恢复捕获的状态。
与onPause()或先前讨论的其它方法不同,onSaveInstanceState() 和 onRestoreInstanceState() 并不是生命周期方法。它们并不是总会被调用。比如说,Android会在activity易于被系统销毁之前调用 onSaveInstanceState(),但用户动作(比如按下了BACK键)造成的销毁则不调用。在这种情况下,用户没打算再次回到这个activity,所以没有保存状态的必要。
因为onSaveInstanceState()不是总被调用,所以你应该只用它来为activity保存一些临时的状态,而不能用来保存持久性数据。而是应该用onPause()来达到这个目的。


Google为何这样设计OnSharedPreferenceChangeListener
[url]http://droidyue.com/blog/2014/11/29/why-onsharedpreferencechangelistener-was-not-called/[/url]
相关标签: Android UI