TLDR:,我正在使用JNI从Unity调用自定义JAR。但安卓库表示,它运行在"UnityMain“线程上,而活动的实际ui线程称为"main”。这两者有什么区别呢?
Details: --这对我来说是个问题,因为我得到了错误“无法在线程中创建没有调用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或调用。我得到以下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“和”主“线程之间有什么区别呢?为什么Java“主”线程与统一线程不同?
发布于 2015-08-12 00:44:45
统一运行自己的线程来处理它的处理。在发布该应用程序时,它不会取代Android操作系统创建的Android主线程。通常,当您编写传统的Android应用程序时,只有一个主线程,处理UI的所有内容都必须在主线程上运行。使用第二个“主”线程,是由联合公司做出的一个设计选择,这样它就可以做它想做的任何事情,而不会干扰Android主线程的应用程序。如果您想在联合之外的Android中做任何事情,您需要在主线程上运行您的代码。您可以使用以下代码片段在任何地方执行此操作:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Log.d("MAIN", "Thread? " + Thread.currentThread());
}
});
如果要调用的Android/Java代码能够访问应用程序上下文或活动上下文,也可以使用runOnUiThread
。
https://stackoverflow.com/questions/31953890
复制相似问题