本文介绍了Google Fit API Sleep在Session中插入并读取DataPoint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试(如所描述的主题)插入并将睡眠阅读为健身活动。主要目标是为单个会话分析整个睡眠(何时是轻微/深度睡眠和多久)。
与GoogleFit的连接成功。
但是我有数据点和数据会话的麻烦。
也许你可以帮助我。
谢谢你们:D



一些代码,我认为我很麻烦。
我知道不明确的代码。我试图复制我试图粘贴。在某些地方名称不适合。但正如我所说。我试图找出睡眠期间的轻度和深度睡眠阶段。
我收集这个日期与sonyband 2。

  private class InsertAndVerifySessionTask extends AsyncTask< Void,Void,Void> {
protected void doInBackground(Void ... params){
//首先,创建一个新的会话和一个插入请求。
SessionInsertRequest insertRequest = insertFitnessSession();


Log.i(TAG,在历史API中插入会话);
com.google.android.gms.common.api.Status insertStatus =
Fitness.SessionsApi.insertSession(mClient,insertRequest)
.await(1,TimeUnit.MINUTES);

//在查询会话之前,检查插入是否成功。
if(!insertStatus.isSuccess()){
Log.i(TAG,插入会话时出现问题:+
insertStatus.getStatusMessage());
返回null;
}

//此时,会话已被插入并且可以被读取。
Log.i(标签,会话插入成功!);
// [END insert_session]

//开始创建查询。
SessionReadRequest readRequest = readFitnessSession();

// [START read_session]
//调用Sessions API以查询会话并等待读取请求的结果
//。注意:Fitness.SessionsApi.readSession()需要
// ACCESS_FINE_LOCATION权限。
SessionReadResult sessionReadResult =
Fitness.SessionsApi.readSession(mClient,readRequest)
.await(1,TimeUnit.MINUTES);

//获取符合条件的会话列表以检查结果。
Log.i(TAG,会话读取成功,返回的会话数量为:
+ sessionReadResult.getSessions()。size());
for(Session session:sessionReadResult.getSessions()){
//处理会话
dumpSession(session);

//处理此会话的数据集
List< DataSet> dataSets = sessionReadResult.getDataSet(session);
for(DataSet dataSet:dataSets){
dumpDataSet(dataSet);
}
}
// [END read_session]

return null;





private SessionInsertRequest insertFitnessSession(){
Log.i(TAG,创建一个下午的新会话跑);
//设置我们运行的开始和结束时间。
日历cal = Calendar.getInstance();
现在的日期= 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]
//使用关于活动的元数据创建会话。
Session session = new Session.Builder()
.setName(SAMPLE_SESSION_NAME)
.setDescription(Longline around Shoreline Park)
.setIdentifier(UniqueIdentifierHere)
.setActivity(FitnessActivities.SLEEP)
.setStartTime(startTime,TimeUnit.MILLISECONDS)
.setEndTime(endTime,TimeUnit.MILLISECONDS)
.build();

//创建会话插入请求
SessionInsertRequest insertRequest = new SessionInsertRequest.Builder()
.setSession(session)
.addDataSet(activitySegments)
。建立();

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

return insertRequest;
}

/ **
*在过去一周内为所有速度数据返回{@link SessionReadRequest}。
* /
private SessionReadRequest readFitnessSession(){
Log.i(TAG,阅读会话的历史API结果:+ SAMPLE_SESSION_NAME);
// [START build_read_session_request]
//设置我们查询的开始和结束时间,使用此时刻之前1周的开始时间。
日历cal = Calendar.getInstance();
现在的日期= new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.WEEK_OF_YEAR,-1);
long startTime = cal.getTimeInMillis();

//建立会话读取请求
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]

返回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))); (Field field:dp.getDataType()。getFields()){
Log.i(TAG,\ tField:+ field.getName()+

Value: + dp.getValue(field));



$ b private void dumpSession(Session session){
DateFormat dateFormat = getTimeInstance();
Log.i(TAG,会话返回的数据:+ session.getName()
+\\\
\tDescription:+ session.getDescription()
+\\ \\ n \ tStart:+ dateFormat.format(session.getStartTime(TimeUnit.MILLISECONDS))
+\\\
\tEnd:+ dateFormat.format(session.getEndTime(TimeUnit.MILLISECONDS))) ;
}


解决方案

5天解决插入在GoogleFit上进行会话....
这是我的代码:



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

pre $ 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烧))
.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) // Inserimentoattività
.build();

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

pendingResult.setResultCallback(新的ResultCallback< com.google.android.gms.common.api.Status>(){
@Override
public void onResult(@NonNull com。 google.android.gms.common.api.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,插在GoogleFit上的会话!);
Toast.makeText(fragmentActivity,R.string.aggiunto_fitness_db_fit,Toast.LENGTH_SHORT).show();
} else {
Log.d(iKcal.TAG +/+ TAG,无法在GoogleFit上插入会话!);
Toast.makeText(fragmentActivity,R.string.aggiunto_fitness_solo_db,Toast.LENGTH_SHORT).show();
}

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

最后,我忽略了一个对话框,然后我调用一个新的Activity,但是可以做任何事。你不会收到结果,因为它是在400-500毫秒之后返回的。



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


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)));
}
解决方案

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.

这篇关于Google Fit API Sleep在Session中插入并读取DataPoint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:19