History API ทําให้แอปของคุณดําเนินการเป็นกลุ่มในสโตร์การออกกําลังกายได้: อ่าน แทรก อัปเดต และลบข้อมูลประวัติสุขภาพและความเป็นอยู่ที่ดี ใช้ History API เพื่อทําสิ่งต่อไปนี้
- อ่านข้อมูลด้านสุขภาพและความเป็นอยู่ที่ดีที่แทรกหรือบันทึกไว้โดยใช้แอปอื่นๆ
- นําเข้าข้อมูลกลุ่มไปยัง Google Fit
- อัปเดตข้อมูลใน Google Fit
- ลบข้อมูลย้อนหลังที่แอปเก็บไว้ก่อนหน้านี้
หากต้องการแทรกข้อมูลที่มีข้อมูลเมตาของเซสชัน ให้ใช้ Sessions API
อ่านข้อมูล
ส่วนต่อไปนี้จะครอบคลุมวิธีอ่านข้อมูลรวมประเภทต่างๆ
อ่านข้อมูลอย่างละเอียดและรวบรวม
หากต้องการอ่านข้อมูลย้อนหลัง ให้สร้างอินสแตนซ์ 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();
ตัวอย่างนี้ใช้จุดข้อมูลรวมที่ DataPoint
แต่ละรายการแสดงจํานวนจํานวนก้าวใน 1 วัน สําหรับกรณีการใช้งานนี้ จุดข้อมูลรวมมีข้อดี 2 ประการดังนี้
- แอปและ Store การออกกําลังกายแลกเปลี่ยนข้อมูลปริมาณเล็กน้อย
- แอปไม่จําเป็นต้องรวบรวมข้อมูลด้วยตนเอง
รวบรวมข้อมูลสําหรับกิจกรรมหลายประเภท
แอปใช้คําขอข้อมูลเพื่อดึงข้อมูลได้หลายประเภท ตัวอย่างต่อไปนี้แสดงวิธีสร้าง DataReadRequest
เพื่อเผาผลาญแคลอรี่สําหรับแต่ละกิจกรรมที่ทําภายในช่วงเวลาที่ระบุ ข้อมูลผลลัพธ์จะตรงกับจํานวนแคลอรีต่อกิจกรรมตามที่รายงานในแอป Google Fit ซึ่งแต่ละกิจกรรมจะได้รับที่เก็บข้อมูลแคลอรี่ของตนเอง
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();
หลังจากสร้างอินสแตนซ์ DataReadRequest
แล้ว ให้ใช้เมธอด HistoryClient.readData()
เพื่ออ่านข้อมูลย้อนหลังแบบไม่พร้อมกัน
ตัวอย่างต่อไปนี้แสดงวิธีรับอินสแตนซ์ DataPoint
จาก 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(); }
อ่านข้อมูลรวมรายวัน
Google Fit ยังให้สิทธิ์เข้าถึงข้อมูลรวมประเภทรายวันแบบง่ายๆ ด้วย ใช้วิธีHistoryClient.readDailyTotal()
ดึงข้อมูลประเภทที่คุณระบุ ณ เวลาเที่ยงคืนของวันปัจจุบันในเขตเวลาปัจจุบันของอุปกรณ์ ตัวอย่างเช่น ส่งประเภทข้อมูล TYPE_STEP_COUNT_DELTA
ไปยังเมธอดนี้เพื่อเรียกข้อมูลขั้นตอนรวมรายวัน คุณส่งประเภทข้อมูลได้ทันทีซึ่งมียอดรวมรายวันได้ ดูข้อมูลเพิ่มเติมเกี่ยวกับประเภทข้อมูลที่รองรับได้ที่ DataType.getAggregateType
Google Fit ไม่จําเป็นต้องให้สิทธิ์สมัครใช้บริการการอัปเดต TYPE_STEP_COUNT_DELTA
จากเมธอด HistoryClient.readDailyTotal()
เมื่อมีการเรียกใช้เมธอดนี้ด้วยบัญชีเริ่มต้น และไม่มีการระบุขอบเขต
วิธีนี้มีประโยชน์หากคุณต้องการข้อมูลขั้นตอนสําหรับการใช้งานในพื้นที่ที่คุณไม่สามารถแสดงแผงสิทธิ์ เช่น บนหน้าปัดของ Wear OS ได้
ผู้ใช้ต้องการเห็นจํานวนก้าวที่สอดคล้องกันในแอป Google Fit, แอปอื่นๆ และหน้าปัดของ Wear OS เนื่องจากผู้ใช้จะได้รับประสบการณ์การใช้งานที่สม่ําเสมอและเชื่อถือได้ นับขั้นตอนในแพลตฟอร์ม Google Fit จากแอปหรือหน้าปัด แล้วอัปเดตจํานวนใน onExitAmbient()
เพื่อให้การนับจํานวนก้าวสอดคล้องกัน
ดูข้อมูลเพิ่มเติมเกี่ยวกับวิธีใช้ข้อมูลนี้ในหน้าปัดได้ที่ข้อมูลแทรกหน้าปัดและแอปพลิเคชันตัวอย่างของ WatchFace ใน Android
แทรกข้อมูล
หากต้องการแทรกข้อมูลย้อนหลัง ให้สร้างอินสแตนซ์ 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();
หลังจากสร้างอินสแตนซ์ DataSet
แล้ว ให้ใช้เมธอด HistoryClient.insertData
เพื่อเพิ่มข้อมูลย้อนหลังนี้แบบไม่พร้อมกัน
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)); }
จัดการจุดข้อมูลที่ขัดแย้งกัน
DataSet
DataPoint
แต่ละรายการในแอปต้องมี startTime
และ endTime
ที่กําหนดช่วงเวลาที่ไม่ซ้ํากันภายใน DataSet
นั้น โดยไม่มีการทับซ้อนระหว่างอินสแตนซ์ DataPoint
หากแอปพยายามแทรก DataPoint
ใหม่ซึ่งขัดแย้งกับอินสแตนซ์ DataPoint
ที่มีอยู่ ระบบจะยกเลิก DataPoint
ใหม่ หากต้องการแทรก DataPoint
ใหม่ที่อาจทับซ้อนกับจุดข้อมูลที่มีอยู่ ให้ใช้เมธอด HistoryClient.updateData
ดังที่อธิบายไว้ในอัปเดตข้อมูล
รูปที่ 1 วิธีที่ insertData()
จัดการกับจุดข้อมูลใหม่ซึ่งขัดแย้งกับ DataPoint
ที่มีอยู่
อัปเดตข้อมูล
Google Fit ช่วยให้แอปอัปเดตข้อมูลด้านสุขภาพและความเป็นอยู่ที่ดีที่เคยแทรกไว้ก่อนหน้า หากต้องการเพิ่มข้อมูลย้อนหลังของ DataSet
ใหม่ หรือเพิ่มอินสแตนซ์ DataPoint
ใหม่ที่ไม่ขัดแย้งกับจุดข้อมูลที่มีอยู่ ให้ใช้เมธอด HistoryApi.insertData
ใช้ HistoryClient.updateData
เพื่ออัปเดตข้อมูลย้อนหลัง วิธีนี้ลบอินสแตนซ์ DataPoint
ที่มีอยู่ซึ่งซ้อนทับกับอินสแตนซ์ DataPoint
ที่เพิ่มโดยใช้วิธีนี้
หากต้องการอัปเดตข้อมูลด้านสุขภาพและความเป็นอยู่ที่ดี ก่อนอื่นให้สร้างอินสแตนซ์ 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();
จากนั้นใช้ DataUpdateRequest.Builder()
เพื่อสร้างคําขออัปเดตข้อมูลใหม่ และใช้วิธีการ HistoryClient.updateData
สร้างคําขอ ดังนี้
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));
ลบข้อมูล
Google Fit ช่วยให้แอปลบข้อมูลด้านสุขภาพและความเป็นอยู่ที่ดีที่เคยระบุไว้ก่อนหน้านี้
หากต้องการลบข้อมูลย้อนหลัง ให้ใช้เมธอด 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));
แอปลบข้อมูลออกจากเซสชันที่เฉพาะเจาะจงหรือลบข้อมูลทั้งหมดได้ ดูข้อมูลเพิ่มเติมได้ในการอ้างอิง API สําหรับ DataDeleteRequest
ลงทะเบียนเพื่ออัปเดตข้อมูล
แอปอ่านข้อมูลดิบของเซ็นเซอร์แบบเรียลไทม์ได้โดยการลงทะเบียนกับ SensorsClient
สําหรับข้อมูลประเภทอื่นๆ ที่ไม่บ่อยและจะมีการนับด้วยตนเอง แอปของคุณจะลงทะเบียนเพื่อรับข้อมูลอัปเดตได้เมื่อวัดค่าเหล่านี้ลงในฐานข้อมูล Google Fit ตัวอย่างของประเภทข้อมูลเหล่านี้รวมถึงส่วนสูง น้ําหนัก และการออกกําลังกาย เช่น ยกน้ําหนัก โปรดดูรายละเอียดเพิ่มเติมในรายการประเภทข้อมูลที่รองรับทั้งหมด
โปรดใช้ HistoryClient.registerDataUpdateListener
เพื่อลงทะเบียนรับข้อมูลอัปเดต
ข้อมูลโค้ดต่อไปนี้ช่วยให้แอปรับการแจ้งเตือนเมื่อผู้ใช้ป้อนค่าใหม่สําหรับน้ําหนัก
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"));
คุณใช้ IntentService
เพื่อรับการแจ้งเตือนการอัปเดตได้
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}"); } } }
ต้องประกาศ IntentService
ในไฟล์ AndroidManifest.xml
ของคุณ