Làm việc với dữ liệu trong quá khứ

Với API Nhật ký, ứng dụng của bạn có thể thực hiện hàng loạt thao tác trên kho lưu trữ dữ liệu thể dục: đọc, chèn, cập nhật và xoá dữ liệu trước đây về sức khoẻ thể chất và tinh thần. Sử dụng API Lịch sử để thực hiện những việc sau:

  • Đọc dữ liệu sức khoẻ thể chất và tinh thần được chèn hoặc ghi lại bằng các ứng dụng khác.
  • Nhập dữ liệu hàng loạt vào Google Fit.
  • Cập nhật dữ liệu trong Google Fit.
  • Xoá dữ liệu trong quá khứ mà ứng dụng của bạn đã lưu trữ trước đây.

Để chèn dữ liệu chứa siêu dữ liệu về phiên, hãy sử dụng Sessions API (API Phiên).

Đọc dữ liệu

Các phần sau đây trình bày cách đọc các loại dữ liệu tổng hợp khác nhau.

Đọc dữ liệu chi tiết và dữ liệu tổng hợp

Để đọc dữ liệu trong quá khứ, hãy tạo một thực thể DataReadRequest.

Kotlin

// Read the data that's been collected throughout the past week.
val endTime = LocalDateTime.now().atZone(ZoneId.systemDefault())
val startTime = endTime.minusWeeks(1)
Log.i(TAG, "Range Start: $startTime")
Log.i(TAG, "Range End: $endTime")

