IT

정확히 Activity.finish () 메소드가 수행하는 작업은 무엇입니까?

lottoking 2020. 6. 15. 08:05
반응형

정확히 Activity.finish () 메소드가 수행하는 작업은 무엇입니까?


한동안 안드로이드 응용 프로그램을 개발 중이며 활동 수명주기 및 응용 프로그램 수명주기에 대한 많은 게시물을 따랐습니다.

나는 Activity.finish()메소드 호출을 어딘가에 호출 Activity.onDestroy()하고 스택에서 액티비티를 제거한다는 것을 알고 있으며, 어떻게 든 운영 체제와 가비지 콜렉터가 "트릭을 수행하고"좋은 시간이되면 메모리를 확보 할 수 있다고 생각합니다. 그래서....

이 게시물에 왔습니다- 응용 프로그램을 종료하는 것은 눈살을 찌푸리고 있습니까? Mark Murphy의 답변을 읽으십시오.

정확히 finish()방법이 실제로 하는 일에 대해 약간 혼란 스러웠습니다 .

내가 전화 할게 기회가 있습니까 finish()onDestroy()호출되지 않습니다는?


finish()활동을 호출 하면 메소드 onDestroy()가 실행됩니다. 이 방법은 다음과 같은 작업을 수행 할 수 있습니다.

  1. 활동이 관리하고있는 대화를 닫습니다.
  2. 활동이 관리하고있는 커서를 닫으십시오.
  3. 열려있는 검색 대화 상자를 모두 닫습니다.

또한 onDestroy()소멸자가 아닙니다. 실제로 객체를 파괴하지는 않습니다. 특정 상태를 기반으로 호출되는 메소드 일뿐입니다. 따라서 슈퍼 클래스가 onDestroy()실행되고 돌아온 후에도 인스턴스는 여전히 살아 있고 매우 잘 * 있습니다 .Android는 사용자가 앱을 다시 시작하려는 경우 프로세스를 유지하여 시작 단계를 더 빠르게 만듭니다. 프로세스가 수행하지 않고 메모리를 회수해야하는 경우 프로세스가 종료됩니다.


@K_Anas에서 내 2 센트가 대답합니다. finish () 메소드에서 간단한 테스트를 수행했습니다. 활동 수명주기에서 중요한 콜백 메소드 나열

  1. onCreate ()에서 finish () 호출 : onCreate ()-> onDestroy ()
  2. onStart ()에서 finish () 호출 : onCreate ()-> onStart ()-> onStop ()-> onDestroy ()
  3. onResume ()에서 finish () 호출 : onCreate ()-> onStart ()-> onResume ()-> onPause ()-> onStop ()-> onDestroy ()

내가 말하고자하는 것은 finish ()가 실행될 때 사이에있는 메소드와 함께 메소드의 대응 부분이 호출된다는 것입니다.

예 :

 onCreate() counter part is onDestroy()
 onStart() counter part is onStop()
 onPause() counter part is onResume()

의도 후 finish ()를 호출하면 "뒤로"버튼으로 이전 활동으로 돌아갈 수 없습니다.

startActivity(intent);
finish();

onDestroy()최종 정리를위한 것입니다. 자신이 직접 할 수있는 리소스를 확보하고 열린 연결, 리더, 작성자 등을 닫습니다. 재정의하지 않으면 시스템이 필요한 작업을 수행합니다.

반면에, finish()프로그래머에게 전류 Activity가 완료 되기를 원한다는 것을 시스템에 알리십시오 . 따라서 onDestroy()그 후에 호출됩니다 .

주목할 사항 :

그것은 그 필요는 없습니다 의 호출 finish()트리거 호출에 onDestroy(). 아시다시피, 안드로이드 시스템은 Activity해제 해야하는 전류에 필요한 리소스가 있다고 생각되면 활동 을 자유롭게 종료 할 수 있습니다.


Finish () 메소드는 현재 활동을 파괴합니다. 사용자가 뒤로 버튼을 누를 때이 활동을 다시로드하지 않으려는 경우이 방법을 사용할 수 있습니다. 기본적으로 현재 스택에서 활동을 지 웁니다.


