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

프로그래밍 방식으로 안드로이드 앱을 재시작하는 방법 완벽 가이드

앱 개발 과정에서 설정 변경 적용이나 상태 초기화 등의 이유로 전체 애플리케이션을 프로그래밍 방식으로 재시작해야 하는 경우가 종종 발생합니다. 이 글에서는 AlarmManager와 PendingIntent를 활용하여 안드로이드 앱을 코드만으로 깔끔하게 재시작하는 방법을 단계별로 살펴보겠습니다.

1단계 — 새 프로젝트 생성하기

Android Studio를 실행하고 File ⇒ New Project 메뉴로 이동한 뒤, 프로젝트 생성에 필요한 기본 정보(프로젝트 이름, 패키지명, 최소 SDK 버전 등)를 모두 입력하여 새 프로젝트를 만듭니다.

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

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

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
    android:id = "@+id/parent"
    xmlns:tools = "https://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity"
    android:gravity = "center"
    android:orientation = "vertical">
    <TextView
        android:id = "@+id/text"
        android:textSize = "28sp"
        android:textAlignment = "center"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content" />
</LinearLayout>

위 레이아웃에는 TextView 하나가 배치되어 있습니다. 사용자가 이 텍스트뷰를 탭하면 애플리케이션이 전체적으로 재시작되도록 구현할 것입니다.

3단계 — MainActivity에 재시작 로직 구현하기

MainActivity.java 파일에 다음 코드를 작성합니다.

package com.example.andy.myapplication;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    int view = R.layout.activity_main;
    TextView textview;
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(view);
        textview = findViewById(R.id.text);
        textview.setText("Click here to restart activity");
        textview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mStartActivity = new Intent(MainActivity.this, MainActivity.class);
                int mPendingIntentId = 123456;
                PendingIntent mPendingIntent = PendingIntent.getActivity(MainActivity.this, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
                AlarmManager mgr = (AlarmManager)MainActivity.this.getSystemService(Context.ALARM_SERVICE);
                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
            }
        });
    }
}

재시작 로직의 동작 원리

핵심 코드는 다음과 같습니다.

Intent mStartActivity = new Intent(MainActivity.this, MainActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(MainActivity.this, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)MainActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

동작 흐름을 정리하면 다음과 같습니다.

현재 액티비티(MainActivity)를 다시 여는 Intent를 생성합니다.
고유 ID(123456)를 지정해 PendingIntent로 감싸고, FLAG_CANCEL_CURRENT 플래그를 통해 이전에 등록된 같은 ID의 알람이 있다면 취소합니다.
AlarmManager에 현재 시점으로부터 100밀리초 후에 해당 PendingIntent를 실행하도록 예약합니다.
System.exit(0)으로 프로세스를 즉시 종료합니다.

결과적으로 앱이 완전히 종료된 직후 알람이 발동되어 MainActivity가 새롭게 실행되며, 이는 곧 앱 전체가 재시작된 것과 동일한 효과를 냅니다. 이 방식은 프로세스가 실제로 종료되었다가 다시 시작되기 때문에 단순히 recreate()를 호출하는 것보다 더 완전한 초기화가 필요할 때 유용합니다.

4단계 — 앱 실행 및 결과 확인하기

실제 안드로이드 기기를 컴퓨터에 연결했다고 가정하고 앱을 실행해 보겠습니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭합니다. 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

프로그래밍 방식으로 안드로이드 앱을 재시작하는 방법 완벽 가이드

화면의 텍스트뷰를 탭하면 잠시 후 애플리케이션이 자동으로 종료되고 다시 시작되는 것을 확인할 수 있습니다.