val readRequest =
    DataReadRequest.Builder()
        // The data request can specify multiple data types to return,
        // effectively combining multiple data queries into one call.
        // This example demonstrates aggregating only one data type.
        .aggregate(DataType.AGGREGATE_STEP_COUNT_DELTA)
        // Analogous to a "Group By" in SQL, defines how data should be
        // aggregated.
        // bucketByTime allows for a time span, whereas bucketBySession allows
        // bucketing by <a href="/fit/android/using-sessions">sessions</a>.
        .bucketByTime(1, TimeUnit.DAYS)
        .setTimeRange(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
        .build()

Java

// Read the data that's been collected throughout the past week.
ZonedDateTime endTime = LocalDateTime.now().atZone(ZoneId.systemDefault());
ZonedDateTime startTime = endTime.minusWeeks(1);
Log.i(TAG, "Range Start: $startTime");
Log.i(TAG, "Range End: $endTime");

DataReadRequest readRequest = new DataReadRequest.Builder()
        // The data request can specify multiple data types to return,
        // effectively combining multiple data queries into one call.
        // This example demonstrates aggregating only one data type.
        .aggregate(DataType.AGGREGATE_STEP_COUNT_DELTA)
        // Analogous to a "Group By" in SQL, defines how data should be
        // aggregated.
        // bucketByTime allows for a time span, while bucketBySession allows
        // bucketing by sessions.
        .bucketByTime(1, TimeUnit.DAYS)
        .setTimeRange(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
        .build();

Ví dụ trước sử dụng các điểm dữ liệu tổng hợp, trong đó mỗi DataPoint đại diện cho số bước đã đi trong một ngày. Đối với trường hợp sử dụng cụ thể này, các điểm dữ liệu tổng hợp có hai ưu điểm:

  • Ứng dụng và cửa hàng thể dục sẽ trao đổi lượng dữ liệu nhỏ hơn.
  • Ứng dụng của bạn không phải tổng hợp dữ liệu theo cách thủ công.

Dữ liệu tổng hợp cho nhiều loại hoạt động

Ứng dụng của bạn có thể dùng các yêu cầu dữ liệu để truy xuất nhiều loại dữ liệu. Ví dụ sau cho thấy cách tạo DataReadRequest để nhận calo đã đốt cháy cho từng hoạt động được thực hiện trong phạm vi thời gian đã chỉ định. Dữ liệu kết quả khớp với lượng calo của mỗi hoạt động như được báo cáo trong ứng dụng Google Fit. Trong ứng dụng này, mỗi hoạt động sẽ nhận được nhóm dữ liệu calo riêng.

Kotlin

val readRequest = DataReadRequest.Builder()
    .aggregate(DataType.AGGREGATE_CALORIES_EXPENDED)
    .bucketByActivityType(1, TimeUnit.SECONDS)
    .setTimeRange(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
    .build()

Java

DataReadRequest readRequest = new DataReadRequest.Builder()
        .aggregate(DataType.AGGREGATE_CALORIES_EXPENDED)
        .bucketByActivityType(1, TimeUnit.SECONDS)
        .setTimeRange(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
        .build();

Sau khi bạn tạo một thực thể DataReadRequest, hãy dùng phương thức HistoryClient.readData() để đọc không đồng bộ dữ liệu trong quá khứ.

Ví dụ sau minh hoạ cách lấy các thực thể DataPoint từ DataSet:

Kotlin

Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    .readData(readRequest)
    .addOnSuccessListener { response ->
        // The aggregate query puts datasets into buckets, so flatten into a
        // single list of datasets
        for (dataSet in response.buckets.flatMap { it.dataSets }) {
            dumpDataSet(dataSet)
        }
    }
    .addOnFailureListener { e ->
        Log.w(TAG,"There was an error reading data from Google Fit", e)
    }

fun dumpDataSet(dataSet: DataSet) {
    Log.i(TAG, "Data returned for Data type: ${dataSet.dataType.name}")
    for (dp in dataSet.dataPoints) {
        Log.i(TAG,"Data point:")
        Log.i(TAG,"\tType: ${dp.dataType.name}")
        Log.i(TAG,"\tStart: ${dp.getStartTimeString()}")
        Log.i(TAG,"\tEnd: ${dp.getEndTimeString()}")
        for (field in dp.dataType.fields) {
            Log.i(TAG,"\tField: ${field.name.toString()} Value: ${dp.getValue(field)}")
        }
    }
}

fun DataPoint.getStartTimeString() = Instant.ofEpochSecond(this.getStartTime(TimeUnit.SECONDS))
    .atZone(ZoneId.systemDefault())
    .toLocalDateTime().toString()

fun DataPoint.getEndTimeString() = Instant.ofEpochSecond(this.getEndTime(TimeUnit.SECONDS))
    .atZone(ZoneId.systemDefault())
    .toLocalDateTime().toString()

Java

Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
        .readData(readRequest)
        .addOnSuccessListener (response -> {
            // The aggregate query puts datasets into buckets, so convert to a
            // single list of datasets
            for (Bucket bucket : response.getBuckets()) {
                for (DataSet dataSet : bucket.getDataSets()) {
                    dumpDataSet(dataSet);
                }
            }
        })
        .addOnFailureListener(e ->
            Log.w(TAG, "There was an error reading data from Google Fit", e));

}

private void dumpDataSet(DataSet dataSet) {
    Log.i(TAG, "Data returned for Data type: ${dataSet.dataType.name}");
    for (DataPoint dp : dataSet.getDataPoints()) {
        Log.i(TAG,"Data point:");
        Log.i(TAG,"\tType: ${dp.dataType.name}");
        Log.i(TAG,"\tStart: ${dp.getStartTimeString()}");
        Log.i(TAG,"\tEnd: ${dp.getEndTimeString()}");
        for (Field field : dp.getDataType().getFields()) {
            Log.i(TAG,"\tField: ${field.name.toString()} Value: ${dp.getValue(field)}");
        }
    }
}


private String getStartTimeString() {
    return Instant.ofEpochSecond(this.getStartTime(TimeUnit.SECONDS))
        .atZone(ZoneId.systemDefault())
        .toLocalDateTime().toString();
}

private String getEndTimeString() {
    return Instant.ofEpochSecond(this.getEndTime(TimeUnit.SECONDS))
            .atZone(ZoneId.systemDefault())
            .toLocalDateTime().toString();
}

Đọc dữ liệu tổng hằng ngày

Google Fit cũng cung cấp quyền truy cập đơn giản vào dữ liệu tổng số hằng ngày của một loại dữ liệu đã chỉ định. Sử dụng phương thức HistoryClient.readDailyTotal() để truy xuất loại dữ liệu bạn chỉ định kể từ nửa đêm của ngày hiện tại theo múi giờ hiện tại của thiết bị. Ví dụ: chuyển loại dữ liệu TYPE_STEP_COUNT_DELTA vào phương thức này để truy xuất tổng số bước hằng ngày. Bạn có thể truyền vào một loại dữ liệu tức thì có tổng giá trị tổng hợp hằng ngày. Để biết thêm thông tin về các loại dữ liệu được hỗ trợ, hãy xem DataType.getAggregateType.

Google Fit không yêu cầu quyền đăng ký các nội dung cập nhật TYPE_STEP_COUNT_DELTA từ phương thức HistoryClient.readDailyTotal() khi phương thức này được gọi bằng tài khoản mặc định và không có phạm vi nào được chỉ định. Điều này có thể hữu ích nếu bạn cần dữ liệu về bước sử dụng ở những khu vực mà bạn không thể hiển thị bảng quyền, chẳng hạn như trên mặt đồng hồ Wear OS.

Người dùng muốn thấy số bước nhất quán trên ứng dụng Google Fit, các ứng dụng khác và mặt đồng hồ Wear OS, vì điều này mang lại trải nghiệm nhất quán và đáng tin cậy cho họ. Để đảm bảo số bước nhất quán, hãy đăng ký số bước trong nền tảng Google Fit ngay trên ứng dụng hoặc mặt đồng hồ của bạn, sau đó cập nhật số bước trong onExitAmbient(). Để biết thêm thông tin về cách sử dụng dữ liệu này trong mặt đồng hồ, hãy xem bài viết Các chức năng trên Mặt đồng hồứng dụng mẫu Android WatchFace.

Chèn dữ liệu

Để chèn dữ liệu trong quá khứ, trước tiên, hãy tạo một thực thể DataSet:

Kotlin

// Declare that the data being inserted was collected during the past hour.
val endTime = LocalDateTime.now().atZone(ZoneId.systemDefault())
val startTime = endTime.minusHours(1)

// Create a data source
val dataSource = DataSource.Builder()
    .setAppPackageName(this)
    .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
    .setStreamName("$TAG - step count")
    .setType(DataSource.TYPE_RAW)
    .build()

// For each data point, specify a start time, end time, and the
// data value -- in this case, 950 new steps.
val stepCountDelta = 950
val dataPoint =
    DataPoint.builder(dataSource)
        .setField(Field.FIELD_STEPS, stepCountDelta)
        .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
        .build()

val dataSet = DataSet.builder(dataSource)
    .add(dataPoint)
    .build()

Java

// Declare that the data being inserted was collected during the past hour.
ZonedDateTime endTime = LocalDateTime.now().atZone(ZoneId.systemDefault());
ZonedDateTime startTime = endTime.minusHours(1);

// Create a data source
DataSource dataSource = new DataSource.Builder()
        .setAppPackageName(this)
        .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
        .setStreamName("$TAG - step count")
        .setType(DataSource.TYPE_RAW)
        .build();

// For each data point, specify a start time, end time, and the
// data value -- in this case, 950 new steps.
int stepCountDelta = 950;
DataPoint dataPoint = DataPoint.builder(dataSource)
        .setField(Field.FIELD_STEPS, stepCountDelta)
        .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
        .build();

DataSet dataSet = DataSet.builder(dataSource)
        .add(dataPoint)
        .build();

Sau khi bạn tạo một thực thể DataSet, hãy sử dụng phương thức HistoryClient.insertData để thêm dữ liệu trong quá khứ này một cách không đồng bộ.

Kotlin

Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    .insertData(dataSet)
    .addOnSuccessListener {
        Log.i(TAG, "DataSet added successfully!")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "There was an error adding the DataSet", e)
    }

Java

Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
        .insertData(dataSet)
        .addOnSuccessListener (unused ->
                Log.i(TAG, "DataSet added successfully!"))
        .addOnFailureListener(e ->
                Log.w(TAG, "There was an error adding the DataSet", e));
}

Quản lý các điểm dữ liệu xung đột

Mỗi DataPoint trong DataSet của ứng dụng phải có một startTime và một endTime xác định một khoảng thời gian duy nhất trong DataSet đó, không chồng chéo giữa các thực thể DataPoint.

Nếu ứng dụng của bạn cố gắng chèn một DataPoint mới xung đột với một thực thể DataPoint hiện có, thì DataPoint mới sẽ bị loại bỏ. Để chèn một DataPoint mới có thể trùng lặp với các điểm dữ liệu hiện có, hãy sử dụng phương thức HistoryClient.updateData được mô tả trong phần Cập nhật dữ liệu.

Bạn không thể chèn một điểm dữ liệu nếu thời lượng của điểm đó trùng lặp với bất kỳ điểm dữ liệu hiện có nào

Hình 1. Cách phương thức insertData() xử lý các điểm dữ liệu mới xung đột với DataPoint hiện có.

Cập nhật dữ liệu

Google Fit cho phép ứng dụng của bạn cập nhật dữ liệu sức khoẻ thể chất và tinh thần trước đây mà ứng dụng đã chèn trước đó. Để thêm dữ liệu trong quá khứ cho DataSet mới hoặc để thêm các thực thể DataPoint mới không xung đột với các điểm dữ liệu hiện có, hãy sử dụng phương thức HistoryApi.insertData.

Để cập nhật dữ liệu trong quá khứ, hãy sử dụng phương thức HistoryClient.updateData. Phương thức này sẽ xoá mọi thực thể DataPoint hiện có trùng lặp với các thực thể DataPoint được thêm vào bằng phương thức này.

Để cập nhật dữ liệu trước đây về sức khoẻ thể chất và tinh thần, trước tiên, hãy tạo một thực thể DataSet:

Kotlin

// Declare that the historical data was collected during the past 50 minutes.
val endTime = LocalDateTime.now().atZone(ZoneId.systemDefault())
val startTime = endTime.minusMinutes(50)

// Create a data source
val dataSource  = DataSource.Builder()
    .setAppPackageName(this)
    .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
    .setStreamName("$TAG - step count")
    .setType(DataSource.TYPE_RAW)
    .build()

// Create a data set
// For each data point, specify a start time, end time, and the
// data value -- in this case, 1000 new steps.
val stepCountDelta = 1000

val dataPoint = DataPoint.builder(dataSource)
    .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
    .setField(Field.FIELD_STEPS, stepCountDelta)
    .build()

val dataSet = DataSet.builder(dataSource)
    .add(dataPoint)
    .build()

Java

// Declare that the historical data was collected during the past 50 minutes.
ZonedDateTime endTime = LocalDateTime.now().atZone(ZoneId.systemDefault());
ZonedDateTime startTime = endTime.minusMinutes(50);

// Create a data source
DataSource dataSource = new DataSource.Builder()
        .setAppPackageName(this)
        .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
        .setStreamName("$TAG - step count")
        .setType(DataSource.TYPE_RAW)
        .build();

// Create a data set
// For each data point, specify a start time, end time, and the
// data value -- in this case, 1000 new steps.
int stepCountDelta = 1000;

DataPoint dataPoint = DataPoint.builder(dataSource)
        .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
        .setField(Field.FIELD_STEPS, stepCountDelta)
        .build();

DataSet dataSet = DataSet.builder(dataSource)
        .add(dataPoint)
        .build();

Sau đó, sử dụng DataUpdateRequest.Builder() để tạo một yêu cầu cập nhật dữ liệu mới và sử dụng phương thức HistoryClient.updateData để tạo yêu cầu:

Kotlin

val request = DataUpdateRequest.Builder()
    .setDataSet(dataSet)
    .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
    .build()

Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    .updateData(request)
    .addOnSuccessListener {
        Log.i(TAG, "DataSet updated successfully!")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "There was an error updating the DataSet", e)
    }

