建立 Fitness API 用戶端

本例說明如何建立 Fitness API 用戶端。

建立 API 用戶端,如下所示:

  1. 建立 FitnessOptions 例項,並宣告 資料類型和應用程式存取類型 (讀取和/或寫入) 需要:

    val fitnessOptions = FitnessOptions.builder()
        .addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
        .addDataType(DataType.AGGREGATE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
        .build()
    
  2. 取得要與 API 搭配使用的 Account 物件執行個體:

    val account = GoogleSignIn.getAccountForExtension(this, fitnessOptions)
    
  3. 檢查使用者是否已授予必要的資料存取權,以及 操作時,請啟動授權流程:

    if (!GoogleSignIn.hasPermissions(account, fitnessOptions)) {
        GoogleSignIn.requestPermissions(
            this, // your activity
            GOOGLE_FIT_PERMISSIONS_REQUEST_CODE, // e.g. 1
            account,
            fitnessOptions)
    } else {
        accessGoogleFit()
    }
    
  4. 如果需要授權流程,請處理使用者回應:

    override fun onActivityResult(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
            }
        }
    }
    
  5. 在使用者授權存取要求的資料後,建立健身 用戶端 (例如,讀取及/或寫入歷史健身資料的 HistoryClient) 資料:

    private fun accessGoogleFit() {
        val end = LocalDateTime.now()
        val start = end.minusYears(1)
        val endSeconds = end.atZone(ZoneId.systemDefault()).toEpochSecond()
        val startSeconds = start.atZone(ZoneId.systemDefault()).toEpochSecond()
    
        val readRequest = DataReadRequest.Builder()
            .aggregate(DataType.AGGREGATE_STEP_COUNT_DELTA)
            .setTimeRange(startSeconds, endSeconds, TimeUnit.SECONDS)
            .bucketByTime(1, TimeUnit.DAYS)
            .build()
        val account = GoogleSignIn.getAccountForExtension(this, fitnessOptions)
        Fitness.getHistoryClient(this, account)
            .readData(readRequest)
            .addOnSuccessListener({ response ->
                // Use response data here
                Log.i(TAG, "OnSuccess()")
            })
            .addOnFailureListener({ e -> Log.d(TAG, "OnFailure()", e) })
    }