Migracja do Usług gier Play w wersji 2 (Java lub Kotlin)

Z tego dokumentu dowiesz się, jak przenieść istniejące gry z pakietu SDK gier w wersji 1 do pakietu SDK gier w wersji 2.

Zanim zaczniesz

Do przeniesienia gry możesz użyć dowolnego preferowanego środowiska IDE, np. Android Studio. Zanim przejdziesz na wersję 2 usług gier, wykonaj te czynności:

Aktualizowanie zależności

  1. W pliku build.gradle modułu odszukaj ten wiersz w poziomie modułu zależności.

    implementation "com.google.android.gms:play-services-games-v1:+"

    Zastąp go tym kodem:

    implementation "com.google.android.gms:play-services-games-v2:version"

    Zastąp version najnowszą wersją pakietu SDK gier.

  2. Po zaktualizowaniu zależności wykonaj wszystkie czynności opisane w tym dokumencie.

Migracja z wycofanego logowania przez Google

Zastąp klasę GoogleSignInClient klasą GamesSignInClient.

Java

Znajdź pliki z klasą 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);
}

Zmień go na:

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

Znajdź pliki z klasą 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)
}

Zmień go na:

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)
}

Zaktualizuj kod GoogleSignIn

Interfejs GoogleSignIn API i zakresy nie są obsługiwane w pakiecie SDK gier w wersji 2. Zastąp kod interfejsu API GoogleSignIn w przypadku zakresów OAuth 2.0 kodem interfejsu API GamesSignInClient, jak pokazano w tym przykładzie:

Java

Znajdź pliki z klasą i zakresem 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");
            }
        });
  }

Zmień go na:

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

Znajdź pliki z klasą i zakresem 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")
        }
    }
}

Zmień go na:

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()
}

Dodaj kod GamesSignInClient

Jeśli gracz się zaloguje, usuń z gry przycisk logowania w usługach gier Play. Jeśli użytkownik zdecyduje się nie logować podczas uruchamiania gry, nadal wyświetlaj przycisk z ikoną usług gier Play i rozpocznij proces logowania za pomocą 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
            }
        }
  }

Usuwanie kodu wylogowywania

Usuń kod GoogleSignInClient.signOut.

Usuń kod pokazany w tym przykładzie:

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.
    }
}

Sprawdzanie, czy automatyczne logowanie się powiodło

Użyj tego kodu, aby sprawdzić, czy logowanie zostało wykonane automatycznie, i w razie potrzeby dodaj logikę niestandardową.

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
        }
    }
}

Zmienianie nazw i metod klasy klienta

Podczas migracji do wersji 2 usług gier metody używane do uzyskiwania nazw klas klienta są inne. Zamiast metod Games.getxxxClient() używaj odpowiednich metod PlayGames.getxxxClient().

Na przykład w przypadku kolumny LeaderboardsClient użyj operatora PlayGames.getLeaderboardsClient() zamiast metody Games.getLeaderboardsClient().

Java

Znajdź kod 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));
}

Zmień go na:

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

Znajdź kod 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))
}

Zmień go na:

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)
}

Podobnie używaj odpowiednich metod w przypadku tych klientów: AchievementsClient, EventsClient, GamesSignInClient, PlayerStatsClient, RecallClient, SnapshotsClient lub PlayersClient.

Zaktualizuj klasy dostępu po stronie serwera

Aby poprosić o token dostępu po stronie serwera, użyj metody GamesSignInClient.requestServerSideAccess(), a nie metody GoogleSignInAccount.getServerAuthCode().

Ten przykład pokazuje, jak poprosić o token dostępu po stronie serwera.

Java

Znajdź kod zajęć 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();
        }
      }
    }
  

Zmień go na:

  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

Znajdź kod zajęć 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()
            }
        }
  }
  

Zmień go na:

  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.
              }
        });
  }
  

Migracja z GoogleApiClient

W przypadku starszych, istniejących integracji gra może być zależna od GoogleApiClientwersji interfejsu API pakietu SDK usług gier Play. Został on wycofany pod koniec 2017 r. i zastąpiony przez klientów „bez połączenia”. Aby przeprowadzić migrację, możesz zastąpić klasę GoogleApiClient jej odpowiednikiem „bez połączenia”. W tabeli poniżej znajdziesz listę typowych mapowań klas z wersji 1 na wersję 2:

