Google Fit API Sleep在会话

时间:2016-11-11 16:12:27

标签: android session google-api google-fit

我尝试(如在所描述的主题中)插入和读取睡眠作为健身活动。主要目标是分析单个会话的整个睡眠时间(轻度/深度睡眠时间和持续时间)。 与GoogleFit的连接成功。 但我遇到Datapoint和Data Session问题。 也许你可以帮助我。 谢谢你们:D

我认为我遇到麻烦的一些代码。 我知道不清楚的代码。我试图复制我试图粘贴。在某些部分名称不适合。但正如我所说。我试着在睡眠期间弄清楚轻度和深度睡眠阶段。 我用sonyband 2收集这个日期。

private class InsertAndVerifySessionTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params) {
        //First, create a new session and an insertion request.
       SessionInsertRequest insertRequest = insertFitnessSession();


        Log.i(TAG, "Inserting the session in the History API");
        com.google.android.gms.common.api.Status insertStatus =
                Fitness.SessionsApi.insertSession(mClient, insertRequest)
                        .await(1, TimeUnit.MINUTES);

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

        // At this point, the session has been inserted and can be read.
        Log.i(TAG, "Session insert was successful!");
        // [END insert_session]

        // Begin by creating the query.
        SessionReadRequest readRequest = readFitnessSession();

        // [START read_session]
        // Invoke the Sessions API to fetch the session with the query and wait for the result
        // of the read request. Note: Fitness.SessionsApi.readSession() requires the
        // ACCESS_FINE_LOCATION permission.
        SessionReadResult sessionReadResult =
                Fitness.SessionsApi.readSession(mClient, readRequest)
                        .await(1, TimeUnit.MINUTES);

        // Get a list of the sessions that match the criteria to check the result.
        Log.i(TAG, "Session read was successful. Number of returned sessions is: "
                + sessionReadResult.getSessions().size());
        for (Session session : sessionReadResult.getSessions()) {
            // Process the session
            dumpSession(session);

            // Process the data sets for this session
            List<DataSet> dataSets = sessionReadResult.getDataSet(session);
            for (DataSet dataSet : dataSets) {
                dumpDataSet(dataSet);
            }
        }
        // [END read_session]

        return null;
    }
}



private SessionInsertRequest insertFitnessSession() {
    Log.i(TAG, "Creating a new session for an afternoon run");
    // Setting start and end times for our run.
    Calendar cal = Calendar.getInstance();
    Date now = new Date();
    cal.setTime(now);

    long endTime = cal.getTimeInMillis();
    cal.add(Calendar.MINUTE, -10);
    long endWalkTime = cal.getTimeInMillis();
    cal.add(Calendar.MINUTE, -10);
    long startWalkTime = cal.getTimeInMillis();
    cal.add(Calendar.MINUTE, -10);
    long startTime = cal.getTimeInMillis();




    DataSource activitySegmentDataSource = new DataSource.Builder()
            .setAppPackageName(this.getPackageName())
            .setDataType(DataType.TYPE_ACTIVITY_SEGMENT)
            .setName(SAMPLE_SESSION_NAME + "-activity segments")
            .setType(DataSource.TYPE_RAW)
            .build();
   DataSet activitySegments = DataSet.create(activitySegmentDataSource);

    DataPoint firstRunningDp = activitySegments.createDataPoint()
            .setTimeInterval(startTime, startWalkTime, TimeUnit.MILLISECONDS);
    firstRunningDp.getValue(Field.FIELD_ACTIVITY).setActivity(FitnessActivities.SLEEP_LIGHT);
    activitySegments.add(firstRunningDp);

    DataPoint walkingDp = activitySegments.createDataPoint()
            .setTimeInterval(startWalkTime, endWalkTime, TimeUnit.MILLISECONDS);
    walkingDp.getValue(Field.FIELD_ACTIVITY).setActivity(FitnessActivities.SLEEP_DEEP);
    activitySegments.add(walkingDp);

    DataPoint secondRunningDp = activitySegments.createDataPoint()
            .setTimeInterval(endWalkTime, endTime, TimeUnit.MILLISECONDS);
    secondRunningDp.getValue(Field.FIELD_ACTIVITY).setActivity(FitnessActivities.SLEEP_LIGHT);
    activitySegments.add(secondRunningDp);

    // [START build_insert_session_request]
    // Create a session with metadata about the activity.
    Session session = new Session.Builder()
            .setName(SAMPLE_SESSION_NAME)
            .setDescription("Long run around Shoreline Park")
            .setIdentifier("UniqueIdentifierHere")
            .setActivity(FitnessActivities.SLEEP)
            .setStartTime(startTime, TimeUnit.MILLISECONDS)
            .setEndTime(endTime, TimeUnit.MILLISECONDS)
            .build();

    // Build a session insert request
    SessionInsertRequest insertRequest = new SessionInsertRequest.Builder()
            .setSession(session)
            .addDataSet(activitySegments)
            .build();

    // [END build_insert_session_request]
    // [END build_insert_session_request_with_activity_segments]

    return insertRequest;
}

/**
 * Return a {@link SessionReadRequest} for all speed data in the past week.
 */
