unity+android:拨打电话

2023-08-24 14:35:59 浏览数 (2)

代码语言:javascript复制
package com.luoyikun.call;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import com.unity3d.player.UnityPlayer;

public class MyCall extends Fragment {
    String m_gameObjectName;
    String m_funcName;

    private Context unityContext;
    private Activity unityActivity;

    private static final String TAG = "MyCall";

    public void UnityFunc(String gameObjectName, String funcName)
    {
        m_gameObjectName = gameObjectName;
        m_funcName = funcName;
    }

    private static MyCall Instance = null;

    public static MyCall GetInstanceByAndroid(Activity activity,Context context)
    {
        if (Instance == null)
        {
            Instance = new MyCall();
            Instance.unityActivity = activity;
            Instance.unityContext = context;

            activity.getFragmentManager().beginTransaction().add(Instance, TAG).commit();
        }
        return Instance;
    }

    public static MyCall GetInstance()
    {
        if(Instance == null)
        {
            Instance = new MyCall();
            //Instance.gameObjectName = gameObject;
            Instance.unityActivity = UnityPlayer.currentActivity;
            if (Instance.unityActivity == null)
            {
                Instance.CallUnity("Instance.unityActivity == null");
            }
            Instance.unityContext = Instance.unityActivity.getBaseContext();
            if (Instance.unityContext == null)
            {
                Instance.CallUnity("Instance.unityContext == null");
            }
            UnityPlayer.currentActivity.getFragmentManager().beginTransaction().add(Instance, TAG).commit();

        }
        return Instance;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);  // 这一句很重要,保存对该Fragment的引用,防止在旋转屏幕等操作时时丢失引用(Fragment隶属于Activity)
    }

    // 调用 Unity
    // gameObjectName 为接受消息的Unity 中 GameObject 的名字
    // functionName   为接受消息的GameObject 挂载 C# 脚本中的函数名
    // _content       为发送给Unity 的内容
    public void CallUnity( String _content)
    {
        UnityPlayer.UnitySendMessage(m_gameObjectName, m_funcName, _content);
    }

    public void CallPhone(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        unityActivity.startActivity(intent);
    }

}

unity端调用

代码语言:javascript复制
    public static void CallPhone(string phone)
    {
        AndroidJavaObject pluginObject = new AndroidJavaClass("com.luoyikun.call.MyCall").CallStatic<AndroidJavaObject>("GetInstance");
        pluginObject.Call("CallPhone", phone);
    }

0 人点赞