Este documento descreve como migrar jogos do SDK para jogos v1 para o SDK para jogos v2.
Antes de começar
Você pode usar qualquer ambiente de desenvolvimento integrado de sua preferência, como o Android Studio, para migrar seu jogo. Conclua as etapas a seguir antes de migrar para a versão 2 dos jogos:
- Fazer o download e instalar o Android Studio
- Seu jogo precisa usar o SDK v1
Atualizar as dependências
No arquivo
build.gradle
do módulo, encontre esta linha nas dependências do módulo.implementation "com.google.android.gms:play-services-games-v1:+"
Substitua por este código:
implementation "com.google.android.gms:play-services-games-v2:version"
Substitua version pela versão mais recente do SDK do Google Play Games.
Depois de atualizar as dependências, conclua todas as etapas deste documento.
Migrar do Login do Google descontinuado
Substitua a classe GoogleSignInClient
pela classe GamesSignInClient
.
Java
Localize os arquivos com a classe GoogleSignInClient
.
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
// ... existing code
@Override
public void onCreate(@Nullable Bundle bundle) {
super.onCreate(bundle);
// ... existing code
val signInOptions = GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN
// Client used to sign in to Google services
GoogleSignInClient googleSignInClient =
GoogleSignIn.getClient(this, signInOptions);
}
E atualize para o seguinte:
import com.google.android.gms.games.PlayGamesSdk;
import com.google.android.gms.games.PlayGames;
import com.google.android.gms.games.GamesSignInClient;
// ... existing code
@Override
public void onCreate(){
super.onCreate();
// Client used to sign in to Google services
GamesSignInClient gamesSignInClient =
PlayGames.getGamesSignInClient(getActivity());
}
Kotlin
Localize os arquivos com a classe GoogleSignInClient
.
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
// ... existing code
val signInOptions = GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN
// ... existing code
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val googleSignInClient: GoogleSignInClient =
GoogleSignIn.getClient(this, signInOptions)
}
E atualize para o seguinte:
import com.google.android.gms.games.PlayGames
import com.google.android.gms.games.PlayGamesSdk
import com.google.android.gms.games.GamesSignInClient
// ... existing code
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
PlayGamesSdk.initialize(this)
// client used to sign in to Google services
val gamesSignInClient: GamesSignInClient =
PlayGames.getGamesSignInClient(this)
}
Atualizar o código GoogleSignIn
A API GoogleSignIn
e os escopos não são compatíveis com o SDK v2 dos jogos. Substitua o código da API GoogleSignIn
para escopos do OAuth 2.0 pela
API GamesSignInClient
,
conforme mostrado no exemplo a seguir:
Java
Localize os arquivos com a classe e os escopos GoogleSignIn
.
// Request code used when invoking an external activity.
private static final int RC_SIGN_IN = 9001;
private boolean isSignedIn() {
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
GoogleSignInOptions signInOptions =
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN;
return GoogleSignIn.hasPermissions(account, signInOptions.getScopeArray());
}
private void signInSilently() {
GoogleSignInOptions signInOptions =
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN;
GoogleSignInClient signInClient = GoogleSignIn.getClient(this, signInOptions);
signInClient
.silentSignIn()
.addOnCompleteListener(
this,
task -> {
if (task.isSuccessful()) {
// The signed-in account is stored in the task's result.
GoogleSignInAccount signedInAccount = task.getResult();
showSignInPopup();
} else {
// Perform interactive sign in.
startSignInIntent();
}
});
}
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, RC_SIGN_IN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result =
Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// The signed-in account is stored in the result.
GoogleSignInAccount signedInAccount = result.getSignInAccount();
showSignInPopup();
} else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
message = getString(R.string.signin_other_error);
}
new AlertDialog.Builder(this).setMessage(message)
.setNeutralButton(android.R.string.ok, null).show();
}
}
}
private void showSignInPopup() {
Games.getGamesClient(requireContext(), signedInAccount)
.setViewForPopups(contentView)
.addOnCompleteListener(
task -> {
if (task.isSuccessful()) {
logger.atInfo().log("SignIn successful");
} else {
logger.atInfo().log("SignIn failed");
}
});
}
E atualize para o seguinte:
private void signInSilently() {
gamesSignInClient.isAuthenticated().addOnCompleteListener(isAuthenticatedTask -> {
boolean isAuthenticated =
(isAuthenticatedTask.isSuccessful() &&
isAuthenticatedTask.getResult().isAuthenticated());
if (isAuthenticated) {
// Continue with Play Games Services
} else {
// If authentication fails, either disable Play Games Services
// integration or
// display a login button to prompt players to sign in.
// Use`gamesSignInClient.signIn()` when the login button is clicked.
}
});
}
@Override
protected void onResume() {
super.onResume();
// When the activity is inactive, the signed-in user's state can change;
// therefore, silently sign in when the app resumes.
signInSilently();
}
Kotlin
Localize os arquivos com a classe e os escopos GoogleSignIn
.
// Request codes we use when invoking an external activity.
private val RC_SIGN_IN = 9001
// ... existing code
private fun isSignedIn(): Boolean {
val account = GoogleSignIn.getLastSignedInAccount(this)
val signInOptions = GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN
return GoogleSignIn.hasPermissions(account, *signInOptions.scopeArray)
}
private fun signInSilently() {
val signInOptions = GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN
val signInClient = GoogleSignIn.getClient(this, signInOptions)
signInClient.silentSignIn().addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// The signed-in account is stored in the task's result.
val signedInAccount = task.result
// Pass the account to showSignInPopup.
showSignInPopup(signedInAccount)
} else {
// Perform interactive sign in.
startSignInIntent()
}
}
}
private fun startSignInIntent() {
val signInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
val intent = signInClient.signInIntent
startActivityForResult(intent, RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
if (result.isSuccess) {
// The signed-in account is stored in the result.
val signedInAccount = result.signInAccount
showSignInPopup(signedInAccount) // Pass the account to showSignInPopup.
} else {
var message = result.status.statusMessage
if (message == null || message.isEmpty()) {
message = getString(R.string.signin_other_error)
}
AlertDialog.Builder(this)
.setMessage(message)
.setNeutralButton(android.R.string.ok, null)
.show()
}
}
}
private fun showSignInPopup(signedInAccount: GoogleSignInAccount) {
// Add signedInAccount parameter.
Games.getGamesClient(this, signedInAccount)
.setViewForPopups(contentView) // Assuming contentView is defined.
.addOnCompleteListener { task ->
if (task.isSuccessful) {
logger.atInfo().log("SignIn successful")
} else {
logger.atInfo().log("SignIn failed")
}
}
}
E atualize para o seguinte:
private fun signInSilently() {
gamesSignInClient.isAuthenticated.addOnCompleteListener { isAuthenticatedTask ->
val isAuthenticated = isAuthenticatedTask.isSuccessful &&
isAuthenticatedTask.result.isAuthenticated
if (isAuthenticated) {
// Continue with Play Games Services
} else {
// To handle a user who is not signed in, either disable Play Games Services integration
// or display a login button. Selecting this button calls `gamesSignInClient.signIn()`.
}
}
}
override fun onResume() {
super.onResume()
// Since the state of the signed in user can change when the activity is
// not active it is recommended to try and sign in silently from when the
// app resumes.
signInSilently()
}
Adicionar o código GamesSignInClient
Se o jogador tiver feito login, remova o botão de login dos Serviços relacionados a jogos do
Google Play do jogo. Se o usuário optar por não fazer login quando o jogo for iniciado,
continue mostrando um botão com o ícone dos Serviços relacionados a jogos do Google Play
e inicie o processo de login com
GamesSignInClient.signIn()
.
Java
private void startSignInIntent() {
gamesSignInClient
.signIn()
.addOnCompleteListener( task -> {
if (task.isSuccessful() && task.getResult().isAuthenticated()) {
// sign in successful
} else {
// sign in failed
}
});
}
Kotlin
private fun startSignInIntent() {
gamesSignInClient
.signIn()
.addOnCompleteListener { task ->
if (task.isSuccessful && task.result.isAuthenticated) {
// sign in successful
} else {
// sign in failed
}
}
}
Remover código de desativação
Remova o código de GoogleSignInClient.signOut
.
Remova o código mostrado no exemplo abaixo:
Java
// ... existing code
private void signOut() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
signInClient.signOut().addOnCompleteListener(this,
new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
// At this point, the user is signed out.
}
});
}
Kotlin
// ... existing code
private fun signOut() {
val signInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
signInClient.signOut().addOnCompleteListener(this) {
// At this point, the user is signed out.
}
}
Verificar o login automático bem-sucedido
Inclua o código abaixo para verificar se você fez login automaticamente e adicione a lógica personalizada, se disponível.
Java
private void checkIfAutomaticallySignedIn() {
gamesSignInClient.isAuthenticated().addOnCompleteListener(isAuthenticatedTask -> {
boolean isAuthenticated =
(isAuthenticatedTask.isSuccessful() &&
isAuthenticatedTask.getResult().isAuthenticated());
if (isAuthenticated) {
// Continue with Play Games Services
// If your game requires specific actions upon successful sign-in,
// you can add your custom logic here.
// For example, fetching player data or updating UI elements.
} else {
// Disable your integration with Play Games Services or show a
// login button to ask players to sign-in. Clicking it should
// call GamesSignInClient.signIn().
}
});
}
Kotlin
private void checkIfAutomaticallySignedIn() {
gamesSignInClient.isAuthenticated()
.addOnCompleteListener { task ->
val isAuthenticated = task.isSuccessful && task.result?.isAuthenticated ?: false
if (isAuthenticated) {
// Continue with Play Games Services
} else {
// Disable your integration or show a login button
}
}
}
Atualizar nomes e métodos de classes do cliente
Quando você migra para a versão 2 dos jogos, os métodos usados para extrair os nomes das classes de cliente
são diferentes.
Use os métodos
PlayGames.getxxxClient()
correspondentes em vez dos
Games.getxxxClient()
.
Por exemplo, para
LeaderboardsClient
,
use PlayGames.getLeaderboardsClient()
em vez do
método Games.getLeaderboardsClient()
.
Java
Localize o código de LeaderboardsClient
.
import com.google.android.gms.games.LeaderboardsClient;
import com.google.android.gms.games.Games;
@Override
public void onCreate(@Nullable Bundle bundle) {
super.onCreate(bundle);
// Get the leaderboards client using Play Games services.
LeaderboardsClient leaderboardsClient = Games.getLeaderboardsClient(this,
GoogleSignIn.getLastSignedInAccount(this));
}
E atualize para o seguinte:
import com.google.android.gms.games.LeaderboardsClient;
import com.google.android.gms.games.PlayGames;
@Override
public void onCreate(@Nullable Bundle bundle) {
super.onCreate(bundle);
// Get the leaderboards client using Play Games services.
LeaderboardsClient leaderboardsClient = PlayGames.getLeaderboardsClient(getActivity());
}
Kotlin
Localize o código de LeaderboardsClient
.
import com.google.android.gms.games.LeaderboardsClient
import com.google.android.gms.games.Games
// Initialize the variables.
private lateinit var leaderboardsClient: LeaderboardsClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
leaderboardsClient = Games.getLeaderboardsClient(this,
GoogleSignIn.getLastSignedInAccount(this))
}
E atualize para o seguinte:
import com.google.android.gms.games.LeaderboardsClient
import com.google.android.gms.games.PlayGames
// Initialize the variables.
private lateinit var leaderboardsClient: LeaderboardsClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
leaderboardsClient = PlayGames.getLeaderboardsClient(this)
}
Da mesma forma, use os métodos correspondentes para os seguintes clientes:
AchievementsClient
, EventsClient
, GamesSignInClient
,
PlayerStatsClient
, RecallClient
, SnapshotsClient
ou PlayersClient
.
Atualizar as classes de acesso do lado do servidor
Para solicitar um token de acesso do lado do servidor, use o método
GamesSignInClient.requestServerSideAccess()
em vez do método
GoogleSignInAccount.getServerAuthCode()
.
O exemplo a seguir mostra como solicitar um token de acesso do lado do servidor.
Java
Localize o código da classe GoogleSignInOptions
.
private static final int RC_SIGN_IN = 9001;
private GoogleSignInClient googleSignInClient;
private void startSignInForAuthCode() {
/** Client ID for your backend server. */
String webClientId = getString(R.string.webclient_id);
GoogleSignInOptions signInOption = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestServerAuthCode(webClientId)
.build();
GoogleSignInClient signInClient = GoogleSignIn.getClient(this, signInOption);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, RC_SIGN_IN);
}
/** Auth code to send to backend server */
private String mServerAuthCode;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
mServerAuthCode = result.getSignInAccount().getServerAuthCode();
} else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
message = getString(R.string.signin_other_error);
}
new AlertDialog.Builder(this).setMessage(message)
.setNeutralButton(android.R.string.ok, null).show();
}
}
}
E atualize para o seguinte:
private void startRequestServerSideAccess() {
GamesSignInClient gamesSignInClient = PlayGames.getGamesSignInClient(this);
gamesSignInClient
.requestServerSideAccess(OAUTH_2_WEB_CLIENT_ID, /* forceRefreshToken= */ false)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
String serverAuthToken = task.getResult();
// Send authentication code to the backend game server.
// Exchange for an access token.
// Verify the player with Play Games Services REST APIs.
} else {
// Authentication code retrieval failed.
}
});
}
Kotlin
Localize o código da classe GoogleSignInOptions
.
// ... existing code
private val RC_SIGN_IN = 9001
private lateinit var googleSignInClient: GoogleSignInClient
// Auth code to send to backend server.
private var mServerAuthCode: String? = null
private fun startSignInForAuthCode() {
// Client ID for your backend server.
val webClientId = getString(R.string.webclient_id)
val signInOption = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestServerAuthCode(webClientId)
.build()
googleSignInClient = GoogleSignIn.getClient(this, signInOption)
val intent = googleSignInClient.signInIntent
startActivityForResult(intent, RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
if (result.isSuccess) {
mServerAuthCode = result.signInAccount.serverAuthCode
} else {
var message = result.status.statusMessage
if (message == null || message.isEmpty()) {
message = getString(R.string.signin_other_error)
}
AlertDialog.Builder(this).setMessage(message)
.setNeutralButton(android.R.string.ok, null).show()
}
}
}
E atualize para o seguinte:
private void startRequestServerSideAccess() {
GamesSignInClient gamesSignInClient = PlayGames.getGamesSignInClient(this);
gamesSignInClient
.requestServerSideAccess(OAUTH_2_WEB_CLIENT_ID, /* forceRefreshToken= */ false)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
String serverAuthToken = task.getResult();
// Send authentication code to the backend game server.
// Exchange for an access token.
// Verify the player with Play Games Services REST APIs.
} else {
// Authentication code retrieval failed.
}
});
}
Migrar do GoogleApiClient
Para integrações existentes mais antigas, seu jogo pode depender da
variação da API GoogleApiClient
do SDK dos Serviços relacionados a jogos do Google Play. Ela foi
descontinuada no final de 2017
e substituída por clientes "sem conexão". Para migrar, substitua a
classe GoogleApiClient
por um equivalente "sem conexão".
Confira um mapeamento de classes comuns:
games v2
// Replace com.google.android.gms.games.achievement.Achievements
com.google.android.gms.games.AchievementsClient
// Replace com.google.android.gms.games.leaderboard.Leaderboard
com.google.android.gms.games.LeaderboardsClient
// Replace com.google.android.gms.games.snapshot.Snapshots
com.google.android.gms.games.SnapshotsClient
// Replace com.google.android.gms.games.stats.PlayerStats
com.google.android.gms.games.PlayerStatsClient
// Replace com.google.android.gms.games.Players
com.google.android.gms.games.PlayersClient
// Replace com.google.android.gms.games.GamesStatusCodes
com.google.android.gms.games.GamesClientStatusCodes
games v1
com.google.android.gms.games.achievement.Achievements
com.google.android.gms.games.leaderboard.Leaderboard
com.google.android.gms.games.snapshot.Snapshots
com.google.android.gms.games.stats.PlayerStats
com.google.android.gms.games.Players
com.google.android.gms.games.GamesStatusCodes
Criar e executar o jogo
Para criar e executar no Android Studio, consulte Criar e executar o app.
Testar o jogo
Teste o jogo para garantir que ele funcione como planejado. Os testes que você realiza dependem dos recursos do jogo.
Confira a seguir uma lista de testes comuns a serem executados.
Login concluído.
O login automático funciona. O usuário precisa estar conectado aos Serviços relacionados a jogos do Google Play ao iniciar o jogo.
O pop-up de boas-vindas é exibido.
Exemplo de pop-up de boas-vindas (clique para ampliar). As mensagens de registro bem-sucedidas são exibidas. Execute o seguinte comando no terminal:
adb logcat | grep com.google.android.
Uma mensagem de registro bem-sucedida é mostrada no exemplo a seguir:
[
$PlaylogGamesSignInAction$SignInPerformerSource@e1cdecc number=1 name=GAMES_SERVICE_BROKER>], returning true for shouldShowWelcomePopup. [CONTEXT service_id=1 ]
Garantir a consistência dos componentes da interface.
Pop-ups, placares e conquistas são exibidos corretamente e de forma consistente em vários tamanhos e orientações de tela na interface do usuário (IU) dos serviços relacionados a jogos do Google Play.
A opção de encerramento de sessão não aparece na interface dos Serviços relacionados a jogos do Google Play.
Verifique se você consegue recuperar o ID do jogador e, se aplicável, se os recursos do lado do servidor funcionam conforme o esperado.
Se o jogo usar autenticação do lado do servidor, teste completamente o fluxo
requestServerSideAccess
. Verifique se o servidor recebe o código de autenticação e pode trocá-lo por um token de acesso. Teste cenários de sucesso e de falha para erros de rede e cenários inválidos declient ID
.
Se o jogo usava algum dos recursos abaixo, teste-os para garantir que eles funcionem da mesma forma que antes da migração:
- Placares: envie pontuações e confira os placares. Verifique se a classificação e a exibição dos nomes e pontuações dos jogadores estão corretas.
- Conquistas: desbloqueie conquistas e verifique se elas são gravadas e exibidas corretamente na interface do Google Play Games.
- Jogos salvos: se o jogo usa jogos salvos, verifique se o salvamento e o carregamento do progresso do jogo funcionam perfeitamente. Isso é especialmente importante para testar em vários dispositivos e após atualizações do app.
Tarefas pós-migração
Conclua as etapas a seguir depois de migrar para a versão 2 dos jogos.
Publicar o jogo
Crie os APKs e publique o jogo no Play Console.
- No menu do Android Studio, selecione Build > Build Bundles / APKs > Build APKs.
- Publicar o jogo. Para mais informações, consulte Publicar apps particulares no Play Console.