会话和数据点从 google fit 的 SessionsClient 返回 null

问题描述 投票:0回答:0

我正在尝试从 Google Fit 读取睡眠数据,但总是收到空/空会话和数据点。我参考了多种资源,但没有任何帮助。下面是我的代码片段,用于从 google fit 读取睡眠数据。

请让我知道我的代码出了什么问题以及必须做什么。

 val calendar = Calendar.getInstance(Locale.getDefault())
    val now = Date()

    calendar.time = now
    calendar.set(Calendar.HOUR_OF_DAY, 23)
    calendar.set(Calendar.MINUTE, 59)
    calendar.set(Calendar.SECOND, 59)
    val endTime = calendar.timeInMillis

    calendar.add(Calendar.MONTH, -6)
    calendar.set(Calendar.HOUR_OF_DAY, 0)
    calendar.set(Calendar.MINUTE, 0)
    calendar.set(Calendar.SECOND, 0)
    val startTime = calendar.timeInMillis

    val dataSource = DataSource.Builder()
        .setAppPackageName("com.google.android.gms")
        .setDataType(DataType.TYPE_SLEEP_SEGMENT)
        .setType(DataSource.TYPE_RAW)
        .setStreamName("sleep_session")
        .build()

    val readRequest = SessionReadRequest.Builder()
        .readSessionsFromAllApps()
        // By default, only activity sessions are included, so it is necessary to explicitly
        // request sleep sessions. This will cause activity sessions to be *excluded*.
        .includeSleepSessions()
        .includeActivitySessions()
        .enableServerQueries()
        // Sleep segment data is required for details of the fine-granularity sleep, if it is present.
        .read(DataType.TYPE_SLEEP_SEGMENT)
        .read(dataSource)
        .setSessionName("Sample Session sleep")
        .setTimeInterval(startTime, endTime, TimeUnit.SECONDS)
        .build()
    Fitness.getSessionsClient(
        activity,
        GoogleSignIn.getAccountForExtension(activity, fitnessOptions)
    ).readSession(readRequest)
        .addOnSuccessListener { dataReadResponse ->
            processData(dataReadResponse)
        }
        .addOnFailureListener { error -> }


private fun processData(
    dataReadResponse: SessionReadResponse?,
) {
    for (session in dataReadResponse!!.sessions) {
        val sessionStart = session.getStartTime(TimeUnit.MILLISECONDS)
        val sessionEnd = session.getEndTime(TimeUnit.MILLISECONDS)

        // If the sleep session has finer granularity sub-components, extract them:
        val dataSets = dataReadResponse.getDataSet(session)
        for (dataSet in dataSets) {
            for (point in dataSet.dataPoints) {
                val sleepStageVal = point.getValue(Field.FIELD_SLEEP_SEGMENT_TYPE).asInt()
                val sleepStage = SLEEP_STAGE_NAMES[sleepStageVal]
                val segmentStart = point.getStartTime(TimeUnit.MILLISECONDS)
                val segmentEnd = point.getEndTime(TimeUnit.MILLISECONDS)
            }
        }
    }
}

运行代码后,SessionReadResult状态码为成功,但有空会话和数据点。

SessionReadResult{status=Status{statusCode=SUCCESS, resolution=null}, sessions=[], sessionDataSets=[]}

android android-studio kotlin google-fit google-fit-sdk
© www.soinside.com 2019 - 2024. All rights reserved.