如何在KotlinAndroid中集成Google游戏服务并检索排行榜和成就

wribegjk  于 2022-12-13  发布在  Kotlin
关注(0)|答案(1)|浏览(164)

我是Kotlin的新手,我想尝试一下谷歌的游戏服务。我在谷歌的登录功能上卡住了。我点击了登录按钮,它显示被点击,但UI没有变成谷歌帐户登录窗口。这行是做什么的?当游戏开始时,我如何显示登录窗口?

主要活动:

package com.example.spotifygame

import android.os.Bundle
import android.widget.Button
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isInvisible
import com.google.android.gms.games.*
import com.google.android.gms.tasks.Task
import com.google.android.gms.games.PlayGamesSdk;

class MainActivity : AppCompatActivity() {
    //UI Buttons
    private lateinit var signInButton: Button
    private lateinit var achievementButton: Button
    private lateinit var leaderBoardButton: Button
    //Game service Clients
    private lateinit var gamesSignInClient: GamesSignInClient
    private lateinit var achievementsClient: AchievementsClient
    private lateinit var leaderboardsClient: LeaderboardsClient


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //google game services
        PlayGamesSdk.initialize(this);

        // Buttons wire
        signInButton = findViewById(R.id.signIn)
        achievementButton = findViewById(R.id.achievements)
        leaderBoardButton = findViewById(R.id.leader_board)

        //verify user authentication
        initGoogleServiceClients()

        //default Buttons invisible
        signInButton.isInvisible = true
        achievementButton.isInvisible = true
        leaderBoardButton.isInvisible = true

        // setup button functions
        signInButton.setOnClickListener() {
            println("debug: sign btn clicked")
            gamesSignInClient.signIn()
        }
        achievementButton.setOnClickListener() {
            println("debug: achievement btn clicked")

            showAchievements()
        }
        leaderBoardButton.setOnClickListener() {
            println("debug: leader board btn clicked")
            showTopPlayers()
        }
    }

    private fun initGoogleServiceClients() {
        gamesSignInClient = PlayGames.getGamesSignInClient(this)
        gamesSignInClient.isAuthenticated.addOnCompleteListener { isAuthenticatedTask: Task<AuthenticationResult> ->

            // boolean = successfully authenticated
            val isAuthenticated = isAuthenticatedTask.isSuccessful &&
                    isAuthenticatedTask.result.isAuthenticated
            if (isAuthenticated) {
                // Continue with Play Games Services
                // get two clients
                achievementsClient = PlayGames.getAchievementsClient(this)
                leaderboardsClient = PlayGames.getLeaderboardsClient(this)

                // make buttons visible
                achievementButton.isInvisible = false
                leaderBoardButton.isInvisible = false

                //show current player ID
                PlayGames.getPlayersClient(this).currentPlayer.addOnCompleteListener { mTask: Task<Player?>? ->
                    val iD = mTask?.result?.playerId
                    println("debug: id is $iD")
                }
                //debug
                println("debug: successfully authenticated")

            } 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().
                gamesSignInClient.signIn()

                //make sign in button visible
                signInButton.isInvisible = false

                //debug
                println("debug: failed authenticated")
            }
        }

    }

    // Button Functions
    fun showTopPlayers() {
        leaderboardsClient.allLeaderboardsIntent.addOnSuccessListener {
            //deprecated
            startActivityForResult(intent,0)

            //new way
//            val previewRequest =
//                registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
//                    if (it.resultCode == RESULT_OK) {
//                        val list = it.data
//                        // do whatever with the data in the callback
//                        println("debug: data list have $list")
//
//                    }
//                }
        }

    }
    fun showAchievements() {
        achievementsClient.achievementsIntent.addOnSuccessListener {
            startActivityForResult(intent,0)

        }
    }

    // Feature Functions

    fun unlockAchievements(achievementID: String) {
        // unlock the achievement
        achievementsClient.unlock(achievementID)
    }

    fun updateScore(leaderboardID: String, score: Long) {
        leaderboardsClient.submitScore(leaderboardID, score)

    }

}

我也不确定如何在函数中调用show leaderboard和achievement。我使用的是过时的代码startactivityforResults。

Gradle(:应用程序)

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'

}

android {
    namespace 'com.example.spotifygame'
    compileSdk 32

    defaultConfig {
        applicationId "com.example.spotifygame"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildscript {
        repositories {
            google()
            mavenCentral()
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    //google play games
    implementation "com.google.android.gms:play-services-games-v2:+"
    implementation 'com.google.android.gms:play-services-location:21.0.1'
    implementation 'com.google.android.gms:play-services-auth:20.3.0'

}

终端与UI捕获:

---------------------------- PROCESS STARTED (10405) for package com.example.spotifygame ----------------------------
2022-11-11 00:15:52.449 10405-10405 System.out              com.example.spotifygame              I  debug: failed authenticated
2022-11-11 00:15:54.992 10405-10405 System.out              com.example.spotifygame              I  debug: sign btn clicked

我遵循Google Play服务android文档。我已经在谷歌游戏控制台中设置了项目。对于我的gradle文件,我没有包括allproject范围,因为它给我错误。

allprojects {
    repositories {
      google()
      mavenCentral()
    }
  }

链接:https://developers.google.com/games/services/android/quickstart
Youtube:https://www.youtube.com/watch?v=NwJkoI3IIWo&t=427s
我希望:当我运行应用程序时,会有一个谷歌游戏帐户登录窗口。

shyt4zoc

shyt4zoc1#

我理解你的痛苦,谷歌没有提供如何使用implementation "com.google.android.gms:play-services-games-v2:+"的代码。这是在Java(与lambda),所以只需复制/粘贴到Android Studio的Kotlin文件,它会翻译它。
我会让你一半的方式,因为我的代码是如此不同,我不想尝试工作到你有什么。这表明了球员已经取得的成就。我们假设PlayGamesSdk.initialize(this);加载没有错误(logcat没有**** APP NOT CORRECTLY CONFIGURED TO USE GOOGLE PLAY GAME SERVICES **** DEVELOPER_ERROR等)和

GamesSignInClient gamesSignInClient = PlayGames.getGamesSignInClient(this);
    gamesSignInClient.isAuthenticated().addOnCompleteListener(isAuthenticatedTask -> {
      if (isAuthenticatedTask.isSuccessful() && isAuthenticatedTask.getResult().isAuthenticated())

是真的!(我需要提到注意在哪里使用this吗?如果它在一个runner中,它可能不是传递参数所需的上下文。)
下面是我的show achiefings,按下UI Achiefings按钮时调用的例程:-

private void showAchievements() {
    try {
        AchievementsClient ac = PlayGames.getAchievementsClient(this);
        Task<Intent> ti = ac.getAchievementsIntent();
        ti.addOnSuccessListener(intent -> startActivityForResult(intent, 0));
    } catch (Exception | Error e) {
        //log error / whatever
    }
}

这可能是一行程序,我只是用变量将其分解,以便于阅读。请注意,Task是一个异步函数,它返回您想要启动的Intent,而不是Intent本身。因此,在任务完成时放置一个侦听器,以获取启动Activity的Intent。
对所有这些返回Task<Intent>的例程都使用此方法。
希望这对你有帮助!

相关问题