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

Android에서 앱 힙(Heap) 크기 확인하는 방법 완벽 가이드

이 튜토리얼에서는 ActivityManager 클래스를 활용해 Android 애플리케이션의 힙(Heap) 크기를 감지하는 방법을 단계별로 살펴봅니다.

안드로이드에서는 각 앱에 할당 가능한 메모리(힙) 한도가 정해져 있으며, getMemoryClass() 메서드를 호출하면 현재 앱에 허용된 힙 크기를 메가바이트(MB) 단위로 확인할 수 있습니다. 대용량 이미지 처리나 캐싱 작업을 수행하기 전에 이 값을 미리 파악해 두면 OutOfMemoryError를 예방하는 데 큰 도움이 됩니다.

구현 단계

1단계 — 새 프로젝트 생성

Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하고, 새 프로젝트 생성에 필요한 모든 정보를 입력하여 프로젝트를 만듭니다.

2단계 — 레이아웃 작성 (res/layout/activity_main.xml)

버튼과 결과를 표시할 TextView를 포함한 기본 레이아웃을 아래와 같이 구성합니다.

<?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"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="8dp"
    tools:context=".MainActivity">
    <Button
        android:onClick="HeapSize"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Detect Heap Size"/>
    <TextView
        android:textSize="24sp"
        android:textStyle="bold"
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

3단계 — MainActivity.java 코드 추가

버튼을 클릭하면 ActivityManager를 통해 힙 크기를 가져와 화면에 출력하는 로직입니다.

import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
    }
    public void HeapSize(View view) {
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        int memoryClass = Objects.requireNonNull(activityManager).getMemoryClass();
        textView.setText("Heap Size: " + memoryClass);
    }
}

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 Android에서 앱 힙(Heap) 크기 확인하는 방법 완벽 가이드 아이콘을 클릭하세요. 옵션 목록에서 자신의 모바일 기기를 선택하면 앱이 기기에 설치되어 실행됩니다.

앱이 실행되면 "Detect Heap Size" 버튼을 눌러 보세요. 버튼 아래의 TextView에 해당 기기에서 앱에 할당된 힙 크기(MB)가 표시됩니다.

Android에서 앱 힙(Heap) 크기 확인하는 방법 완벽 가이드

추가 팁: 더 큰 힙이 필요하다면?

이미지 편집 앱처럼 많은 메모리가 필요한 경우라면, AndroidManifest.xml의 <application> 태그에 android:largeHeap="true" 속성을 추가하여 일부 기기에서 더 큰 힙을 할당받을 수 있습니다. 다만 이 속성은 배터리 소모 증가와 전체 시스템 성능 저하를 유발할 수 있으므로 반드시 필요한 경우에만 신중하게 사용하는 것이 좋습니다. 또한 getLargeMemoryClass() 메서드를 활용하면 largeHeap 적용 시 확보 가능한 최대 힙 크기도 함께 확인할 수 있습니다.