2019-03-20 Android 第三方登录集-Google 登录集成整理

Google+登录集成 点击按钮标准式配置

1.请科学打开官网地址

WechatIMG16.jpeg

  1. Add Google Play services

In your project's top-level build.gradle file, ensure that Google's Maven repository is included:

allprojects {
    repositories {
        google()

        // If you're using a version of Gradle lower than 4.1, you must instead use:
        // maven {
        //     url 'https://maven.google.com'
        // }
    }
}

Then, in your app-level build.gradle file, declare Google Play services as a dependency:

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

检查AS是否下载Google Play services
WechatIMG17.jpeg
  1. 在 Activity 类 onCreate()方法 中添加如下配置
    In your sign-in activity's onCreate method, configure Google Sign-In to request the user data required by your app. For example, to configure Google Sign-In to request users' ID and basic profile information, create aGoogleSignInOptions object with the DEFAULT_SIGN_IN parameter. To request users' email addresses as well, create the GoogleSignInOptions object with the requestEmail option.
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestEmail()
        .build();

// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

If you need to request additional scopes to access Google APIs, specify them with requestScopes. For the best user experience, on sign-in, only request the scopes that are required for your app to minimally function. Request any additional scopes only when you need them, so that your users see the consent screen in the context of an action they performed. See Requesting Additional Scopes.

4.onStart() 方法中检查 是否已经登录

In your activity's onStart method, check if a user has already signed in to your app with Google.

// Check for existing Google Sign In account, if the user is already signed in
// the GoogleSignInAccount will be non-null.
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
// 已登录 account 不为空
  1. layout 文件中添加googleButton 使用自己写的也是可以的。
<com.google.android.gms.common.SignInButton
 android:id="@+id/sign_in_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />

6.点击事件
In the activity's onClick method, handle sign-in button taps by creating a sign-in intent with the getSignInIntent method, and starting the intent with startActivityForResult

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.sign_in_button:
            signIn();
            break;
    }
}

private void signIn() {
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}
  1. onActivityResult() 方法中添加回调
    After the user signs in, you can get a GoogleSignInAccount object for the user in the activity's onActivityResult method.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
    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);
    }
}

private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);

        // Signed in successfully, show authenticated UI.
        updateUI(account);
    } catch (ApiException e) {
        // The ApiException status code indicates the detailed failure reason.
        // Please refer to the GoogleSignInStatusCodes class reference for more information.
        Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
        updateUI(null);
    }
}

到此Google 第三方登录已集成完毕!
附:完整代码

/**
 *  @author BuMingYang
 *  @des 谷歌登录
 */
class GoogleLogin(private var context: Activity) {

    private var mGoogleSignInClient: GoogleSignInClient? = null
    private var googleListener: GoogleListener? = null


    private val RC_SIGN_IN = 9001

    init {

        val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build()

        mGoogleSignInClient = GoogleSignIn.getClient(context, gso)


    }

    //google
    fun signIn() {

        val signInIntent = mGoogleSignInClient?.signInIntent
        context.startActivityForResult(signInIntent, RC_SIGN_IN)
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        if (requestCode === RC_SIGN_IN) {
            val task = GoogleSignIn.getSignedInAccountFromIntent(data)
            handleSignInResult(task)
        }

    }

    private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
        try {
            var account: GoogleSignInAccount? = completedTask.getResult(ApiException::class.java)
            // Signed in successfully, show authenticated UI.
            googleListener?.onGoogleSuccess("${account?.id}")

        } catch (e: ApiException) {
            Log.e("Login", "signInResult:failed code=" + e.statusCode)
            context.showSnackMsg("signInResult:failed code=${e.statusCode}")
        }
    }

    fun setGoogleListener(googleListener: GoogleListener) {

        this.googleListener = googleListener
    }

    interface GoogleListener {

        /**
         * 登录成功
         * @param id
         */
        fun onGoogleSuccess(id: String)
    }

Activity 中使用 (项目代码 避免嫌疑 提供主要使用地方)

      
//初始化
googleLogin = GoogleLogin(this)
//添加回调事件 复写成功请求方法
googleLogin?.setGoogleListener(this)
// 登录事件方法中调用
googleLogin?.signIn()
//onActivityResult 方法中添加
googleLogin?.onActivityResult(requestCode, resultCode, data)

参考DEMO

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,490评论 0 10
  • 今天星期天本来是上画画的,画画课取消了,今天没特长课,不用这么忙活了,小雨睡到自然醒,醒来在客厅看电视,昨晚...
    小雨儿的妈妈阅读 259评论 0 1
  • 那一天我准备踏上火车 回到我生长的地方 转过身看着这个拥挤的城市 突然才发现 我爱上这里的你早已足够了两年 平平淡...
    子遇烟阅读 226评论 0 1
  • 今天天气很好。天蓝气清。这应该是我自己最喜欢的天气。 现在渐渐的事情在进入正规,突然间有一种不管遇见什么样的事情自...
    不完美的你我他阅读 219评论 0 0
  • 周六,小六晚上一直没吃饭,终于找到了一家面馆,要了碗油泼面,端上来时辣椒油的香味扑入鼻腔。 小六又加了一勺,犹豫着...
    谢沛霖阅读 256评论 0 1