Skip to content

Instantly share code, notes, and snippets.

@SoftwareGuy
Forked from ChrisNZL/Platform_AndroidTV.cs
Created December 8, 2023 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SoftwareGuy/40985871ec9f1a6707051b91b474282c to your computer and use it in GitHub Desktop.
Save SoftwareGuy/40985871ec9f1a6707051b91b474282c to your computer and use it in GitHub Desktop.
Detects Android TV using Unity.
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