Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Health 10.2.0] Health().requestAuthorization(...) always returning false for Android / Health Connect #959

Open
CarlosCabarcos opened this issue May 16, 2024 · 20 comments
Labels
bugfix a bug fix

Comments

@CarlosCabarcos
Copy link

CarlosCabarcos commented May 16, 2024

Remember to specify the plugin name in the title!

Device / Emulator and OS

Please complete the following information for each phone and/or emulator you're experiencing this bug on:

  • Device: [Android Emulator / Xiaomi MI 11 Lite 5G]
  • OS: [Android 14]

NB: Bugs pertaining to old devices/OS versions will likely not be fixed.

Describe the bug

After doing the setup as indicated in readme at https://pub.dev/packages/health, I have added a new view to my App including the code from the demo. It seems to run just fine, however, when I try to "Authenticate" I am getting: "Access Denied (to Health Connect)!"

    if (!hasPermissions) {
      // requesting access to the data types before reading them
      try {
        authorized = await Health().requestAuthorization(types, permissions: permissions);
      } catch (error) {
        debugPrint("Exception in authorize: $error");
      }
    }

The "Health().requestAuthorization" call is always coming back false. I've tried with many types at once or just a single one and with READ or READ/WRITE permissions. The result is always the same: false.

The demo error pre-configured messages suggest I should check the permissions and services added to my manifest file, which I have done many times, but cant' see anything wrong.

To Reproduce

Add plugin to project, add demo scene to a new view, try to Authenticate.

Expected behavior

Should return "true".

Actual behavior

Returns "false".

