title: Flutter Health Plugin "Authorization not granted" in Foreground Service Function
body: <p>I am trying to create an app about periodically fetching step data from Google Fit API and send that data to custom API. So far everything is ok and works fine while app is open. Then I wanted to make these things happen even if i kill the app.</p>
  <p>For that, i used <a href="https://pub.dev/packages/flutter_foreground_task" rel="nofollow noreferrer">Flutter Foreground Task</a> plugin and it is working fine. BUT when i try to call fetch health data function in foreground, plugin says &quot;Authorization not granted.&quot;. I really don't know why is this happening and what i have to do. I am kinda new at Flutter and it is my first time doing a project like that.</p>
  <p>Note: I did everything to setup <a href="https://pub.dev/packages/health" rel="nofollow noreferrer">Health Plugin</a>. I got SHA1 key and added it to the Google API console etc. It is working fine when i use it in app. The problem is using it on foreground service method.</p>
  <p><strong>Foregorund Service Method</strong> (where i call the fetch health data method)</p>
  <pre><code>class FirstTaskHandler implements TaskHandler {
    @override
    Future&lt;void&gt; onStart(DateTime timestamp, SendPort? sendPort) async {
      // You can use the getData function to get the data you saved.
      final customData =
          await FlutterForegroundTask.getData&lt;String&gt;(key: 'Steps');
      print('Steps: $customData');
    }
  
    @override
    Future&lt;void&gt; onEvent(DateTime timestamp, SendPort? sendPort) async {
      // Send data to the main isolate.
      GetHealthData().fetchHealthDataMethod(); //This is where i call health plugin to fetch steps data on foreground.
      sendPort?.send(timestamp);
    }
  
    @override
    Future&lt;void&gt; onDestroy(DateTime timestamp) async {
      // You can use the clearAllData function to clear all the stored data.
      await FlutterForegroundTask.clearAllData();
    }
  }
  </code></pre>
  <p><strong>healthData.dart class</strong> (the place that i implement the fetch health data function)</p>
  <pre><code>class GetHealthData extends StatefulWidget {
    const GetHealthData({Key? key}) : super(key: key);
    fetchHealthDataMethod() =&gt; createState().fetchHealthData();
  
    @override
    _GetHealthDataState createState() =&gt; _GetHealthDataState();
  }
  
  class _GetHealthDataState extends State&lt;GetHealthData&gt; {
    List&lt;HealthDataPoint&gt; _healthDataList = [];
    var nickname;
  
    @override
    void initState() {
      super.initState();
    }
  
    Future fetchHealthData() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      var datasource = prefs.getInt('datasource');
      if (prefs.getString(&quot;token&quot;) != null &amp;&amp; datasource == 1) {
        // get everything from midnight until now
        DateTime current = DateTime.now();
        DateTime dateFrom;
        DateTime dateTo;
  
        dateFrom = current.subtract(Duration(
          hours: current.hour,
          minutes: current.minute,
          seconds: current.second,
          milliseconds: current.millisecond,
        ));
        dateTo = DateTime.now();
  
        HealthFactory health = HealthFactory();
  
        // define the types to get
        List&lt;HealthDataType&gt; types = [
          HealthDataType.STEPS,
        ];
  
        // 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&lt;HealthDataPoint&gt; healthData =
                await health.getHealthDataFromTypes(dateFrom, dateTo, types);
  
            // save all the new data points
            _healthDataList.addAll(healthData);
          } catch (e) {
            print(&quot;Caught exception in getHealthDataFromTypes: $e&quot;);
          }
  
          // filter out duplicates
          _healthDataList = HealthFactory.removeDuplicates(_healthDataList);
          SharedPreferences prefs = await SharedPreferences.getInstance();
          // print the results
          _healthDataList.forEach((x) {
            print(&quot;Data point: $x&quot;);
            steps += x.value.round();
            Users.steps = steps;
            TempData.tempSteps = steps;
            prefs.setInt(('sharedSteps'), steps);
          });
          await FlutterForegroundTask.saveData(key: 'Steps', value: steps);
  
          print(&quot;Steps: $steps&quot;);
  
  
        } else {
          print(&quot;Authorization not granted&quot;);
          
        }
      }
    }
  </code></pre>
  <p><strong>AND THE ERROR</strong></p>
  <p><a href="https://i.stack.imgur.com/2wRvY.jpg" rel="nofollow noreferrer">ERROR IMAGE</a></p>
  <p>And debug console;</p>
  <pre><code>Connecting to VM Service at ws://127.0.0.1:50101/GkZr18KQmIA=/ws
  [log] 2021-11-09 12:24:16.768249    FlutterForegroundTask started
  
  I/flutter (18179): Data point: HealthDataPoint - value: 19, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 01:08:09.585, dateTo: 2021-11-09 01:09:09.585, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 10, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 01:09:09.585, dateTo: 2021-11-09 01:09:46.051, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 12, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 01:09:46.051, dateTo: 2021-11-09 01:09:53.487, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 9, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 01:15:43.795, dateTo: 2021-11-09 01:16:43.795, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 17, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 06:31:24.190, dateTo: 2021-11-09 06:32:24.190, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 24, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 06:34:48.088, dateTo: 2021-11-09 06:35:48.088, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 10, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 08:25:12.995, dateTo: 2021-11-09 08:26:12.995, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 17, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 08:53:43.038, dateTo: 2021-11-09 08:54:43.038, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 3, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 08:54:43.038, dateTo: 2021-11-09 08:54:45.471, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 15, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 08:56:23.259, dateTo: 2021-11-09 08:57:23.259, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 8, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 09:01:12.205, dateTo: 2021-11-09 09:02:12.205, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 6, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 10:02:14.110, dateTo: 2021-11-09 10:03:14.110, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 3, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 10:03:14.110, dateTo: 2021-11-09 10:03:16.431, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Data point: HealthDataPoint - value: 36, unit: HealthDataUnit.COUNT, dateFrom: 2021-11-09 11:01:47.001, dateTo: 2021-11-09 11:02:59.001, dataType: HealthDataType.STEPS,platform: PlatformType.ANDROIDsourceId: raw:com.google.step_count.cumulative:samsung:SM-A705FN:c74e7372:step_counter  Non-wakeup,sourceName: SM-A705FN,
  I/flutter (18179): Steps: 189
  74
  I/flutter (18179): Authorization not granted
  
  </code></pre>
  <p>As you can see, fetching function works fine when it is called from initState. It can show the steps data and can print to the screen but when i call the same function from foreground, it says &quot;Authorization not granted&quot;.</p>
  <p>If you need more information please ask to me. Thanks for any advice and help already.</p>