美文网首页
2020-10-16 Unity调用Android常用方法整理

2020-10-16 Unity调用Android常用方法整理

作者: VECTOR_Y | 来源:发表于2020-10-26 09:40 被阅读0次

    Android代码部分

    /**
         * unity项目启动时的的上下文
         */
        private Activity _unityActivity;
    
        /**
         * 获取unity项目的上下文
         * @return
         */
        Activity getActivity(){
            if(null == _unityActivity) {
                try {
                    Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
                    Activity activity = (Activity) classtype.getDeclaredField("currentActivity").get(classtype);
                    _unityActivity = activity;
                } catch (ClassNotFoundException e) {
                    Log.d("Unity2Android", "getActivity: "+e);
                } catch (IllegalAccessException e) {
                    Log.d("Unity2Android", "getActivity: "+e);
                } catch (NoSuchFieldException e) {
                    Log.d("Unity2Android", "getActivity: "+e);
                }
            }
            return _unityActivity;
        }
    
        /**
         * 调用Unity的方法
         * @param gameObjectName    调用的GameObject的名称
         * @param functionName      方法名
         * @param args              参数
         * @return                  调用是否成功
         */
       pulbic boolean callUnity(String gameObjectName, String functionName, String args){
            try {
                Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
                Method method =classtype.getMethod("UnitySendMessage", String.class,String.class,String.class);
                method.invoke(classtype,gameObjectName,functionName,args);
                return true;
            } catch (ClassNotFoundException e) {
                Log.d("Unity2Android", "callUnity: "+e);
            } catch (NoSuchMethodException e) {
                Log.d("Unity2Android", "callUnity: "+e);
            } catch (IllegalAccessException e) {
                Log.d("Unity2Android", "callUnity: "+e);
            } catch (InvocationTargetException e) {
                Log.d("Unity2Android", "callUnity: "+e);
            }
            return false;
        }
    
        /**
         * Toast显示unity发送过来的内容
         * @param content           消息的内容
         * @return                  调用是否成功
         */
        public boolean showToast(String content){
            Toast.makeText(getActivity(),content,Toast.LENGTH_SHORT).show();
             //这里是主动调用Unity中的方法,该方法之后unity部分会讲到
            callUnity("AndroidSend","AndroidCall", "hello unity i'm android");
            return true;
        }
    
        /***
         * 将Unity发送过来的文本内容复制到粘贴板
         * @param str
         * @throws Exception
         */
        public  boolean CopyTextToClipboard( String str){
    
            if(Looper.myLooper() ==null){
                Looper.prepare();
            }
    
            ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Activity.CLIPBOARD_SERVICE);
            ClipData textCd = ClipData.newPlainText("Label", str);
            clipboard.setPrimaryClip(textCd);
    
            return true;
        }
    
        /**
         * 获取设备唯一值
         * @return
         */
        public  String getUniversalID( )
        {
            String androidId = "" + Settings.Secure.getString(getActivity().getContentResolver(), "android_id");
            String uuid;
            try
            {
                if (!"9774d56d682e549c".equals(androidId))
                    uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8")).toString();
                else
                    uuid = UUID.randomUUID().toString();
            }
            catch (Exception e)
            {
                uuid = UUID.randomUUID().toString();
            }
            return uuid;
        }
    
    //包名    商店
    
        //com.taptap  taptap
    
        //com.android.vending   Google Play
    
        //com.tencent.android.qqdownloader  应用宝
    
        //com.qihoo.appstore    360手机助手
    
        //com.baidu.appsearch   百度手机助
    
        //com.xiaomi.market 小米应用商店
    
        //com.wandoujia.phoenix2    豌豆荚
    
        //com.huawei.appmarket  华为应用市场
    
        //com.taobao.appcenter  淘宝手机助手
    
        //com.hiapk.marketpho   安卓市场
    
        //cn.goapk.market   安智市场
        /**
         * 打开商店
         * @param appPkg  要打开的应用包名
         * @param marketPkg 商店的包名
         * @return
         */
        public  boolean toMarket(String appPkg, String marketPkg)
        {
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent("android.intent.action.VIEW", uri);
            intent.addFlags(268435456);
    
            if (marketPkg != null)
            {
                intent.setPackage(marketPkg);
            }
    
            try
            {
                getActivity().startActivity(intent);
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return false;
        }
    
        /**
         * 获取国家码
         */
        public  String getCountryZipCode( ) {
            String CountryID = "";
            String CountryZipCode = "";
            TelephonyManager manager = (TelephonyManager)  getActivity().getSystemService(Context.TELEPHONY_SERVICE);
            CountryID = manager.getSimCountryIso().toUpperCase();
            Log.d("ss", "CountryID--->>>" + CountryID);
            String[] rl =  getActivity().getResources().getStringArray(R.array.CountryCodes);
            for (int i = 0; i < rl.length; i++) {
                String[] g = rl[i].split(",");
                if (g[1].trim().equals(CountryID.trim())) {
                    CountryZipCode = g[1];
                    break;
                }
            }
            return CountryZipCode;
        }
    
      using System.Collections;
    using System.Collections.Generic;
    using System.Reflection.Emit;
    using UnityEngine;
    
    
    /// <summary>
    /// 与Android通讯脚本 
    /// </summary>
    public class AndroidSend :SingletonObject<AndroidSend>
    {
        /// <summary>
        /// android原生代码对象
        /// </summary>
        static AndroidJavaObject _ajc;
        public  AndroidJavaObject _Ajc { get { if (_ajc == null) _ajc = new AndroidJavaObject("com.zsy.callandroid.Unity2Android"); return _ajc; } }
    
    
        protected override void Spawn()
        {
            base.Spawn();
            this.name = "AndroidSend";
        }
    
        /// <summary>
        /// 显示Toast
        /// </summary>
        public  void ShowToast(string str)
        {
            try
            {
                _Ajc.Call<bool>("showToast", str);
            }
            catch (System.Exception e)
            {
                Debug.LogError("ShowToast error:" + e);
            }
        }
    
        /// <summary>
        /// 将文本复制到剪切板
        /// </summary>
        public  void Copy(string str)
        {
            bool su = false;
            try
            {
                su = _Ajc.Call<bool>("CopyTextToClipboard", str);
                if (su)
                    ShowToast("已复制到粘贴板!");
                else
                    ShowToast("复制失败!");
            }
            catch (System.Exception e)
            {
                Debug.LogError("Copy error:" + e);
            }
        }
    
        /// <summary>
        /// 获取设备码
        /// </summary>
        public  string GetDevice()
        {
            string str = "";
            try
            {
                str = _Ajc.Call<string>("getUniversalID");
            }
            catch (System.Exception e)
            {
                Debug.LogError("GetDevice error:" + e);
            }
            return str;
        }
    
        /// <summary>
        /// 打开商店
        /// </summary>
        public  void OpenShop()
        {
            bool su = false;
            try
            {
               su = _Ajc.Call<bool>("toMarket", "com.xxxxxx.XXX", "com.taptap");
            }
            catch (System.Exception e)
            {
                ShowToast("商店打开失败!");
                Debug.LogError("OpenShop error:" + e);
            }
        }
    
        /// <summary>
        /// 获取手机设置的当前国家码
        /// </summary>
        public  string GetCountryCode()
        {
            string su = "";
            try
            {
               su = _Ajc.Call<string>("getUniversalID");
            }
            catch (System.Exception e)
            {
                Debug.LogError("GetCountryCode error:" + e);
            }
            return su;
        }
    
        /// <summary>
        /// 通过包名判断应用是否已经安装
        /// </summary>
        /// <returns></returns>
        public  bool IsApplicationAvilible(string appPackageName) 
        {
            bool bo = false;
            try
            {
               bo = _Ajc.Call<bool>("isApplicationAvilible", appPackageName);
            }
            catch (System.Exception e)
            {
                Debug.LogError("IsApplicationAvilible error:"+e);
            }
            return bo;
        }
    
        /// <summary>
        /// 安装APK
        /// </summary>
        public  void InstallAPK(string apkPath)
        {
            try
            {
                AndroidJavaClass javaClass = new AndroidJavaClass("example.administrator.myapplication.MainActivity");
                javaClass.CallStatic<bool>("installAPK", Application.persistentDataPath + "/miner.apk");
                //_Ajc.Call<bool>("installAPK", apkPath);
            }
            catch (System.Exception e)
            {
                Debug.LogError("InstallAPK error:" + e);
            }
        }
    
        /// <summary>
        /// 来自android的通知
        /// </summary>
        public void AndroidCall(string code) 
        {
            Debug.Log(code) ;
        }
    
        /// <summary>
        /// 发往Android
        /// </summary>
        public void Send(string key,params object []  par) 
        {
            string parStr = "";
            foreach (var item in par)
            {
                parStr += item.ToString() + ",";
            }
    
            try
            {
                _Ajc.Call<bool>("UnitySendReceive", key, parStr);
            }
            catch (System.Exception e)
            {
                Debug.LogError("Send error:" + e);
            }
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:2020-10-16 Unity调用Android常用方法整理

          本文链接:https://www.haomeiwen.com/subject/lwltmktx.html