Steps Count using sensor with google fit

微笑、不失礼 提交于 2019-12-23 04:33:32

问题


I am using Google health kit in my application . I know that Health kit doesn't provide the Sensor Steps Count directly .I read the google fit Documentation And i found that we can use Recording api for Step Count in background . So if it is possible to use Recording api and Sensor api To get the step Counts in background ,Please Tell me how to achieve this. I Want to sense the user activity and how many steps user took during that activity in background . Any help Would be appreciated .

As per the google fit documentation if my application subscribe for recording a data type then it will record the data of that type and store it into HISTORYAPI even if my app is not running. This is the subscription code

Fitness.RecordingApi.subscribe(fitnessClient, DataType.TYPE_ACTIVITY_SAMPLE)
    .setResultCallback(new ResultCallback<Status>() {
        @Override
        public void onResult(Status status) {
            if (status.isSuccess()) {
                if (status.getStatusCode()
                        == FitnessStatusCodes.SUCCESS_ALREADY_SUBSCRIBED) {
                    Log.e(TAG, "Existing subscription for activity detected.");
                } else {
                    Log.e(TAG, "Successfully subscribed activity !");
                }
            } else {
                Log.e(TAG, "There was a problem subscribing.");
            }
        }
    });


Fitness.RecordingApi.subscribe(fitnessClient,DataType.TYPE_STEP_COUNT_DELTA).
        setResultCallback(new ResultCallback<Status>() {

            @Override
            public void onResult(Status arg0) {
                if(arg0.isSuccess()){
                    Log.e("Steps Recording","Subcribe");
                }
            }
        });

Now i have subscribe for the steps and activity. But till now it is not sensing anything . Can anyone explain What is the purpose of subscribe recording a datatype .


回答1:


I just googled about google fit API, it seems the sensor API is use to get the data from the sensor such as user's heart rate, the Recording api is used to collect the data, such as the geolocation data when user running is, and a history api is used to edit the record data. The data which is recorded is collected by google fit in the background, this data can be stored in the cloud, but where is this data stored in local device or will this data be stored in local device? I did't see any information about it, and in your code I didn't see it too. I didn't do any project using google fit API, sorry, can't help more.




回答2:


I know that this is an old question, but I needed help on this too so i'll try to help:

Your activity needs to implements this:

implements NavigationView.OnNavigationItemSelectedListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener

Create this variable before onCreate : public GoogleApiClient mGoogleApiClient = null;

Inside onCreate write this :

mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Fitness.HISTORY_API)
                .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
                .addConnectionCallbacks(this)
                .enableAutoManage(this, 0, this)
                .build();

Don't forget the OAuth authentication.

Then you need this methods:

public void onConnected(@Nullable Bundle bundle) {
        Log.e("HistoryAPI", "onConnected");
    }
@Override
    public void onConnectionSuspended(int i) {
        Log.e("HistoryAPI", "onConnectionSuspended");
    }

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.e("HistoryAPI", "onConnectionFailed");
}


public void onClick(View v) {

}

After this, you will create this method, read the step counter(Google Fit API count them)

public void displayStepDataForToday() {
        DailyTotalResult result = Fitness.HistoryApi.readDailyTotal( mGoogleApiClient, DataType.TYPE_STEP_COUNT_DELTA ).await(1, TimeUnit.MINUTES);
        showDataSet(result.getTotal());
    }

This is the showDataSet that is inside displayStepDataForToday()

private void showDataSet(DataSet dataSet) {
        Log.e("History", "Data returned for Data type: " + dataSet.getDataType().getName());
        DateFormat dateFormat = DateFormat.getDateInstance();
        DateFormat timeFormat = DateFormat.getTimeInstance();

        for (DataPoint dp : dataSet.getDataPoints()) {
            Log.e("History", "Data point:");
            Log.e("History", "\tType: " + dp.getDataType().getName());
            Log.e("History", "\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
            Log.e("History", "\tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
            for(Field field : dp.getDataType().getFields()) {
                Log.e("History", "\tField: " + field.getName() +
                        " Value: " + dp.getValue(field));
                //writeToFile(dp.getValue(field).asInt());
                //this is how I save the data (wit the writeToFile)
            }
        }

    }

Finally you need to create a class (inside your activity) to use the displayStepDataForToday() method

public class ViewTodaysStepCountTask extends AsyncTask<Void, Void, Void> {
        protected Void doInBackground(Void... params) {
            displayStepDataForToday();
            return null;
        }
    }

You just need to start the activity when you want and then get the values of it. This runs in background and updates as I want. If you want this code to update faster you can do some research, but I think that you need to change this line:

 public void displayStepDataForToday() {
        DailyTotalResult result = Fitness.HistoryApi.readDailyTotal( mGoogleApiClient, DataType.TYPE_STEP_COUNT_DELTA ).await(1, TimeUnit.MINUTES);


来源:https://stackoverflow.com/questions/33729379/steps-count-using-sensor-with-google-fit

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