This is my manifest. I added every single permission just in case.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.testApp">
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.USE_EXACT_ALARM" />
    <!-- For health -->
    <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.READ_ACTIVE_CALORIES_BURNED" />
    <uses-permission android:name="android.permission.WRITE_ACTIVE_CALORIES_BURNED" />
    <uses-permission android:name="android.permission.READ_BASAL_BODY_TEMPERATURE" />
    <uses-permission android:name="android.permission.WRITE_BASAL_BODY_TEMPERATURE" />
    <uses-permission android:name="android.permission.READ_BASAL_METABOLIC_RATE" />
    <uses-permission android:name="android.permission.WRITE_BASAL_METABOLIC_RATE" />
    <uses-permission android:name="android.permission.READ_BLOOD_GLUCOSE" />
    <uses-permission android:name="android.permission.WRITE_BLOOD_GLUCOSE" />
    <uses-permission android:name="android.permission.READ_BLOOD_PRESSURE" />
    <uses-permission android:name="android.permission.WRITE_BLOOD_PRESSURE" />
    <uses-permission android:name="android.permission.READ_BODY_FAT" />
    <uses-permission android:name="android.permission.WRITE_BODY_FAT" />
    <uses-permission android:name="android.permission.READ_BODY_TEMPERATURE" />
    <uses-permission android:name="android.permission.WRITE_BODY_TEMPERATURE" />
    <uses-permission android:name="android.permission.READ_BODY_WATER_MASS" />
    <uses-permission android:name="android.permission.WRITE_BODY_WATER_MASS" />
    <uses-permission android:name="android.permission.READ_BONE_MASS" />
    <uses-permission android:name="android.permission.WRITE_BONE_MASS" />
    <uses-permission android:name="android.permission.READ_CERVICAL_MUCUS" />
    <uses-permission android:name="android.permission.WRITE_CERVICAL_MUCUS" />
    <uses-permission android:name="android.permission.READ_EXERCISE" />
    <uses-permission android:name="android.permission.WRITE_EXERCISE" />
    <uses-permission android:name="android.permission.READ_DISTANCE" />
    <uses-permission android:name="android.permission.WRITE_DISTANCE" />
    <uses-permission android:name="android.permission.READ_ELEVATION_GAINED" />
    <uses-permission android:name="android.permission.WRITE_ELEVATION_GAINED" />
    <uses-permission android:name="android.permission.READ_FLOORS_CLIMBED" />
    <uses-permission android:name="android.permission.WRITE_FLOORS_CLIMBED" />
    <uses-permission android:name="android.permission.READ_HEART_RATE" />
    <uses-permission android:name="android.permission.WRITE_HEART_RATE" />
    <uses-permission android:name="android.permission.READ_HEART_RATE_VARIABILITY" />
    <uses-permission android:name="android.permission.WRITE_HEART_RATE_VARIABILITY" />
    <uses-permission android:name="android.permission.READ_HEIGHT" />
    <uses-permission android:name="android.permission.WRITE_HEIGHT" />
    <uses-permission android:name="android.permission.READ_HYDRATION" />
    <uses-permission android:name="android.permission.WRITE_HYDRATION" />
    <uses-permission android:name="android.permission.READ_INTERMENSTRUAL_BLEEDING" />
    <uses-permission android:name="android.permission.WRITE_INTERMENSTRUAL_BLEEDING" />
    <uses-permission android:name="android.permission.READ_LEAN_BODY_MASS" />
    <uses-permission android:name="android.permission.WRITE_LEAN_BODY_MASS" />
    <uses-permission android:name="android.permission.READ_MENSTRUATION" />
    <uses-permission android:name="android.permission.WRITE_MENSTRUATION" />
    <uses-permission android:name="android.permission.READ_NUTRITION" />
    <uses-permission android:name="android.permission.WRITE_NUTRITION" />
    <uses-permission android:name="android.permission.READ_OVULATION_TEST" />
    <uses-permission android:name="android.permission.WRITE_OVULATION_TEST" />
    <uses-permission android:name="android.permission.READ_OXYGEN_SATURATION" />
    <uses-permission android:name="android.permission.WRITE_OXYGEN_SATURATION" />
    <uses-permission android:name="android.permission.READ_POWER" />
    <uses-permission android:name="android.permission.WRITE_POWER" />
    <uses-permission android:name="android.permission.READ_RESPIRATORY_RATE" />
    <uses-permission android:name="android.permission.WRITE_RESPIRATORY_RATE" />
    <uses-permission android:name="android.permission.READ_RESTING_HEART_RATE" />
    <uses-permission android:name="android.permission.WRITE_RESTING_HEART_RATE" />
    <uses-permission android:name="android.permission.READ_SEXUAL_ACTIVITY" />
    <uses-permission android:name="android.permission.WRITE_SEXUAL_ACTIVITY" />
    <uses-permission android:name="android.permission.READ_SLEEP" />
    <uses-permission android:name="android.permission.WRITE_SLEEP" />
    <uses-permission android:name="android.permission.READ_SPEED" />
    <uses-permission android:name="android.permission.WRITE_SPEED" />
    <uses-permission android:name="android.permission.READ_STEPS" />
    <uses-permission android:name="android.permission.WRITE_STEPS" />
    <uses-permission android:name="android.permission.READ_TOTAL_CALORIES_BURNED" />
    <uses-permission android:name="android.permission.WRITE_TOTAL_CALORIES_BURNED" />
    <uses-permission android:name="android.permission.READ_VO2_MAX" />
    <uses-permission android:name="android.permission.WRITE_VO2_MAX" />
    <uses-permission android:name="android.permission.READ_WEIGHT" />
    <uses-permission android:name="android.permission.WRITE_WEIGHT" />
    <uses-permission android:name="android.permission.READ_WHEELCHAIR_PUSHES" />
    <uses-permission android:name="android.permission.WRITE_WHEELCHAIR_PUSHES" />

    <!-- Check if Health Connect is installed -->
    <queries>
        <package android:name="com.google.android.apps.healthdata" />

        <intent>
            <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
        </intent>
        <intent>
            <action android:name="android.intent.action.SENDTO" />
            <data android:scheme="smsto" />
        </intent>
    </queries>
    <application
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher"
        android:label="Test"
        tools:replace="android:label">
        <!-- flutter_background_geolocation licence -->
        <meta-data
            android:name="com.transistorsoft.locationmanager.license"
            android:value="..." />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="..." />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/ic_stat_ic_notification" />

        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:exported="true"
            android:hardwareAccelerated="true"
            android:launchMode="singleTop"
            android:screenOrientation="portrait"
            android:theme="@style/LaunchTheme"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
            </intent-filter>
            <!-- Intention to show Permissions screen for Health Connect API -->
            <!--<intent-filter>
                <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
            </intent-filter>-->
        </activity>
        <activity
            android:name="com.aboutyou.dart_packages.sign_in_with_apple.SignInWithAppleCallback"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="signinwithapple" />
                <data android:path="callback" />
            </intent-filter>
        </activity>

        <activity-alias
            android:name="ViewPermissionUsageActivity"
            android:exported="true"
            android:permission="android.permission.START_VIEW_PERMISSION_USAGE"
            android:targetActivity=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
                <category android:name="android.intent.category.HEALTH_PERMISSIONS" />
            </intent-filter>
        </activity-alias>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

