【问题标题】:Unity3D & Android: Difference between "UnityMain" and "main" threads?Unity3D 和 Android:“UnityMain”和“主”线程之间的区别?
【发布时间】:2015-08-11 23:54:49
【问题描述】:

TLDR:我正在使用 JNI 从 Unity C# 调用我的自定义 JAR。但是android库说它在“UnityMain”线程上运行,而活动的实际ui线程被称为“main”。两者有什么区别?

详情: 这对我来说是个问题,因为我收到错误“无法在未调用 Looper.prepare() 的线程内创建处理程序”。这是我从 Java 打印两个线程时得到的输出:

/// Java Output
Current Thread:    Thread[UnityMain,5,main]
MainLooper Thread: Thread[main,5,main]

为了解决这个问题,我正在使用 Activity.runOnUiThread 方法运行 JNI 调用:

/// Unity C# Code
activityObj.Call("runOnUiThread", new AndroidJavaRunnable(() => {
  // JNI calls and other stuff
}

现在我从 Java 打印两个线程时得到以下输出:

/// Java Output
Current Thread:    Thread[main,5,main]
MainLooper Thread: Thread[main,5,main]

现在唯一的问题是我无法从“主”线程(即在“runOnUiThread”回调中)进行 Unity Coroutine 或 Invoke 调用。我收到以下 Unity 错误:

/// Unity C# Output
E/Unity   (21048): Invoke can only be called from the main thread.
E/Unity   (21048): Constructors and field initializers will be executed from the loading thread when loading a scene.
E/Unity   (21048): Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.

那么“UnityMain”和“main”线程有什么区别呢?为什么 Java 的“主”线程与 Unity 的不同?

【问题讨论】:

    标签: android multithreading unity3d


    【解决方案1】:

    Unity 运行自己的线程来处理其处理。它不会在启动应用程序时篡夺由 Android 操作系统创建的 Android 主线程。通常,当你编写一个传统的 Android 应用程序时,只有一个主线程,所有处理 UI 的东西都必须在主线程上运行。使用第二个“主”线程,是 Unity 做出的设计选择,可能是为了让它可以做任何想做的事情,而不会弄乱应用程序的 Android 主线程。如果你想在 Unity 之外的 Android UI 中做任何事情,你需要让你的代码在主线程上运行。您可以使用以下 sn-p 从任何地方执行此操作:

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Log.d("MAIN", "Thread? " + Thread.currentThread());
        }
    });
    

    如果您调用的 Android/Java 代码可以访问 Application 上下文或 Activity 上下文,您也可以使用 runOnUiThread

    【讨论】:

    • 感谢您的信息!我无法使用“new Handler(Looper.getMainLooper())”方法,因为处理程序初始化位于我的库正在使用的库中。刚刚找到该库的源代码,对其进行了修改,现在一切正常。
    • 修改黑盒库是个坏主意
    猜你喜欢
    • 2010-12-28
    • 2015-05-08
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2015-01-06
    相关资源
    最近更新 更多