private SessionReadRequest readFitnessSession() {
    Log.i(TAG, "Reading History API results for session: " + SAMPLE_SESSION_NAME);
    // [START build_read_session_request]
    // Set a start and end time for our query, using a start time of 1 week before this moment.
    Calendar cal = Calendar.getInstance();
    Date now = new Date();
    cal.setTime(now);
    long endTime = cal.getTimeInMillis();
    cal.add(Calendar.WEEK_OF_YEAR, -1);
    long startTime = cal.getTimeInMillis();

    // Build a session read request
    SessionReadRequest readRequest = new SessionReadRequest.Builder()
            .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
            .read(DataType.TYPE_ACTIVITY_SEGMENT)
            .setSessionName(SAMPLE_SESSION_NAME)
            .build();


    // [END build_read_session_request]

    return readRequest;
}

private void dumpDataSet(DataSet dataSet) {
    Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
    for (DataPoint dp : dataSet.getDataPoints()) {
        DateFormat dateFormat = getTimeInstance();
        Log.i(TAG, "Data point:");
        Log.i(TAG, "\tType: " + dp.getDataType().getName());
        Log.i(TAG, "\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
        Log.i(TAG, "\tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));
        for(Field field : dp.getDataType().getFields()) {
            Log.i(TAG, "\tField: " + field.getName() +
                    " Value: " + dp.getValue(field));
        }
    }
}

private void dumpSession(Session session) {
    DateFormat dateFormat = getTimeInstance();
    Log.i(TAG, "Data returned for Session: " + session.getName()
            + "\n\tDescription: " + session.getDescription()
            + "\n\tStart: " + dateFormat.format(session.getStartTime(TimeUnit.MILLISECONDS))
            + "\n\tEnd: " + dateFormat.format(session.getEndTime(TimeUnit.MILLISECONDS)));
}

1 个答案:

答案 0 :(得分:1)

5天解决GoogleFit上的插入会话.... 那是我的代码:

Log.d(iKcal.TAG +“/”+ TAG,“在GoogleFit上插入会话...”);

    DataSource activitySegmentDataSource = new DataSource.Builder()
            .setAppPackageName(fragmentActivity.getPackageName())
            .setDataType(DataType.TYPE_ACTIVITY_SEGMENT)
            .setName("Activity")
            .setType(DataSource.TYPE_RAW)
            .build();

    DataSource kcalSegmentDataSource = new DataSource.Builder()
            .setAppPackageName(fragmentActivity.getPackageName())
            .setDataType(DataType.AGGREGATE_CALORIES_EXPENDED)
            .setName("Kcal burned")
            .setType(DataSource.TYPE_RAW)
            .build();

    DataSet activityDataSet = DataSet.create(activitySegmentDataSource);
    DataSet kcalDataSet = DataSet.create(kcalSegmentDataSource);

    DataPoint activityDataPoint = activityDataSet.createDataPoint().setTimeInterval(fitness.getStart().getTime(), fitness.getEnd().getTime(), TimeUnit.MILLISECONDS);
    activityDataPoint.getValue(Field.FIELD_ACTIVITY).setActivity(fitness.getFitnessActivity().getFitnessActivity());
    activityDataSet.add(activityDataPoint);

    DataPoint kcalDataPoint = kcalDataSet.createDataPoint().setTimeInterval(fitness.getStart().getTime(), fitness.getEnd().getTime(), TimeUnit.MILLISECONDS);
    kcalDataPoint.getValue(Field.FIELD_CALORIES).setFloat((float) (fitness.getKcal()));
    kcalDataSet.add(kcalDataPoint);

    Session session = new Session.Builder()
            .setName(fragmentActivity.getResources().getString(fitness.getFitnessActivity().getName()))
            .setIdentifier(fragmentActivity.getString(R.string.app_name) + "_" + fitness.getFitnessID()) // ID FITNESS DB
            .setDescription(fitness.getComments())
            .setStartTime(fitness.getStart().getTime(), TimeUnit.MILLISECONDS)
            .setEndTime(fitness.getEnd().getTime(), TimeUnit.MILLISECONDS)
            .setActivity(fitness.getFitnessActivity().getFitnessActivity())
            .build();

    SessionInsertRequest insertRequest = new SessionInsertRequest.Builder()
            .setSession(session)
            .addDataSet(kcalDataSet)        // Inserimento kcal
            //.addDataSet(activityDataSet)    // Inserimento attività
            .build();

    PendingResult<com.google.android.gms.common.api.Status> pendingResult = Fitness.SessionsApi.insertSession(mGoogleApiClient, insertRequest);

    pendingResult.setResultCallback(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())
                onPostExecuteInsert(true);
            else
                onPostExecuteInsert(false);
        }
    });
}

private void onPostExecuteInsert (boolean value){
    FitnessActivity fitnessActivity = (FitnessActivity) fragmentActivity;
    fitnessActivity.getLoadingDialog().dismiss();

    if(value) {
        Log.d(iKcal.TAG + "/" + TAG, "Session inserted on GoogleFit!");
        Toast.makeText(fragmentActivity, R.string.aggiunto_fitness_db_fit, Toast.LENGTH_SHORT).show();
    } else {
        Log.d(iKcal.TAG + "/" + TAG, "Failed to insert session on GoogleFit!");
        Toast.makeText(fragmentActivity, R.string.aggiunto_fitness_solo_db, Toast.LENGTH_SHORT).show();
    }

    fragmentActivity.startActivity(new Intent(fragmentActivity, MainActivity.class));
}

最后我解雇了一个Dialog并且我调用了一个新的Activity,但你可以做任何事情。您没有收到结果,因为它在400-500毫秒后返回。

插入工作完美,但我看不懂:如果我尝试读入onCreate或onResume,第一次不起作用,但如果我插入一个新的Session并读取,则效果很好。