2015-06-30 82 views
0

無法找出爲什麼onSaveInstanceState和onRestoreInstanceState不會輸出Logcat消息,當我單擊主頁按鈕時以及分別恢復應用程序時。onSaveInstanceState和onRestoreInstanceState

public class MainActivity extends ActionBarActivity { 

    int count = 0; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     count++; 
    } 

    @Override 
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { 
     super.onSaveInstanceState(outState, outPersistentState); 
     Log.d("TAG", count + " was restored"); 

    } 

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

回答

1

單擊主頁按鈕不足以殺死該應用程序。這只是暫停它。 onSave/onRestore僅在框架將要終止活動並在稍後恢復時調用。只是最小化它不會那樣做。

2

onSaveInstanceState()onRestoreInstanceState()在活動生命週期的特定時間被調用。

Activity lifecycle

正如你所看到的,對於onSaveInstanceState()被調用,該活動需要由操作系統被破壞。按主頁按鈕只會調用onPause()方法。

要調試onSaveInstanceState()方法,請在Android設備上進入Settings -> Developer options,並在Apps部分中選中Kill app back button旁邊的框。現在,長按後退按鈕應該殺死可見的應用程序,並通知您烤麪包。再次打開該應用程序將打電話onRestoreInstanceState()

如果該選項不存在您的設備上,或者如果您使用的是仿真器,請按照下列指示就如何立即銷燬活動,以測試onSaveInstanceState()onRestoreInstanceState()http://developer.android.com/tools/debugging/debugging-devtools.html

相關問題