I have an application that acts like a clapperboard, in which I use a variable i going to i++ every millisecond (I need milliseconds to display frames per second, and the chronometer updates only once per second), then I display it in the format HH:MM:SS:FF. I also have a quit button which goes by
if (item.getTitle() == "Quit") {
Process.killProcess(id);
}
The problem is that I want the app to remember the value of i when I press quit, so the timer would start at the same point it was before quitting it if I star开发者_如何学Ct it again. I tried
public void onSaveInstanceState(Bundle outState) {
outState.putLong(MILLISECONDS, i);
super.onSaveInstanceState(outState);
}
then calling it by
public void onStart(Bundle savedInstanceState) {
super.onStart();
i = savedInstanceState.getLong(MILLISECONDS);
}
and
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
i = savedInstanceState.getLong(MILLISECONDS);
}
but it doesn't work. Also if I go with
onCreate(Bundle savedInstanceState) {
...
i = savedInstanceState.getLong(MILLISECONDS);
...
}
the app force closes. Any idea of what I'm doing wrong, please? Thank you very much.
You are not really doing it the Android way :-) Don't kill your app, but go back to home. In that case, saveinstancestate will be called.
It would help if you added some more details to your question:
"It doesn't work" -> how exactly does it not work? Is savedInstanceState empty? Does it through an exception?
"the app force closes" -> can you provide the exact exception that is thrown, or the logcat text around the crash?
That being said, this section of documentation on saving persistant state might be helpful. There are two different times to save state, in onPause and in onSavedInstanceState. onPause is the more reliable one, because it is gauranteed to be called as part of the activity lifecycle.
If you save in onSaveInstanceState, you should recreate in onCreate. However, as Sebi pointed out, the way you are killing the application might be preventing onSaveInstanceState from being called at all.
If you want to end your activity, just call finish().
精彩评论