Screenshots

This is the result of pressing the "Authenticate" button:

image

Flutter doctor

Doctor summary (to see all details, run flutter doctor -v):
[!] Flutter (Channel stable, 3.19.2, on Microsoft Windows [Versi¢n 10.0.19045.4412], locale es-ES)
! The flutter binary is not on your path. Consider adding C:\Users\myuser\fvm\versions\3.19.2\bin to your path.
! Warning: dart on your path resolves to C:\tools\dart-sdk\bin\dart.exe, which is not inside your current Flutter SDK checkout at C:\Users\louen\fvm\versions\3.19.2. Consider adding C:\Users\myuser\fvm\versions\3.19.2\bin to th
e front of your path.
[√] Windows Version (Installed version of Windows is version 10 or higher)
[√] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[√] Chrome - develop for the web
[√] Android Studio (version 2021.3)
[√] Connected device (4 available)
[√] Network resources

Additional information

Add any other info about the problem here.

@CarlosCabarcos CarlosCabarcos added the bugfix a bug fix label May 16, 2024
@larrytamnjong
Copy link

I have a similar issue. I have one screen that checks for permission. If permission is not granted, I redirect the user to the permission screen. Since the permission request returns null every time the user opens the app, they need to grant permission each time.

@Milimeter
Copy link

I have the same issue. i have done everything. yet, still always false

@AdamBrejcak
Copy link

same here

@larrytamnjong
Copy link

larrytamnjong commented May 28, 2024

@AdamBrejcak @Milimeter I found out that we could avoid checking if permission is granted or not. What I have done is to always request authorization blindly if the user hasn't granted permission the plugin request the user to grant permission and if the user already granted permission the plugin skips that step.

It works both on Android and iOS. Instead of checking if user has permission simply always just request for the authorization

@CarlosCabarcos
Copy link
Author

@AdamBrejcak @Milimeter I found out that we could avoid checking if permission is granted or not. What I have done is to always request authorization blindly if the user hasn't granted permission the plugin request the user to grant permission and if the user already granted permission the plugin skips that step.

It works both on Android and iOS. Instead of checking if user has permission simply always just request for the authorization

@larrytamnjong I think we're talking about different issues. In my case, I'm not troubled by the permissions for now (might be an issue later on) the problem right now is that the Health().requestAuthorization(types, permissions: permissions) call always returns false.

If I missunderstood your reply, would you mind adding a code snippet to see how you got it to work a bit more in detail?

Thank you very much.

@larrytamnjong
Copy link

larrytamnjong commented May 28, 2024

image
@CarlosCabarcos I hope this helps you if you need further help you can send me an email and I will look at your code detaily

@CarlosCabarcos
Copy link
Author

Thank you for your reply @larrytamnjong unfortunately, it seems I understood correctly, haha. It's just that my Health().requestAuthorization(types, permissions: permissions); does not seem to ever return anything except false.

I just discovered a few days ago that there is a registration process for Health Connect: https://docs.google.com/forms/d/1LFjbq1MOCZySpP5eIVkoyzXTanpcGTYQH26lKcrQUJo/viewform?edit_requested=true&pli=1 (I thought it would be indicated somewhere in the plugin's instructions. Even if it's not strictly about the plugin, if the plugin is meant to connect to Health Connect, I think it's very relevant information...) I just came across this while trying to Google for solutions for the problem I'm having.