Java

DataUpdateRequest request = new DataUpdateRequest.Builder()
        .setDataSet(dataSet)
        .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
        .build();

Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
        .updateData(request)
        .addOnSuccessListener(unused ->
                Log.i(TAG, "DataSet updated successfully!"))
        .addOnFailureListener(e ->
                Log.w(TAG, "There was an error updating the DataSet", e));

Xoá dữ liệu

Google Fit cho phép ứng dụng của bạn xoá dữ liệu sức khoẻ thể chất và tinh thần trước đây mà ứng dụng đã chèn trước đó.

Để xoá dữ liệu trong quá khứ, hãy sử dụng phương thức HistoryClient.deleteData:

Kotlin

// Declare that this code deletes step count information that was collected
// throughout the past day.
val endTime = LocalDateTime.now().atZone(ZoneId.systemDefault())
val startTime = endTime.minusDays(1)

// Create a delete request object, providing a data type and a time interval
val request = DataDeleteRequest.Builder()
    .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
    .addDataType(DataType.TYPE_STEP_COUNT_DELTA)
    .build()

// Invoke the History API with the HistoryClient object and delete request, and
// then specify a callback that will check the result.
Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    .deleteData(request)
    .addOnSuccessListener {
        Log.i(TAG, "Data deleted successfully!")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "There was an error with the deletion request", e)
    }

