Juancarlord
Juancarlord

Reputation: 116

How to receive data from Huawei Health App?

I already got Health Kit Authorization, but whenever i run the sign in method i keep getting error code 8002 which is not documented, and when i run authorizations or whenever i try to read any data with health kit for example heart rate i keep getting result Code 4 which means the communication with Health App was interrupted.

How can i solve this.

I'm providing code and Logcat

package com.example.catrep;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

import com.huawei.hihealth.error.HiHealthError;
import com.huawei.hihealthkit.auth.HiHealthAuth;
import com.huawei.hihealthkit.auth.HiHealthOpenPermissionType;
import com.huawei.hihealthkit.auth.IAuthorizationListener;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.common.ApiException;
import com.huawei.hms.support.api.entity.auth.Scope;
import com.huawei.hms.support.hwid.HuaweiIdAuthAPIManager;
import com.huawei.hms.support.hwid.HuaweiIdAuthManager;
import com.huawei.hms.support.hwid.request.HuaweiIdAuthParams;
import com.huawei.hms.support.hwid.request.HuaweiIdAuthParamsHelper;
import com.huawei.hms.support.hwid.result.AuthHuaweiId;
import com.huawei.hms.support.hwid.result.HuaweiIdAuthResult;
import com.huawei.hms.support.hwid.service.HuaweiIdAuthService;

import java.util.ArrayList;
import java.util.List;

public class Permissions extends AppCompatActivity {
    private static final int REQUEST_SIGN_IN_LOGIN = 1002;
    private static final String TAG = "HihealthKitMainActivity";
    private static Context mContext;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        handleSignInResult(requestCode, data);


    }
    private void handleSignInResult(int requestCode, Intent data) {
        // Handle only the authorized responses.
        if (requestCode != REQUEST_SIGN_IN_LOGIN) {
            return;
        }

        // Obtain the authorization response from the intent.
        HuaweiIdAuthResult result = HuaweiIdAuthAPIManager.HuaweiIdAuthAPIService.parseHuaweiIdFromIntent(data);
        Log.d(TAG, "handleSignInResult status = " + result.getStatus() + ", result = " + result.isSuccess());
        if (result.isSuccess()) {
            Log.d(TAG, "sign in is success");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permissions);

        authorization();
        signIn();

    }
    private void signIn(){
        Log.i(TAG, "begin sign in");
        List<Scope> scopeList = new ArrayList<>();

        scopeList.add(new Scope("https://www.huawei.com/healthkit/extend/realtimeheart.read"));
        scopeList.add(new Scope("https://www.huawei.com/healthkit/heartrate.read"));
        scopeList.add(new Scope("https://www.huawei.com/healthkit/oxygensaturation.read"));

        HuaweiIdAuthParamsHelper authParamsHelper = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM);
        HuaweiIdAuthParams authParams = authParamsHelper.setIdToken()
                .setAccessToken()
                .setScopeList(scopeList)
                .createParams();
        final HuaweiIdAuthService authService = HuaweiIdAuthManager.getService(this.getApplicationContext(), authParams);
        Task<AuthHuaweiId> authHuaweiIdTask = authService.silentSignIn();

        authHuaweiIdTask.addOnSuccessListener(new OnSuccessListener<AuthHuaweiId>() {
            @Override
            public void onSuccess(AuthHuaweiId authHuaweiId) {
                Log.i(TAG, "silentSignIn success");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                if (e instanceof ApiException){
                    ApiException apiException = (ApiException) e;
                    Log.i(TAG, "sign failed status:" + apiException.getStatusCode());
                    Log.i(TAG, "begin sign in by intent");

                    // Call the sign-in API using the getSignInIntent() method.
                    Intent signInIntent = authService.getSignInIntent();

                    // Display the authorization screen by using the startActivityForResult() method of the activity.
                    // You can change HihealthKitMainActivity to the actual activity.
                    Permissions.this.startActivityForResult(signInIntent, REQUEST_SIGN_IN_LOGIN);
                }
            }
        });
    }
    public static void authorization() {
        int[] userAllowTypesToRead =
                new int[]{
                        HiHealthOpenPermissionType.HEALTH_OPEN_PERMISSION_TYPE_READ_REALTIME_HEARTRATE,
                        HiHealthOpenPermissionType.HEALTH_OPEN_PERMISSION_TYPE_READ_DATA_LAST_OXYGEN_SATURATION
                        ,};
        int[] userAllowTypesToWrite =
                new int[]{};
        HiHealthAuth.requestAuthorization(mContext, userAllowTypesToWrite, userAllowTypesToRead,
                new IAuthorizationListener() {
                    @Override
                    public void onResult(int resultCode, Object object) {
                        Log.i(TAG, "requestAuthorization onResult:" + resultCode);
                        if (resultCode == HiHealthError.SUCCESS) {
                            Log.i(TAG, "requestAuthorization success resultContent:" + object);
                        }
                    }
                });
    }


}

