当调用onRestoreInstanceState时? (android kitkat)

时间:2014-06-09 22:05:06

标签: java android

为了看看是否调用onRestoreInstanceState,我已经制作了这个小java代码

package com.MCHAppy.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);

     }

     @Override
     protected void onResume() {
         super.onResume();
          visiters++;
         Log.d("Test","Resumed");
     }

     @Override
       protected void onSaveInstanceState(Bundle outState) {
           super.onSaveInstanceState(outState);
           outState.putInt("visiters",visiters);
           Log.d("Test",visiters+" visiters  was saved ");
       }

     @Override
     protected void onRestoreInstanceState(Bundle savedInstanceState) {
           super.onRestoreInstanceState(savedInstanceState);
           visiters=savedInstanceState.getInt("visiters");
           Log.d("Test",visiters+" visiters was restored");
     }
 }

当我点击主页图标时,我在Logcat中得到了这个图标

  06-09 17:09:58.240    1316-1316/com.MCHAppy.demostate.app D/MCHAppy﹕ 1 visiters  was saved

当我回到我的活动时,我在Logcat中得到了这个

06-09 17:58:13.230    1316-1316/com.MCHAppy.demostate.app D/MCHAppy﹕ Resumed

似乎从未调用onRestoreInstanceState。这真的是什么事吗?

由于

1 个答案:

答案 0 :(得分:0)

通过the documentation

  

当从之前保存的状态重新初始化活动时,在onStart()之后调用此方法,此处在savedInstanceState中给出。

这一点的关键部分是只在活动重新初始化时才会调用它。但是,同一个包总是在onCreate(Bundle savedInstanceState)中传递,因此您可以在那里移动逻辑。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        visiters=savedInstanceState.getInt("visiters");
    }
}