在Android应用中集成Google登录

在Android应用中集成Google登录

在本教程中,我们将使用 Google API 在我们的Android应用程序中集成 Google登录 功能。将Google API合并到Android应用程序中可以帮助用户使用Google账户登录。

要在我们的应用程序中集成Google登录API,我们需要将应用程序配置到Google开发者帐号并下载 ‘google-service.json’ 文件用于Android应用程序。

配置Android应用程序的步骤在Google开发者帐号上

1. 在https://developers.google.com/identity/sign-in/android/start-integrating上创建一个Google开发者帐号,并点击’GET A CONFIGURATION FILE’。

在Android应用中集成Google登录

2. 填写所有的应用细节,选择您的国家/地区,然后点击“选择并配置服务”。

在Android应用中集成Google登录

3. 成功创建谷歌应用支持配置后,将会重定向到下一个窗口以选择谷歌服务。我们将选择谷歌登录服务。

在Android应用中集成Google登录

4. 现在,我们需要提供应用程序的签名证书 SHA-1 密钥。

5. 有两种不同的方式生成证书的SHA-1密钥。

  • 通过使用命令提示符。

Windows:

keytool -exportcert -list -v \
-alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore

Mac/Linux

keytool -exportcert -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore
  • 通过Android Studio自身。
    1. 打开Android项目。
    2. 从右侧面板打开Gradle选项卡。
    3. 双击’signingReport’。
    4. 我们将会在’Gradle Console’上找到我们的应用SHA-1密钥。

在Android应用中集成Google登录

6. 将生成的SHA-1密钥粘贴到Google Sign-In服务中,然后点击’启用Google Sign-In’和’生成认证文件’。

在Android应用中集成Google登录

7. 现在下载 ‘google-services.json’ 文件,并将其集成到Android应用程序中。

在Android应用中集成Google登录

在Android应用程序中集成Google Sign-In的示例

在本示例中,我们将在Android应用程序中集成Google Sign-In。一旦用户成功通过Google Sign-In登录,我们将重定向到下一个活动(ProfileActivity)并检索用户详细信息。

我们需要将下载的’google-services.json’文件粘贴到我们的Android项目应用程序目录中。

在Android应用中集成Google登录

必要的权限

在AndroidMenifest.xml文件中添加Internet权限。

<uses-permission android:name="android.permission.INTERNET" />

build.gradle(项目)

build.gradle 文件中添加以下依赖项。

dependencies{
classpath 'com.google.gms:google-services:3.1.0'
}

build.gradle(模块)

dependencies {
    implementation 'com.google.android.gms:play-services-auth:11.6.0'
    implementation 'com.github.bumptech.glide:glide:3.7.0'
}
apply plugin: 'com.google.gms.google-services'

activity_main.xml

在activity_main.xml文件中添加TextView和Google SignInButton。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="gloginexample.example.com.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:textSize="20dp"
        android:text="This is main activity, sign in to move next activity." />

    <com.google.android.gms.common.SignInButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/sign_in_button"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp">

    </com.google.android.gms.common.SignInButton>

</RelativeLayout>

MainActivity.java

在MainActivity.java类中,我们调用Auth.GoogleSignInApi.getSignInIntent()方法通过Google Sign-In API登录。Google API的GoogleApiClient.OnConnectionFailedListener接口重写其未实现的方法onConnectionFailed(ConnectionResult),该方法返回连接失败的结果。GoogleApiClient类用于管理Android应用程序与Google Sign-In API之间的连接。

package gloginexample.example.com;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
    SignInButton signInButton;
    private GoogleApiClient googleApiClient;
    TextView textView;
    private static final int RC_SIGN_IN = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GoogleSignInOptions gso =  new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
        googleApiClient=new GoogleApiClient.Builder(this)
                .enableAutoManage(this,this)
                .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
                .build();



        signInButton=(SignInButton)findViewById(R.id.sign_in_button);
        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
                startActivityForResult(intent,RC_SIGN_IN);
            }
        });


    }


    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==RC_SIGN_IN){
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }
    private void handleSignInResult(GoogleSignInResult result){
        if(result.isSuccess()){
            gotoProfile();
        }else{
            Toast.makeText(getApplicationContext(),"Sign in cancel",Toast.LENGTH_LONG).show();
        }
    }
    private void gotoProfile(){
        Intent intent=new Intent(MainActivity.this,ProfileActivity.class);
        startActivity(intent);
    }
}

activity_profile.xml

在 activity_profile.xml 文件中添加以下组件。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="gloginexample.example.com.ProfileActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">
        <ImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:id="@+id/profileImage"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/name"
            android:text="name"
            android:textSize="20dp"
            android:layout_marginTop="20dp"/>
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/email"
        android:textSize="20dp"
        android:text="email"
        android:layout_marginTop="20dp"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/userId"
            android:textSize="20dp"
            android:text="id"
            android:layout_marginTop="20dp"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/logoutBtn"
            android:text="Logout"
            android:layout_marginTop="30dp"/>
    </LinearLayout>

</RelativeLayout>

创建一个ProfileActivity.java类,在成功登录后显示用户详细信息。

ProfileActivity.java

在这个类中,如果用户成功登录,我们将检索用户详细信息。GoogleSignInResult类实现了Result接口,表示调用Google Play服务API方法的最终结果。

GoogleSignInAccount类保存用户的基本信息。

package gloginexample.example.com;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

public class ProfileActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
    Button logoutBtn;
    TextView userName,userEmail,userId;
    ImageView profileImage;
    private GoogleApiClient googleApiClient;
    private GoogleSignInOptions gso;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        logoutBtn=(Button)findViewById(R.id.logoutBtn);
        userName=(TextView)findViewById(R.id.name);
        userEmail=(TextView)findViewById(R.id.email);
        userId=(TextView)findViewById(R.id.userId);
        profileImage=(ImageView)findViewById(R.id.profileImage);

        gso =  new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        googleApiClient=new GoogleApiClient.Builder(this)
                .enableAutoManage(this,this)
                .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
                .build();


        logoutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(
                        new ResultCallback<Status>() {
                            @Override
                            public void onResult(Status status) {
                                if (status.isSuccess()){
                                    gotoMainActivity();
                                }else{
                                    Toast.makeText(getApplicationContext(),"Session not close",Toast.LENGTH_LONG).show();
                                }
                            }
                        });
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        OptionalPendingResult<GoogleSignInResult> opr= Auth.GoogleSignInApi.silentSignIn(googleApiClient);
        if(opr.isDone()){
            GoogleSignInResult result=opr.get();
            handleSignInResult(result);
        }else{
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(@NonNull GoogleSignInResult googleSignInResult) {
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }
    private void handleSignInResult(GoogleSignInResult result){
        if(result.isSuccess()){
            GoogleSignInAccount account=result.getSignInAccount();
            userName.setText(account.getDisplayName());
            userEmail.setText(account.getEmail());
            userId.setText(account.getId());
            try{
                Glide.with(this).load(account.getPhotoUrl()).into(profileImage);
            }catch (NullPointerException e){
                  Toast.makeText(getApplicationContext(),"image not found",Toast.LENGTH_LONG).show();
            }

        }else{
            gotoMainActivity();
        }
    }
    private void gotoMainActivity(){
        Intent intent=new Intent(this,MainActivity.class);
        startActivity(intent);
    }
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

输出:

在Android应用中集成Google登录

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程