草庐IT

android - GoogleSignInAccount 返回 null

coder 2023-12-30 原文

我正在尝试使用最新的 Google API。
我按照 Google 的建议设置了所有依赖项。

编译 'com.google.android.gms:play-services:9.0.0'

并且还创建了一个 google-service.json。
在控制台中启用 Google API...
我认为一切都应该有效。 我可以使用 Google 引用和 Intent 登录。
但是得到回调后

GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
    if (result.isSuccess()) {
        GoogleSignInAccount acct = result.getSignInAccount();
        if (listener != null) {
            listener.onSuccess(acct);
        }
    }

GoogleSignInAccount 中,所有属性值都是 null

this.mGoogleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            //.requestScopes(new Scope(Scopes.PLUS_LOGIN)) // "https://www.googleapis.com/auth/plus.login"
            //.requestScopes(new Scope(Scopes.PLUS_ME)) // "https://www.googleapis.com/auth/plus.me"
            //.requestScopes(new Scope(Scopes.EMAIL))
            //.requestScopes(new Scope(Scopes.PROFILE))
            //.requestEmail()
            //.requestProfile()
            .build();
    this.mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
            .enableAutoManage((FragmentActivity) mActivity /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API)
            .build();

您应该能够使用requestEmailscope
这是最新 Google API 的问题吗?

最佳答案

尝试使用这个:

public class GooglePlusLoginUtils implements ConnectionCallbacks, OnConnectionFailedListener,OnClickListener {

private String TAG = "GooglePlusLoginUtils";
/* Request code used to invoke sign in user interactions. */
private static final int RC_SIGN_IN = 0;
private static final int PROFILE_PIC_SIZE = 400;
public static final String NAME = "name";
public static final String EMAIL = "email";
public static final String PHOTO = "photo";
public static final String PROFILE= "profile";

/* Client used to interact with Google APIs. */
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;

private SignInButton btnSignIn;
private Context ctx;
private GPlusLoginStatus loginstatus;
public interface GPlusLoginStatus{
    public void OnSuccessGPlusLogin(Bundle profile);
}

public GooglePlusLoginUtils(Context ctx,int btnRes){
    Log.i(TAG, "GooglePlusLoginUtils");
    this.ctx= ctx;
    this.btnSignIn =(SignInButton) ((Activity)ctx).findViewById(btnRes);
    btnSignIn.setOnClickListener(this);
     // Initializing google plus api client
    mGoogleApiClient = new GoogleApiClient.Builder(ctx)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).addApi(Plus.API)
            .addScope(Plus.SCOPE_PLUS_LOGIN).build();


}

public void setLoginStatus(GPlusLoginStatus loginStatus){
    this.loginstatus = loginStatus;
}
@Override
public void onConnectionFailed(ConnectionResult result) {
    Log.i(TAG, "onConnectionFailed");
    Log.i(TAG,"Error Code "+ result.getErrorCode());
    if (!result.hasResolution()) {
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), (Activity)ctx,0).show();
        return;
    }

    if (!mIntentInProgress) {
        // Store the ConnectionResult for later usage
        mConnectionResult = result;

        if (mSignInClicked) {
            // The user has already clicked 'sign-in' so we attempt to
            // resolve all
            // errors until the user is signed in, or they cancel.
            resolveSignInError();
        }
    }       
}
public void setSignInClicked(boolean value){
    mSignInClicked  =value;
}
public void setIntentInProgress(boolean value){
    mIntentInProgress = value;
}
public void connect(){
    mGoogleApiClient.connect();
}
public void reconnect(){
    if (!mGoogleApiClient.isConnecting()) {
        mGoogleApiClient.connect();
    }
}
public void disconnect(){
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}
private void signInWithGplus() {
    Log.i(TAG, "signInWithGplus");
    if (!mGoogleApiClient.isConnecting()) {
        mSignInClicked = true;
        resolveSignInError();
    }
}
private void resolveSignInError() {
    Log.i(TAG, "resolveSignInError");
    if (mConnectionResult.hasResolution()) {
        try {
            mIntentInProgress = true;
            mConnectionResult.startResolutionForResult((Activity)ctx, RC_SIGN_IN);
        } catch (SendIntentException e) {
            mIntentInProgress = false;
            mGoogleApiClient.connect();
        }
    }
}
@Override
public void onConnected(Bundle arg0) {
    Log.i(TAG, "onConnected");
     mSignInClicked = false;
        Toast.makeText(ctx, "User is connected!", Toast.LENGTH_LONG).show();

        // Get user's information
        getProfileInformation();

}
@Override
public void onConnectionSuspended(int arg0) {
    Log.i(TAG, "onConnectionSuspended");
    mGoogleApiClient.connect();
}

