如何让我的Android应用程序使用“a”;服务帐户“;要访问共享的谷歌日历?
我想答案是肯定的,但我不知道怎么做。我一直在使用API从设备上存储的日历中获取事件。e、 g如何让我的Android应用程序使用“a”;服务帐户“;要访问共享的谷歌日历?,android,google-calendar-api,Android,Google Calendar Api,我想答案是肯定的,但我不知道怎么做。我一直在使用API从设备上存储的日历中获取事件。e、 g public static ArrayList<MINCalendarEvent> queryEvents(long startMillis, long endMillis) throws MINPermissionException { if ( ContextCompat.checkSelfPermission(MINMainActivity.getSharedInstan
public static ArrayList<MINCalendarEvent> queryEvents(long startMillis, long endMillis) throws MINPermissionException
{
if ( ContextCompat.checkSelfPermission(MINMainActivity.getSharedInstance(), Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED )
{
throw new MINPermissionException(NO_PERMISSION);
}
else
{
ArrayList<MINCalendarEvent> eventArray = new ArrayList<MINCalendarEvent>();
Cursor cur = CalendarContract.Instances.query(MINMainActivity.getSharedInstance().getContentResolver(), EVENT_PROJECTION, startMillis, endMillis);
int numItems = cur.getCount();
Log.d("MINCalendarUtils.queryEvents", "Number of events retrieved: " + numItems);
while (cur.moveToNext())
{
MINCalendarEvent event = new MINCalendarEvent();
event.calendarID = cur.getLong(EVENT_PROJECTION_CALENDAR_ID);
event.organizer = cur.getString(EVENT_PROJECTION_ORGANIZER);
event.title = cur.getString(EVENT_PROJECTION_TITLE);
event.eventLocation = cur.getString(EVENT_PROJECTION_EVENT_LOCATION);
event.description = cur.getString(EVENT_PROJECTION_DESCRIPTION);
event.dtStart = cur.getLong(EVENT_PROJECTION_DTSTART);
event.dtEnd = cur.getLong(EVENT_PROJECTION_DTEND);
event.eventTimeZone = cur.getString(EVENT_PROJECTION_EVENT_TIMEZONE);
event.eventEndTimeZone = cur.getString(EVENT_PROJECTION_EVENT_END_TIMEZONE);
event.duration = cur.getString(EVENT_PROJECTION_DURATION);
event.allDay = (cur.getInt(EVENT_PROJECTION_ALL_DAY) != 0);
event.rRule = cur.getString(EVENT_PROJECTION_RRULE);
event.rDate = cur.getString(EVENT_PROJECTION_RDATE);
event.availability = cur.getInt(EVENT_PROJECTION_AVAILABILITY);
event.guestsCanModify = (cur.getInt(EVENT_PROJECTION_GUESTS_CAN_MODIFY) != 0);
event.guestsCanInviteOthers = (cur.getInt(EVENT_PROJECTION_GUESTS_CAN_INVITE_OTHERS) != 0);
event.guestsCanSeeGuests = (cur.getInt(EVENT_PROJECTION_GUESTS_CAN_SEE_GUESTS) != 0);
eventArray.add(event);
}
return eventArray;
}
}
有几个问题。1) 我无法编译此事件。我似乎无法让导入正常工作:
import com.google.api.services.sqladmin.SQLAdminScopes;
假设我能克服这些,现在怎么办。我不确定如何使用凭据访问远程日历。我需要的是从共享日历中获取事件列表
我还在下面的链接中查看了源代码,以获取指导,但它没有使用服务帐户:
另外,是否有一种方法可以将更改挂接到基于服务器的共享日历,以便在共享日历发生更改时收到ping命令
有什么帮助吗
编辑工作代码
根据Andres的回答,我整理了以下代码:
public static void calendarAuthenticate()
{
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
MINAppConfiguration appConfig = MINAppConfiguration.getSharedInstance();
// Application Name
appName = appConfig.getCurrentAppInfo().appName;
// Directory to store user credentials for this application;
//dataStoreDir = new File(appConfig.appDirectoryOnDevice);
// Instance of the JSON factory
jsonFactory = JacksonFactory.getDefaultInstance();
// Instance of the scopes required
scopes = new ArrayList<String>();
scopes.add(CalendarScopes.CALENDAR_READONLY);
// Http transport creation
httpTransport = AndroidHttp.newCompatibleTransport();
java.io.File licenseFile = getSecretFile();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("account-1@handy-contact-762.iam.gserviceaccount.com")
.setServiceAccountScopes(scopes)
.setServiceAccountPrivateKeyFromP12File(licenseFile)
.build();
com.google.api.services.calendar.Calendar.Builder builder = new com.google.api.services.calendar.Calendar.Builder(httpTransport, jsonFactory, credential);
builder.setApplicationName(appName);
com.google.api.services.calendar.Calendar client = builder.build();
// List the next 10 events from the target calendar.
DateTime now = new DateTime(System.currentTimeMillis());
com.google.api.services.calendar.Calendar.Events.List list = client.events().list("mobilityinitiative.com_qfvbdrk368f9la06hacb4bduos@group.calendar.google.com");
list.setMaxAttendees(10);
list.setTimeMin(now);
list.setOrderBy("startTime");
list.setSingleEvents(true);
Events events = list.execute();
List<Event> items = events.getItems();
if (items.size() == 0)
{
Log.d(TAG, "No upcoming events found.");
}
else
{
Log.d(TAG, "Upcoming events");
for (Event event : items) {
DateTime start = event.getStart().getDateTime();
if (start == null) {
start = event.getStart().getDate();
}
Log.d(TAG, event.getSummary() + " (" + start + ")\n");
}
}
}
catch (GeneralSecurityException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
thread.start();
}
public static java.io.File getSecretFile()
{
File f = new File(MINMainActivity.getSharedInstance().getCacheDir()+ "/" +"google_calendar_secret.p12");
if (f.exists())
{
f.delete();
}
try
{
InputStream is = MINMainActivity.getSharedInstance().getAssets().open("google_calendar_secret.p12");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return f;
}
公共静态无效日历身份验证()
{
Thread Thread=新线程(new Runnable()
{
@凌驾
公开募捐
{
尝试
{
MINAppConfiguration appConfig=MINAppConfiguration.getSharedInstance();
//应用程序名称
appName=appConfig.getCurrentAppInfo().appName;
//用于存储此应用程序的用户凭据的目录;
//dataStoreDir=新文件(appConfig.appDirectoryOnDevice);
//JSON工厂的实例
jsonFactory=JacksonFactory.getDefaultInstance();
//所需作用域的实例
scopes=newarraylist();
添加(CalendarScopes.CALENDAR\u只读);
//Http传输创建
httpTransport=AndroidHttp.newCompatibleTransport();
java.io.File licenseFile=getSecretFile();
GoogleCredential credential=新建GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(“帐户-1@handy-联系人:762.iam.gserviceaccount.com)
.setServiceAccountScopes(范围)
.SetServiceAccountPrivateKeyFromp12文件(许可证文件)
.build();
com.google.api.services.calendar.calendar.Builder=new com.google.api.services.calendar.calendar.Builder(httpTransport、jsonFactory、凭证);
builder.setApplicationName(appName);
com.google.api.services.calendar.calendar客户端=builder.build();
//列出目标日历中接下来的10个事件。
DateTime now=新的日期时间(System.currentTimeMillis());
com.google.api.services.calendar.calendar.Events.List List=client.Events().List(“mobilityinitiative.com_qfvbdrk368f9la06hacb4bduos@group.calendar.google.com");
与会者名单(10人);
list.setTimeMin(现在);
list.setOrderBy(“startTime”);
列表。设置SingleEvents(真);
Events=list.execute();
List items=events.getItems();
如果(items.size()==0)
{
Log.d(标记“未发现即将发生的事件”);
}
其他的
{
Log.d(标签“即将到来的事件”);
用于(事件:项目){
DateTime start=event.getStart().getDateTime();
if(start==null){
start=event.getStart().getDate();
}
Log.d(标记,event.getSummary()+”(“+start+”)\n”);
}
}
}
捕获(一般安全性例外e)
{
e、 printStackTrace();
}
捕获(IOE异常)
{
e、 printStackTrace();
}
}
});
thread.start();
}
公共静态java.io.File getSecretFile()
{
文件f=新文件(MINMainActivity.getSharedInstance().getCacheDir()+“/”+“google\u calendar\u secret.p12”);
如果(f.exists())
{
f、 删除();
}
尝试
{
InputStream is=MINMainActivity.getSharedInstance().getAssets().open(“google\u calendar\u secret.p12”);
int size=is.available();
字节[]缓冲区=新字节[大小];
is.read(缓冲区);
is.close();
FileOutputStream fos=新的FileOutputStream(f);
写入(缓冲区);
fos.close();
}
捕获(例外e)
{
抛出新的运行时异常(e);
}
返回f;
}
几点注意:
- 确保您正确创建了服务帐户,并且该帐户具有相应的权限:
- 确保您是在后台线程中进行呼叫。如果您尝试使用UI线程进行调用,它将失败
- 确保将项目添加到日历中,以便您知道它正在工作:)
GoogleCredential credential = new GoogleCredential.Builder()
...
.setServiceAccountScopes(CalendarScopes.CALENDAR)
.setServiceAccountPrivateKeyFromP12File(xxxx)
.build();
希望这对你有帮助,祝你好运 我在上面添加了一个更新部分,其中包含我能够拼凑的源代码。它仍然有问题。有什么想法吗?为了服务
GoogleCredential credential = new GoogleCredential.Builder()
...
.setServiceAccountScopes(CalendarScopes.CALENDAR)
.setServiceAccountPrivateKeyFromP12File(xxxx)
.build();