首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从华为健康应用程序接收数据?

如何从华为健康应用程序接收数据?
EN

Stack Overflow用户
提问于 2021-11-08 03:58:28
回答 2查看 371关注 0票数 2

我已经获得了Health授权,但是每当我在方法中运行登录时,我都会得到错误代码8002,这是没有文档记录的,当我运行授权时,或者每当我尝试使用健康工具包读取任何数据(例如心率)时,我都会得到结果代码4,这意味着与health App的通信中断了。

我该怎么解决这个问题。

我提供代码和日志

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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 im时,在logcat上获得以下信息

代码语言:javascript
运行
复制
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类。

代码语言:javascript
运行
复制
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());
                    }
                }
            }
        });
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-11-08 06:30:40

在下面的代码中,似乎没有为context赋值。因此,出现了错误4:

因此,您可以尝试将代码更改为:

代码语言:javascript
运行
复制
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为null。

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

代码语言:javascript
运行
复制
HiHealthAuth.requestAuthorization(mContext, userAllowTypesToWrite, userAllowTypesToRead,

因此,使授权不是静态的,并将mContext更改为此,它可以工作。

更改后的代码:

代码语言:javascript
运行
复制
 public void authorization() {
    ... // no change
    HiHealthAuth.requestAuthorization(this, userAllowTypesToWrite, userAllowTypesToRead,
            new IAuthorizationListener() {
    ... // no change                

您可以将旧的HiHealth工具包implementation 'com.huawei.hihealth:hihealthkit:{version}'这个存档的文档一起使用。

根据HiHealth工具包的结果代码

errorcode 4意味着ERR_API_EXECEPTION 4 API调用错误。例如,一个应用程序已经注册了多次,但没有被取消注册。

目前,华为HiHealth和健康工具包现在被称为健康工具包。

申请HiHealth数据API权限的通道将关闭。访问HiHealth的应用程序仍然可以使用这些权限。如果您的应用程序可以访问HiHealth,建议您申请访问Health 以获得增强的用户体验。

你可以跟着健康工具包发展指南implementation 'com.huawei.hms:health:{version}'一起走。

票数 2
EN

Stack Overflow用户

发布于 2021-11-10 02:26:21

代码片段在没有生成8002错误的情况下工作。请求错误代码4可以复制。因为API被废弃了,所以担心那里返回的信息并不重要。错误代码表示应用程序与华为健康应用程序之间的通信中断。

由于您在登录时已请求权限,如代码所示,如果在AGC中授予了读取此类数据的权限,则只需获取数据即可。

请按照此链接获得您的应用程序的数据权限设置。您请求的数据通常是自动授予的,但是您需要在AGC中检查它们才能获得权限。

请注释掉“授权”方法,运行您的应用程序,如果您得到所需的数据,请通知我们。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69878510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档