您可以使用 Activity 中的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 将保存当前教程页面和一个布尔值,表示用户尚未完成它。
当用户稍后再次启动应用程序时,它首先检查 onRestoreInstanceState 并检查字段“savedInstanceState”是否存在。如果没有,则继续执行 onCreate() 方法。然后应用程序从 init() 方法开始。
“YourActivity”可以替换为您的项目/应用程序的名称。
附加信息:您必须自己处理传递的数据。将它传递给一个单独的类来处理教程(fe 页面上的 getters/setters)。