Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Forked from ChrisNZL/Platform_AndroidTV.cs
Created July 17, 2022 08:06
Show Gist options
  • Select an option

  • Save unitycoder/dc49ab23c2774c7ad6648922937787c2 to your computer and use it in GitHub Desktop.

Select an option

Save unitycoder/dc49ab23c2774c7ad6648922937787c2 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