Getting Started on Android

This guide explains how to start developing with Google Fit on Android. Google Fit is part of Google Play services.

Step 1: Get a Google Account

To use the Google Fit APIs, you need a Google Account. If you already have an account, then you're all set. You may also want to create a separate Google Account for testing purposes.

Step 2: Get Google Play services

Google Fit is available on Android devices with Google Play services 7.0 or higher. Devices running Android 2.3 or higher that have the Google Play Store app automatically receive updates to Google Play services.

To check which version of Google Play services is installed on your device, go to Settings > Apps > Google Play services.

Ensure that you have the latest client library for Google Play services on your development host:

  1. Open the Android SDK Manager.
  2. Under SDK Tools, find Google Play services and Google Repository.
  3. If the status for these packages is different than Installed, select them both and click Install Packages.

Step 3: Get an OAuth 2.0 client ID

If you haven't already enabled the Fitness API and obtained an OAuth 2.0 client ID, follow the instructions in Get an OAuth 2.0 Client ID to do so now.

Step 4: Configure your project

Android Studio is the recommended development environment for building an app with the Fitness API. To create a new project, follow the steps described in Creating a Project.

In the IDE, open the build.gradle file for your module and add the Google Play services client library as a dependency:

apply plugin: 'com.android.application'
...

dependencies {
    compile 'com.google.android.gms:play-services-fitness:9.8.0'
}

Step 5: Connect to the fitness service

Before you can invoke methods from the Google Fit APIs, you have to connect to the appropriate fitness service or services, which are part of Google Play services. The following APIs are available to you:

For more information on these APIs, see the Android APIs Overview.

When your app requests a connection to the service, it specifies the scope of access that it needs. Google Fit asks the user to grant permission to your app to access their fitness data. For more information about scopes and authorization, see Authorization.

Create the API client as follows:

  1. Define variables in your activity to help you track the connection status:

    private GoogleApiClient mClient = null;
    

  2. Connect to the Google Fit Platform, and then check and request permissions if required by the Fit APIs that you use in your app:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Put application specific code here.
    
        setContentView(R.layout.activity_main);
        // This method sets up our custom logger, which will print all log messages to the device
        // screen, as well as to adb logcat.
        initializeLogging();
    
        // When permissions are revoked the app is restarted so onCreate is sufficient to check for
        // permissions core to the Activity's functionality.
        if (!checkPermissions()) {
            requestPermissions();
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
    
        // This ensures that if the user denies the permissions then uses Settings to re-enable
        // them, the app will start working.
        buildFitnessClient();
    }
    

  3. Create the Google API client and provide the required callback methods:

    /**
     *  Build a {@link GoogleApiClient} that will authenticate the user and allow the application
     *  to connect to Fitness APIs. The scopes included should match the scopes your app needs
     *  (see documentation for details). Authentication will occasionally fail intentionally,
     *  and in those cases, there will be a known resolution, which the OnConnectionFailedListener()
     *  can address. Examples of this include the user never having signed in before, or having
     *  multiple accounts on the device and needing to specify which account to use, etc.
     */
    private void buildFitnessClient() {
        if (mClient == null && checkPermissions()) {
            mClient = new GoogleApiClient.Builder(this)
                    .addApi(Fitness.SENSORS_API)
                    .addScope(new Scope(Scopes.FITNESS_LOCATION_READ))
                    .addConnectionCallbacks(
                            new GoogleApiClient.ConnectionCallbacks() {
                                @Override
                                public void onConnected(Bundle bundle) {
                                    Log.i(TAG, "Connected!!!");
                                    // Now you can make calls to the Fitness APIs.
                                    findFitnessDataSources();
                                }
    
                                @Override
                                public void onConnectionSuspended(int i) {
                                    // If your connection to the sensor gets lost at some point,
                                    // you'll be able to determine the reason and react to it here.
                                    if (i == ConnectionCallbacks.CAUSE_NETWORK_LOST) {
                                        Log.i(TAG, "Connection lost.  Cause: Network Lost.");
                                    } else if (i
                                            == ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
                                        Log.i(TAG,
                                                "Connection lost.  Reason: Service Disconnected");
                                    }
                                }
                            }
                    )
                    .enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() {
                        @Override
                        public void onConnectionFailed(ConnectionResult result) {
                            Log.i(TAG, "Google Play services connection failed. Cause: " +
                                    result.toString());
                            Snackbar.make(
                                    MainActivity.this.findViewById(R.id.main_activity_view),
                                    "Exception while connecting to Google Play services: " +
                                            result.getErrorMessage(),
                                    Snackbar.LENGTH_INDEFINITE).show();
                        }
                    })
                    .build();
        }
    }
    

Send feedback about...