android google 登录登出接入

  • Post author:
  • Post category:其他


官方地址 https://developers.google.com/identity/sign-in/android/sign-in

登录

集成google库


dependencies {


implementation 'com.google.android.gms:play-services-auth:19.2.0'


}

  • 配置 Google Sign-in 和 GoogleSignInClient 对象

在入口activity onCreate 或者init方法中加入👇🏻下面代码


①配置谷歌登录到请求用户的ID和基本信息

①配置谷歌登录到请求用户的ID和基本信息
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestEmail()
        .build();
②使用上面gso指定的选项构建googlesignclient对象
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
  • 检测已登录应用的用户,获取登录用户个人信息
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

if (account != null) {

String personName = account.getDisplayName();

String personGivenName = account.getGivenName();

String personFamilyName = account.getFamilyName();

String personEmail = account.getEmail();

String personId = account.getId();

Uri personPhoto = account.getPhotoUrl();

}



如果GoogleSignIn.getLastSignedInAccount返回GoogleSignInAccount对象,用户已经登录到您与谷歌应用程序的程序

如果GoogleSignIn.getLastSignedInAccount返回null,用户尚未登录到谷歌与您的应用程序。
  • 启动登录
  • Intent signInIntent = mGoogleSignInClient.getSignInIntent(); 
    ​​​​​​​startActivityForResult(signInIntent, RC_SIGN_IN); 
    
    
    启动意图会提示用户选择要登录的谷歌帐户。如果你要求的范围超出了profile,email和openid,用户也被提示授权访问所请求的资源。


    在用户登录后,你可以得到一个




    GoogleSignInAccount




    在活动的用户对象



    onActivityResult



    方法

@Override

public void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

// 启动intent 返回的结果

if (requestCode == RC_SIGN_IN) {

// The Task returned from this call is always completed, no need to attach

// a listener.

Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);

handleSignInResult(task);

}

}


GoogleSignInAccount 包含有关信息的登录用户,例如用户名、email、id等

Google登出

mGoogleSignInClient.signOut()
            .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    // ...
                }
            });
代码清除了与该应用程序关联的账户。要再次登录,用户必须再次选择他们的账户。



版权声明:本文为u010207898原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。