首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Google Fit:保存医疗数据

Google Fit:保存医疗数据
EN

Stack Overflow用户
提问于 2017-03-16 18:22:08
回答 2查看 536关注 0票数 1

备注

我在StackOverflow上找不到任何类似的问题。在我找到的唯一线索中,他们问的是阅读,而不是写作。

问题

我正在集成GoogleFit,但我无法将血压数据insertHistoryApi。我成功登录,但在添加数据时,我总是得到:

Status{statusCode=TIMEOUT, resolution=null}

我尝试将代码放在AsyncTask中,并与.await(1, TimeUnit.MINUTES)同步插入,但仍然收到相同的错误。

我还尝试卸载了GoogleFit,并且我可以通过WiFi访问互联网。

如果有帮助的话,S Health运行得很好。

代码

代码语言:javascript
复制
public static void saveBloodPressure(Context context, long timestampMillis, int systolic, int diastolic){

    // Create DataSource
    DataSource bloodPressureSource = new DataSource.Builder()
            .setDataType(HealthDataTypes.TYPE_BLOOD_PRESSURE)
            .setAppPackageName(context)
            .setStreamName(TAG + " - blood pressure")
            .setType(DataSource.TYPE_RAW)
            .build();

    // Create DataPoint with DataSource
    DataPoint bloodPressure = DataPoint.create(bloodPressureSource);
    bloodPressure.setTimestamp(timestampMillis, TimeUnit.MILLISECONDS);
    bloodPressure.getValue(HealthFields.FIELD_BLOOD_PRESSURE_SYSTOLIC).setFloat(systolic);
    bloodPressure.getValue(HealthFields.FIELD_BLOOD_PRESSURE_DIASTOLIC).setFloat(diastolic);

    // Create DataSet
    DataSet dataSet = DataSet.create(bloodPressureSource);
    dataSet.add(bloodPressure);

    // Create Callback to manage Result
    ResultCallback<com.google.android.gms.common.api.Status> callback = new ResultCallback<com.google.android.gms.common.api.Status>() {
        @Override
        public void onResult(@NonNull com.google.android.gms.common.api.Status status) {

            if (status.isSuccess()) {
                Log.v("GoogleFit", "Success: " + status);
            }else{
                Log.v("GoogleFit", "Error: " + status);
            }
        }
    };

    // Execute insert
    Fitness.HistoryApi.insertData(mGoogleApiClient, dataSet)
            .setResultCallback(callback, 1, TimeUnit.MINUTES);
}

如果有人问起,我也会把GoogleApiClient初始化放在下面。

GoogleApiClient初始化

代码语言:javascript
复制
public static void initialize(final FragmentActivity activity){

    // Setup Callback listener
    GoogleApiClient.ConnectionCallbacks connectionCallbacks = new GoogleApiClient.ConnectionCallbacks() {
        @Override
        public void onConnected(Bundle bundle) {
            Log.i(TAG, "Connected! ");
            // Now you can make calls to the Fitness APIs.
            //subscribe();
        }

        @Override
        public void onConnectionSuspended(int i) {
            // If your connection to the sensor gets lost at some point,
            // you'll be able to determine the reason and react to it here.
            if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
                Log.i(TAG, "1 Connection lost.  Cause: Network Lost.");
            } else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
                Log.i(TAG, "2 Connection lost.  Reason: Service Disconnected");
            }
        }
    };

    // Handle Failed connection
    GoogleApiClient.OnConnectionFailedListener connectionFailed = new GoogleApiClient.OnConnectionFailedListener() {
        @Override
        public void onConnectionFailed(@NonNull ConnectionResult result) {

            Log.i(TAG, "3 Google Play services connection failed. Cause: " + result.toString());

            Toast.makeText(activity, "4 Exception while connecting to Google Play services: " +
                    result.getErrorMessage() + ":" + result.getErrorCode(), Toast.LENGTH_SHORT).show();

        }
    };

    // Create Google Api Client
    mGoogleApiClient = new GoogleApiClient.Builder(activity)
            .addConnectionCallbacks(connectionCallbacks)
            .enableAutoManage(activity, connectionFailed)
            .addScope(new Scope(Scopes.FITNESS_BODY_READ_WRITE))
            .addApi(Fitness.HISTORY_API)
            .build();
}

谢谢!

EN

回答 2

Stack Overflow用户

发布于 2017-03-17 21:20:28

尽管它看起来像是连接超时错误,但在我看来,您似乎遗漏了一些东西。

我不确定这是否会有帮助,但FITNESS_BODY_READ_WRITE作用域需要权限。

您是否在调用Fitness.HistoryApi.insertData之前使用Fitness API进行了授权?

您要为哪个用户插入数据?

查看此处:https://developers.google.com/android/guides/permissions

这里(授权):https://developers.google.com/android/reference/com/google/android/gms/fitness/Fitness

票数 0
EN

Stack Overflow用户

发布于 2017-03-17 23:41:24

按照Insert data上的指南进行操作

插入数据

要将数据插入到健身历史记录中,请首先创建一个DataSet实例:

代码语言:javascript
复制
// Set a start and end time for our data, using a start time of 1 hour before this moment.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.HOUR_OF_DAY, -1);
long startTime = cal.getTimeInMillis();

// 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
int stepCountDelta = 950;
DataSet dataSet = DataSet.create(dataSource);
// For each data point, specify a start time, end time, and the data value -- in this case,
// the number of new steps.
DataPoint dataPoint = dataSet.createDataPoint()
        .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
dataPoint.getValue(Field.FIELD_STEPS).setInt(stepCountDelta);
dataSet.add(dataPoint);

创建DataSet实例后,使用HistoryApi.insertData方法并同步等待,或者提供一个回调方法来检查插入状态。

代码语言:javascript
复制
// Then, invoke the History API to insert the data and await the result, which is // possible here because of the {@link AsyncTask}. Always include a timeout when calling // await() to prevent hanging that can occur from the service being shutdown because // of low memory or other conditions. Log.i(TAG, "Inserting the dataset in the History API."); com.google.android.gms.common.api.Status insertStatus
=
        Fitness.HistoryApi.insertData(mClient, dataSet)
                .await(1, TimeUnit.MINUTES);

// Before querying the data, check to see if the insertion succeeded. if (!insertStatus.isSuccess()) {
    Log.i(TAG, "There was a problem inserting the dataset.");
    return null; }

// At this point, the data has been inserted and can be read. Log.i(TAG, "Data insert was successful!");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42831225

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档