2

使用 Google Play 服务进行身份验证时一切正常:

String token = GoogleAuthUtil.getToken(mActivity, mEmail, "oauth2:" + DriveScopes.Drive);

使用令牌,我现在可以创建我的 Drive 实例并访问 Google Drive。但我意识到这仅支持 android 2.2 及更高版本。我需要支持android 2.1。

我尝试使用此代码来获取令牌:

AccountManager am = AccountManager.get(this);
Bundle options = new Bundle();
am.getAuthToken (
        account,
        "oauth2:" + DriveScopes.Drive,
        options,
        this,
        new OnTokenAcquired(this),
        null);

使用此代码时,我会得到一个令牌,但在使用它创建我的 Drive 实例时,我将无法访问 Google Drive。例如,当执行此代码时:

drive.files().list().setQ(trashed=false and title="'someTitle'").execute();

我会收到这个错误:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
    "code" : 401,
    "errors" : [ {
        "domain" : "global",
        "location" : "Authorization",
        "locationType" : "header",
        "message" : "Invalid Credentials",
        "reason" : "authError"
    } ],
    "message" : "Invalid Credentials"
}

这是创建我的 Drive 实例的方法:

    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
    b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
        public void initialize(JsonHttpRequest request) throws IOException {
            DriveRequest driveRequest = (DriveRequest) request;
            driveRequest.setPrettyPrint(true);
            driveRequest.setKey(CLIENT_ID);
            driveRequest.setOauthToken(token);
            driveRequest.setEnableGZipContent(true);
        }
    });

    drive = b.build();
4

2 回答 2

0

这似乎是正确的,但 AccountManager OAuth2 支持的问题取决于平台版本(Google 服务库等)。它可能适用于某些设备,但可能不适用于具有稍微不同的库的其他设备。确保它在 2.1 上始终如一地工作的唯一方法是使用 WebView 来获取令牌。如果某些设备上的 AccountManager 损坏或出现故障,您将无能为力。

于 2012-10-17T02:31:14.253 回答
0

好的,我已经解决了。问题实际上是我使用了错误的客户端 ID。使用 Google Play 服务时,我将客户端 ID 用于在 Google API 控制台中找到的已安装应用程序。使用 AccountManager 时,此 ID 不起作用,我不得不使用 API 密钥进行简单 API 访问。

编辑

发现这并不完全正确。对于不同的设备,使用的客户端 ID 似乎不同。

于 2012-10-18T09:54:58.073 回答