问题
I'm writing an android application which needs to read user's fitness data (steps, calories, etc) from a back end server. this server will read the data and push notifications to android app if necessary.
I managed to get the authentication part done and app is now sending the code recevied from oauth flow to the backend server (followed this example) and the server successfully exchanges the code access and refresh tokens.
The problem is I did not find any resource on how to access the fitness data from a backend server in the google samples. I found the library
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-fitness</artifactId>
<version>v1-rev16-1.21.0</version>
</dependency>
but did not find any guideline on how to use this in a backend server. Is there any guideline on how to access the fitness data from a backend server without user interaction?
Thanks in advance and I searched stackoverflow and internet with no success
回答1:
In case anyone needs this, there is javadoc available here. And here is a simple example of a batch request for the user's height and weight from the backend server:
GoogleCredential credential = new GoogleCredential().setAccessToken(activeUser.getAccessToken());
Fitness fitness = new Fitness.Builder(new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
credential)
.setApplicationName("MyApp")
.build();
BatchRequest batchRequest = new BatchRequest(new NetHttpTransport(), credential);
fitness.users()
.dataSources()
.datasets()
.get("me", "derived:com.google.weight:com.google.android.gms:merge_weight",
String.format("0-%d", System.nanoTime()))
.queue(batchRequest, new WeightRequestCallback(activeUser));
fitness.users()
.dataSources()
.datasets()
.get("me", "derived:com.google.height:com.google.android.gms:merge_height",
String.format("0-%d", System.nanoTime()))
.queue(batchRequest, new HeightRequestCallback(activeUser));
batchRequest.execute();
HeightRequestCallback
and WeightRequestCallback
extend JsonBatchCallback<Dataset>
来源:https://stackoverflow.com/questions/35740630/using-google-fit-api-from-a-backend-server