google fit api php
Как получить количество шагов из Google Fit REST API, например из приложения Google Fit?
Я разрабатываю приложение PHP, которое работает с API Google Fit для сбора ежедневного количества шагов пользователя.
Я обнаружил, что существует множество источников данных, и они возвращают разные значения. И значения слишком отличаются от того, что я вижу в приложении Google Fit на моем телефоне.
Вопросы:
1. Какой источник данных использует приложение Google Fit для расчета количества шагов?
2. Почему значение источника данных отличается от значения Google Fit?
3. Как я могу получить значение Google Fit?
4 ответа
Я думаю, но не знаю наверняка, что приложение Fit использует api датчиков. В приложении вы можете использовать API датчиков, как описано в API датчиков Документов Google, и управлять возвращенными данными, как вы желание.
Ниже показан простой способ получить шаги с помощью TYPE_STEP_COUNT_CUMULATIVE и TYPE_RAW.
Вы можете обнаружить, что это дает вам более близкое значение к тому, что дает приложение Fit. Однако, очевидно, что это доступно только на устройстве, поэтому вам нужно будет запустить фоновую службу, которая обновит внешнюю базу данных, что предоставляют вам API записи и истории.
В качестве примечания, чтобы гарантировать, что данные продолжают отправляться в магазин фитнеса, когда ваше приложение находится в фоновом режиме, вам необходимо использовать API записи, это также может изменить значения, которые вы видите.
ОБНОВЛЕНИЕ:
Написав вышесказанное, я подумал, что надо это проверить. Это было из утренней прогулки.
Это из сообщения Google+, которое вы можете найти здесь
«merge_step_deltas дает вам объединенный поток всех ваших счетчиков шагов. Estimated_steps также учитывает активность и оценивает шаги, когда их нет»
Другая незначительно любопытная вещь заключается в том, что днем позже Fit показывает мне, что я сделал 6668 шагов, что так близко к результату Apple, но является пересчетом того, что он первоначально показал мне после синхронизации данных. Мое приложение по-прежнему показывает 6920!
Я не измерял время для синхронизации.
Шаги Google Fit получают через REST Api
Запрос активности пользователя при входе в систему через Google и сохранение токена аутентификации пользователя
Добавить дополнительную область для примера в iOS =
Таким же образом мы можем добавлять области на другом языке
Теперь вызовите api, чтобы получить шаги
Вот ответ от API GoogleFit Steps
Больше всего мне повезло с derived:com.google.step_count.delta:com.google.android.gms:estimated_steps
Первоначально результат был выше, чем то, что читал мой телефон, поэтому я отфильтровал два своих основных шаговых устройства select<|q| q["originDataSourceId"] =
Если позже я попробую другой дневной диапазон, и он будет совершенно нестандартным, я вернусь и отмечу это здесь.
Приложение Google Fit использует источник данных Estimated_steps для расчета количества шагов. DataSourceId: производный: com.google.step_count.delta: com.google.android.gms: Estimated_steps
Каждый источник данных представляет разные устройства / источники. Я вижу, у вас есть умные часы Sony и HTC Desire, подключенные к Google Fit. Каждое из ваших устройств передает в Fit значения, которые объединяются. Merge_step_deltas дает вам объединенный поток всех ваших счетчиков шагов. Estimated_steps также учитывает активность и оценивает шаги, когда их нет.
Platform Overview
Google Fit is an open ecosystem. It lets developers upload health and wellness data to a central repository where users can access their data from different devices and apps in one location. They can still access their data if they upgrade to a new device.
Your health and wellness app can store data from any wearable or sensor, and access data created by other apps.
Read the Google Fit Developer and User Data Policy thoroughly and make sure your app complies with it. Carefully review the Google Fit Terms and Conditions before using Google Fit. By using the API, you agree to the Google Fit Terms and Conditions.
Components
Google Fit consists of the following components:
The fitness store
The fitness store is a cloud service that persists health and wellness data using Google’s infrastructure. Apps on different platforms and devices can store data and access data created by other apps. Google Fit provides a set of APIs that make it easy to insert data and query the fitness store.
The sensor framework
The sensor framework defines high-level representations for sensors, data types, data points, and sessions. These representations make it easy to work with the fitness store on any platform.
Data Sources Data sources represent sensors and consist of a name, the type of data collected, and other sensor details. A data source may represent a hardware sensor or a software sensor. You can define software sensors in your apps. Data Types Data types represent different kinds of health and wellness data, like step count or heart rate. Data types establish a schema through which different apps can understand each other’s data. A data type consists of a name and an ordered list of fields, where each field represents a dimension. For example, a data type for location contains three fields (latitude, longitude, and accuracy), whereas a data type for weight contains only one field. Data Points Data points consist of a timestamped array of values for a data type, read from a data source. You use data points to record and insert health and wellness data in the fitness store, and to read raw data from a data source. Points that contain a start time represent a time range instead of an instantaneous reading. Datasets Datasets represent a set of data points of the same type from a particular data source covering some time interval. You use datasets to insert data into the fitness store. Queries to read data from the fitness store also return datasets. Sessions Sessions represent a time interval during which users perform a fitness activity, such as a run, a bike ride, and so on. Sessions help organize data and perform detailed or aggregate queries on the fitness store for a fitness activity.
Permissions and user controls
Google Fit requires user consent before apps can read or store health and wellness data. Google Fit defines OAuth scopes that map to a number of permission groups with separate read and write privileges: activity, body, location, nutrition and health-related data types (health-related data types are grouped with finer granularity). Each permission group grants apps access to a set of data types. Apps specify one or more of these scopes to work with health and wellness data, and Google Fit requests the corresponding permissions from the user.
Google Fit APIs
Google Fit provides the following APIs:
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Android APIs
The Google Fit APIs for Android are part of Google Play services. The Google Fit APIs are supported on Android 4.1 (API level 16) and higher. Using these APIs, your app can do the following:
Read sensor data
If your app provides information about a user’s activity, such as their daily steps, it can be helpful to show near-real-time data about the user’s movements. The Sensors API provides access to streams of raw data that contain this information. The data can come from sensors available on the Android-powered device as well as from sensors in companion devices, such as wearables.
Record data
If your app needs to gather, store, and sync data about a user’s physical activity, you can use the Recording API. This API stores health and wellness data using subscriptions. Your app specifies one or more types of activities to record. Google Fit then stores data of the specified types in the background even when your app isn’t running. It also restores these subscriptions when the system is restarted.
Historical data
If you want users to be able to view fitness data from past activities, you can use the History API. This API provides access to the historical health and wellness data and lets apps perform bulk operations, such as inserting, deleting, and reading data.
Sessions
Fitness data can be beneficial by itself, but the data is more useful when you combine it with additional information about the user’s activity. The Sessions API bundles health and wellness data, along with some metadata, into units called sessions. Sessions represent a time interval during which the user performs a fitness activity.
View and set goals
Your app can help motivate users by showing how their fitness activity compares to the goals that they’ve set. The Goals API helps your app show users the health and fitness goals that they’ve created.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Getting Started with the REST API
This tutorial shows you how to activate access to the Fitness REST API, obtain OAuth access tokens, and invoke the API methods using HTTP requests.
To use the Fitness REST API, it is important that you understand the basics of RESTful web services and JSON representations.
Get a Google Account
To use the Fitness REST API, you need a Google Account. If you already have an account, then you’re all set. You may also want to create a separate Google Account for testing purposes.
Request an OAuth 2.0 client ID
Follow these steps to request an OAuth 2.0 client ID for the Fitness API.
Click Create. Your new OAuth 2.0 Client ID and secret appear in the list of IDs for your project. An OAuth 2.0 Client ID is a string of characters, something like this:
Try the REST API in the OAuth Playground
The OAuth Playground is the easiest way to familiarize yourself with the Fitness REST API by submitting HTTP requests and observing the responses before you write any client code.
To authorize the Fitness REST API in the OAuth Playground:
Submit HTTP requests
The following examples demonstrate how to send HTTP requests to list all available data sources, and to create a new data source. For the Fitness REST API, the URI format is:
To list all available data sources:
The request and the response appear on the right side of the page. If the request is successful, the response shows the data source from the previous example in JSON format.
To create a data source:
In the Request Body window, copy and paste the following JSON:
In the Request Body window, click Close.
Click Send the request.
The request and the response appear on the right side of the page. The request includes the OAuth access token in the Authorization header:
Authorization: Bearer ya29. OAuthTokenValue
If the request is successful, the first line of the response is:
Use cURL to access the Fit REST API
You can use the cURL command line tool to access the Fit REST API. You will need an OAuth access token to make requests using cURL (see the preceding instructions). Note that access tokens expire after an hour. The following example shows a simple bash script to list all data sources.
Next steps
To learn more about the REST API, see these pages:
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
How to get step count from Google Fit REST API like Google Fit app?
I’m developing a PHP application which work with Google Fit APIs to collect daily user’s step count.
I found that, there are many datasources and they returns different values. And the values are too different from what I see in Google Fit app on my phone.
Questions:
1. Which datasource the Google Fit app use to calculate step count?
2. Why there are different between datasources’s value and Google Fit value?
3. How can I get the Google Fit value?
4 Answers 4
Google Fit App uses the estimated_steps data source to calculate step counts. DataSourceId: derived:com.google.step_count.delta:com.google.android.gms:estimated_steps
Each data source represents a different device/source. I see you have a Sony Smart Watch and a HTC Desire connected to Google Fit. Each of your devices reports values to Fit which are merged together. Merge_step_deltas gives you the merged stream of all your step counters. Estimated_steps also takes into account activity, and estimates steps when there are none.
REST API can only access data which has been synced to the backend. To get same values as Google Fit, read estimated_steps data source. It should be the same as what you see on https://fit.google.com/. The device could have latest values which are not yet synced to the server. We are working on making the syncs and the cross-platform experience more seamless.
— Engineer on Google Fit Team.
I think the difference you are seeing is the difference between how Google uses the History API and the Sensors API. If you are using PHP, you are querying the Google Fit Store via the available fitness API and this is then dependant on what the App has had the ability to save via the recording API. So you may not see all of the data the device has available.
I think, but don’t know for certain, that the Fit App uses the sensors api. Within the App you can use the sensors API as described in the Google Docs Sensors API and manipulate the returned data as you desire.
Below shows a simple way to get steps using TYPE_STEP_COUNT_CUMULATIVE and TYPE_RAW
You may find this gives you a closer value to that given by the Fit App. However this is obviously only available on the device, so you would then need to run a background service that updated an external database, which is what the Recording and History APIs give you.
As a point of note to ensure that data continues to be sent to the Fitness Store when your app is in background you need to use the Recording API, this may also change the values you are seeing.
UPDATE:
Having written the above I thought I ought to test it. This was from a mornings walking.
This is from a Google+ post you can find here
«merge_step_deltas gives you the merged stream of all your step counters. estimated_steps also takes into account activity, and estimates steps when there are none»
The one I haven’t got to the bottom of yet is the sensors using what I show above, it only gives me 2,548 steps.
The other marginally curious thing is that a day later Fit shows me I did 6,668 steps, so closer to the Apple result, but a recalculation from what it initially showed me after the data had synced. My app still shows 6,920!
The time for it all to sync I didn’t measure.