Search code examples
androidgoogle-fit

Get third party application (Sleep as Android) data from Google Fit


I'm curently trying to get Sleep as Android data from Google Fit in my own android application. I read from a post that Sleep as Android data are stored in Google Fit and any 3rd party app can view them. To achieve that, I use History sessions. This is the sample code for reading sleep data:

public static DataReadRequest queryFitnessData() {
    // [START build_read_data_request]
    // Setting a start and end date using a range of 1 week before this moment.
    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 = getDateInstance();
    Log.i(TAG, "Range Start: " + dateFormat.format(startTime));
    Log.i(TAG, "Range End: " + dateFormat.format(endTime));

    DataReadRequest readRequest = new DataReadRequest.Builder()
            .read(DataType.TYPE_ACTIVITY_SEGMENT)
            .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
            .build();
    // [END build_read_data_request]

    return readRequest;
}

And to execute that query:

DataReadRequest readRequest = queryFitnessData();
DataReadResult dataReadResult = Fitness.HistoryApi.readData(
        mClient, readRequest).await(1, TimeUnit.MINUTES);
printData(dataReadResult);

My guess is that I'm missing something. I also read this post on the same topic but no success until now.

[QUESTION]

How can I get recorded Fitness Data for sleep activities from Google Fit?

[EDIT]

This is a screenshot of Sleep as Android data in Google Fit's timeline

Google Fit Sleep data


Solution

  • Finally, I got it. Thanks to Martin Stava from Urbandroid Team.

    final SessionReadRequest.Builder sessionBuilder = new SessionReadRequest.Builder()
    
            .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
            .read(DataType.TYPE_ACTIVITY_SEGMENT)
            .readSessionsFromAllApps()
            .enableServerQueries();
    
    final SessionReadRequest readRequest = sessionBuilder.build();
    
    // Invoke the Sessions API to fetch the session with the query and wait for the result
    // of the read request.
    SessionReadResult sessionReadResult = SessionsApi.readSession(apiClient, readRequest).await(120, TimeUnit.SECONDS);
    
    Status status = sessionReadResult.getStatus();