Work with Fitness Goals

Goals let Google Fit users track their progress against daily targets they set for themselves. The Goals Client lets your app read these goals. You can then use this data to create a more personalized experience and motivate your users.

Reading user goals

To read a user's goals:

  1. Connect to the fitness service.
  2. Call GoalsClient.readCurrentGoals to get a list of the goals for a user.

    This example shows how to get a user's Heart Point goals:

    Task<List<Goal>> response = Fitness.getGoalsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    .readCurrentGoals(
        new GoalsReadRequest.Builder()
            .addDataType(DataType.TYPE_HEART_POINTS)
            .build());
    
  3. Subscribe to the TYPE_HEART_POINTS data type using the Recording Client. Note: You need to subscribe to data types before your app can read the relevant data. Subscribing triggers Google Fit to start recording the relevant data and syncs it to the user's device. If you don't subscribe to data types, you won't be able to read any data from Google Fit.

  4. Finally, check their progress towards completing their goal using the HistoryClient.

    This example shows how to read a user's Heart Points and calculate their progress toward their goal: Note: The time range for a goal is calculated based on its frequency. For example, for a daily goal, the current time is used to calculate when the day starts and ends.

    Calendar current = Calendar.getInstance();
    
    DataReadRequest readRequest = new DataReadRequest.Builder()
        .read(DataType.TYPE_HEART_POINTS)
        .setTimeRange(
            goal.getStartTime(current, TimeUnit.NANOSECONDS),
            goal.getEndTime(current, TimeUnit.NANOSECONDS),
            TimeUnit.NANOSECONDS)
        .build();
    
    Task<DataReadResponse> response = Fitness.getHistoryClient(this,
        GoogleSignIn.getLastSignedInAccount(this)).readData(readRequest);