The Memory Advice API beta is now deprecated, and no longer recommended for use.
Memory Advice API 시작하기
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
이 가이드에서는 Android 스튜디오를 사용하여 Memory Advice API의 Jetpack 버전을 앱에 통합하는 방법을 설명합니다.
게임은 빌드 환경에 권장되는 Memory Advice API 버전을 사용해야 합니다. Android 스튜디오의 경우 Jetpack 버전을 사용하는 것이 좋습니다. Android 게임 개발 확장 프로그램(AGDE)과 같은 다른 빌드 환경을 위한 버전을 자세히 알아보려면 배포를 참고하세요.
라이브러리 추가
이 섹션에서는 Android 스튜디오(Android Gradle 플러그인) 프로젝트에 라이브러리를 추가하는 방법을 설명합니다.
종속 항목 추가
라이브러리를 Android 스튜디오 프로젝트에 추가하려면 다음 단계를 완료하세요.
프로젝트 수준(gradle.properties
)에서 Android Jetpack 라이브러리를 사용 설정합니다. 이 파일은 일반적으로 프로젝트의 루트 디렉터리에 있습니다.
android.useAndroidX=true
모듈 수준의 build.gradle
파일을 열고 다음 implementation
을 종속 항목 블록에 추가합니다. 이렇게 하면 앱에서 Memory Advice API 종속 항목이 선언됩니다.
dependencies {
implementation 'androidx.games:games-memory-advice:1.0.0-beta01'
}
android
블록 내에 NDK 버전을 지정합니다.
ndkVersion "23.1.7779620"
Memory Advice API와 호환되는 NDK 버전을 선택해야 합니다.
지원되는 NDK 버전 목록은 Android 게임 Jetpack 버전 페이지에서 확인할 수 있습니다.
CMake의 추가 빌드 플래그를 선언합니다. 빌드 플래그를 선언하려면 android
블록 내부에 있는 defaultConfig
블록에 다음 코드를 추가하면 됩니다.
externalNativeBuild {
cmake {
cppFlags '-std=c++14'
// c++_shared flavor is the only supported STL type.
arguments "-DANDROID_STL=c++_shared"
}
}
Prefab 기능을 사용 설정합니다.
Android Gradle 플러그인(AGP) 4.1 이상의 경우 android
블록에 다음 코드를 추가합니다.
buildFeatures {
prefab true
}
AGP 4.0 이하를 사용하는 경우 구성 안내는 Prefab 페이지를 참고하세요.
파일을 저장합니다. 다음 메시지가 표시되면 Sync Now 버튼을 클릭하여 프로젝트를 업데이트합니다.
Gradle files have changed since last project sync. A project sync may be
necessary for the IDE to work properly.
Memory Advice API의 헤더 파일과 런타임 라이브러리를 프로젝트에 추가하려면 프로젝트의 기본 CMakeLists.txt
파일을 엽니다. Project 창에서 파일은 app > src > main > cpp에 있습니다. 파일을 연 후 다음 단계를 실행하세요.
파일 상단에서 cmake_minimum_required
및 project
줄 뒤에 다음 줄을 추가합니다.
find_package(games-memory-advice REQUIRED CONFIG)
target_link_libraries
명령어에 games-memory-advice::memory_advice
를 추가합니다. 이렇게 하면 Memory Advice API가 프로젝트의 네이티브 라이브러리의 종속 항목이 되고 최종 애플리케이션 패키지에 포함됩니다.
명령어를 업데이트한 후에는 다음과 같이 표시되어야 합니다.
target_link_libraries(
your-native-lib
#link memory advice to the project
games-memory-advice::memory_advice
#rest of the dependencies
#...
)
Memory Advice API가 포함된 네이티브 라이브러리는 libmemory_advice.so
입니다. 이 라이브러리는 앱 자체 C/C++ 공유 라이브러리의 컴파일 종속 항목이며 앱이 System.loadlibrary()
함수를 사용하여 자체 공유 라이브러리를 로드할 때 자동으로 로드됩니다.
이 단계는 선택사항입니다.
프로젝트에서 네이티브 라이브러리를 로드하는 자바 코드를 찾습니다. 코드가 존재하지 않는 경우 추가합니다. 코드는 System.loadLibrary("your-native-lib")
와 유사하고 static
블록에 있습니다.
System.loadLibrary("your-native-lib")
아래에 System.loadLibrary("memory_advice")
를 추가합니다. 추가한 후에는 다음과 같이 표시되어야 합니다.
static {
System.loadLibrary("your-native-lib");
// Note: loading libmemory_advice.so is optional.
System.loadLibrary("memory_advice");
}
라이브러리 사용
이 섹션에서는 라이브러리 사용 방법을 설명합니다.
프로젝트에 다음 라이브러리 헤더 파일을 포함합니다.
#include <memory_advice/memory_advice.h>
라이브러리 초기화
앱이 시작되면 라이브러리를 한 번 초기화해야 합니다. 프로젝트에 다음 코드를 추가하면 됩니다.
MemoryAdvice_init(env, activity);
env
및 activity
매개변수는 네이티브 라이브러리에서 사용할 수 있는 JNIEnv*
및 jobject
변수입니다. 네이티브 라이브러리에 관한 모든 JNI 호출에는 이러한 변수가 포함되어야 합니다. GameActivity 라이브러리를 사용하고 있다면 MemoryAdvice_init
함수를 호출하기 전에 호출 스레드를 JavaVM에 연결해야 합니다.
메모리 상태 폴링
지정한 간격으로 라이브러리를 폴링하여 앱의 메모리 상태를 가져올 수 있습니다. 라이브러리를 폴링해야 할 때마다 MemoryAdvice_getMemoryState 함수를 사용하세요.
MemoryAdvice_MemoryState state = MemoryAdvice_getMemoryState();
switch (state) {
case MEMORYADVICE_STATE_OK:
// The application can safely allocate significant memory.
break;
case MEMORYADVICE_STATE_APPROACHING_LIMIT:
//The application should minimize memory allocation.
break;
case MEMORYADVICE_STATE_CRITICAL:
// The application should free memory as soon as possible,
// until the memory state changes.
break;
}
감시자 설정
감시자를 설정하고 Memory Advice API를 등록할 수도 있습니다. 상태가 한계에 가까워지거나 중요한 메모리 상태가 되면 감시자 함수가 호출됩니다(일반적인 상태에서는 호출되지 않음). 예를 들어, 다음 코드는 감시자를 만들고 2초마다 Memory Advice API 알림을 요청합니다.
static int USER_DATA;
constexpr int callback_waittime_ms = 2000;
void callback(MemoryAdvice_MemoryState state, void* context) {
switch (state) {
case MEMORYADVICE_STATE_APPROACHING_LIMIT:
//The application should minimize memory allocation.
break;
case MEMORYADVICE_STATE_CRITICAL:
// The application should free memory as soon as possible,
// until the memory state changes.
break;
}
}
MemoryAdvice_registerWatcher(callback_waittime_ms, callback, &USER_DATA);
다음 단계
추가 리소스 및 문제 보고는 개요를 참고하세요.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-08-26(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-26(UTC)"],[],[],null,["| **Note:** The Memory Advice API Beta is now over and the library is deprecated. [learn more about alternative memory management approaches](/games/optimize/memory-allocation).\n\nThis guide describes how to integrate the\n[Jetpack release](/jetpack/androidx/releases/games) of the\n[Memory Advice API](/games/sdk/memory-advice/overview) in your\napp using Android Studio.\n\nGames should use the Memory Advice API release that is\nrecommended for their build environment. For Android Studio, we recommend the\nJetpack release. For information about releases for other build environments,\nsuch as the [Android Game Development Extension](/games/agde)\n(AGDE), see [Distributions](/games/sdk/memory-advice/overview#distributions).\n\nAdd the library\n\nThis section describes how to add the library to your Android Studio (Android\nGradle Plugin) project.\n\nAdd the dependencies\n\nTo add the library to your Android Studio project, complete the following steps:\n\n1. Enable Android Jetpack library in the project level\n [`gradle.properties`](/studio/build#properties-files)), the file normally is located in root directory\n of your project:\n\n android.useAndroidX=true\n\n2. Open the module level `build.gradle` file and add the following\n `implementation` to the dependencies block. This declares [the memory advice API\n dependencies](/jetpack/androidx/releases/games) in your app.\n\n dependencies {\n implementation 'androidx.games:games-memory-advice:1.0.0-beta01'\n }\n\n3. Specify the NDK version inside the `android` block:\n\n ndkVersion \"23.1.7779620\"\n\n Make sure to choose a version of the NDK compatible with Memory Advice API.\n A list of supported NDK versions is available on the [Android Games Jetpack Release page](/jetpack/androidx/releases/games).\n4. Declare additional build flags for CMake. To do so, add the following code to the\n `defaultConfig` block that is inside the `android` block:\n\n externalNativeBuild {\n cmake {\n cppFlags '-std=c++14'\n // c++_shared flavor is the only supported STL type.\n arguments \"-DANDROID_STL=c++_shared\"\n }\n }\n\n5. Enable the [Prefab](/studio/build/dependencies#native-dependencies-aars) feature.\n For Android Gradle Plugin(AGP) 4.1 or higher, add the following code to the\n `android` block:\n\n buildFeatures {\n prefab true\n }\n\n If you are using AGP 4.0 or older, see the\n [Prefab page](/studio/build/dependencies#native-dependencies-aars)\n for configuration instructions.\n6. Save the file. If you see the following message, click the **Sync Now**\n button to update your project:\n\n Gradle files have changed since last project sync. A project sync may be\n necessary for the IDE to work properly.\n\nConfigure CMake for C/C++ build\n\nTo add the header files and runtime library for Memory Advice API\ninto your project, open your project's main `CMakeLists.txt` file. In the\n**Project** pane, the file is in **app \\\u003e src \\\u003e main \\\u003e cpp**. After opening the\nfile, perform the following steps:\n\n1. Near the top of the file, add the following line after any\n `cmake_minimum_required` and `project` lines:\n\n find_package(games-memory-advice REQUIRED CONFIG)\n\n2. In the `target_link_libraries` command, add\n `games-memory-advice::memory_advice`. This makes the Memory Advice API\n a dependency to your project's native library and includes it in your final application package.\n The update should look similar to the following:\n\n target_link_libraries(\n your-native-lib\n\n #link memory advice to the project\n games-memory-advice::memory_advice\n\n #rest of the dependencies\n #...\n )\n\nConfigure the Java files\n\nThe native library included with the Memory Advice API is\n`libmemory_advice.so`. It is a compiling dependency for your app's own\nC/C++ shared library, and is automatically loaded when your app loads its own\nshared library with the `System.loadlibrary()` function.\n\nThis step is optional.\n\n1. Find the java code in your project that loads the native libraries. If it\n doesn't exist, add it. The code\n should look similar to `System.loadLibrary(\"your-native-lib\")`, and is\n located in a `static` block.\n\n2. Add `System.loadLibrary(\"memory_advice\")` under\n `System.loadLibrary(\"your-native-lib\")`. The update should look similar to\n the following:\n\n static {\n System.loadLibrary(\"your-native-lib\");\n // Note: loading libmemory_advice.so is optional.\n System.loadLibrary(\"memory_advice\");\n }\n\nUse the library\n\nThis section describes how to use the library.\n\nAdd the header files\n\nInclude the following library header file in your project: \n\n #include \u003cmemory_advice/memory_advice.h\u003e\n\nInitialize the library\n\nYou need to initialize the library once when the app starts. To do so, add this\ncode to your project: \n\n MemoryAdvice_init(env, activity);\n\nThe `env` and `activity` parameters are the `JNIEnv*` and `jobject` variables\nthat should be available to your native library. Every JNI call to your native\nlibrary should contain these variables. If you are using the\n[GameActivity library](/games/agdk/game-activity),\nmake sure to\n[attach the calling thread to the JavaVM](/training/articles/perf-jni#threads)\nbefore calling the `MemoryAdvice_init` function.\n\nPoll for memory state\n\nYou can retrieve the memory state of your app by polling the library at the\ninterval of your choosing. Use the\n[MemoryAdvice_getMemoryState](/reference/games/memory-advice/group/memory-advice#memoryadvice_getmemorystate)\nfunction whenever you need to poll the library: \n\n MemoryAdvice_MemoryState state = MemoryAdvice_getMemoryState();\n switch (state) {\n case MEMORYADVICE_STATE_OK:\n // The application can safely allocate significant memory.\n break;\n case MEMORYADVICE_STATE_APPROACHING_LIMIT:\n //The application should minimize memory allocation.\n break;\n case MEMORYADVICE_STATE_CRITICAL:\n // The application should free memory as soon as possible,\n // until the memory state changes.\n break;\n }\n\nSet up a watcher\n\nYou can also set up\n[a watcher](/reference/games/memory-advice/group/memory-advice#memoryadvice_registerwatcher)\nand register the Memory Advice API, and your watcher function will get called\nwhen the state is either approaching the limit or the critical\n[memory state](/reference/games/memory-advice/group/memory-advice#memoryadvice_memorystate)\n(but not for the ok state). For example, the following code creates a watcher\nand requests a Memory Advice API notification every 2 seconds: \n\n static int USER_DATA;\n constexpr int callback_waittime_ms = 2000;\n\n void callback(MemoryAdvice_MemoryState state, void* context) {\n switch (state) {\n case MEMORYADVICE_STATE_APPROACHING_LIMIT:\n //The application should minimize memory allocation.\n break;\n case MEMORYADVICE_STATE_CRITICAL:\n // The application should free memory as soon as possible,\n // until the memory state changes.\n break;\n }\n }\n\n MemoryAdvice_registerWatcher(callback_waittime_ms, callback, &USER_DATA);\n\nWhat's next\n\nSee the [overview](/games/sdk/memory-advice/overview) for\n[additional resources](/games/sdk/memory-advice/overview#additional_resources)\nand [reporting issues](/games/sdk/memory-advice/overview#issues_and_feedback)."]]