diff --git a/frameworks/js/ani/include/sensor_ani.h b/frameworks/js/ani/include/sensor_ani.h index 3fd5c5a63bc240bc28e3cbb9c889fea54c1ec4b7..be11ac1711c37a0a90df2978ea5e93a182a7a27d 100644 --- a/frameworks/js/ani/include/sensor_ani.h +++ b/frameworks/js/ani/include/sensor_ani.h @@ -106,13 +106,14 @@ struct BusinessError { class AsyncCallbackInfo : public RefBase { public: - ani_env* env = nullptr; + ani_vm *vm = nullptr; + ani_env *env = nullptr; ani_ref callback[CALLBACK_NUM] = { 0 }; CallbackData data; BusinessError error; CallbackDataType type; vector sensorInfos; - AsyncCallbackInfo(ani_env* env, CallbackDataType type) : env(env), type(type) {} + AsyncCallbackInfo(ani_vm *vm, ani_env *env, CallbackDataType type) : vm(vm), env(env), type(type) {} ~AsyncCallbackInfo() { CALL_LOG_ENTER; @@ -122,6 +123,8 @@ public: SEN_HILOGD("Delete reference, i:%{public}d", i); env->GlobalReference_Delete(callback[i]); callback[i] = nullptr; + env = nullptr; + vm = nullptr; } } } diff --git a/frameworks/js/ani/src/sensor_ani.cpp b/frameworks/js/ani/src/sensor_ani.cpp index 9df282032c8fda9919327af8d74e0e73450c9764..361c6e413dfb84705ad6a085dd67e82fd132bb9c 100644 --- a/frameworks/js/ani/src/sensor_ani.cpp +++ b/frameworks/js/ani/src/sensor_ani.cpp @@ -86,7 +86,7 @@ static float g_bodyState = -1.0f; static std::map>> g_subscribeCallbacks; static std::mutex onMutex_; static std::map>> g_onCallbackInfos; -static thread_local std::shared_ptr mainHandler; +static thread_local std::shared_ptr mainHandler = nullptr; static void ThrowBusinessError(ani_env *env, int errCode, std::string&& errMsg) { @@ -344,6 +344,16 @@ static void EmitUvEventLoop(sptr asyncCallbackInfo) CHKPV(asyncCallbackInfo); auto task = [asyncCallbackInfo]() { SEN_HILOGD("Begin to call task"); + ani_env *env = nullptr; + ani_options aniArgs {0, nullptr}; + if (ANI_ERROR == asyncCallbackInfo->vm->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &env)) { + if (ANI_OK != asyncCallbackInfo->vm->GetEnv(ANI_VERSION_1, &env)) { + SEN_HILOGE("GetEnv failed"); + return; + } + } + asyncCallbackInfo->env = env; + AniLocalScopeGuard aniLocalScopeGuard(asyncCallbackInfo->env, ANI_SCOPE_SIZE); if (!aniLocalScopeGuard.IsStatusOK()) { SEN_HILOGE("CreateLocalScope failed"); @@ -452,12 +462,19 @@ static bool IsSubscribed(ani_env *env, int32_t sensorTypeId, ani_object callback } return false; } + static void UpdateCallbackInfos(ani_env *env, int32_t sensorTypeId, ani_object callback) { CALL_LOG_ENTER; std::lock_guard onCallbackLock(onMutex_); CHKCV((!IsSubscribed(env, sensorTypeId, callback)), "The callback has been subscribed"); - sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, ON_CALLBACK); + + ani_vm *vm = nullptr; + if (ANI_OK != env->GetVM(&vm)) { + SEN_HILOGE("GetVM failed."); + return; + } + sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(vm, env, ON_CALLBACK); CHKPV(asyncCallbackInfo); if (ANI_OK != env->GlobalReference_Create(callback, &asyncCallbackInfo->callback[0])) {