Android获取手机方向

假设用户开启了设置里的屏幕旋转,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(传感器管理程序)接收通知的辅助类。

使用方法例如以下:

@Override
protected 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");
	}
}

@Override
protected 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);
	}

	@Override
	public void onOrientationChanged(int orientation) {
		if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
			return;
		}

		//保证仅仅返回四个方向
		int newOrientation = ((orientation + 45) / 90 * 90) % 360
		if (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°来处理,依此类推......



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值