The Memory Advice API beta is now deprecated, and no longer recommended for use.
Memory Advice API 使用入门
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
本指南介绍了如何使用 Android Studio 将 Memory Advice API 的 Jetpack 版本集成到您的应用中。
Android Games 应使用为其构建环境推荐的 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 Games 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 > 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()
函数加载自己的共享库时自动加载。
这是可选步骤。
在项目中找到加载原生库的 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
函数。
内存状态轮询
您可以通过按选择的时间间隔轮询库,来检索应用的内存状态。如果您需要轮询库,请使用 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,并在状态接近上限或紧急内存状态(但不适用于 ok 状态)时调用 watcher 函数。例如,以下代码会创建一个观察器并每 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 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-26。
[null,null,["最后更新时间 (UTC):2025-08-26。"],[],[],null,["# Get started with the Memory Advice API\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---------------\n\nThis section describes how to add the library to your Android Studio (Android\nGradle Plugin) project.\n\n### Add 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 [`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\n### Configure 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\n### Configure 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---------------\n\nThis section describes how to use the library.\n\n### Add the header files\n\nInclude the following library header file in your project: \n\n #include \u003cmemory_advice/memory_advice.h\u003e\n\n### Initialize 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\n### Poll 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\n### Set 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-----------\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)."]]