我的应用程序设计为在手机和平​​板电脑中使用纵向模式。我正在尝试支持需要横向模式的Android TV,因此我的应用现在根据设备是否为Android TV使用不同的布局。

问题是Google拒绝了Android TV中使用“人像”功能的应用。如何保留手机/平板电脑的“人像”,并仅针对具有相同APK的电视切换到横向?是制作两个不同APK的唯一方法吗?如果可能的话,我想避免这种情况。

PS。我正在使用Unity 3D,这可能会限制一些更晦涩的解决方案。

最佳答案

您可以根据设备是手机/平板电脑还是电视,通过代码设置屏幕模式。

第一步是检查该应用程序是否在电视或移动设备上运行。在Android上没有官方API可以执行此操作,但是this帖子介绍了如何使用AndroidJavaClass作为插件来执行此操作。

bool isAndroidTv()
{
    #if !UNITY_ANDROID || UNITY_EDITOR
    return false;
    #else

    AndroidJavaClass unityPlayerJavaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject androidActivity = unityPlayerJavaClass.GetStatic<AndroidJavaObject>("currentActivity");
    AndroidJavaClass contextJavaClass = new AndroidJavaClass("android.content.Context");
    AndroidJavaObject modeServiceConst = contextJavaClass.GetStatic<AndroidJavaObject>("UI_MODE_SERVICE");
    AndroidJavaObject uiModeManager = androidActivity.Call<AndroidJavaObject>("getSystemService", modeServiceConst);
    int currentModeType = uiModeManager.Call<int>("getCurrentModeType");
    AndroidJavaClass configurationAndroidClass = new AndroidJavaClass("android.content.res.Configuration");
    int modeTypeTelevisionConst = configurationAndroidClass.GetStatic<int>("UI_MODE_TYPE_TELEVISION");

    return (modeTypeTelevisionConst == currentModeType);
    #endif
}


然后,您可以在Screen.orientation功能中使用Awake更改屏幕方向:

void Awake()
{
    bool androidTv = isAndroidTv();
    Screen.autorotateToLandscapeLeft = androidTv;
    Screen.autorotateToLandscapeRight = false;
    Screen.autorotateToPortrait = !androidTv;
    Screen.autorotateToPortraitUpsideDown = false;

    if (androidTv)
    {
        Screen.orientation = ScreenOrientation.LandscapeLeft;
    }
    else
    {
        Screen.orientation = ScreenOrientation.Portrait;
    }
}


您可以在“游戏控制器”对象中使用此对象,该对象设置为可以通过脚本顺序设置尽早运行。

另外,您需要将Android播放器设置设为将“默认方向”设置为“自动旋转”。

07-26 09:33
查看更多