在 Google 中插入 TYPE_NUTRITION

Insert TYPE_NUTRITION in Google Fit

我收到用户输入(卡路里)并想将其插入 Google Fit 但插入不起作用。

private DataSet insertNutritionData(){
    Calendar cal = Calendar.getInstance();
    Date now = new Date();
    cal.setTime(now);
    long endTime = cal.getTimeInMillis();

    DataSource nutritionSource = new DataSource.Builder()
            .setAppPackageName(getApplicationContext().getPackageName())
            .setDataType(DataType.TYPE_NUTRITION)
            .setType(DataSource.TYPE_RAW)
            .build();

    DataSet dataSet = DataSet.create(nutritionSource);

    DataPoint dataPoint = DataPoint.create(nutritionSource);
    dataPoint.setTimestamp(endTime, TimeUnit.MILLISECONDS); 
    dataPoint.getValue(Field.FIELD_NUTRIENTS).setKeyValue(Field.NUTRIENT_CALORIES,calorie);                          

    dataSet.add(dataPoint);

    return dataSet;

}

插入在 AsyncTask 中完成:

private class InsertAndVerifyNutritionTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params) {

        DataSet dataSet = insertNutritionData();

        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);

        if (!insertStatus.isSuccess()) {
            Log.i(TAG, "There was a problem inserting the dataset.");

            return null;
        }

        Log.i(TAG, "Data insert was successful!");            

        return null;
    }
}

不幸的是,插入没有完成,我不知道为什么。没有示例来解释我们如何使用 TYPE_NUTRIENTS...

非常感谢!

[更新]

我发现了这个错误:

Couldn't connect to Google API client: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null}

但是,我是这样构建我的客户端的:

mClient = new GoogleApiClient.Builder(this)
            .addApi(Fitness.RECORDING_API)
            .addApi(Fitness.SENSORS_API)
            .addApi(Fitness.HISTORY_API)
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
            .addScope(new Scope(Scopes.FITNESS_NUTRITION_READ_WRITE))
            .addConnectionCallbacks(
                    new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(Bundle bundle) {
                            Log.i(TAG, "Google Fit connected.");
                            mTryingToConnect = false;
                            Log.d(TAG, "Notifying the UI that we're connected.");
                            notifyUiFitConnected();

                        }

                        @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.
                            mTryingToConnect = false;
                            if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
                                Log.i(TAG, "Connection lost.  Cause: Network Lost.");
                            } else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
                                Log.i(TAG, "Connection lost.  Reason: Service Disconnected");
                            }
                        }
                    }
            )
            .addOnConnectionFailedListener(
                    new GoogleApiClient.OnConnectionFailedListener() {
                        // Called whenever the API client fails to connect.
                        @Override
                        public void onConnectionFailed(ConnectionResult result) {
                            //Toast.makeText(getActivity(),"connection failed 1",Toast.LENGTH_SHORT).show();
                            mTryingToConnect = false;
                            notifyUiFailedConnection(result);
                        }
                    }
            )
            .build();
}

此外,我不明白为什么我不能连接到合适的,虽然它工作得很好......

更新清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.webear.mysilhouette">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
    android:allowBackup="true"
    android:label="mySilhouette"
    android:icon="@drawable/ic_launcher"
    >

    <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

<service
    android:enabled="true"
    android:name="com.example.webear.mysilhouette.GoogleApiIntentService"/>

(...)

</application>

</manifest>

卡梅尔

statusCode 表示 API_UNAVAILABLE。这意味着:

One of the API components you attempted to connect to is not available. The API will not work on this device, and updating Google Play services will not likely solve the problem. Using the API on the device should be avoided.

也许试试其他设备?或者 Play 服务配置错误。