这篇文章写的传感器数据从驱动传递到应用程序的整个流程,还有数据校正的问题。
应用程序怎么样设置可以让自己随着设备的倾斜度变化而旋转方向呢?在AndroidManifest.xml文件中的android:screenOrientation就可以了。这里追踪一下它的内部机制。
先看一个最关键的部件:/frameworks/base/core/java/android/view/WindowOrientationListener.java
这个接口注册一个accelerator,并负责把accelerator的数据转化为orientation。这个API对应用程序不公开,我看Android2.3的源码时发现只有PhoneWindowManager使用到它了。
/frameworks/base/policy/../PhoneWindowManager.java
PhonwWindowManager注册了一个WindowOrientationListener,就可以异步获取当前设备的orientation了。再结合应用程序在AndroidManifest.xml中设置的值来管理着应用程序界面的旋转方向。以下是PhoneWindowManager.java中相关的两个代码片段。
public void onOrientationChanged(int rotation) {
// Send updates based on orientation value
if (localLOGV) Log.v(TAG, "onOrientationChanged, rotation changed to " +rotation);
try {
mWindowManager.setRotation(rotation, false,
mFancyRotationAnimation);
} catch (RemoteException e) {
// Ignore
}
}
... ...
switch (orientation) {//这个值就是当前设备屏幕的旋转方向,再结合应用程序设置的android:configChanges属性值就可以确定应用程序界面的旋转方向了。应用程序设置值的优先级大于传感器确定的优先级。
case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
//always return portrait if orientation set to portrait
return mPortraitRotation;
case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
//always return landscape if orientation set to landscape
return mLandscapeRotation;
case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
//always return portrait if orientation set to portrait
return mUpsideDownRotation;
case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
//always return seascape if orientation set to reverse landscape
return mSeascapeRotation;
case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
//return either landscape rotation based on the sensor
mOrientationListener.setAllow180Rotation(
isLandscapeOrSeascape(Surface.ROTATION_180));
return getCurrentLandscapeRotation(lastRotation);
case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
mOrientationListener.setAllow180Rotation(
!isLandscapeOrSeascape(Surface.ROTATION_180));
retur