Google Fit API Sleep insert and read DataPoint in Session

白昼怎懂夜的黑 提交于 2019-12-24 00:13:36

问题


I try (like in the topic described) to insert and read Sleep as an Fitness Activity. Main Goal is to analyse a whole sleep with (when was Light/deep sleep and how long) for a single Session. Connection to GoogleFit succeed. But i have trouble with Datapoint and Data Session. Maybe you can help me. Thanks guys :D

A little bit of code where i think i'm trouble. I'm aware of the not clear code. i tried to copy i tried to paste. in some parts the names doesn't fit. But as i mention. i try to figure out the light and deep sleep phases during a sleep session. I gather this date with 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:


5 days to solve the insert session on GoogleFit.... That's my code:

Log.d(iKcal.TAG + "/" + TAG, "Inserting sessions on 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));
}

At the end I dismiss a Dialog and I call a new Activity but you can do everything. You don't receive results because it's return after 400-500 milliseconds.

The insert works perfectly but I can't read well: If I try to read in onCreate or onResume the first time doesn't work, but if I insert a new Session and read, works perfectly.



来源:https://stackoverflow.com/questions/40551958/google-fit-api-sleep-insert-and-read-datapoint-in-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!