gpt4 book ai didi

android - 如何让我的 Android 应用程序使用 "Service Account"访问共享的 Google 日历?

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:17 26 4
gpt4 key购买 nike

我认为答案是肯定的,但我不确定该怎么做。我一直在使用 API 从设备上存储的日历中获取事件。例如

 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;
}
}

这很好用。问题是我需要查询存储在用户没有权限的服务器上的共享日历。我的应用程序创建了一个本地日历。我需要访问一个用户也没有权限的共享,并将存储在共享日历中的事件与本地日历(非同步)同步。我假设我可以使用服务帐户访问共享日历。

我已成功创建服务帐户并将该帐户添加到共享日历。现在呢????

似乎有几种使用服务帐户访问日历事件的方法,但我完全搞不清楚。显然,我想使用我一直在使用的 API,但我认为它只适用于与设备同步的日历。

我已经使用“GoogleCredentials”进行了调查,但我需要一些示例源代码才能完成这项工作。首先,当我创建服务帐户时,我使用 JSON 而不是 p12 将其导出。我不知道如何使用它。 API 似乎需要 p12。我也完全不知道如何在获得凭据后使用这些凭据。这是我开始使用的示例源:

    //String emailAddress = "123456789000-abc123def456@developer.gserviceaccount.com";
GoogleCredential credential = null;
JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
HttpTransport httpTransport = null;
try
{
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(emailAddress)
.setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12"))
.setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN))
.build();
}
catch (GeneralSecurityException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

有几个问题。 1)我无法编译它。我似乎无法让导入工作:

 import com.google.api.services.sqladmin.SQLAdminScopes;

假设我可以克服它,现在该怎么做。我不确定如何使用凭据访问远程日历。我需要的是从共享日历中获取事件列表。

我也一直在通过以下链接查看源代码以获取指导,但它不使用服务帐户:https://developers.google.com/google-apps/calendar/quickstart/android

此外,是否有一种方法可以 Hook 对基于服务器的共享日历的更改,以便在共享日历发生更改时收到 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;
}

一些注意事项:

最佳答案

我不是 Android 专家,但以下任一方法都适用于您的用例。

  1. 您的方法:使用服务帐户,将避免用户对您的应用程序进行身份验证。您可能想阅读有关“Delegating domain-wide authority”的内容',这将允许您的应用程序以您域中的用户身份进行 API 调用(也称为“模拟”用户)。我也找到了这个SO有帮助。

  2. 另一种方法:使用 Acl.Insert资源。这将要求用户每次登录到您的应用程序时进行身份验证。这是一个 example关于如何实现这一点。

从上面的示例源中,将范围设置为日历范围而不是 SQL 管理,看起来像这样:

GoogleCredential credential = new GoogleCredential.Builder()
...
.setServiceAccountScopes(CalendarScopes.CALENDAR)
.setServiceAccountPrivateKeyFromP12File(xxxx)
.build();

希望这对您有所帮助,祝您好运!

关于android - 如何让我的 Android 应用程序使用 "Service Account"访问共享的 Google 日历?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33947631/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com