using UnityEngine;
using System;
using UnityEngine.UI;

public class GameDataMgr : MonoBehaviour
{
    public Button Btn_UnityExit;
    public Button Btn_ShowMainActivityQuit;
    public Button Btn_ShowMainActivityUnload;
    public Text Txt_FormAndroidMessage;
    string userData = "用户信息(UseData):张三,22,男";

    private void Awake()
    {
        DontDestroyOnLoad(this);
    }

    private void Start()
    {
        Btn_UnityExit.onClick.AddListener(OnQuitUnity);
        // 点击ShowMainActivityUnload按钮调用
        Btn_ShowMainActivityUnload.onClick.AddListener(() =>
        {
            CallAndroidMethod("showMainActivity", false, ("UnloadSend:" + userData));
        });
        // 点击ShowMainActivityQuit按钮调用
        Btn_ShowMainActivityQuit.onClick.AddListener(() =>
        {
            CallAndroidMethod("showMainActivity", true, ("QuitSend:" + userData));
        });
    }

    /// <summary>
    /// 调用UnityGameActivity的方法
    /// </summary>
    /// <param name="methodName">Android方法名称</param>
    /// <param name="isFinish">方法参数1:是否结束UnityGameActivity</param>
    /// <param name="data">方法参数2:具体数据</param>
    private void CallAndroidMethod(string methodName, bool isFinish, string data)
    {
#if UNITY_ANDROID
        try
        {
            AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
            jo.Call(methodName, isFinish, data);
        }
        catch (Exception e)
        {
            Debug.LogError(e.Message);
        }
#endif
    }

    /// <summary>
    /// Android调用方法 在安卓UnityGameActivity OnCreate调用
    /// </summary>
    /// <param name="str"></param>
    public void sendMessageToUnity(string str)
    {
        Debug.Log("Unity获取Android MainActivity发送过来的Token信息: " + str);
        Txt_FormAndroidMessage.text = "来自Android MainActivity信息：" + str;
    }

    #region Unity程序原生方法
    void OnQuitUnity()
    {
        Application.Quit();
    }
    #endregion
}

