How to pass a JNI C# class into Java or handle this situation?

前端 未结 6 2631
[愿得一人]
[愿得一人] 2021-02-20 01:42

I\'m trying to call a Java method from C#, it\'s called like this from java:

EgamePay.pay(thisActivity, payAlias, new EgamePayListener() {
            @Override
         


        
6条回答
  •  再見小時候
    2021-02-20 02:05

    if you are in a context of Unity3D, a better way to interact from Java native code to Unity3D C# script would be the calling the UnitySendMessage method. You can call this method in you Java code, and a message will be sent to C#, so you can get a specified method executed in C#.

    You could add a gameObject in your Unity scene and create a MonoBehavior script which contains these three methods (paySucess(string message), payFailed(string message) and payCancel(message)). Then attach the new created script to the gameObject (let us assume the name of this gameObject to be "PayListener") and make sure the gameObject existing in your scene when the Java code be executed (you can call DontDestroyOnLoad on the gameObject in Awake, for example).

    Then, in your Java code, just write like these:

    EgamePay.pay(thisActivity, payAlias, new EgamePayListener() {
        @Override
        public void paySuccess(String alias) {
            com.unity3d.player.UnityPlayer.UnitySendMessage("PayListener","paySuccess", alias);
        }
    
        @Override
        public void payFailed(String alias, int errorInt) {
            com.unity3d.player.UnityPlayer.UnitySendMessage("PayListener","payFailed", alias + "#" + errorInt);
        }
    
        @Override
        public void payCancel(String alias) {
            com.unity3d.player.UnityPlayer.UnitySendMessage("PayListener","payCancel", alias);
        }
    });
    

    It would prevent the java file to build successfully without the com.unity3d.player.UnityPlayer class. You could find the /Applications/Unity/Unity.app/Contents/PlaybackEngines/AndroidPlayer/bin/classes.jar file and add it as a dependency library for your java project. Then you can build, generate and use the new jar file without error.

    Because of the UnitySendMessage method can only take 1 parameter, so you might have to connect the payFailed result alias and errorInt by a strategy, and parse it back in Unity C# side.

    By using the new built jar file and load it as a AndroidJavaClass or AndroidJavaObject, the corresponding method in the PayListener script should be called when the one in Java is get called.

    For documentation of the Android plugin with UnitySendMessage, you can visit the official guide of how to implement a Android JNI plugin here, in the example 3.

提交回复
热议问题