I'm just hoping that the reason why it doesn't work is that my app has not yet been approved... Although it seems rather strange that they wouldn't allow it to work even for development/testing purposes...

@larrytamnjong
Copy link

Thank you for your reply @larrytamnjong unfortunately, it seems I understood correctly, haha. It's just that my Health().requestAuthorization(types, permissions: permissions); does not seem to ever return anything except false.

I just discovered a few days ago that there is a registration process for Health Connect: https://docs.google.com/forms/d/1LFjbq1MOCZySpP5eIVkoyzXTanpcGTYQH26lKcrQUJo/viewform?edit_requested=true&pli=1 (I thought it would be indicated somewhere in the plugin's instructions. Even if it's not strictly about the plugin, if the plugin is meant to connect to Health Connect, I think it's very relevant information...) I just came across this while trying to Google for solutions for the problem I'm having.

I'm just hoping that the reason why it doesn't work is that my app has not yet been approved... Although it seems rather strange that they wouldn't allow it to work even for development/testing purposes...

Its suppose to work in development.. My app works in development then I tried to release but playstore rejected the app I had to remove the permission on the manifest files then re-upload the app without the permissions once its approved then I will be able to apply for the approval then re upload an update with the permissions

@CarlosCabarcos
Copy link
Author

Thank you for your reply @larrytamnjong unfortunately, it seems I understood correctly, haha. It's just that my Health().requestAuthorization(types, permissions: permissions); does not seem to ever return anything except false.
I just discovered a few days ago that there is a registration process for Health Connect: https://docs.google.com/forms/d/1LFjbq1MOCZySpP5eIVkoyzXTanpcGTYQH26lKcrQUJo/viewform?edit_requested=true&pli=1 (I thought it would be indicated somewhere in the plugin's instructions. Even if it's not strictly about the plugin, if the plugin is meant to connect to Health Connect, I think it's very relevant information...) I just came across this while trying to Google for solutions for the problem I'm having.
I'm just hoping that the reason why it doesn't work is that my app has not yet been approved... Although it seems rather strange that they wouldn't allow it to work even for development/testing purposes...

Its suppose to work in development.. My app works in development then I tried to release but playstore rejected the app I had to remove the permission on the manifest files then re-upload the app without the permissions once its approved then I will be able to apply for the approval then re upload an update with the permissions

