Introdução aos serviços relacionados a jogos do Google Play para C++ no Android
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Após a descontinuação da
API Google Sign-In, vamos remover o SDK v1 de jogos em 2026. A partir de fevereiro de 2025, não será mais possível publicar
títulos recém-integrados ao SDK v1 para jogos no Google Play. Recomendamos que você use o
SDK v2 para jogos.
Embora os títulos atuais com as integrações anteriores dos jogos da v1 continuem funcionando por
alguns anos, recomendamos que você
migre para a v2
a partir de junho de 2025.
Este guia é para usar o SDK dos serviços relacionados a jogos do Google Play v1. O SDK C++ para
os serviços relacionados a jogos do Google Play v2 ainda não está disponível.
Este guia para desenvolvedores mostra como compilar e executar um jogo C++ no Android que usa a API Google Play
Game Services. Antes de começar, faça o download e configure os seguintes requisitos:
Este guia para desenvolvedores usa o Kit de desenvolvimento nativo do Android (NDK). Se você não conhece o NDK,
consulte a documentação e exemplos do NDK
antes de continuar.
Etapa 1: configurar o ambiente
Faça o download do SDK do Android e do NDK do Android e extraia-os para sua máquina. No
ambiente, defina SDK_ROOT como o local da pasta do SDK do Android e NDK_ROOT como o
local da pasta do NDK do Android.
Faça o download dos exemplos de jogos em C++. Este
guia para desenvolvedores se refere ao local das amostras na sua máquina como SAMPLES_DIR.
Faça o download do SDK para C++ dos serviços relacionados a jogos do Google Play. Extraia o
SDK na sua máquina de desenvolvimento. No seu ambiente, defina a variável NDK_MODULE_PATH para
apontar para o diretório acima do diretório gpg-cpp-sdk. Você terá a seguinte
estrutura de diretórios:
NDK_MODULE_PATH/
gpg-cpp-sdk/
Abra o Eclipse. Se ainda não fez isso, informe ao Eclipse onde você instalou o NDK
clicando em Preferences > Android > NDK.
Importe o projeto da biblioteca do Google Play Services para o espaço de trabalho do Eclipse.
No Eclipse, clique em File > Import > Android > Existing Android Code into Workspace.
Selecione SDK_ROOT/extras/google/google_play_services/libproject/google-play-services_lib,
em que SDK_ROOT é o local do SDK do Android.
Clique em Finish.
Importe o projeto de exemplo minimalista para o espaço de trabalho do Eclipse.
No Eclipse, clique em File > Import > Android > Existing Android Code into Workspace.
Selecione SAMPLES_DIR/samples-android/minimalist.
Clique em Finish.
Clique com o botão direito do mouse no projeto MinimalistActivity e clique em Properties. Em Android, role
a tela para baixo até a seção Library e verifique se o projeto google-play-services_lib está corretamente
referenciado. Se não, remova a referência e adicione novamente no seu espaço de trabalho.
O Eclipse compila automaticamente as origens Java e Android do seu projeto. No entanto, o
código nativo na pasta jni precisa ser compilado separadamente. Para fazer isso manualmente, navegue até
a pasta jni e execute ndk-build. Faça isso depois de fazer mudanças na
pasta jni.
Seu projeto vai ser compilado, mas ainda não vai funcionar. Primeiro, configure seu jogo
no Google Play Console.
Etapa 2: configurar o jogo no Google Play Console
Crie uma entrada para o jogo no Google Play Console. Isso ativa os serviços relacionados a jogos para seu
app e cria um ID do cliente OAuth 2.0, se você ainda não tiver um.
Em AndroidManifest.xml, mude o atributo package da tag <manifest> para o
nome do pacote escolhido ao configurar o Google Play Console. Talvez seja necessário corrigir algumas referências
no projeto depois de fazer essa mudança, principalmente na classe R gerada.
Abra res/values/ids.xml e coloque seu ID do app. O ID do app não é o mesmo que
o ID do cliente. Ele é o número ao lado do nome do jogo na página Detalhes do jogo do
Google Play Console.
Etapa 3: executar a amostra
Para executar o exemplo, você vai precisar de um dispositivo Android físico ou um emulador com
o Google Play Services instalado:
Execute ndk-build para compilar o código nativo.
No Eclipse, clique em Run > Run As > Android Application e execute o exemplo no seu dispositivo.
Quando a amostra abrir, toque em qualquer lugar da tela. O logotipo do Google Play Games vai aparecer. Se você tiver configurado o app corretamente, será necessário fazer login.
Opcional: criar automaticamente com o Eclipse
As etapas a seguir mostram como configurar o Eclipse para executar ndk-build automaticamente quando você
faz alterações nos arquivos na pasta jni.
Clique com o botão direito do mouse no projeto MinimalistActivity e clique em Properties. Na janela "Propriedades",
selecione o painel Builders.
Clique em Novo para adicionar um novo Builder e selecione Program. Em seguida, clique em OK.
No campo Nome, digite "NDK Builder".
Em Local, clique em Procurar sistema de arquivos, navegue até o diretório NDK_ROOT e
selecione o comando ndk-build.
Em Working Directory, clique em Browse Workspace e selecione a pasta do projeto
MinimalistActivity.
Clique na guia Atualizar. Confira se a caixa Refresh resources upon completion (Atualizar recursos após a conclusão) está marcada.
Selecione o botão de opção Recursos específicos e clique em Especificar recursos. Na
caixa de diálogo resultante, selecione a pasta jni em MinimalActivity.
Clique em Aplicar e em OK para concluir a criação do Builder.
Agora, sempre que você editar um arquivo na pasta jni, o Eclipse vai executar ndk-build e imprimir a
saída no console do Eclipse.
O conteúdo e os exemplos de código nesta página estão sujeitos às licenças descritas na Licença de conteúdo. Java e OpenJDK são marcas registradas da Oracle e/ou suas afiliadas.
Última atualização 2025-07-27 UTC.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Não contém as informações de que eu preciso","missingTheInformationINeed","thumb-down"],["Muito complicado / etapas demais","tooComplicatedTooManySteps","thumb-down"],["Desatualizado","outOfDate","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Problema com as amostras / o código","samplesCodeIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-07-27 UTC."],[],[],null,["# Get Started with Play Games Services for C++ on Android\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\nThis developer guide will show you how to compile and run a C++ game on Android that uses the Google Play\nGame services API. Before you begin, download and configure the following requirements:\n\n- [Android NDK](/ndk), Revision 14 or higher.\n- [Android SDK v10 or higher and latest version of the Eclipse ADT](/studio/tools/sdk/eclipse-adt).\n- Device must be running Android 4.0 (API level 14) or higher.\n- [The latest version of the Google Play services SDK.](https://developers.google.com/android/guides/setup)\n\nThis developer guide uses the Android Native Development Kit (NDK). If you are unfamiliar with the NDK,\nrefer to the [NDK documentation and samples](/ndk)\nbefore continuing.\n\nStep 1: Set up your environment\n-------------------------------\n\n1. Download the Android SDK and the Android NDK and extract them to your machine. In your environment, set `SDK_ROOT` to the location of your Android SDK folder and `NDK_ROOT` to the location of your Android NDK folder.\n2. Download the [C++ sample games](//github.com/playgameservices/cpp-android-basic-samples). This developer guide refers to the location of the samples on your machine as `SAMPLES_DIR`.\n3. Download the [Google Play Games services C++ SDK](/games/pgs/downloads#sdk). Extract the SDK onto your development machine. In your environment, set the variable `NDK_MODULE_PATH` to point to the directory **above** the `gpg-cpp-sdk` directory. You should have the following directory structure: \n\n ```\n NDK_MODULE_PATH/\n gpg-cpp-sdk/\n ```\n4. Open Eclipse. If you have not already done so, tell Eclipse where you installed the NDK by clicking **Preferences \\\u003e Android \\\u003e NDK**.\n5. Import the Google Play services library project into your Eclipse workspace.\n\n 1. In Eclipse, click **File \\\u003e Import \\\u003e Android \\\u003e Existing Android Code into Workspace**.\n 2. Select `SDK_ROOT/extras/google/google_play_services/libproject/google-play-services_lib` where `SDK_ROOT` is the location of your Android SDK.\n 3. Click **Finish**.\n6. Import the minimalist sample project into your Eclipse workspace.\n\n 1. In Eclipse, click **File \\\u003e Import \\\u003e Android \\\u003e Existing Android Code into Workspace**.\n 2. Select `SAMPLES_DIR/samples-android/minimalist`.\n 3. Click **Finish**.\n7. Right click the MinimalistActivity project and click **Properties** . Under **Android** , scroll\n down to the **Library** section and make sure the google-play-services_lib project is correctly\n referenced. If not, remove the reference and add it again from your workspace.\n\nEclipse will automatically compile the Java and Android sources of your project; however, the\nnative code in the `jni` folder needs to be compiled separately. To do this manually, navigate to\nthe `jni` folder and run `ndk-build`. Remember to do this after you make any changes inside\nthe `jni` folder.\n\nYour project should now compile, though it will not work yet. You must first configure your game\nin the Google Play Console.\n\nStep 2: Set up the game in the Google Play Console\n--------------------------------------------------\n\nCreate an entry for your game in the Google Play Console. This enables Games services for your\napplication, and creates an OAuth 2.0 client ID, if you don't already have one.\n\n1. Create an entry for your game by following the steps described in [Setting Up Google Play Games Services](/games/pgs/console/setup).\n2. In `AndroidManifest.xml`, change the `package` attribute of the `\u003cmanifest\u003e` tag to the package name you chose when setting up the Google Play Console. You may have to fix some references throughout the project after making this change (particularly to the generated `R` class).\n3. Open `res/values/ids.xml` and place your App ID there. Note that the App ID is not the same as the client ID; it is the number next to the name of your game in the **Game Details** page of the Google Play Console.\n\nStep 3: Run the sample\n----------------------\n\nIn order to run the sample you will need a physical Android device or an emulator with\nGoogle Play services installed:\n\n1. Run `ndk-build` to compile the native code.\n2. In Eclipse, click **Run \\\u003e Run As \\\u003e Android Application** and run the sample on your device.\n3. When the sample opens, tap anywhere on the screen. You should see a Google Play Games logo appear. If you have correctly configured your app, you will be prompted to sign in.\n\n| **Important:** Make sure to sign your APK with the same certificate as the one whose fingerprint you configured on Google Play Console. Failure to do so will produce errors.\n| **Important:** If you are testing an unpublished game, make sure that the account with which you intend to sign in (usually, the account on the test device) is listed as a tester in the project. Open the **Testing** page, in the **Game services** subtab of the Google Play Console, to check or perform whitelisting. Failure to perform this step causes the server to act as though your project does not exist, and return errors.\n\nOptional: Build automatically with Eclipse\n------------------------------------------\n\nThe following steps show you how to configure Eclipse to automatically run `ndk-build` when you\nmake changes to files in the `jni` folder.\n\n1. Right-click the MinimalistActivity project and click **Properties** . In the Properties window, select the **Builders** pane.\n2. Click **New** to add a new Builder and select **Program** then click **OK**.\n3. In the **Name** field, enter 'NDK Builder'.\n4. Under **Location** click **Browse File System** and navigate to the `NDK_ROOT` directory and select the `ndk-build` command.\n5. Under **Working Directory** click **Browse Workspace** and select the MinimalistActivity project folder.\n6. Click the **Refresh** tab. Make sure the **Refresh resources upon completion** box is checked.\n7. Select the **Specific resources** radio button and then click **Specify Resources** . In the resulting dialog, select the `jni` folder under MinimalActivity.\n8. Click **Apply** and then **OK** to finish creating your Builder.\n\nNow every time you edit a file within the `jni` folder, Eclipse will run `ndk-build` and print the\noutput to the Eclipse Console.\n| **Note:** If you see errors when editing C or C++ files in Eclipse that prevent you from building the project, you may want to disable C/C++ error reporting in Eclipse. In your project properties, navigate to **C/C++ General \\\u003e Code Analysis \\\u003e Launching** and make sure that both boxes are unchecked. Then click **Apply** and **OK** . This is a workaround to prevent Eclipse from checking your native code, it does **not** fix any real underlying errors you may have."]]