Java

// Declare that this code deletes step count information that was collected
// throughout the past day.
ZonedDateTime endTime = LocalDateTime.now().atZone(ZoneId.systemDefault());
ZonedDateTime startTime = endTime.minusDays(1);

// Create a delete request object, providing a data type and a time interval
DataDeleteRequest request = new DataDeleteRequest.Builder()
        .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
        .addDataType(DataType.TYPE_STEP_COUNT_DELTA)
        .build();

// Invoke the History API with the HistoryClient object and delete request, and
// then specify a callback that will check the result.
Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
        .deleteData(request)
        .addOnSuccessListener (unused ->
                Log.i(TAG, "Data deleted successfully!"))
        .addOnFailureListener(e ->
        Log.w(TAG, "There was an error with the deletion request", e));

Các ứng dụng có thể xoá dữ liệu khỏi phiên cụ thể hoặc xoá tất cả dữ liệu. Để biết thêm thông tin, hãy xem tài liệu tham khảo API cho DataDeleteRequest.

Đăng ký nhận thông tin cập nhật về dữ liệu

Ứng dụng có thể đọc dữ liệu cảm biến thô theo thời gian thực bằng cách đăng ký bằng SensorsClient.

Đối với các loại dữ liệu khác ít thường xuyên hơn và được tính theo cách thủ công, ứng dụng của bạn có thể đăng ký để nhận thông tin cập nhật khi các phép đo này được chèn vào cơ sở dữ liệu của Google Fit. Ví dụ về các loại dữ liệu này bao gồm chiều cao, cân nặng và các bài tập thể dục như nâng tạ; để biết thêm thông tin chi tiết, hãy xem danh sách đầy đủ các loại dữ liệu được hỗ trợ. Để đăng ký nhận bản cập nhật, hãy dùng HistoryClient.registerDataUpdateListener.