다양한 답변과 메모에 따르면 finish ()는 onPause () 및 onStop ()을 건너 뛰고 onDestroy ()를 직접 실행할 수 있다고 주장합니다. 공평하게 말하면, 이것에 대한 Android 문서 ( http://developer.android.com/reference/android/app/Activity.html )는 "활동이 시스템에 의해 마무리되거나 파괴되고 있습니다"라고 지적하지만 상당히 모호하지만 finish ()는 onDestroy ()로 이동할 수 있습니다.

finish ()의 JavaDoc은 비슷하게 실망스럽고 ( http://developer.android.com/reference/android/app/Activity.html#finish () ) 실제로 종료에 대한 응답으로 어떤 메소드가 호출되는지 기록하지 않습니다. ().

그래서이 미니 응용 프로그램을 아래에 작성하여 진입시 각 상태를 기록합니다. finish ()를 호출하는 버튼이 포함되어있어 어떤 메소드의 로그가 실행되는지 확인할 수 있습니다. 이 실험은 finish () 가 실제로 onPause () 및 onStop ()을 호출 한다고 제안했습니다 . 내가 얻는 결과는 다음과 같습니다.

2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onCreate
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onStart
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onResume
2170-2170/? D/LIFECYCLE_DEMO﹕ User just clicked button to initiate finish() 
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onPause
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onStop 
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onDestroy

package com.mvvg.apps.lifecycle;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class AndroidLifecycle extends Activity {

    private static final String TAG = "LIFECYCLE_DEMO";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "INSIDE: onCreate");
        setContentView(R.layout.activity_main);
        LinearLayout layout = (LinearLayout) findViewById(R.id.myId);
        Button button = new Button(this);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                Toast.makeText(AndroidLifecycle.this, "Initiating finish()",
                        Toast.LENGTH_SHORT).show();
                Log.d(TAG, "User just clicked button to initiate finish()");
                finish();
            }

        });

        layout.addView(button);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "INSIDE: onStart");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "INSIDE: onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "INSIDE: onDestroy");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "INSIDE: onPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "INSIDE: onResume");
    }

}

위의 @rommex 답변 외에도 finish()활동 파괴가 대기하고 활동 우선 순위에 달려 있음을 알았 습니다.

finish()이후 onPause()전화하면이 표시 onStop()되고 onDestroy()즉시 전화했습니다.

finish()이후 onStop()전화하면 onDestroy()5 분 후에 는 표시되지 않습니다 .

From my observation, it looks like finish is queued up and when I looked at the adb shell dumpsys activity activities it was set to finishing=true, but since it is no longer in the foreground, it wasn't prioritized for destruction.

In summary, onDestroy() is never guaranteed to be called, but even in the case it is called, it could be delayed.


My study shows that finish() method actually places some destruction operations in the queue, but the Activity is not destroyed immediately. The destruction is scheduled though.

For example, if you place finish() in onActivityResult() callback, while onResume() has yet to run, then first onResume() will be executed, and only after that onStop() and onDestroy() are called.

NOTE: onDestroy() may not be called at all, as stated on the documentation.


@user3282164 According to the Activity life-cycle it should go through onPause() -> onStop() -> onDestroy() upon calling finish().

The diagram does not show any straight path from [Activity Running] to [onDestroy()] caused by the system.

onStop() doc says "Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called."


calling finish in onCreate() will not call onDestroy() directly as @prakash said. The finish() operation will not even begin until you return control to Android.

Calling finish() in onCreate(): onCreate() -> onStart() -> onResume(). If user exit the app will call -> onPause() -> onStop() -> onDestroy()

Calling finish() in onStart() : onCreate() -> onStart() -> onStop() -> onDestroy()

Calling finish() in onResume(): onCreate() -> onStart() -> onResume() -> onPause() -> onStop() -> onDestroy()

For further reference check look at this oncreate continuous after finish & about finish()


It seems that the only correct answer here so far has been given by romnex: "onDestroy() may not be called at all". Even though in practice, in almost all cases it will, there is no guarantee: The documentation on finish() only promises that the result of the activity is propagated back to the caller, but nothing more. Moreover, the lifecycle documentation clarifies that the activity is killable by the OS as soon as onStop() finishes (or even earlier on older devices), which, even though unlikely and therefore rare to observe in a simple test, might mean that the activity might be killed while or even before onDestroy() is executed.

So if you want to make sure some work is done when you call finish(), you cannot put it in onDestroy(), but will need to do in the same place where you call finish(), right before actually calling it.


finish () just sends back to the previous activity in android, or may be you can say that it is going one step back in application

참고URL : https://stackoverflow.com/questions/10847526/what-exactly-activity-finish-method-is-doing

반응형