עובדים עם נתונים היסטוריים

ה-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 מייצג את מספר הצעדים ביום. בתרחיש לדוגמה זה, לנקודות על נתונים נצברים יש שני יתרונות:

  • האפליקציה וחנות הכושר מחליפים כמות קטנה יותר של נתונים.
  • אין צורך לצבור את הנתונים באופן ידני באפליקציה.

נתונים נצברים של מספר סוגי פעילות

האפליקציה שלכם יכולה להשתמש בבקשות לנתונים כדי לאחזר סוגים רבים של נתונים. הדוגמה הבאה מראה איך ליצור 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));
}

ניהול נקודות נתונים מתנגשות

לכל DataSetDataPoint באפליקציה שלך 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.