神刀安全网

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 aprevious 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 theSensors andRecording 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.

compile 'com.google.android.gms:play-services-fitness:8.4.0'

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.

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     android:orientation="vertical">      <Button         android:id="@+id/btn_view_week"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="View this weeks steps" />      <Button         android:id="@+id/btn_view_today"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="View today's steps"/>      <Button         android:id="@+id/btn_add_steps"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Add step data for today" />      <Button         android:id="@+id/btn_update_steps"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Update step data for yesterday" />      <Button         android:id="@+id/btn_delete_steps"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Delete step data for yesterday" />  </LinearLayout>

When you run your application, the user interface should look like this:

Google Fit for Android: History API

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.

public class MainActivity extends AppCompatActivity implements     GoogleApiClient.ConnectionCallbacks,     GoogleApiClient.OnConnectionFailedListener,     View.OnClickListener {       private Button mButtonViewWeek;     private Button mButtonViewToday;     private Button mButtonAddSteps;     private Button mButtonUpdateSteps;     private Button mButtonDeleteSteps;      private GoogleApiClient mGoogleApiClient;       @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);                  mButtonViewWeek = (Button) findViewById(R.id.btn_view_week);         mButtonViewToday = (Button) findViewById(R.id.btn_view_today);         mButtonAddSteps = (Button) findViewById(R.id.btn_add_steps);         mButtonUpdateSteps = (Button) findViewById(R.id.btn_update_steps);         mButtonDeleteSteps = (Button) findViewById(R.id.btn_delete_steps);          mButtonViewWeek.setOnClickListener(this);         mButtonViewToday.setOnClickListener(this);         mButtonAddSteps.setOnClickListener(this);         mButtonUpdateSteps.setOnClickListener(this);         mButtonDeleteSteps.setOnClickListener(this);     }       @Override     public void onConnectionSuspended(int i) {         Log.e("HistoryAPI", "onConnectionSuspended");     }      @Override     public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {         Log.e("HistoryAPI", "onConnectionFailed");     }       public void onConnected(@Nullable Bundle bundle) {         Log.e("HistoryAPI", "onConnected");     }        @Override     public void onClick(View v) {     } }

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.

mGoogleApiClient = new GoogleApiClient.Builder(this)         .addApi(Fitness.HISTORY_API)         .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))         .addConnectionCallbacks(this)         .enableAutoManage(this, 0, this)         .build();

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 :

private class ViewWeekStepCountTask extends AsyncTask<Void, Void, Void> {     protected Void doInBackground(Void... params) {         displayLastWeeksData();         return null;     } }

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.

Calendar cal = Calendar.getInstance(); Date now = new Date(); cal.setTime(now); long endTime = cal.getTimeInMillis(); cal.add(Calendar.WEEK_OF_YEAR, -1); long startTime = cal.getTimeInMillis();  java.text.DateFormat dateFormat = DateFormat.getDateInstance(); Log.e("History", "Range Start: " + dateFormat.format(startTime)); Log.e("History", "Range End: " + dateFormat.format(endTime));  //Check how many steps were walked and recorded in the last 7 days DataReadRequest readRequest = new DataReadRequest.Builder()         .aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)         .bucketByTime(1, TimeUnit.DAYS)         .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)         .build();

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.

DataReadResult dataReadResult = Fitness.HistoryApi.readData(mGoogleApiClient, readRequest).await(1, TimeUnit.MINUTES);

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:

//Used for aggregated data if (dataReadResult.getBuckets().size() > 0) {     Log.e("History", "Number of buckets: " + dataReadResult.getBuckets().size());     for (Bucket bucket : dataReadResult.getBuckets()) {         List<DataSet> dataSets = bucket.getDataSets();         for (DataSet dataSet : dataSets) {             showDataSet(dataSet);         }     } } //Used for non-aggregated data else if (dataReadResult.getDataSets().size() > 0) {     Log.e("History", "Number of returned DataSets: " + dataReadResult.getDataSets().size());     for (DataSet dataSet : dataReadResult.getDataSets()) {         showDataSet(dataSet);     } }

You can then retrieve each DataPoint from the DataSet objects that have been returned.

private void showDataSet(DataSet dataSet) {     Log.e("History", "Data returned for Data type: " + dataSet.getDataType().getName());     DateFormat dateFormat = DateFormat.getDateInstance();     DateFormat timeFormat = DateFormat.getTimeInstance();      for (DataPoint dp : dataSet.getDataPoints()) {         Log.e("History", "Data point:");         Log.e("History", "/tType: " + dp.getDataType().getName());         Log.e("History", "/tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));         Log.e("History", "/tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));         for(Field field : dp.getDataType().getFields()) {             Log.e("History", "/tField: " + field.getName() +                     " Value: " + dp.getValue(field));         }     } }

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:

