问题详情
系统提供了ArkTS 接口,但未提供对应的NDK接口,当伙伴使用C++ 代码实现业务逻辑时,部分系统能力需要依赖系统ArkTS接口。
解决措施
- 通过napi_load_module接口加载模块。
- 通过napi_get_named_property接口获取模块属性。
- 通过napi_call_function接口调用方法。
具体方法可参考以下获取设备的屏幕宽高示例代码。
#include "CallSystemModule.h"
#include "napi/native_api.h"
#include <hilog/log.h>
#define LOG_TAG "Pure"
napi_value CallSystemModule::GetDisplaySize(napi_env env, napi_callback_info info) {
// 获取arkts侧的系统库路径
char path[64] = "@ohos.display";
size_t typeLen = 0;
napi_value string;
napi_create_string_utf8(env, path, typeLen, &string);
// 加载系统库
napi_value sysModule;
napi_load_module(env, path, &sysModule);
// 获取系统库中的"getDefaultDisplaySync"方法
napi_value func = nullptr;
napi_get_named_property(env, sysModule, "getDefaultDisplaySync", &func);
napi_value funcResult;
napi_call_function(env, sysModule, func, 0, nullptr, &funcResult);
napi_value widthValue = nullptr;
napi_get_named_property(env, funcResult, "width", &widthValue);
double width;
napi_get_value_double(env, widthValue, &width);
OH_LOG_INFO(LOG_APP, "width: %{public}f", width);
napi_value heightValue = nullptr;
napi_get_named_property(env, funcResult, "height", &heightValue);
double height;
napi_get_value_double(env, heightValue, &height);
OH_LOG_INFO(LOG_APP, "height: %{public}f", height);
// 业务拿到width 和 height,可以进一步处理具体业务逻辑
return nullptr;
}