How to create Android Handler in a Java plugin cal

2019-06-08 03:41发布

问题:

So, let's say you have a Unity Java plugin, you call into the Java plugin like so

private static readonly AndroidJavaClass m_somePlugin = new AndroidJavaClass("com.unity3d.Plugin.blah.SomePlugin");

using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
    using (var currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
    {
        m_somePlugin.CallStatic("onInitialise", currentActivity);
    }
}

and the plugin looks something like this

public class SomePlugin 
{
    static public void onInitialise(final Activity currentActivity) 
    {
        Handler someHandler = new Handler();
    }
}

All quite simple. Except it will crash. Creating a Handler is the cause. I'm guessing it's a thread issue.

So the question is, how does one create a handler in a Java plugin, in the activity that I'm passing in? Anyone know?

回答1:

Yes, the solution to the problem was to use runOnUiThread. So in order to get the above code to not crash SomePlugin should look like so

public class SomePlugin 
{
    static public void onInitialise(final Activity currentActivity) 
    {
        currentActivity.runOnUiThread(new Runnable() {
            Handler someHandler = new Handler(); });
    }
}