Đoạn mã sau đây cho phép ứng dụng nhận được thông báo khi người dùng nhập một giá trị mới cho cân nặng của họ:

Kotlin

val intent = Intent(this, MyDataUpdateService::class.java)
val pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

val request = DataUpdateListenerRegistrationRequest.Builder()
    .setDataType(DataType.TYPE_WEIGHT)
    .setPendingIntent(pendingIntent)
    .build()

Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    .registerDataUpdateListener(request)
    .addOnSuccessListener {
        Log.i(TAG, "DataUpdateListener registered")
    }

Java

Intent intent = new Intent(this, MyDataUpdateService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

DataUpdateListenerRegistrationRequest request = new DataUpdateListenerRegistrationRequest.Builder()
        .setDataType(DataType.TYPE_WEIGHT)
        .setPendingIntent(pendingIntent)
        .build();

Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
        .registerDataUpdateListener(request)
        .addOnSuccessListener(unused ->
                Log.i(TAG, "DataUpdateListener registered"));

Bạn có thể sử dụng IntentService để nhận thông báo về nội dung cập nhật:

Kotlin

class MyDataUpdateService : IntentService("MyDataUpdateService") {
    override fun onHandleIntent(intent: Intent?) {
        val update = DataUpdateNotification.getDataUpdateNotification(intent)
        // Show the time interval over which the data points were collected.
        // To extract specific data values, in this case the user's weight,
        // use DataReadRequest.
        update?.apply {
            val start = getUpdateStartTime(TimeUnit.MILLISECONDS)
            val end = getUpdateEndTime(TimeUnit.MILLISECONDS)

            Log.i(TAG, "Data Update start: $start end: $end DataType: ${dataType.name}")
        }
    }
}

Java

public class MyDataUpdateService extends IntentService {

    public MyDataUpdateService(String name) {
        super("MyDataUpdateService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent != null) {
            DataUpdateNotification update = DataUpdateNotification.getDataUpdateNotification(intent);

            // Show the time interval over which the data points
            // were collected.
            // To extract specific data values, in this case the user's weight,
            // use DataReadRequest.
            if (update != null) {
                long start = update.getUpdateStartTime(TimeUnit.MILLISECONDS);
                long end = update.getUpdateEndTime(TimeUnit.MILLISECONDS);
            }

            Log.i(TAG, "Data Update start: $start end: $end DataType: ${dataType.name}");
        }
    }
}

Bạn phải khai báo IntentService trong tệp AndroidManifest.xml.