在充电的情况下,玩手机的时候,屏幕一般需要特定的旋转方向。
功能实现分成两部分:一部分根据手机重力方向X,Y,Z得出所需要的角度;另一方面根据旋转角度,设置屏幕旋转方向。
通过监听手机相对于X,Z方向的值,算出绕着某一轴的角度。X,Y方向分别平行于手机界面,Z垂直于手机界面。
本文以绕Y轴旋转为例,如需绕Z轴只需把Y和Z互换,一般情况下只会要求这两种情况。
代码借鉴网上的。
- package com.gamemaster.orientation;
- import android.hardware.Sensor;
- import android.hardware.SensorEvent;
- import android.hardware.SensorEventListener;
- import android.os.Handler;
- public class OrientationSensorListener implements SensorEventListener {
- private static final int _DATA_X = 0;
- private static final int _DATA_Y = 1;
- private static final int _DATA_Z = 2;
- public static final int ORIENTATION_UNKNOWN = -1;
- private Handler rotateHandler;
- public OrientationSensorListener(Handler handler) {
- rotateHandler = handler;
- }
- public void onAccuracyChanged(Sensor arg0,int arg1) {
- // TODO Auto-generated method stub
- }
- public void onSensorChanged(SensorEvent event) {
- float[] values = event.values;
- int orientation = ORIENTATION_UNKNOWN;
- float X = -values[_DATA_X];
- float Y = -values[_DATA_Y];
- float Z = -values[_DATA_Z];
- float magnitude = X*X + Z*Z;
- // Don't trust the angle if the magnitude is small compared to the y value
- if (magnitude * 4 >= Y*Y) {
- float OneEightyOverPi = 57.29577957855f;
- float angle = (float)Math.atan2(-Z,X) * OneEightyOverPi;
- orientation = 90 - (int)Math.round(angle);
- // normalize to 0 - 359 range
- while (orientation >= 360) {
- orientation -= 360;
- }
- while (orientation < 0) {
- orientation += 360;
- }
- }
- if (rotateHandler!=null) {
- rotateHandler.obtainMessage(888,orientation,0).sendToTarget();
- }
- }
- }
第二部分 根据旋转角度,设置屏幕方向。
- package com.gamemaster.orientation;
- import android.app.Activity;
- import android.os.Handler;
- import android.os.Message;
- import android.util.Log;
- public class ChangeOrientationHandler extends Handler {
- private Activity activity;
- public ChangeOrientationHandler(Activity ac) {
- super();
- activity = ac;
- }
- @Override
- public void handleMessage(Message msg) {
- if (msg.what==888) {
- int orientation = msg.arg1;
- if (orientation>70&&orientation<135) {
- activity.setRequestedOrientation(8);
- }else if (orientation>135&&orientation<225){
- //activity.setRequestedOrientation(9);
- }else if (orientation>225&&orientation<290){
- activity.setRequestedOrientation(0);
- }else if ((orientation>315&&orientation<360)||(orientation>0&&orientation<45)){
- //activity.setRequestedOrientation(1);
- }
- }
- super.handleMessage(msg);
- }
- }
在Cocos2dxActivity中的onCreate外面添加
- private Handler handler;
- private OrientationSensorListener listener;
- private SensorManager sm;
- private Sensor sensor;
在onCreate函数里面添加
- handler = new ChangeOrientationHandler(this);
- sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
- sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
- listener = new OrientationSensorListener(handler);
- sm.registerListener(listener,sensor,SensorManager.SENSOR_DELAY_UI);