- Google Fit for Android: History API
- 1. Project Setup
- Step 1: Set Up the Developer Console
- Step 2: Create the Android Project
- 2. Using the Google Fit History API
- Step 1: Displaying Data Over Time
- Step 2: Displaying Data for Today
- Step 3: Inserting Data Into Google Fit
- Step 4: Update Data on Google Fit
- Step 5: Deleting Data From Google Fit
- Conclusion
- Google Fit for Android: Sessions API
- 1. Project Setup
- Step 1: Set Up the Developer Console
- Step 2: Set Up the Android Project
- 2. Using the Sessions API
- Starting and Stopping a Session
- Inserting Into Google Fit
- Reading Session Data
- Deleting Session Data
- Conclusion
Google Fit for Android: History API
Google Fit is a platform that allows developers to build applications that are focused on user fitness data. One of the tools Google has provided is Google Fit for Android, which is available as a package in Google Play Services.
In a previous tutorial, we explored how to use the Google Fit Recording API to store fitness data through Google Play Services. This tutorial expands on the topic by exploring how to access and update data stored in Google Fit using the History API.
What makes Google Fit powerful is that fitness data is stored through Google Cloud Services, which allows it to be accessed and analyzed at a later time. While the Sensors and Recording APIs are focused on gathering fitness data from an Android device, the History API is intended to give developers easy access to that stored data.
This tutorial walks you through a sample project that demonstrates how to work with the History API. The finished product can be downloaded from GitHub.
1. Project Setup
Step 1: Set Up the Developer Console
To use Google Fit, you need to create an OAuth 2.0 client ID and register your application through the Google Developer Console. You can find a detailed explanation of how to set up a project in the Google Developer Console in my tutorial about the Google Fit Sensors API.
Step 2: Create the Android Project
Once you have your application configured for authentication in the Google Developer Console, use the package name you registered to create a new Android application with a minimum SDK of 9 and an empty Activity .
With the base Android app created, open build.gradle and include Google Play Services under the dependencies node and sync your app.
You should now be able to include the necessary Google Play Services classes into your application. Before we dive into the Java code for this tutorial, open activity_main.xml and modify it so that it includes five Button items that we will use to demonstrate some of the functionality of the History API.
When you run your application, the user interface should look like this:
To continue setting up your project, open MainActivity.java and implement the following callbacks and required methods:
- GoogleApiClient.ConnectionCallbacks
- GoogleAPiClient.OnConnectionFailedListener
- View.OnClickListener
You also need to add a member variable for the GoogleApiClient and a set of references to your Button objects, as shown below.
The final thing you need to do to set up your sample project is connect to Google Play Services. This can be done at the end of the onCreate() method.
With the above code, we connect to Google Play Services and request access to the History API in Google Fit, as well as permission to read and write activity data. By adding the enableAutoManage property, Google Play Services manages connecting and disconnecting properly.
2. Using the Google Fit History API
Using the History API, you can retrieve and aggregate data, insert values that you have gathered in your app or delete data that may be stored. One important thing to note is that all of the History API operations in this tutorial must be done off of the main thread. In other words, each operation takes place in an AsyncTask :
Step 1: Displaying Data Over Time
One task that you may want to do is use or display data that has been collected over time. You can do this by creating a new DataReadRequest for a specific type of data that fits some query parameters.
You can group this data together in Bucket objects by time or sessions. For this example, you request aggregated step data for the last week and bucket that data by day.
Once you have your DataReadRequest created, you can request data from the GoogleApiClient using the Fitness.HistoryApi.readData command. You also call await on the API client so that the thread stalls for up to a minute while waiting for the query. If something goes wrong, the thread continues after that minute.
If the call returns successfully, you are able to access the user’s fitness data from the DataReadResult object. Your step data request is returned in Bucket objects, though other types of data are returned as a List of DataSet objects. Depending on the type of data returned, you can access it with the following code:
You can then retrieve each DataPoint from the DataSet objects that have been returned.
If an app on the user’s device has turned on the Recording API within the last week, then you receive data for each day that it was active. The logs from the above code should look similar to this:
Step 2: Displaying Data for Today
You now know how to retrieve Google Fit data based on a timeframe. One common use case developers have is needing data for the current day. Luckily, Google has made this easy by adding the Fitness.HistoryApi.readDailyTotal call, which creates a DailyTotalResult object containing data collected for the day.
The above code logs out the user’s step data for the day.
Step 3: Inserting Data Into Google Fit
While being able to read data from Google Fit is important, there may be times where you need to add your own collected data to the Google Fit data store. To do this, you select a time range for the data and create a DataSource object that represents the kind of information that you put into Google Fit. Next, you create a DataSet object and place a new DataPoint into it for the insert operation.
For this example, we are going to assume the user has walked one million steps, or roughly 500 miles, and insert that raw step data into the last hour of the user’s activity.
It is important to note that if you select a time range that spans multiple days, the number of steps that you insert is evenly distributed among those days.
After creating the DataSet object, you can insert it into the Google Fit data store using the History API’s insertData call.
If you insert the user’s steps and then read the activity log, you should see something similar to the following:
Step 4: Update Data on Google Fit
Once you have inserted data into Google Fit, you are unable to insert any more data of that type if it overlaps with existing data. This could cause a problem if the user had walked 500 miles and then walked 500 more.
To solve this, you need to use the updateData call. Luckily, updating data is almost identical to inserting new data, except that you create a DataUpdateRequest instead.
If you were to log out the user’s steps for the day after running the above, you should see over two million steps.
Step 5: Deleting Data From Google Fit
The final operation available through the Google Fit History API is the ability to delete data that you have stored in Google Fit. This can be done by selecting a date range, creating a DataDeleteRequest object, and calling deleteData from the History API. While you can delete your own inserted data, data stored by Google Fit is not removed.
Conclusion
As you have seen, the History API is an incredibly powerful tool for accessing and manipulating the Google Fit data store. While other Google Fit APIs are intended to gather data, the History API allows you to maintain and access data for analysis. You should now be able to create amazing apps that take advantage of this feature.
Источник
Google Fit for Android: Sessions API
Google Fit is a platform that allows developers to build applications that are focused on user fitness data. One of the tools Google has provided is Google Fit for Android, which is available as a package in Google Play Services.
Earlier in this series, we have explored how to store fitness data through Google Play Services using the Recording API and how to access and update data through the History API. In this tutorial, we expand on these ideas with the Sessions API, which allows you to organize activity data by time intervals.
This tutorial walks you through a sample project that demonstrates how to work with the Sessions API. The finished project can be downloaded from GitHub.
1. Project Setup
Step 1: Set Up the Developer Console
To use Google Fit, you need to create an OAuth 2.0 client ID and register your application through the Google Developer Console. You can find a detailed explanation of how to set up a project in the Google Developer Console in my tutorial about the Google Fit Sensors API.
Step 2: Set Up the Android Project
Once you have your application configured for authentication in the Google Developer Console, use the package name you registered to create a new Android application with an empty Activity .
With the Android project created, open build.gradle and include Google Play Services under the dependencies node and sync your app. In this sample, I am also using the Butter Knife library to cut down on boiler plate code for click listeners and finding View items.
Once you have synced your dependencies, open AndroidManifest.xml and include the ACCESS_FINE_LOCATION permission. This permission is required to read session data from Google Fit. While I don’t go into detail in this tutorial, it is worth noting that, if you are targeting API 23 or higher, you need to request the location permission from the user.
Next, open activity_main.xml and update it so that it includes five Button items that will be used to demonstrate some of the functionality of the Sessions API. The end result should look similar to the following:
Once the layout is created, open MainActivity.java and connect to Google Play Services.
You may have noticed that you are including the History API along with the Sessions API. This is necessary because the History API is used for deleting session data, which we’ll discuss later in this tutorial. You also need to use both the FITNESS_LOCATION_READ_WRITE and FITNESS_ACTIVITY_READ_WRITE scope properties for the Sessions API features that we will be discussing.
Once you have set your app up for connecting to Google Play Services and Google Fit, it’s time to start trying out the Sessions API.
2. Using the Sessions API
The Sessions API is another tool from Google Fit for storing fitness data for the user. As such, it is not intended to be a replacement for the Recording or History APIs, but rather is an additional way to improve your apps for a better user experience.
In this section, you learn how to start and stop real time session data collection, how to insert a session into the Google Fit data store, how to read previously stored session data, and how to delete unnecessary or incorrect sessions. Similar to the History API, Sessions API calls must be made off of the main thread. While the tutorial for the History API wrapped operations in AsyncTask calls, this tutorial will focus on using PendingResult callbacks to keep track of tasks.
Starting and Stopping a Session
The most common scenario for the Sessions API is recording information after a user has initiated a fitness activity. This is often started concurrently with the Recording API so that sensor data can be associated with the session timeframe. To start recording a session, you need to create a session object with a name, a unique identifier, a description, a start time, and the type of activity that the user is performing.
Once your Session object is created, you can call startSession on the Sessions API to start recording your user’s activity.
When your user has finished their activity, you can end the session by calling stopSession with the unique identifier for the Session .
Something worth noting here is that the Session object implements the Parcelable interface, so it can be stored in a Bundle in case you need to store or pass it off to another component within your application. This can be useful if the user starts an activity and then closes the app, as you may need that session data later to stop recording the session.
Inserting Into Google Fit
Now that you know how to record real time session information, the next step is being able to insert sessions after-the-fact. While you can insert a block of time as a session, the Sessions API also allows you to associate activities with segments of a session. This is useful for situations where the user may not continuously do the same activity over their entire fitness routine.
An example of this may be when your app has detected that the user ran, rested for a short period by walking, and then ran again. In the following example, you insert a Session where the user ran for 15 minutes, walked for five, and then ran for another 15 minutes by keeping track of when the user started and stopped each activity. You also record their average speed for each of those activities.
Once you have the key time and speed values, you need to create two DataSet groups for storing information on activities and speed. These can be created from a set of DataSource objects with the appropriate DataType properties set.
Next, you need to create the DataPoint objects that will be inserted into the Google Fit data store. Each DataPoint has a time interval and a set of Field properties that store related data. Once each DataPoint is configured, you need to insert it into the proper DataSet . For brevity, I only show the code snippet for creating DataPoint objects for the first run segment below, though, the other data point objects are shown in the source code for this tutorial on GitHub.
Once you have populated the two DataSet groups, it’s time to create the Session that you will insert. This Session will need to set the name, unique identifier, description, start and end times, and activity properties. One important thing to be aware of is that the name that you use when inserting a Session is the name that you need to use when attempting to read this session later.
Now that your Session is created, you need to create a SessionInsertRequest , add your DataSet objects to it, and then insert that Session into Google Fit.
Reading Session Data
No matter how much session data you store with your app, it won’t do you much good unless you’re able to read that data and use it to make your app better for your users. Luckily, Google Fit makes it incredibly easy to receive session data within a set timeframe.
First, you need to select the start and end time for the data you would like to receive. In this example, we request session data for the last month.
Once you have your window of time selected, you need to create a SessionReadRequest . This request includes the time interval for your desired session data, the type of session data you are looking for (this tutorial will only look for speed data), and the name of the sessions that you are requesting, though, the time interval is the only required property.
After you have called SessionsApi.readSession , you receive a SessionReadResult object that contains lists of Session and DataSet objects that you can use within your app. For this tutorial, we simply log the data.
If you run your application now and use the insert and read operations, you should receive the three speed DataPoint objects that you created in the previous section.
Deleting Session Data
There may be times where you need to delete some session information that is either incorrect or unnecessary. This can be done by using the History API to delete sessions that have been saved in the Google Fit data store.
First, you need to determine a time interval for the delete operation. You can then add additional information, such as a DataType or other Session properties to delete, or you can simply delete all session data within the time interval.
Conclusion
As you have learned in this tutorial, the Sessions API is a powerful tool for organizing gathered data in blocks of time. It is a great compliment to the other Google Fit APIs. When used in conjunction with the History and Recording APIs, there’s a lot you can do to understand the activity of your app’s users and provide them with an excellent experience with your fitness apps.
Источник