在安卓设备上使用JavaScript检测方向

6
使用来自这个问题的一些代码,我设置了一些代码来检测当Android设备旋转时。它在华硕平板电脑(4.0.3)和两个模拟器(4.0.3和2.1)上运行得很好,但对于Kindle Fire(2.3.4)和Droidx(2.3.4),它会切换宽度和高度。
代码:
<script type="text/javascript">
    var supportsOrientationChange = "onorientationchange" in window,orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

    window.addEventListener(orientationEvent, function() {
        alert("The rotation is " + window.orientation + " and the resolution is " + screen.width + " x " + screen.height);
        modRule();
    }, false);
</script>

华硕平板输出

横屏:

旋转角度为0,分辨率为1280 x 800

竖屏:

旋转角度为-90,分辨率为800 x 1280

Kindle Fire输出

横屏:

旋转角度为90,分辨率为600 x 819

竖屏:

旋转角度为0,分辨率为1024 x 395

droidx输出

横屏:

旋转角度为90,分辨率为320x488

竖屏:

旋转角度为0,分辨率为569x239

有没有办法:

a)使JavaScript检测应该使用高度还是宽度

或者

b)使设备报告其宽度和高度的正确值?

1个回答

1

在继续寻找一段时间后,我发现这是2.2和2.3操作系统的一个错误。我通过将此代码放入我的应用程序中来修复了2.3.4的错误。

browser = (WebView)findViewById(R.id.webBrowser);
browser.setBackgroundColor(Color.BLACK);
WebSettings webSettings = browser.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setUserAgentString("Android " + android.os.Build.VERSION.SDK);//this is so the JavaScript knows what version of the OS I'm using

然后用于检测是否处于横屏模式:

var uagent = navigator.userAgent.toLowerCase();
function isLandscape()
{
    var width = screen.width;
    var height = screen.height;
    if (isBugged())
    {
        var temp = width;
        width = height;
        height = temp;
    }
    var landscape = width > height;
    return landscape;
}

function isBugged()
{
    return uagent == "android 10"
}

如果这还不够令人困惑,当页面初始加载时,它就会确定是否处于横屏模式。因此,我不得不绕过自己的解决方法。

<body onload="if(isBugged()){uagent = 'bypass';}/*code that depends on isLandscape()*/;uagent = navigator.userAgent.toLowerCase();">

这真的很麻烦,比它应该做的工作要多得多。特别是在2.1中可以工作但在2.3.4中不能。真的很令人沮丧,但那就是我所拥有的。目前,我只检查SDK 10,我很快就会添加对其他有错误版本的检查。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接