Just what I feared... then, I have absolutely no idea about why it's not working. The setup is pretty straightforward... so I doubt anything is missing... the requestAuthorization shouldn't return false :(

@larrytamnjong
Copy link

larrytamnjong commented May 28, 2024 via email

@CarlosCabarcos
Copy link
Author

CarlosCabarcos commented May 28, 2024

Hi again @larrytamnjong and thanks a lot for you help.

My whole manifest is attached to the opening post and the code I'm using is just the example code provided here: https://pub.dev/packages/health/example

I'm just navigating from one of my app's views, through a simple button, to a view that contains the exact code of the example.
When I press "Authenticate" in the button from the demo. It just doesn't do it.

I wasn't even trying it to customize it yet, for now, just wanted to check if it worked "out of the box", but unfortunately, it seems it didn't.

@larrytamnjong
Copy link

larrytamnjong commented May 28, 2024 via email

@CarlosCabarcos
Copy link
Author

Ohh from your image it seems your running the app on an emulator you need to run it on a real device or have you tested running it on a real device already?

On Tue, May 28, 2024, 17:04 CarlosCabarcos @.> wrote: Hi again @larrytamnjong https://github.com/larrytamnjong and thanks a lot for you help. My whole manifest is attached to the opening post and the code I'm using is just the example code provided here: https://pub.dev/packages/health/example I'm just navigating from one of my app's views, through a simple button, to a view that contains the exact code of the example. When I press "Authenticate" in the button from the demo. It just doesn't do it. I wasn't even try it to customize it yet, for now, just wanted to check if it worked "out of the box", but unfortunately, it seems it didn't. — Reply to this email directly, view it on GitHub <#959 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/A5DVXRYRKTPMEZ3EGZ4EYZTZESTHLAVCNFSM6AAAAABH2SKEFWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDCMZVGYYTIOBXHA . You are receiving this because you were mentioned.Message ID: @.>

I've tried both on an emulator and on a physical device (Xiaomi 11 Lite 5G, Android 14). Unfortunately, I'm getting exactly the same result.

@larrytamnjong
Copy link

larrytamnjong commented May 28, 2024 via email

@CarlosCabarcos
Copy link
Author

CarlosCabarcos commented May 28, 2024

On Android 14 some special steps need to be done.. if you review the documentation on pub.dev you'll find that Android 14 # This plugin uses the new registerForActivityResult when requesting permissions from Health Connect. In order for that to work, the Main app's activity should extend FlutterFragmentActivity instead of FlutterActivity. This adjustment allows casting from Activity to ComponentActivity for accessing registerForActivityResult. In your MainActivity.kt file, update the MainActivity class so that it extends FlutterFragmentActivity instead of the default FlutterActivity: ... import io.flutter.embedding.android.FlutterFragmentActivity ... class MainActivity: FlutterFragmentActivity() { ... } On Tue, May 28, 2024, 5:20 PM CarlosCabarcos @.> wrote:

Ohh from your image it seems your running the app on an emulator you need to run it on a real device or have you tested running it on a real device already? … <#m_6301888796331116641_> On Tue, May 28, 2024, 17:04 CarlosCabarcos @.
> wrote: Hi again @larrytamnjong https://github.com/larrytamnjong https://github.com/larrytamnjong https://github.com/larrytamnjong and thanks a lot for you help. My whole manifest is attached to the opening post and the code I'm using is just the example code provided here: https://pub.dev/packages/health/example https://pub.dev/packages/health/example I'm just navigating from one of my app's views, through a simple button, to a view that contains the exact code of the example. When I press "Authenticate" in the button from the demo. It just doesn't do it. I wasn't even try it to customize it yet, for now, just wanted to check if it worked "out of the box", but unfortunately, it seems it didn't. — Reply to this email directly, view it on GitHub <#959 (comment) <#959 (comment)>>, or unsubscribe https://github.com/notifications/unsubscribe-auth/A5DVXRYRKTPMEZ3EGZ4EYZTZESTHLAVCNFSM6AAAAABH2SKEFWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDCMZVGYYTIOBXHA https://github.com/notifications/unsubscribe-auth/A5DVXRYRKTPMEZ3EGZ4EYZTZESTHLAVCNFSM6AAAAABH2SKEFWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDCMZVGYYTIOBXHA . You are receiving this because you were mentioned.Message ID: @.
> I've tried both on an emulator and on a physical device (Xiaomi 11 Lite 5G, Android 14). Unfortunately, I'm getting exactly the same result. — Reply to this email directly, view it on GitHub <#959 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/A5DVXRYMCOLV4XLLBDZ3BYLZESVDNAVCNFSM6AAAAABH2SKEFWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDCMZVGY2TINJSHA . You are receiving this because you were mentioned.Message ID: @.
**>

Hi again @larrytamnjong. Yeah, I had done that too. As far as I know, I followed every step mentioned in the instructions.

My MainActivity looks like this:

package com.MyApp

import android.os.Bundle
import io.flutter.embedding.android.FlutterFragmentActivity

class MainActivity: FlutterFragmentActivity() {
}

@AdamBrejcak
Copy link

Guys for me, it didn't work until i get reply from google about form you mentioned earlierer, i had to follow their instructions (they sent me an email), and comply with everything they asked for, only after that they said that it should work i was able to do -> await Health().requestAuthorization(types, permissions: permissions); which opened popup from Google Health Connect

@CarlosCabarcos
Copy link
Author

CarlosCabarcos commented May 29, 2024

Guys for me, it didn't work until i get reply from google about form you mentioned earlierer, i had to follow their instructions (they sent me an email), and comply with everything they asked for, only after that they said that it should work i was able to do -> await Health().requestAuthorization(types, permissions: permissions); which opened popup from Google Health Connect

Hi @AdamBrejcak, thanks for the update.

Ok, so according to what @larrytamnjong said and what you're saying now, it seems for some unknown reason it's not working the same way for everyone. That's so weird... however, I am hoping it's good news for me and it will start working as soon as Google accepts my request... If I manage to get it to work or I get the reply from Google and later it works, I'll update this post to let everyone know.

@AdamBrejcak
Copy link

AdamBrejcak commented May 29, 2024

@CarlosCabarcos sure hopefully it will work for you, if you any question or need help feel free to reach out to me :)