private void getProfileInformation() {
    Log.i(TAG, "getProfileInformation");
    try {
        if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
            Person currentPerson = Plus.PeopleApi
                    .getCurrentPerson(mGoogleApiClient);
            String personName = currentPerson.getDisplayName();
            String personPhotoUrl = currentPerson.getImage().getUrl();
            String personGooglePlusProfile = currentPerson.getUrl();
            String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

            Log.e(TAG, "Name: " + personName + ", plusProfile: "
                    + personGooglePlusProfile + ", email: " + email
                    + ", Image: " + personPhotoUrl);


            // by default the profile url gives 50x50 px image only
            // we can replace the value with whatever dimension we want by
            // replacing sz=X
            personPhotoUrl = personPhotoUrl.substring(0,
                    personPhotoUrl.length() - 2)
                    + PROFILE_PIC_SIZE;

            Bundle profile = new Bundle();
            profile.putString(NAME, personName);
            profile.putString(EMAIL, email);
            profile.putString(PHOTO, personPhotoUrl);
            profile.putString(PROFILE, personGooglePlusProfile);

            loginstatus.OnSuccessGPlusLogin(profile);

         //   new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);

        } else {
            Toast.makeText(ctx,
                    "Person information is null", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
@Override
public void onClick(View v) {
    signInWithGplus();
}
public void onActivityResult(int requestCode,int responseCode,Intent intent){
    if (requestCode == RC_SIGN_IN) {
        if (responseCode != ((Activity)ctx).RESULT_OK) {
            setSignInClicked(false);
        }
        setIntentInProgress(false);
        reconnect();
    }
}


}

你的主要 Activity :

public class LoginActivity extends ActionBarActivity implements GooglePlusLoginUtils.GPlusLoginStatus {

private String TAG = "LoginActivity";
private GooglePlusLoginUtils gLogin;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    gLogin = new GooglePlusLoginUtils(this, R.id.activity_login_gplus);
    gLogin.setLoginStatus(this);

}
@Override
protected void onStart() {
    super.onStart();
    gLogin.connect();
}
@Override
protected void onStop() {
    super.onStop();
    gLogin.disconnect();
}
@Override
protected void onActivityResult(int requestCode, int responseCode,
                                Intent intent) {
    gLogin.onActivityResult(requestCode, responseCode, intent);

}

@Override
public void OnSuccessGPlusLogin(Bundle profile) {
    Log.i(TAG,profile.getString(GooglePlusLoginUtils.NAME));
    Log.i(TAG,profile.getString(GooglePlusLoginUtils.EMAIL));
    Log.i(TAG,profile.getString(GooglePlusLoginUtils.PHOTO));
    Log.i(TAG,profile.getString(GooglePlusLoginUtils.PROFILE));
}
}

确保您已在 Developers Console 中启用 Google+ 登录并在您的应用程序目录中添加 JSON 文件!

关于android - GoogleSignInAccount 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37506840/

有关android - GoogleSignInAccount 返回 null的更多相关文章

  1. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  2. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  3. ruby - Ruby 中的隐式返回值是怎么回事? - 2

    所以我开始关注ruby​​,很多东西看起来不错,但我对隐式return语句很反感。我理解默认情况下让所有内容返回self或nil但不是语句的最后一个值。对我来说,它看起来非常脆弱(尤其是)如果你正在使用一个不打算返回某些东西的方法(尤其是一个改变状态/破坏性方法的函数!),其他人可能最终依赖于一个返回对方法的目的并不重要,并且有很大的改变机会。隐式返回有什么意义?有没有办法让事情变得更简单?总是有返回以防止隐含返回被认为是好的做法吗?我是不是太担心这个了?附言当人们想要从方法中返回特定的东西时,他们是否经常使用隐式返回,这不是让你组中的其他人更容易破坏彼此的代码吗?当然,记录一切并给出

  4. ruby-on-rails - ruby 日期方程不返回预期的真值 - 2

    为什么以下不同?Time.now.end_of_day==Time.now.end_of_day-0.days#falseTime.now.end_of_day.to_s==Time.now.end_of_day-0.days.to_s#true 最佳答案 因为纳秒数不同:ruby-1.9.2-p180:014>(Time.now.end_of_day-0.days).nsec=>999999000ruby-1.9.2-p180:015>Time.now.end_of_day.nsec=>999999998

  5. ruby - 从 String#split 返回的零长度字符串 - 2

    在Ruby1.9.3(可能还有更早的版本,不确定)中,我试图弄清楚为什么Ruby的String#split方法会给我某些结果。我得到的结果似乎与我的预期相反。这是一个例子:"abcabc".split("b")#=>["a","ca","c"]"abcabc".split("a")#=>["","bc","bc"]"abcabc".split("c")#=>["ab","ab"]在这里,第一个示例返回的正是我所期望的。但在第二个示例中,我很困惑为什么#split返回零长度字符串作为返回数组的第一个值。这是什么原因呢?这是我所期望的:"abcabc".split("a")#=>["bc"

  6. "\0"null 的 Ruby 测试? - 2

    我在破坏脚本的字符串中出现了一些奇怪的字符。据我所知,通过putbadstring到控制台,它们是"\0\0\0\0"。我想对此进行测试,以便我可以忽略它们...但是如何呢?以为这就是blank?和empty?的用途?!?:>badstring="\0"=>"\u0000">badstring.blank?NoMethodError:undefinedmethod`blank?'for"\u0000":Stringfrom(irb):97from/Users/meltemi/.rvm/rubies/ruby-2.0.0-p195/bin/irb:16:in`'>badstring.em

  7. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  8. ruby - 为什么 Integer.respond_to?( :even? ) 返回 false? - 2

    我一直在研究RubyKoans,我发现about_open_classes.rbkoan很有趣。特别是他们修改Integer#even?方法的最后一个测试。我想尝试一下这个概念,所以我打开了Irb并尝试运行Integer.respond_to?(:even?),但令我惊讶的是我得到了错误。然后我尝试了Fixnum.respond_to?(:even?)并得到了错误。我还尝试了Integer.respond_to?(:respond_to?)并得到了true,当我执行2.even?时,我也得到了true。我不知道发生了什么。谁能告诉我缺少什么? 最佳答案

  9. ruby - Time.to_i 是否总是以 UTC 返回自 EPOCH 以来的秒数? - 2

    无论时间在哪个时区表示,时区差异是否总是被忽略?直觉上,对于那些使用UTC+2的人来说,从EPOCH开始经过的秒数应该更高。然而,事实并非如此。 最佳答案 Epoch基于utc时区https://en.wikipedia.org/wiki/Unix_time它与您当前所在的时区无关。 关于ruby-Time.to_i是否总是以UTC返回自EPOCH以来的秒数?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.

  10. ruby-on-rails - Ruby 流量控制 : throw an exception, 返回 nil 还是让它失败? - 2

    我在思考流量控制的最佳实践。我应该走哪条路?1)不要检查任何东西并让程序失败(更清晰的代码,自然的错误消息):defself.fetch(feed_id)feed=Feed.find(feed_id)feed.fetchend2)通过返回nil静默失败(但是,“CleanCode”说,你永远不应该返回null):defself.fetch(feed_id)returnunlessfeed_idfeed=Feed.find(feed_id)returnunlessfeedfeed.fetchend3)抛出异常(因为不按id查找feed是异常的):defself.fetch(feed_id

随机推荐