Logcat

2021-11-07 22:52:22.380 9173-9173/com.example.catrep I/HmsHealth_kit HealthKitAuthHub: checkOrAuthorizeHealth get result success
2021-11-07 22:52:22.381 9173-9173/com.example.catrep I/HmsHealth_kit HealthKitAuthHub: Health authorize result is success
2021-11-07 22:52:22.381 9173-9173/com.example.catrep I/HmsHealth_kit HealthKitAuthHub: auth success
2021-11-07 22:52:22.385 9173-9173/com.example.catrep I/HmsHealth_kit HealthKitAuthHub: to finish HealthKitAuthHubActivity
2021-11-07 22:52:22.428 9173-9173/com.example.catrep I/HealthKitAuthActivity: authorization success
2021-11-07 22:52:22.430 9173-9173/com.example.catrep V/Activity: mLastPackageName-com.example.catrep.login
2021-11-07 22:52:22.482 9173-9173/com.example.catrep V/Activity: onStop mLastPackageResume = false com.huawei.hms.hihealth.activity.HealthKitAuthHubActivity@89fcce3
2021-11-07 22:52:38.026 9173-9173/com.example.catrep W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@d00beef
2021-11-07 22:52:38.068 9173-9173/com.example.catrep I/HihealthKitMainActivity: begin sign in
2021-11-07 22:52:38.075 9173-9173/com.example.catrep I/HMSSDK_HMSBIInitializer: Builder->biInitFlag :false
2021-11-07 22:52:38.076 9173-9173/com.example.catrep I/HMSSDK_[HUAWEIIDSDK]HuaweiIdAuthService: silentSignIn
2021-11-07 22:52:38.077 9173-9173/com.example.catrep E/HMSSDK_[HUAWEIIDSDK]HuaweiIdAuthService: JSONException
2021-11-07 22:52:38.084 9173-9173/com.example.catrep I/HiHealthAuth: HiHealthAuth: requestAuthorization
2021-11-07 22:52:38.084 9173-9173/com.example.catrep I/HihealthKitMainActivity: requestAuthorization onResult:4
2021-11-07 22:52:38.086 9173-9319/com.example.catrep I/HMSSDK_HuaweiApi: inner hms is empty,hms pkg name is com.huawei.hwid
2021-11-07 22:52:38.088 9173-9319/com.example.catrep I/HMSSDK_HuaweiApiManager: sendRequest
2021-11-07 22:52:38.090 9173-9173/com.example.catrep V/Activity: mLastPackageName-com.example.catrep.Permissions
2021-11-07 22:52:38.090 9173-9319/com.example.catrep I/HMSSDK_BaseHmsClient: ====== HMSSDK version: 50300301 ======
2021-11-07 22:52:38.092 9173-9319/com.example.catrep I/HMSSDK_BaseHmsClient: Enter connect, Connection Status: 1
2021-11-07 22:52:38.094 9173-9319/com.example.catrep I/HMSSDK_BaseHmsClient: connect minVersion:30000000 packageName:com.huawei.hwid
2021-11-07 22:52:38.095 9173-9319/com.example.catrep I/HMSSDK_Util: available exist: true
2021-11-07 22:52:38.100 9173-9319/com.example.catrep I/HMSSDK_HMSPackageManager: current versionCode:60100314, minimum version requirements: 30000000
2021-11-07 22:52:38.103 9173-9319/com.example.catrep I/HMSSDK_HMSPackageManager: MinApkVersion is disabled.
2021-11-07 22:52:38.104 9173-9319/com.example.catrep I/HMSSDK_BaseHmsClient: check available result: 0
2021-11-07 22:52:38.105 9173-9319/com.example.catrep I/HMSSDK_BaseHmsClient: enter bindCoreService, packageName is com.huawei.hwid, serviceAction is com.huawei.hms.core.aidlservice
2021-11-07 22:52:38.179 9173-9173/com.example.catrep I/HMSSDK_BinderAdapter: Enter onServiceConnected.
2021-11-07 22:52:38.181 9173-9173/com.example.catrep I/HMSSDK_BaseHmsClient: Enter onServiceConnected.
2021-11-07 22:52:38.182 9173-9319/com.example.catrep I/HMSSDK_HmsClient: post msg api_name:hwid.silentSignIn, app_id:104759719|, pkg_name:com.example.catrep, sdk_version:50300301, session_id:*, transaction_id:104759719SignIn20211107225238080363043, kitSdkVersion:50300300, apiLevel:1
2021-11-07 22:52:38.184 9173-9319/com.example.catrep I/HMSSDK_BaseAdapter: in baseRequest + uri is :hwid.silentSignIn, transactionId is : 104759719SignIn20211107225238080363043
2021-11-07 22:52:38.186 9173-9319/com.example.catrep I/HMSSDK_PendingResultImpl: init uri:hwid.silentSignIn
2021-11-07 22:52:38.186 9173-9319/com.example.catrep I/HMSSDK_PendingResultImpl: setResultCallback
2021-11-07 22:52:38.611 9173-9173/com.example.catrep V/Activity: onStop mLastPackageResume = false com.example.catrep.login@e8c5906
2021-11-07 22:52:39.796 9173-9212/com.example.catrep I/HMSSDK_PendingResultImpl: setResult:0
2021-11-07 22:52:39.800 9173-9173/com.example.catrep I/HMSSDK_BaseAdapter: baseCallBack.onComplete
2021-11-07 22:52:39.803 9173-9173/com.example.catrep I/HMSSDK_HmsClient: receive msg status_code:0, error_code0, api_name:hwidjos.silentSignIn, app_id:104759719|, pkg_name:com.example.catrep, session_id:*, transaction_id:104759719SignIn20211107225238080363043, resolution:null
2021-11-07 22:52:39.809 9173-9173/com.example.catrep I/HMSSDK_[HUAWEIIDSDK]SignInTaskApiCall: ResponseErrorCode.status:0
2021-11-07 22:52:39.816 9173-9173/com.example.catrep I/HMSSDK_[HUAWEIIDSDK]SignInTaskApiCall: signIn success
2021-11-07 22:52:39.823 9173-9173/com.example.catrep I/HMSSDK_HMSBIInitializer: Builder->biInitFlag :false
2021-11-07 22:52:39.825 9173-9173/com.example.catrep I/HMSSDK_SignInNoticeClientImpl: request Jos Notice.
2021-11-07 22:52:39.838 9173-9173/com.example.catrep I/HMSSDK_AGCUtils: In getMetaDataCpId, Failed to read meta data for the CpId.
2021-11-07 22:52:39.841 9173-9173/com.example.catrep E/HMSSDK_AGCUtils: Get client/cp_id failed: java.io.FileNotFoundException: agconnect-services.json
2021-11-07 22:52:39.844 9173-9173/com.example.catrep E/HMSSDK_AGCUtils: The client/cp_id is null.
2021-11-07 22:52:39.848 9173-9173/com.example.catrep I/HMSSDK_[HUAWEIIDSDK]HuaweiIdAuthMemCache: saveDefaultHuaweiIdSignInAccount start.
2021-11-07 22:52:39.849 9173-9319/com.example.catrep I/HMSSDK_HuaweiApi: inner hms is empty,hms pkg name is com.huawei.hwid
2021-11-07 22:52:39.850 9173-9173/com.example.catrep I/HMSSDK_[HUAWEIIDSDK]HuaweiIdAuthMemCache: saveDefaultHuaweiIdSignInAccount start.
2021-11-07 22:52:39.851 9173-9319/com.example.catrep I/HMSSDK_HuaweiApiManager: sendRequest
2021-11-07 22:52:39.853 9173-9319/com.example.catrep I/HMSSDK_BaseHmsClient: ====== HMSSDK version: 50300301 ======
2021-11-07 22:52:39.854 9173-9173/com.example.catrep I/HMSSDK_[HUAWEIIDSDK]SignInTaskApiCall: report: api=hwid.silentSignInversion=50300301
2021-11-07 22:52:39.854 9173-9173/com.example.catrep I/HihealthKitMainActivity: silentSignIn success
2021-11-07 22:52:39.857 9173-9319/com.example.catrep I/HMSSDK_BaseHmsClient: Enter connect, Connection Status: 1
2021-11-07 22:52:39.858 9173-9319/com.example.catrep I/HMSSDK_BaseHmsClient: connect minVersion:30000000 packageName:com.huawei.hwid
2021-11-07 22:52:39.858 9173-9319/com.example.catrep I/HMSSDK_Util: available exist: true
2021-11-07 22:52:39.864 9173-9319/com.example.catrep I/HMSSDK_HMSPackageManager: current versionCode:60100314, minimum version requirements: 30000000
2021-11-07 22:52:39.868 9173-9319/com.example.catrep I/HMSSDK_HMSPackageManager: MinApkVersion is disabled.
2021-11-07 22:52:39.869 9173-9319/com.example.catrep I/HMSSDK_BaseHmsClient: check available result: 0
2021-11-07 22:52:39.870 9173-9319/com.example.catrep I/HMSSDK_BaseHmsClient: enter bindCoreService, packageName is com.huawei.hwid, serviceAction is com.huawei.hms.core.aidlservice
2021-11-07 22:52:39.878 9173-9173/com.example.catrep I/HMSSDK_BinderAdapter: Enter onServiceConnected.
2021-11-07 22:52:39.879 9173-9173/com.example.catrep I/HMSSDK_BaseHmsClient: Enter onServiceConnected.
2021-11-07 22:52:39.880 9173-9319/com.example.catrep I/HMSSDK_HmsClient: post msg api_name:core.getNoticeIntent, app_id:104759719|, pkg_name:com.example.catrep, sdk_version:50300301, session_id:*, transaction_id:104759719Intent20211107225239829513541, kitSdkVersion:0, apiLevel:1
2021-11-07 22:52:39.881 9173-9319/com.example.catrep I/HMSSDK_BaseAdapter: in baseRequest + uri is :core.getNoticeIntent, transactionId is : 104759719Intent20211107225239829513541
2021-11-07 22:52:39.883 9173-9319/com.example.catrep I/HMSSDK_PendingResultImpl: init uri:core.getNoticeIntent
2021-11-07 22:52:39.884 9173-9319/com.example.catrep I/HMSSDK_PendingResultImpl: setResultCallback
2021-11-07 22:52:40.598 9173-9212/com.example.catrep I/HMSSDK_PendingResultImpl: setResult:0
2021-11-07 22:52:40.602 9173-9173/com.example.catrep I/HMSSDK_BaseAdapter: baseCallBack.onComplete
2021-11-07 22:52:40.605 9173-9173/com.example.catrep I/HMSSDK_HmsClient: receive msg status_code:0, error_code8002, api_name:core.getNoticeIntent, app_id:104759719|, pkg_name:com.example.catrep, session_id:*, transaction_id:104759719Intent20211107225239829513541, resolution:null
2021-11-07 22:52:40.608 9173-9173/com.example.catrep W/HMSSDK_NoticeTaskApiCall: Jos Notice onResult failed:8002,ErrReason:
2021-11-07 22:54:22.418 9173-9313/com.example.catrep I/HmsHealth_kit HiHealthKitClient: sync message begin to handle 1000
2021-11-07 22:54:22.438 9173-9313/com.example.catrep I/HmsHealth_kit HiHealthKitClient: begin executeServiceDisconnectedListener
2021-11-07 22:54:22.438 9173-9313/com.example.catrep I/HmsHealth_kit ControllerImpl: clearBinder
2021-11-07 22:54:22.438 9173-9313/com.example.catrep W/HmsHealth_kit HiHealthKitClient: unbind hmsService success
2021-11-07 22:56:37.386 9173-9173/com.example.catrep V/Activity: onStop mLastPackageResume = false com.example.catrep.login@e8c5906
2021-11-07 22:56:38.424 9173-9173/com.example.catrep W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@1f88ace
2021-11-07 22:56:38.508 9173-9173/com.example.catrep V/Activity: mLastPackageName-com.example.catrep.pulso
2021-11-07 22:56:39.060 9173-9173/com.example.catrep V/Activity: onStop mLastPackageResume = false com.example.catrep.Menu@b2ab33e
2021-11-07 22:56:40.372 9173-9173/com.example.catrep I/HiHealthDataStore: enter startReadingHeartRate
2021-11-07 22:56:40.372 9173-9173/com.example.catrep W/HiHealthDataStore: startReadingHeartRate context is null
2021-11-07 22:56:40.372 9173-9173/com.example.catrep I/HihealthKitMainActivity: Reading Heart Rate onResult state: 4


