안드로이드 onRestart - andeuloideu onRestart

Before this, let me ask you what is the running order of onCreate(), onStart(), onResume(),

onPause in called 
onStop in called
onDestroy in called
0? And when can I override the
onPause in called 
onStop in called
onDestroy in called
1?

Many people get confused when and what method should they call when they start the Android development. This article is the quick guide give you an overview on this.

Two main Views in the Android, Activity and Fragment.

Activity

Here is a demo on the running order:

The output of first start up:

onCreate in called 
onStart in called
onResume in called

The output of go back to mobile home screen:

onPause in called 
onStop in called
onDestroy in called

The output of going back to app from background:

onCreate in called 
onStart in called
onResume in called
Fragment

The output of first start up:

running onCreateView 
running onViewCreated
running onActivityCreated
running onStart

The output of go back to mobile home screen:

running onPause 
running onStop
running onDestroyView
running onDestroy

The output of going back to app from background:

running onCreateView 
running onViewCreated
running onActivityCreated
running onStart

Update on Activity lifecycle methods:

onCreate(): This method will get called when the activity is created. Here we can have some initialisation work done here, such as load the layout xml file.

onPause in called 
onStop in called
onDestroy in called
3: The current Activity is being restarted, from invisible to visible.

onStart(): Activity is created but not visible yet.

onPause in called 
onStop in called
onDestroy in called
5 Activity is being stopping but still visible. Normally the
onPause in called 
onStop in called
onDestroy in called
6 will be called next to it.
onPause in called 
onStop in called
onDestroy in called
7 can't have too much heavy duty work, as new Activity's onResume() starts only when onPause() finished.

onResume(): Activity is visible, so users can interact with it.

onPause in called 
onStop in called
onDestroy in called
6: Activity is about to be destroyed. You can do some clean up work here, but not too heavy.

음 제목은 이렇게 지었지만, 4대 컴포넌트중 생명주기를 가지고 있는 컴포넌트는 크게 두가지밖에 없습니다.

오늘은, 그 Activity, Service, 그리고 Fragment 생명주기에 대해 다루어 보도록 하겠습니다.

1. Activity 생명주기

아래 엑티비티 생명주기 다이어그램을 참고하면서 이야기를 해보도록 합시다.

안드로이드 onRestart - andeuloideu onRestart
이미지 출처

일단, 다이어그램을 보면 알수있듯, Activity의 상태에 따라 함수들이 호출됩니다.

아래는 Activity의 상태에 따라 호출되는 함수들에 대해 정리했습니다.

onCreate()

  1. 최초로 Activity를 실행하면, 처음으로 호출되는 함수입니다.
  2. 초기화 관련 작업을 하면 좋습니다..

onStart()

  1. 최초로 Activity를 실행하면, onCreate() 다음으로 호출되는 함수입니다.
  2. onStop() -> onRestart() 다음으로 호출되는 함수이기도 합니다.
  3. 이 시점부터는 사용자가 액티비티를 볼 수 있습니다.

onResume()

  1. 최초로 Activity를 실행하면, onStart() 다음으로 호출되는 함수입니다.
  2. onPause() 다음으로 호출되는 함수이기도 합니다.
  3. 이 시점부터는 Activity가 활성화 된 상태(실행중인 상태)로 봅니다.

onPause()

  1. 만약 onResume()가 호출된 이후에(Activity가 활성화 된 이후에) 다른 Activity가 최상단에서 보여지는(포커스를 잃은) 경우 호출되는 함수입니다.
  2. 만약 onPause()가 호출된 이후에(다른 Activity가 최상단에서 보여진 이후에) 다시 기존 Activity로 돌아오는 경우 onResume()가 호출됩니다.
  3. 만약 다른 앱이 메모리를 필요로 할 경우 앱 프로세스가 종료될 수 있습니다.

onStop()

  1. 만약 onResume()가 호출된 이후에(Activity가 활성화 된 이후에) 다른 Activity가 최상단에서 보여지는(포커스를 잃은) 경우 + Activity가 완전히 보이지 않는경우 호출되는 함수입니다.
  2. 만약 onStop()이 호출된 이후에(다른 Activity가 최상단에서 보여진 이후에) 다시 기존 Activity로 돌아오는 경우 onStart()가 호출됩니다.
  3. 사용자에 의하거나(ex: onStop()1 호출), 시스템에 의해(ex: 자원부족) Activity가 완전히 종료되면 onStop()2 가 호출됩니다.
  4. 만약 다른 앱이 메모리를 필요로 할 경우 앱 프로세스가 종료될 수 있습니다.

onDestroy()

  1. Activity가 사용자에 의하거나 시스템에 의해 완전히 종료되는 경우 호출되는 함수
    1.1. 사용자에 의해 종료되는 경우는 onStop()1호출 , onStop()4등의 경우가 있습니다.
    (onBackPressed()호출 시, 기존 실행된 엑티비티가 onResume()까지 호출된 후 onStop()6가 호출됨.)
    1.2. 시스템에 의해 종료되는 경우는 대표적으로 자원부족 문제를 해결하기 위한(메모리 확보를 위한)경우가 있습니다.

onRestart()

  1. onStop()이 호출된 이후에(다른 Activity가 최상단에서 보여진 이후에) 다시 기존 Activity로 돌아오는 경우 호출되는 함수
  2. onRestart()가 호출된 이후 이어서 onStart()가 호출됨

2. Fragment 생명주기

