android - 在没有指南针的设备上从服务中获取方向

标签 android

我有一个应用程序可以接收推送通知、检测当前设备方向(纵向/右侧横向/左侧横向)并拍照。 方向用于为 Camera.Parameters 设置旋转。

我正在使用 SensorManager.getRotationMatrix() 来计算方向,但它需要来自地磁传感器的值。 Lenovo S90-A 没有指南针,所以我似乎无法获得这些值。

我尝试使用这段代码:

int rotation = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getRotation();

来 self 的服务,但它仅在设备开启时有效。 但是,如果设备正在休眠并且我收到推送通知,则此方法始终返回 Surface.ROTATION_0

设备将固定在墙上,不应移动。

那么,有没有一种方法可以在没有指南针的情况下检测当前设备的方向?

最佳答案

answer真的很有帮助。实际上,如果您的设备的方向是平的(例如,它位于 table 上),您不能只依赖加速度计。 我最终采用了这种用于没有指南针的设备的方法。 对于带罗盘的设备,我使用 SensorManager.getRotationMatrix()SensorManager.getOrientation()

    /**
     * calculates rotation only from accelerometer values
     * @param g - accelerometer event values
     * @return
     */
    private int getRotationFromAccelerometerOnly(float[] g) {
        double normOfG = Math.sqrt(g[0] * g[0] + g[1] * g[1] + g[2] * g[2]);
        // Normalize the accelerometer vector
        g[0] = (float) (g[0] / normOfG);
        g[1] = (float) (g[1] / normOfG);
        g[2] = (float) (g[2] / normOfG);
        int inclination = (int) Math.round(Math.toDegrees(Math.acos(g[2])));
        int rotation;
        if (inclination < 25 || inclination > 155) {
            // device is flat, return 0
            rotation = 0;
        } else {
            // device is not flat
            rotation = (int) Math.round(Math.toDegrees(Math.atan2(g[0], g[1])));
        }

        return rotation;
    }

关于android - 在没有指南针的设备上从服务中获取方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33101488/

相关文章:

android - 如何使 Modal 在 react-native 中显示为不同的组件

android - 获取可写数据库时 Android 中的 NullPointerException

android - 如何在 calabash-android 中使用嵌套 ScrollView 向下滚动?

android - Parse.com 初始化服务器

android - 如何升级sqlite数据库文件

java - 即使使用迭代器,添加到我的数组列表也会导致 ConcurrentModificationException

android - Realm 以有效的方式删除孤立对象

java - 在 Android 中将 Php 连接到 MySQLi

android - apache commons IOUtils.toByteArray 不为 android 编译

Android 导航组件通过 safeArgs 和深度链接传递参数