面向 C++ 的 Play 游戏服务
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
在弃用 Google 登录 API 后,我们将于 2026 年移除 games v1 SDK。2025 年 2 月之后,您将无法在 Google Play 上发布新集成了 games v1 SDK 的游戏。我们建议您改用 games v2 SDK。
虽然采用旧版游戏 v1 集成的现有游戏仍可在未来几年内正常运行,但我们建议您从 2025 年 6 月开始迁移到 v2。
本指南介绍了如何使用 Play 游戏服务 v1 SDK。Play 游戏服务 v2 的 C++ SDK 尚未推出。
Google Play 游戏服务 C++ SDK 提供了可与 Google Play 游戏服务配合使用的 C++ API,专为已有 C++ 游戏实现的开发者而设计。
该 SDK 目前实现了以下服务:
- 授权
- 成就
- 排行榜
- 事件
- 游戏存档
- 附近连接(仅限 Android)
- 玩家统计信息
概念
大体上讲,您需要执行以下步骤来使用 SDK:
- 为 Android 设置平台配置。
- 使用
GameServices::Builder
配置和构建 GameServices
对象。GameServices
对象会自动尝试登录,并通过 OnAuthActionFinished()
回调返回结果。记下回调所返回的结果。如果自动登录尝试失败,您可以显示一个按钮供用户手动登录。
收到 OnAuthActionFinished()
结果后,您可以使用 GameServices
对象及其子对象管理器来进行 Play 游戏服务调用,包括:
- 登录(授权失败后):
StartAuthorizationUI()
- 解锁成就:
Achievements().Unlock()
- 使用内置界面显示成就:
Achievements().ShowAllUI()
- 提交最高得分:
Leaderboards().SubmitScore()
- 退出账号:
SignOut()
当您使用完 GameServices
对象时,请将其重置或销毁。
在更详细的级别:
初始化平台配置:这是一个包含平台特定初始化信息的对象。在 Android 上,平台配置包含 Java 虚拟机和指向当前 Activity
的指针:
// In android_main(), create a platform configuration
// and bind the object activity.
// Alternately, attach the activity in JNI_Onload().
gpg::AndroidPlatformConfiguration platform_configuration;
platform_configuration.SetActivity(state->activity->clazz);
构建一个 GameServices
对象:该对象是 Google Play 游戏服务功能的主要入口点。使用 GameServices::Builder
创建 GameServices
实例。
在大多数实现中,只要您的 C 环境持续存在,给定 GameServices
对象就会持续存在;在 Android Activity
暂停和恢复时,您无需重新初始化该对象。
// Creates a GameServices object that has lambda callbacks.
game_services_ = gpg::GameServices::Builder()
.SetDefaultOnLog(gpg::LogLevel::VERBOSE)
.SetOnAuthActionStarted([started_callback](gpg::AuthOperation op) {
is_auth_in_progress_ = true;
started_callback(op);
})
.SetOnAuthActionFinished([finished_callback](gpg::AuthOperation op,
gpg::AuthStatus status) {
LOGI("Sign in finished with a result of %d", status);
is_auth_in_progress_ = false;
finished_callback(op, status);
})
.Create(pc);
使用 Manager 类来管理 GameServices
对象。管理器可通过 GameServices
实例访问,用于将相关功能集合在一起,例如成就管理器和排行榜管理器。它们本身不含用户可见状态。管理器由引用返回,所含的 GameServices
实例可控制其生命周期。您的客户端绝不应保留管理器引用,而应保留 GameServices
实例。
管理器通过常量值类型的对象返回数据。这些值可一致地反映执行查询所对应时刻的基础数据情况。
// Submit a high score
game_services_->Leaderboards().SubmitScore(leaderboard_id, score);
// Show the default Achievements UI
game_services_->Achievements().ShowAllUI();
当您使用完 GameServices
对象后,通过以下方式进行清理:在拥有该对象的 unique_ptr
上调用 reset()
,或者在超出使用期限后让 unique_ptr
自动销毁它。
线程模型
除非另有说明,否则所有 GameServices
和 Manager 方法都拥有线程安全异步实现。它们可在任何线程上调用,无需外部锁定,并且执行顺序与其调用顺序一致。
访问器方法(读取状态的方法)具有两种主要变体。第一种方法(名称类似 FetchProperty()
)以异步方式将其结果提供给所提供的回调;第二种方法(名称类似 FetchPropertyBlocking()
)以同步方式将其结果返回给调用线程。
// Blocking callback
gpg::AchievementManager::FetchAllResponse fetchResponse =
game_services_->Achievements().FetchAllBlocking(std::chrono::milliseconds(1000));
// Non-blocking callback
game_services_->Achievements().FetchAll(gpg::DataSource::CACHE_OR_NETWORK,
[] (gpg::AchievementManager::FetchAllResponse response) {
LogI("Achievement response status: %d", response.status);});
所有用户回调均在一个专用回调线程上调用。该线程可能不同于“主线程”或“界面线程”的任何平台概念。您还应尽力确保用户回调能快速执行;回调线程停止可能会引起用户可见问题(例如,注销请求延迟完成)。
要开始在 Android 上使用 Play 游戏 C++ SDK,请继续阅读快速入门指南。
深入阅读
务必阅读 Google Play 游戏服务 C++ SDK 自带的类文档以了解更多详情,并查看演示 SDK 使用方法的示例。
如果您的游戏使用后端服务器,请参阅启用 Google Play 游戏服务的服务器端访问。
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-07-26。
[null,null,["最后更新时间 (UTC):2025-07-26。"],[],[],null,["# Play Games Services for C++\n\nFollowing the deprecation of the\n[Google Sign-In](https://android-developers.googleblog.com/2024/09/streamlining-android-authentication-credential-manager-replaces-legacy-apis.html)\nAPI, we are removing the games v1 SDK in 2026. After February 2025, you will be unable to publish\ntitles that are newly integrated with games v1 SDK, on Google Play. We recommend that you use the\ngames v2 SDK instead. \n\nWhile existing titles with the previous games v1 integrations continue to function for a\ncouple of years, you are encouraged to\n[migrate to v2](/games/pgs/android/migrate-to-v2)\nstarting June 2025. \n\nThis guide is for using the Play Games Services v1 SDK. The C++ SDK for\nPlay Games Services v2 is not yet available.\n\nThe Google Play games Services C++ SDK provides a C++ API for use with Google Play Game\nservices, and is meant for developers who have an existing C++ implementation\nof their game.\n\nCurrently, the SDK implements the following services:\n\n- Authorization\n- Achievements\n- Leaderboards\n- Events\n- Saved Games\n- Nearby Connections (Android only)\n- Player Statistics\n\nConcepts\n--------\n\nAt a high level, you use the SDK by following these steps:\n\n1. Set up a platform configuration for Android.\n2. Use a `GameServices::Builder` to configure and construct a `GameServices` object. The `GameServices` object automatically attempts to sign in, and returns the result via an `OnAuthActionFinished()` callback. Take note of the result returned by the callback. If the automatic sign-in attempt failed, you can display a button to let users sign in.\n3. After receiving the `OnAuthActionFinished()` result, you can use the\n `GameServices` object and its child Managers to make Play Games services calls,\n including:\n\n - Sign in (after authorization fails): `StartAuthorizationUI()`\n - Unlock achievements: `Achievements().Unlock()`\n - Show achievements using built-in UI: `Achievements().ShowAllUI()`\n - Submit a high score: `Leaderboards().SubmitScore()`\n - Sign out: `SignOut()`\n4. When you are done using the `GameServices` object, reset or destroy it.\n\nAt a more detailed level:\n\n1. Initialize a platform configuration: This is an object that contains\n platform-specific initialization information. On Android, the platform configuration contains the\n Java VM and a pointer to the current `Activity`:\n\n // In android_main(), create a platform configuration\n // and bind the object activity.\n // Alternately, attach the activity in JNI_Onload().\n gpg::AndroidPlatformConfiguration platform_configuration;\n platform_configuration.SetActivity(state-\u003eactivity-\u003eclazz);\n\n2. Construct a `GameServices` object: This object is the main entry point for\n Google Play games Services functionality. `GameServices` instances are created\n with `GameServices::Builder`.\n\n In most implementations, a given `GameServices` object will persist as long as\n your C environment does; you do not need to reinitialize it when your\n Android `Activity` pauses and resumes. \n\n // Creates a GameServices object that has lambda callbacks.\n game_services_ = gpg::GameServices::Builder()\n .SetDefaultOnLog(gpg::LogLevel::VERBOSE)\n .SetOnAuthActionStarted([started_callback](gpg::AuthOperation op) {\n is_auth_in_progress_ = true;\n started_callback(op);\n })\n .SetOnAuthActionFinished([finished_callback](gpg::AuthOperation op,\n gpg::AuthStatus status) {\n LOGI(\"Sign in finished with a result of %d\", status);\n is_auth_in_progress_ = false;\n finished_callback(op, status);\n })\n .Create(pc);\n\n3. Use the Manager classes to manage your `GameServices` object. Managers are accessed from a `GameServices` instance and group related functionality\n together. Examples of these\n include the Achievement and Leaderboard Managers. They contain no user-visible\n state themselves. Managers are returned by reference, and the containing\n `GameServices` instance controls their lifecycle. Your client should never hold\n onto a Manager reference. Instead, your client should hold on to the\n `GameServices` instance.\n\n Managers return data via immutable value type objects. These values\n reflect a consistent view of the underlying data at the point in time when\n the query was made. \n\n // Submit a high score\n game_services_-\u003eLeaderboards().SubmitScore(leaderboard_id, score);\n\n // Show the default Achievements UI\n game_services_-\u003eAchievements().ShowAllUI();\n\n4. When you are finished using the `GameServices` object, clean up by\n calling `reset()` on the `unique_ptr` that owns it, or by letting the\n `unique_ptr` automatically destroy it when going out of scope.\n\nThreading model\n---------------\n\nUnless otherwise noted, all `GameServices` and Manager methods have\nthread-safe, asynchronous implementations. They can be called on any thread without\nexternal locking, and will execute in an order consistent with their invocation\norder.\n\nAccessor methods (those that read state) come in two major variants. The first\ntype of method (with names like `FetchProperty()`) asynchronously supplies its results\nto a provided callback; the second (with names like\n`FetchPropertyBlocking()`) synchronously returns its results to the calling\nthread. \n\n // Blocking callback\n gpg::AchievementManager::FetchAllResponse fetchResponse =\n game_services_-\u003eAchievements().FetchAllBlocking(std::chrono::milliseconds(1000));\n\n // Non-blocking callback\n game_services_-\u003eAchievements().FetchAll(gpg::DataSource::CACHE_OR_NETWORK,\n [] (gpg::AchievementManager::FetchAllResponse response) {\n LogI(\"Achievement response status: %d\", response.status);});\n\nAll user callbacks are invoked on a dedicated callback thread. This thread is\npotentially distinct from any platform concept of a \"main thread\" or \"UI\nthread\". You should also try to ensure that user callbacks execute quickly; a stalled callback thread\nmay cause user-visible issues (for example, delayed completion of a sign-out\nrequest).\n\nPlatform-specific information\n-----------------------------\n\nTo get started using the Play Games C++ SDK on Android, continue to the\n[quickstart guide](/games/pgs/v1/cpp/quickstart).\n\nFurther reading\n---------------\n\nBe sure to read the class documentation that comes in the Google Play Game\nservices C++ SDK for further details, and check out the\n[samples](https://github.com/playgameservices/) that demonstrate how to use the SDK.\n\nIf your game uses a backend server, see\n[Enabling Server-Side Access to Google Play Games Services](/games/pgs/v1/android/server-access)."]]