앞서 4대 컴포넌트 포스팅에서 말씀드렸다시피, Fragment는
Activity의 특징 일부를 물려받은 독자적인 생명주기를 가지는 UI컴포넌트입니다.
그래서, Fragment의 생명주기는 Activity가 활성화 된 상태(실행중인 상태)에서 작동합니다.

그럼 Fragment의 생명주기 설명도 다이어그램으로 시작하겠습니다.

안드로이드 onRestart - andeuloideu onRestart
이미지 출처

onAttach()

  1. Activity에서 Fragment를 추가하면 호출됩니다.
  2. 인자로 context를 받아서 Listener interface를 implement한 경우 에 Context를 통해 가져올 수 있습니다. [1]

onCreate()

  1. onRestart()0다음으로 호출되는 함수입니다.
  2. 액티비티의 onCreate()와 역할이 비슷합니다.
  3. 단, UI에 관련된 작업(ex. View와 ViewGroup의 ui바인딩과 같은 작업들..)은 할 수 없습니다.
  4. 하지만, UI관련된 작업외, Int형..등등의 변수 초기화 등의 작업정도는 가능합니다.

onCreateView()

  1. onCreate()다음으로 호출되는 함수입니다.
  2. 지금부터, Fragment에 속한 UI관련된 작업을 할수 있는 단계입니다.

onActivityCreated()

  1. onCreate()다음으로 호출되는 함수입니다.
  2. Fragment가 backStack에서 돌아오면 호출되는 함수이기도 합니다.
  3. Activity에서 Fragment 생성이 완료되면 호출되는 함수입니다.

onStart()

  1. onRestart()4다음으로 호출되는 함수입니다.
  2. Activity와 마찬가지로 이 시점부터는 사용자가 액티비티를 볼 수 있습니다.

onResume()

  1. onStart() 다음으로 호출되는 함수입니다.
  2. Activity와 마찬가지로 이 시점부터는 Fragment가 활성화 된 상태(실행중인 상태)로 봅니다.

onPause()

  1. Fragment의 호스트 Activity가 포커스를 잃고 다른 Activity가 최상단에서 보여지는 경우 호출된다.
  2. 1번과 같은 경우, Fragment가 backStack으로 들어갑니다.

onStop()

  1. Fragment의 호스트 Activity가 포커스를 잃고 다른 Activity가 최상단에서 보여지는 경우 + Activity가 완전히 보이지 않는경우 호출됩니다.

onDestroyView()

  1. Fragment에 구현된 View가 제거되는 단계입니다.
  2. 이 메소드가 호출된 이후 Fragment가 BackStack에서 돌아오면 onRestart()6가 호출됩니다.

onDestroy()

onDetach()

  1. Fragment가 제거되고, Activity로부터 해제될때 호출됩니다.

Plus Alpha

1-1. Activity의 onCreate의 기능을 Fragment에서는 두가지로 분리했습니다.

1-2. 그리고, Activity의 onDestroy의 기능도 Fragment에서는 두가지로 분리했습니다.

  1. onDestroy()
  2. onDestroyView()

2. Fragment의 생명주기와 Activity의 생명주기는 이렇게 움직입니다.


Fragment Commit

Activity: onCreate()
Activity: Fragment1 commit()

Fragment1: onAttach()
Fragment1: onCreate()
Fragment1: onCreateView()
Fragment1: onActivityCreated()
Fragment1: onStart()

Activity: onStart()
Activity: onResume()
Fragment1: onResume()


New Fragment Commit

Activity: Fragment2 commit()
Fragment2: onAttach()
Fragment2: onCreate()

Fragment1: onPause()
Fragment1: onStop()
Fragment1: onDestroyView()
Fragment1: onDestroy()
Fragment1: onDetach()

Fragment2: onCreateView()
Fragment2: onActivityCreated()
Fragment2: onStart()
Fragment2: onResume()


onBackPressed called

Fragment2: onPause()

Activity: onPause()

Fragment2: onStop()

Activity: onStop()

Fragment2: onDestroyView()
Fragment2: onDestroy()
Fragment2: onDetach()

Activity: onDestroy()


직접 로그를 찍어본 결과입니다. 위 로그를 보고 꼭 결론을 도출해 보시기 바랍니다.

3. Service 생명주기

서비스는 아래의 두가지 case의 생명주기를 가집니다.
1. startService()를 통해 호출된 서비스
2. bindService()를 통해 호출된 서비스

그럼, Service의 생명주기 다이어그램으로 시작합니다.

안드로이드 onRestart - andeuloideu onRestart
이미지 출처

다이어그램을 보시다시피 Framgnet나 Activity의 생명주기와 비교했을 때 굉장히 단순한 모습입니다.

onRestart()7를 통해 호출된 서비스

서비스 스스로가 서비스를 종료하거나, 클라이언트가 onRestart()8를 호출하는 경우, 서비스는 소멸됩니다.

onRestart()9를 통해 호출된 서비스

서비스에 연결된 클라이언트가 모두 onStart()0된 상태면, 서비스는 소멸됩니다.


이렇게 4대 컴포넌트 중, 생명주기를 가지고 있는 컴포넌트인 Activity, Service와 Fragment의 생명주기에 대해서 다루어 보았습니다.

혹시, 내용에서 잘못된 내용이나 부족한 내용에 대해서는 댓글로 남겨주시면 보완해 나가도록 하겠습니다.

다음에는 안드로이드 ACC(Android Architecture Components)에 대해 알아보겠습니다.


[1] Listener interface를 implement 한 경우 : 일반적으로 Fragment에서 Activity에 있는 메소드 호출 시 사용하는 방법.