AndroidJavaException无法在Unity中未调用looper.prepare的线程内创建处理程序

时间:2016-04-15 12:07:56

标签: android plugins unity3d

这是我的代码。而我收到错误AndroidJavaException无法在Unity中调用looper.prepare的线程中创建处理程序。在activity.Call(runOnUiThread)

public static void showToast(string text)
        {
            if (Application.platform == RuntimePlatform.Android)
            {
                AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
                AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
                AndroidJavaClass Toast = new AndroidJavaClass("android.widget.Toast");
                AndroidJavaObject javaString = new AndroidJavaObject("java.lang.String", text);
                AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext");
                AndroidJavaObject toast = Toast.CallStatic<AndroidJavaObject>("makeText", context, javaString, Toast.GetStatic<int>("LENGTH_SHORT"));
                activity.Call("runOnUiThread", new AndroidJavaRunnable(()=> { toast.Call("show"); }));
            }
        }

如果有解决方案请帮忙。我做错了什么。谢谢提前

2 个答案:

答案 0 :(得分:2)

问题是Unity团队在没有looper的线程中运行,这意味着需要处理程序/ looper的任何东西必须在UI线程上运行,在你的情况下

            activity.Call("runOnUiThread", new AndroidJavaRunnable(()=> 
        { 
            AndroidJavaClass Toast = new AndroidJavaClass("android.widget.Toast");
            AndroidJavaObject javaString = new AndroidJavaObject("java.lang.String", text);
            AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext");
            AndroidJavaObject toast = Toast.CallStatic<AndroidJavaObject>("makeText", context, javaString, Toast.GetStatic<int>("LENGTH_SHORT"));
            toast.Call("show"); }
        ));

或者只是makeText部分

答案 1 :(得分:0)

UnityPlayer仅为整个应用创建一个活动。它运行在没有looper的后台线程上。 因此,任何需要处理程序/循环程序的东西都必须在UI线程上运行。

public static void showToast(string text)
{
    if (Application.platform == RuntimePlatform.Android)
    {
        AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
        AndroidJavaClass Toast = new AndroidJavaClass("android.widget.Toast");
        AndroidJavaObject javaString = new AndroidJavaObject("java.lang.String", text);
        AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext");
        activity.Call("runOnUiThread", new AndroidJavaRunnable(()=> { 
            AndroidJavaObject toast = Toast.CallStatic<AndroidJavaObject>("makeText", context, javaString, Toast.GetStatic<int>("LENGTH_SHORT"));
            toast.Call("show"); }));
                }
            }