Android - 使用 Google 按钮登录并备份到 Google 云端硬盘

问题描述 投票:0回答:1

在我的 Android 应用程序中,我有一个 Google 登录按钮 - 当用户单击它时,他会登录到 Google 帐户,然后可以将数据库备份到 Google Drive。这工作正常,但现在 GoogleSignIn 已被弃用。

用户单击按钮后,我检查是否已签名:

     if(!isSignedIn()) {
            requestSignIn();}
    
    private boolean isSignedIn() {
        return GoogleSignIn.getLastSignedInAccount(this) != null && GoogleSignIn.hasPermissions(GoogleSignIn.getLastSignedInAccount(this));
    }

 private void requestSignIn() {
        GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .requestScopes(new Scope(DriveScopes.DRIVE_FILE))
                .build();

        GoogleSignInClient client = GoogleSignIn.getClient(this, signInOptions);

        Intent signInIntent = client.getSignInIntent();
        someActivityResultLauncher.launch(signInIntent);
    }

   final ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    handleSignInInent(result.getData());
                } else {
                    showMsgSnack(getString(R.string.nologin));
                }
            });

    private void handleSignInInent(Intent data) {
        GoogleSignIn.getSignedInAccountFromIntent(data)
                .addOnSuccessListener(googleSignInAccount -> {
                    GoogleAccountCredential credential = GoogleAccountCredential.
                            usingOAuth2(BackupActivity.this, Collections.singleton(DriveScopes.DRIVE_FILE));
etc...

正如 Google 建议使用凭据管理器,所有 GoogleSignIn 内容均已弃用。

我尝试遵循文档,但没有成功:

GetCredentialRequest request = new GetCredentialRequest.Builder()
  .addGetCredentialOption(googleIdOption)
  .build();

// Launch sign in flow and do getCredential Request to retrieve the credentials
credentialManager.getCredentialAsync(
  requireActivity(),
  request,
  cancellationSignal,
  <executor>,
  new CredentialManagerCallback<GetCredentialResponse, GetCredentialException>() {
    @Override
    public void onResult(GetCredentialResponse result) {
      handleSignIn(result);
    }

    @Override
    public void onError(GetCredentialException e) {
      handleFailure(e);
    }
  }
);

public void handleSignIn(GetCredentialResponse result) {
  // Handle the successfully returned credential.
  Credential credential = result.getCredential();

  if (credential instanceof PublicKeyCredential) {
    String responseJson = ((PublicKeyCredential) credential).getAuthenticationResponseJson();
    // Share responseJson i.e. a GetCredentialResponse on your server to validate and authenticate
  } else if (credential instanceof PasswordCredential) {
    String username = ((PasswordCredential) credential).getId();
    String password = ((PasswordCredential) credential).getPassword();
    // Use id and password to send to your server to validate and authenticate
  } else if (credential instanceof CustomCredential) {
    if (GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL.equals(credential.getType())) {
      try {
        // Use googleIdTokenCredential and extract id to validate and
        // authenticate on your server
        GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential.createFrom(((CustomCredential) credential).getData());
      } catch (GoogleIdTokenParsingException e) {
        Log.e(TAG, "Received an invalid Google ID token response", e);
      }
    } else {
      // Catch any unrecognized custom credential type here.
      Log.e(TAG, "Unexpected type of credential");
    }
  } else {
    // Catch any unrecognized credential type here.
    Log.e(TAG, "Unexpected type of credential");
  }
}

它说

GetCredentialRequest.Builder() Expected 1 arguments but found 0
,也无法解析符号“credentialManager”,等等...

最主要的是,这仅适用于 API>=34,我真的不想保留我的旧代码和凭证管理器,也仅适用于 API 34 及更高版本。

还有一个问题是,如何检查用户是否已经登录?

有人可以帮助编写具有向后兼容性的工作代码吗?

android google-signin android-credential-manager
1个回答
0
投票

在我看来,您没有使用 Jetpack 库,而是直接使用框架 API。您应该切换到 Jetpack 库 (androidx),它将提供不带参数的 Builder 类,并且还为您的应用程序提供向后兼容的 API。

请记住,凭据管理器库仅为您的应用程序提供“身份验证”。您曾提到您还需要访问用户的云端硬盘。为此,您需要使用属于 Google 身份服务一部分的单独“授权”API,请参阅此开发人员文档了解详细信息。如果您遇到问题,请发布一个包含详细信息的单独问题,我会尽力帮助您解决该问题。

© www.soinside.com 2019 - 2024. All rights reserved.