|
| 1 | +using System.Collections; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Runtime.InteropServices; |
| 4 | +using UnityEngine; |
| 5 | +using UnityEngine.UI; |
| 6 | + |
| 7 | +public class MyScript : MonoBehaviour |
| 8 | +{ |
| 9 | + |
| 10 | + private static readonly string AndroidKey = "YouAndroidQQGroupKey"; |
| 11 | + |
| 12 | + private static readonly string iOSUid = "YouiOSUid"; |
| 13 | + private static readonly string iOSKey = "YouiOSQQGroupKey"; |
| 14 | + |
| 15 | + private AndroidJavaClass _jc; |
| 16 | + private AndroidJavaObject _jo; |
| 17 | + |
| 18 | + // Use this for initialization |
| 19 | + void Start() |
| 20 | + { |
| 21 | + _jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); |
| 22 | + _jo = _jc.GetStatic<AndroidJavaObject>("currentActivity"); |
| 23 | + |
| 24 | + var btnObj = this.transform.Find("BtnQQ"); |
| 25 | + var button = btnObj.GetComponent<Button>(); |
| 26 | + button.onClick.AddListener(OnClick); |
| 27 | + } |
| 28 | + |
| 29 | + private void OnClick() |
| 30 | + { |
| 31 | + bool result = JoinQQGroup(); |
| 32 | + if (result) |
| 33 | + { |
| 34 | + //TODO 你的业务逻辑 |
| 35 | + } |
| 36 | + else |
| 37 | + { |
| 38 | + Debug.LogWarning("未安装手Q或者版本不支持!"); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// 加入QQ群的方法,有返回值,代表成功或者失败 |
| 44 | + /// </summary> |
| 45 | + /// <returns></returns> |
| 46 | + private bool JoinQQGroup() |
| 47 | + { |
| 48 | +#if !UNITY_EDITOR && UNITY_ANDROID |
| 49 | + return CallAndroidMethod<bool>("joinQQGroup", AndroidKey); |
| 50 | +#elif !UNITY_EIDTOR && UNITY_IOS |
| 51 | + return iOSJoinQQGroup(iOSKey, iOSUid); |
| 52 | +#else |
| 53 | + return false; |
| 54 | +#endif |
| 55 | + } |
| 56 | + |
| 57 | + /// <summary> |
| 58 | + /// 调用一个带有返回值的原生Android方法 |
| 59 | + /// </summary> |
| 60 | + /// <typeparam name="ReturnType"></typeparam> |
| 61 | + /// <param name="method"></param> |
| 62 | + /// <param name="args"></param> |
| 63 | + /// <returns></returns> |
| 64 | + private ReturnType CallAndroidMethod<ReturnType>(string method, params object[] args) |
| 65 | + { |
| 66 | +#if !UNITY_EDITOR && UNITY_ANDROID |
| 67 | + return _jo.Call<ReturnType>(method, args); |
| 68 | +#endif |
| 69 | + return default(ReturnType); |
| 70 | + } |
| 71 | + |
| 72 | + //iOS方法导入 |
| 73 | +#if !UNITY_EDITOR && UNITY_IOS |
| 74 | + [DllImport("__Internal")] |
| 75 | + private static extern bool iOSJoinQQGroup(string key, string uid); |
| 76 | +#endif |
| 77 | + |
| 78 | +} |
0 commit comments