E/History: Range Start: Feb 17, 2016 E/History: Range End: Feb 24, 2016 E/History: Number of buckets: 7 E/History: Data returned for Data type: com.google.step_count.delta E/History: Data point: E/History:  Type: com.google.step_count.delta E/History:  Start: Feb 17, 2016 11:01:46 PM E/History:  End: Feb 17, 2016 11:01:46 PM E/History:  Field: steps Value: 9360 E/History: Data returned for Data type: com.google.step_count.delta E/History: Data returned for Data type: com.google.step_count.delta E/History: Data returned for Data type: com.google.step_count.delta E/History: Data point: E/History:  Type: com.google.step_count.delta E/History:  Start: Feb 21, 2016 9:58:03 AM E/History:  End: Feb 21, 2016 9:58:03 AM E/History:  Field: steps Value: 10041 E/History: Data returned for Data type: com.google.step_count.delta E/History: Data point: E/History:  Type: com.google.step_count.delta E/History:  Start: Feb 21, 2016 11:22:53 PM E/History:  End: Feb 22, 2016 11:22:53 PM E/History:  Field: steps Value: 10786 E/History: Data returned for Data type: com.google.step_count.delta E/History: Data point: E/History:  Type: com.google.step_count.delta E/History:  Start: Feb 22, 2016 11:06:31 PM E/History:  End: Feb 23, 2016 11:06:31 PM E/History:  Field: steps Value: 13099 E/History: Data returned for Data type: com.google.step_count.delta E/History: Data point: E/History:  Type: com.google.step_count.delta E/History:  Start: Feb 23, 2016 11:02:31 PM E/History:  End: Feb 24, 2016 11:02:31 PM E/History:  Field: steps Value: 9765

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.

private void displayStepDataForToday() {     DailyTotalResult result = Fitness.HistoryApi.readDailyTotal( mGoogleApiClient, DataType.TYPE_STEP_COUNT_DELTA ).await(1, TimeUnit.MINUTES);     showDataSet(result.getTotal()); }

The above code logs out the user’s step data for the day.

E/History: Data returned for Data type: com.google.step_count.delta E/History: Data point: E/History:     Type: com.google.step_count.delta E/History:     Start: Feb 24, 2016 8:39:59 AM E/History:     End: Feb 24, 2016 8:39:59 AM E/History:     Field: steps Value: 9474

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.

Calendar cal = Calendar.getInstance(); Date now = new Date(); cal.setTime(now); long endTime = cal.getTimeInMillis(); cal.add(Calendar.HOUR_OF_DAY, -1); long startTime = cal.getTimeInMillis();  DataSource dataSource = new DataSource.Builder()     .setAppPackageName(this)     .setDataType(DataType.TYPE_STEP_COUNT_DELTA)     .setName("Step Count")     .setType(DataSource.TYPE_RAW)     .build();      int stepCountDelta = 1000000; DataSet dataSet = DataSet.create(dataSource);  DataPoint point = dataSet.createDataPoint()         .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS); point.getValue(Field.FIELD_STEPS).setInt(stepCountDelta); dataSet.add(point);

After creating the DataSet object, you can insert it into the Google Fit data store using the History API’s insertData call.

Fitness.HistoryApi.insertData(mGoogleApiClient, dataSet).await(1, TimeUnit.MINUTES);

If you insert the user’s steps and then read the activity log, you should see something similar to the following:

E/History: Data returned for Data type: com.google.step_count.delta E/History: Data point: E/History:     Type: com.google.step_count.delta E/History:  Start: Feb 27, 2016 10:05:18 PM E/History:  End: Feb 28, 2016 10:05:18 PM E/History:  Field: steps Value: 1008747

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.

Calendar cal = Calendar.getInstance(); Date now = new Date(); cal.setTime(now); long endTime = cal.getTimeInMillis(); cal.add(Calendar.HOUR_OF_DAY, -1); long startTime = cal.getTimeInMillis();  DataSource dataSource = new DataSource.Builder()         .setAppPackageName(this)         .setDataType(DataType.TYPE_STEP_COUNT_DELTA)         .setName("Step Count")         .setType(DataSource.TYPE_RAW)         .build();  int stepCountDelta = 2000000; DataSet dataSet = DataSet.create(dataSource);  DataPoint point = dataSet.createDataPoint()         .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS); point.getValue(Field.FIELD_STEPS).setInt(stepCountDelta); dataSet.add(point);  DataUpdateRequest updateRequest = new DataUpdateRequest.Builder().setDataSet(dataSet).setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS).build(); Fitness.HistoryApi.updateData(mGoogleApiClient, updateRequest).await(1, TimeUnit.MINUTES);

If you were to log out the user’s steps for the day after running the above, you should see over two million steps.

E/History: Data returned for Data type: com.google.step_count.delta E/History: Data point: E/History:     Type: com.google.step_count.delta E/History:  Start: Feb 27, 2016 10:05:18 PM E/History:  End: Feb 28, 2016 10:05:18 PM E/History:  Field: steps Value: 2008747

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.

Calendar cal = Calendar.getInstance(); Date now = new Date(); cal.setTime(now); long endTime = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_YEAR, -1); long startTime = cal.getTimeInMillis();  DataDeleteRequest request = new DataDeleteRequest.Builder()         .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)         .addDataType(DataType.TYPE_STEP_COUNT_DELTA)         .build();  Fitness.HistoryApi.deleteData(mGoogleApiClient, request).await(1, TimeUnit.MINUTES);

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: History API

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