Edit: Additional details regarding the realtime heart rate data adquisition. Whenever i run the method startReadingHeartRate im getting the following on the logcat

V/Activity: mLastPackageName-com.example.catrep.pulso
V/Activity: onStop mLastPackageResume = false com.example.catrep.Menu@f4221c1
I/HiHealthDataStore: enter startReadingHeartRate
W/HiHealthDataStore: startReadingHeartRate context is null
I/HihealthKitMainActivity: Reading Heart Rate onResult state: 4
I/HmsHealth_kit HiHealthKitClient: sync message begin to handle 1000
I/HmsHealth_kit HiHealthKitClient: begin executeServiceDisconnectedListener
I/HmsHealth_kit ControllerImpl: clearBinder
W/HmsHealth_kit HiHealthKitClient: unbind hmsService success

I'll add the .java class that contains the method which fails.

public class RealtimeHeart {
    private static final String TAG = "HihealthKitMainActivity";
    private static Context context;
    public static void getHeartRate(){
        HiHealthDataStore.startReadingHeartRate(context, new HiRealTimeListener() {
            @Override
            public void onResult(int state) {
                Log.i(TAG, "Reading Heart Rate onResult state: "+state);
            }

            @Override
            public void onChange(int resultCode, String value) {
                Log.i(TAG, "Start reading heart rate onChange resultCode: "+ resultCode + " value: " + value);
                if(resultCode == HiHealthError.SUCCESS){
                    try{
                        JSONObject jsonObject = new JSONObject(value);
                        Log.i(TAG, "hri_info : " + jsonObject.getInt("hri_info"));
                        Log.i(TAG, "hr_info : " + jsonObject.getInt("hr_info"));
                        Log.i(TAG, "hrsqi_info : " + jsonObject.getInt("hrsqi_info"));
                        Log.i(TAG, "time_info : " + jsonObject.getLong("time_info"));
                    } catch (JSONException e) {
                        Log.e(TAG, "JSONException e " + e.getMessage());
                    }
                }
            }
        });
    }
}

