访问原始传感器数据

借助 传感器 API,您可以实时读取应用中的原始传感器数据。使用 此 API 可以执行以下操作:

  • 列出设备和配套设备上可用的数据源。
  • 注册监听器以接收原始传感器数据。
  • 取消注册监听器,使其不再接收原始传感器数据。

列出可用的数据源

获取设备和配套设备上所有可用数据源的列表 设备,请使用 SensorsClient.findDataSources 方法:

Kotlin

private val fitnessOptions = FitnessOptions.builder().addDataType(DataType.TYPE_STEP_COUNT_DELTA).build()

// Note: Fitness.SensorsApi.findDataSources() requires the
// ACCESS_FINE_LOCATION permission.
Fitness.getSensorsClient(requireContext(), GoogleSignIn.getAccountForExtension(requireContext(), fitnessOptions))
    .findDataSources(
        DataSourcesRequest.Builder()
            .setDataTypes(DataType.TYPE_STEP_COUNT_DELTA)
            .setDataSourceTypes(DataSource.TYPE_RAW)
            .build())
    .addOnSuccessListener { dataSources ->
        dataSources.forEach {
            Log.i(TAG, "Data source found: ${it.streamIdentifier}")
            Log.i(TAG, "Data Source type: ${it.dataType.name}")

            if (it.dataType == DataType.TYPE_STEP_COUNT_DELTA) {
                Log.i(TAG, "Data source for STEP_COUNT_DELTA found!")

                ...
            }
        }
    }
    .addOnFailureListener { e ->
        Log.e(TAG, "Find data sources request failed", e)
    }

Java

FitnessOptions fitnessOptions = FitnessOptions.builder().addDataType(DataType.TYPE_STEP_COUNT_DELTA).build();

// Note: Fitness.SensorsApi.findDataSources() requires the
// ACCESS_FINE_LOCATION permission.
Fitness.getSensorsClient(getApplicationContext(), GoogleSignIn.getAccountForExtension(getApplicationContext(), fitnessOptions))
        .findDataSources(
                new DataSourcesRequest.Builder()
                        .setDataTypes(DataType.TYPE_STEP_COUNT_DELTA)
                        .setDataSourceTypes(DataSource.TYPE_RAW)
                        .build())
        .addOnSuccessListener(dataSources -> {
            dataSources.forEach(dataSource -> {
                Log.i(TAG, "Data source found: ${it.streamIdentifier}");
                Log.i(TAG, "Data Source type: ${it.dataType.name}");

                if (dataSource.getDataType() == DataType.TYPE_STEP_COUNT_DELTA) {
                    Log.i(TAG, "Data source for STEP_COUNT_DELTA found!");
                    ...
                }
            })})
        .addOnFailureListener(e ->
            Log.e(TAG, "Find data sources request failed", e));

如需为数据源获取设备信息,请使用 DataSource.getDevice 方法。设备信息有助于与类似设备区分开来 不同设备上的传感器,可显示从传感器到 用户或根据设备以不同方式处理数据。例如,您可以 专门从穿戴式设备上的传感器读取数据 但并非来自手机上同类型的传感器。

获取 Device 例如,对于运行 activity 的设备,请使用 Device.getLocalDevice 方法。如果您想检查某个数据源是否位于 运行您的应用的设备

添加监听器

添加监听器,以从特定健身数据类型或从 特定数据源,请使用 SensorsClient.add 方法:

Kotlin

val listener = OnDataPointListener { dataPoint ->
        for (field in dataPoint.dataType.fields) {
            val value = dataPoint.getValue(field)
            Log.i(TAG, "Detected DataPoint field: ${field.name}")
            Log.i(TAG, "Detected DataPoint value: $value")
        }
    }

Fitness.getSensorsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    .add(
        SensorRequest.Builder()
            .setDataSource(dataSource) // Optional but recommended for custom
            // data sets.
            .setDataType(dataType) // Can't be omitted.
            .setSamplingRate(10, TimeUnit.SECONDS)
            .build(),
        listener
    )
    .addOnSuccessListener {
    	Log.i(TAG, "Listener registered!")
    }
    .addOnFailureListener {
    	Log.e(TAG, "Listener not registered.", task.exception)
    }

Java

OnDataPointListener listener = dataPoint -> {
    for (Field field : dataPoint.getDataType().getFields()) {
        Value value = dataPoint.getValue(field);
        Log.i(TAG, "Detected DataPoint field: ${field.getName()}");
        Log.i(TAG, "Detected DataPoint value: $value");
    }
};
Fitness.getSensorsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
        .add(
                new SensorRequest.Builder()
                        .setDataSource(dataSource) // Optional but recommended
                        // for custom data sets.
                        .setDataType(dataType) // Can't be omitted.
                        .setSamplingRate(10, TimeUnit.SECONDS)
                        .build(),
                listener
        )
        .addOnSuccessListener(unused ->
                Log.i(TAG, "Listener registered!"))
        .addOnFailureListener(task ->
    Log.e(TAG, "Listener not registered.", task.getCause()));
}

移除监听器

要从原始数据更新中移除监听器,请使用 SensorsClient.remove 方法:

Kotlin

Fitness.getSensorsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    .remove(listener)
    .addOnSuccessListener {
    	Log.i(TAG, "Listener was removed!")
    }
    .addOnFailureListener {
    	Log.i(TAG, "Listener was not removed.")
    }

Java

Fitness.getSensorsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
        .remove(listener)
        .addOnSuccessListener(unused ->
                Log.i(TAG, "Listener was removed!"))
        .addOnFailureListener(e ->
                Log.i(TAG, "Listener was not removed."));