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

Android 앱이 백그라운드에서 실행 중인지 확인하는 방법 완벽 가이드

이 튜토리얼에서는 ActivityManager를 활용하여 Android 애플리케이션이 현재 백그라운드에서 실행 중인지 확인하는 방법을 단계별로 알아봅니다. 앱의 상태(포그라운드/백그라운드)를 감지하는 것은 알림 처리, 리소스 관리, 사용자 경험 최적화 등 다양한 상황에서 유용하게 활용됩니다.

핵심 원리

Android에서는 ActivityManager.getMyMemoryState() 메서드를 호출하여 현재 앱 프로세스의 중요도(importance)를 확인할 수 있습니다. 반환된 값이 IMPORTANCE_FOREGROUND가 아니라면 해당 앱은 백그라운드에서 실행 중이라고 판단할 수 있습니다.

구현 단계

1단계 — 새 프로젝트 생성

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

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

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

<?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"
    android:padding="4dp"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textStyle="bold"
        android:layout_centerInParent="true"
        android:text="Checking if Android Application is running in Background"/>
</RelativeLayout>

3단계 — MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityManager;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Boolean appRunningBackground;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActivityManager.RunningAppProcessInfo runningAppProcessInfo = new ActivityManager.RunningAppProcessInfo();
        ActivityManager.getMyMemoryState(runningAppProcessInfo);
        appRunningBackground = runningAppProcessInfo.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;

        if (appRunningBackground) {
            Toast.makeText(getApplicationContext(), "Your Android Application is Running in Background", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Your Android Application is not Running in Background", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Toast.makeText(getApplicationContext(), "Your Android Application is Running in Background", Toast.LENGTH_SHORT).show();
    }
}

위 코드에서 핵심 부분은 getMyMemoryState() 호출입니다. 이 메서드는 현재 프로세스의 상태 정보를 RunningAppProcessInfo 객체에 채워 넣으며, importance 필드 값이 IMPORTANCE_FOREGROUND와 같지 않으면 앱이 백그라운드에 있다는 의미입니다. 또한 onPause() 콜백에서도 앱이 화면에서 벗어나 백그라운드로 전환되는 시점을 감지할 수 있습니다.

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 앱이 백그라운드에서 실행 중인지 확인하는 방법 완벽 가이드

마무리

이처럼 ActivityManager.getMyMemoryState()를 사용하면 별도의 권한 없이도 간단하게 앱의 포그라운드/백그라운드 상태를 판별할 수 있습니다. 참고로 최신 Android 개발 환경에서는 ProcessLifecycleOwner(Jetpack Lifecycle 라이브러리)를 활용하면 앱 전체 수명 주기를 더욱 체계적으로 관찰할 수 있으니, 규모가 큰 프로젝트에서는 함께 검토해 보시길 권장합니다.