如果用户开启了设置里的屏幕旋转,Android中处理横竖屏切换,通常的做法是在AndroidManifest.xml中定义android:configChanges="orientation|keyboardHidden,然后在重写onOrientationChanged方法,如下:

if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {    Log.i("info", "landscape"); // 横屏 } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {    Log.i("info", "portrait"); // 竖屏 }

如果用户在设置里禁止了屏幕旋转,怎么在应用中获取手机的方向呢?我们可以用OrientationEventListener(方向事件监听器),是一个当方向发生变化时,从SensorManager(传感器管理程序)接收通知的辅助类。

用法如下:

@Overrideprotected void onCreate(Bundle savedInstanceState) {mAlbumOrientationEventListener = new AlbumOrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL);if (mAlbumOrientationEventListener.canDetectOrientation()) {mAlbumOrientationEventListener.enable();} else {Log.d("chengcj1", "Can't Detect Orientation");}}@Overrideprotected void onDestroy() {mAlbumOrientationEventListener.disable();super.onDestroy();}private class AlbumOrientationEventListener extends OrientationEventListener {public AlbumOrientationEventListener(Context context) {super(context);}public AlbumOrientationEventListener(Context context, int rate) {super(context, rate);}@Overridepublic void onOrientationChanged(int orientation) {if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {return;}//保证只返回四个方向int newOrientation = ((orientation + 45) / 90 * 90) % 360if (newOrientation != mOrientation) {mOrientation = newOrientation;//返回的mOrientation就是手机方向,为0°、90°、180°和270°中的一个}}}

说明:只要手机偏移一点,方向发生变化时,onOrientationChanged会一直执行,但是在实际开发中,我们只关心4个方向(0°,90°,180°,270°),因此用上面的方法转化一下,转化原理为:当偏移角度小于45°,都当成0°来处理;大于45°,小于90°,都当成90°来处理;同理,大于90°,小于135°,当成90°来处理;大于135°,小于180°,都当成180°来处理,依此类推......



更多相关文章

  1. android-详解Android中的屏幕方向
  2. Qt for Android获取手机热点开关状态
  3. 判断手机是android还是ios,是否用了微信内置浏览器,判断是移动端还
  4. Android屏幕相关设置
  5. 第十周智能手机开发学习笔记
  6. 调用android手机微博客户端发送微博
  7. 扫描二维码自动识别手机系统(Android/IOS)跳转不同页面

随机推荐

  1. Xamarin.Android使用教程之创建第一个And
  2. Android项目流程、设计原则、编码规范、
  3. Arcgis Android(安卓)- HelloWorld
  4. 如何修改Android的Bitmap
  5. android 的短信数据库的读取
  6. Android(安卓)Studio逆向分析APK(Analyse
  7. Android(安卓)EditText inputType属性
  8. Android中的singleLine(单行显示)和ellipsi
  9. android xml常规布局属性
  10. android国际化操作