我已经完成了游戏的大部分机制,现在我需要能够:
Save一切data当前活动和retrieve回来时(我希望有一个例子SharedPreferences
如果这就是我需要的)
开背相同Activity
I left from and在相同的time我离开的时候就是这样。
只是为了更清楚:我不想每次应用程序关闭甚至被杀死时都从我的主活动重新启动。
EDIT:
好的,我用过这个谷歌文章 https://developer.android.com/training/basics/activity-lifecycle/recreating.html为了保存我的活动并稍后重新创建它。
我的一项活动中的代码如下:
onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_selection);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
village = savedInstanceState.getString(VILLAGE);
seekBarProgress = savedInstanceState.getInt(PROGRESS);
} else {
// Probably initialize members with default values for a new instance
initializeVariables();
Bundle bundle = getIntent().getExtras();
village = bundle.getString(VILLAGE);
}
[...] // Other code skipped
}
onSaveInstanceState()
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putString(VILLAGE, village);
savedInstanceState.putInt(PROGRESS, seekBarProgress);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
因此,我创建了一个调度员活动 https://stackoverflow.com/a/2441745/6489557(现在是我的主要)当应用程序被杀死然后重新启动时,知道哪个是最后一个打开的要启动的活动。但是当我尝试这样做时,它应该打开(即)PlayerSelection
活动,我得到一个
java.lang.NullPointerException
因为它运行这部分代码
else {
// Probably initialize members with default values for a new instance
initializeVariables();
Bundle bundle = getIntent().getExtras();
village = bundle.getString(VILLAGE);
}
而不是以前的if
它运行的语句else
.
调度员
这是调度程序活动,它过滤应启动的活动:
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", MainActivity.class.getName()));
} catch(ClassNotFoundException ex) {
activityClass = MainActivity.class;
}
startActivity(new Intent(this, activityClass));
}
}
这是我发送到调度程序活动的内容:
@Override
protected void onPause() {
super.onPause();
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("lastActivity", getClass().getName());
editor.commit();
}
}
Question
为什么会发生这种情况?我可以做什么来解决这个问题?