diff --git a/engine/src/flutter/shell/platform/android/android_shell_holder.cc b/engine/src/flutter/shell/platform/android/android_shell_holder.cc index 7dc454f1fb..5ef505e77a 100644 --- a/engine/src/flutter/shell/platform/android/android_shell_holder.cc +++ b/engine/src/flutter/shell/platform/android/android_shell_holder.cc @@ -6,6 +6,7 @@ #include "flutter/shell/platform/android/android_shell_holder.h" +#include #include #include @@ -27,9 +28,18 @@ AndroidShellHolder::AndroidShellHolder( static size_t shell_count = 1; auto thread_label = std::to_string(shell_count++); + FXL_CHECK(pthread_key_create(&thread_destruct_key_, ThreadDestructCallback) == + 0); + thread_host_ = {thread_label, ThreadHost::Type::UI | ThreadHost::Type::GPU | ThreadHost::Type::IO}; + // Detach from JNI when the UI thread exits. + thread_host_.ui_thread->GetTaskRunner()->PostTask( + [key = thread_destruct_key_]() { + FXL_CHECK(pthread_setspecific(key, reinterpret_cast(1)) == 0); + }); + fml::WeakPtr weak_platform_view; Shell::CreateCallback on_create_platform_view = [java_object, &weak_platform_view](Shell& shell) { @@ -80,7 +90,15 @@ AndroidShellHolder::AndroidShellHolder( } } -AndroidShellHolder::~AndroidShellHolder() = default; +AndroidShellHolder::~AndroidShellHolder() { + shell_.reset(); + thread_host_.Reset(); + FXL_CHECK(pthread_key_delete(thread_destruct_key_) == 0); +} + +void AndroidShellHolder::ThreadDestructCallback(void* value) { + fml::jni::DetachFromVM(); +} bool AndroidShellHolder::IsValid() const { return is_valid_; diff --git a/engine/src/flutter/shell/platform/android/android_shell_holder.h b/engine/src/flutter/shell/platform/android/android_shell_holder.h index e0905f0f9e..4bf42a776d 100644 --- a/engine/src/flutter/shell/platform/android/android_shell_holder.h +++ b/engine/src/flutter/shell/platform/android/android_shell_holder.h @@ -50,6 +50,9 @@ class AndroidShellHolder { ThreadHost thread_host_; std::unique_ptr shell_; bool is_valid_ = false; + pthread_key_t thread_destruct_key_; + + static void ThreadDestructCallback(void* value); FXL_DISALLOW_COPY_AND_ASSIGN(AndroidShellHolder); };