Cloud Stack Ninja

The problem is it is getting steps from google fit api but i have to kill my app and restart my app and then it syncs or shows daily steps from google fit api.What i want is to keep fetching steps from google fit api without killing the app.Please can you tell me the exact way to avoid killing my app and fetch steps in the right way.

//onCreateView

 mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                    .addApi(Fitness.HISTORY_API)
                    .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
                    .addConnectionCallbacks(this)
                    .enableAutoManage(getActivity(), 0, this)
                    .build();
            if (runningTask != null)
                runningTask.cancel(true);
            runningTask = new ViewWeekStepCountTask();
            runningTask.execute();

//Asynctask to avoid ANR's

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

            Calendar cal = Calendar.getInstance();
            Date now = new Date();
            cal.setTime(now);
            long endTime = cal.getTimeInMillis();
            cal.add(Calendar.DAY_OF_WEEK, -1);
            long startTime = cal.getTimeInMillis();

            java.text.DateFormat dateFormat = DateFormat.getDateInstance();
            Log.e("History", "Range Start: " + dateFormat.format(startTime));
            Log.e("History", "Range End: " + dateFormat.format(endTime));


                    DataSource ESTIMATED_STEP_DELTAS = new DataSource.Builder()
                            .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
                            .setType(DataSource.TYPE_DERIVED)
                            .setStreamName("estimated_steps")
                            .setAppPackageName("com.google.android.gms")
                            .build();

                    DataReadRequest readRequest = new DataReadRequest.Builder()
                            .aggregate(ESTIMATED_STEP_DELTAS, DataType.AGGREGATE_STEP_COUNT_DELTA)
                            .bucketByTime(1, TimeUnit.DAYS)
                            .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
                            .build();


                    long total = 0;
                    PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mGoogleApiClient, DataType.TYPE_STEP_COUNT_DELTA);
                    DailyTotalResult totalResult = result.await(30, TimeUnit.SECONDS);
                    if (totalResult.getStatus().isSuccess()) {
                        DataSet totalSet = totalResult.getTotal();
                        total = totalSet.isEmpty()
                                ? 0
                                : totalSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt();
                    } else {
                        Log.w("error steps", "There was a problem getting the step count.");
                    }
                    long globalsteps=0;
                    globalsteps = globalsteps + total;
                    Log.i("stepsfittoday", "Total steps: " + total);
                    
                    DataReadResult dataReadResult = Fitness.HistoryApi.readData(mGoogleApiClient, readRequest).await(1, TimeUnit.MINUTES);
                    if (dataReadResult.getBuckets().size() > 0) {
                        Log.e("History", "Number of buckets: " + dataReadResult.getBuckets().size());
                        for (Bucket bucket : dataReadResult.getBuckets()) {
                            List<DataSet> dataSets = bucket.getDataSets();
                            for (DataSet dataSet : dataSets) {
                                showDataSet(dataSet);
                            }
                        }
                    }
//Used for non-aggregated data
                    else if (dataReadResult.getDataSets().size() > 0) {
                        Log.e("History", "Number of returned DataSets: " + dataReadResult.getDataSets().size());
                        for (DataSet dataSet : dataReadResult.getDataSets()) {
                            showDataSet(dataSet);
                        }
                    }

            return null;
        }
    }



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

            }
        }

    }


Read more here: https://stackoverflow.com/questions/64399440/google-fit-not-syncing-properly

Content Attribution

This content was originally published by akash sharma at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: