Last active
December 8, 2023 10:49
-
-
Save ChrisNZL/bf4ef75a4922557bbef69efde26525f3 to your computer and use it in GitHub Desktop.
Detects Android TV using Unity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
// DERIVED FROM https://stewmcc.com/post/check-for-android-tv-in-unity/ | |
public class Platform_AndroidTV : MonoBehaviour { | |
#if UNITY_ANDROID | |
sbyte isAndroidTV = -1; // -1 == not checked yet; 0 == false; 1 == true | |
#if !UNITY_EDITOR | |
AndroidJavaClass androidUnityActivity = null; | |
AndroidJavaObject GetUnityActivity () { | |
if (androidUnityActivity == null) { | |
androidUnityActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); | |
} | |
return androidUnityActivity.GetStatic<AndroidJavaObject>("currentActivity"); | |
} | |
#endif | |
#endif | |
public bool IsAndroidTV { | |
get { | |
#if UNITY_ANDROID | |
switch (isAndroidTV) { | |
case 0: return false; | |
case 1: return true; | |
} | |
#if !UNITY_EDITOR | |
try { | |
using (AndroidJavaObject context = GetUnityActivity().Call<AndroidJavaObject>("getApplicationContext")) | |
using (AndroidJavaObject packageManager = context.Call<AndroidJavaObject>("getPackageManager")) { | |
const string hasSystemFeature = "hasSystemFeature"; | |
bool isTv = packageManager.Call<bool>(hasSystemFeature, "android.software.leanback") || | |
packageManager.Call<bool>(hasSystemFeature, "android.hardware.type.television"); | |
isAndroidTV = isTv ? (sbyte)1 : (sbyte)0; | |
Debug.Log($"Platform_AndroidTV: Using native Android calls, isAndroidTV is {isAndroidTV}."); | |
} | |
} | |
catch (System.Exception e) { | |
Debug.LogWarning($"WARNING: Platform_AndroidTV: Failed to use native Android calls. {e}"); | |
} | |
if (isAndroidTV == 1) { | |
return true; | |
} | |
#endif | |
const string TV = "TV"; | |
if (SystemInfo.deviceName.Contains(TV) || SystemInfo.deviceModel.Contains(TV)) { | |
isAndroidTV = 1; | |
Debug.Log("Platform_AndroidTV: Is a TV, according to SystemInfo."); | |
return true; | |
} | |
isAndroidTV = 0; | |
Debug.Log("Platform_AndroidTV: Not a TV."); | |
#endif | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment