Các API của Google Fit, bao gồm cả API Google Fit REST, sẽ ngừng hoạt động vào năm 2026. Kể từ ngày 1 tháng 5 năm 2024, nhà phát triển không thể đăng ký sử dụng các API này.
Kiểm tra xem trước đây người dùng đã cấp quyền truy cập cần thiết vào dữ liệu hay chưa, và
không, hãy bắt đầu quy trình uỷ quyền:
if(!GoogleSignIn.hasPermissions(account,fitnessOptions)){GoogleSignIn.requestPermissions(this,// your activityGOOGLE_FIT_PERMISSIONS_REQUEST_CODE,// e.g. 1account,fitnessOptions)}else{accessGoogleFit()}
Nếu quy trình uỷ quyền là bắt buộc, hãy xử lý phản hồi của người dùng:
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}}}
Sau khi người dùng cấp quyền truy cập vào dữ liệu được yêu cầu, hãy tạo một
ứng dụng khách (ví dụ: HistoryClient để đọc và/hoặc ghi dữ liệu về hoạt động thể dục trước đây
dựa trên mục đích và nhu cầu của ứng dụng:
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)})}
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 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,[]]