📌  相关文章
📜  如何使用Android Studio创建Google登录界面?(1)

📅  最后修改于: 2023-12-03 14:52:02.646000             🧑  作者: Mango

如何使用Android Studio创建Google登录界面?

要在Android Studio中创建Google登录界面,可以按照以下步骤进行操作:

步骤一:创建Firebase项目

首先,需要在Firebase控制台创建一个项目。可以按照以下步骤进行操作:

  1. 打开Firebase控制台。
  2. 点击“添加项目”按钮。
  3. 输入项目名称并选择国家/地区,然后点击“继续”按钮。
  4. (可选)启用Google Analytics。
  5. 点击“创建项目”按钮。
步骤二:添加Firebase SDK和Google登录插件
  1. 打开Android Studio。
  2. 在项目级别的build.gradle文件中添加Firebase SDK依赖:
buildscript {
    // ...

    dependencies {
        // ...

        // Add the following line:
        classpath 'com.google.gms:google-services:4.3.4'
    }
}

// ...

dependencies {
    // ...

    // Add the following lines:
    implementation 'com.google.firebase:firebase-auth:19.4.0'
    implementation 'com.google.android.gms:play-services-auth:18.0.0'
}

// Add at the bottom of the file
apply plugin: 'com.google.gms.google-services'
  1. 在应用级别的build.gradle文件中,添加Google登录插件:
apply plugin: 'com.google.gms.google-services'
步骤三:创建Google登录按钮
  1. 在布局文件中创建一个Google登录按钮:
<com.google.android.gms.common.SignInButton
    android:id="@+id/google_sign_in_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"/>
  1. 在java文件中初始化Google登录按钮,并添加点击事件:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private SignInButton mGoogleSignInButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize the Google Sign In button
        mGoogleSignInButton = findViewById(R.id.google_sign_in_button);
        mGoogleSignInButton.setOnClickListener(this);
    }

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

    private void signIn() {
        // ...
    }
}
步骤四:实现Google登录
  1. 在signIn()方法中,使用以下代码实现Google登录:
private void signIn() {
    // Configure Google Sign In
    GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, googleSignInOptions);

    Intent signInIntent = googleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

其中,RC_SIGN_IN是一个请求码,用于在onActivityResult()方法中接收Google登录结果。

  1. 在onActivityResult()方法中,使用以下代码处理Google登录结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);

        try {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = task.getResult(ApiException.class);
            firebaseAuthWithGoogle(account.getIdToken());
        } catch (ApiException e) {
            // Google Sign In failed, update UI appropriately
            Log.w(TAG, "Google sign in failed", e);
            // ...
        }
    }
}
  1. 最后,在firebaseAuthWithGoogle()方法中,使用以下代码将Google登录凭据传递给Firebase进行验证:
private void firebaseAuthWithGoogle(String idToken) {
    AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        // ...
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        // ...
                    }
                }
            });
}

至此,我们已经完成了在Android Studio中创建Google登录界面的全部步骤。

注意:本文只是一个简单的指南,实际应用中可能需要更多的代码和配置。完整的代码可以从GitHub上的示例项目中获取:https://github.com/firebase/quickstart-android/tree/master/auth。