- Google Calendar API Overview
- Next steps
- Android Calendar API
- Зачем!?
- Использовать недокументированное API — это ПЛОХО! Пнятненько?
- API Reference
- Resource types
- CalendarList
- Calendars
- Channels
- Colors
- Events
- Freebusy
- Settings
- #getaroom — Android Things & Google Calendar API, via Nearby API.
- Context
- Technical flow
- Step by step
- — Retrieving authorization code
- ‘mobile’ module
- -Transmitting code via Nearby API
- ‘things’ module
- — Retrieving authorization code
Google Calendar API Overview
The Google Calendar API is a RESTful API that can be accessed through explicit HTTP calls or via the Google Client Libraries. The API exposes most of the features available in the Google Calendar Web interface.
Following is a list of common terms used in the Google Calendar API:
Event An event on a calendar containing information such as the title, start and end times, and attendees. Events can be either single events or recurring events. An event is represented by an Event resource. Calendar A collection of events. Each calendar has associated metadata, such as calendar description or default calendar time zone. The metadata for a single calendar is represented by a Calendar resource. Calendar List A list of all calendars on a user’s calendar list in the Calendar UI. The metadata for a single calendar that appears on the calendar list is represented by a CalendarListEntry resource. This metadata includes user-specific properties of the calendar, such as its color or notifications for new events. Setting A user preference from the Calendar UI, such as the user’s time zone. A single user preference is represented by a Setting Resource. ACL An access control rule granting a user (or a group of users) a specified level of access to a calendar. A single access control rule is represented by an ACL resource.
Next steps
To get started with Google Calendar API:
To learn about developing with Google Workspace APIs, including handling authentication and authorization, refer to Get started as a Workspace developer.
To learn how to configure and run a simple Google Calendar API app, read the Quickstarts overview.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник
Android Calendar API
Зачем!?
Я столкнулся с такой задачей, когда писал приложение для составления своего университетского расписания. Удобно иметь свое расписание отдельно, да еще и стандартный календарь не поддерживает повторение событий через одну неделю, что необходимо для двухнедельного (чет./нечет.) расписания.
Идеей фикс была функция приложения, которая позволит “заполнить” введенным расписанием Android календарь. Плюсы очевидны: синхронизация с Google Calendar от google (простите за тавтологию), встроенные виджеты календаря (очень уж хорош этот виджет от HTC Sense) и гора виджетов от сторонних производителей, которые хоть покажут следующее событие, хоть загруженность недели, и т.д. Тут и понадобилась работа с календарем Android.
Использовать недокументированное API — это ПЛОХО! Пнятненько?
Неужели чтобы решить эту очевидную задачу необходимо использовать недокументированное API? Ответ – нет. Самый правильный метод использовать API Google Calendar, что я вам и советую сделать в своих разработках.
Но “правильный” метод налагает ряд ограничений:
• Нельзя использовать в отсутствии соединения с Интернет;
• Необходима синхронизация после заполнения календаря;
• Данные (а их не мало при заполнении целого года) идут до сервера а потом при синхронизации идут обратно, что, очевидно, увеличивает трафик в два раза.
По моему мнению, намного удобней использовать офлайн версию календаря, которую при любом удобном случае можно синхронизировать с гуглокалендарем. К сожалению google не позаботился о разработчиках под Android и не опубликовал официального API, но к нашей радости исходные коды Android открыты и умные люди уже давно нашли волшебные URI контент провайдеров.
Источник
API Reference
This API reference is organized by resource type. Each resource type has one or more data representations and one or more methods.
Resource types
For Acl Resource details, see the resource representation page.
Method | HTTP request | Description |
---|---|---|
URIs relative to https://www.googleapis.com/calendar/v3, unless otherwise noted | ||
delete | DELETE /calendars/ calendarId /acl/ ruleId | Deletes an access control rule. |
get | GET /calendars/ calendarId /acl/ ruleId | Returns an access control rule. |
insert | POST /calendars/ calendarId /acl | Creates an access control rule. |
list | GET /calendars/ calendarId /acl | Returns the rules in the access control list for the calendar. |
patch | PATCH /calendars/ calendarId /acl/ ruleId | Updates an access control rule. This method supports patch semantics. |
update | PUT /calendars/ calendarId /acl/ ruleId | Updates an access control rule. |
watch | POST /calendars/ calendarId /acl/watch | Watch for changes to ACL resources. |
CalendarList
For CalendarList Resource details, see the resource representation page.
Method | HTTP request | Description |
---|---|---|
URIs relative to https://www.googleapis.com/calendar/v3, unless otherwise noted | ||
delete | DELETE /users/me/calendarList/ calendarId | Removes a calendar from the user’s calendar list. |
get | GET /users/me/calendarList/ calendarId | Returns a calendar from the user’s calendar list. |
insert | POST /users/me/calendarList | Inserts an existing calendar into the user’s calendar list. |
list | GET /users/me/calendarList | Returns the calendars on the user’s calendar list. |
patch | PATCH /users/me/calendarList/ calendarId | Updates an existing calendar on the user’s calendar list. This method supports patch semantics. |
update | PUT /users/me/calendarList/ calendarId | Updates an existing calendar on the user’s calendar list. |
watch | POST /users/me/calendarList/watch | Watch for changes to CalendarList resources. |
Calendars
For Calendars Resource details, see the resource representation page.
Method | HTTP request | Description |
---|---|---|
URIs relative to https://www.googleapis.com/calendar/v3, unless otherwise noted | ||
clear | POST /calendars/ calendarId /clear | Clears a primary calendar. This operation deletes all events associated with the primary calendar of an account. |
delete | DELETE /calendars/ calendarId | Deletes a secondary calendar. Use calendars.clear for clearing all events on primary calendars. |
get | GET /calendars/ calendarId | Returns metadata for a calendar. |
insert | POST /calendars | Creates a secondary calendar. |
patch | PATCH /calendars/ calendarId | Updates metadata for a calendar. This method supports patch semantics. |
update | PUT /calendars/ calendarId | Updates metadata for a calendar. |
Channels
For Channels Resource details, see the resource representation page.
Method | HTTP request | Description |
---|---|---|
URIs relative to https://www.googleapis.com/calendar/v3, unless otherwise noted | ||
stop | POST /channels/stop | Stop watching resources through this channel. |
Colors
For Colors Resource details, see the resource representation page.
Method | HTTP request | Description |
---|---|---|
URIs relative to https://www.googleapis.com/calendar/v3, unless otherwise noted | ||
get | GET /colors | Returns the color definitions for calendars and events. |
Events
For Events Resource details, see the resource representation page.
Method | HTTP request | Description |
---|---|---|
URIs relative to https://www.googleapis.com/calendar/v3, unless otherwise noted | ||
delete | DELETE /calendars/ calendarId /events/ eventId | Deletes an event. |
get | GET /calendars/ calendarId /events/ eventId | Returns an event. |
import | POST /calendars/ calendarId /events/import | Imports an event. This operation is used to add a private copy of an existing event to a calendar. |
insert | POST /calendars/ calendarId /events | Creates an event. |
instances | GET /calendars/ calendarId /events/ eventId /instances | Returns instances of the specified recurring event. |
list | GET /calendars/ calendarId /events | Returns events on the specified calendar. |
move | POST /calendars/ calendarId /events/ eventId /move | Moves an event to another calendar, i.e. changes an event’s organizer. Required query parameters: destination |
patch | PATCH /calendars/ calendarId /events/ eventId | Updates an event. This method supports patch semantics. The field values you specify replace the existing values. Fields that you don’t specify in the request remain unchanged. Array fields, if specified, overwrite the existing arrays; this discards any previous array elements. |
quickAdd | POST /calendars/ calendarId /events/quickAdd | Creates an event based on a simple text string. Required query parameters: text |
update | PUT /calendars/ calendarId /events/ eventId | Updates an event. |
watch | POST /calendars/ calendarId /events/watch | Watch for changes to Events resources. |
Freebusy
For Freebusy Resource details, see the resource representation page.
Method | HTTP request | Description |
---|---|---|
URIs relative to https://www.googleapis.com/calendar/v3, unless otherwise noted | ||
query | POST /freeBusy | Returns free/busy information for a set of calendars. |
Settings
For Settings Resource details, see the resource representation page.
Method | HTTP request | Description |
---|---|---|
URIs relative to https://www.googleapis.com/calendar/v3, unless otherwise noted | ||
get | GET /users/me/settings/ setting | Returns a single user setting. |
list | GET /users/me/settings | Returns all user settings for the authenticated user. |
watch | POST /users/me/settings/watch | Watch for changes to Settings resources. |
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник
#getaroom — Android Things & Google Calendar API, via Nearby API.
May 6, 2018 · 12 min read
Android Things is one of those… well things, that I knew about in the back of my mind (I did see the I/O 2015, albeit extended). It popped back in my Life last week, and gave me the occasion to remember old love and express new one. Don’t be fooled, this is a technical how to article, how to setup access to the Google Calendar API on an Android Things application. It does not contain exhaustive code but represent a good overview of the relevant parts and how they fit together. Full Github Available
Side n o te : this represent my first real Medium contribution ever, so don’t hesitate to interact and let me know, especially if you’d like to see some other on a subject mentioned here but not in details. Cheers !
Context
From a developper perspective, Android things can be seen as a lite version of the android platform, designed to run on embedded systems where screen support is optional and traditional screen touched based interactions are not available. As such, some APIs are modified or removed. More on that in a sec.
On the other hand, it is augmented of a few APIs regarding bluetooth pairing and communication, wifi direct connection, user space drivers injection, Over The Air updates and more that is all explained here.
Let’s focus on the relevant parts regarding our goal of accessing Google Calendar data from Android Things.
However, production calendar apps will strongly benefit by making use of the Calendar Provider content provider, which works offline, receives pushes, is a good match for the platform.
Android Things doesn’t include the standard suite of system apps and content providers.
So we know we’ll have to use lower level libraries. Reading the Google Calendar API Android Quickstart, we see that the authentication required by the Google provided Java library relies on Google Sign-In.
Going back once again to Things, the documentation provides a handy list of what is and isn’t available :
… . At this point, I explored the avenue of using Firebase authentication, and then initialize the Java library. Maybe I’m not cool enough or something, but I couldn’t figure out how to extract tokens from firebase or construct compatible objects in any way. At that moment, I took a step back from trying to do everything in the Things, opting to figure out how to do authorization on an Android Phone application and then share and use it on Things. The resulting tech demo is the object of this publication.
For this article, I used the default Android Things image running on a raspberry PI 3.
Technical flow
- user taps a Sing in button in an Android Phone Application (APA)
- APA requests access (here with CALENDAR_READONLY scope) through the use of GoogleSigning configured for offline access
- APA obtains a one time redeemable auth code (a String)
- APA uses Android Nearby API to advertise and send the auth code
- Android Things Application (ATA) uses Android Nearby API to discover and retrieve the auth code
- ATA then exchanges it for an access token (and possibly a refresh token, see notes)
- ATA builds a valid GoogleCredentialfrom token(s)
- ATA builds Calendar API client with GoogleCredential
- ATA can now access the API through the client
- Optionally, the ATA can serialize the information on disk and deserialize on boot through the use of StoredCredentialDatastore (more on that later)
- The whole contraption works because both application have the same package name and are signed with the same certificate. As usual with OAuth and APIs app, you have to setup identifiers in your google Cloud console (or Google Firebase console), and then add the API to it.
- The auth code you obtain will allow you to get both tokens only when the user authorize the application for the first time. Subsequent authorization will only give you a code that will retrieve an access token, valid for one hour at most. You can manually remove access to an application from here. If you do so, the next auth code generated will be redeemable for a new pair of access and refresh tokens. For more information on OAuth, see here.
Step by step
Version of Android Studio used : 3.1.2
File → New → New Project
Now you have your favorite IDE set up with a project containing two modules, one name ‘mobile’ that will target phones and the other named ‘things’ that will target the PI.
— Retrieving authorization code
Let’s start by adding a Google singin button, following the instruction found here : https://developers.google.com/identity/sign-in/android/start-integrating
- add the Google play Services dependency to the module gradle file
- configure a project in the cloud console
To find your SHA-1 fingerprint
Now we’re ready to write some Kotlin code. I will not go into details, referring you to the complete github of this demo as well as various official documentation pages. That being said, you should be able to get a good idea by simply reading this article. Hopefully. Lemme know !
‘mobile’ module
Suffice to say we need to manage a GoogleSignIn object, setting it up for offline access. For that we create a class called GoogleSignInHelper, constructed as follow
the argument for .requestServerAuthCode comes from t he json file downloaded earlier. It is also visible in your project configuration in the Google Cloud Console.
With that, we can easily add a Sign in button to our app layout, with the following click listener in MobileMainActivity
and forward the result
To finally retrieve the authorization code and write it to the ViewModel class used by convenience.
A note on ModelView : for this demo, you just need to know that a model can hold instances of any types (including base ones like Boolean), and exposes them in an observable way. Meaning on one side you do model.setSomeValue(toSet), and on the other side, changes to someValue get dispatched to classes that decided to observe it. It’s a nice way to decouple pieces of code. Of course ModelView is way more powerful than that (and its dirty little secret regarding 😉 the observable pattern comes from LiveData , which you don’t have to concern yourself with right now)
-Transmitting code via Nearby API
Now we have the autorization code on the phone side, we need to transfert it to the Things application.
Following along the documentation, we add a singleton NearbyHelper class to handle Nearby advertising when an autorization code becomes available in the model. It’s actually MobileMainActivity that observes the model changes because there is one dangerous permission required by Nearby to request from the user. We uses easypermissions Firebase library to… ease… permission request process.
In the helper, the advertising code is simple as
Time to turn our attention to the Things module, to discover and retrieve the auth code.
‘things’ module
— Retrieving authorization code
Following the Nearby documentation again, we copy the NearbyHelper singleton class to the things module, and set it up as a discoverer.
The client code on ThingsMainActivity is different, for this demo it simply starts discovering in the onCreate method
As you can deduce from the init (constructor) call, Nearby uses a callback model for everything. Nearby API is almost symmetrical between the advertiser and the discoverer, except at connection establishing time.
- both advertiser and discoverer independently start doing their thing, described above (startAdvertising and startDiscovery)
- the discoverer discovers a endpoint, then requests connection. NearbyEndpointDiscoveryCallback:
- both advertiser and discoverer are advised of the connection attempt in onConnectionInitiated, they must both accept for the connection to be established, in our case they automatically do. The discoverer can inspect the result of the process in onConnectionResult. NearbyConnectionLifecycleCallback:
- after the connection is successfully established, everything is ready for data to be exchanged.
- In our case, we’ll transfer the authorization code String as a byteArray from thePhone application to the Things one.
- on the discoverer side, it’s received as follow
As of writing, there is no proper management for multiple authorization code transfers. I guess I let it as an exercice for the reader, and if you ever wanna Pull Request, be my guest ! 😉
At this point, here are logcat grabs of what happens
We’re happy we’ve used Nearby because data transfer is encrypted. The rest of the magic happens on the Thing side only. It consist in exchanging the code against an access token (and possibly a refresh token too), use those to build a GoogleCredential object and then initialize a Calendar client object with those credentials. Let’s dive in !
First, we’ll again add a singleton class. AuthHelper will be responsible for building and managing a GoogleCredential object. To do so, it simply observes when an auth code becomes available in model, and exchange it for a TokenResponse. CLIENT_SECRET_DATA comes from the file previously downladed when setting up the project in Google cloud console. It is alos available for download there.
with it, it can build valid credentials
At this point, we have a valid set of credentials. If this is the first time the user authorized your app, your credentials will contain both an access and refresh token. It will manage for you refreshing the access token using the refresh token when required. If the user had already authorize your app, you’ll only get an access token, valid for an hour at most. Depending on your use case, you could serialize the credentials as follow
Be warned though this will save a file on disk. i’m actually not sure how big of a security issue it is, probably quite large. That being said, it allows you to save both tokens and restore credentials on boot, meaning once authenticated, as long as the access is not revoked, it could go on forever !
It’s now time to introduce our last but not least singleton class GoogleCalendarHelper, responsible for initializing and managing a Calendar API client object. It observes the model, reacting to the login state.
pretty simple hu ?
Our ThingsMainActivity is now complete, the full class being as follow
And here is what the complete logcat on the things side should look, minus the specific events in your calendar. This completes our quest to have the Google Calendar API available in an Android Things application. \o/
Again, this is my first Medium contribution, thks for reading and please don’t hesitate to interact !
Источник