Solution to Flash Back of Unity Multi thread Calling Android Method

When the Android AAR/JAR plug-in is used in Unity, if the Android java method is called in the main thread, it can be called normally, but when a new thread is opened, it will flash back. Record the solution here.

Problem recurrence

The following test code generates an Android object and calls its JAVA instance method TestFunc.

1. Synchronous call (normal)

Call Android methods in the Unity main thread, that is, synchronously call:

 void Start() { androidObj = new AndroidJavaObject("com.azimiao.test.class1"); } void CallAndroidFunc(params object[] test) { androidObj?.Call("TestFunc",test); }

The method in the Android plug-in is called normally.

2. Asynchronous thread call (flashback, error call method)

Try calling Android methods in another thread:

 void CallAndroidFunc(params object[] test) { testThread = new Thread(() => { androidObj?.Call("TestFunc", test); }); testThread.Start(); }

When executing, the APK packaged by Unity will flash back directly.

solve the problem

about AndroidJNI.AttachCurrentThread , the document is described as follows:

  • Attach the current thread to the Java (Dalvik) VM.
  • A thread must be attached to the VM before any other JNI calls can be made.

Therefore, the thread call method is modified as follows:

 void Start() { androidObj = new AndroidJavaObject("com.azimiao.test.class1"); } void CallAndroidFunc(params object[] test) { testThread = new Thread(() => { AndroidJNI.AttachCurrentThread(); ndroidObj?.Call("TestFunc", test); }); testThread.Start(); }

After modification, the problem is solved.

Zimiao haunting blog (azimiao. com) All rights reserved. Please note the link when reprinting: https://www.azimiao.com/7859.html
Welcome to the Zimiao haunting blog exchange group: three hundred and thirteen million seven hundred and thirty-two thousand

Comment

*

*