Android Firebase-连接到游戏服务排行榜



我已经使用Firebase进行了登录活动与Google连接。现在,用户可以登录而没有问题,我想在另一个活动上显示排行榜,但是当我检查用户是否登录并尝试显示排行榜时,我会收到错误:

e/nocaughtexception:java.lang.illegalstateException:googleapiclient 必须连接。

如何使用Firebase连接GoogleApiClient?我尝试使用mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL);,但这也不起作用。

在这里我的代码:

      protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_achievements);

                // Configure Google Sign In
                GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestIdToken(getString(R.string.default_web_client_id))
                        .requestEmail()
                        .build();
                mGoogleApiClient = new GoogleApiClient.Builder(this)
                        .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                            @Override
                            public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                                // connection failed, should be handled
                            }
                        })
                        .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                        .build();
                mAuth = FirebaseAuth.getInstance();
                mAuthListener = new FirebaseAuth.AuthStateListener() {
                    @Override
                    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                        FirebaseUser user = firebaseAuth.getCurrentUser();
                        if (user != null) {
                            // User is signed in
                            Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
     ////// is crashing googleapiclient not connected
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
                                    getString(R.string.leaderboard_la_classifica)), REQUEST_LEADERBOARD); 
                        } else {
                            // User is signed out
                        }
                        // ...
                    }
                };
            }

请参阅https://firebase.google.com/docs/auth/android/google-signin有关更多详细信息。

构建客户端时,您需要使用googlesigninoptions.default_games_sign_in。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
       setContentView(R.layout.fragment_firebase_games_signin);
     String webclientId = getString(R.string.web_client_id);
    GoogleSignInOptions options =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
                    .requestServerAuthCode(webclientId)
                    .requestEmail()
                    .requestIdToken()
                    .build();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Games.API).addScope(Games.SCOPE_GAMES)
            .addApi(Auth.GOOGLE_SIGN_IN_API, options)
            .addConnectionCallbacks(this)
            .build();
}

然后开始明确的登录启动签名意图:

private void signIn() {
    Intent signInIntent =
         Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

您还应该使用自动宣传的客户端,或者只需在onStart()中调用mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL);,然后在onStop()中断开连接。

在OnActivityResult中,处理明确登录意图的结果:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount acct = result.getSignInAccount();
            completeFirebaseAuth(acct);
            // At this point, the Games API can be called.
        } else {
            // Google Sign In failed, update UI appropriately
            // ...
        }
    }
}

完成firebase身份验证:

private void completeFirebaseAuth(GoogleSignInAccount  acct) {
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    FirebaseAuth mAuth = FirebaseAuth.getInstance();
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new
                    OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Log.w(TAG, "signInWithCredential", task.getException());
                    }
                    // ...
                }
            });
}

您需要处理的另一种情况是无声登录,在恢复应用程序时会发生这种情况:

@Override
public void onConnected(@Nullable Bundle bundle) {
    // Handle the silent sign-in case.
    if (mGoogleApiClient.hasConnectedApi(Games.API)) {
        Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient).setResultCallback(
                new ResultCallback<GoogleSignInResult>() {
                    @Override
                    public void onResult(
                            @NonNull GoogleSignInResult googleSignInResult) {
                        if (googleSignInResult.isSuccess()) {
                            completePlayGamesAuth(
                                    googleSignInResult.getSignInAccount());
                        } else {
                            Log.e(TAG, "Error with silentSignIn: " +
                                    googleSignInResult.getStatus());
                        }
                    }
                }
        );
    }
}

最新更新