我想在用户退出时保存活动状态,然后在下次同一屏幕再次启动。
我只是分别放置了一些教程,按一个难度按钮,你将被带到一个带有更多按钮和教程名称的屏幕。按任意一个,滚动视图中只有一些文本的活动将打开。
如何保存用户离开时的位置?
假设一个用户正在读一个啧啧,然后他/她需要离开,他按下并最终退出......但他们正处于啧啧中间。我希望他们能够继续他们离开的地方......怎么做?
我是从https://groups.google.com/forum/#!forum/android-developers
来到这里的它说我们可以在这里问初学者问题,但人们似乎宁愿花费宝贵的时间来表达自己的意思。是不是真的值得吗 ?如果你知道请帮助我。 (一个代码示例会很棒,但任何帮助都会受到赞赏)
答案 0 :(得分:3)
您可以使用活动中的onSaveInstanceState和onRestoreInstanceState。
public class YourActivity extends Activity {
private boolean tutorialUsed;
private int tutorialPage;
/** this will be called when you launch the app */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// place default field values here below if you have private variables - always at first
tutorialUsed = false;
tutorialPage = 1;
// your onCreate method/tasks (when you start this application)
init(); // see below *%* for details
}
/** this will be called when the app closes */
@Override
protected void onDestroy() {
super.onDestroy();
}
/** this will be called when you switch to other app (or leaves it without closing) */
@Override
protected void onPause() {
super.onPause();
// pauze tasks
}
/** this will be called when you returns back to this app after going into pause state */
@Override
protected void onResume() {
super.onResume();
// resume tasks
}
/** this starts when app closes, but BEFORE onDestroy() */
// please remember field "savedInstanceState", which will be stored in the memory after this method
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// save the tutorial page (or something else)
savedInstanceState.putInt("TutPage", tutorialPage);
savedInstanceState.putBoolean("tutUsed", tutorialUsed);
// more additions possible
}
/** this starts after onStart(). After this method, onCreate(Bundle b) gets invoked, followed by onPostCreate(Bundle b) method
* When this method has ended, the app starts skipping the onCreate and onPostCreate method and initiates then.
* -- *%* A best practice is to add an init() method which have all startup functions.
*/
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// restore state
tutorialPage = savedInstanceState.getInt("TutPage");
tutorialUsed = savedInstanceState.getBoolean("tutUsed");
init();
}
/** do your startup tasks here */
public void init() {
if(!tutorialUsed) {
showTutorial(tutorialPage);
}
}
因此,如果用户第一次启动应用程序,它将调用onCreate()方法。在那里,您已经初始化了教程页面。用户浏览了10个页面,但他停止并在第6页离开应用程序。那么,在那一刻,应用程序将调用onSaveInstanceState,它将保存当前的教程页面和一个表示用户没有完成的布尔值它。
当用户稍后再次启动应用程序时,它首先检查RestoreInstanceState并检查字段“savedInstanceState”是否存在。如果没有,它继续onCreate()方法。 然后应用程序以init()方法启动。
“YourActivity”可以替换为您的项目/应用程序名称。
其他信息:您必须自己对传递的数据执行某些操作。将它传递给一个单独的类来处理教程(fe页面上的getter / setters)。