onDestroy()란 무엇인가?
onDestroy()는 안드로이드 액티비티(Activity) 생명주기에서 가장 마지막에 호출되는 콜백 메서드입니다. 사용자가 뒤로 가기 버튼을 누르거나 finish()를 호출해 액티비티가 완전히 종료될 때, 또는 시스템이 리소스 확보를 위해 액티비티를 파괴할 때 실행됩니다. 이 예제에서는 onDestroy()를 오버라이드하여 로그(Logcat)로 호출 시점을 확인하는 방법을 단계별로 살펴보겠습니다.
1단계: 새 프로젝트 생성
Android Studio를 열고 File → New Project를 선택한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.
2단계: 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="32dp"
android:text="Destroy"
android:textColor="@color/colorPrimary"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>3단계: MainActivity 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다. 여기서 핵심은 onDestroy() 메서드를 오버라이드하고, super.onDestroy()를 반드시 먼저 호출한 뒤 로그를 기록하는 것입니다.
package com.sample.q2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
public static final String MY_TAG = "Destroy";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(MY_TAG, "onCreate");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(MY_TAG, "onDestroy");
}
}4단계: 매니페스트 설정
androidManifest.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>애플리케이션 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터와 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run(실행) 아이콘을 클릭합니다. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

앱이 정상적으로 실행되면 Logcat 창에서 태그 "Destroy"로 필터링하여 onCreate 로그를 확인할 수 있습니다. 그다음 기기의 뒤로 가기 버튼을 누르거나 최근 앱 목록에서 앱을 종료하면, onDestroy()가 호출되면서 "onDestroy" 로그가 기록되는 것을 확인할 수 있습니다.
정리
onDestroy()는 액티비티가 소멸되기 직전 마지막으로 호출되는 콜백으로, 리스너 해제, 스레드 종료, 데이터베이스 연결 닫기 등 리소스 정리 작업을 수행하기에 적합한 위치입니다. 단, 시스템에 의해 언제든 프로세스가 종료될 수 있으므로 onDestroy()에 중요한 데이터 저장 로직을 의존하는 것은 피하는 것이 좋습니다.