Upvotes: 2

Views: 1301

Answers (2)

zhangxaochen
zhangxaochen

Reputation: 34017

In your following code, seems you have not assign a value to the context. As a result, error 4 occurs:

enter image description here

So you could try to change your code to the following:

public class RealtimeHeart {
    private static final String TAG = "HihealthKitMainActivity";

    /**
     * 
     * @param context  activity or application
     */
    public static void getHeartRate(Context context){
        HiHealthDataStore.startReadingHeartRate(context, new HiRealTimeListener() {
            // no change
        });
    }

I trid your code , get the same error : 4 , which means mContext is null.

So in the code below , mContext is null:

HiHealthAuth.requestAuthorization(mContext, userAllowTypesToWrite, userAllowTypesToRead,

So make the authorization not static , and change the mContext to this, it works.

code after changing:

 public void authorization() {
    ... // no change
    HiHealthAuth.requestAuthorization(this, userAllowTypesToWrite, userAllowTypesToRead,
            new IAuthorizationListener() {
    ... // no change                

You may use the old HiHealth Kit implementation 'com.huawei.hihealth:hihealthkit:{version}' with this archived docs.

According to the Result Codes of HiHealth Kit:

errorcode 4 means ERR_API_EXECEPTION 4 API calling error. For example, an app has been registered for multiple times but has not been unregistered.

Currently, HUAWEI HiHealth and Health Kit are now known as Health Kit.

The channel for applying for the HiHealth data API permissions will be closed. Apps with access to HiHealth can still use the permissions. If your app has access to HiHealth, It is recommended that apply for access to Health Kit for an enhanced user experience.

You could follow the Health Kit development guide which implementation 'com.huawei.hms:health:{version}'.

Upvotes: 2

Zinna
Zinna

Reputation: 2025

The code snippet works as it without 8002 error generated. Request error code 4 could be reproduced. Since the API is deprecated, it is not important to worry about the information returned there. The error code indicates the communication between your app and Huawei Health app is interrupted.

Since you have requested permission in the scope when login as your code shown, it is sufficient to get the data if permission of reading such data is granted in the AGC.

enter image description here

Please follow this link to get the data permission setup for your app. The data you requested are normally granted automatically, but you need to check them in the AGC to get permissions.

enter image description here enter image description here

Please comment out the “authorization” method, run your app and let us know if you get the data needed.

Upvotes: 1

Related Questions