我已经使用此代码为我的 Android 应用程序中使用的每个日历获得了 oAuth token
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;
}
现在如何使用该 oAuth token 实例化 com.google.api.services.calendar.Calendar
对象,以便我可以代表该用户访问日历 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;
}
最佳答案
在查看了一些 Google Calendar API 和示例之后,似乎将 token 分配给日历的最佳方式是在初始化它时。这需要一些设置,请查看此链接:
https://developers.google.com/google-apps/calendar/instantiate
如果您已经通过它,我深表歉意,但看起来您可以对该示例进行一些调整。
就在日历初始化之前,这段代码被执行:
GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
response.accessToken, httpTransport, jsonFactory, clientId, clientSecret,
response.refreshToken);
这又被用作日历初始化的一部分。
查看 GoogleAccessProtectedResource 的文档,似乎存在一个只接收访问 token 的构造函数。
您可以使用之前已经在您的方法中请求的 token ,然后使用上面的谷歌日历实例化链接中描述的几个其他对象,您应该能够使用给定的访问 token 正确实例化日历。
希望对您有所帮助,
编辑
看起来 GoogleAccessProtectedResource 实际上将被弃用,或者已经被弃用。
javadoc 声明:
“已弃用。(计划在 1.8 中删除)使用 GoogleCredential”
所以看起来您需要的是 GoogleCredential 来替换 GoogleAccessProtectedResource。我发现您可以像这样使用访问 token 设置凭证:
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
然后您可以通过执行以下操作来创建新日历:
Calendar service = new Calendar.Builder(httpTransport, jsonFactory,
credential).build();
httpTransport 和 jsonFactory 与另一个示例中的类似。
祝你好运!
关于android - 如何在给定 oAuth token 的情况下实例化 com.google.api.services.calendar.Calendar 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18424610/