Unity2019.4 calls Android communication interaction

Preface

UnityPlayerActivity could not be found! UnityPlayerActivity could not be found! UnityPlayerActivity could not be found! Changed to
the 2019.4 version, and found many errors in exporting android. For example, UnityPlayerActivity could not be found, resources were duplicated and so on. The reason is that Unity has made changes. It seems to be after 2019.2. The version has been upgraded (the specific version is unknown), don't say much, just start it

Android Studio

Create a project, remember the package name

Configuration and code examples in Android Studio

First import classes.jar, there is no change in this step.According to your andriod project mono/IL2Cpp, find the corresponding jar package, such as my project

ctrl+c, then ctrl+v in the AS Libs folder, then click Add as library



and edit MainActivity.java, and found that the UnityplayerActivity

plug-in cannot be inherited unity of Classes.jar package is not present in this class, this time we need to find Untiy in UnityPlayerActivity, for example, my path

you can simply add the class to MainActivitythe same directory, but I recommend more directly copied the entire package

last Effect

Then we MainActivitywrite code in

package com.test.unityandroidtest;
import android.os.Bundle;
import android.widget.Toast;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

public class MainActivity extends UnityPlayerActivity {
    
    
    public static MainActivity instance = null;  //单例类
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        instance=this;
    }
    //利用Toast
    public void SayHi(final String str)
    {
    
    
        runOnUiThread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
            }
        });
    }
    //计算两数之和
    public int GetSum(int num1,int num2)
    {
    
    
     return num1+num2;
    }

    public static void SendUnity(String str)
    {
    
    
        String newstr="我是Android传来的消息:"+str;
        UnityPlayer.UnitySendMessage("UnityAndroidConnect","AndroidCallUnityMsg",newstr);
    }
}

Then modify the AndroidManifest.xml
original

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.unityandroidtest">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

After modification

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.unityandroidtest">

    <application>
      <!--表明这个Activity是启动Activity 一定要写完全的包名 路径-->
        <activity android:name="com.test.unityandroidtest.MainActivity">
           
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
        </activity>
    </application>
</manifest>

Then in AS, the title taskbar Build->Make Project.
Generally, we only need one jar .

Open the jar package with the compressed package, delete the com directory inside, delete

the buildConfig.class in the test file.

Note: When packaging unity , If you encounter

this, D8:Program type already presenit indicates that the resources are duplicated. The above two parts are deleting redundant files.

In Unity

Then put our classes.jarsum AndroidManifest.xmlin Unity, classes.jar in the libs folder,

then create a new gameobject in Unity, name it UnityAndroidConnect, and then add a new script and write the code

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class NewBehaviourScript : MonoBehaviour
{
    
    
    public Button btnToast, btnNum, btnString;
    public Text text;

    AndroidJavaClass jc;
    AndroidJavaObject androidInstance; //单例

    private void Start()
    {
    
    
        try
        {
    
    
            /* 下面的代码已不再适用
            AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
            */

            //一定要写完整
            jc = new AndroidJavaClass("com.test.unityandroidtest.MainActivity");
            androidInstance = jc.GetStatic<AndroidJavaObject>("instance");
        }
        catch (Exception e)
        {
    
    
            text.text = "初始化错误:" + e.ToString();
        }
        btnToast.onClick.AddListener(MakeToast);
        btnNum.onClick.AddListener(GetSum);
        btnString.onClick.AddListener(UnitySendAndroid);
    }

    public void MakeToast()
    {
    
    
        try
        {
    
    
            androidInstance.Call("SayHi", "hello unity");
        }
        catch (Exception e)
        {
    
    
            text.text = e.ToString();
        }
    }

    public void GetSum()
    {
    
    
        try
        {
    
    
            int num = 90;
            int num2 = 90;
            num = androidInstance.Call<int>("GetSum", num, num2); //返回值Int方法
            text.text = "计算结果:" + num.ToString();
        }
        catch (Exception e)
        {
    
    
            text.text = e.ToString();
        }
    }

    public void UnitySendAndroid()
    {
    
    
        try
        {
    
    
            string str = "loveyou";
            jc.CallStatic("SendUnity", str); //静态方法 可以直接用AndroidJavaClass jc
        }
        catch (Exception e)
        {
    
    
            text.text = e.ToString();
        }
    }

    /// <summary>
    /// android 发来的消息
    /// </summary>
    /// <param name="recvMsg"></param>
    public void AndroidCallUnityMsg(string recvMsg)
    {
    
    
        text.text = "结果:" + recvMsg;
    }
}

Just build the Unity interface,

package settings,

package test results

The last show operation

The above steps are packaged and run. When looking for information, we found other sao operations, that is, we can directly compile the written java class in unity. Here is an official GitHub project, you can check https://github. com/Unity-Technologies/uaal-example
For example, the MainActivityfiles above are directly placed under the Unity Android (AndroidMainfest.xml should also be placed) folder, it is also completely possible, really possible!!! It is convenient to save a lot of steps

Thanks for the article

  1. Unity2019 Android environment configuration
  2. Unity3D and Android platform communication
  3. Unity2019.4.4 interacts with AndroidStudio3.5.2

Guess you like

Origin blog.csdn.net/K20132014/article/details/109159008