如何接收华为健康App的数据?

How to receive data from Huawei Health App?

我已经获得了 Health Kit 授权,但是每当我 运行 登录方法时,我总是收到错误代码 8002,这没有记录,当我 运行 授权或每当我尝试阅读时任何带有健康工具包的数据,例如心率,我不断得到结果代码 4,这意味着与健康应用程序的通信被中断。

我该如何解决这个问题。

我正在提供代码 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


编辑: 有关实时心率数据采集的其他详细信息。 每当我 运行 方法 startReadingHeartRate 我在 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

我将添加包含失败方法的 .java class。

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());
                    }
                }
            }
        });
    }
}

在您的以下代码中,您似乎没有为 context 赋值。结果出现错误4:

因此您可以尝试将代码更改为以下内容:

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
        });
    }

我试过你的代码,得到同样的错误:4,这意味着 mContext 是空的。

因此在下面的代码中,mContext 为空:

HiHealthAuth.requestAuthorization(mContext, userAllowTypesToWrite, userAllowTypesToRead,

所以使授权不是静态的,并将 mContext 更改为此,它有效。

修改后的代码:

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

您可以将旧的 HiHealth Kit implementation 'com.huawei.hihealth:hihealthkit:{version}'this archived docs 一起使用。

根据 Result Codes of HiHealth Kit:

errorcode 4 表示 ERR_API_EXECEPTION 4 API 调用错误。例如,某个应用注册了多次,但一直没有注销。

目前HUAWEI HiHealth和Health Kit更名为Health Kit。

HiHealth数据API权限申请通道即将关闭。有权访问 HiHealth 的应用程序仍然可以使用这些权限。如果您的应用接入了HiHealth,建议申请接入Health Kit,提升用户体验。

您可以关注 Health Kit development guide 其中 implementation 'com.huawei.hms:health:{version}'

代码片段按原样运行,未生成 8002 错误。可以重现请求错误代码 4。由于 API 已弃用,因此担心那里返回的信息并不重要。该错误码表示您的应用与华为运动健康应用之间的通信中断。

由于您在登录时请求了范围内的权限,如您的代码所示,因此只要在AGC中授予读取此类数据的权限即可获取数据。

请按照此 link 为您的应用设置数据权限。您请求的数据通常会自动授予,但您需要在AGC中检查它们以获得权限。

请注释掉“授权”方法,运行 您的应用,如果您获得了所需的数据,请告诉我们。