ใช้งานข้อมูลย้อนหลัง

API ของประวัติช่วยให้แอปของคุณดำเนินการแบบกลุ่มใน Store การออกกำลังกายได้ดังนี้ การอ่าน แทรก การอัปเดต และการลบข้อมูลประวัติด้านสุขภาพและความแข็งแรงสมบูรณ์ ใช้ 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 ข้อ ได้แก่

  • แอปของคุณและร้านฟิตเนสแลกเปลี่ยนข้อมูลจำนวนน้อย
  • แอปของคุณไม่จําเป็นต้องรวบรวมข้อมูลด้วยตนเอง

รวบรวมข้อมูลสำหรับกิจกรรมหลายประเภท

แอปของคุณสามารถใช้คำขอข้อมูลเพื่อดึงข้อมูลประเภทต่างๆ ได้หลายประเภท ตัวอย่างต่อไปนี้จะแสดงวิธีสร้าง 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() ดูข้อมูลเพิ่มเติมเกี่ยวกับวิธีใช้ข้อมูลนี้ในหน้าปัดได้ที่ ข้อมูลแทรกของหน้าปัด และแอปพลิเคชันตัวอย่างสำหรับ Android WatchFace

แทรกข้อมูล

หากต้องการแทรกข้อมูลย้อนหลัง ให้สร้างอินสแตนซ์ 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));
}

จัดการจุดข้อมูลที่ขัดแย้งกัน

ชิ้น DataPoint ใน DataSet ของแอปต้องมี 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