나무 숲

Android / +Xamarin android 문서 보면서 기록한 Activity Lifecycle 본문

Career/모바일

Android / +Xamarin android 문서 보면서 기록한 Activity Lifecycle

wood.forest 2020. 8. 18. 10:24

  1. Active or Running – Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in Android, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive.
  2. Paused – When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in Android and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running Activity stable and responsive.
    → 디바이스 Sleep / Activity는 보이지만 다른 액티비티에 의해 일부 가려질 때
    리소스 관리 차원에서 지워질 순위2
  3. Stopped/Backgrounded – Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities.
    → 지워질순위 1
  4. Restarted – It is possible for an activity that is anywhere from paused to stopped in the lifecycle to be removed from memory by Android. If the user navigates back to the activity it must be restarted, restored to its previously saved state, and then displayed to the user.
    → Pause/Stopped에서 다시 시작할 수 있지만, 시작하면 이전 state를 restore해야한다

Activity 수명 주기에 대한 이해 | Android 개발자 | Android Developers

 

1. OnCreate

  • 항상 overridden
  • view 생성 및 initialize variable, binding static data ..

2. OnStart

  • Activity가 visible해지기 전에 수행해야 할것 있으면 override해서 하면됨

3. OnResume

  • Activity is ready to start interacting with the user
  • always call the superclass first base.OnResume()

4. OnPause

  • Called when the sys is about to put the activity into the background / activity becomes partly obscured
  • override to
    • Commit unsaved changes to persistent data
    • Destroy or clean up other objects consuming resources
    • Ramp down frame rates and pausing animations
    • Unregister external event handlers or notification handlers (i.e. those that are tied to a service). This must be done to prevent Activity memory leaks.
    • Likewise, if the Activity has displayed any dialogs or alerts, they must be cleaned up with the .Dismiss() method.
  • OnPause 이후, 액티비티가 foreground일 때 OnResume 되고 background로 가면 OnStop이다

5. OnStop

  • Activity가 사용자에게 보이지 않을때
    • A new activity is being started and is covering up this activity.
    • An existing activity is being brought to the foreground.
    • The activity is being destroyed.
  • 안드로이드 메모리가 없을때는 불리지 않을 수도 있다!
  • Activity가 없어지면 OnDestroy가 되고, 다시 불리면 OnRestart이다

6-1. OnDestroy (끝)

  • 메모리에서 완전히 지워지기 전 불린다
  • Extreme situation에서는 불리지 않을 수도 있다! (대부분의 클린업과 셧다운은 OnPauseOnStop에서 진행)
  • 보통 맄 될수있는 long running resource를 클린업하기 위해 사용된다

6-2. OnRestart

  • activity stop 후, start하기 전
  • 예시로는 홈버튼 눌렀다가 task manager에서 다시 불러올때
  • 특별히 뭐 하지는 않음, 필요한 리소스는 OnStart에서 초기화되어야함

Back와 Home 버튼 차이

  • Back: activity가 끝났다고 android에 알림 = activity가 destroy됨
  • Home: activity를 단순히 background로 보냄

Managing State Throughout the Lifecycle

  • activity가 stopped / destroyed일 때, can save the state(=Instance state) of the activity for later rehydration

3 options for storing instance state during the Activity lifecycle:

  1. Storing primitive values in a Dictionary known as a Bundle that Android will use to save state.
  2. Creating a custom class that will hold complex values such as bitmaps. Android will use this custom class to save state.
  3. Circumventing the configuration change lifecycle and assuming complete responsibility for maintaining state in the activity.

This guide covers the first two options.

1) Using Bundle State

  • key/value dic obj(=Bundle)에 instance state를 저장
  • OnCreate에서 recall
  • bitmap같은 복잡한 데이터는 X, string, int정도만..
  • OnSaveInstanceState activity가 destroy될때
    • Activity가 stopped될때(테스트했을땐 되기전) 불림
    • OnCreate에서는, bundle ≠ null일때 bundle.GetInt 하는식으로 사용
    • 디폴트 동작은 각 뷰 (엘레멘트)의 android:id값을 통해 transient data를 저장한다
  • OnRestoreInstanceState OnCreate 끝나고 불리며, state를 restore할 수 있는 또다른 기회
    • OnStart끝나고 불림
    • savedState.Get..
    • 대부분의 경우에서는 OnCreate에서 restore할 수 있으므로 굳이 override할 필요는 X
  • Limitation
    • 홈버튼 / 백버튼을 누를때는 OnSaveInstanceState가 안불린다!!!!!!
    • 이미지 등의 큰 obj는 안된다
    • bundle의 데이터가 serialize되므로 delay가 있을수 있다

2) Persisting complex data .. thrh configuration changes by overriding OnRetainNonConfigurationInstance

  • obj returned from here performs well with larger, more complex data 왜냐면 memory retains this obj

  • 필요할때만 불리고 캐시보다 경제적임

  • ex Web service call

    • ex 트위터 검색결과를 불러왔는데, 이걸 가로로 바꾸면 또 불러오면 낭비니까 이렇게

      public class NonConfigInstanceActivity : ListActivity
      {
      TweetListWrapper _savedInstance;
      
      protected override void OnCreate (Bundle bundle)
      {
        base.OnCreate (bundle);
      
        var tweetsWrapper = LastNonConfigurationInstance as TweetListWrapper;
      
        if (tweetsWrapper != null) {
          PopulateTweetList (tweetsWrapper.Tweets);
        } else {
          SearchTwitter ("xamarin");
        }
      
        public override Java.Lang.Object OnRetainNonConfigurationInstance ()
        {
          base.OnRetainNonConfigurationInstance ();
          return _savedInstance;
        }
      
        ...
      
        void PopulateTweetList (string[] results)
        {
          ListAdapter = new ArrayAdapter<string> (this, Resource.Layout.ItemView, results);
          _savedInstance = new TweetListWrapper{Tweets=results};
        }
      }
728x90
반응형
Comments