我正在尝试测试onRestoreInstanceState方法以及何时(确切地)调用它。因此,我按照以下步骤操作:

  • 开始我的 Activity 。 onCreate -- > onStart --> onResume称为。
  • 按下模拟器上的“主页”按钮。 onPause --> onSaveInstanceState --> onStop称为。
  • 单击启动器中的图标,然后再次启动我的 Activity 。 onRestart --> onStart --> onResume称为。

  • 我的Java代码:
    package com.test.demostate.app;
    
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.util.Log;
    
    
     public class MainActivity extends ActionBarActivity {
       private int visiters=0;
    
       @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
           Log.d("TAG","onCreate");
    
       }
    
      @Override
       protected void onPause() {
          super.onPause();
           Log.d("TAG","onPause");
      }
    
      @Override
       protected void onStop() {
           super.onStop();
           Log.d("TAG","onStop");
       }
    
       @Override
       protected void onStart() {
           super.onStart();
           Log.d("TAG","onStart");
       }
    
       @Override
        protected void onRestart() {
           super.onRestart();
           Log.d("TAG","onRestart");
    
       }
    
        @Override
         protected void onResume() {
           super.onResume();
            visiters++;
            Log.d("TAG","onResume");
        }
    
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putInt("visiters",visiters);
            Log.d("TAG",visiters+" visiters  was saved ");
        }
    
        @Override
         protected void onRestoreInstanceState(Bundle savedInstanceState) {
             super.onRestoreInstanceState(savedInstanceState);
            visiters=savedInstanceState.getInt("visiters");
             Log.d("TAG",visiters+" visiters was restored");
        }
    
         @Override
        protected void onDestroy() {
            super.onDestroy();
            Log.d("TAG","onDestroy");
        }
    }
    

    从文档:Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method .
    因此,onRestoreInstanceState被称为

    Activity 被销毁后的
  • onPause --> onStop --> onDestroy然后是onCreate --> onRestoreInstanceState --> onResume(例如由于屏幕旋转)
  • 停止 Activity 后的
  • onPause --> onStop --> onRestart --> onStart --> onRestoreInstanceState --> onResume(例如,由于按下主页图标)

  • 但是为什么在onStart之后不调用它呢?

    谢谢

    最佳答案

    仅在onStart()被调用的情况下,在onSaveInstanceState()之后。

    从文档中:



    Activity#onRestoreInstanceState()

    关于android - 为什么在onStart之后不调用onRestoreInstanceState?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24130726/

    10-11 00:41