The Memory Advice API beta is now deprecated, and no longer recommended for use.
開始使用 Memory Advice API
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
本指南說明如何使用 Android Studio,在應用程式中整合 Memory Advice API 的 Jetpack 版本。
遊戲使用的 Memory Advice API 版本必須是建構環境的建議版本。如果使用 Android Studio,建議採用 Jetpack 版本。如要瞭解其他建構環境適用的 Android Game Development Extension (AGDE) 等版本,請參閱「發布情況」一節。
新增程式庫
本節說明如何將程式庫新增至 Android Studio (Android Gradle 外掛程式) 專案。
新增依附元件
如要將程式庫新增到 Android Studio 專案,請完成下列步驟:
在專案層級 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 版本。Android 遊戲 Jetpack 版本頁面提供支援的 NDK 版本清單。
宣告 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」>「primary」>「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()
函式載入該程式庫時自動載入。
此為選擇性步驟。
在專案中尋找載入原生程式庫的 Java 程式碼。如果找不到,請新增程式碼。程式碼應該與 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 程式庫,請務必將呼叫執行緒附加至 JavaVM,再呼叫 MemoryAdvice_init
函式。
記憶體狀態輪詢
以您選擇的時間間隔輪詢程式庫,即可擷取應用程式的記憶體狀態。每當您需要輪詢程式庫時,請使用 MemoryAdtip_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 Adtip 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);
後續步驟
請參閱總覽,瞭解其他資源以及如何回報問題。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-08-26 (世界標準時間)。
[null,null,["上次更新時間:2025-08-26 (世界標準時間)。"],[],[],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)."]]