5

我需要我的应用程序从 Google Fit 读取步数。我正在使用健康 3.05 包。现在我复制了示例代码以查看它是否有效,不幸的是它不是。当然,我从这个包自述文件中完成了每一步。我设置了 OAuth2 客户端 ID,我更改了 gradle.properties,因为它们显示在 AndroidManifest.xml 中<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/> 。但是,在运行应用程序后,我没有获得任何权限窗口,当我单击按钮获取数据时,我在控制台中收到错误“未授予授权”。我应该怎么办?谢谢

这是我从包示例中复制的代码:

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:health/health.dart';

class DailyStepsScreen extends StatefulWidget {
  @override
  _DailyStepsScreenState createState() => _DailyStepsScreenState();
}

enum AppState {
  DATA_NOT_FETCHED,
  FETCHING_DATA,
  DATA_READY,
  NO_DATA,
  AUTH_NOT_GRANTED
}

class _DailyStepsScreenState extends State<DailyStepsScreen> {
  List<HealthDataPoint> _healthDataList = [];
  AppState _state = AppState.DATA_NOT_FETCHED;

  @override
  void initState() {
    super.initState();
  }


  Future<void> fetchData() async {
    /// Get everything from midnight until now
    DateTime startDate = DateTime(2020, 11, 07, 0, 0, 0);
    DateTime endDate = DateTime(2025, 11, 07, 23, 59, 59);

    HealthFactory health = HealthFactory();

    /// Define the types to get.
    List<HealthDataType> types = [
      HealthDataType.STEPS,
      HealthDataType.WEIGHT,
      HealthDataType.HEIGHT,
      HealthDataType.BLOOD_GLUCOSE,
      HealthDataType.DISTANCE_WALKING_RUNNING,
    ];

    setState(() => _state = AppState.FETCHING_DATA);

    /// You MUST request access to the data types before reading them
    bool accessWasGranted = await health.requestAuthorization(types);

    int steps = 0;

    if (accessWasGranted) {
      try {
        /// Fetch new data
        List<HealthDataPoint> healthData =
        await health.getHealthDataFromTypes(startDate, endDate, types);

        /// Save all the new data points
        _healthDataList.addAll(healthData);
      } catch (e) {
        print("Caught exception in getHealthDataFromTypes: $e");
      }

      /// Filter out duplicates
      _healthDataList = HealthFactory.removeDuplicates(_healthDataList);

      /// Print the results
      _healthDataList.forEach((x) {
        print("Data point: $x");
        steps += x.value.round();
      });

      print("Steps: $steps");

      /// Update the UI to display the results
      setState(() {
        _state =
        _healthDataList.isEmpty ? AppState.NO_DATA : AppState.DATA_READY;
      });
    } else {
      print("Authorization not granted");
      setState(() => _state = AppState.DATA_NOT_FETCHED);
    }
  }

  Widget _contentFetchingData() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
            padding: EdgeInsets.all(20),
            child: CircularProgressIndicator(
              strokeWidth: 10,
            )),
        Text('Fetching data...')
      ],
    );
  }

  Widget _contentDataReady() {
    return ListView.builder(
        itemCount: _healthDataList.length,
        itemBuilder: (_, index) {
          HealthDataPoint p = _healthDataList[index];
          return ListTile(
            title: Text("${p.typeString}: ${p.value}"),
            trailing: Text('${p.unitString}'),
            subtitle: Text('${p.dateFrom} - ${p.dateTo}'),
          );
        });
  }

  Widget _contentNoData() {
    return Text('No Data to show');
  }

  Widget _contentNotFetched() {
    return Text('Press the download button to fetch data');
  }

  Widget _authorizationNotGranted() {
    return Text('''Authorization not given.
        For Android please check your OAUTH2 client ID is correct in Google Developer Console.
         For iOS check your permissions in Apple Health.''');
  }

  Widget _content() {
    if (_state == AppState.DATA_READY)
      return _contentDataReady();
    else if (_state == AppState.NO_DATA)
      return _contentNoData();
    else if (_state == AppState.FETCHING_DATA)
      return _contentFetchingData();
    else if (_state == AppState.AUTH_NOT_GRANTED)
      return _authorizationNotGranted();

    return _contentNotFetched();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          appBar: AppBar(
            title: const Text('Plugin example app'),
            actions: <Widget>[
              IconButton(
                icon: Icon(Icons.file_download),
                onPressed: () {
                  fetchData();
                },
              )
            ],
          ),
          body: Center(
            child: _content(),
          )
    );

  }
}
4

2 回答 2

3

第 1 步使用health: 3.0.4

第 2 步正确设置 OAuth2 客户端 ID,下载新的 google-service.json

第 3 步从 Android 10。您必须添加ACTIVITY_RECOGNITION以获得 STEP Count 权限AndroidManifest.xml

<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

第 4 步然后使用permission_handler请求权限。

if (Platform.isAndroid) {
  final permissionStatus = Permission.activityRecognition.request();
  if (await permissionStatus.isDenied ||
      await permissionStatus.isPermanentlyDenied) {
    showToast(
        'activityRecognition permission required to fetch your steps count');
    return;
  }
}
于 2021-06-18T11:02:49.730 回答
0

终于解决了这个问题!

所以问题不在于我使用的版本 3.4.0 但仍然解决了问题

未授予授权。并且卡在加载界面

卡在授权请求屏幕

当您创建 OAuth 2.0 同意屏幕时,请尝试将至少 2 个电子邮件地址添加到 TEST USER 部分,并确保从该电子邮件登录。

在测试用户中添加 2 个电子邮件地址

之后,请确保从 Google 验证您的应用程序,它会一直有效,直到您发布应用程序后测试您的应用程序,它才会有效

从 Google 验证您的应用程序

最后结果

于 2022-01-03T07:09:06.823 回答