Unity3D上的Java插件无法启动新线程

时间:2013-10-22 07:13:00

标签: java android multithreading unity3d

我有一个java插件,我在我开发的简单java应用程序上使用。 这个插件启动了一个也使用网络的新线程。

执行的类正在实现Runnable并以这种方式启动线程:

AsyncTask.execute(this);

这适用于java应用程序并运行没有任何问题,但是,当我尝试使用Unity3D运行此插件时,它会抛出错误并且不会运行我的插件

在Unity3D中执行的代码:

var token="AbCd123456789";
var jo = new AndroidJavaObject("com.edealya.lib.AppayableUnityAdapter");
jo.Call("runApplayble",token);

runAppayable方法是:

public void runAppayable(String token){
DeviceIdentifier edDevice = new DeviceIdentifier(
                                this.getApplicationContext(),token);
edDevice.update();

}

和edDevice.update();是启动新线程的方法。

I/Unity   (27624): Exception: java.lang.RuntimeException: Can't create handler inside     thread that has not called Looper.prepare()
I/Unity   (27624):   at UnityEngine.AndroidJNISafe.CheckException () [0x00000] in   <filename unknown>:0 
I/Unity   (27624):   at UnityEngine.AndroidJNISafe.NewObject (IntPtr clazz, IntPtr methodID, UnityEngine.jvalue[] args) [0x00000] in <filename unknown>:0 
I/Unity   (27624):   at UnityEngine.AndroidJavaObject._AndroidJavaObject (System.String className, System.Object[] args) [0x00000] in <filename unknown>:0 
I/Unity   (27624):   at UnityEngine.AndroidJavaObject..ctor (System.String className, System.Object[] args) [0x00000] in <filename unknown>:0 
I/Unity   (27624):   at ReflectionFx.startAppayable () [0x00006] in /Users/Shared/Unity/4-0_AngryBots/Assets/Scripts/Fx/ReflectionFx.cs:30 
I/Unity   (27624):   at ReflectionFx.Start () [0x00000] in /Users/Shared/Unity/4-0_AngryBots/Assets/Scripts/Fx/ReflectionFx.cs:38 

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

必须在具有Looper的UiThread或线程上启动AsyncTask,尝试使用

启动它
myActivity.runOnUiThread(new Runnable(){AsyncTask.execute(this);})

或在线程上调用Looper.prepare()你在开始之前

答案 1 :(得分:0)

通过阅读堆栈跟踪,它看起来像Unity层正在捕获运行时异常并抛弃不同的东西。

我看到了类似的堆栈跟踪与NullPointerException:而不是堆栈跟踪追溯到我的代码中问题所在的地方,我看到这个Unity JNI堆栈跟踪。

任何人都可以解释为什么会这样,以及如何让Unity转出正确的堆栈跟踪?