public static bool ForceLoadLowLevelBinary() { // This is a hack that forces Android to load the .so libraries in the correct order #if UNITY_ANDROID && !UNITY_EDITOR FMOD.Studio.UnityUtil.Log("loading binaries: " + FMOD.Studio.STUDIO_VERSION.dll + " and " + FMOD.VERSION.dll); AndroidJavaClass jSystem = new AndroidJavaClass("java.lang.System"); jSystem.CallStatic("loadLibrary", FMOD.VERSION.dll); jSystem.CallStatic("loadLibrary", FMOD.Studio.STUDIO_VERSION.dll); #endif // Hack: force the low level binary to be loaded before accessing Studio API #if !UNITY_IPHONE || UNITY_EDITOR FMOD.Studio.UnityUtil.Log("Attempting to call Memory_GetStats"); int temp1, temp2; if (!ERRCHECK(FMOD.Memory.GetStats(out temp1, out temp2))) { FMOD.Studio.UnityUtil.LogError("Memory_GetStats returned an error"); return false; } FMOD.Studio.UnityUtil.Log("Calling Memory_GetStats succeeded!"); #endif return true; }
void IRedeem.RedeemWithCode(RedeemParameter param, System.Action<RedeemResult, int, RedeemParameter> callback) { callbackContexts.Add(param.Code, new CallbackContext(callback, param)); using (AndroidJavaClass klass = new AndroidJavaClass("com.cocoachina.runningcube.SDK_08")) { klass.CallStatic("RedeemWithCode", "GlobalObject", "OnRedeemResult", param.Code, param.Code); } }
void IExitHandler.OnExit(System.Action<ExitResult> callback) { string context = CallingIndex.ToString(); this.callbackContexts.Add(context, new ExitContext()); CallingIndex ++; using(AndroidJavaClass klass = new AndroidJavaClass("com.cocochina.runningcube.SDK_03")) { klass.CallStatic("Exit", this.gameObject.name, "OnExit", context); } }
void IShop.Buy(BuyParameter param, System.Action<BuyResult, BuyParameter> callback) { string context = CallingIndex.ToString(); this.callbackContexts.Add(context, new PayContext(callback, param)); CallingIndex ++; using(AndroidJavaClass klass = new AndroidJavaClass("com.cocochina.runningcube.SDK_03")) { klass.CallStatic("Pay", this.gameObject.name, "OnPay", context); } }
public static bool ForceLoadLowLevelBinary() { // This is a hack that forces Android to load the .so libraries in the correct order #if UNITY_ANDROID && !UNITY_EDITOR if (FMOD.VERSION.number >= 0x00010500) { AndroidJavaObject activity = null; // First, obtain the current activity context using (var actClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { activity = actClass.GetStatic<AndroidJavaObject>("currentActivity"); } UnityEngine.Debug.Log("FMOD ANDROID AUDIOTRACK: " + (activity == null ? "ERROR NO ACTIVITY" : "VALID ACTIVITY!")); using (var fmodJava = new AndroidJavaClass("org.fmod.FMOD")) { if (fmodJava != null) { UnityEngine.Debug.Log("FMOD ANDROID AUDIOTRACK: assigning activity to fmod java"); fmodJava.CallStatic("init", activity); } else { UnityEngine.Debug.Log("FMOD ANDROID AUDIOTRACK: ERROR NO FMOD JAVA"); } } } FMOD.Studio.UnityUtil.Log("loading binaries: " + FMOD.Studio.STUDIO_VERSION.dll + " and " + FMOD.VERSION.dll); AndroidJavaClass jSystem = new AndroidJavaClass("java.lang.System"); jSystem.CallStatic("loadLibrary", FMOD.VERSION.dll); jSystem.CallStatic("loadLibrary", FMOD.Studio.STUDIO_VERSION.dll); #endif // Hack: force the low level binary to be loaded before accessing Studio API #if !UNITY_IPHONE || UNITY_EDITOR FMOD.Studio.UnityUtil.Log("Attempting to call Memory_GetStats"); int temp1, temp2; if (!ERRCHECK(FMOD.Memory.GetStats(out temp1, out temp2))) { FMOD.Studio.UnityUtil.LogError("Memory_GetStats returned an error"); return false; } FMOD.Studio.UnityUtil.Log("Calling Memory_GetStats succeeded!"); #endif return true; }
// Use: // runOnAndroidUiThread(someMethod) public static void runOnAndroidUiThread(Action target) { // Calls an Android activity on the UI Thread (needed for some interactions with Views) using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { using (var activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity")) { #if USE_ANDROID activity.Call("runOnUiThread", new AndroidJavaRunnable(target)); #else Debug.Log("[Android] Would call [" + target + "] later on the UI thread"); #endif //string a = activity.Call<string>("someNomw", param); //window.Call("setFlags", flagsValue, -1); // (int)0x7FFFFFFF //window.Call("setStatusBarColor", unchecked((int)_statusBarColor)); // for an uint } } }
public static AndroidJavaObject GetAdSizeJavaObject(AdSize adSize) { switch (adSize.AdType) { case AdSize.Type.SmartBanner: #if UNITY_2019_2_OR_NEWER // AndroidJavaClass.GetStatic<AndroidJavaObject>() returns null since Unity 2019.2. // Creates an AdSize object by directly calling the constructor, as a workaround. return(new AndroidJavaObject(AdSizeClassName, -1, -2) .GetStatic <AndroidJavaObject>("SMART_BANNER")); #else return(new AndroidJavaClass(AdSizeClassName) .GetStatic <AndroidJavaObject>("SMART_BANNER")); #endif case AdSize.Type.AnchoredAdaptive: AndroidJavaClass adSizeClass = new AndroidJavaClass(AdSizeClassName); AndroidJavaClass playerClass = new AndroidJavaClass(Utils.UnityActivityClassName); AndroidJavaObject activity = playerClass.GetStatic <AndroidJavaObject>("currentActivity"); switch (adSize.Orientation) { case Orientation.Landscape: return(adSizeClass.CallStatic <AndroidJavaObject>("getLandscapeBannerAdSizeWithWidth", activity, adSize.Width)); case Orientation.Portrait: return(adSizeClass.CallStatic <AndroidJavaObject>("getPortraitBannerAdSizeWithWidth", activity, adSize.Width)); case Orientation.Current: return(adSizeClass.CallStatic <AndroidJavaObject>("getCurrentOrientationBannerAdSizeWithWidth", activity, adSize.Width)); default: throw new ArgumentException("Invalid Orientation provided for ad size."); } case AdSize.Type.Standard: return(new AndroidJavaObject(AdSizeClassName, adSize.Width, adSize.Height)); default: throw new ArgumentException("Invalid AdSize.Type provided for ad size."); } }
private string PrepareAdsUrlQueue(string adsId, int adsLimited) { string text = (!this.isTablet) ? "phone" : "tablet"; int num; try { using (AndroidJavaClass androidJavaClass = new AndroidJavaClass("android.os.Build$VERSION")) { num = androidJavaClass.GetStatic <int>("SDK_INT"); } } catch (Exception) { num = 15; } string text2 = "Android" + num; string text3 = (!string.IsNullOrEmpty(adsId)) ? adsId : string.Empty; string text4 = (adsLimited != -1) ? adsLimited.ToString() : "1"; string text5 = string.Concat(new string[] { "?app_id=coloring&device_type=", text, "&app_ver=", Application.version, "&software_name=", text2, "&advertising_id=", text3, "&isLimitAdTrackingEnabled=", text4, "&alt_id=", SystemInfo.deviceUniqueIdentifier, "&package_name=", SystemUtils.GetAppPackage() }); text5 = Uri.EscapeUriString(text5); FMLogger.vAds(text5); return(text5); }
private void OnInvitationInboxResult(bool success, string invitationId) { Logger.d(string.Concat(new object[] { "AndroidRtmpClient.OnInvitationInboxResult, success=", success, ", invitationId=", invitationId })); if (!this.CheckRtmpActive("OnInvitationInboxResult")) { return; } this.mLaunchedExternalActivity = false; if (!success || invitationId == null || invitationId.Length == 0) { Logger.w("Failed to setup room because invitation inbox UI failed."); this.FailRoomSetup("Invitation inbox UI failed."); return; } this.mClient.ClearInvitationIfFromNotification(invitationId); this.mClient.CallClientApi("accept invite from inbox", delegate { Logger.d("Accepting invite from inbox via support lib."); AndroidJavaClass @class = JavaUtil.GetClass("com.google.example.games.pluginsupport.RtmpUtils"); @class.CallStatic("accept", new object[] { this.mClient.GHManager.GetApiClient(), invitationId, new AndroidRtmpClient.RoomUpdateProxy(this), new AndroidRtmpClient.RoomStatusUpdateProxy(this), new AndroidRtmpClient.RealTimeMessageReceivedProxy(this) }); }, delegate(bool ok) { if (!ok) { this.FailRoomSetup("GoogleApiClient lost connection."); } }); }
public System.Collections.IEnumerator ShareTextInAnroid() { string gameURL = "https://play.google.com/store/apps/details?id=" + Application.identifier; Debug.Log(gameURL); var shareSubject = "Kore ile alakalı harika bir oyun buldum!"; var shareMessage = "Hey! Kore ile alakalı harika bir oyun buldum! \nEğer sende bu oyunu denemek istiyorsan hemen indir. " + " \nKOREGAME\n\n" + gameURL; isProcessing = true; if (!Application.isEditor) { //Create intent for action send AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent"); AndroidJavaObject intentObject = new AndroidJavaObject("android.content.Intent"); intentObject.Call <AndroidJavaObject> ("setAction", intentClass.GetStatic <string>("ACTION_SEND")); //put text and subject extra intentObject.Call <AndroidJavaObject>("setType", "text/plain"); intentObject.Call <AndroidJavaObject>("putExtra", intentClass.GetStatic <string>("EXTRA_SUBJECT"), shareSubject); intentObject.Call <AndroidJavaObject>("putExtra", intentClass.GetStatic <string>("EXTRA_TEXT"), shareMessage); //call createChooser method of activity class AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject currentActivity = unity.GetStatic <AndroidJavaObject>("currentActivity"); AndroidJavaObject chooser = intentClass.CallStatic <AndroidJavaObject>("createChooser", intentObject, "Share your high score"); currentActivity.Call("startActivity", chooser); } yield return(new WaitUntil(() => isFocus)); isProcessing = false; }
public static bool OpenAppScheme(string packageName, string scheme) { bool result; using (AndroidJavaClass androidJavaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { using (AndroidJavaObject @static = androidJavaClass.GetStatic <AndroidJavaObject>("currentActivity")) { using (AndroidJavaClass androidJavaClass2 = new AndroidJavaClass("jp.crooz.neptune.NPEtcetera")) { result = androidJavaClass2.CallStatic <bool>("openAppScheme", new object[] { packageName, scheme, @static }); } } } return(result); }
protected override void _pushEventGetFeedFinished(Provider provider, SocialPageData <String> feedPage, string payload) { if (SoomlaProfile.IsProviderNativelyImplemented(provider)) { return; } List <JSONObject> feeds = new List <JSONObject>(); foreach (var feed in feedPage.PageData) { feeds.Add(JSONObject.StringObject(feed)); } JSONObject feedJson = new JSONObject(feeds.ToArray()); AndroidJNI.PushLocalFrame(100); using (AndroidJavaClass jniSoomlaProfile = new AndroidJavaClass("com.soomla.profile.unity.ProfileEventHandler")) { ProfileJNIHandler.CallStaticVoid(jniSoomlaProfile, "pushEventGetFeedFinished", provider.ToString(), feedJson.ToString(), payload, feedPage.HasMore); } AndroidJNI.PopLocalFrame(IntPtr.Zero); }
/// <summary> /// Initializes a new instance of the Android platform class. /// </summary> /// <param name="targetName">The name of the game object which will receive native callbacks</param> /// <param name="methodName">The method of the game object which will be called from the native code</param> /// <param name="version">Plugin version</param> /// <param name="capacity">Console capacity (elements over this amount will be trimmed)</param> /// <param name="trim">Console trim amount (how many elements will be trimmed on the overflow)</param> /// <param name="gesture">Gesture name to activate the console</param> public PlatformAndroid(string targetName, string methodName, string version, int capacity, int trim, string gesture) { pluginClass = new AndroidJavaClass(PluginClassName); pluginClassRaw = pluginClass.GetRawClass(); IntPtr methodInit = GetStaticMethod(pluginClassRaw, "init", "(Ljava.lang.String;Ljava.lang.String;Ljava.lang.String;IILjava.lang.String;)V"); CallStaticVoidMethod(methodInit, new jvalue[] { jval(targetName), jval(methodName), jval(version), jval(capacity), jval(trim), jval(gesture) }); methodLogMessage = GetStaticMethod(pluginClassRaw, "logMessage", "(Ljava.lang.String;Ljava.lang.String;I)V"); methodShowConsole = GetStaticMethod(pluginClassRaw, "show", "()V"); methodHideConsole = GetStaticMethod(pluginClassRaw, "hide", "()V"); methodClearConsole = GetStaticMethod(pluginClassRaw, "clear", "()V"); }
/// <summary> /// Show an Android toast message. /// </summary> /// <param name="message">Message string to show in the toast.</param> /// <param name="length">Toast message time length.</param> public static void _ShowAndroidToastMessage(string message) { AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject unityActivity = unityPlayer.GetStatic <AndroidJavaObject>("currentActivity"); if (unityActivity != null) { AndroidJavaClass toastClass = new AndroidJavaClass("android.widget.Toast"); unityActivity.Call("runOnUiThread", new AndroidJavaRunnable(() => { AndroidJavaObject toastObject = toastClass.CallStatic <AndroidJavaObject>( "makeText", unityActivity, message, 0); toastObject.Call("show"); })); } }
public static void Init() { AudioCallbackWrapper.CreateAudioManager(); #if !UNITY_EDITOR #if UNITY_ANDROID using (AndroidJavaClass cls = new AndroidJavaClass(JAVA_AUDIO_CLASS)) { cls.CallStatic("Init"); MAX_SYSTEM_VOLUME = cls.CallStatic <int>("AndroidGetMaxSystemStreamVolume"); MAX_VOICE_VOLUME = cls.CallStatic <int>("AndroidGetMaxVoiceStreamVolume"); MAX_MUSIC_VOLUME = cls.CallStatic <int>("AndroidGetMaxMusicStreamVolume"); } #elif UNITY_IPHONE //Init(); #endif #else MAX_MUSIC_VOLUME = 100; MAX_SYSTEM_VOLUME = 100; MAX_VOICE_VOLUME = 100; #endif }
public override string GetCodeVersion() { try { Dictionary <string, object> statDict; var sdkObj = _actObj.Call <AndroidJavaObject>("getSdkModel"); var utilsCls = new AndroidJavaClass(CODE_PACKAGE + ".util.PlatformUtils"); //init stat var statJsonStr = utilsCls.CallStatic <string>("getStatistics"); statDict = MiniJSON.Json.Deserialize(statJsonStr) as Dictionary <string, object>; sdkObj.Dispose(); utilsCls.Dispose(); return(statDict["version_code"] as string); } catch (System.Exception e) { Logger.Error("GameStart.GetVersionCode Init error: {0}", e.ToString()); } return(null); }
/// <summary> /// Initializes the SOOMLA Vungle plugin. /// </summary> public static void Initialize() { #if UNITY_ANDROID && !UNITY_EDITOR SoomlaUtils.LogDebug(TAG, "Starting Vungle for: " + VungleSettings.VungleAppIdAndroid); AndroidJNI.PushLocalFrame(100); // Initializing SoomlaEventHandler using (AndroidJavaClass jniEventHandler = new AndroidJavaClass("com.soomla.core.unity.SoomlaVungleEventHandler")) { jniEventHandler.CallStatic("initialize"); } using (AndroidJavaClass jniSoomlaVungleClass = new AndroidJavaClass("com.soomla.plugins.ads.vungle.SoomlaVungle")) { using (AndroidJavaObject jniSoomlaVungle = jniSoomlaVungleClass.CallStatic <AndroidJavaObject>("getInstance")) { jniSoomlaVungle.Call("initialize", VungleSettings.VungleAppIdAndroid); } } AndroidJNI.PopLocalFrame(IntPtr.Zero); #elif UNITY_IOS && !UNITY_EDITOR SoomlaUtils.LogDebug(TAG, "Starting Vungle for: " + VungleSettings.VungleAppIdiOS); soomlaVungle_Init(VungleSettings.VungleAppIdiOS); #endif }
/// <summary> /// 向剪贴板中添加文本 /// </summary> /// <param name="str"></param> public static void CopyTextToClipboard(string str) { if (str == null || str == "") { return; } #if !UNITY_EDITOR #if UNITY_ANDROID using (AndroidJavaClass GameTools = new AndroidJavaClass("com.wmhd.tools.GameTools")) { AndroidJavaObject currentActivity = getApplicationContext(); if (currentActivity != null) { GameTools.CallStatic("copyTextToClipboard", currentActivity, str); } } #elif UNITY_IPHONE copyTextToClipboard(str); #endif #endif }
// Must be launched from the game thread (otherwise the classloader cannot locate the unity // java classes we require). private void LaunchBridgeIntent(IntPtr bridgedIntent) { object[] objectArray = new object[2]; jvalue[] jArgs = AndroidJNIHelper.CreateJNIArgArray(objectArray); try { using (var bridgeClass = new AndroidJavaClass(BridgeActivityClass)) { using (var currentActivity = GetActivity()) { // Unity no longer supports constructing an AndroidJavaObject using an IntPtr, // so I have to manually munge with JNI here. IntPtr methodId = AndroidJNI.GetStaticMethodID(bridgeClass.GetRawClass(), LaunchBridgeMethod, LaunchBridgeSignature); jArgs[0].l = currentActivity.GetRawObject(); jArgs[1].l = bridgedIntent; AndroidJNI.CallStaticVoidMethod(bridgeClass.GetRawClass(), methodId, jArgs); } } } finally { AndroidJNIHelper.DeleteJNIArgArray(objectArray, jArgs); } }
// Use this for initialization private void Start() { anchorLocateCriteria = new AnchorLocateCriteria(); #if UNITY_IOS arkitSession = UnityARSessionNativeInterface.GetARSessionNativeInterface(); UnityARSessionNativeInterface.ARFrameUpdatedEvent += UnityARSessionNativeInterface_ARFrameUpdatedEvent; #endif #if UNITY_ANDROID UnityAndroidHelper.Instance.DispatchUiThread(unityActivity => { using (AndroidJavaClass cloudServices = new AndroidJavaClass("com.microsoft.CloudServices")) { cloudServices.CallStatic("initialize", unityActivity); this.CreateNewCloudSession(); } }); #else CreateNewCloudSession(); #endif }
public NativeImplementationAndroid() { AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); if (jc == null) { Debug.LogError("Could not find class com.unity3d.player.UnityPlayer!"); } // find the plugin instance m_javaActivity = jc.GetStatic <AndroidJavaObject>("currentActivity"); if (m_javaActivity == null) { Debug.LogError("Could not find currentActivity!"); } using (var nativeClass = new AndroidJavaClass("com.softliu.hlsun.SoftLiuNative")) { m_javaNative = nativeClass.CallStatic <AndroidJavaObject>("Init", m_javaActivity); } }
/// <summary> /// 获取Lua文件缓存目录 /// </summary> /// <returns>换粗目录对象.</returns> private AndroidJavaObject getLuaCacheDir() { AndroidJavaObject currentActivity = getCurrentActivity(); AndroidJavaClass EnvironmentClass = new AndroidJavaClass("android.os.Environment"); int perm = currentActivity.Call <int> ("checkCallingOrSelfPermission", new object[] { "android.permission.WRITE_EXTERNAL_STORAGE" }); AndroidJavaObject cacheDir = null; if ("mounted" == EnvironmentClass.CallStatic <string> ("getExternalStorageState", new object[0]) && perm == 0) { cacheDir = currentActivity.Call <AndroidJavaObject> ("getExternalCacheDir", new object[0]); } if (cacheDir == null) { cacheDir = currentActivity.Call <AndroidJavaObject> ("getCacheDir", new object[0]); } return(new AndroidJavaObject("java.io.File", string.Format("{0}/lua", cacheDir.Call <string>("toString", new object[0])))); }
/// <summary> /// Gets the unity activity. /// </summary> /// <returns>The unity activity.</returns> public static AndroidJavaObject GetUnityActivity() { #if ANDROID_DEVICE if (m_unityActivity == null) { try { AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); m_unityActivity = unityPlayer.GetStatic <AndroidJavaObject>("currentActivity"); } catch (AndroidJavaException e) { Debug.Log("AndroidJavaException : " + e.Message); m_unityActivity = null; } } return(m_unityActivity); #else return(null); #endif }
static string GetStringProperty(string propertyName) { if (AGUtils.IsNotAndroidCheck()) { return(string.Empty); } try { using (var env = new AndroidJavaClass(C.AndroidOsEnvironment)) { return(env.GetStaticStr(propertyName)); } } catch (Exception e) { Debug.LogWarning("Could not get the property: " + propertyName + ". Check the device API level if the property is present, reason: " + e.Message); return(string.Empty); } }
/// <summary> /// Shows the android toast message. /// </summary> /// <param name="message">Message string to show in the toast.</param> /// <param name="length">Toast message time length.</param> private static void _ShowAndroidToastMessage(string message, ToastLength length) { AndroidJavaObject unityActivity = GetUnityActivity(); if (unityActivity != null) { try { AndroidJavaClass toastClass = new AndroidJavaClass("android.widget.Toast"); unityActivity.Call("runOnUiThread", new AndroidJavaRunnable(() => { AndroidJavaObject toastObject = toastClass.CallStatic <AndroidJavaObject>("makeText", unityActivity, message, (int)length); toastObject.Call("show"); })); } catch (AndroidJavaException e) { Debug.Log("AndroidJavaException : " + e.Message); } } }
/// <summary> /// 获取设备号 /// </summary> /// <returns></returns> public static string GetDeviceID() { #if UNITY_IOS return(getDeviceId()); #endif #if UNITY_ANDROID && !UNITY_EDITOR string str = "unknown"; using (AndroidJavaClass GameTools = new AndroidJavaClass("com.wmhd.tools.GameTools")) { AndroidJavaObject currentActivity = getApplicationContext(); if (currentActivity != null) { str = GameTools.CallStatic <string>("getDeviceID", currentActivity); } } return(str); #endif return("unknown"); }
/// <summary> /// Plays a video ad and grants the user a reward for watching it. /// </summary> /// <param name="reward">The reward that will be given to users for watching the video ad.</param> /// <param name="enableBackButton">Determines whether you would like to give the user the /// option to skip out of the video. <c>true</c> means a close button will be displayed.</param> public static bool HasAds() { SoomlaUtils.LogDebug(TAG, "Checking if Vungle has Ads to show."); #if UNITY_ANDROID && !UNITY_EDITOR bool answer = false; AndroidJNI.PushLocalFrame(100); using (AndroidJavaClass jniSoomlaVungleClass = new AndroidJavaClass("com.soomla.plugins.ads.vungle.SoomlaVungle")) { using (AndroidJavaObject jniSoomlaVungle = jniSoomlaVungleClass.CallStatic <AndroidJavaObject>("getInstance")) { answer = jniSoomlaVungle.Call <bool>("hasAds"); } } AndroidJNI.PopLocalFrame(IntPtr.Zero); return(answer); #elif UNITY_IOS && !UNITY_EDITOR return(soomlaVungle_HasAds()); #else return(false); #endif }
public static void Initialize() { #if UNITY_ANDROID && !UNITY_EDITOR using (AndroidJavaClass activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { using (AndroidJavaObject activityContext = activityClass.GetStatic <AndroidJavaObject>("currentActivity")) { using (AndroidJavaClass pluginClass = new AndroidJavaClass("com.mykaelos.unityandroidvibrator.Vibrator")) { if (pluginClass != null) { VibratorInstance = pluginClass.CallStatic <AndroidJavaObject>("getInstance"); VibratorInstance.Call("setContext", activityContext); } } } } if (VibratorInstance == null) { Debug.Log("UnityAndroidVibratorBridge: Failed to setup the UnityAndroidVibrator."); } #endif }
public AdLoaderClient(AdLoader unityAdLoader) : base(Utils.UnityAdLoaderListenerClassName) { AndroidJavaClass playerClass = new AndroidJavaClass(Utils.UnityActivityClassName); AndroidJavaObject activity = playerClass.GetStatic <AndroidJavaObject>("currentActivity"); adLoader = new AndroidJavaObject(Utils.NativeAdLoaderClassName, activity, unityAdLoader.AdUnitId, this); this.CustomNativeTemplateCallbacks = unityAdLoader.CustomNativeTemplateClickHandlers; if (unityAdLoader.AdTypes.Contains(NativeAdType.CustomTemplate)) { foreach (string templateId in unityAdLoader.TemplateIds) { adLoader.Call("configureCustomNativeTemplateAd", templateId, this.CustomNativeTemplateCallbacks.ContainsKey(templateId)); } } adLoader.Call("create"); }
protected override void _pushEventGetContactsFinished(Provider provider, SocialPageData <UserProfile> contactsPage, string payload) { if (SoomlaProfile.IsProviderNativelyImplemented(provider)) { return; } List <JSONObject> profiles = new List <JSONObject>(); foreach (var profile in contactsPage.PageData) { profiles.Add(profile.toJSONObject()); } JSONObject contacts = new JSONObject(profiles.ToArray()); AndroidJNI.PushLocalFrame(100); using (AndroidJavaClass jniSoomlaProfile = new AndroidJavaClass("com.soomla.profile.unity.ProfileEventHandler")) { ProfileJNIHandler.CallStaticVoid(jniSoomlaProfile, "pushEventGetContactsFinished", provider.ToString(), contacts.ToString(), payload, contactsPage.HasMore); } AndroidJNI.PopLocalFrame(IntPtr.Zero); }
public int AdjustBottomMargin(int bottom) { if (!mIsKeyboardVisible) { return(bottom); } else { int keyboardHeight = 0; using (AndroidJavaClass UnityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { AndroidJavaObject View = UnityClass.GetStatic <AndroidJavaObject>("currentActivity").Get <AndroidJavaObject>("mUnityPlayer").Call <AndroidJavaObject>("getView"); using (AndroidJavaObject Rct = new AndroidJavaObject("android.graphics.Rect")) { View.Call("getWindowVisibleDisplayFrame", Rct); keyboardHeight = View.Call <int>("getHeight") - Rct.Call <int>("height"); } } return((bottom > keyboardHeight) ? bottom : keyboardHeight); } }
//获取安卓磁盘大小 测试代码 public static void TestGetAndroidSize() { #if !UNITY_EDITOR && UNITY_ANDROID AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject jo = jc.GetStatic <AndroidJavaObject> ("currentActivity"); //获取总磁盘大小 long allSize = jo.Call <long> ("getTotalInternalAllMemorySize"); //获取可用总磁盘大小 long avoidsize = jo.Call <long> ("getTotalInternalAvodiMemorySize"); bool isGet = jo.Call <bool> ("isExternalStorageAvailable"); //获取系统磁盘大小 long sysAllSize = jo.Call <long> ("readSystemAllSize"); //获取可用系统磁盘大小 long sysAvaliSize = jo.Call <long> ("readSystemAvailSize"); //获取SD卡磁盘大小[测试后较准。推荐] long SdAllSize = jo.Call <long> ("readSDCardAllSize"); //获取可用SD卡磁盘大小[测试后较准。推荐] long SdAvaliSize = jo.Call <long> ("readSDCardAvailSize"); //TraceUtil.Log ("==========================isGet==="+isGet+"allSize="+allSize+"avoidsize="+avoidsize+"sysAllSize="+sysAllSize+"sysAvaliSize="+sysAvaliSize+"SdAllSize="+SdAllSize+"SdAvaliSize="+SdAvaliSize); #endif }
void UpdateUsed() { sUserMemory = ""; #if UNITY_EDITOR MonoUsedM = (uint)(Profiler.GetMonoUsedSize() / m_KBSize); AllMemory = (uint)(Profiler.GetTotalAllocatedMemory() / m_KBSize); sUserMemory += "MonoUsed:" + MonoUsedM + "M\nAllMemory:" + AllMemory + "M\n"; #elif UNITY_ANDROID using (AndroidJavaClass jc = new AndroidJavaClass("com.keefor.tool.DebugTools")) { AllMemory = (uint)(jc.CallStatic <long>("getTotalMemory") / 1024); MonoUsedM = (uint)(jc.CallStatic <long>("getUsedMemory") / 1024); sUserMemory += "TotalMemory:" + AllMemory + "K\nUseMemory:" + MonoUsedM + "K\n"; } #endif sUserMemory += "UnUsedReserved:" + Profiler.GetTotalUnusedReservedMemory() / m_KBSize + "M" + "\n"; }
private void OpenExternBrowser() { if (Application.platform == RuntimePlatform.Android) { var url = "www.ribbonchase.top"; AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject jo = jc.GetStatic <AndroidJavaObject>("currentActivity"); var content = jo.Call <string>("getHTML", url); string pattern = @"<!--Version=(.*?)-->"; string matchString = null; foreach (Match match in Regex.Matches(content, pattern)) { matchString = match.Value; } var versionName = matchString.Substring(13, 7); AndroidJavaClass jc1 = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject jo1 = jc1.GetStatic <AndroidJavaObject>("currentActivity"); jo1.Call("DownloadAPK", "http://104.236.215.170/RibbonChaseV" + versionName + ".apk"); } }
public DisplayMetrics() { using ( AndroidJavaClass unityPlayerClass = new AndroidJavaClass(Utils.UnityActivityClassName), metricsClass = new AndroidJavaClass(Utils.DisplayMetricsClassName) ) { using ( AndroidJavaObject metricsInstance = new AndroidJavaObject(Utils.DisplayMetricsClassName), activityInstance = unityPlayerClass.GetStatic <AndroidJavaObject>("currentActivity"), windowManagerInstance = activityInstance.Call <AndroidJavaObject>("getWindowManager"), displayInstance = windowManagerInstance.Call <AndroidJavaObject>("getDefaultDisplay") ) { displayInstance.Call("getMetrics", metricsInstance); Density = metricsInstance.Get <float>("density"); HeightPixels = metricsInstance.Get <int>("heightPixels"); WidthPixels = metricsInstance.Get <int>("widthPixels"); } } }
public static string GetDeviceId() { //if the platform is real device // string ret = null; if (deviceId == null && Application.platform != RuntimePlatform.OSXEditor && Application.platform != RuntimePlatform.WindowsEditor) { #if UNITY_IPHONE deviceId = _tdgaGetDeviceId(); #elif UNITY_ANDROID if (agent == null) { agent = new AndroidJavaClass(JAVA_CLASS); } AndroidJavaObject activity = unityClass.GetStatic <AndroidJavaObject>("currentActivity"); deviceId = agent.CallStatic <string>("getDeviceId", activity); #elif UNITY_WP8 deviceId = TalkingDataGAWP.TalkingDataGA.getDeviceID(); #endif } return(deviceId); }
public void HasChanged() { cont_items_ubicados_correct = 0; cont_items_en_slots = 0; lista_objetos = new int[8];//OJO CADA FASE TIENE UN NUMERO DIFERENTE DE PASOS int contad = 0; Debug.Log ("Se ha notificado de un cambio en CanvasProcessManagerEval organizando pasos"); foreach (Transform slotTransform in slots) { item_slot = slotTransform.GetComponent<SlotsBehaviourMenuStepsPhaseTwo>().slot_con_objeto_correcto; id_paso = slotTransform.GetComponent<SlotsBehaviourMenuStepsPhaseTwo>().id_of_step_in_slot; lista_objetos[contad] = id_paso; contad++; //Debug.Log ("Se ha obtenido el componente SlotsBehaviour en CanvasProcessManagerEval organizando pasos"); if(item_slot){ Debug.Log ("Los pasos estan correctamente ordenados en CanvasProcessManagerEval organizando pasos"); cont_items_ubicados_correct++; } if(slotTransform.childCount > 0){ cont_items_en_slots++; } } Debug.Log ("CanvasProcessPhasesManagEval: Cantidad de items correctamente ubicados: " + cont_items_ubicados_correct); Debug.Log ("Cantidad de items en slots:" + cont_items_en_slots); if (cont_items_ubicados_correct == 8) items_ubicados_correctamente = true; else items_ubicados_correctamente = false; Debug.Log ("CanvasProcessPhasesManagEval: Se va a definir en el manager organizacion correcta de fases = " + items_ubicados_correctamente); if (items_ubicados_correctamente) { if (tickCorrectOrder != null){ tickCorrectOrder.GetComponent<Image>().sprite = img_tick; tickCorrectOrder.enabled = true; } this.NotifyStepsOrganized (true); if(!steps_organized_from_manager){ Debug.Log ("Ingresa al metodo para bloquear los pasos por organizacion automatica del appmanager"); //inactivando los pasos para que el estudiante no pueda acceder a cualquier otro sino al primero //inicialmente: if(imgs_gray_random.Length >= 8){ Debug.Log ("Ingresa a deshabilitar los botones "); Debug.Log ("Numero step_btn_one=" + step_number_btn_one); if(step_number_btn_one != 1) this.btn_one_to_order.interactable = false; img_gray_step = Resources.Load<Sprite>(imgs_gray_random[0]); if(img_gray_step != null) this.btn_one_to_order.GetComponent<Image>().sprite = img_gray_step; Debug.Log ("Numero step_btn_two=" + step_number_btn_two); if(step_number_btn_two != 1){ this.btn_two_to_order.interactable = false; } img_gray_step = Resources.Load<Sprite>(imgs_gray_random[1]); if(img_gray_step != null) this.btn_two_to_order.GetComponent<Image>().sprite = img_gray_step; Debug.Log ("Numero step_btn_three=" + step_number_btn_three); if(step_number_btn_three != 1){ this.btn_three_to_order.interactable = false; } img_gray_step = Resources.Load<Sprite>(imgs_gray_random[2]); if(img_gray_step != null) this.btn_three_to_order.GetComponent<Image>().sprite = img_gray_step; Debug.Log ("Numero step_btn_four=" + step_number_btn_four); if(step_number_btn_four != 1){ this.btn_four_to_order.interactable = false; } img_gray_step = Resources.Load<Sprite>(imgs_gray_random[3]); if(img_gray_step != null) this.btn_four_to_order.GetComponent<Image>().sprite = img_gray_step; Debug.Log ("Numero step_btn_five=" + step_number_btn_five); if(step_number_btn_five != 1){ this.btn_five_to_order.interactable = false; } img_gray_step = Resources.Load<Sprite>(imgs_gray_random[4]); if(img_gray_step != null) this.btn_five_to_order.GetComponent<Image>().sprite = img_gray_step; Debug.Log ("Numero step_btn_six=" + step_number_btn_six); if(step_number_btn_six != 1){ this.btn_six_to_order.interactable = false; } img_gray_step = Resources.Load<Sprite>(imgs_gray_random[5]); if(img_gray_step != null) this.btn_six_to_order.GetComponent<Image>().sprite = img_gray_step; Debug.Log ("Numero step_btn_seven=" + step_number_btn_seven); if(step_number_btn_seven != 1){ this.btn_seven_to_order.interactable = false; } img_gray_step = Resources.Load<Sprite>(imgs_gray_random[6]); if(img_gray_step != null) this.btn_seven_to_order.GetComponent<Image>().sprite = img_gray_step; Debug.Log ("Numero step_btn_eight=" + step_number_btn_eight); if(step_number_btn_eight != 1){ this.btn_eight_to_order.interactable = false; } img_gray_step = Resources.Load<Sprite>(imgs_gray_random[7]); if(img_gray_step != null) this.btn_eight_to_order.GetComponent<Image>().sprite = img_gray_step; } else { Debug.Log ("MenuOfStepsPhaseOneManager: El vector de imagenes en GRIS es NULO"); } }//cierra if interno que valida si se ha pedido organizar los pasos desde el app-manager } else { if (tickCorrectOrder != null) tickCorrectOrder.enabled = false; if(cont_items_en_slots == 8){ tickCorrectOrder.GetComponent<Image>().sprite = img_warning; tickCorrectOrder.enabled = true; } this.NotifyStepsOrganized (false); } Debug.Log ("MenuOfStepsPhaseTwoEval: Los items estan correctamente ubicados? = " + items_ubicados_correctamente); //se va a obtener la secuencia del orden de pasos secuencia_pasos = ""; if (lista_objetos.Length >= 8 && cont_items_en_slots >= 8) { //recorriendo la secuencia de pasos como esta organizados actualmente: Debug.Log ("La capacidad de la lista es: " + lista_objetos.Length ); for (int i=0; i<lista_objetos.Length; i++) { Debug.Log ("Secuencia de pasos en i= "+i+"= " + lista_objetos [i]); elemento_secuencia = lista_objetos [i].ToString(); if (i == 0) secuencia_pasos = secuencia_pasos + elemento_secuencia; else secuencia_pasos = secuencia_pasos + "-" + elemento_secuencia; } //intentando guardar en la BD: Debug.Log ("Se va a solicitar guardar la secuencia en la BD:"); var and_unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); var current_act = and_unity.GetStatic<AndroidJavaObject>("currentActivity"); Debug.Log("Se ha obtenido current activity..."); // Accessing the class to call a static method on it var save_todb_activity = new AndroidJavaClass("edu.udg.bcds.pintura.arapp.SaveDatabaseData"); Debug.Log ("Se ha obtenido StartActivity..."); Debug.Log ("Se va a intentar obtener la fecha..."); string fecha = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); Debug.Log ("La fecha obtenida es: " + fecha); object[] parameters = new object[3]; parameters [0] = current_act; //pasando el argumento de la actividad actual que se debe reproducir parameters [1] = fecha; //pasando el argumento de la fecha y hora actual parameters [2] = secuencia_pasos; //enviando // Se llama al metodo estatico de android que almacena la secuencia en la base de datos: save_todb_activity.CallStatic("SaveStepsPhaseTwoSeqToDB", parameters); } else { Debug.Log ("La lista de elementos para la secuencia aun NO ESTA COMPLETA items_en_slots =" + cont_items_en_slots ); } }
public void Init(string appId, string responder) { jiverClass = new AndroidJavaClass("com.smilefam.jia.Jiver"); jiverClass.CallStatic ("init", appId); jiverClass.CallStatic ("setUnityResponder", responder); }
void loadLowLevelBinary() { // This is a hack that forces Android to load the .so libraries in the correct order #if UNITY_ANDROID && !UNITY_EDITOR Debug.Log("loading binaries: " + FMOD.Studio.STUDIO_VERSION.dll + " and " + FMOD.VERSION.dll); AndroidJavaClass jSystem = new AndroidJavaClass("java.lang.System"); jSystem.CallStatic("loadLibrary", FMOD.VERSION.dll); jSystem.CallStatic("loadLibrary", FMOD.Studio.STUDIO_VERSION.dll); #endif // This is a hack that forces Unity to load the lowlevel dylib (required for mac) int temp1 = 0, temp2 = 0; #if !UNITY_IPHONE || UNITY_EDITOR //Debug.Log("calling memory getStats"); FMOD.Memory.GetStats(ref temp1, ref temp2); #endif }