Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android에서 onCreate()와 onStart()의 차이점은 무엇일까? 생명주기 완벽 이해하기

이 글에서는 Android 액티비티 생명주기(Lifecycle)에서 onCreate()onStart()가 어떻게 다른지 실제 예제를 통해 단계별로 살펴보겠습니다.

onCreate()와 onStart()의 핵심 차이

두 메서드는 모두 액티비티 생명주기 콜백 메서드지만, 호출되는 시점과 역할이 명확히 다릅니다.

  • onCreate() — 액티비티가 처음 생성될 때 딱 한 번 호출됩니다. 레이아웃 설정(setContentView), 뷰 초기화 등 필수적인 초기화 작업을 수행하는 곳입니다.
  • onStart() — 액티비티가 사용자 눈에 보이기 시작할 때 호출됩니다. 홈 버튼을 눌렀다가 다시 돌아오는 경우처럼 액티비티가 중단 상태(Stopped)에서 화면으로 복귀할 때도 다시 호출될 수 있습니다.

즉, onCreate()는 액티비티 전체 수명 주기 동안 한 번만 실행되는 반면, onStart()는 화면에 표시될 때마다 반복적으로 실행될 수 있다는 점이 가장 큰 차이입니다.

예제 프로젝트 만들기

1단계 — 새 프로젝트 생성

Android Studio에서 File ⇒ New Project를 선택하고, 새 프로젝트를 만들기 위한 필수 정보를 모두 입력합니다.

2단계 — 레이아웃 파일 작성

res/layout/activity_main.xml에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Have a very nice day!"
        android:textSize="35dp"
        android:textStyle="bold"
        android:textColor="@color/colorAccent"
        android:layout_centerInParent="true"
        android:padding="20sp"
        android:layout_gravity="center_vertical" />
</LinearLayout>

3단계 — MainActivity 작성

src/MainActivity.java에 아래 코드를 추가합니다. 각 콜백 메서드 안에 로그(Log)를 출력하도록 작성하여, 어떤 순서로 호출되는지 Logcat에서 직접 확인할 수 있습니다.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
    public static final String TAG = "Have a nice day!";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i(TAG,"onCreate");
    }
    protected void onStart(){
        super.onStart();
        Log.i(TAG,"onStart");
    }
}

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 스마트폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

Android에서 onCreate()와 onStart()의 차이점은 무엇일까? 생명주기 완벽 이해하기

앱이 실행되면 Logcat에서 onCreate 로그가 먼저 출력된 후 onStart 로그가 이어서 출력되는 것을 확인할 수 있습니다. 여기서 홈 버튼을 눌러 앱을 나갔다가 다시 진입해 보면, onCreate는 다시 호출되지 않고 onStart만 새로 호출되는 것을 통해 두 메서드의 차이를 명확하게 체감할 수 있습니다.