Le API Google Fit, inclusa l'API REST di Google Fit, verranno ritirate nel 2026. A partire dal 1° maggio 2024, gli sviluppatori non possono registrarsi per utilizzare queste API.
Verifica se l'utente ha precedentemente concesso l'accesso ai dati necessario e se
avvia il flusso di autorizzazione:
if(!GoogleSignIn.hasPermissions(account,fitnessOptions)){GoogleSignIn.requestPermissions(this,// your activityGOOGLE_FIT_PERMISSIONS_REQUEST_CODE,// e.g. 1account,fitnessOptions)}else{accessGoogleFit()}
Se il flusso di autorizzazione è richiesto, gestisci la risposta dell'utente:
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}}}
Dopo che l'utente ha autorizzato l'accesso ai dati richiesti, crea un client per il fitness (ad esempio un HistoryClient per leggere e/o scrivere dati storici relativi al fitness) in base alle finalità e alle esigenze della tua app:
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)})}
[null,null,["Ultimo aggiornamento 2025-08-31 UTC."],[[["\u003cp\u003eThis code snippet demonstrates how to build a Fitness API client to read aggregate step count data.\u003c/p\u003e\n"],["\u003cp\u003eIt highlights the importance of requesting only necessary data types to improve user consent rates.\u003c/p\u003e\n"],["\u003cp\u003eThe example guides developers through creating \u003ccode\u003eFitnessOptions\u003c/code\u003e, handling user authorization, and accessing historical fitness data using \u003ccode\u003eHistoryClient\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eIt showcases how to query and retrieve aggregate step count data within a specified time frame.\u003c/p\u003e\n"]]],[],null,["# Create a Fitness API client\n\nThis example shows how to create a Fitness API client.\n| **Note:** In this example, only aggregate steps are read, so no Android permissions are required.\n\nCreate the API client as follows:\n\n1. Create a `FitnessOptions` instance, declaring the\n [data types](/fit/datatypes) and access type (read and/or write) your app\n needs:\n\n **Tip:** Choose data types responsibly. Don't request every data type in case your app might need it. The types specified determine which scopes the user is prompted to grant permission for. Only ask for the data types your app needs so users are more likely to grant access. Users more readily grant access to limited, clearly described scopes. \n\n val fitnessOptions = FitnessOptions.builder()\n .addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)\n .addDataType(DataType.AGGREGATE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)\n .build()\n\n2. Get an instance of the `Account` object to use with the API:\n\n val account = GoogleSignIn.getAccountForExtension(this, fitnessOptions)\n\n3. Check if the user has previously granted the necessary data access, and if\n not, initiate the authorization flow:\n\n if (!GoogleSignIn.hasPermissions(account, fitnessOptions)) {\n GoogleSignIn.requestPermissions(\n this, // your activity\n GOOGLE_FIT_PERMISSIONS_REQUEST_CODE, // e.g. 1\n account,\n fitnessOptions)\n } else {\n accessGoogleFit()\n }\n\n4. If the authorization flow is required, handle the user's response:\n\n override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {\n super.onActivityResult(requestCode, resultCode, data)\n when (resultCode) {\n Activity.RESULT_OK -\u003e when (requestCode) {\n GOOGLE_FIT_PERMISSIONS_REQUEST_CODE -\u003e accessGoogleFit()\n else -\u003e {\n // Result wasn't from Google Fit\n }\n }\n else -\u003e {\n // Permission not granted\n }\n }\n }\n\n5. After the user has authorized access to the data requested, create a fitness\n client (for example, a `HistoryClient` to read and/or write historic fitness\n data) based on your app's purpose and needs:\n\n private fun accessGoogleFit() {\n val end = LocalDateTime.now()\n val start = end.minusYears(1)\n val endSeconds = end.atZone(ZoneId.systemDefault()).toEpochSecond()\n val startSeconds = start.atZone(ZoneId.systemDefault()).toEpochSecond()\n\n val readRequest = DataReadRequest.Builder()\n .aggregate(DataType.AGGREGATE_STEP_COUNT_DELTA)\n .setTimeRange(startSeconds, endSeconds, TimeUnit.SECONDS)\n .bucketByTime(1, TimeUnit.DAYS)\n .build()\n val account = GoogleSignIn.getAccountForExtension(this, fitnessOptions)\n Fitness.getHistoryClient(this, account)\n .readData(readRequest)\n .addOnSuccessListener({ response -\u003e\n // Use response data here\n Log.i(TAG, \"OnSuccess()\")\n })\n .addOnFailureListener({ e -\u003e Log.d(TAG, \"OnFailure()\", e) })\n }"]]