Google Fit API for Android

huangapple go评论88阅读模式
英文:

Google Fit API for Android

问题

以下是您要翻译的内容:

Google Fit 和 Flutter

我正在按照 Google 的这份文档操作:
Google Fit<br />

我不明白第 5 步。我不是 Android 开发者,不知道在哪里找到代码。第 5 步<br />

例如,文档中写道:<br /><br /> 在调用 Google Fit API 的方法之前,您必须连接到以下一个或多个 API 客户端,这些客户端是 Google Play 服务的一部分:

  • 传感器客户端 (Sensors Client)
  • 记录客户端 (Recording Client)
  • 历史客户端 (History Client)
  • 会话客户端 (Sessions Client)
  • 目标客户端 (Goals Client)
  • BLE 客户端 (BLE Client)
  • 配置客户端 (Config Client)

现在,我尝试连接第一个 传感器客户端 (SensorsClient)<br />

但我不知道在哪里找到这段代码,是哪个文件?我是 Flutter 开发者,需要在第 5 步中获得帮助。

build.gradle

dependencies {
    implementation &#39;com.google.android.gms:play-services-fitness:18.0.0&#39;
    implementation &#39;com.google.android.gms:play-services-auth:17.0.0&#39;
    implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version&quot;
    testImplementation &#39;junit:junit:4.12&#39;
    androidTestImplementation &#39;androidx.test:runner:1.1.1&#39;
    androidTestImplementation &#39;androidx.test.espresso:espresso-core:3.1.1&#39;
}
英文:

Google Fit and Flutter

I am following this documentation from Google:
Google Fit<br />

I don't understand step 5. I am not an Android developer and I have no idea where to locate the code. Step 5<br />

For example, it says:<br /><br /> Before you can invoke methods from the Google Fit APIs, you must connect to one or more of the following API clients, which are part of Google Play services:

  • Sensors Client
  • Recording Client
  • History Client
  • Sessions Client
  • Goals Client
  • BLE Client
  • Config Client

Now, I try to connect the first one SensorsClient<br />

But I don't know where to locate the code, which file? I am a flutter developer and I need help in step 5.

build.grandle

dependencies {
    implementation &#39;com.google.android.gms:play-services-fitness:18.0.0&#39;
    implementation &#39;com.google.android.gms:play-services-auth:17.0.0&#39;
    implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version&quot;
    testImplementation &#39;junit:junit:4.12&#39;
    androidTestImplementation &#39;androidx.test:runner:1.1.1&#39;
    androidTestImplementation &#39;androidx.test.espresso:espresso-core:3.1.1&#39;
}

答案1

得分: 6

Use Google Fit [Rest Api][1] in Flutter.

使用Google Fit [Rest API][1]在Flutter中。

Google manages the data through data sources. To see all the data sources:

Google通过数据源管理数据。要查看所有的数据源:

https://www.googleapis.com/fitness/v1/users/me/dataSources

要获取步数:

https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate
请求体:

{    
    "aggregateBy" : [{    
        "dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"    
    }],    
    "bucketByTime": { "durationMillis": 86400000 }, // This is 24 hours    
    "startTimeMillis": 1546210381932,   // Start time    
    "endTimeMillis": 1547210381932  // End Time    
} 

你可以使用[fitKit][2],这是一个用于读取健康和健身数据的Flutter插件。在iOS上封装了HealthKit,在Android上封装了GoogleFit。

import 'package:fit_kit/fit_kit.dart';

void read() async {
  final results = await FitKit.read(
    DataType.HEART_RATE,
    dateFrom: DateTime.now().subtract(Duration(days: 5)),
    dateTo: DateTime.now(),
  );
}

void readLast() async {
  final result = await FitKit.readLast(DataType.HEIGHT);
}

void readAll() async {
  if (await FitKit.requestPermissions(DataType.values)) {
    for (DataType type in DataType.values) {
      final results = await FitKit.read(
        type,
        dateFrom: DateTime.now().subtract(Duration(days: 5)),
        dateTo: DateTime.now(),
      );
    }
  }
}

如果你正在编写自定义的平台特定代码

在调用Google Fit API的方法之前,你必须连接到以下一个或多个API客户端,这些客户端是Google Play服务的一部分:

  1. 传感器客户端: 用于在本地和连接设备中公开不同的健身数据源,并将实时事件传递给监听器。
  2. 录制客户端: 用于将传感器数据低功耗、始终开启的后台收集到Google Fit存储中。
  3. 历史客户端: 用于在Google Fit中插入、删除和读取数据。
  4. 会话客户端: 用于在Google Fit中创建和管理用户活动会话。
  5. 目标客户端: 用于读取用户在Google Fit中创建的健身目标。BLE客户端。
  6. 配置客户端: 用于访问Google Fit中的自定义数据类型和设置。

你必须连接其中一个。

