Created
August 18, 2020 17:48
-
-
Save brh/9a6646214c0d75ce348421fa1e06621f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* For more than simple apps this is sufficient, larger apps the actual data fetch would | |
* be through a repository or a usecase class | |
*/ | |
fun fetchData() { | |
val cal = Calendar.getInstance(); | |
cal.setTime(Date()); | |
val endTime = cal.getTimeInMillis (); | |
cal.add(Calendar.DATE, -14); | |
val startTime = cal.getTimeInMillis (); | |
val ds= DataSource.Builder() | |
.setAppPackageName("com.google.android.gms") | |
.setDataType(DataType.TYPE_STEP_COUNT_DELTA) | |
.setType(DataSource.TYPE_DERIVED) | |
.setStreamName("estimated_steps") | |
.build() | |
val readRequest = DataReadRequest.Builder() | |
.aggregate(ds, DataType.AGGREGATE_STEP_COUNT_DELTA) | |
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS) | |
.bucketByTime(1, TimeUnit.DAYS) | |
.build(); | |
Fitness.getHistoryClient(FitApp.ctx, account) | |
.readData(readRequest) | |
.addOnSuccessListener {dataResponse:DataReadResponse -> | |
//spawn a coroutine to stay off of main thread | |
viewModelScope.launch(Dispatchers.IO) { | |
val stepField = DataType.AGGREGATE_STEP_COUNT_DELTA.fields[0] | |
//filter only days that have actual data so there won't be 0s in the list | |
val dateStepsList = | |
dataResponse.buckets.filter { bucket -> !(bucket.dataSets[0].dataPoints.isEmpty()) } | |
.map { bucket -> | |
val steps = | |
bucket.dataSets[0].dataPoints[0].getValue(stepField).asInt() | |
val date = Date(bucket.getStartTime(TimeUnit.MILLISECONDS)) | |
StepData(date, steps) | |
} | |
liveData.postValue(State.Content(dateStepsList)) | |
} | |
} | |
.addOnFailureListener{ e:Exception -> | |
liveData.value = State.Error(e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment