C++ 適用的 Play 遊戲服務
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
隨著 Google Sign-In API 淘汰,我們將在 2026 年移除遊戲第 1 版 SDK。2025 年 2 月後,您將無法在 Google Play 上發布新整合 games v1 SDK 的遊戲。建議您改用 games v2 SDK。
雖然採用舊版遊戲第 1 版整合功能的現有遊戲仍可繼續運作幾年,但建議您從 2025 年 6 月開始遷移至第 2 版。
本指南適用於使用 Play 遊戲服務第 1 版 SDK。Play 遊戲服務第 2 版的 C++ SDK 尚未推出。
Google Play 遊戲服務 C++ SDK 提供 C++ API,可與 Google Play 遊戲服務搭配使用,適用於已實作遊戲 C++ 的開發人員。
目前 SDK 實作以下服務:
- 授權
- 成就
- 排行榜
- 事件
- 遊戲進度存檔
- Nearby Connections (僅限 Android)
- 玩家統計資料
概念
整體來說,您可以按照下列步驟使用 SDK:
- 為 Android 設定平台設定。
- 使用
GameServices::Builder
設定及建構 GameServices
物件。GameServices
物件會自動嘗試登入,並透過 OnAuthActionFinished()
回呼傳回結果。請注意回呼傳回的結果。如果自動登入失敗,您可以顯示按鈕,讓使用者登入。
收到 OnAuthActionFinished()
結果後,您可以使用 GameServices
物件及其子項管理工具,發出 Play 遊戲服務呼叫,包括:
- 登入 (授權失敗後):
StartAuthorizationUI()
- 解鎖成就:
Achievements().Unlock()
- 使用內建 UI 顯示成就:
Achievements().ShowAllUI()
- 提交最高分:
Leaderboards().SubmitScore()
- 登出:
SignOut()
使用 GameServices
物件完畢後,請重設或銷毀該物件。
更詳細的層級如下:
初始化平台設定:這是包含平台專屬初始化資訊的物件。在 Android 上,平台設定包含 Java VM 和目前 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
例項會使用 GameServices::Builder
建立。
在大多數實作中,只要 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()
上呼叫 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);});
所有使用者回呼都會在專用回呼執行緒中叫用。這個執行緒可能與「主執行緒」或「UI 執行緒」等任何平台概念不同。您也應盡量確保使用者回呼能快速執行;停止的回呼執行緒可能會導致使用者可見的問題 (例如登出要求完成時間延遲)。
如要開始在 Android 上使用 Play Games C++ SDK,請繼續參閱快速入門指南。
其他資訊
請務必參閱 Google Play 遊戲服務 C++ SDK 中提供的類別說明文件,進一步瞭解相關細節,並查看範例,瞭解如何使用 SDK。
如果您的遊戲使用後端伺服器,請參閱「啟用 Google Play 遊戲服務的伺服器端存取功能」。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-07-26 (世界標準時間)。
[null,null,["上次更新時間: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)."]]