DataReadRequest readRequest = new DataReadRequest.Builder()
            .aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
            .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
            .bucketByTime(1, TimeUnit.DAYS)
            .enableServerQueries()
            .build();
// 历史客户端
Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this))
        .readData(readRequest)
        .addOnSuccessListener(new OnSuccessListener<DataReadResponse>() {
            @Override
            public void onSuccess(DataReadResponse dataReadResponse) {
                Log.d(TAG, "onSuccess()");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(TAG, "onFailure()", e);
            }
        })
        .addOnCompleteListener(new OnCompleteListener<DataReadResponse>() {
            @Override
            public void onComplete(@NonNull Task<DataReadResponse> task) {
                Log.d(TAG, "onComplete()");
            }
        });

从历史客户端获取心率的示例:

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.FitnessOptions;
import com.google.android.gms.fitness.data.Bucket;
import com.google.android.gms.fitness.data.DataPoint;
import com.google.android.gms.fitness.data.DataSet;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.request.DataReadRequest;
import com.google.android.gms.fitness.result.DataReadResponse;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class googleFitData extends AppCompatActivity {
private static final String TAG = "googleFitData";
private static final int GOOGLE_FIT_PERMISSIONS_REQUEST_CODE = 2;
private static final int PERMISSIONS_REQUEST_ACTIVITY_RECOGNITION = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smart_wacth);
String[] PERMISSIONS = {
Manifest.permission.ACTIVITY_RECOGNITION
};
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
PERMISSIONS,
PERMISSIONS_REQUEST_ACTIVITY_RECOGNITION);
}
} else {
googleSignin();
}
}
public void googleSignin() {
FitnessOptions fitnessOptions = FitnessOptions.builder()
.addDataType(DataType.TYPE_HEART_RATE_BPM, FitnessOptions.ACCESS_READ)
.build();
if (!GoogleSignIn.hasPermissions(GoogleSignIn.getLastSignedInAccount(this), fitnessOptions)) {
GoogleSignIn.requestPermissions(
this, // your activity
GOOGLE_FIT_PERMISSIONS_REQUEST_CODE,
GoogleSignIn.getLastSignedInAccount(this),
fitnessOptions);
} else {
accessGoogleFit();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (GOOGLE_FIT_PERMISSIONS_REQUEST_CODE == requestCode) {
accessGoogleFit();
}
if (PERMISSIONS_REQUEST_ACTIVITY_RECOGNITION == requestCode) {
accessGoogleFit();
}
} else {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResult
<details>
<summary>英文:</summary>
Use Google Fit [Rest Api][1] in Flutter.
Google manages the data through data sources. To see all the data sources:
https://www.googleapis.com/fitness/v1/users/me/dataSources  
To get Number of Steps:
https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate
Request body:
{    
&quot;aggregateBy&quot; : [{    
&quot;dataSourceId&quot;: &quot;derived:com.google.step_count.delta:com.google.android.gms:estimated_steps&quot;    
}],    
&quot;bucketByTime&quot;: { &quot;durationMillis&quot;: 86400000 }, // This is 24 hours    
&quot;startTimeMillis&quot;: 1546210381932,   // Start time    
&quot;endTimeMillis&quot;: 1547210381932  // End Time    
} 
You can use [fitKit][2] which is Flutter plugin for reading health and fitness data. Wraps HealthKit on iOS and GoogleFit on Android.
import &#39;package:fit_kit/fit_kit.dart&#39;;
void read() async {
final results = await FitKit.read(
DataType.HEART_RATE,
dateFrom: DateTime.now().subtract(Duration(days: 5)),
dateTo: DateTime.now(),
);
}
void readLast() async {
final result = await FitKit.readLast(DataType.HEIGHT);
}
void readAll() async {
if (await FitKit.requestPermissions(DataType.values)) {
for (DataType type in DataType.values) {
final results = await FitKit.read(
type,
dateFrom: DateTime.now().subtract(Duration(days: 5)),
dateTo: DateTime.now(),
);
}
}
}
***If you are writing custom platform-specific code***
Before you can invoke methods from the Google Fit APIs, you must connect to one or more of the following API clients, which are part of Google Play services:
1. ***Sensors Client :*** Client which exposes different sources of fitness data in local and connected devices, and delivers live events to
listeners.
2. ***Recording Client :*** Client which enables low-power, always-on background collection of sensor data into the Google Fit store.
3. ***History Client :*** Client for inserting, deleting, and reading data in Google Fit.
4. ***Sessions Client :*** Client for creating and managing sessions of user activity in Google Fit.
5. ***Goals Client :*** Client for reading fitness Goals created by users in Google Fit. BLE Client
6. ***Config Client :*** Client for accessing custom data types and settings in Google Fit.
You must connect one of above. 
DataReadRequest readRequest = new DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.bucketByTime(1, TimeUnit.DAYS)
.enableServerQueries()
.build();
// History Client 
Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this))
.readData(readRequest)
.addOnSuccessListener(new OnSuccessListener&lt;DataReadResponse&gt;() {
@Override
public void onSuccess(DataReadResponse dataReadResponse) {
Log.d(TAG, &quot;onSuccess()&quot;);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, &quot;onFailure()&quot;, e);
}
})
.addOnCompleteListener(new OnCompleteListener&lt;DataReadResponse&gt;() {
@Override
public void onComplete(@NonNull Task&lt;DataReadResponse&gt; task) {
Log.d(TAG, &quot;onComplete()&quot;);
}
});
Example for getting Heart Rate from History Client:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.FitnessOptions;
import com.google.android.gms.fitness.data.Bucket;
import com.google.android.gms.fitness.data.DataPoint;
import com.google.android.gms.fitness.data.DataSet;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.request.DataReadRequest;
import com.google.android.gms.fitness.result.DataReadResponse;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class googleFitData extends AppCompatActivity {
private static final String TAG = &quot;googleFitData&quot;;
private static final int GOOGLE_FIT_PERMISSIONS_REQUEST_CODE = 2;
private static final int PERMISSIONS_REQUEST_ACTIVITY_RECOGNITION = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smart_wacth);
String[] PERMISSIONS = {
Manifest.permission.ACTIVITY_RECOGNITION
};
if (android.os.Build.VERSION.SDK_INT &gt;= android.os.Build.VERSION_CODES.Q) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
PERMISSIONS,
PERMISSIONS_REQUEST_ACTIVITY_RECOGNITION);
}
} else {
googleSignin();
}
}
public void googleSignin() {
FitnessOptions fitnessOptions = FitnessOptions.builder()
.addDataType(DataType.TYPE_HEART_RATE_BPM, FitnessOptions.ACCESS_READ)
.build();
if (!GoogleSignIn.hasPermissions(GoogleSignIn.getLastSignedInAccount(this), fitnessOptions)) {
GoogleSignIn.requestPermissions(
this, // your activity
GOOGLE_FIT_PERMISSIONS_REQUEST_CODE,
GoogleSignIn.getLastSignedInAccount(this),
fitnessOptions);
} else {
accessGoogleFit();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (GOOGLE_FIT_PERMISSIONS_REQUEST_CODE == requestCode) {
accessGoogleFit();
}
if (PERMISSIONS_REQUEST_ACTIVITY_RECOGNITION == requestCode) {
accessGoogleFit();
}
} else {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
}
}
private void accessGoogleFit() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
long endTime = cal.getTimeInMillis();
cal.add(Calendar.YEAR, -1);
long startTime = cal.getTimeInMillis();
DataReadRequest readRequest = new DataReadRequest.Builder()
.read(DataType.TYPE_HEART_RATE_BPM)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.bucketByTime(365, TimeUnit.DAYS)
.build();
Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this))
.readData(readRequest)
.addOnSuccessListener(new OnSuccessListener&lt;DataReadResponse&gt;() {
@Override
public void onSuccess(DataReadResponse dataReadResponse) {
Log.d(TAG, &quot;onSuccess()&quot;);
for (Bucket bucket : dataReadResponse.getBuckets()) {
Log.e(&quot;History&quot;, &quot;Data returned for Data type: &quot; + bucket.getDataSets());
List&lt;DataSet&gt; dataSets = bucket.getDataSets();
for (DataSet dataSet : dataSets) {
showDataSet(dataSet);
}
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, &quot;onFailure()&quot;, e);
}
})
.addOnCompleteListener(new OnCompleteListener&lt;DataReadResponse&gt;() {
@Override
public void onComplete(@NonNull Task&lt;DataReadResponse&gt; task) {
Log.d(TAG, &quot;onComplete()&quot;);
}
});
}
private void showDataSet(DataSet dataSet) {
DateFormat dateFormat = DateFormat.getDateInstance();
DateFormat timeFormat = DateFormat.getTimeInstance();
for (DataPoint dp : dataSet.getDataPoints()) {
Log.e(&quot;History&quot;, &quot;Data point:&quot;);
Log.e(&quot;History&quot;, &quot;\tType: &quot; + dp.getDataType().getName());
Log.e(&quot;History&quot;, &quot;\tStart: &quot; + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)) + &quot; &quot; + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
Log.e(&quot;History&quot;, &quot;\tEnd: &quot; + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)) + &quot; &quot; + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
for (Field field : dp.getDataType().getFields()) {
Log.e(&quot;History&quot;, &quot;\tField: &quot; + field.getName() +
&quot; Value: &quot; + dp.getValue(field));
}
}
}
}
[1]: https://developers.google.com/fit/rest
[2]: https://pub.dev/packages/fit_kit
</details>

huangapple
  • 本文由 发表于 2020年1月3日 21:18:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579285.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定