gry v2 (obecna), gry w wersji 1 (starsza wersja),
com.google.android.gms.games.AchievementsClient com.google.android.gms.games.achievement.Achievements
com.google.android.gms.games.LeaderboardsClient com.google.android.gms.games.leaderboard.Leaderboard
com.google.android.gms.games.SnapshotsClient com.google.android.gms.games.snapshot.Snapshots
com.google.android.gms.games.PlayerStatsClient com.google.android.gms.games.stats.PlayerStats
com.google.android.gms.games.PlayersClient com.google.android.gms.games.Players
com.google.android.gms.games.GamesClientStatusCodes com.google.android.gms.games.GamesStatusCodes

Tworzenie i uruchamianie gry

Aby kompilować i uruchamiać aplikację w Android Studio, zapoznaj się z artykułem Tworzenie i uruchamianie aplikacji.

Testowanie gry

Przetestuj grę, aby sprawdzić, czy działa zgodnie z zamierzeniami. Testy, które przeprowadzasz, zależą od funkcji gry.

Poniżej znajdziesz listę typowych testów do wykonania.

  1. Zalogowano się.

    1. Logowanie automatyczne działa. Użytkownik powinien być zalogowany w usługach gier Play, gdy uruchamia grę.

    2. Wyświetla się wyskakujące okienko powitalne.

      Przykładowe wyskakujące okienko powitalne
      Przykładowe wyskakujące okienko powitalne (kliknij, aby powiększyć).

    3. Wyświetlają się komunikaty o udanym zapisaniu danych do dziennika. Uruchom w terminalu to polecenie:

      adb logcat | grep com.google.android.

      Przykład komunikatu o udanym wykonaniu:

      [$PlaylogGamesSignInAction$SignInPerformerSource@e1cdecc
      number=1 name=GAMES_SERVICE_BROKER>], returning true for shouldShowWelcomePopup.
      [CONTEXT service_id=1 ]
  2. Zadbaj o spójność komponentów interfejsu.

    1. Wyskakujące okienka, tabele wyników i osiągnięcia wyświetlają się prawidłowo i w sposób spójny na różnych rozmiarach i orientacjach ekranu w interfejsie Usług Gier Play.

    2. Opcja wylogowania nie jest widoczna w interfejsie usług gier Play.

    3. Upewnij się, że możesz pobrać identyfikator gracza, a w odpowiednich przypadkach, że funkcje po stronie serwera działają zgodnie z oczekiwaniami.

    4. Jeśli gra używa uwierzytelniania po stronie serwera, dokładnie przetestuj proces requestServerSideAccess. Upewnij się, że serwer otrzyma kod autoryzacji i będzie mógł go wymienić na token dostępu. Testowanie scenariuszy powodzenia i niepowodzenia w przypadku błędów sieci i nieprawidłowych scenariuszy client ID.

Jeśli Twoja gra używała którejś z tych funkcji, przetestuj ją, aby upewnić się, że działa tak samo jak przed migracją:

  • Tabele wyników: możesz przesyłać wyniki i wyświetlać tabele wyników. Sprawdź, czy nazwy i wyniki graczy są prawidłowo wyświetlane i czy prawidłowo wyświetlane jest też ich ranking.
  • Osiągnięcia: odblokuj osiągnięcia i sprawdź, czy są one prawidłowo rejestrowane i wyświetlane w interfejsie Gier Play.
  • Zapisane gry: jeśli gra korzysta z zapisanych gier, sprawdź, czy zapisywanie i wczytywanie postępów w grze działa bez zarzutu. Jest to szczególnie ważne w przypadku testów na wielu urządzeniach i po aktualizacji aplikacji.

Zadania po migracji

Po migracji do wersji 2 gier wykonaj te czynności.

Publikowanie gry

Utwórz pliki APK i opublikuj grę w Konsoli Play.

  1. W menu Android Studio kliknij Utwórz > Utwórz pakiety > Utwórz pakiety APK > Utwórz pakiety APK.
  2. Opublikuj grę. Więcej informacji znajdziesz w artykule Publikowanie aplikacji prywatnych w Konsoli Play.