Unity accesses third-party SDKs and its own SDK to merge Unity and Android communication

Android version

1. I have connected ShareSDK in my project to realize the login and share function, but I also need to write my own SDK to realize some functions that unity does not provide, such as power, wife, and access to photo albums.
2. I tried to write an Android project that inherits UnityPlayerActivity, merged it with the AndroidManifest file of ShareSDK, and made my Activity as the main startup item, but two icons appeared when I packaged it, and I don't know what happened.
3. Finally figured out a way, write a class in java, refer to the com.unity3d.player.UnityPlayer package name, can send messages to unity, write a method in the class to return the object of this class, you can new in the unity layer A java class, by calling the static method of the java class, get the object of the class, and call the method on the object through the object. This enables communication between unity and java, even in the presence of other SDKs

4. The code is as follows
in the java layer:

package com.sanyougame.guangliyx;

import com.unity3d.player.UnityPlayer;

public class MainActivity 
{
    public static  MainActivity mainActivity=null;

    public  void Init()
    {
        UnityPlayer.UnitySendMessage("LuaTools", "Receive", "在jar包中MainActivity初始化了");
    }

    //得到MainActivity对象 并执行初始化方法
    public static MainActivity GetMainActivity()
    {
        if(mainActivity==null)
        {
            mainActivity=new MainActivity();
        }
        mainActivity.Init();//初始化
        return mainActivity;
    }
    public void Say(String msg)
    {
        //Toast.makeText(this, "Say", Toast.LENGTH_LONG).show();
        UnityPlayer.UnitySendMessage("LuaTools", "Receive", "进入jar保重并传递给unity了");
    }
}

unity layers

using UnityEngine;
using System.Collections;

public class GASDK  
{
    public static void CallAndroid(string msg)
    {
        Debug.Log("add by  keshen ----->>>>CallAndroid");
        AndroidJavaClass jc = new AndroidJavaClass("com.sanyougame.guangliyx.Testxk");//参数包名.类名 >>得到一个AndroidJava类
        Debug.Log("add by  keshen ----->>>>cla" + jc);

        jc.CallStatic("init", "toast");//CallStatic调用java类中的静态方法(方法名,可变参数数组)
        Debug.Log("add by  keshen ----->>>>jo" + jc);
        AndroidJavaObject jo = jc.CallStatic<AndroidJavaObject>("getInstance");//调用java类中的静态方法返回一个java对象
        //AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("getInstance");//GetStatic  得到java类中静态字段对象的java对象
        jo.Call("say");//java对象调用普通方法,可传参也可不传
        Debug.Log("add by  keshen ----->>>>jo  init初始化完成" + jo);
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325543415&siteId=291194637