Unity and Android Studio call each other

Unity and Android Studio call each other

Foreword: Recently, I was studying the interaction between unity and Android, so I searched a lot of things about this on the Internet. Because when you search on the Internet, you feel that everything is fragmentary, almost all of them are available, but they are not comprehensive enough, so they write articles to sort out the knowledge that Unity and Android Studio call each other.

Some API of android is called in 1.u3d.

The code is as follows (example):

Let's introduce it first u3d Call in android Some of API 
UnityPlayer yes unity3d One of its own jar Packet, the key to communication at both ends, 
currentActivity yes android Need context, these two things you can think of as calling something android Parameters required by method,Just write it down
 
AndroidJavaClass jc=new AndroidJavaClass("com.unity3d.player.UnityPlayer"); 
AndroidJavaObject jo=jc.GetStatic("currentActivity");
 
jo.Call(method ,parameter );
jo.Get(method ,parameter );
jo.Set(method ,parameter );
jo.CallStatic(method ,parameter );
jo.GetStatic (method ,parameter );
jo.SetStatic (method ,parameter );
12345678910111213

The url used here is the data requested by the network.

Unity calls Android

1.unity calls Android's non static methods. Inherit UnityPlayerActivity

Note: when using this method, the class you write in Android Studio can only be transferred by inheriting UnityPlayerActivity, but only one class can inherit it. When multiple classes inherit, other classes cannot be transferred
Unit code:

AndroidJavaClass jc = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject> ("currentActivity");
jo.Call ("login","Here are the parameters passed in the past");

Android Code:

package com.example.test;

public class MainActivity extends UnityPlayerActivity {

public void login( String str )
{      
   
}

2.unity calls the static method of Android

Note: the Android javaclass () here contains its own package name + class name
This can be written without inheriting the UnityPlayerActivity
Unit code:

AndroidJavaClass jc = new AndroidJavaClass ("com.example.test.Test");
jc.GetStatic<AndroidJavaObject> ("login","");

Android Code:

package com.example.test;

public class Test{
public static void login( String str )
 {      
   
  }

3.unity calls Android's non static methods

Unit code:

AndroidJavaObject jo = new AndroidJavaObject("com.example.test.Test"); 
jo.Call("login","");

Android Code:

package com.example.test;

public class Test{

public void login( String str ) {      
   
}

4.unity calls Android's non static methods. Write a static constructor for your class

Note: the Android javaclass () here contains its own package name + class name
This can be written without inheriting the UnityPlayerActivity
I wrote a static constructor here. First get this method through Unity, and then call the non static method written in this class through this method
In the final analysis, I first used the first step of static method acquisition

Unit code:

AndroidJavaClass jc = new AndroidJavaClass("com.hasee.librarydemo.Test"); 
AndroidJavaObject jo = jc.CallStatic<AndroidJavaObject>("getInstance");
 jo.Call("login","");

Android Code:

public class Test{
    public static Test_instance;
    public static Test getInstance(){
        if(_instance==null){
            _instance=new Test();
        }
       return _instance;
    }
public static void login( String str ) {      
   
}

Android calls Unity

1. Call Unity by sending UnitySendMessage

//Send the message to the OnResult method on the iFlytekASRController object in the Unity scene
UnityPlayer.UnitySendMessage("iFlytekASRController", "OnResultWake", resultString);

example:

//Method encapsulation
private static final String METHOD_NAME = "OnMessage"; // Method name of GameObject arbitrary script
private static final String METHOD_NAME = "OnMessage"; // Method name of GameObject arbitrary script
private void sendMessageToUnity(String key, String param) {
        String args = key + "|" + param;
        UnityPlayer.UnitySendMessage(GO_NAME, METHOD_NAME,  args);
    }
//call
sendMessageToUnity("LOGIN_SUCCEED",1)

2. By proxy AndroidJavaProxy

Android can communicate with Unity through this Android Java proxy, which is more troublesome than sending messages, but it can do a lot of things. Moreover, using this proxy is equivalent to a callback to Unity, which is more reliable than sending messages. The reflection mechanism is used to send messages. The string is also easy to be written incorrectly. There may be sending failure, delay, etc., but it is more stable to use this callback
Now I write a Demo to do communication test

AS end:
1. First, write an interface on the AS side. Some methods or parameters that need to be called to Unity can be written in the interface, which is equal to the callback passed to Unity

package com.example.test;

public interface UnityasrEventCallback {
    public void Speechcontent(int a);
    public void Test1(String msg);
}

2. Write an Activity to communicate with unity. The unity side calls this method (setcallback (unityasreventcallback)) to pass the proxy, and then passes the callback of methods and parameters defined in the AS interface to the unity side through the passed proxy

private UnityasrEventCallback mCallback;
    
    public void setCallback(UnityasrEventCallback callback){
        Log.d("@@@", "UnityBatteryEventCallback setCallback start ");
        mCallback = callback;
        Log.d("@@@", "UnityBatteryEventCallback setCallback end ");
         mCallback.Test1("The connection succeeded");
          mCallback.Speechcontent(666);
    }

Unity end:
1. Write an internal class in a cs script, and then inherit AndroidJavaProxy. Then write a constructor to inherit the package name + interface name of AS
Then implement this interface. The method name must be the same AS that written in the AS, and then define a value to receive the data transmitted from the AS

public class AsrEventCallback : AndroidJavaProxy
    {
        public AsrEventCallback() : base("com.example.test.UnityasrEventCallback") {  }
        public void Speechcontent(int content){int a = content;}
        public void Test1(string msg){string b = msg;}
    }

The in base() is the interface in AS, package name + interface name. Look, don't make mistakes

2. Create a new agent in the Start of this cs script, and then use jo.Call("setCallback", asreeventcallback); Pass the proxy to the AS, and then the AS can call the proxy to return data to Unity

void Start()
    {
    AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
    AsrEventCallback asrEventCallback = new AsrEventCallback();
    
        jo.Call("setCallback", asrEventCallback);
    }

Unity simple implementation of Toast in Android

1.Unity end C# direct code writing call (no need to operate in AS)

Where Toast needs to be used, you can directly use this set of code and change the Chinese character to the desired use

AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
       AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");

       AndroidJavaClass toast = new AndroidJavaClass("android.widget.Toast");
       AndroidJavaObject context = jo.Call<AndroidJavaObject>("getApplicationContext");
        
       jo.Call("runOnUiThread", new AndroidJavaRunnable(() =>
        {
            toast.CallStatic<AndroidJavaObject>("makeText", context, "Start agent test", toast.GetStatic<int>("LENGTH_SHORT")).Call("show");
        }));

2.Unity side calls Toast written by AS side

Unity end:

public void OnClickAndroid()
    {
        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
      
        jo.Call<int>("testToast", "Toast!");
    }

AS end:

package com.test;

import android.os.Bundle;
import android.widget.Toast;

import com.unity3d.player.UnityPlayerActivity;

public class MainActivity extends UnityPlayerActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    public void testToast(final String msg)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG).show();
            }
        });
    }
}

The above briefly sorted out several ways of interaction between Unity and Android Studio. Of course, it is not comprehensive enough. At present, we know almost the same about these ways. I will continue to sort out the new knowledge I learned later. If you think it's useful, point a praise before you go < > > >

If you forget how to package into aar package on Android to interact with Unity. You can refer to this article, which is very complete
Write code in Android Studio, export aar package, and use interaction in Unity (Xiaobai complete article)

Posted by calabiyau on Sun, 24 Oct 2021 04:36:57 -0700