如何让我的 Android 应用程序使用“服务帐户”访问共享的 Google 日历?

Jus*_*ain 7 android google-calendar-api

我认为答案是肯定的,但我不知道该怎么做。我一直在使用 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我已成功创建服务帐户并将该帐户添加到共享日历。怎么办????

似乎有几种使用服务帐户访问日历事件的方法,但我完全感到困惑。显然,我想使用我一直在使用的 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();
    }
Run Code Online (Sandbox Code Playgroud)

有几个问题。1)我无法编译这个。我似乎无法让进口工作:

 import com.google.api.services.sqladmin.SQLAdminScopes;
Run Code Online (Sandbox Code Playgroud)

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

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

另外,有没有办法将更改挂钩到基于服务器的共享日历,以便在共享日历发生更改时收到 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;
}
Run Code Online (Sandbox Code Playgroud)

一些注意事项:

小智 7

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

  1. 您的方法:使用服务帐户,将避免让用户对您的应用程序进行身份验证。您可能想了解“委派域范围的权限”,这将允许您的应用程序以域中的用户(也称为“模拟”用户)的身份进行 API 调用。我还发现这个SO很有帮助。

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

从上面的示例源中,将范围设置为日历范围而不是 SQL Admin,如下所示:

GoogleCredential credential = new GoogleCredential.Builder()
    ...    
      .setServiceAccountScopes(CalendarScopes.CALENDAR)
      .setServiceAccountPrivateKeyFromP12File(xxxx)  
      .build();
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助,祝你好运!