3

我已经使用此代码为我的 android 应用程序中使用的每个日历获取了 oAuth 令牌

private HashMap<String, String> getAuthrizedCalendarsOnPhone() {
    HashMap<String, String> authorized_calendars = new HashMap<String, String>();

    AccountManager acctmgr = AccountManager.get(app_context);
    Account[] accounts = acctmgr.getAccountsByType("com.google");

    for (Account account : accounts) {
        String auth_token_type = "oauth2:https://www.googleapis.com/auth/calendar";
        AccountManagerFuture<Bundle> amf = acctmgr.getAuthToken(account, auth_token_type, null, this, null, null);

        String authToken;
        try {
            Bundle authTokenBundle = amf.getResult();
            authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
        } catch(Exception e) {
            authToken = "";
        }
        authorized_calendars.put(account.name, authToken);
    }

    return authorized_calendars;
}

现在如何com.google.api.services.calendar.Calendar使用该 oAuth 令牌实例化一个对象,以便我可以代表该用户访问日历 api?

即我可以做这样的事情

private HashMap<String, HCEvent> getCalendarEvents(String calendar_name) {
    HashMap<String, HCEvent> return_map = new HashMap<String, HCEvent>();
    com.google.api.services.calendar.Calendar service = null; //create a Calendar object using the oauth token for associated with calendar_name
    com.google.api.services.calendar.model.Events events = service.events().list(calendar_name).setPageToken(pageToken).execute();

    /*
     * do something with the events
     */

    return return_map;
}
4

1 回答 1

3

在查看了一些 Google 日历 API 和示例之后,将令牌分配给日历的最佳方式似乎是在初始化它时。这需要一些设置,看看这个链接:

https://developers.google.com/google-apps/calendar/instantiate

如果您已经经历过,我深表歉意,但看起来您可以对该示例进行一些调整。

在 Calendar 初始化之前,这段代码被执行:

    GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
    response.accessToken, httpTransport, jsonFactory, clientId, clientSecret,
    response.refreshToken);

这又被用作日历初始化的一部分。

查看 GoogleAccessProtectedResource 的文档,似乎存在一个只接受访问令牌的构造函数。

http://javadoc.google-api-java-client.googlecode.com/hg/1.4.1-beta/com/google/api/client/googleapis/auth/oauth2/draft10/GoogleAccessProtectedResource.html#GoogleAccessProtectedResource(java. lang.String)

您可以使用之前在方法中请求的令牌,然后使用上面 google calendar 实例化链接中描述的其他几个对象,您应该能够使用给定的访问令牌正确实例化日历。

希望这可以帮助,

编辑

看起来 GoogleAccessProtectedResource 实际上将被弃用,或者已经被弃用。

javadoc 指出:

“已弃用。(计划在 1.8 中删除)使用 GoogleCredential”

http://javadoc.google-api-java-client.googlecode.com/hg/1.7.0-beta/com/google/api/client/googleapis/auth/oauth2/draft10/GoogleAccessProtectedResource.html

所以看起来您需要的是 GoogleCredential 来替换 GoogleAccessProtectedResource。我发现您可以使用访问令牌设置凭据,如下所示:

GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);

然后,您可以通过执行以下操作创建新日历:

Calendar service = new Calendar.Builder(httpTransport, jsonFactory,
            credential).build();

httpTransport 和 jsonFactory 与其他示例的类似。

祝你好运!

于 2013-08-30T19:02:39.070 回答