7

I'm using the new Google Drive Android API and I can connect, and do all that it will allow me to do, but in order to use the SpreadsheetService, I need to extract the accountName/email from the signed in user.

How do I do that?

Here's the code where I connect the Google Drive API. It works fine.

private void connect() {

    if (isGooglePlayServicesAvailable()) {
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Drive.API)
                    .addScope(Drive.SCOPE_FILE)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
        }
        // And, connect!

        if (!mGoogleApiClient.isConnecting() && !mGoogleApiClient.isConnected()) {
            mGoogleApiClient.connect();
            writeLog("Connecting...");
        }

    }
}

Here's where I'm using the SpreadsheetService API, but I need the account name to get the token.

String accountName = "???"; // how do I get this From GoogleClientApi / mGoogleApiClient ?
String accessToken = GoogleAuthUtil.getTokenWithNotification(GDriveActivity.this, accountName, scope, null);
SpreadsheetService service = new SpreadsheetService("v1");

I have tried this adding this:

String accountName = Plus.AccountApi.getAccountName(mGoogleApiClient);

... in the onConnected method, but it throws a NullPointerException.

Also, here are my permissions:

<uses-permission
    android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission
    android:name="android.permission.VIBRATE" />
<uses-permission
    android:name="android.permission.INTERNET" />
<uses-permission
    android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
    android:name="android.permission.GET_ACCOUNTS" />
<uses-permission
    android:name="android.permission.NETWORK" />
<uses-permission
    android:name="android.permission.USE_CREDENTIALS" />
4

2 回答 2

14

您需要添加:

                    .addApi(Plus.API)

在构建客户端时。然后这将适用于onConnected(Bundle)

String accountName = Plus.AccountApi.getAccountName(mGoogleApiClient);

假设您已经拥有正确的权限(您已经拥有):

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
于 2014-04-07T05:01:18.300 回答
4

我现在已恢复到以下内容,这使我可以随时获取帐户。

当我问这个问题时,我的印象是我只有在最初连接时才能得到它。显然我错了。

private String getAccountName() {

    String accountName = null;

    AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
    Account[] list = manager.getAccounts();
    for (Account account : list) {
        if (account.type.equalsIgnoreCase("com.google")) {
            accountName = account.name;
            break;
        }
    }
    return accountName;
}

当然,在 AndroidManifest 中包括以下权限:

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
于 2014-10-14T15:31:08.303 回答