Unity3D & Android: Difference between “UnityMain” and “main” threads?

TLDR: I’m using JNI to call into my custom JAR from Unity C#. But the android library says it’s running on the “UnityMain” thread, while the actual ui thread for the activity is called “main”. What is the difference between the two?

Details:
This is a problem for me since I get the error “Can’t create handler inside thread that has not called Looper.prepare()”. Here’s the output I get when printing the two threads from Java:

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

To resolve this, I’m running the JNI calls using the Activity.runOnUiThread method:

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

Now I get the following output I get when printing the two threads from Java:

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

Only problem now is that I can’t make Unity Coroutine or Invoke calls from the “main” thread. I get the following Unity error

/// 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.

So what is the difference between the “UnityMain” and “main” threads? And why is the Java “main” thread different from that of Unity?

NOTE: I’ve posted the same question on StackOverflow: multithreading - Unity3D & Android: Difference between "UnityMain" and "main" threads? - Stack Overflow

1 Answer

1

See the answer on Stackoverflow:

http://stackoverflow.com/questions/31953890/unity3d-android-difference-between-unitymain-and-main-threads