Dokumen ini menjelaskan cara memigrasikan game yang ada dari SDK game v1 ke SDK game v2.
Sebelum memulai
Anda dapat menggunakan IDE pilihan, seperti Android Studio, untuk memigrasikan game. Selesaikan langkah-langkah berikut sebelum Anda bermigrasi ke game v2:
- Mendownload dan menginstal Android Studio
- Game Anda harus menggunakan SDK game v1
Memperbarui dependensi
Dalam file
build.gradle
modul Anda, temukan baris ini dalam dependensi level modul.implementation "com.google.android.gms:play-services-games-v1:+"
Ganti dengan kode berikut:
implementation "com.google.android.gms:play-services-games-v2:version"
Ganti version dengan SDK game versi terbaru.
Setelah mengupdate dependensi, pastikan Anda menyelesaikan semua langkah dalam dokumen ini.
Bermigrasi dari Login dengan Google yang tidak digunakan lagi
Ganti class GoogleSignInClient
dengan class GamesSignInClient
.
Java
Cari file dengan class 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);
}
Lalu, perbarui menjadi:
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
Cari file dengan class 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)
}
Lalu, perbarui menjadi:
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)
}
Mengupdate kode GoogleSignIn
API
dan cakupan GoogleSignIn
tidak didukung di SDK game v2. Ganti kode API GoogleSignIn
untuk cakupan OAuth 2.0 dengan
API GamesSignInClient
seperti yang ditunjukkan dalam contoh berikut:
Java
Temukan file dengan class dan cakupan 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");
}
});
}
Lalu, perbarui menjadi:
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
Temukan file dengan class dan cakupan 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")
}
}
}
Lalu, perbarui menjadi:
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()
}
Menambahkan kode GamesSignInClient
Jika pemain berhasil login, hapus tombol login Layanan game Play
dari game Anda. Jika pengguna memilih untuk tidak login saat game diluncurkan,
terus tampilkan tombol dengan ikon Layanan game Play,
dan mulai proses login dengan
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
}
}
}
Menghapus kode logout
Hapus kode untuk GoogleSignInClient.signOut
.
Hapus kode yang ditampilkan dalam contoh berikut:
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.
}
}
Memeriksa keberhasilan login otomatis
Sertakan kode berikut untuk memeriksa apakah Anda telah login secara otomatis dan tambahkan logika kustom jika tersedia.
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
}
}
}
Memperbarui nama dan metode class klien
Saat Anda bermigrasi ke game v2, metode yang digunakan untuk mendapatkan nama class klien
akan berbeda.
Gunakan metode
PlayGames.getxxxClient()
yang sesuai, bukan
metode
Games.getxxxClient()
.
Misalnya, untuk
LeaderboardsClient
,
gunakan PlayGames.getLeaderboardsClient()
, bukan
metode Games.getLeaderboardsClient()
.
Java
Temukan kode untuk 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));
}
Lalu, perbarui menjadi:
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
Temukan kode untuk 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))
}
Lalu, perbarui menjadi:
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)
}
Demikian pula, gunakan metode yang sesuai untuk klien berikut:
AchievementsClient
, EventsClient
, GamesSignInClient
,
PlayerStatsClient
, RecallClient
, SnapshotsClient
, atau PlayersClient
.
Memperbarui class akses sisi server
Untuk meminta token akses sisi server, gunakan metode
GamesSignInClient.requestServerSideAccess()
,
bukan metode
GoogleSignInAccount.getServerAuthCode()
.
Contoh berikut menunjukkan cara meminta token akses sisi server.
Java
Temukan kode untuk class 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();
}
}
}
Lalu, perbarui menjadi:
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
Temukan kode untuk class 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()
}
}
}
Lalu, perbarui menjadi:
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.
}
});
}
Bermigrasi dari GoogleApiClient
Untuk integrasi lama, game Anda mungkin bergantung pada
variasi GoogleApiClient
API SDK Layanan game Play. Perangkat ini
tidak digunakan lagi pada akhir 2017
dan digantikan oleh klien "tanpa koneksi". Untuk bermigrasi, Anda dapat mengganti
class GoogleApiClient
dengan yang setara "tanpa koneksi".
Berikut adalah pemetaan class umum:
game 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
game 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
Membangun dan menjalankan game
Untuk mem-build dan menjalankan di Android Studio, lihat Mem-build dan menjalankan aplikasi.
Menguji game Anda
Pastikan game Anda berfungsi seperti yang dirancang dengan mengujinya. Pengujian yang Anda lakukan bergantung pada fitur game Anda.
Berikut adalah daftar pengujian umum yang akan dijalankan.
Login berhasil.
Login otomatis berfungsi. Pengguna harus login ke Layanan game Play setelah meluncurkan game.
Pop-up selamat datang akan ditampilkan.
Pesan log yang berhasil akan ditampilkan. Jalankan perintah berikut di terminal:
adb logcat | grep com.google.android.
Pesan log yang berhasil ditampilkan dalam contoh berikut:
[
$PlaylogGamesSignInAction$SignInPerformerSource@e1cdecc number=1 name=GAMES_SERVICE_BROKER>], returning true for shouldShowWelcomePopup. [CONTEXT service_id=1 ]
Memastikan konsistensi komponen UI.
Pop-up, papan peringkat, dan pencapaian ditampilkan dengan benar dan konsisten di berbagai ukuran dan orientasi layar di antarmuka pengguna (UI) Layanan game Play.
Opsi logout tidak terlihat di UI Layanan game Play.
ID pemain konsisten dan dapat digunakan untuk integrasi backend.
Jika game menggunakan autentikasi sisi server, uji alur
requestServerSideAccess
secara menyeluruh. Pastikan server menerima kode autentikasi dan dapat menukarnya dengan token akses. Uji skenario keberhasilan dan kegagalan untuk error jaringan, skenarioclient ID
yang tidak valid.
Jika game Anda menggunakan salah satu fitur berikut, uji fitur tersebut untuk memastikan bahwa fitur tersebut berfungsi sama seperti sebelum migrasi:
- Papan peringkat: Kirim skor dan lihat papan peringkat. Periksa peringkat dan tampilan nama serta skor pemain yang benar.
- Pencapaian: Membuka pencapaian dan memverifikasi bahwa pencapaian dicatat dan ditampilkan dengan benar di UI Play Game.
- Game Tersimpan: Jika game menggunakan game tersimpan, pastikan menyimpan dan memuat progres game berfungsi dengan lancar. Hal ini sangat penting untuk diuji di beberapa perangkat dan setelah update aplikasi.
Tugas pascamigrasi
Selesaikan langkah-langkah berikut setelah Anda bermigrasi ke game v2.
Memublikasikan game
Build APK dan publikasikan game di Konsol Play.
- Di menu Android Studio, pilih Build > Build Bundles/APK > Build APK.
- Publikasikan game Anda. Untuk mengetahui informasi selengkapnya, lihat Memublikasikan aplikasi pribadi dari Konsol Play.