The Google Fit APIs, including the Google Fit REST API, will no longer be available after June 30, 2025. As of May 1, 2024, developers cannot sign up to use these APIs.
Check if the user has previously granted the necessary data access, and if
not, initiate the authorization flow:
if(!GoogleSignIn.hasPermissions(account,fitnessOptions)){GoogleSignIn.requestPermissions(this,// your activityGOOGLE_FIT_PERMISSIONS_REQUEST_CODE,// e.g. 1account,fitnessOptions)}else{accessGoogleFit()}
If the authorization flow is required, handle the user's response:
overridefunonActivityResult(requestCode:Int,resultCode:Int,data:Intent?){super.onActivityResult(requestCode,resultCode,data)when(resultCode){Activity.RESULT_OK->when(requestCode){GOOGLE_FIT_PERMISSIONS_REQUEST_CODE->accessGoogleFit()else->{// Result wasn't from Google Fit}}else->{// Permission not granted}}}
After the user has authorized access to the data requested, create a fitness
client (for example, a HistoryClient to read and/or write historic fitness
data) based on your app's purpose and needs:
privatefunaccessGoogleFit(){valend=LocalDateTime.now()valstart=end.minusYears(1)valendSeconds=end.atZone(ZoneId.systemDefault()).toEpochSecond()valstartSeconds=start.atZone(ZoneId.systemDefault()).toEpochSecond()valreadRequest=DataReadRequest.Builder().aggregate(DataType.AGGREGATE_STEP_COUNT_DELTA).setTimeRange(startSeconds,endSeconds,TimeUnit.SECONDS).bucketByTime(1,TimeUnit.DAYS).build()valaccount=GoogleSignIn.getAccountForExtension(this,fitnessOptions)Fitness.getHistoryClient(this,account).readData(readRequest).addOnSuccessListener({response->
// Use response data hereLog.i(TAG,"OnSuccess()")}).addOnFailureListener({e->Log.d(TAG,"OnFailure()",e)})}