0

我正在使用 Google Fit Android API 来检索健身数据,这一切都像一个魅力。我还想访问当前登录用户的名称,GoogleSignInAccount .getDisplayName() 应该可以访问该名称;

我已经问过这个问题,但不幸的是没有得到任何答复,我无法通过文档弄清楚。

示例代码:

 //Create a FitnessOptions instance, declaring the data types and access type (read and/or write) your app needs:
        FitnessOptions fitnessOptions = FitnessOptions.builder()
                .addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
                .addDataType(DataType.TYPE_SLEEP_SEGMENT, FitnessOptions.ACCESS_READ)
                .addDataType(DataType.TYPE_HEART_RATE_BPM, FitnessOptions.ACCESS_READ)
                .addDataType(DataType.AGGREGATE_HEART_RATE_SUMMARY, FitnessOptions.ACCESS_READ)
                .build();


        //Get an instance of the Account object to use with the API:
        GoogleSignInAccount account = GoogleSignIn.getAccountForExtension(this, fitnessOptions);
        GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);

        if (acct != null) {
            loggedInUser = account.getDisplayName();
        }

问题是 acct.getDisplayname().getGrantedScopes 就像一个魅力,我看到了授予的范围。当我尝试阅读 .getDisplayName 时,我总是得到 NULL。

4

1 回答 1

0

我决定使用另一种登录方式...

我现在使用它来配置登录选项和访问:

// 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()
        .requestProfile()
        .build();


mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

然后我们开始登录意图:


  Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, 000000);

现在我们处理结果:


@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 == 000000) {
        // 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 而不是 AWS 的 ApiException.class

于 2022-01-02T21:16:38.190 回答