在Android應用中集成Google登錄
在本教程中,我們將使用 Google API 在我們的Android應用程序中集成 Google登錄 功能。愛掏網 - it200.com將Google API合并到Android應用程序中可以幫助用戶使用Google賬戶登錄。愛掏網 - it200.com
要在我們的應用程序中集成Google登錄API,我們需要將應用程序配置到Google開發者帳號并下載 ‘google-service.json’ 文件用于Android應用程序。愛掏網 - it200.com
1. 在https://developers.google.com/identity/sign-in/android/start-integrating上創建一個Google開發者帳號,并點擊’GET A CONFIGURATION FILE’。愛掏網 - it200.com
2. 填寫所有的應用細節,選擇您的國家/地區,然后點擊“選擇并配置服務”。愛掏網 - it200.com
3. 成功創建谷歌應用支持配置后,將會重定向到下一個窗口以選擇谷歌服務。愛掏網 - it200.com我們將選擇谷歌登錄服務。愛掏網 - it200.com
4. 現在,我們需要提供應用程序的簽名證書 SHA-1 密鑰。愛掏網 - it200.com
5. 有兩種不同的方式生成證書的SHA-1密鑰。愛掏網 - it200.com
- 通過使用命令提示符。愛掏網 - it200.com
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自身。愛掏網 - it200.com
- 打開Android項目。愛掏網 - it200.com
- 從右側面板打開Gradle選項卡。愛掏網 - it200.com
- 雙擊’signingReport’。愛掏網 - it200.com
- 我們將會在’Gradle Console’上找到我們的應用SHA-1密鑰。愛掏網 - it200.com
6. 將生成的SHA-1密鑰粘貼到Google Sign-In服務中,然后點擊’啟用Google Sign-In’和’生成認證文件’。愛掏網 - it200.com
7. 現在下載 ‘google-services.json’ 文件,并將其集成到Android應用程序中。愛掏網 - it200.com
在Android應用程序中集成Google Sign-In的示例
在本示例中,我們將在Android應用程序中集成Google Sign-In。愛掏網 - it200.com一旦用戶成功通過Google Sign-In登錄,我們將重定向到下一個活動(ProfileActivity)并檢索用戶詳細信息。愛掏網 - it200.com
我們需要將下載的’google-services.json’文件粘貼到我們的Android項目應用程序目錄中。愛掏網 - it200.com
必要的權限
在AndroidMenifest.xml文件中添加Internet權限。愛掏網 - it200.com
<uses-permission android:name="android.permission.INTERNET" />
build.gradle(項目)
在 build.gradle 文件中添加以下依賴項。愛掏網 - it200.com
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。愛掏網 - it200.com
<?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登錄。愛掏網 - it200.comGoogle API的GoogleApiClient.OnConnectionFailedListener接口重寫其未實現的方法onConnectionFailed(ConnectionResult),該方法返回連接失敗的結果。愛掏網 - it200.comGoogleApiClient類用于管理Android應用程序與Google Sign-In API之間的連接。愛掏網 - it200.com
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 文件中添加以下組件。愛掏網 - it200.com
<?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類,在成功登錄后顯示用戶詳細信息。愛掏網 - it200.com
ProfileActivity.java
在這個類中,如果用戶成功登錄,我們將檢索用戶詳細信息。愛掏網 - it200.comGoogleSignInResult類實現了Result接口,表示調用Google Play服務API方法的最終結果。愛掏網 - it200.com
GoogleSignInAccount類保存用戶的基本信息。愛掏網 - it200.com
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) {
}
}
輸出: