简体   繁体   English

Android | 登录Google Api有时不起作用

[英]Android | SignIn Google Api sometimes does not work

In my app, I've implemented the GoogleSignInApi, with this code: 在我的应用中,我使用以下代码实现了GoogleSignInApi:

in onCreate: 在onCreate中:

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.server_client_id))
                .requestEmail()
                .build();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, null /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

in an AsyncTask 在AsyncTask中

        if (mGoogleApiClient != null)
            mGoogleApiClient.connect();
        if (mGoogleApiClient != null) {
            ConnectionResult result = mGoogleApiClient.blockingConnect();
            if(result.isSuccess()){
                GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient).await();
                GoogleSignInAccount account = googleSignInResult.getSignInAccount();
                authToken = account.getIdToken();
            }else {
                return null;
            }
        }else{
            return null;
        }

The app crash with "Attempt to invoke virtual method 'java.lang.String com.google.android.gms.auth.api.signin.GoogleSignInAccount.getIdToken()' on a null object reference" (account is null!) 应用程序崩溃,原因是“尝试在空对象引用上调用虚拟方法'java.lang.String com.google.android.gms.auth.api.signin.GoogleSignInAccount.getIdToken()'”(帐户为空!)
Now I've added if(account!=null) {get error}, but why account could be null, if "result.isSuccess()"? 现在,我添加了if(account!= null){get error},但是如果“ result.isSuccess()”,为什么account可以为null?

result is only the variable containing the result of connecting to the API. result仅是包含连接到API的结果的变量。 This does not involve any authentication yet. 这还不涉及任何身份验证。 Only once you are connected, you can sign in. However, the credentials may be wrong, so you get a null result. 只有连接后,您才能登录。但是,凭据可能不正确,因此您得到的结果为null

    You can use the following code for Google login:

     protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
            if (requestCode == RC_SIGN_IN) {
                    GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(intent);
                    if (result.isSuccess()) {
                    GoogleSignInAccount acct = result.getSignInAccount();
                    }
            }
        }

GoogleSignInAccount will give you all account details. GoogleSignInAccount将为您提供所有帐户详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM