- Home /
AndroidJNI attaching to multiple threads
I am creating multiple threads in Unity with C# (I know, I know, Unity isn't built for multithreading).
I have a Java function that simply returns the number 3. On the C# side if I call the Java function on the main Unity thread then I get the number 3 returned:
int foo = javaObject.Call<int>("foo");
// foo == 3
Now if I call the same Java function from a thread I created in C# then I get the number 0 returned:
new Thread(delegate() {
AndroidJNI.AttachCurrentThread();
int foo = javaObject.Call<int>("foo");
// foo == 0
}).Start();
The reason I am using threading is because I am sending and receiving packets and I don't want both ends to be stuck on receiving and not being able to send, essentially creating deadlock.
I am using AndroidJNI because the library I am using for networking was built for Android using Java. I have to use this library for this project.
I am fairly new to JNI and so I might be missing some steps. I know I have the synchronous method setup properly (not all setup steps are shown). But please let me know if there are more steps required for using multiple threads.
Let me know if you need any additional information.
Note: An alternate solution to this would be to have the threads running in Java then passing the received data to C#. However, currently it is only possible to send strings from Java to C#. A question regarding this subject has been posted here http://answers.unity3d.com/questions/314271/will-unity-40-support-sending-complex-data-from-an.html#comment-315848
Answer by BGawenda · Aug 19, 2013 at 02:14 PM
I know this post is rather old, but I just ran into the same kind of problem using Unity 4 When I try to create at AndroidJavaObject from a different thread it throws exception. Although I first called the AndroidJNI.AttachCurrentThread method. Is there any update on this issue? Or is it just not supported to call into JNI from different threads?
Your answer
Follow this Question
Related Questions
Unity networking tutorial? 6 Answers
Unity Asynchronous Socket Client - Threading Problem 2 Answers
Asynchronous Sockets still have problem in 4.6.3f1 with IL2CPP 3 Answers
Asynchronous Game server 2 Answers
Thread continues to run after game quits 0 Answers