when to use?
- Activity의 간단한 UI정보를 저장할 때
- portrait <-> landscape (세로 <->가로) 모드 변경 시
ex) 화면 모드 전환 Activity Lifecycle
[소멸과정]
onPause() ->onSaveInstanceState() -> onStop() -> onDestroy()
[재생성 과정]
onCreate() -> onStart() ->onRestoreInstanceState(savedInstanceState : Bundle) -> onResume()
새로 액티비티를 생성하는데 이때 기존에 액티비티가 가지고 있던 정보가 사라짐.
(ex. EditText)
onSaveInstanceState (outState : Bundle)
outState : Bundle in which to place your saved state. This value can't be null
onRestoreInstanceState(savedInstanceState : Bundle)
when is it called? this method is called between onStatrt() and onPostCreate(Bundle)
Example
//outState – Bundle in which to place your saved state.
// user가 명시적으로 activity를 닫거나 finish()호출시 다음 메소드는 호출되지않음.
override fun onSaveInstanceState(outState: Bundle) {
// 입력했던것 저장
Log.i("State", "save Instance")
outState.putString("USER_NAME", user_name_input_editText.text.toString())
outState.putString("USER_PHONE", user_phone_number_editText.text.toString())
super.onSaveInstanceState(outState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
Log.i("State", "Restore Instance")
super.onRestoreInstanceState(savedInstanceState)
savedInstanceState?.run {
user_name_input_editText.setText(savedInstanceState.getString("USER_NAME"))
user_phone_number_editText.setText(savedInstanceState.getString("USER_PHONE"))
}
}
※ 뒤로가기 onBackPressed()같은 메소드 호출시 해당 Activity 객체는 메모리에서 해제되기 때문에
onSaveInstanceState를 해봤자 의미가 없다 .
∵ 다시 activity를 생성할 때는 새로운 activity 객체가 생성되기 때문이다.
[Reference]
https://developer.android.com/reference/android/app/Activity#onSaveInstanceState(android.os.Bundle)
'Android' 카테고리의 다른 글
[Android] Activity to Activity Data Pass (feat. Intent) (0) | 2020.07.06 |
---|---|
[Android] SharedPreference (0) | 2020.07.03 |
[Android] Service 2편 (Foreground) (0) | 2020.06.22 |
[Android] Service <-> Activity Communication (feat. Bind Service) (0) | 2020.06.21 |
[Android] Service (feat. Thread) (0) | 2020.06.20 |