指南针适用于真实设备,但不适用于模拟器

Compass works on real device, but not on Emulator

编辑: Android 工作室很慢地告诉我 Sensor.TYPE_ORIENTATION 已被弃用。出于某种原因,它直到编写 运行 代码很久之后才告诉我。然而,问题仍然存在。我只是想在我的问题中添加这个发现。

我有一个用作指南针的 ImageView。在真实设备上一切正常,但在我的模拟器上,扩展控件对 ImageView 没有影响。

如果我在模拟器上转到 Google 地图,我可以看到指南针在工作。如果我的应用程序在真实设备上运行,为什么它不能正常运行?

字段:

 /*
COMPASS STUFF
 */
private ImageView compass;
private float currentDegree = 0f;
private SensorManager mSensorManager;

创建时:

compass = findViewById(R.id.compass);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

恢复时:

 @Override
protected void onResume() {
    super.onResume();

    mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
            SensorManager.SENSOR_DELAY_GAME);
}

暂停:

@Override
protected void onPause() {
    super.onPause();

    mSensorManager.unregisterListener(this);
}

onSensorChanged:

@Override
public void onSensorChanged(SensorEvent sensorEvent) {

    float degree = Math.round(sensorEvent.values[0]);

    RotateAnimation rotateAnimation = new RotateAnimation(
            currentDegree,
            -degree,
            Animation.RELATIVE_TO_SELF, 0.5f,
            Animation.RELATIVE_TO_SELF,
            0.5f);

    rotateAnimation.setDuration(210);
    rotateAnimation.setFillAfter(true);
    compass.startAnimation(rotateAnimation);
    currentDegree = -degree;
}

老实说,我不知道 post 还有什么,因为我已经在 2 部手机(Galaxy s6 Active 和 Galaxy s8 Edge Plus)上对其进行了测试,并且它在两部手机上都有效。它只是在模拟器中没有做任何事情。

我会证明它可以在我自己的物理设备上运行。

模拟器失败.... --_______--

有什么建议吗?我真的很想测试其他 APIs/devices.

好吧,事实证明我关于已弃用 Sensor.TYPE_ORIENTATION 的发现解决了我的问题。我使用了 Sensor.TYPE_ACCELEROMETERSensor.TYPE_MAGNETIC_FIELD 常量,我的指南针现在可以在我的模拟器中使用了。 :-)

我使用 this 博客来帮助我了解传感器的用法。

This是博客的一步步视频版。