ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Understand the Activity Lifecycle
    Android 공식문서 2020. 10. 16. 17:23
    반응형

    As a user navigates through, out of, and back to your app, the Activity instances in your app transition through different states in their lifecycle. The Activity class provides a number of callbacks that allow the activity to know that a state has changed: that the system is creating, stopping, or resuming an activity, or destroying the process in which the activity resides.

    사용자가 앱을 탐색하고, 그리고 앱에서 나갔다가 다시 돌아오면 앱의 activity 인스턴스는 생명주기의 여러 다른 상태를 통해 전환 됩니다.
    activity 클래스는 상태가 변했다는걸 activity에게 알려주는 다수의 콜백을 제공합니다.
    (activity를 생성, 중지, 재개,파괴)

    Within the lifecycle callback methods, you can declare how your activity behaves when the user leaves and re-enters the activity. For example, if you're building a streaming video player, you might pause the video and terminate the network connection when the user switches to another app. When the user returns, you can reconnect to the network and allow the user to resume the video from the same spot. In other words, each callback allows you to perform specific work that's appropriate to a given change of state. Doing the right work at the right time and handling transitions properly make your app more robust and performant. For example, good implementation of the lifecycle callbacks can help ensure that your app avoids:

    생명주기 콜백 메서드 내에서 사용자가 activity를 떠났다가 다시 들어왔을 때 어떻게 작동하는지 알 수 있습니다.
    예를 들어, 스트리밍 비디오 플레이어를 만드는 경우 사용자가 다른 앱으로 전환 할 때 비디오를 일시 중지하고 네트워크 연결을 중지 시킬 수 있습니다. 사용자가 다시 돌아오면, 네트워크를 재연결 하고 같은 재생지점의 비디오를 다시 볼수 있게 할 수 있습니다.
    다시 말해, 각각 콜백은 주어진 상태 변경에 적합한 특정 작업을 수행 할 수 있습니다.
    맞는 시간에 맞는 작업을 수행하고 전환하는것을 적절히 처지하면 앱은 강력하고 성능이 향상됩니다.
    예를 들어, 생명주기 콜백을 잘 구현하면 다음과 같은 내용을 방지 할 수 있습니다.
    • Crashing if the user receives a phone call or switches to another app while using your app.
    • Consuming valuable system resources when the user is not actively using it.
    • Losing the user's progress if they leave your app and return to it at a later time.
    • Crashing or losing the user's progress when the screen rotates between landscape and portrait orientation.
    1. 사용자가 앱을 사용하는 동안 전화를 받거나 다른 앱으로 전환하면 충돌이 발생합니다.
    2. 사용자가 적극적으로 사용하지 않을 때 소중한 시스템 리소스를 소비합니다.
    3. 사용자가 앱을 떠나 나중에 다시 돌아 오면 사용자의 진행 상황이 손실됩니다.
    4. 화면을 회전 할 때 사용자의 진행 상황이 충돌하거나 손실됩니다.

    This document explains the activity lifecycle in detail. The document begins by describing the lifecycle paradigm. Next, it explains each of the callbacks: what happens internally while they execute, and what you should implement during them. It then briefly introduces the relationship between activity state and a process’s vulnerability to being killed by the system. Last, it discusses several topics related to transitions between activity states.

    이 문서는 activity 생명주기를 상세하게 설명합니다.
    생명주기 패러다임을 설명하는 것으로 시작합니다.
    그다음, 각각의 콜백을 설명합니다. : 실행하는 동안 내부적으로 발생하는 작업, 구현해야하는 작업.
    그 다음 activity 상태와 시스템에 의해 종료되는 프로세스의 취약성 간의 관계를 간략하게 소개합니다.
    마지막으로, activity 상태 간의 전환과 관련된 몇 가지 주제를 설명합니다.

    For information about handling lifecycles, including guidance about best practices, see Handling Lifecycles with Lifecycle-Aware Components and Saving UI States. To learn how to architect a robust, production-quality app using activities in combination with architecture components, see Guide to App Architecture.

    모범 사례에 대한 지침을 포함하여 생명주기 처리에 대한 자세한 내용은 Handling Lifecycles with Lifecycle-Aware Components 그리고 Saving UI States을 참조하십시오.
    아키텍처 구성 요소와 함께 activity를 사용하여 프로덕션 품질의 앱을 설계하는 방법을 알아 보려면 Guide to App Architecture를 참조하세요.

    Activity-lifecycle concepts

    To navigate transitions between stages of the activity lifecycle, the Activity class provides a core set of six callbacks: onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(). The system invokes each of these callbacks as an activity enters a new state.

    activity 생명주기의 단계 간 전환을 탐색하기 위해 activity 클래스는 6개의 콜백의 핵심 단계를 제공합니다.
    -> onCreate(), onStart(), onResume(), onPause(), onStop(), 그리고 onDestroy().
    시스템은 activity가 새로운 상태에 들어갈 때 각각의 콜백을 호출합니다.

    Figure 1.   A simplified illustration of the activity lifecycle.

    Figure 1 presents a visual representation of this paradigm.

     

    As the user begins to leave the activity, the system calls methods to dismantle the activity. In some cases, this dismantlement is only partial; the activity still resides in memory (such as when the user switches to another app), and can still come back to the foreground. If the user returns to that activity, the activity resumes from where the user left off. With a few exceptions, apps are restricted from starting activities when running in the background.

    사용자가 activity를 떠나기 시작하면 시스템은 activity를 해제하는 메소드를 호출합니다.
    이 해제는 부분적일 뿐입니다. activity는 아직 메모리에 있고(예 :사용자가 다른 앱으로 전환 할 때) 다시 포 그라운드로 돌아갈 수 있습니다.
    사용자가 activity로 다시 돌아가면 중단 했던 지점부터 다시 시작됩니다.
    몇 가지 예외를 제외하고 앱은 백그라운드에서 실행될 때 activity 실행이 제한됩니다.

    The system’s likelihood of killing a given process—along with the activities in it—depends on the state of the activity at the time. Activity state and ejection from memory provides more information on the relationship between state and vulnerability to ejection.

    시스템의 activity와 함께 특정 프로세스를 종료 할 가능성은 당시 activity의 상태에 따라 다릅니다.
    activity 상태와 메모리에서 제거하는 것은 제거하는 것에 대한 상태와 취약성 간의 관계에 대한 자세한 정보를 제공합니다.

    Depending on the complexity of your activity, you probably don't need to implement all the lifecycle methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect.

    activity의 복잡성에 따라, 모든 생명주기를 구현할 필요는 없습니다.
    하지만 하나 하나 이해하는 것과 앱이 사용자가 기대하는 방식으로 작동하도록 구현하는 것은 중요합니다.

    The next section of this document provides detail on the callbacks that you use to handle transitions between states.

    다음 섹션은 콜백을 상태 변화에 따른 처리하는 방법을 자세하게 제공합니다.

    Lifecycle callbacks

    This section provides conceptual and implementation information about the callback methods used during the activity lifecycle.

    이 섹션에서는 activity 생명주기 동안 새용되는 콜백 메서드에 대한 개념 및 구현 정보를 제공합니다.

    Some actions, such as calling setContentView(), belong in the activity lifecycle methods themselves. However, the code implementing the actions of a dependent component should be placed in the component itself. To achieve this, you must make the dependent component lifecycle-aware. See Handling Lifecycles with Lifecycle-Aware Components to learn how to make your dependent components lifecycle-aware.

    setContentView() 같은 몇몇 actions은 activity 생명주기 메서드 자체에 있습니다.
    하지만, 종속 구성 요소의 작업을 구현하는 코드는 구용 요소 자체에 배치되어야 합니다.
    이를 위해서는 종속 구성 요소의 생명주기를 인식해야합니다.
    종속 구성 요소의 생명주기를 인식하는 방법을 알아 보려면 Handling Lifecycles with Lifecycle-Aware Components를 참조하세요.

    onCreate()

    You must implement this callback, which fires when the system first creates the activity. On activity creation, the activity enters the Created state. In the onCreate() method, you perform basic application startup logic that should happen only once for the entire life of the activity. For example, your implementation of onCreate() might bind data to lists, associate the activity with a ViewModel, and instantiate some class-scope variables. This method receives the parameter savedInstanceState, which is a Bundle object containing the activity's previously saved state. If the activity has never existed before, the value of the Bundle object is null.

    시스템이 activity를 처음 구현 할 때 이 콜백을 반드시 구현해야 합니다.
    activity를 생성시에, activity는 Created 상태에 들어갑니다.
    onCreate() 메서드에서 activity 생명 주기 전체중 단 한번만 실행 시켜야하는 기본 앱 startup logic을 수행합니다.
    예를 들어, data를 목록에 바인딩하고, activity를 VIewModel과 연결 시키고, 일부 클래스 범위 변수를 인스턴스화 할 수 있습니다.
    이 메서드는 activity의 이전에 저장된 상태를 포함하는 Bundle 객체인 savedInstanceState 매개 변수를 받습니다.
    만약 activity가 이전에 존재하지 않았다면 Bundle 개체의 값은 null입니다.

    If you have a lifecycle-aware component that is hooked up to the lifecycle of your activity it will receive the ON_CREATE event. The method annotated with @OnLifecycleEvent will be called so your lifecycle-aware component can perform any setup code it needs for the created state.

    activity의 생명주기에 연결된 lifecycle-aware component가 있는 경우 ON_CREATE 이벤트를 수신합니다.
    @OnLifecycleEvent라는 어노테이션이 달린 메서드가 호출되어 lifecycle-aware component가 생성 된 상태에 필요한 설정 코드를 수행 할 수 있습니다.

    The following example of the onCreate() method shows fundamental setup for the activity, such as declaring the user interface (defined in an XML layout file), defining member variables, and configuring some of the UI. In this example, the XML layout file is specified by passing file’s resource ID R.layout.main_activity to setContentView().

    onCreate () 메서드의 다음 예제는 사용자 인터페이스 선언 (XML 레이아웃 파일에 정의), 멤버 변수 정의 및 일부 UI 구성과 같은 activity의 기본 설정을 보여줍니다.
    XML 레이아웃 파일은 파일의 리소스 ID인 R.layout.main_activity를 setContentView()에 전달하여 지정됩니다.
    lateinit var textView : TextView
    
    // activity 인스턴스의 일시적인 상태
    var gameState : String? = null
    
    override fun onCreate(savedInstanceState : Bundle?) {
        // 슈퍼 클래스를 호출하여 activty 생성을 완료
    	super.onCreate(savedInstanceState)
        // 인스턴스 상태 복구
        gameState = savedInstanceState?.getString(GAME_STATE_KEY)
        // activity에 대한 레이아웃 설정
        setContentVIew(R.layout.main_activty)
        // 변수 초기화
        textView = findViewById(R.id.text_view)
    }
    
    override fun onRestoreInstanceState(savedInstanceState : Bundle?){
    	textView.text = savedInstanceState?.getString(TEXT_VIEW_KEY)
    }
    // 이 콜백은 다음과 같이 사용하여 저장 한 인스턴스가 있는경우에만 호출합니다.
    // onCreate ()에서 일부 상태를 복원하는 반면, 
    // 여기에서 선택적으로 다른 상태를 복원 할 수 있습니다. 
    // onStart ()가 완료된 후에 사용할 수 있습니다.
    override fun onSaveInstanceState(outState : Bundle?){
    	outState?.run {
        	putString(GAME_STATE_KEY, gameState)
            putString(TEXT_VIEW_KEY, textView.text.toString())
        }
       //activity가 일시적으로 소멸 될 때 호출됩니다. 여기에 인스턴스 상태를 저장하십시오.
        super.onaSaveInstanceState(outState)
    }

    As an alternative to defining the XML file and passing it to setContentView(), you can create new View objects in your activity code and build a view hierarchy by inserting new Views into a ViewGroup. You then use that layout by passing the root ViewGroup to setContentView(). For more information about creating a user interface, see the User Interface documentation.

    XML 파일을 정의하고 setContentView()에 전달하는 대신 activity code에 새 VIew 개체를 만들고 ViewGroup에 새 view를 삽입하여 view 계층 구조를 만들 수 있습니다.
    그 다음 root ViewGroup을 setContentVIew()에 전달하여 해당 레이아웃을 사용합니다.
    사용자 인터페이스 생성에 대한 자세한 내용은 User Inteface를 참조하십시오.

    Your activity does not reside in the Created state. After the onCreate() method finishes execution, the activity enters the Started state, and the system calls the onStart() and onResume() methods in quick succession. The next section explains the onStart() callback.

    activity가 Created 상태가 아니게 됩니다. onCreate() 메서드가 실행을 마친후에, activity는 onStart와onResum을 호출하여Started 상태에 들어갑니다.
    다음 섹선은 onStart 콜백을 설명합니다.

    onStart()

    When the activity enters the Started state, the system invokes this callback. The onStart() call makes the activity visible to the user, as the app prepares for the activity to enter the foreground and become interactive. For example, this method is where the app initializes the code that maintains the UI.

    activity가 Started 상태에 들어갔을때 시스템이 이 콜백을 호출합니다.
    onStart() 호출은 activity가 사용자에게 보이게 만들고, activity가 포 그라운드로 들어가 상호 작용 할 수 있도록 준비 합니다.
    예를 들어, 이 메서드는 앱이 UI를 유지하는 코드를 초기화하는 곳입니다.

    When the activity moves to the started state, any lifecycle-aware component tied to the activity's lifecycle will receive the ON_START event.

    activity가 started state로 이동했을때, 생명주기에 연결된 모든 lifecycle-aware component는 ON_START 이벤트를 수신합니다.

    The onStart() method completes very quickly and, as with the Created state, the activity does not stay resident in the Started state. Once this callback finishes, the activity enters the Resumed state, and the system invokes the onResume() method.

    onStart() 메서드는 매우 빠르게 완료됩니다 그리고 Created 상태와 마찬가지로 활동이 Started 상태로 유지되지 않습니다.
    콜백이 완료되면 activity는 Resumed 상태가 되고 시스템은 onResume()을 호출합니다.

    onResume()

    When the activity enters the Resumed state, it comes to the foreground, and then the system invokes the onResume() callback. This is the state in which the app interacts with the user. The app stays in this state until something happens to take focus away from the app. Such an event might be, for instance, receiving a phone call, the user’s navigating to another activity, or the device screen’s turning off.

    activity가 Resumed 상태로 들어갈때, 포 그라운드로 오면 시스템이 onResume() 콜백을 호출합니다.
    앱이 사용자와 상호 작용이 가능한 상태 입니다.
    앱이 focus를 잃기 전까지 앱은 계속 이 상태에 머물러 있습니다.
    예를 들어 전화를 받거나 사용자가 다른 activity로 이동하거나 기기 화면이 꺼지는 등의 이벤트가 있을 수 있습니다.

    When the activity moves to the resumed state, any lifecycle-aware component tied to the activity's lifecycle will receive the ON_RESUME event. This is where the lifecycle components can enable any functionality that needs to run while the component is visible and in the foreground, such as starting a camera preview.

    activity가 resumed 상태로 이동할때, 생명주기에 연결된 모든 lifecycle-aware component들은 ON_RESUME 이벤트를 수신 받습니다.
    생명주기 요소는 요소가 표시되고 포 그라운드에서 실행되어야하는 모든 기능(예: 카메라 미리보기)을 활성화 할 수 있습니다.

    When an interruptive event occurs, the activity enters the Paused state, and the system invokes the onPause() callback.

    중단 이벤트가 발생하면, activity는 Paused 상태에 들어갑니다 그리고 onPause()를 호출합니다.

    If the activity returns to the Resumed state from the Paused state, the system once again calls onResume() method. For this reason, you should implement onResume() to initialize components that you release during onPause(), and perform any other initializations that must occur each time the activity enters the Resumed state.

    activity가 Paused 상태에서 Resumed 상태로 돌아간다면, 시스템은 다시 onResume을 호출합니다.
    따라서 onPause()중에 해제 한 구성 요소를 초기화하고 activity가 Resumed 상태가 될 때마다 발생해야하는 다른 초기화를 수행하려면 onResume()을 구현해야합니다.

    Here is an example of a lifecycle-aware component that accesses the camera when the component receives the ON_RESUME event:

    다음 예제는 요소가 ON_RESUME 이벤트를 수신 할 때 카메라에 액세스하는 lifecycle-aware component의 예입니다.
    class CameraComponent : LifecycleObserver {
    
        ...
    
        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        fun initializeCamera() {
            if (camera == null) {
                getCamera()
            }
        }
    
        ...
    }

    The code above initializes the camera once the LifecycleObserver receives the ON_RESUME event. In multi-window mode, however, your activity may be fully visible even when it is in the Paused state. For example, when the user is in multi-window mode and taps the other window that does not contain your activity, your activity will move to the Paused state. If you want the camera active only when the app is Resumed (visible and active in the foreground), then initialize the camera after the ON_RESUME event demonstrated above. If you want to keep the camera active while the activity is Paused but visible (e.g. in multi-window mode) then you should instead initialize the camera after the ON_START event. Note, however, that having the camera active while your activity is Paused may deny access to the camera to another Resumed app in multi-window mode. Sometimes it may be necessary to keep the camera active while your activity is Paused, but it may actually degrade the overall user experience if you do. Think carefully about where in the lifecycle it is more appropriate to take control of shared system resources in the context of multi-window. To learn more about supporting multi-window mode, see Multi-Window Support.

    위의 코드는 LifecycleObserver가 ON_RESUME 이벤트를 수신하면 카메라를 초기화 합니다.
    하지만 multi-window mode에서는 activity가 Paused 상태인 경우에도 완전히 표시 될 수 있습니다.
    예를 들어, 사용자가 multi-window mode에 있고 activity가 포함되지 않은 다른 window를 탭하면 activity는 Paused 상태로 이동합니다.
    카메라를 앱이 Resumed일때 단 한번 활성화되도록 하려면(포 그라운드에서 표시 및 활성화) ON_RESUME 이벤트 후에 카메라를 초기화해야합니다.
    activity가 Paused 됐지만 보이는 동안 카메라를 활성 상태로 유지하려면(e.g : multi-window) ON_START 이벤트 후에 카메라를 초기화 해야합니다.
    하지만 activity가 Paused된 동안 카메라를 활성화 하면 multi-window에서 다른 Resumed된 앱에 대한 카메라 엑세스가 거부 될 수 있습니다.
    activity가 Paused된 동안에 카메라 활성화를 유지해야할 때도 있지만 실제로는 전체 UX가 저하 될 수 있습니다.
    생명주기에서 multi-window context에서 공유된 시스템 resources를 제어할 적정한 위치를 신중하게 생각하세요.
    multi-window에 대한 자세한 내용은 Multi-Window Support를 참조하세요.

    Regardless of which build-up event you choose to perform an initialization operation in, make sure to use the corresponding lifecycle event to release the resource. If you initialize something after the ON_START event, release or terminate it after the ON_STOP event. If you initialize after the ON_RESUME event, release after the ON_PAUSE event.

    초기화 작업을 수행하기 위해 선택한 빌드업 이벤트에 상관없이 해당 생명주기 이벤트를 사용하여 리소스를 해제해야합니다.
    ON_START 이벤트 후에 초기화하면 ON_STOP이벤트 후에 해제하거나 종료합니다.
    ON_RESUME 이벤트 후에 초기화하면 ON_PAUSE 후에 합니다.

    Note, the code snippet above places camera initialization code in a lifecycle aware component. You can instead put this code directly into the activity lifecycle callbacks such as onStart() and onStop() but this isn't recommended. Adding this logic into an independent, lifecycle-aware component allows you to reuse the component across multiple activities without having to duplicate code. See Handling Lifecycles with Lifecycle-Aware Components to learn how to create a lifecycle-aware component.

    위의 code snippet은 lifecycle aware component에 카메라 초기화 코드를 배치합니다.
    이 코드를 onStart() 또는 onStop()과 같은 생명주기 콜백에 직접 넣을 수 있지만 권장하지 않습니다.
    이 로직을 독립적인 lifecycle-aware component에 추가하면 코드를 복제하지 않고도 여러 activity에서 구성 요소를 재사용 할 수 있습니다.
    lifecycle-aware component를 만드는 방법을 알아보려면 Handling Lifecycles with Lifecycle-Aware Components를 참조하세요.

    onPause()

    The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed); it indicates that the activity is no longer in the foreground (though it may still be visible if the user is in multi-window mode). Use the onPause() method to pause or adjust operations that should not continue (or should continue in moderation) while the Activity is in the Paused state, and that you expect to resume shortly. There are several reasons why an activity may enter this state. For example:

    시스템은 사용자가 activity를 떠나는 첫번째 신호로 onPause()를 호출합니다.(항상 activity가 파괴된다는 뜻이 아닙니다.)
    activity가 더 이상 포 그라운드에 있지 않음을 나타냅니다.
    (사용자가 multi-window mode일 경우 여전히 표시 될 수 있습니다.)
    onPause() 메서드를 사용하여 activity가 Paused 상태에 있고 곧 재개 될 것이라고 예상되는 동안 계속 실행해서는 안되는 작업을 일시 중지하거나 조정합니다.
    activity가 이러한 상태가 되는 데에는 몇 가지 이유가 있습니다.
    • Some event interrupts app execution, as described in the onResume() section. This is the most common case.
    • In Android 7.0 (API level 24) or higher, multiple apps run in multi-window mode. Because only one of the apps (windows) has focus at any time, the system pauses all of the other apps.
    • A new, semi-transparent activity (such as a dialog) opens. As long as the activity is still partially visible but not in focus, it remains paused.
    일부 이벤트는 app 실행을 중단합니다. 이것이 가장 일반적인 경우입니다.
    Android 7.0 ( API level 24) 이상에서는 여러 앱이 다중 창 모드로 실행됩니다.
    한 번에 하나의 포커스만 있기 때문에 시스템은 다른 모든 앱을 일시 중지 합니다.
    새로운 반투명 activity (예 : dialog)이 열립니다. activity는 부분적으로 표시되지만 초점이 맞지 않는 한 일시 중지 된 상태로 유지됩니다.

    When the activity moves to the paused state, any lifecycle-aware component tied to the activity's lifecycle will receive the ON_PAUSE event. This is where the lifecycle components can stop any functionality that does not need to run while the component is not in the foreground, such as stopping a camera preview.

    activity가 paused 상태가 되면, 연결된 모든 lifecycle-aware component들은 ON_PAUSE 이벤트를 수신합니다.
    lifecycle components가 카메라 미리보기 중지와 같은 component가 포그라운드에 있지 않는 동안에 실행할 필요가 없는 모든 기능을 중지 할 수 있습니다.

    You can also use the onPause() method to release system resources, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them. However, as mentioned above in the onResume() section, a Paused activity may still be fully visible if in multi-window mode. As such, you should consider using onStop() instead of onPause() to fully release or adjust UI-related resources and operations to better support multi-window mode.

    onPause()를 사용하여 시스템 리소스를 해제할 수도 있고, GPS와 같은 센서를 다룰 수 있고 또는 activity가 일시 중지 일때 배터리에 영향을 주고 사용자가 필요로 하지 않는 리소스를 해제 할 수 있습니다.
    하지만 multi-window mode에서는 일시 중지된 activity가 여전히 표시 될 수 있습니다.
    때문에, multi-window mode를 잘 지원하기 위해 UI 관련 리소스 나 작업을 완전히 해제하거나 조정하려면 onStop()를 사용하는 것이 좋습니다.

    The following example of a LifecycleObserver reacting to the ON_PAUSE event is the counterpart to the ON_RESUME event example above, releasing the camera that was initialized after the ON_RESUME event was received:

    다음 예제는 위의 ON_RESUME 이벤트 예제에 맞춰 ON_RESUME 이벤트가 수신 된 후 초기화 된 카메라를 해제 합니다.
    class CameraComponent : LifecycleObserver {
    
        ...
    
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        fun releaseCamera() {
            camera?.release()
            camera = null
        }
    
        ...
    }

    Note, the code snippet above places camera release code after the ON_PAUSE event is received by the LifecycleObserver. As previously mentioned, see Handling Lifecycles with Lifecycle-Aware Components to learn how to create a lifecycle-aware component.

    위의 코드 snippet은 ON_PAUSE 이벤트가 LifecycleObserver에서 수신 된 후 camera release 코드를 배치합니다.
    lifecycle-aware component를 만드는 법을 공부하려면 Handling Lifecycles with Lifecycle-Aware Components를 참고하세요.

    onPause() execution is very brief, and does not necessarily afford enough time to perform save operations. For this reason, you should not use onPause() to save application or user data, make network calls, or execute database transactions; such work may not complete before the method completes. Instead, you should perform heavy-load shutdown operations during onStop(). For more information about suitable operations to perform during onStop(), see onStop(). For more information about saving data, see Saving and restoring activity state.

    onPause() 실행은 매우 간단하고 저장 작업을 수행 할 시간이 충분하지 않습니다.
    이러한 이유로, onPause()를 app 또는 사용자 데이터를 저장하거나, 네트워크를 호출하거나, DB transactions를 실행하는데 사용하면 안됩니다. (작업이 완료되지 않을 수 있습니다.)
    대신에 onStop()중에 과부하가 걸리는 작업을 수행해야합니다.
    onStop() 동안 수행 할 적적한 작업에 대한 내용은 onStop()을 참조하세요, 데이터 저장에 대한 자세한 정보는 Saving and restoring activity state를 참조하세요.

    Completion of the onPause() method does not mean that the activity leaves the Paused state. Rather, the activity remains in this state until either the activity resumes or becomes completely invisible to the user. If the activity resumes, the system once again invokes the onResume() callback. If the activity returns from the Paused state to the Resumed state, the system keeps the Activity instance resident in memory, recalling that instance when the system invokes onResume(). In this scenario, you don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state. If the activity becomes completely invisible, the system calls onStop(). The next section discusses the onStop() callback.

    onPause()가 완료 된다고 Paused 상태를 떠난다는 의미가 아닙니다.
    사용자에게 완전히 표시되지 않거나 다시 재개되기 전까지 상태를 유지합니다.
    activity가 재개되면, 시스템은 다시 한 번 onResume()을 호출합니다.
    activity가 Paused 상태에서 Resumed 상태로 돌아가면, 시스템은 activity 인스턴스를 메모리에 유지시켜서 onResume()을 호출 할 때 해당 인스턴스를 호출합니다.
    이 시나리오에서는 Resumed 상태로 이어지는 콜백 메서드 중에 생성 된 요소를 다시 초기화할 필요가 없습니다.
    activity가 완전히 보이지 않는다면, 시스템은 onStop()을 호출합니다.
    다음 섹션에서는 onStop()을 설명합니다.

    onStop()

    When your activity is no longer visible to the user, it has entered the Stopped state, and the system invokes the onStop() callback. This may occur, for example, when a newly launched activity covers the entire screen. The system may also call onStop() when the activity has finished running, and is about to be terminated.

    사용자에게 activity가 더이상 보이지 않을때, Stopped 상태에 들어갑니다 그리고 시스템은 onStop()을 호출합니다.
    예를 들어 새로 시작된 activity가 전체 화면을 덮을 때 발생 할 수 있습니다.
    시스템은 activity 실행이 완료된 다음 종료 될때 onStop()을 호출 할 수도 있습니다.

    When the activity moves to the stopped state, any lifecycle-aware component tied to the activity's lifecycle will receive the ON_STOP event. This is where the lifecycle components can stop any functionality that does not need to run while the component is not visible on the screen.

    activity가 stopped 상태로 이동했을 때, activity의 생명주기에 연결된 모든 lifecycle-aware component들은 ON_STOP 이벤트를 수신 받습니다.
    여기에서 화면에 표시되지 않는 동안 실행할 필요가 없는 모든 기능을 중지 시킬 수 있습니다.

    In the onStop() method, the app should release or adjust resources that are not needed while the app is not visible to the user. For example, your app might pause animations or switch from fine-grained to coarse-grained location updates. Using onStop() instead of onPause() ensures that UI-related work continues, even when the user is viewing your activity in multi-window mode.

    onStop() 안에서, 앱은 사용자에게 앱이 보이지 않는 동안에 필요없는 리소스를 조정하거나 해제 해야합니다.
    예를 들어, 애니메이션을 일시 중지하거나 세분화 된 위치 업데이트에서 대략적인 위치 업데이트로 전환 할 수 있습니다.
    onPause() 대신에 onStop()을 사용하면 사용자가 multi-window mode를 사용할 때 UI 관련 작업이 계속됩니다.

    You should also use onStop() to perform relatively CPU-intensive shutdown operations. For example, if you can't find a more opportune time to save information to a database, you might do so during onStop(). The following example shows an implementation of onStop() that saves the contents of a draft note to persistent storage:

    상대적으로 CPU 집약적인 종료 작업을 수행하려면 onStop()을 사용해야 합니다.
    예를 들어, 데이터베이스에 정보를 저장하기 위한 적절한 시간을 더 찾을 수 없다면, onStop 동안에 할 수 있습니다.
    다음 예제는 초안 메모의 내용을 persistent 저장소에 저장하는 onStop() 구현을 보여줍니다.
    override fun onStop() {
        // 수퍼 클래스 메서드를 먼저 호출하세요.
        super.onStop()
    
        // activity가 중지되므로 메모의 현재 초안을 저장합니다.
        // 그리고 현재 노트 진행 상황이 손실 되지 않았는지 확인 하고 싶습니다.
        val values = ContentValues().apply {
            put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText())
            put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle())
        }
    
        // AsyncQueryHandler 나 동등한 background에 업데이트를 수행하세요
        asyncQueryHandler.startUpdate(
                token,     // int token to correlate calls
                null,      // cookie, not used here
                uri,       // The URI for the note to update.
                values,    // The map of column names and new values to apply to them.
                null,      // No SELECT criteria are used.
                null       // No WHERE columns are used.
        )
    }

    Note, the code sample above uses SQLite directly. You should instead use Room, a persistence library that provides an abstraction layer over SQLite. To learn more about the benefits of using Room, and how to implement Room in your app, see the Room Persistence Library guide.

    위의 코드 샘플은 SQLite를 직접 사용합니다.
    SQLite 대신에 SQLite를 통해 추상화 계층을 제공하는 Room 라이브러리를 사용해야 합니다.
    Room 사용의 장점과 앱에서 Room을 구현하는 방법을 알고 싶다면 Room Persistence Library를 참고하세요.

    When your activity enters the Stopped state, the Activity object is kept resident in memory: It maintains all state and member information, but is not attached to the window manager. When the activity resumes, the activity recalls this information. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state. The system also keeps track of the current state for each View object in the layout, so if the user entered text into an EditText widget, that content is retained so you don't need to save and restore it.

    activity가 Stopped 상태에 들어갈 때, Activity object는 메모리에 머무릅니다.
    모든 상태와 멤버 정보를 유지하지만 window manager에는 연결되지 않습니다.
    activity가 재개 되면, activity는 정보를 다시 호출 합니다.
    Resumed 상태로 이어지는 콜백 메서드 중에 생성 된 구성 요소를 다시 초기화 할 필요가 없습니다.
    시스템은 레이아웃 안에 있는 각 View object에 대한 현재 상태를 추적합니다.
    사용자가 EditText에 text를 입력한 경우 해당 context가 유지되므로 저장하고 복원 할 필요가 없습니다.

    Note: Once your activity is stopped, the system might destroy the process that contains the activity if the system needs to recover memory. Even if the system destroys the process while the activity is stopped, the system still retains the state of the View objects (such as text in an EditText widget) in a Bundle (a blob of key-value pairs) and restores them if the user navigates back to the activity. For more information about restoring an activity to which a user returns, see Saving and restoring activity state.

    activity가 중지되면 시스템이 메모리를 복구해야 하는 경우 활동이 포함 된 프로세스를 파괴 할 수 있습니다.
    activity가 중지 된 동안 시스팀이 프로세스를 파괴 하더라도,시스템은 bundle(키 - 값 쌍의 blob)에 View 개체의 상태를 유지하고 사용자가 activity로 다시 이동하면 복원합니다.

    From the Stopped state, the activity either comes back to interact with the user, or the activity is finished running and goes away. If the activity comes back, the system invokes onRestart(). If the Activity is finished running, the system calls onDestroy(). The next section explains the onDestroy() callback.

    stopped 상태에서 activity는 사용자와 상호 작용을 하기 위해 돌아 오거나 실행이 완료되고 사라집니다.
    activity가 다시 돌아오면 시스템은 onRestart()를 호출합니다.
    activity가 실행을 완료하면 onDestory()를 호출 합니다.

    onDestroy()

    onDestroy() is called before the activity is destroyed. The system invokes this callback either because:

    onDestory()는 activity가 파괴되기 전에 호출 됩니다.
    시스템은 다음과 같은 이유로 콜백을 호출합니다.
    1. the activity is finishing (due to the user completely dismissing the activity or due to finish() being called on the activity), or
    2. the system is temporarily destroying the activity due to a configuration change (such as device rotation or multi-window mode)
    1. activity가 종료 중이거나(사용자가 activity를 완전히 해제했거나 finish()를 호출 했기 떄문),
    2. configuration 변경을 위해 시스템이 일시적으로 activity을 파괴할 때(예 : 회전, window mode) 

    When the activity moves to the destroyed state, any lifecycle-aware component tied to the activity's lifecycle will receive the ON_DESTROY event. This is where the lifecycle components can clean up anything it needs to before the Activity is destroyed.

    activity가 destroyed 상태로 이동하면, 생명주기에 연관된 모든 lifecycle-aware component에 ON_DESTORY 이벤트를
    수신합니다.

    lifecycle component는 activity가 파괴되기 전에 필요한 모든 것을 정리할 수 있습니다.

    Instead of putting logic in your Activity to determine why it is being destroyed you should use a ViewModel object to contain the relevant view data for your Activity. If the Activity is going to be recreated due to a configuration change the ViewModel does not have to do anything since it will be preserved and given to the next Activity instance. If the Activity is not going to be recreated then the ViewModel will have the onCleared() method called where it can clean up any data it needs to before being destroyed.

    파괴되는 이유를 결정하기 위해 activity에 로직을 넣는 대신, activity에 대한 관련 View data를 포함하기 위한 ViewModel 개체를 사용해야합니다.
    configuration  변경 때문에 activity가 다시 생성되는 경우 ViewModel은 보존되고 다음 activity instance에 제공되므로
    아무것도 할 필요가 없습니다.

    activity가 다시 생성되지 않는다면 ViewModel은 파괴되기 전에 데이터를 정리할 수 있는 onCleared()를 호출 합니다.

    You can distinguish between these two scenarios with the isFinishing() method.

    isFinishing()을 사용하여 이 두 시나리오를 구분 할 수 있습니다.

    If the activity is finishing, onDestroy() is the final lifecycle callback the activity receives. If onDestroy() is called as the result of a configuration change, the system immediately creates a new activity instance and then calls onCreate() on that new instance in the new configuration.

    activity가 완료되면, onDestroy()가 activity가 수신하는 마지막 콜백입니다.
    configuration  변경의 결과로 onDestroy()가 호출되면, 시스템은 즉시 새로운 activity instance를 만들고 onCreate()를 새로운 configuration 안에 새로운 instance에서 호출 합니다.

    The onDestroy() callback should release all resources that have not yet been released by earlier callbacks such as onStop().

    onDestroy()는 onStop과 같은 이전 콜백에 의해 아직 해제되지 않은 모든 리소스를 해제해야합니다.

    Activity state and ejection from memory

    The system kills processes when it needs to free up RAM; the likelihood of the system killing a given process depends on the state of the process at the time. Process state, in turn, depends on the state of the activity running in the process. Table 1 shows the correlation among process state, activity state, and likelihood of the system’s killing the process.

    시스템은 RAM을 확보해야 할 때 프로세스를 종료합니다.
    시스템이 주어진 프로세스를 종료 할 가능성은 당시 프로세스의 상태에 따라서 다릅니다.
    프로세스 상태는 프로세스에서 실행중인 activity의 상태에 따라 달라집니다.
    표 1은 프로세스 상태, activity 상태 및 시스템이 프로세스를 종료할 가능성 사이의 상관 관계를 보여줍니다.
    Likelihood of being  killed Process state Activity state
    Least Foreground (having or about to get focus) Created
    Started
    Resumed
    More Background (lost focus) Paused
    Most

    Background (not visible)
    Stopped
    Empty Destroyed

    Table 1. Relationship between process lifecycle and activity state

     

    The system never kills an activity directly to free up memory. Instead, it kills the process in which the activity runs, destroying not only the activity but everything else running in the process, as well. To learn how to preserve and restore your activity's UI state when system-initiated process death occurs, see Saving and restoring activity state.

    시스템은 절대 메모리를 확보하기 위해 activity를 직접 종료하지 않습니다.
    그대신 activity가 실행되고 있는 프로세스를 종료합니다.
    그리고 프로세스에 실행중인 다른 모든 것도 파괴 합니다.

    A user can also kill a process by using the Application Manager under Settings to kill the corresponding app.

    For more information about processes in general, see Processes and Threads. For more information about how the lifecycle of a process is tied to the states of the activities in it, see the Process Lifecycle section of that page.

    사용자는 설정에서 application Manager를 사용하여 앱을 종료하여 프로세스를 종료 할 수도 있습니다.

    Saving and restoring transient UI state

    A user expects an activity’s UI state to remain the same throughout a configuration change, such as rotation or switching into multi-window mode. However, the system destroys the activity by default when such a configuration change occurs, wiping away any UI state stored in the activity instance. Similarly, a user expects UI state to remain the same if they temporarily switch away from your app to a different app and then come back to your app later. However, the system may destroy your application’s process while the user is away and your activity is stopped.

    사용자는 회전 이나 multi-window mode로 전환 같은 configuration 변경 동안에 activity의 UI 상태가 동일하게 유지되기를 기대합니다. 하지만 시스템은 configuration 변경이 발생하면 기본적으로 activity를 파괴 하여 activity 인스턴스에 저장된 모든 UI 상태를 지웁니다. 비슷하게, 사용자는 일시적으로 앱에서 다른 앱으로 전환한 다음 나중에 앱으로 돌아오는 경우 UI 상태가 동일하게 유지되기를 기대합니다.
    하지만,  시스템은 사용자가 떠나고 activity가 중지된 동안에 application의 프로세스를 파괴할 수 있습니다.

    When the activity is destroyed due to system constraints, you should preserve the user’s transient UI state using a combination of ViewModel, onSaveInstanceState(), and/or local storage. To learn more about user expectations versus system behavior, and how to best preserve complex UI state data across system-initiated activity and process death, see Saving UI State.

    시스템 제약으로 인해 activity가 삭제되면 ViewModel, onSaveInstanceState() 및 로컬 저장소의 조합을 사용하여 사요자의 임시 UI 상태를 유지해야합니다.

    This section outlines what instance state is and how to implement the onSaveInstance() method, which is a callback on the activity itself. If your UI data is simple and lightweight, such as a primitive data type or a simple object (like String), you can use onSaveInstanceState() alone to persist the UI state across both configuration changes and system-initiated process death. In most cases, though, you should use both ViewModel and onSaveInstanceState() (as outlined in Saving UI State) since onSaveInstanceState() incurs serialization/deserialization costs.

    이 섹션에서는 인스턴스 상태와 activity 자체 콜백인 onSaveInstance() 메서드를 구현 하는 방법에 대해 설명합니다.
    UI 데이터가 기본 데이터 유형 이나 단순 객체(예: String) 같이 단순하고 가벼운 경우에는 onSaveInstanceState() 만 사용하여 configuration 변경 및 시스템 시작 프로세스 종료시 UI 상태를 유지할 수 있습니다.
    그러나 대부분의 경우 onSaveInstanceState()는 직렬화 / 역 직렬화 비용을 발생 시키므로 ViewModel 과 onSaveInstanceState()를 모두 사용해야합니다.

    Instance state

    There are a few scenarios in which your activity is destroyed due to normal app behavior, such as when the user presses the Back button or your activity signals its own destruction by calling the finish() method. When your activity is destroyed because the user presses Back or the activity finishes itself, both the system's and the user's concept of that Activity instance is gone forever. In these scenarios, the user's expectation matches the system's behavior and you do not have any extra work to do.

    사용자가 뒤로가기 버튼을 누르거나 activity 가 finish()를 호출하여 자체적으로 파괴 신호를 보내는 경우등 정상적인 앱 동작으로 인해 activity가 파괴되는 몇 가지 시나리오가 있습니다.
    사용자가 뒤로가기 버튼을 누르거나 activity 자체적으로 종료되어 파괴되면 해당 activity 인스턴스에 대한 시스템과 사용자의 개념이 영원히 사라집니다.
    이러한 시나리오에서 사용자의 기대치는 시스템의 동작과 일치하며 수행 할 추가 작업이 없습니다.

    However, if the system destroys the activity due to system constraints (such as a configuration change or memory pressure), then although the actual Activity instance is gone, the system remembers that it existed. If the user attempts to navigate back to the activity, the system creates a new instance of that activity using a set of saved data that describes the state of the activity when it was destroyed.

    하지만, 시스템이 시스템 제약으로 인해(예: configuration 변경 또는 메모리 부족) activity를 파괴하는 경우 실제 activity 인스턴스가 없어지더라도 시스템은 존재했음을 기억합니다.
    사용자가 activity로 다시 이동하려고하면 시스템은 activity가 파괴 되었을 때 activity의 상태를 설명하는 저장된 데이터 세트를 사용하여 해당 activity의 새 인스턴스를 만듭니다.

    The saved data that the system uses to restore the previous state is called the instance state and is a collection of key-value pairs stored in a Bundle object. By default, the system uses the Bundle instance state to save information about each View object in your activity layout (such as the text value entered into an EditText widget). So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you'd like to restore, such as member variables that track the user's progress in the activity.

    시스템이 이전 상태를복원하는데 사용하는 저장된 데이터는 instance state 상태라고 불리고, Bundle 객체에 저장된 키-값 쌍의 모음입니다.
    기본적으로 시스템은 Bundle 인스턴스 상태를 사용하여 activity 레이아웃의 각 View 개체에 대한 정보(예: EdiText의 Text 값)를 저장합니다.
    activity 인스턴스가 파괴되고 재생성 되었을때 레이아웃의 상태가 코드없이 이전 상태로 복원이 됩니다.
    하지만, activity에는 activity에서 사용자의 진행 상황을 추적하는 멤버 변수와 같이 복원하려는 추가 상태 정보가 있을 수 있습니다.

    Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.

    시스템이 activity의 View 상태를 복원 하려면 android : id 속성에 id 값이 있어야 합니다.

    Bundle object isn't appropriate for preserving more than a trivial amount of data because it requires serialization on the main thread and consumes system-process memory. To preserve more than a very small amount of data, you should take a combined approach to preserving data, using persistent local storage, the onSaveInstanceState() method, and the ViewModel class, as outlined in Saving UI States.

    Bundle 객체는 메인 스레드에서 직렬화가 필요하고 시스템 프로세스 메모리를 사용하기 때문에 적정량 이상의 데이터를 보존하는 데 적합하지 않습니다.
    아주 적은 양의 데이터를 보존하려면 영구 로컬 저장소, onSaveInstanceState() 및 ViewModel 클래스를 사용하여 데이터를 보존하는 결합 된 접근 방식을 취해야합니다.

    Save simple, lightweight UI state using onSaveInstanceState()

    As your activity begins to stop, the system calls the onSaveInstanceState() method so your activity can save state information to an instance state bundle. The default implementation of this method saves transient information about the state of the activity's view hierarchy, such as the text in an EditText widget or the scroll position of a ListView widget.

    activity가 멈추기 시작하면, 시스템은 onSaveInstanceState() 메서드를 호출하여 activity가 상태 정보를 인스턴스 상태 bundle에 저장할 수 있도록 합니다.
    이 메서드의 기본 구현은 EditText의 텍스트, ListView의 스크롤 위치와 같은 activity의 View 계층 구조 상태에 대한 일시적인 정보를 저장합니다.

    To save additional instance state information for your activity, you must override onSaveInstanceState() and add key-value pairs to the Bundle object that is saved in the event that your activity is destroyed unexpectedly. If you override onSaveInstanceState(), you must call the superclass implementation if you want the default implementation to save the state of the view hierarchy. For example:

    activity의 추가적인 인스턴스 상태 정보를 저장하려면 onSaverInstanceState()를 오버라이드 해야합니다. 그리고 activity가 예상치 못하게 파괴되는 경우 저장되는 Bundle 객체에 키-값 쌍을 추가해야 합니다.
    onSaveInstanceState()를 오버라이드 했다면, 기본적인 구현이 View 계층의 상태를 저장하게 하려면 superclass를
    호출 해야합니다.
    override fun onSaveInstanceState(outState: Bundle?) {
    	// 사용자의 현재 게임 상태를 저장
        outState?.run {
        	putInt(STATE_SCORE, currentScore)
            putInt(STATE_LEVEL, currentLevel)
        }
        
        // 항상 View 게층 구조 상태를 저장 할 수 있게 superclasss를 호출하세요
        super.onSaveInstanceState(outState)
    }
    
    companion object {
    	val STATE_SCORE = "playerScore"
        val STATE_LEVEL = "playerLevel"
    }

    Note: onSaveInstanceState() is not called when the user explicitly closes the activity or in other cases when finish() is called.

    onSaveInstanceState()는 사용자가 명시적으로 activity를 닫을 때 또는 finish()가 호출 될 때 호출 되지 않습니다.

    To save persistent data, such as user preferences or data for a database, you should take appropriate opportunities when your activity is in the foreground. If no such opportunity arises, you should save such data during the onStop() method.

    사용자 기본 설정이나 데이터베이스 데이터와 같은 영구 데이터를 저장하려면 activity가 포그라운드에 있을때 적절한 기회를 가져야합니다.
    기회가 발생하지 않으면 onStop()메서드 중에 이러한 데이터를 저장해야합니다.

    Restore activity UI state using saved instance state

    When your activity is recreated after it was previously destroyed, you can recover your saved instance state from the Bundle that the system passes to your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.

    activity가 파괴 된 후 다시 생성되면, 시스템이 activity에 전달하는 Bundle에 저장된 인스턴스 상태를 복구 할 수 있습니다.
    onCreate() 및 onRestoreInstanceState() 콜백 메서드는 모두 인스턴스 상태 정보가 포함 된 동일한 Bundle을 수신합니다.

    Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.

    onCreate()는 시스템이 activity의 새 인스턴스를 생성하는지 또는 이전 인스턴스를 다시 생성하는지에 관계없이 호출되기 때문에 읽기를 시도하기 전에 상태 Bundle이 null인지 확인해야합니다.
    null이면 시스템은 이전에 파괴 된 인스턴스를 복원 하는 대신 새 인스턴스를 생성합니다.

    For example, the following code snippet shows how you can restore some state data in onCreate():

    예제에서는 일부 상태 데이터를 복원하는 것을 보여줍니다.
    override fun onCreate(savedInstanceState : Bundle?){
    	super.onCreate(savedInstanceState) // 항상 첫번째로 superclass를 호출
        
        // 이전에 파괴된 인스턴스를 다시 만들고 있는지 확인
        if(savedInstanceState != null){
        	with(savedInstanceState) {
            	// 저장된 상태에서 구성원 값 복원
                currentScore = getInt(STATE_SCORE)
                currentLevel = getInt(STATE_LEVEL)
            }
        } else {
        	// 새 인스턴스에 대한 기본값으로 멤버를 초기화 할 수 있습니다.
        }
    }

    Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null:

    onCreate() 동안 상태를 복원하는 대신 시스템이 onStart() 메서드 이후에 호출하는 onRestoreInstanceState()를 구현하도록
    선택할 수 있습니다. 시스템은 복원 할 저장된 상태가 있는 경우에만 onRestoreInstanceState()를 호춣하므로 번들이 null인지 여부를 확인 할 필요가 없습니다.
    override fun onRestoreInstanceState(savedInstanceState : Bundle?) {
    	// View 계층 구조를 복원 할 수 있도록 항상 superclass를 호출합니다.
        super.onRestoreInstanceState(savedInstanceState)
        
        // 저장된 인스턴스에서 상태 멤버를 복원 합니다.
        savedInstanceState?.run {
        	currentScore = getInt(STATE_SCORE)
            currentLevel = getInt(STATE_LEVEL)
        }
    }

    Caution: Always call the superclass implementation of onRestoreInstanceState() so the default implementation can restore the state of the view hierarchy.

    기본 구현이 View 계층 구조의 상태를 복원 할 수 있도록 항상 onRestoreInstanceState()의 superclass를 호출 하세요.

    Navigating between activities

    An app is likely to enter and exit an activity, perhaps many times, during the app’s lifetime. For example, the user may tap the device’s Back button, or the activity may need to launch a different activity. This section covers topics you need to know to implement successful activity transitions. These topics include starting an activity from another activity, saving activity state, and restoring activity state.

    앱은 앱의 수명 동안에 여러 번 activity에 들어가고 나갈 가능성이 있습니다.
    예를 들어, 사용자는 장치의 뒤로가기 버튼을 탭 할 수 있고 activity가 다른 activity를 시작해야 할 수 있습니다.
    이 섹션에서는 성공적인 activity 전환을 구현하기 위해 알아야 할 주제를 다룹니다.
    주제에는 다른 activity에서 activity 시작, activity 상태 저장 및 activity 상태 복원이 포함됩니다.

    Starting one activity from another

    An activity often needs to start another activity at some point. This need arises, for instance, when an app needs to move from the current screen to a new one.

    activity는 종종 몇몇 시점에서 다른 activity를 시작시켜야 합니다.
    예를 들어, 앱이 현재 화면에서 새 화면으로 이동 해야 할 때 이러한 요구가 발생합니다.

    Depending on whether your activity wants a result back from the new activity it’s about to start, you start the new activity using either the startActivity() or the startActivityForResult() method. In either case, you pass in an Intent object.

    activity가 시작하려는 새 activity의 결과를 원하는지 여부에 따라 startActivity() 또는 startActivityForResult()를 사용하여 새로운 activity를 시작합니다.
    두 경우 모두 Intent를 전달합니다.

    The Intent object specifies either the exact activity you want to start or describes the type of action you want to perform (and the system selects the appropriate activity for you, which can even be from a different application). An Intent object can also carry small amounts of data to be used by the activity that is started. For more information about the Intent class, see Intents and Intent Filters.

    Intent는 시작하려는 정확한 activity를 지정하거나 수행하려는 작업 유형을 설명합니다.
    (그리고 시스템은 다른 응용 프로그램에서도 가능할 수 있는 적절한 activity를 선택합니다.)
    Intent는 시작된 activity에서 사용할 작은양의 데이터를 전달 할 수도 있습니다.

    startActivity()

     

    If the newly started activity does not need to return a result, the current activity can start it by calling the startActivity() method.

    새로 시작된 activity가 결과를 리턴할 필요가 없다면, 현재 activity는 startActivity() 메서드를 호출하여 새로운 activity를 시작 할 수 있습니다.

    When working within your own application, you often need to simply launch a known activity. For example, the following code snippet shows how to launch an activity called SignInActivity.

    자신의 응용 프로그램 내에서 작업 할 때, 종종 known activity를 시작 해야 합니다.
    예시에서 SignInActivity를 시작하는 방법을 보여줍니다.
    val intent = Intent(this, SignInActivity::class.java)
    startActivity(intent)

    Your application might also want to perform some action, such as send an email, text message, or status update, using data from your activity. In this case, your application might not have its own activities to perform such actions, so you can instead leverage the activities provided by other applications on the device, which can perform the actions for you. This is where intents are really valuable: You can create an intent that describes an action you want to perform and the system launches the appropriate activity from another application. If there are multiple activities that can handle the intent, then the user can select which one to use. For example, if you want to allow the user to send an email message, you can create the following intent:

    application에서 activity의 데이터를 사용하여 이메일, 문자, 상태 업데이트 같은 일부 작업을 수행 할 수도 있습니다. 
    application에 이러한 작업을 수행하는 자체 activity가 없을 수도 있으므로 대신 다른 activity에서 제공하는 activity를 활용하여 작업을 수행 할 수 있습니다.
    수행하려는 작업을 설명하는 intent를 만들 수 있으며 시스템은 다른 application에서 적절한 activity를 시작합니다.
    intent를 처리 할 수 있는 activity가 여러 개인 경우 사용자는 사용할 activity를 선택 할 수 있습니다.
    예를 들어, 사용자가 이메일 메시지를 보내도록 허용하려면 예시 같은 intent를 만들 수 있습니다.
    val intent = Intent(Intent.ACTION_SEND).apply {
    	putExtra(Intent.EXTRA_EMAIL, recipientArray)
    }
    stratActivity(intent)

    The EXTRA_EMAIL extra added to the intent is a string array of email addresses to which the email should be sent. When an email application responds to this intent, it reads the string array provided in the extra and places them in the "to" field of the email composition form. In this situation, the email application's activity starts and when the user is done, your activity resumes.

    intent에 추가 된 EXTRA_EMAIL 추가는 이메일을 보내야하는 이메일 주소의 문자열 배열입니다.
    이메일 application이 인텐트에 응답하면 extra에 제공된 문자열 배열을 읽고 이메일 작성 양식의 "받는 사람" 필드에 배치합니다.
    이 상황에서 이메일 application의 activity가 시작되고 사용자가 완료되면 activity가 재개됩니다.

    startActivityForResult()

     

    Sometimes you want to get a result back from an activity when it ends. For example, you may start an activity that lets the user pick a person in a list of contacts; when it ends, it returns the person that was selected. To do this, you call the startActivityForResult(Intent, int) method, where the integer parameter identifies the call. This identifier is meant to disambiguate between multiple calls to startActivityForResult(Intent, int) from the same activity. It's not global identifier and is not at risk of conflicting with other apps or activities.The result comes back through your onActivityResult(int, int, Intent) method.

    때때로 activity가 끝났을 때 결과를 다시 얻고 싶을 때가 있습니다.
    예를 들어, 사용자가 연락처 목록에서 사람을 선택할 수 있는 activity를 시작 할 수 있습니다. 종료되면 선택된 사람을 반환합니다.
    예시대로 하려면 정수 매개 변수가 호출을 식별하는 startActivityForResult(Intent , int) 메소드를 호출 합니다.
    식별자는 동일한 activity에서 startActivityForResult(Intent, int)에 대한 여러 호출을 명확하게 하기위한 것입니다.
    전역 식별자가 아니며 다른 앱 또는 activity와 충돌 할 위험이 없습니다.
    결과는 onActivityResult(int, int, Intent) 메서드를 통해 반환됩니다.

    When a child activity exits, it can call setResult(int) to return data to its parent. The child activity must always supply a result code, which can be the standard results RESULT_CANCELED, RESULT_OK, or any custom values starting at RESULT_FIRST_USER. In addition, the child activity can optionally return an Intent object containing any additional data it wants. The parent activity uses the onActivityResult(int, int, Intent) method, along with the integer identifier the parent activity originally supplied, to receive the information.

    child activity가 종료 될 때, setResult(int)를 호출하여 데이터를 parent에게 반환 할 수 있습니다.
    child activity는 항상 결과 코드를 제공해야합니다.
    결과 코드는 표준적으로 RESULT_CANCELED, RESULT_OK 또는 RESULT_FIRST_USER 같이 사용자 정의 값 일 수 있습니다.
    child activity는 원하는 추가 데이터를 포함하는 Intent 개체를 선택적으로 반환 할 수 있습니다.
    parent activity는 parent activity가 원래 제공한 정수 식별자와 함께 onActivityResult(int, int, Intent)를 사용하여 정보를 수신합니다.

    If a child activity fails for any reason, such as crashing, the parent activity receives a result with the code RESULT_CANCELED.

    충돌과 같은 어떤 이유로 child activity가 실패하면 parent activity는 RESULT_CANCELED 코드와 함께 결과를 받습니다.
    class MyActivity : Activity() {
    	
        overrid fun onKeyDown(keyCode : Int, event : KeyEvent?) : Boolean {
        	if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
            	// 사용자가 center를 눌르면 연락처를 선택하도록 한다.
                startActivityForResult(
                			Intent(Intent.ACTION_PICK,Uri.parse("content://contacts")),
                            PICK_CONTACT_REQUEST)
                return true
            }
            return false
        }
        
        override fun onActivityResult(requestCode : Int, resultCode : Int, intent : Intent?) {
        	when(requestCode) {
            	PICK_CONTACT_REQUEST ->
                	if(resultCode == RESULT_OK) {
             			startActivity(Intent(Intent.ACTION_VIEW, intent?.data))       	
                    }
            }
        }
        
        companion object {
        	internal val PICK_CONTACT_REQUEST = 0
        }
    }

    Coordinating activities

     

    When one activity starts another, they both experience lifecycle transitions. The first activity stops operating and enters the Paused or Stopped state, while the other activity is created. In case these activities share data saved to disc or elsewhere, it's important to understand that the first activity is not completely stopped before the second one is created. Rather, the process of starting the second one overlaps with the process of stopping the first one.

    activty가 다른 activity를 시작하면 둘 다 생명주기 전환을 경험합니다.
    첫 번째 activity는 작동을 중지하고 일시 중지 또는 중지 상태가 되고 다른 activity는 생성됩니다.
    이러한 activity가 디스크 또는 다른 곳에 저장된 데이터를 공유하는 경우 두 번째 activity가 생성되기 전에 첫 번째 activity가 완전히 중지되지 않는다는 점을 이해하는 것이 중요합니다.
    오히려 두 번째 시작 프로세스는 첫 번째 프로세스를 중지하는 프로세스와 겹칩니다.

    The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process (app) and one is starting the other. Here's the order of operations that occur when Activity A starts Activity B:

    특히 두 activity가 동일한 프로세스(앱)에 있고 하나가 다른 activity를 시작하는 경우 생명주기 콜백의 순서가 잘 정의되어 있습니다. 다음은 activityA 가 activityB를 시작할 때 발생하는 작업 순서입니다.
    1. Activity A's onPause() method executes.
    2. Activity B's onCreate(), onStart(), and onResume() methods execute in sequence. (Activity B now has user focus.)
    3. Then, if Activity A is no longer visible on screen, its onStop() method executes.
    1. Activity A의 onPause()를 실행합니다.
    2. Activity B의 onCreate(), onStart(), onResume()을 순서대로 실행 합니다.(Activity B는 이제 사용자 focus를 갖습니다.)
    3. Activity A가 더 이상 화면에 표시되지 않으면 해당 onStop()이 실행됩니다.

    This predictable sequence of lifecycle callbacks allows you to manage the transition of information from one activity to another.

    예측 가능한 생명주기 콜백 시퀀스를 사용하면 한 activity에서 다른 activity로 정보 전환을 관리 할 수 있습니다.
    반응형

    'Android 공식문서' 카테고리의 다른 글

    Test your app's activites  (0) 2020.10.27
    Handle Activity State Changes  (0) 2020.10.22
    Introduction to Activities  (0) 2020.09.22
    Fragment - OverView  (0) 2020.09.11

    댓글

Designed by Tistory.