Android fundamentals 02.2:Activity lifecycle and state

0

Google Codelabs

목록 보기
4/14
post-thumbnail

Android fundamentals 02.2:Activity lifecycle and state

이 포스팅은 아래 구글 코드랩을 개인 학습용으로 정리한 글입니다.

1. Welcome

Introduction

  • activity lifecycle: the set of states an activity can be in during its entire lifetime
    -> from when it's created
    -> to when it's destroyed and the system reclaims its resources

  • Each stage in an activity's lifecycle has a corresponding callback method:
    onCreate(), onStart(), onPause(), ...

  • When an activity changes state, the associated callback method is invoked.

  • The activity state can also change in response to device-configuration changes
    -> ex. when the user rotates the device from portrait to landscape

  • when configuration changes happen,
    -> the activity is destroyed and recreated in its default state
    -> the user might lose information that they've entered in the activity.

2. App overview

3. Task 1: Add lifecycle callbacks to TwoActivities

1.1 (Optional) Copy the TwoActivities project

1.2 Implement callbacks into MainActivity

1.3 Implement lifecycle callbacks in SecondActivity

1.4 Observe the log as the app runs

4. Task 2: Save and restore the Activity instance state

  • The state of each Activity is stored as a set of key/value pairs
    -> in a Bundle object called the Activity instance state

  • The system saves default state information to instance state Bundle just before the Activity is stopped
    -> passes that Bundle to the new Activity instance to restore

  • the onSaveInstanceState() method

  • The system calls this method on your Activity
    -> between onPause() and onStop()
    -> when there is a possibility the Activity may be destroyed and recreated.

  • The data you save in the instance state is specific to only this instance of this specific Activity during the current app session

  • When you stop and restart a new app session
    -> the Activity instance state is lost
    -> the Activity reverts to its default appearance

  • If you need to save user data between app sessions
    -> use shared preferences or a database

2.1 Save the Activity instance state with onSaveInstanceState()

  • In each Activity, any text you typed into EditText elements is retained even when the device is rotated
    -> the state information of some of the View elements in your layout are automatically saved across configuration changes

  • So the only Activity state you're interested in are the TextView elements for the reply header and the reply text in the main Activity
    -> Both TextView elements are invisible by default

➕ 화면 회전으로 구성 변경되면 main activity는 destroyed and recreated
-> main activity 상태 디폴트로 돌아감
-> reply header, reply text 가시성 디폴트인 invisible로 돌아감

  • In this task, you add code to preserve the instance state of these two TextView elements using onSaveInstanceState().

  1. Add this skeleton implementation of onSaveInstanceState() to the Activity, or use Code > Override Methods to insert a skeleton override.
@Override
public void onSaveInstanceState(Bundle outState) {
          super.onSaveInstanceState(outState);
}

➕ In Kotlin:

override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
}

MainActivity.kt

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)

    if (mReplyHeadTextView.visibility == View.VISIBLE) {
        outState.putBoolean("reply_visible", true)
        outState.putString("reply_text",mReplyTextView.text.toString());
    }
 }

2.2 Restore the Activity instance state in onCreate()

  • Once you've saved the Activity instance state
    -> you also need to restore it when the Activity is recreated

  • You can do this either in onCreate()
    or by implementing the onRestoreInstanceState() callback(called after onStart() after the Activity is created)

  • Most of the time the better place to restore the Activity state is in onCreate()
    -> ensure that the UI(including the state) is available as soon as possible.

  • It is sometimes convenient to do it in onRestoreInstanceState()
    -> after all of the initialization has been done
    -> allow subclasses to decide whether to use your default implementation.

  1. In the onCreate() method, after the View variables are initialized with findViewById()
    -> add a test to make sure that savedInstanceState is not null
// Restore the state.
if (savedInstanceState != null) {
}
  • When your Activity is created
    -> the system passes the state Bundle to onCreate() as its only argument

  • The first time onCreate() is called
    -> the Bundle is null
    -> there's no existing state the first time your app starts.

  • Subsequent calls to onCreate()
    -> have a bundle populated with the data you stored in onSaveInstanceState().

MainActivity.kt

  override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Log.d(TAG, "-------");
        Log.d(TAG, "onCreate");

        mMessageEditText = findViewById(R.id.editText_main)

        mReplyHeadTextView = findViewById(R.id.text_header_reply)
        mReplyTextView = findViewById(R.id.text_message_reply)

        if(savedInstanceState != null){
            val isVisible : Boolean = savedInstanceState.getBoolean("reply_visible")
            if(isVisible){
                mReplyHeadTextView.visibility = View.VISIBLE
                mReplyTextView.visibility = View.VISIBLE
                mReplyTextView.text = savedInstanceState.getString("reply_text")
            }
        }
    }

5. Coding challenge

profile
Be able to be vulnerable, in search of truth

0개의 댓글