@Milimeter
Copy link

Hi. I was able to get mine to return true but the health data just keeps up coming empty:
` final HealthFactory health =
HealthFactory(useHealthConnectIfAvailable: true);

// Define the types of health data to fetch.
List<HealthDataType> types = [
  HealthDataType.STEPS,
  HealthDataType.BODY_TEMPERATURE,

  HealthDataType.HEART_RATE,
  // HealthDataType.WALKING_HEART_RATE,
  // Add other data types as needed.
];

final permissions = [
  HealthDataAccess.READ_WRITE,
  HealthDataAccess.READ_WRITE,
  HealthDataAccess.READ_WRITE,
];

// Set the date range for the data.
DateTime startDate = DateTime.now().subtract(const Duration(days: 30));
DateTime endDate = DateTime.now();

// Request access to the health data.
bool accessGranted =
    await health.requestAuthorization(types, permissions: permissions);
log("isAccesGranted: $accessGranted");

if (accessGranted) {
  try {
    // Fetch health data.
    List<HealthDataPoint> healthData =
        await health.getHealthDataFromTypes(startDate, endDate, types);
    log("healthData: $healthData");
    cToast(title: "data", message: healthData.toString());
    // Filter out duplicates (based on the underlying platform's behavior).
    healthDataList.value = HealthFactory.removeDuplicates(healthData);
    log("healthDataList: ${healthDataList.value}");
  } catch (exception) {
    log("Failed to fetch health data: $exception");
  }
} else {
  AppSettings.openAppSettings();
}`

What can i do to sort this out

@AdamBrejcak
Copy link

AdamBrejcak commented Jun 4, 2024

okay so if your await Health().requestAuthorization(types, permissions: permissions); return true, and you have Google Health Connect installed (for me whole process works fine on emulator), i would suggest to simplify things for testing if everything is okay, try following:

  1. go install google fit after installation, open it, fill everything it asks for, and then you will see circle graph and under neat there is tile which will say if you want to connect it to Google Health Connect, do this, this is important!

  2. go to code, use permissions and types like this (just for now while we will test it)

  final types = [HealthDataType.STEPS];
  final permissions = [HealthDataAccess.READ];

and main logic for my code is like this

    await Permission.activityRecognition.request();

    // configure the health plugin before use.
    await Health().configure(useHealthConnectIfAvailable: true);
    await Health().requestAuthorization(types, permissions: permissions);

    try {
      int? steps;

      final DateTime now = DateTime.now();
      // get the number of steps for today
      final midnightNextDay = DateTime(now.year, now.month, now.day + 1);
      final midnightPreviousDay = DateTime(now.year, now.month, now.day + 1);

      steps = await Health()
          .getTotalStepsInInterval(midnightPreviousDay, midnightNextDay);

      return steps ?? 0;
    } catch (err) {
    }
  1. go to Google Fit and add there walk activity with some steps, but set time within the window which you are using in your code!, this is crucial since Health package might return you empty data because you didnt have any health app which contained any data you asked for

of course i got everything in AndroidManifest.xml as describe in package documentation, if you got still issue its good idea to check Google Health Connect and maybe share a screen if your app and google fit is there as allowed apps

the code above works for me just fine, hope it will help you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bugfix a bug fix
Projects
None yet
Development

No branches or pull requests

4 participants