Unity 中调用Android 的Toast方法

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AndroidTest : MonoBehaviour {


    public Text t;
void Start () {
        //AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        //AndroidJavaObject jo = jc.GetStatic("currentActivity");
        //jo.Call("test","你好,世界");
        TestToast();


}
    ///
    /// C#调用Android 的Toast
    ///

    public void TestToast()
    {
        AndroidJavaClass player = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject activity = player.GetStatic("currentActivity");
        AndroidJavaClass toast = new AndroidJavaClass("android.widget.Toast");
        AndroidJavaObject context = activity.Call("getApplicationContext");
        activity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
         {
             toast.CallStatic("makeText", context, "send from unity",toast.GetStatic("LENGTH_LONG")).Call("show");
         }));
        
    }
    ///
    /// unity调用Android的方法
    ///

    public void OnClickAndroid()
    {
        //AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        //AndroidJavaObject jo = jc.GetStatic("currentActivity");
        //AndroidJavaObject jo = new AndroidJavaObject("com.lidongtgao.vtr.testclass.Test");
        //t.text = (jo.Call("add", 1, 3)).ToString();
    }
public void ChangeColor()
    {
        t.color = Color.red;
    }

}



Android原生的Toast方法

package com.lidongtgao.vtr.toasttest;


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 test(final String msg)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG).show();
            }
        });
    }
}

你可能感兴趣的:(unity)