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

안드로이드에서 액티비티(Activity)를 재시작하는 방법 – 단계별 완벽 가이드

이 튜토리얼에서는 안드로이드(Android)에서 액티비티(Activity)를 다시 시작(재시작)하는 방법을 단계별로 살펴봅니다. 버튼을 클릭하면 현재 액티비티가 종료된 후 동일한 인텐트(Intent)로 새롭게 실행되어 화면 전체가 갱신되는 실전 예제입니다.

구현 순서

1단계 — 새 프로젝트 생성

Android Studio에서 File ⇒ New Project로 이동하여 새 프로젝트를 생성하고, 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.

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

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 랜덤 숫자를 표시할 TextView와 액티비티를 재시작할 Button을 배치합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="24sp"
        android:textStyle="bold"/>
    <Button
        android:id="@+id/button"
        android:layout_below="@id/textView"
        android:layout_marginTop="16sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Restart Activity"/>
</RelativeLayout>

3단계 — 메인 액티비티 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 액티비티가 실행되면 0~99 사이의 랜덤 숫자가 TextView에 표시되며, 버튼을 누르면 액티비티가 재시작되면서 새로운 숫자로 갱신됩니다.

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    Button button;
    Random random = new Random();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        button = findViewById(R.id.button);
        textView.setText("Random Number: " + random.nextInt(100));
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = getIntent();
                finish();
                startActivity(intent);
            }
        });
    }
}

4단계 — 매니페스트 설정

AndroidManifest.xml 파일에 아래 코드를 추가하여 MainActivity를 런처(Launcher) 액티비티로 등록합니다.

<?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 아이콘을 클릭하고, 목록에서 사용 중인 모바일 기기를 선택하세요. 그러면 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 액티비티(Activity)를 재시작하는 방법 – 단계별 완벽 가이드

안드로이드에서 액티비티(Activity)를 재시작하는 방법 – 단계별 완벽 가이드

핵심 원리 정리

재시작 로직의 핵심은 다음 세 줄입니다. 먼저 getIntent()로 현재 액티비티를 시작한 인텐트를 가져온 뒤, finish()로 현재 액티비티를 종료하고, 마지막으로 startActivity(intent)로 동일한 인텐트를 다시 실행합니다. 이렇게 하면 액티비티가 완전히 새로 생성되어 onCreate()부터 생명주기가 처음부터 다시 호출됩니다.

참고로 API 레벨 11(Honeycomb) 이상에서는 recreate() 메서드를 호출하는 것만으로도 액티비티를 더 간편하게 재생성할 수 있으니, 상황에 맞게 활용해 보시기 바랍니다.