도대체뭐가문제임

액티비티를 종료하는 여러 함수들 본문

안드로이드

액티비티를 종료하는 여러 함수들

뭐가문제임 2021. 4. 28. 18:00

finish()

 /**
     * Call this when your activity is done and should be closed.  The
     * ActivityResult is propagated back to whoever launched you via
     * onActivityResult().
     */
    public void finish() {
        finish(DONT_FINISH_TASK_WITH_ACTIVITY);
    }

Activity를 종료하는 대표적인 함수다.

해당 Activity를 startActivityForResult()로 호출했다면 호출한 부모Activity에 대해서는 현재 Activity를 종료함과 동시에 ActivityResult를 onActivityResult()함수를 통해 전달한다. 

finishAffinity()

/**
     * Finish this activity as well as all activities immediately below it
     * in the current task that have the same affinity.  This is typically
     * used when an application can be launched on to another task (such as
     * from an ACTION_VIEW of a content type it understands) and the user
     * has used the up navigation to switch out of the current task and in
     * to its own task.  In this case, if the user has navigated down into
     * any other activities of the second application, all of those should
     * be removed from the original task as part of the task switch.
     *
     * <p>Note that this finish does <em>not</em> allow you to deliver results
     * to the previous activity, and an exception will be thrown if you are trying
     * to do so.</p>
     */
    public void finishAffinity() {
        if (mParent != null) {
            throw new IllegalStateException("Can not be called from an embedded activity");
        }
        if (mResultCode != RESULT_CANCELED || mResultData != null) {
            throw new IllegalStateException("Can not be called to deliver a result");
        }
        try {
            if (ActivityTaskManager.getService().finishActivityAffinity(mToken)) {
                mFinished = true;
            }
        } catch (RemoteException e) {
            // Empty
        }
    }

안드로이드에서 앱을 종료할 때에는 보통 최초 실행 된 Activity인 RootActivity를 종료할 것을 권장한다.

하지만 현재 최상단에 있는 Activity가 RootActivity가 아니라면 RootActivity를 찾아가 종료하는 번거로운 과정이 생긴다.

이 때 유용한 함수가 finishAffinity()이다.

어떤 Activity에서든 finishAffinity()를 사용하면 모든 부모 액티비티를 닫을 수 있다. 

*affinity: 친화력, 친밀감, 관련성

finishAndRemoveTask()

  /**
     * Call this when your activity is done and should be closed and the task should be completely
     * removed as a part of finishing the root activity of the task.
     */
    public void finishAndRemoveTask() {
        finish(FINISH_TASK_WITH_ROOT_ACTIVITY);
    }

함수명 그대로 Activity를 종료하고 Task를 제거하는 함수이다.

단, Task를 종료할 뿐 Process까지 종료되진 않는다.

finishAndRemoveTask()로 앱을 종료하고 다시 실행하면 Application class의 onCreate()를 거치지 않는다.

즉, 앱의 프로세스는 종료되지 않았다는 뜻이다.

프로세스까지 완전히 종료하려면 System.runFinalizersOnExit(true), System.exit()를 사용하면 된다.

'안드로이드' 카테고리의 다른 글

[Android]Deeplink란?  (0) 2021.08.19
안드로이드의 구조  (0) 2021.05.03
onBackPressed()에서 백버튼 더블클릭으로 앱 종료하기  (1) 2021.04.29
Comments